code
stringlengths
281
23.7M
class RunningRMS(nn.Module): def __init__(self, size: Union[(int, Tuple[int])], dtype: Optional[torch.dtype]=None) -> None: super().__init__() self._size = ((size,) if isinstance(size, int) else size) self.register_buffer('_count', torch.zeros(1, dtype=torch.int64)) self.register_buf...
def draw(): init() print('___________ __________ __ __ .__ __ ') print('\\__ ___/_________\\______ \\ ____ _____/ |_| | _|__|/ |_ ') print(' | | / _ \\_ __ \\ _// _ \\ / _ \\ __\\ |/ / \\ __\\') print(' | |( <_> ) | \\/ | ( <_> |...
def filter_log_fortianalyzer2_setting_data(json): option_list = ['__change_ip', 'access_config', 'alt_server', 'certificate', 'certificate_verification', 'conn_timeout', 'enc_algorithm', 'fallback_to_primary', 'faz_type', 'hmac_algorithm', 'interface', 'interface_select_method', 'ips_archive', 'max_log_rate', 'mgmt...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--apply', default=False, required=False, action='store_true', help='Apply workstation configuration with Salt') parser.add_argument('--validate', default=False, required=False, action='store_true', help='Validate the configuration') ...
class LazyEntity(RemoteEntity, typing.Generic[T]): def __init__(self, name: str, getter: typing.Callable[([], T)], *args, **kwargs): super().__init__(*args, **kwargs) self._entity = None self._getter = getter self._name = name if (not self._getter): raise ValueErr...
def set_config(passthrough_values: list, arg_parse_options: dict) -> dict: default_datetime = datetime.strptime(f'{settings.API_SEARCH_MIN_DATE}+0000', '%Y-%m-%d%z') if (arg_parse_options['load_type'] == 'award'): config = {'base_table': 'awards', 'base_table_id': 'id', 'create_award_type_aliases': True...
class OptionPlotoptionsBellcurveSonificationTracks(Options): def activeWhen(self) -> 'OptionPlotoptionsBellcurveSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsBellcurveSonificationTracksActivewhen) def instrument(self): return self._config_get('piano')...
def extractHeftychonktranslateCom(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...
class TestBIST(unittest.TestCase): def test_bist(self): def main_generator(dut): dut.hdd.malloc(0, 64) sector = 0 count = 1 generator = dut.generator checker = dut.checker for i in range(4): (yield dut.generator.sector.e...
class VersionedDatabaseMixin(): VERSION = 6 def _version(self): cursor = execute(self.connection, 'PRAGMA user_version;') for res in cursor: version = res[0] return (version if version else None) assert False def _set_version(self): if (self._version i...
_ns.route('/<username>/<coprname>/delete/', methods=['GET', 'POST']) _ns.route('/g/<group_name>/<coprname>/delete/', methods=['GET', 'POST']) _required _with_copr def copr_delete(copr): if copr.group: url_on_success = url_for('groups_ns.list_projects_by_group', group_name=copr.group.name) else: ...
def _make_safe_backend_store(backend_store, remove_backends): safe_backend_store = DictProxy(old_dict=backend_store, new_dict=backend_store.copy()) for backend_cls in backend_store: if any((isinstance(rem_backend, backend_cls) for rem_backend in remove_backends)): safe_specific_backends = []...
_time('2023-09-22') def test_production(snapshot): session = Session() adapter = Adapter() session.mount(' adapter) mock_file = open('parsers/test/mocks/ESKOM/Station_Build_Up.csv', 'rb') adapter.register_uri(GET, get_url(), content=mock_file.read()) production = fetch_production(zone_key=ZoneKe...
class MyClass(): def __init__(self, a, b): self.a = a self.b = b def compute(self, n): a = self.a b = self.b if ts.is_transpiled: result = ts.use_block('block0') else: result = (((a ** 2) + (b.mean() ** 3)) + n) return result
def test_call_undefined_error_message_with_container_provider_parent_deep(): class Database(): pass class UserService(): def __init__(self, db): self.db = db class Gateways(containers.DeclarativeContainer): database_client = providers.Singleton(Database) class Service...
def extractSupertranslationWordpressCom(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...
class LLMModelAdapter(ABC): model_name: Optional[str] = None model_path: Optional[str] = None conv_factory: Optional[ConversationAdapterFactory] = None support_4bit: bool = False support_8bit: bool = False support_system_message: bool = True def __repr__(self) -> str: return f'<{self...
class RunExplainerTest(ForsetiTestCase): def test_list_permissions_no_roles_and_no_role_prefixes(self): ignored = mock.MagicMock() mock_client = mock.MagicMock() mock_config = mock.MagicMock() mock_config.action = 'list_permissions' mock_config.roles = None mock_confi...
class Score(object): __metaclass__ = ABCMeta def __init__(self, name='score', range_in=None, range_out=(0, 1), sleep=0, **kwargs): self.name = name self.range_in = range_in self.range_out = range_out self.sleep = sleep self._normalize = True def normalize(self): ...
class MelancholyAction(GenericAction): def __init__(self, source, target, amount): self.source = source self.target = target self.amount = amount def apply_action(self): src = self.source tgt = self.target draw = DrawCards(src, self.amount) g = self.game ...
def draw_allele_plot(refs_11, alts_11, refs_10, alts_10, refs_00, alts_00, refs_nn, alts_nn, output): num_points = (((len(refs_11) + len(refs_10)) + len(refs_00)) + len(refs_nn)) point_alpha = (10 / math.sqrt(max(100, num_points))) plt.scatter(x=[(ref + random.uniform((- 0.5), 0.5)) for ref in refs_11], y=[...
_custom_acc_mapper_fn(op_and_target=('call_function', getattr), arg_replacement_tuples=[]) def custom_getattr_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node: input_obj = node.args[0] attr_name = node.args[1] assert isinstance(input_obj, torch.fx.Node) input_obj_type = input_obj.meta['type'] ...
def test_regular_mode_fisher(): outfile_differential = NamedTemporaryFile(suffix='.hdf5', delete=False) outfile_differential.close() args = '--aggregatedFile {} --alpha {} --statisticTest {} --outFileName {} -t {} '.format((ROOT + 'chicAggregateStatistic/aggregate.hdf5'), 0.5, 'fisher', outfile_diffe...
class TestLocalRegistry(unittest.TestCase): def setUp(self): super().setUp() self._registry = LocalRegistry('tmp_registry') def tearDown(self): del self._registry if os.path.exists('tmp_registry.bak'): os.remove('tmp_registry.bak') if os.path.exists('tmp_regis...
def get_list_converter(type_func: Callable[([Any], _InT)]=str, delimiter: str=',') -> Callable[([str], List[_InT])]: def converter(value: str) -> List[_InT]: if (not value): return [] if (value.startswith('[') and value.endswith(']')): value = value[1:(- 1)] result = ...
class TestsAchromatic(util.ColorAsserts, unittest.TestCase): def test_achromatic(self): self.assertEqual(Color('hsluv', [270, 50, 0]).is_achromatic(), True) self.assertEqual(Color('hsluv', [270, 50, 100]).is_achromatic(), True) self.assertEqual(Color('hsluv', [270, 0, 50]).is_achromatic(), T...
_op([BlockCursorA, ProcA, BoolA]) def replace(proc, block_cursor, subproc, quiet=False): try: (ir, fwd) = DoReplace(subproc._loopir_proc, block_cursor._impl) return Procedure(ir, _provenance_eq_Procedure=proc, _forward=fwd) except UnificationError: if quiet: raise pri...
def cleos(): parser = argparse.ArgumentParser(description='Command Line Interface to EOSIO via python') parser.add_argument('--api-version', '-v', type=str, default='v1', action='store', dest='api_version') parser.add_argument('--url', '-u', type=str, action='store', default=' dest='url') parser.add_arg...
def medidor_de_tempo(func): def aninhada(*args, **kwargs): tempo_inicial = datetime.now() resultado = func(*args, **kwargs) tempo_final = datetime.now() tempo = (tempo_final - tempo_inicial) print(f'{func.__name__} demorou {tempo.total_seconds()} segundos.') return re...
def test_fieldproj_kspace_range(): with pytest.raises(pydantic.ValidationError): _ = td.FieldProjectionKSpaceMonitor(size=(2, 0, 2), ux=[0.1, 2], uy=[0], name='f', freqs=[.0], proj_axis=1) with pytest.raises(pydantic.ValidationError): _ = td.FieldProjectionKSpaceMonitor(size=(2, 0, 2), ux=[0.1, ...
def replace_query_param(url, key, val): (scheme, netloc, path, query, fragment) = urlparse.urlsplit(url) query_dict = urlparse.parse_qs(query) query_dict[key] = [val] query = urlparse.urlencode(sorted(list(query_dict.items())), doseq=True) return urlparse.urlunsplit((scheme, netloc, path, query, fra...
def extractKiwicattranslationsWordpressCom(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...
class MetaRunToRunAssoc(Base, PrepareMixin, RecordMixin): __tablename__ = 'metarun_run_assoc' __table_args__ = BASE_TABLE_ARGS meta_run_id = Column(BIGDBIDType, nullable=False, primary_key=True) run_id = Column(BIGDBIDType, nullable=False, primary_key=True) meta_run = relationship('MetaRun', primary...
def _iter_flat_tei_training_text_from_element(parent_element: etree.ElementBase, current_path: TeiTrainingElementPath=EMPTY_TEI_TRAINING_ELEMENT_PATH) -> Iterable[Union[(TeiTrainingText, ExtractInstruction)]]: LOGGER.debug('current_path: %s', current_path) is_start = True if parent_element.text: (yi...
class BoundedProgram(object): swagger_types = {'duration': 'str'} attribute_map = {'duration': 'duration'} def __init__(self, duration=None): self._duration = None self.discriminator = None self.duration = duration def duration(self): return self._duration def duratio...
def filters(color: 'Color', name: str, amount: Optional[float]=None, space: Optional[str]=None, in_place: bool=False, **kwargs: Any) -> 'Color': try: f = color.FILTER_MAP[name] except KeyError: raise ValueError("'{}' filter is not supported".format(name)) if (space is None): space = ...
def unmark_item_favorite(item_id): log.debug('Remove item from favourites: {0}', item_id) url = ('{server}/emby/Users/{userid}/FavoriteItems/' + item_id) downloadUtils.download_url(url, method='DELETE') check_for_new_content() home_window = HomeWindow() last_url = home_window.get_property('last_...
class RelativeGroupFeatures(): def __init__(self, feature_calculator, group_data_key: str, group_col: str, relation_foo=(lambda x, y: (x - y)), keep_group_feats=False, verbose: bool=False): self.feature_calculator = feature_calculator self.group_data_key = group_data_key self.group_col = gro...
class ImageToggleButton(PixbufButton, OptionsWidget): __gtype_name__ = 'ImageToggleButton' def __init__(self, *args, **kwargs): PixbufButton.__init__(self, *args, **kwargs) OptionsWidget.__init__(self, *args, **kwargs) self.image_display = False self.initialised = False def u...
def main(): module_spec = schema_to_module_spec(versioned_schema) mkeyname = None 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': {...
def main(): global options, config, buildserverid, fdroidserverid (options, parser) = parse_commandline() local_metadata_files = common.get_local_metadata_files() if (len(local_metadata_files) == 1): config = dict(common.default_config) if (not options.all): options.latest = ...
class OptionSeriesHeatmapMarker(Options): def enabled(self): return self._config_get(True) 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_type=False)...
def update(common_options: List[str]) -> None: facefusion.globals.keep_fps = ('keep-fps' in common_options) facefusion.globals.keep_temp = ('keep-temp' in common_options) facefusion.globals.skip_audio = ('skip-audio' in common_options) facefusion.globals.skip_download = ('skip-download' in common_option...
def init(model: Model[(InT, OutT)], X: Optional[InT]=None, Y: Optional[OutT]=None) -> None: if ((X is None) and (Y is None)): for layer in model.layers: layer.initialize() if model.layers[0].has_dim('nI'): model.set_dim('nI', model.layers[0].get_dim('nI')) for (ii, layer)...
class LtpSuite(Suite): NAME = 'ltp' def discover_cases(self) -> List[DiscoveredTestCase]: pass def run(self, cases: Optional[List[DiscoveredTestCase]]=None) -> Iterable[TestCaseResult]: if cases: names = [] for c in cases: name = c.name ...
def run(): tile_types = ['IBUF', 'OBUF', 'IOBUF_INTERMDISABLE', None, None] i_idx = 0 o_idx = 0 io_idx = 0 iostandards = ['LVCMOS12', 'LVCMOS15', 'LVCMOS18', 'LVCMOS25', 'LVCMOS33', 'LVTTL', 'SSTL135', 'SSTL15', 'LVDS_25', 'TMDS_33'] diff_map = {'SSTL135': ['DIFF_SSTL135'], 'SSTL15': ['DIFF_SSTL...
class BIGDBIDType(DBIDType): impl = types.BigInteger def load_dialect_impl(self, dialect: Dialect): if (dialect.name == 'mysql'): return dialect.type_descriptor(mysql.BIGINT(unsigned=True)) elif (dialect.name == 'sqlite'): return dialect.type_descriptor(sqlite.INTEGER()) ...
class group_mod_failed_error_msg(error_msg): version = 6 type = 1 err_type = 6 def __init__(self, xid=None, code=None, data=None): if (xid != None): self.xid = xid else: self.xid = None if (code != None): self.code = code else: ...
def update_diffs(module, is_similar, img, stored_img): diffs_dir.mkdir(exist_ok=True) diffs_rgba = None def get_diffs_rgba(slicer): nonlocal diffs_rgba if (diffs_rgba is None): diffs_rgba = np.abs((stored_img.astype('f4') - img)) diffs_rgba = (((diffs_rgba / 255) ** 0...
def _hash_instruction(x: xxhash.xxh32, instruction: CsInsn, process_controller: ProcessController) -> None: if (instruction.mnemonic == 'call'): op = instruction.operands[0] if ((op.type == X86_OP_IMM) and _is_in_file_mapping(op.value.imm, process_controller)): val = f'{instruction.mnemo...
class Background(): def __init__(self, coroutine: typing.Callable[([], typing.Awaitable[None])]) -> None: self.coroutine = coroutine self._exit_stack = AsyncExitStack() async def __aenter__(self) -> None: nursery = (await self._exit_stack.enter_async_context(trio.open_nursery())) ...
_set_msg_type(ofproto.OFPT_ROLE_REQUEST) class OFPRoleRequest(MsgBase): def __init__(self, datapath, role=None, generation_id=None): super(OFPRoleRequest, self).__init__(datapath) self.role = role self.generation_id = generation_id def _serialize_body(self): assert (self.role is ...
class OptionSeriesBarDataDatalabelsFilter(Options): def operator(self): return self._config_get(None) def operator(self, value: Any): self._config(value, js_type=False) def property(self): return self._config_get(None) def property(self, text: str): self._config(text, js_...
class Solution(): def nextLargerNodes(self, head: ListNode) -> List[int]: ret = [] stack = [] index = 0 curr = head while (curr is not None): ret.append(0) while (stack and (stack[(- 1)][0] < curr.val)): (val, pos) = stack.pop() ...
def throw_config_service_item(is_inpatient): service_item_label = (_('Inpatient Visit Charge Item') if is_inpatient else _('Out Patient Consulting Charge Item')) msg = _(('Please Configure {0} in '.format(service_item_label) + "<b><a href='/app/Form/Healthcare Settings'>Healthcare Settings</a></b>")) frappe...
def example(): t = ft.Text(value='Click the button...') pr = ft.ProgressRing(width=16, height=16, stroke_width=2) async def button_clicked(e): t.value = 'Doing something...' (await t.update_async()) b.disabled = True (await b.update_async()) for i in range(0, 101): ...
.parametrize('run_path, number_of_iterations, start_iteration, active_mask, expected', [('out/realization-%d/iter-%d', 4, 2, [True, True, True, True], False), ('out/realization-%d/iter-%d', 4, 1, [True, True, True, True], True), ('out/realization-%d/iter-%d', 4, 1, [False, False, True, False], False), ('out/realization...
class _PyperfTableRowBase(tuple): _raw: Optional[str] = None _header: 'PyperfTableHeader' _name: str _values: Tuple _baseline: str _others: Tuple def parse(cls, line: str, *, fail: bool=False): values = cls._parse(line, fail) if (not values): return None s...
class ClientLoggerTest(FaunaTestCase): def setUpClass(cls): super(ClientLoggerTest, cls).setUpClass() cls.collection_ref = cls.client.query(create_collection({'name': 'logging_tests'}))['ref'] def test_logging(self): logged = self.get_logged((lambda client: client.ping())) read_l...
class InstanceNetworkInterfaceRulesEngine(bre.BaseRulesEngine): def __init__(self, rules_file_path, snapshot_timestamp=None): super(InstanceNetworkInterfaceRulesEngine, self).__init__(rules_file_path=rules_file_path) self.rule_book = None def build_rule_book(self, global_configs=None): s...
def detect_calling_file_or_module_from_task_function(task_function: Any) -> Tuple[(Optional[str], Optional[str])]: while hasattr(task_function, '__wrapped__'): task_function = task_function.__wrapped__ mdl = task_function.__module__ override = _get_module_name_override() if (override is not None...
class TestUnknownClassArg(): def test_class_unknown(self, monkeypatch): with monkeypatch.context() as m: m.setattr(sys, 'argv', ['', '--config', './tests/conf/yaml/test_missing_class.yaml']) with pytest.raises(TypeError): ConfigArgBuilder(*all_configs, desc='Test Buil...
class MaskPrediction(fl.Chain): def __init__(self, embedding_dim: int, num_mask_tokens: int, num_layers: int=3, device: ((Device | str) | None)=None, dtype: (DType | None)=None) -> None: self.embedding_dim = embedding_dim self.num_mask_tokens = num_mask_tokens self.num_layers = num_layers ...
class OptionPlotoptionsLineLabel(Options): def boxesToAvoid(self): return self._config_get(None) def boxesToAvoid(self, value: Any): self._config(value, js_type=False) def connectorAllowed(self): return self._config_get(False) def connectorAllowed(self, flag: bool): self....
def create_arg_parser(): parser = argparse.ArgumentParser(formatter_class=CustomFormatter) parser.add_argument('--version', action='store_true', help='show version and exit.') pg_exec = parser.add_argument_group('Execution Options') pg_exec.add_argument('--cpu', type=int, default=1, metavar='NUM_CPU', h...
class LabGraphUnitsModel(BaseModel): def __init__(self, name: str, base: str) -> None: self.__name: str = name self.__base: str = base self.__members: Dict[(str, str)] = {} self.__methods: MethodsType = {} def name(self) -> str: return self.__name def base(self) -> st...
class Command(BaseCommand): help = 'Loads an Excel spreadsheet of DATA Act/USAspending data names across the various systems into <>' s3_public_url = settings.DATA_DICTIONARY_DOWNLOAD_URL def add_arguments(self, parser): parser.add_argument('-p', '--path', help='filepath to an Excel spreadsheet to l...
class LigatureSubstTest(unittest.TestCase): def setUp(self): self.glyphs = '.notdef c f i t c_t f_f f_i f_f_i'.split() self.font = FakeFont(self.glyphs) def makeLigature(self, s): lig = otTables.Ligature() lig.Component = list(s) lig.LigGlyph = '_'.join(lig.Component) ...
class TokensPlus(): batch_size: int tok2wp: List[Ints1d] input_ids: torch.Tensor token_type_ids: torch.Tensor attention_mask: torch.Tensor def __init__(self, inputs: List[List[str]], wordpieces: BatchEncoding): self.input_ids = wordpieces['input_ids'] self.attention_mask = wordpi...
class Plugin(plugin.PluginProto): PLUGIN_ID = 29 PLUGIN_NAME = 'Output - Output Helper' PLUGIN_VALUENAME1 = 'State' def __init__(self, taskindex): plugin.PluginProto.__init__(self, taskindex) self.dtype = rpieGlobals.DEVICE_TYPE_SINGLE self.vtype = rpieGlobals.SENSOR_TYPE_SWITCH ...
def create_site(sitename: str, project: str, db_pass: str, admin_pass: str): cprint(f''' Creating site: {sitename} ''', level=3) try: subprocess.run([which('docker'), 'compose', '-p', project, 'exec', 'backend', 'bench', 'new-site', sitename, '--no-mariadb-socket', '--db-root-password', db_pass, '--adm...
class LPDDR4SimPHY(SimSerDesMixin, LPDDR4PHY): def __init__(self, aligned_reset_zero=False, **kwargs): pads = LPDDR4SimulationPads() self.submodules += pads super().__init__(pads, ser_latency=Latency(sys=Serializer.LATENCY), des_latency=Latency(sys=Deserializer.LATENCY), phytype='LPDDR4SimPH...
def exec_workflow(workflow_client, wm: WorkflowMethod, args, workflow_options: WorkflowOptions=None, stub_instance: object=None) -> WorkflowExecutionContext: start_request = create_start_workflow_request(workflow_client, wm, args) (start_response, err) = workflow_client.service.start_workflow(start_request) ...
class ComMemberGenerator(object): def __init__(self, cls_name, vtbl_offset, iid): self._vtbl_offset = vtbl_offset self._iid = iid self._props = ComPropertyGenerator(cls_name) self._mths = [] self._member_index = 0 def add(self, m): proto = ctypes.WINFUNCTYPE(m.res...
def test_ref(): assert (ref_t1.id.project == 'flytesnacks') assert (ref_t1.id.domain == 'development') assert (ref_t1.id.name == 'recipes.aaa.simple.join_strings') assert (ref_t1.id.version == '553018f39e519bdb2597b652639c30ce16b99c79') serialization_settings = flytekit.configuration.SerializationSe...
def get_observations_to_invoice(patient, company): observations_to_invoice = [] observations = frappe.get_list('Observation', fields=['name', 'observation_template'], filters={'patient': patient.name, 'company': company, 'invoiced': False, 'docstatus': 1, 'service_request': ''}) for observation in observati...
def lazy_import(): from fastly.model.included_with_waf_firewall_version import IncludedWithWafFirewallVersion from fastly.model.pagination import Pagination from fastly.model.pagination_links import PaginationLinks from fastly.model.pagination_meta import PaginationMeta from fastly.model.waf_firewal...
def get_related_notes(id: int) -> NoteRelations: note = get_note(id) title = note.title if ((title is not None) and (len(title.strip()) > 1)): related_by_title = find_notes(title) else: related_by_title = [] related_by_tags = [] related_by_folder = [] if ((note.tags is not No...
class TestLowestCommonAncestor(unittest.TestCase): def test_lca(self): node10 = Node(10) node5 = Node(5) node12 = Node(12) node3 = Node(3) node1 = Node(1) node8 = Node(8) node9 = Node(9) node18 = Node(18) node20 = Node(20) node40 = Node...
_error.register def _format_template_syntax_error(error: TemplateSyntaxError, markdown: str, page: Page) -> str: line = markdown.splitlines()[(error.lineno - 1)] return textwrap.dedent(f''' # _Macro Syntax Error_ _File_: `{page.file.src_path}` _Line {error.lineno} in Markdown file:_ **{e...
class SchedulingEventType(str, Enum): START_WORKFLOW_EXECUTION = 'START_WORKFLOW_EXECUTION' STOP_WORKFLOW_EXECUTION = 'STOP_WORKFLOW_EXECUTION' START_TASK_EXECUTION = 'START_TASK_EXECUTION' STOP_TASK_EXECUTION = 'STOP_TASK_EXECUTION' RESTART_TASK_EXECUTION = 'RESTART_TASK_EXECUTION' PERIODIC_RUN...
class DateDetectorCache(object): def __init__(self): self.__lock = Lock() self.__templates = list() def templates(self): if self.__templates: return self.__templates with self.__lock: if self.__templates: return self.__templates ...
(scope='module') def merge_files_oneLR(): def merge(fpath, flist): b = bytearray() for file in flist: with open(file, 'rb') as source: b += bytearray(source.read()) with open(fpath, 'wb') as dest: update_envelope_VRL_and_LRSL(b, lrs_offset=84) ...
def component_has_cycle(node, graph, proceeding, visited): if (node in visited): return False if (node in proceeding): proceeding.append(node) return True proceeding.append(node) if (node in graph): for successor in graph[node]: if component_has_cycle(successo...
class Application(Gtk.Application): def __init__(self, config): super().__init__() self.userConfig = config self.userPrefs = preferences.Preferences(config) self.compiler = fc.Compiler(config) self.compiler.add_func_path('formulas') this_path = os.path.dirname(sys.mod...
def test_plot_efrontier(): d = d_pass[4] pf = build_portfolio(**d) plt.clf() pf.ef_plot_efrontier() assert (len(plt.gcf().get_axes()) == 1) ax = plt.gca() title = ax.get_title() xlabel = ax.get_xlabel() ylabel = ax.get_ylabel() xlim = ax.get_xlim() ylim = ax.get_ylim() ex...
(('config_name', 'overrides', 'expected', 'expected_choices'), [param('empty', [], DefaultsTreeNode(node=ConfigDefault(path='empty')), {}, id='empty'), param('group_default', [], DefaultsTreeNode(node=ConfigDefault(path='group_default'), children=[GroupDefault(group='group1', value='file1'), ConfigDefault(path='_self_'...
_registry.optimizers('Adam.v1') def Adam(learn_rate: FloatOrSeq=0.001, *, beta1: FloatOrSeq=0.001, beta2: FloatOrSeq=0.001, use_averages: bool=True): class Optimizer(): learn_rate: FloatOrSeq beta1: FloatOrSeq beta2: FloatOrSeq use_averages: bool return Optimizer(learn_rate=learn...
def test_config_mismatch(): with pytest.raises(ValueError) as exc: LinkPaginationConfiguration(source='headers', path='links.next') assert ("The 'rel' value must be specified when accessing the link from the headers" in str(exc.value)) with pytest.raises(ValueError) as exc: LinkPaginationCon...
class Testing(unittest.TestCase): def compare_files(self, test_path, ref_path): with io.open(test_path) as test_f, io.open(ref_path) as ref_f: self.assertListEqual(list(test_f), list(ref_f)) def get_same_files(self, dcmp, out): for name in dcmp.same_files: out.append((nam...
def ast_endless_while_init_outside() -> AbstractSyntaxTree: true_value = LogicCondition.initialize_true((context := LogicCondition.generate_new_context())) ast = AbstractSyntaxTree((root := SeqNode(true_value)), condition_map={logic_cond('x1', context): Condition(OperationType.less, [Variable('a'), Constant(2)]...
def test_hydrate_registration_parameters__workflow_nothing_set(): workflow = _workflow_pb2.WorkflowSpec(template=_core_workflow_pb2.WorkflowTemplate(id=_identifier_pb2.Identifier(resource_type=_identifier_pb2.WORKFLOW, name='name'), nodes=[_core_workflow_pb2.Node(id='foo', task_node=_core_workflow_pb2.TaskNode(refe...
class KbuildParser(object): def __init__(self, model=None, arch='x86'): self.model = model self.arch = arch self.local_vars = DataStructures.VariableStore() self.global_vars = DataStructures.VariableStore() self.init_class = Linux.LinuxInit(model, arch) self.before_pa...
class OptionDefsReverseArrowAttributes(Options): def id(self): return self._config_get('reverse-arrow') def id(self, text: str): self._config(text, js_type=False) def markerHeight(self): return self._config_get(10) def markerHeight(self, num: float): self._config(num, js_...
def stop_early(ohlcv, entries, exits, stop_vars, enumeration=True): if (not stop_vars): return (entries, exits) length = (- 1) stop_vars_set = {'sl_stop', 'ts_stop', 'tp_stop', 'sl_trail'} for (s, slist) in stop_vars.items(): if (s not in stop_vars_set): raise Exception(f'var...
class ERC20ApproveBenchmark(BaseERC20Benchmark): def __init__(self) -> None: super().__init__() def name(self) -> str: return 'ERC20 Approve' def _setup_benchmark(self, chain: MiningChain) -> None: self._next_nonce = None (txn, callback) = self._deploy_simple_token(chain) ...
def test_gauss_square1(): print('1st Order Polynomial') print('Square') gaussSquare.setOrder(1) int0_f1 = dot(f1(gaussSquare.points), gaussSquare.weights) print(int0_f1) gaussSquare.setOrder(2) int1_f1 = dot(f1(gaussSquare.points), gaussSquare.weights) print(int1_f1) gaussSquare.setO...
.parametrize('value,is_valid', (((- 1), False), (0, True), (10, True), ((2 ** 256), False), (((2 ** 256) - 1), True))) def test_validate_stack_int(value, is_valid): if is_valid: validate_stack_int(value) else: with pytest.raises(ValidationError): validate_stack_int(value)
def test_load_pyproject_toml() -> None: assert (load_pyproject_toml(Path('tests/data/example_project/pyproject.toml')) == {'tool': {'deptry': {'per_rule_ignores': {'DEP002': ['pkginfo']}}, 'poetry': {'authors': ['test <>'], 'dependencies': {'click': '^8.1.3', 'isort': '^5.10.1', 'pkginfo': '^1.8.3', 'python': '>=3....
class ProviderParameters(): def __init__(self, event_property, event_filters): self._props = ct.pointer(et.ENABLE_TRACE_PARAMETERS()) filter_buf_size = (ct.sizeof(ep.EVENT_FILTER_DESCRIPTOR) * len(event_filters)) filter_buf = (ct.c_char * filter_buf_size)() for i in range(len(event_f...