code
stringlengths
281
23.7M
def test_configuration(): config = UpdateConfiguration(update_steps=[{'name': 'update_step_name', 'observations': ['MY_OBS'], 'parameters': ['MY_PARAMETER'], 'row_scaling_parameters': [('MY_ROW_SCALING', RowScaling())]}]) config.context_validate(['MY_OBS'], ['MY_PARAMETER', 'MY_ROW_SCALING'])
class GitlabFormatter(BaseFormatter): error_format = '{code} {text}' def start(self): super().start() self._write('[') self.newline = '' self._first_line = True def stop(self): self._write('\n]\n') super().stop() def handle(self, error): line = sel...
class OptionSeriesPackedbubbleDatalabelsTextpath(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def enabled(self): return self._config_get(False) def enabled(self, flag: bool): self._confi...
class TestGetDummies(): def test_should_handle_multi_dimensional_tensor(): samples = tf.constant([[1, 2, 0, 2, 3, 0, 10, 10]]) (one_hot, columns) = get_dummies(samples) dummies_df = pd.get_dummies(samples.numpy().flatten())[columns.numpy()] np.testing.assert_array_equal(dummies_df.va...
class DiscoverSocket(socket.socket): def __init__(self, port, mgroup, ttl=20, send_mcast=True, listen_mcast=True): self.port = port self.receive_queue = queue.Queue() self._send_queue = queue.Queue() self._lock = threading.RLock() self.send_mcast = send_mcast self.lis...
def denormalize_get_proofs_payload(raw_payload: GetProofsV1Raw) -> GetProofsPayload: (request_id, raw_proof_requests) = raw_payload proof_requests = tuple((ProofRequest(block_hash, Hash32((None if (storage_key == b'') else storage_key)), state_key, from_level) for (block_hash, storage_key, state_key, from_level...
class FunctionObject(): def __init__(self, function: Function): self._function = function self._lifter = BinaryninjaLifter() self._name = self._lifter.lift(self._function.symbol).name def get(cls, bv: BinaryView, identifier: Union[(str, Function)]) -> FunctionObject: if isinstanc...
def train(model, train_loader, val_loader, optimizer, init_lr=0.002, checkpoint_dir=None, checkpoint_interval=None, nepochs=None, clip_thresh=1.0): if use_cuda: model = model.cuda() criterion = nn.CrossEntropyLoss() global global_step, global_epoch if (hparams.exponential_moving_average is not N...
_groups.command() _context def execute(ctx): if click.confirm('[*] Do you want to attempt to harvest information on all groups? This may take a while to avoid exceeding API rate limits', default=True): msg = 'Attempting to harvest all Okta groups' LOGGER.info(msg) index_event(ctx.obj.es, mod...
def group_tags(segbits, tag_groups, bit_groups): for (tag_group, bit_group) in zip(tag_groups, bit_groups): zeros = set([(b[0], b[1], 0) for b in bit_group]) for tag in tag_group: if (tag in segbits.keys()): bits = segbits[tag] for z in zeros: ...
def test_from_files(toy_tokenizer_from_files, short_sample_texts): encoding = toy_tokenizer_from_files(short_sample_texts) _check_toy_tokenizer(encoding) assert (toy_tokenizer_from_files.decode(encoding.ids) == ['I saw a girl with a telescope.', 'Today we will eat bowl, lots of it!', 'Tokens which are unkno...
class GaugeInfluxUpdateTest(unittest.TestCase): server = None def setUp(self): self.server = start_server(PretendInflux) (self.temp_fd, self.server.output_file) = tempfile.mkstemp() def tearDown(self): os.close(self.temp_fd) os.remove(self.server.output_file) self.ser...
def parse_byhash_uri(parsed: urllib.parse.ParseResult) -> Checkpoint: (scheme, netloc, query) = (parsed.scheme, parsed.netloc, parsed.query) try: parsed_query = urllib.parse.parse_qsl(query) except ValueError as e: raise ValidationError(str(e)) query_dict = dict(parsed_query) score =...
class TestLatitudeToNumber(TestCase): def test_basic(self): self.assertEqual(latitude_to_number(0, 100), 50, '0N is supposed to be the equator') self.assertEqual(latitude_to_number(90, 100), 0, '90N is supposed to be the north pole') self.assertEqual(latitude_to_number((- 90), 100), 100, '90...
def fields_subset(subset, fields): retained_fields = {} allowed_options = ['fields'] for (key, val) in subset.items(): for option in val: if (option not in allowed_options): raise ValueError('Unsupported option found in subset: {}'.format(option)) if (('fields' no...
def test_chaindb_add_block_number_to_hash_lookup(chaindb, block): block_number_to_hash_key = SchemaV1.make_block_number_to_hash_lookup_key(block.number) assert (not chaindb.exists(block_number_to_hash_key)) assert (chaindb.get_chain_gaps() == GENESIS_CHAIN_GAPS) chaindb.persist_block(block) assert c...
def _build_worker(worker_params: ModelWorkerParameters): worker_class = worker_params.worker_class if worker_class: from dbgpt.util.module_utils import import_from_checked_string worker_cls = import_from_checked_string(worker_class, ModelWorker) logger.info(f'Import worker class from {wo...
class BatSensor(BaseSensor): name = 'bat\\d*' desc = _('Battery capacity.') bat = re.compile('\\Abat\\d*\\Z') def check(self, sensor): if self.bat.match(sensor): bat_id = (int(sensor[3:]) if (len(sensor) > 3) else 0) if (not os.path.exists('/sys/class/power_supply/BAT{}'....
def simple_rank(rawMatchInfo): match_info = _parseMatchInfo(rawMatchInfo) score = 0.0 (p, c) = match_info[:2] for phrase_num in range(p): phrase_info_idx = (2 + ((phrase_num * c) * 3)) for col_num in range(c): col_idx = (phrase_info_idx + (col_num * 3)) (x1, x2) =...
def run_interactive(query, editor=None, just_count=False, default_no=False): global yes_to_all bookmark = _load_bookmark() if bookmark: print(('Resume where you left off, at %s (y/n)? ' % str(bookmark)), end=' ') sys.stdout.flush() if (_prompt(default='y') == 'y'): query....
class PersonController(object): def PartialUpdate(request, target, options=(), channel_credentials=None, call_credentials=None, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/hrm.PersonController/PartialUpdate', hrm__pb2.PersonPar...
(autouse=True) def only_on_targets(request, target: str): if request.node.get_closest_marker('only_on_targets'): requested_targets = request.node.get_closest_marker('only_on_targets').args[0] if (target not in requested_targets): pytest.skip('Test unsupported for target: {}'.format(targe...
class IRTCPMapping(IRBaseMapping): binding: str service: str group_id: str route_weight: List[Union[(str, int)]] AllowedKeys: ClassVar[Dict[(str, bool)]] = {'address': True, 'circuit_breakers': False, 'enable_ipv4': True, 'enable_ipv6': True, 'host': True, 'idle_timeout_ms': True, 'metadata_labels':...
class RoleScannerTest(ForsetiTestCase): def setUp(self): def test_retrieve_and_find_violation(self): rule_yaml = '\nrules:\n - role_name: "forsetiBigqueryViewer"\n name: "forsetiBigqueryViewer rule"\n permissions:\n - "bigquery.datasets.get"\n - "bigquery.tables.get"\n - "bigquery.tables...
class TestLedgerApiHandler(ERC1155DeployTestCase): is_agent_to_agent_messages = False def test_setup(self): assert (self.ledger_api_handler.setup() is None) self.assert_quantity_in_outbox(0) def test_handle_unidentified_dialogue(self): incorrect_dialogue_reference = ('', '') ...
def munge_docstring(f, inner): (args, varargs, keywords, defaults) = getargspec(f) del args[1] args.extend(['sudo', 'runner_method', 'runner']) defaults = tuple((list((defaults or [])) + [False, 'run', None])) sigtext = '{}{}'.format(f.__name__, formatargspec(args, varargs, keywords, defaults)) ...
.parametrize('decay', [0.995, 0.9, 0.0, 1.0]) .parametrize('use_num_updates', [True, False]) .parametrize('explicit_params', [True, False]) def test_store_restore(decay, use_num_updates, explicit_params): model = torch.nn.Linear(10, 2) ema = ExponentialMovingAverage(model.parameters(), decay=decay, use_num_upda...
class OptionSeriesArearangeSonificationTracksMappingPan(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._co...
class Update(object): def Field(cls, **kw): return gh.Field(Player, bio=gh.String(description=''), avatar=gh.String(description=''), resolver=cls.mutate, **kw) def mutate(root, info, bio=None, avatar=None): ctx = info.context require_login(ctx) p = ctx.user.player p.bio =...
class Message(metaclass=MessageMeta): __original_message__: Optional[Union[('Message', IsOriginalMessage)]] __sample__: StreamSample __original_message_type__: Optional[Type['Message']] def __init__(self, *args: Any, **kwargs: Any) -> None: super().__setattr__('__original_message__', None) ...
class TestGlobalExceptHook(): def test_should_format_issue_template(self, caplog): caplog.set_level(logging.DEBUG) ex = Exception('Oh no! Something went wrong :(') global_except_hook(type(ex), ex, ex.__traceback__) assert (len(caplog.records) == 2) assert (caplog.records[0].m...
def login_required(level=constant.PERMISSION_LEVEL_5): def verify(view_func): (view_func) def verify_token(*args, **kwargs): try: token = request.headers['Authorization'] except Exception: return jsonify(code=4103, msg='') s = Seria...
class LiteEthMACCore(Module, AutoCSR): def __init__(self, phy, dw, with_sys_datapath=False, with_preamble_crc=True, with_padding=True, tx_cdc_depth=32, tx_cdc_buffered=False, rx_cdc_depth=32, rx_cdc_buffered=False): self.sink = stream.Endpoint(eth_phy_description(dw)) self.source = stream.Endpoint(e...
.parametrize('signature_bytes', [b'\x0cu0\x84\xe5\xa8)\x02\x192L\x1a:\x86\xd4\x06M\xed-\x15\x97\x9b\x1e\xa7\x90sJ\xaa,\xea\xaf\xc1"\x9c\xa4S\x81\x06\x81\x9f\xd3\xa5P\x9d\xd3\x83\xe8\xfeKs\x1chp3\x95V\xa5\xc0o\xeb\x9c\xf30\xbb\x00', b'\x0cu0\x84\xe5\xa8)\x02\x192L\x1a:\x86\xd4\x06M\xed-\x15\x97\x9b\x1e\xa7\x90sJ\xaa,\xe...
class GioEbml(Ebml): def open(self, location): f = Gio.File.new_for_commandline_arg(location) self.buffer = Gio.BufferedInputStream.new(f.read()) self._tell = 0 self.size = f.query_info('standard::size', Gio.FileQueryInfoFlags.NONE, None).get_size() def seek(self, offset, mode): ...
class MockAPIView(APIView): filter_backends = [filters.OrderingFilter] def _test(self, method): view = self.MockAPIView() fields = view.schema.get_filter_fields('', method) field_names = [f.name for f in fields] return ('ordering' in field_names) def test_get(self): a...
def extractSasugatranslationsHomeBlog(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Tower of Karma', 'Tower of Karma', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterou...
def _OptionsTemplateGen(options): if isinstance(options, (list, tuple)): for optname in options: if (len(optname) > 2): (opttype, optname, optvalue) = optname else: ((opttype, optname), optvalue) = (optname, None) (yield (opttype, optname, ...
class LoginSignup(stauth.Authenticate): def login(self, form_name): if (not st.session_state['authentication_status']): self.token = self.cookie_manager.get(self.cookie_name) if (self.token is not None): self.token = self.token_decode() if (self.token ...
def scores(factors): temperaments = {const.CHOLERIC: 0, const.MELANCHOLIC: 0, const.SANGUINE: 0, const.PHLEGMATIC: 0} qualities = {const.HOT: 0, const.COLD: 0, const.DRY: 0, const.HUMID: 0} for factor in factors: element = factor['element'] temperament = props.base.elementTemperament[element...
def _chain_with_block_validation(base_db, genesis_state, chain_cls=Chain): genesis_params = {'bloom': 0, 'coinbase': to_canonical_address('8888f1f195afa192cfeec030f4c9db1'), 'difficulty': 131072, 'extra_data': b'B', 'gas_limit': 3141592, 'gas_used': 0, 'mix_hash': decode_hex('56e81f171bcc55a6ff8345e692c0f86e5b48e01...
def create_delete_trigger(delete_trigger_name, table_name, delta_table_name, dml_col_name, old_column_list, dml_type_delete) -> str: return 'CREATE TRIGGER `{}` AFTER DELETE ON `{}` FOR EACH ROW INSERT INTO `{}` ({}, {}) VALUES ({}, {})'.format(escape(delete_trigger_name), escape(table_name), escape(delta_table_nam...
class MissingDependencyHandler(BinaryBaseHandlerWS): def __init__(self, handler: str, library: str): self._msg = 'The {} requires the {} library, which is not installed.'.format(handler, library) def _raise(self, *args, **kwargs): raise RuntimeError(self._msg) serialize = deserialize = _rais...
class ChatIncrementalEndpoint(BaseEndpoint): def __call__(self, start_time=None, **kwargs): if (start_time is None): raise ZenpyException('Incremental Endpoint requires a start_time parameter!') elif isinstance(start_time, datetime): unix_time = to_unix_ts(start_time) ...
def exclude_trace_path(fields: Dict[(str, FieldEntry)], item: List[Field], path: List[str], removed: List[str]) -> None: for list_item in item: node_path: List[str] = path.copy() for name in list_item['name'].split('.'): node_path.append(name) if (not ('fields' in list_item)): ...
def load_yaml(file): try: config = yaml.full_load(file.read_text()) tool_name = str(file.name.replace('.yaml', '')) tools[tool_name] = config except KeyError as error: dependency = error.args[0] dependency_file = (definitions / (dependency + '.yaml')) load_yaml(de...
class WafFirewallVersionResponseDataAttributes(ModelComposed): allowed_values = {('last_deployment_status',): {'None': None, 'NULL': 'null', 'PENDING': 'pending', 'IN_PROGRESS': 'in progress', 'COMPLETED': 'completed', 'FAILED': 'failed'}} validations = {} _property def additional_properties_type(): ...
def rotate(message, key): coded_message = '' for char in message: if (char in ascii_lowercase): char = ascii_lowercase[((ascii_lowercase.index(char) + key) % ALPHA_LEN)] elif (char in ascii_uppercase): char = ascii_uppercase[((ascii_uppercase.index(char) + key) % ALPHA_LE...
class FlashAndRedirect(object): def __init__(self, message, level, endpoint): if (not callable(endpoint)): endpoint_ = (lambda *a, **k: url_for(endpoint)) else: endpoint_ = endpoint self._message = message self._level = level self._endpoint = endpoint_...
class ActivityDecisionStateMachine(DecisionStateMachineBase): schedule_attributes: ScheduleActivityTaskCommandAttributes = None def __post_init__(self): if (not self.schedule_attributes): raise IllegalArgumentException('schedule_attributes is mandatory') def get_decision(self) -> Optiona...
class OFPMeterFeaturesStats(ofproto_parser.namedtuple('OFPMeterFeaturesStats', ('max_meter', 'band_types', 'capabilities', 'max_bands', 'max_color'))): def parser(cls, buf, offset): meter_features = struct.unpack_from(ofproto.OFP_METER_FEATURES_PACK_STR, buf, offset) stats = cls(*meter_features) ...
_member_required def add_document_tag(request, uuid, tag=None): uuid = UUID(uuid) try: doc = Document.objects.all().get(uuid=uuid) except Document.DoesNotExist: raise Http404('Document with this uuid does not exist.') if (request.method == 'POST'): add_tag_form = DocumentSetTag(r...
def run_trial(): bb.run() model = Sequential([Dense(units=bb.randint('hidden neurons', 1, 15, guess=5), input_shape=X.shape[1:], kernel_regularizer=l1_l2(l1=bb.uniform('l1', 0, 0.1, guess=0.005), l2=bb.uniform('l2', 0, 0.1, guess=0.05)), activation='relu'), Dense(units=y.shape[1], activation='softmax')]) mo...
class OptionSeriesTreemapSonificationContexttracksMappingNoteduration(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_mark_entities_mesh_mark_entities_3d_hex(): label_name = 'test_label' label_value = 999 mesh = UnitCubeMesh(2, 2, 2, hexahedral=True) (x, y, z) = SpatialCoordinate(mesh) V = FunctionSpace(mesh, 'Q', 2) f = Function(V).interpolate(conditional(And((x > 0.6), And((y > 0.4), (y < 0.6))), 1, ...
def _roxapi_export_xyz_viafile(self, rox, name, category, stype, pfilter, realisation, attributes): logger.warning('Realisation %s not in use', realisation) try: import roxar except ImportError as err: raise ImportError('roxar not available, this functionality is not available') from err ...
class MnistTrainer(submitit.helpers.Checkpointable): def __init__(self, clf): self.train_test = None self.scaler = None self.clf = clf self.trained_clf = False self.stage = '0' def __call__(self, train_samples: int, model_path: Path=None): log = functools.partial(...
class TableStats(BaseGenTableTest): def runTest(self): entries = self.do_table_stats() seen = set() for entry in entries: logging.debug(entry.show()) self.assertNotIn(entry.table_id, seen) seen.add(entry.table_id) if (entry.table_id == TABLE_ID...
def gen_function(func_attrs, src_template, element_func=None, element_func_def=None): backend_spec = CUDASpec() inputs = func_attrs['inputs'] original_inputs = func_attrs['original_inputs'] concatenate.check_rank(original_inputs, func_attrs['concat_dim']) orig_x = original_inputs[0] y = func_att...
class Scheduler(object): def __init__(self, conf, optimizer, display_status=True): self.conf = conf self.optimizer = optimizer self.display_status = display_status self.local_index = 0 self._update_training_progress() self.init_learning_rate() self.init_lr_sch...
class ColorMeta(abc.ABCMeta): def __init__(cls, name: str, bases: Tuple[(object, ...)], clsdict: Dict[(str, Any)]) -> None: if (len(cls.mro()) > 2): cls.CS_MAP = cls.CS_MAP.copy() cls.DE_MAP = cls.DE_MAP.copy() cls.FIT_MAP = cls.FIT_MAP.copy() cls.CAT_MAP = cl...
() _option('0.8.5') ('target') ('-d', '--dns-records', default='A,MX,NS,CNAME,SOA,TXT', help='Comma separated DNS records to query. Defaults to: A,MX,NS,CNAME,SOA,TXT') ('--tor-routing', is_flag=True, help='Route HTTP traffic through Tor (uses port 9050). Slows total runtime significantly') ('--proxy-list', help='Path ...
class ConsentReportingMixin(): anonymized_ip_address = Column(StringEncryptedType(type_in=String(), key=CONFIG.security.app_encryption_key, engine=AesGcmEngine, padding='pkcs5')) created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True) email = Column(StringEncryptedType(type_in=St...
def extract_trace_to_dependent_traces(wstates): (trace_to_read_set, trace_to_write_set) = construct_trace_access_sets(wstates) all_traces = (trace_to_write_set.keys() | trace_to_read_set.keys()) trace_to_dependent_traces = defaultdict(set) trace_pairs = itertools.permutations(all_traces, 2) for (a_t...
class Workflow(object): def load(filename): with open(filename) as _input: content = _input.read() items = list(yaml.safe_load_all(content)) if (not items): raise Exception('No DAG found in file {}'.format(filename)) if any(((item is None) for item in items)):...
def get_basedir_git(path=None): previous_directory = None if (path != None): previous_directory = os.getcwd() os.chdir(path) bare_command = subprocess.Popen(['git', 'rev-parse', '--is-bare-repository'], bufsize=1, stdout=subprocess.PIPE, stderr=open(os.devnull, 'w')) isbare = bare_comman...
class BP(EitBase): def setup(self, weight: str='none', perm: Optional[Union[(int, float, complex, np.ndarray)]]=None) -> None: self.params = {'weight': weight} self.B = self.fwd.compute_b_matrix(perm=perm) self.H = self._compute_h(b_matrix=self.B) self.is_ready = True def _comput...
_db() def test_new_table_exists_validation(caplog, monkeypatch): monkeypatch.setattr('usaspending_api.etl.management.commands.swap_in_new_table.logger', logging.getLogger()) with connection.cursor() as cursor: cursor.execute('CREATE TABLE test_table (col1 TEXT)') try: call_command('swap_in_n...
class StatusMixinTester(unittest.TestCase): def setUp(self): super(StatusMixinTester, self).setUp() self.test_stat1 = Status(name='On Hold', code='OH') self.test_stat2 = Status(name='Work In Progress', code='WIP') self.test_stat3 = Status(name='Approved', code='APP') self.tes...
class Package(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_import() retu...
def error_loop(process, handle_error=None, limit=3): errorcount = 0 while True: try: process() except Exception as er: traceback.print_exc() errorcount += 1 if (errorcount >= limit): raise SkipEpisodeError(always=False) from None ...
class TestDeprecatedNotOneValidator(unittest.TestCase): def test_1_warnings(self): with warnings.catch_warnings(record=True) as runtime_warnings: warnings.simplefilter('default') DeprecatedNotOneValidator().to_python('2') for output in (runtime_warnings, not_one_warnings): ...
def _fetch_reference_injections(fn: Callable[(..., Any)]) -> Tuple[(Dict[(str, Any)], Dict[(str, Any)])]: if (GenericAlias and any(((fn is GenericAlias), (getattr(fn, '__func__', None) is GenericAlias)))): fn = fn.__init__ try: signature = inspect.signature(fn) except ValueError as exception...
(scope='function') def githubnotification_manager(token_file, response, request, manager_nospawn, monkeypatch): monkeypatch.setattr('qtile_extras.widget.syncthing.requests.get', response) widget = qtile_extras.widget.githubnotifications.GithubNotifications(**{**{'token_file': token_file, 'active_colour': COLOUR...
def _is_same_shape(gemm_op1: Operator, gemm_op2: Operator) -> bool: inputs1 = gemm_op1._attrs['inputs'] inputs2 = gemm_op2._attrs['inputs'] if (len(inputs1) != len(inputs2)): return False for (input1, input2) in zip(inputs1, inputs2): if (input1._rank() != input2._rank()): re...
_routes.route('/events/<string:event_identifier>/export/attendees/csv', methods=['GET'], endpoint='export_attendees_csv') _event_id _coorganizer def export_attendees_csv(event_id): from .helpers.tasks import export_attendees_csv_task task = export_attendees_csv_task.delay(event_id) create_export_job(task.id...
def test_literal_map_string_repr(): lit = LiteralMap(literals={'a': Literal(scalar=Scalar(primitive=Primitive(integer=1)))}) assert (literal_map_string_repr(lit) == {'a': 1}) lit = LiteralMap(literals={'a': Literal(scalar=Scalar(primitive=Primitive(integer=1))), 'b': Literal(scalar=Scalar(primitive=Primitiv...
class IRCConnection(SingleServerIRCBot): def __init__(self, bot, nickname, server, port=6667, ssl=False, bind_address=None, ipv6=False, password=None, username=None, nickserv_password=None, private_rate=1, channel_rate=1, reconnect_on_kick=5, reconnect_on_disconnect=5): self.use_ssl = ssl self.use_i...
def extractGodAwfulMachineTranslator(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=...
class KVIndexStore(): def __init__(self, kvstore: BaseKVStore, namespace: Optional[str]=None) -> None: self._kvstore = kvstore self._namespace = (namespace or DEFAULT_NAMESPACE) self._collection = f'{self._namespace}/data' def add_index_struct(self, index_struct: IndexStruct) -> None: ...
def pull_save_data(game_version: str) -> Optional[str]: if (not is_ran_as_root()): return None package_name = ('jp.co.ponos.battlecats' + game_version.replace('jp', '')) path = ((get_data_path() + package_name) + '/files/SAVE_DATA') if (not os.path.exists(path)): return None return p...
class Flow_Mod_3_1(base_tests.SimpleProtocol): def runTest(self): logging.info('Flow_Mod_3_1 TEST BEGIN') logging.info('Deleting all flows from switch') delete_all_flows(self.controller) sw = Switch() self.assertTrue(sw.connect(self.controller), 'Failed to connect to switch')...
.parametrize('config_dict', [{'ECLBASE': 'name<IENS>'}, {'JOBNAME': 'name<IENS>'}]) def test_create_run_context(prior_ensemble, config_dict): iteration = 0 ensemble_size = 10 config = ErtConfig.from_dict(config_dict) run_context = ensemble_context(prior_ensemble, ([True] * ensemble_size), iteration=iter...
def find_and_assert_errors_matching_message(errors: List[ErrorInfo], match: Optional[str]=None): if (match is None): return errors re_match = re.compile(match) matching_errors = [err for err in errors if re.search(re_match, err.message)] assert (len(matching_errors) > 0), f'Expected to find erro...
.lkc def test_cves_metadata_fix_all(hound, repo): broken = [] meta = hound.metadata for cve in meta: data = meta[cve] if ('fixes' not in data): continue if (('vendor_specific' in data) and data['vendor_specific']): continue fix = data['fixes'] ...
.parametrize('ownership_range,num_components,n_DOF_pressure', [((5, 25), 3, 7), ((6, 17), 4, 3)]) def test_blocked_dof_order(ownership_range, num_components, n_DOF_pressure): array_start = ownership_range[0] array_end = ownership_range[1] blocked = LS.BlockedDofOrderType(n_DOF_pressure) num_equations = ...
class AdsPixel(AbstractCrudObject): def __init__(self, fbid=None, parent_id=None, api=None): self._isAdsPixel = True super(AdsPixel, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): automatic_matching_fields = 'automatic_matching_fields' can_proxy = 'can_pr...
def testget_revs_behind_parent_branch_up_to_date(): origin = _DEFAULT_HTTPS_REPO_URL source = _generate_source_tree_from_origin(origin) git_cmd = 'git status' git_output = 'On branch master\nYour branch is up to date with \'origin/master\'.\nChanges not staged for commit:\n (use "git add <file>..." to ...
def print_line_with_string(string: str, char: GLYPHS=GLYPHS.HORIZONTAL_LINE, line_colour: TERM_COLOURS=TERM_COLOURS.GREY, string_colour: TERM_COLOURS=TERM_COLOURS.BLUE, align: ALIGN=ALIGN.RIGHT) -> None: width = os.get_terminal_size().columns if (align == ALIGN.RIGHT): l_pad = (((width - len(string)) - ...
class PrivacyNoticeHistory(PrivacyNoticeBase, Base): origin = Column(String, ForeignKey(PrivacyNoticeTemplate.id_field_path), nullable=True) version = Column(Float, nullable=False, default=1.0) privacy_notice_id = Column(String, ForeignKey(PrivacyNotice.id_field_path), nullable=False) def calculate_rele...
def extractThesuntlsWordpressCom(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 StorageForm(SerializerForm): _api_call = dc_storage node = forms.ChoiceField(label=_('Node'), required=True, widget=forms.Select(attrs={'class': 'input-select2 narrow disable_created2'})) zpool = forms.ChoiceField(label=_('Zpool'), required=True, widget=forms.Select(attrs={'class': 'input-select2 narr...
class BaseDagSchema(StrictSchema): name = fields.String(required=True) imports = fields.Nested(ImportSchema) resources = fields.List(fields.Nested(ResourceSchema)) before = fields.List(fields.Nested(OperatorSchema)) operators = fields.List(fields.Nested(OperatorSchema)) after = fields.List(field...
def test_deprecated_argument(tmp_path: Path, monkeypatch) -> None: monkeypatch.setattr(debug.DebugExecutor, '_valid_parameters', (lambda : {'blabla'})) with test_slurm.mocked_slurm(): executor = auto.AutoExecutor(folder=tmp_path) assert (executor.cluster == 'slurm') with pytest.warns(UserWarning...
class OptionPlotoptionsSolidgaugeSonificationTracksActivewhen(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):...
def upgrade(): op.create_table('social_auth_association', sa.Column('id', sa.Integer(), nullable=False), sa.Column('server_url', sa.String(length=255), nullable=True), sa.Column('handle', sa.String(length=255), nullable=True), sa.Column('secret', sa.String(length=255), nullable=True), sa.Column('issued', sa.Integer...
class HeatshrinkDecompressor(object): def __init__(self, number_of_bytes): self._number_of_bytes_left = number_of_bytes self._data = b'' self._encoder = None self.window_sz2 = None self.lookahead_sz2 = None def decompress(self, data, size): if (self._encoder is No...
def find_solc_versions(contract_sources: Dict[(str, str)], install_needed: bool=False, install_latest: bool=False, silent: bool=True) -> Dict: (available_versions, installed_versions) = _get_solc_version_list() pragma_specs: Dict = {} to_install = set() new_versions = set() for (path, source) in con...
.skipif((sys.version_info >= (3, 10)), reason='Test does not support >=3.10 importlib_metadata API') def test_entry_points_older(): ep_string = '[options.entry_points]test_foo\n bar = catalogue:check_exists' ep = importlib.metadata.EntryPoint._from_text(ep_string) catalogue.AVAILABLE_ENTRY_POINTS['test_f...
('rocm.gemm_rcr_bias_add_relu.gen_function') def gen_function(func_attrs, exec_cond_template, dim_info_dict): return common.gen_function(func_attrs, exec_cond_template, dim_info_dict, 'bias_add_relu', extra_code=EXTRA_CODE.render(), input_addr_calculator=common.INPUT_ADDR_CALCULATOR.render(accessor_a=func_attrs['in...