code
stringlengths
281
23.7M
('/projects', methods=['POST'], strict_slashes=False) ('/allure-docker-service/projects', methods=['POST'], strict_slashes=False) _required def create_project_endpoint(): try: if (check_admin_access(current_user) is False): return (jsonify({'meta_data': {'message': 'Access Forbidden'}}), 403) ...
class TestProphetCopy(): (scope='class') def data(self, daily_univariate_ts): df = daily_univariate_ts.copy() df['cap'] = 200.0 df['binary_feature'] = (([0] * 255) + ([1] * 255)) return df def test_prophet_copy(self, data, backend): holiday = pd.DataFrame({'ds': pd.to...
class PCF2AggregationStageService(PCF2BaseStageService): def __init__(self, onedocker_binary_config_map: DefaultDict[(str, OneDockerBinaryConfig)], mpc_service: MPCService, log_cost_to_s3: bool=DEFAULT_LOG_COST_TO_S3, container_timeout: Optional[int]=None) -> None: super().__init__(onedocker_binary_config_m...
class BillingAddressRequest(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(...
class DatabaseConnector(): def __init__(self, module, credentials, conn_pool=None, *args, **kwargs): assert module self._conn_pool_class = conn_pool if (self._conn_pool_class is None): self._conn_pool_class = ConnectionPool self._module = module self._args = args ...
class KMSScanner(base_scanner.BaseScanner): def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, rules): super(KMSScanner, self).__init__(global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, rules) self.rules_engine = kms_rul...
def test_unhandled_exception_capture(sanic_elastic_app, elasticapm_client): (sanic_app, apm) = next(sanic_elastic_app(elastic_client=elasticapm_client)) (_, resp) = sanic_app.test_client.post('/v1/apm/unhandled-exception', headers={constants.TRACEPARENT_HEADER_NAME: '00-0af7651916cd43dd8448eb211c80319c-b7ad6b-0...
def test_error_if_numerator_probability_is_zero(): df = {'var_A': (((['A'] * 6) + (['B'] * 10)) + (['C'] * 4)), 'var_B': (((['A'] * 10) + (['B'] * 6)) + (['C'] * 4)), 'var_C': (((['A'] * 6) + (['B'] * 10)) + (['C'] * 4)), 'target': [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0]} df = pd.DataFrame(...
_settings(MATRIXSTORE_BUILD_DIR=None, MATRIXSTORE_LIVE_FILE=None) class TestMatrixStoreSetLive(SimpleTestCase): def setUpClass(cls): cls.devnull = open(os.devnull, 'w') cls.tempdir = tempfile.mkdtemp() settings.MATRIXSTORE_BUILD_DIR = cls.tempdir cls.live_file = os.path.join(cls.temp...
def test_cmd(): _cli.command(short_help='Test a model', help='Test a model and obtain performance metrics') ('model', type=click.STRING) ('-o', '--output', 'output', required=False, default=None, type=click.STRING) def test(model, output): mdl = ModelTester(model) model_id = mdl.model_id...
_test class ServiceTypeGrpc(Node): path: Name def __init__(self, service_manifests: (str | None)=None, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._manifests = (service_manifests or integration_manifests.load('backend')) def config(self) -> Generator[(Union[(str, Tuple[(...
class ReflectionServiceServicer(object): def GetAuthnDescriptor(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetChainDescriptor(self, request, context): ...
class Migration(migrations.Migration): dependencies = [('manager', '0026_auto__0032')] operations = [migrations.CreateModel(name='EventolSetting', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('background', models.ImageField(blank=True, help_text='A ...
class FixtureFactory(): def __init__(self) -> None: self.mixer = mixer self.registry = FixtureRegistry() def __getattr__(self, name: str) -> Callable: method = self.registry.get(name) return partial(method, self) def cycle(self, count: int) -> CycleFixtureFactory: ret...
class OptionXaxisPlotlinesEvents(Options): def click(self): return self._config_get(None) def click(self, value: Any): self._config(value, js_type=False) def mousemove(self): return self._config_get(None) def mousemove(self, value: Any): self._config(value, js_type=False)...
def login_exhentai(r, suc, fail): try: coo = r.headers.get('set-cookie') cooid = re.findall('ipb_member_id=(.*?);', coo)[0] coopw = re.findall('ipb_pass_hash=(.*?);', coo)[0] except (IndexError,) as ex: errmsg = re.findall('<span class="postcolor">([^<]+)</span>', r.text) ...
.parametrize('input, expected_output', [({'a': 1, 'b': 2}, 'ABIDecodedNamedTuple(a=1, b=2)'), ({'a': 0}, 'ABIDecodedNamedTuple(a=0)'), ({'a': None}, 'ABIDecodedNamedTuple(a=None)'), ({'a': False}, 'ABIDecodedNamedTuple(a=False)'), ({}, 'ABIDecodedNamedTuple()'), ({'a': {}}, 'ABIDecodedNamedTuple(a=ABIDecodedNamedTuple(...
def extractWwwIsekailunaticCom(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) i...
class TestAdmin(object): def testKick(self): env = Environ() t = EventTap() _ = env.server_core() proton = env.client_core() naughty = env.client_core() proton.auth.login('Proton') naughty.auth.login('Naughty') wait() assert (proton.auth.pid ==...
_models('spacy.Command.v1') def cohere_command(config: Dict[(Any, Any)]=SimpleFrozenDict(), name: Literal[('command', 'command-light', 'command-light-nightly', 'command-nightly')]='command', strict: bool=Cohere.DEFAULT_STRICT, max_tries: int=Cohere.DEFAULT_MAX_TRIES, interval: float=Cohere.DEFAULT_INTERVAL, max_request...
class TestListItemObserverIterObjects(unittest.TestCase): def test_trait_list_iter_objects(self): instance = ClassWithList() item1 = mock.Mock() item2 = mock.Mock() instance.values = [item1, item2] observer = ListItemObserver(notify=True, optional=False) actual = list...
def keep_ranges_two_days_apart_separate(): expected = [(_str_to_datetime(DATE_RANGE_3['start_date']), _str_to_datetime(DATE_RANGE_3['end_date'])), (_str_to_datetime(DATE_RANGE_4['start_date']), _str_to_datetime(DATE_RANGE_4['end_date']))] results = list(merge_date_ranges(_convert_ranges_to_dt_list(DATE_RANGE_3,...
class OptionPlotoptionsScatter3dSonificationTracksMappingLowpassFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str)...
class CTCLossFunction(torch.autograd.Function): def create_ctc_graph(target, blank_idx): g_criterion = gtn.Graph(False) L = len(target) S = ((2 * L) + 1) for l in range(S): idx = ((l - 1) // 2) g_criterion.add_node((l == 0), ((l == (S - 1)) or (l == (S - 2))))...
class TestParseId(TestFunction, unittest.TestCase): cases = [(([],), (True, [])), ((['1'],), (True, [1])), ((['11'],), (True, [17])), ((['ae2'],), (True, [2786])), ((['11', 'ae2'],), (True, [17, 2786])), ((['g'],), (False, 'Invalid task ID: g')), ((['11', 'g'],), (False, 'Invalid task ID: g')), ((['11', 'g', 'lol']...
def _dependency_section() -> Tree: dependency_node = Tree('[bold] Dependencies') fdt_package = importlib.metadata.distribution('foundry_dev_tools') extras = {'core': []} for req in fdt_package.requires: r = Requirement(req) if (r.marker is None): extras['core'].append(r) ...
_patch_bwbuild_object('CANCEL_CHECK_PERIOD', 0.5) ('copr_backend.sign.SIGN_BINARY', 'tests/fake-bin-sign') def test_cancel_build_on_tail_log_no_ssh(f_build_rpm_sign_on, caplog): config = f_build_rpm_sign_on worker = config.bw config.ssh.set_command('copr-rpmbuild-log', 0, 'canceled stdout\n', 'canceled stde...
def map_unet_params(pt_mod, dim): pt_params = dict(pt_mod.named_parameters()) params_ait = {} for (key, arr) in pt_params.items(): if (len(arr.shape) == 4): arr = arr.permute((0, 2, 3, 1)).contiguous() elif key.endswith('ff.net.0.proj.weight'): (w1, w2) = arr.chunk(2,...
def get_target_ppu(prescriptions): quantity_by_practice = defaultdict(float) cost_by_practice = defaultdict(float) for prescription in prescriptions: practice = prescription['practice'] quantity_by_practice[practice] += prescription['quantity'] cost_by_practice[practice] += prescript...
class CheckColorAction(argparse.Action): def __call__(self, parser, namespace, value, option_string=None): if ((not is_color(value)) and (value.lower() not in ['off', 'disable'])): raise argparse.ArgumentError(self, ("invalid reactive color: '%s'" % value)) setattr(namespace, self.dest.u...
def user_exists(app, mail): cmd = (gpg_cmd + ['--armor', '--batch', '--export', '<{0}>'.format(mail)]) try: handle = Popen(cmd, stdout=PIPE, stderr=PIPE) (stdout, stderr) = handle.communicate() except Exception as e: log.exception(e) raise GpgErrorException(msg='unhandled exc...
('new') ('--template', '-t', type=click.STRING, default=' help='Path to a cookiecutter template or to a valid git repo.') ('--out-dir', '-o', type=click.Path(), default=None, help='The location for the new FlaskBB theme.') ('--force', '-f', is_flag=True, default=False, help='Overwrite the contents of output directory i...
class InspectorMiddleware(Middleware): STATE = local() INSPECT_STATE_KEY = 'inspector' def __init__(self, rpc_url): self._rpc_url = rpc_url def get_inspector(cls): return getattr(cls.STATE, cls.INSPECT_STATE_KEY, None) def before_process_message(self, _broker, worker): if (no...
class TaskStatusWorkflowDBTestDBCase(UnitTestDBBase): def setUp(self): super(self.__class__, self).setUp() from stalker import User self.test_user1 = User(name='Test User 1', login='tuser1', email='', password='secret') from stalker.db.session import DBSession DBSession.add(s...
def create_service_unit(id=0, service_unit_type=None, service_unit_capacity=0): if frappe.db.exists('Healthcare Service Unit', f'_Test Service Unit {str(id)}'): return f'_Test service_unit {str(id)}' service_unit = frappe.new_doc('Healthcare Service Unit') service_unit.is_group = 0 service_unit....
.skipif(utils.complex_mode, reason="Don't expect coordinate derivatives to work in complex") def test_mixed_derivatives(): mesh = UnitSquareMesh(6, 6) X = SpatialCoordinate(mesh) (x, y) = X V = FunctionSpace(mesh, 'CG', 1) u = Function(V) u.interpolate((((((x * x) + (y * x)) + (y * y)) + sin(x))...
def downgrade(): op.create_table('event_user', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('event_id', sa.INTEGER(), autoincrement=False, nullable=True), sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True), sa.Column('editor', sa.BOOLEAN(), autoincrement=False, nullable=True), sa.Col...
def long_ths(): shape = (25000, 3) samples = np.random.randint(0, 256, shape, dtype='uint8') plaintext = np.random.randint(0, 256, (shape[0], 1), dtype='uint8') return scared.traces.formats.read_ths_from_ram(samples=np.vstack((samples, samples)), plaintext=np.vstack((plaintext, plaintext)))
class OptionPlotoptionsAreasplinerangeSonificationTracksMappingRate(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
class ETMSystemChatMember(ETMChatMember, SystemChatMember): chat_type_name = 'SystemChatMember' def __init__(self, db: 'DatabaseManager', chat: 'Chat', *, name: str='', alias: Optional[str]=None, uid: ChatID=ChatID(''), vendor_specific: Dict[(str, Any)]=None, description: str='', middleware: Optional[Middleware...
_ExtendedCommunity.register_type(_ExtendedCommunity.ENCAPSULATION) class BGPEncapsulationExtendedCommunity(_ExtendedCommunity): _VALUE_PACK_STR = '!B4xH' _VALUE_FIELDS = ['subtype', 'tunnel_type'] TUNNEL_TYPE_L2TPV3 = 1 TUNNEL_TYPE_GRE = 2 TUNNEL_TYPE_IP_IN_IP = 7 TUNNEL_TYPE_VXLAN = 8 TUNNE...
def extractPpochaccocoWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_typ...
_view(('POST',)) _classes(()) _required('API_ENABLED', default_dc=True) def api_login(request): serializer = APIAuthTokenSerializer(data=request.data) if serializer.is_valid(): user = serializer.object['user'] (token, created) = Token.objects.get_or_create(user=user) if (not created): ...
class ObjGraphTemplateTests(TestCase): template_name = 'analysis.py.template' filename = 'some_filename' templates_path = f'{os.path.abspath(os.path.dirname(__file__))}/../templates/' pid = 1234 specific_refs = ['str', 'int'] def setUp(self): self.items = [['builtins.test1', 1, 10000], [...
class ArrayAdapter(TabularAdapter): columns = [('i', 'index'), ('x', 0), ('y', 1), ('z', 2)] font = 'Courier 10' alignment = 'right' format = '%.4f' index_text = Property() index_image = Property() def _get_index_text(self): return str(self.row) def _get_index_image(self): ...
def setup_template(template_name: str, path: str, project_name: str): template = templates[template_name] cmd = template['setup'].format(br='{}', project_name=project_name) cwd = os.path.realpath(os.path.join(path, '..')) print(cmd) completed_process = subprocess.run(cmd, shell=True, stdout=subproce...
def create_ac(data: Iterable[Tuple[(str, Any)]]) -> ahocorasick.Automaton: AC = ahocorasick.Automaton(ahocorasick.STORE_ANY) for (span, value) in data: if (span in AC): t = AC.get(span) else: t = SimpleNamespace(span=span, values=set()) AC.add_word(span, t) ...
class GCSStorageService(StorageService): def __init__(self, credentials_json: Optional[str]=None, config: Optional[Dict[(str, Any)]]=None) -> None: self.gcs_gateway = GCSGateway(credentials_json, config) def __check_dir(self, local_dir: str) -> None: if (not os.path.exists(local_dir)): ...
def example(): class Data(): def __init__(self) -> None: self.counter = 0 d = Data() async def on_click(e): e.control.page.snack_bar = ft.SnackBar(ft.Text(f'Hello {d.counter}')) e.control.page.snack_bar.open = True d.counter += 1 (await e.control.page.upda...
.bigtest def test_slice_simple_layer(tmpdir, show_plot, generate_plot): layslice = Grid3DSlice() mygrid = xtgeo.grid_from_file(USEFILE1) myprop = xtgeo.gridproperty_from_file(USEFILE2, grid=mygrid, name='PORO') assert (myprop.values.mean() == pytest.approx(0.1677, abs=0.001)) wd = None for lay i...
def _format_tuple(abi_types: Sequence[ABIType], values: Union[(List, Tuple)]) -> List: result = [] _check_array(values, len(abi_types)) for (type_, value) in zip(abi_types, values): try: if type_.is_array: result.append(_format_array(type_, value)) elif isinst...
class ToMatrixTest(unittest.TestCase): def test_to_matrix_1by2(self) -> None: self.maxDiff = None bmg = BMGRuntime().accumulate_graph([f1by2()], {}) observed = to_dot(bmg, node_types=True, edge_requirements=True, after_transform=True, label_edges=True) expected = '\ndigraph "graph" {...
class LakeCard(ErsiliaBase): def __init__(self, config_json=None): ErsiliaBase.__init__(self, config_json=config_json) def get(self, model_id, as_json=False): if (Hdf5Explorer is None): self.logger.debug('No lake found') return None card = Hdf5Explorer(model_id=mo...
def getExtSmart(device, output_filename): vid = getVID(device) vid_extsmart_dict = {'': ('nvme ocp smart-add-log %s -o json | tee %s' % (device, output_filename))} extsmart_dict = {} cmd_list = [] cmd_list += [vid_extsmart_dict['']] cmd_list += [vid_extsmart_dict[hex(vid)] for key in vid_extsmar...
def create_redshift_systems(describe_clusters: Dict[(str, List[Dict])], organization_key: str) -> List[System]: redshift_systems = [System(fides_key=cluster['ClusterIdentifier'], name=cluster['ClusterIdentifier'], description=f"Fides Generated Description for Redshift Cluster: {cluster['ClusterIdentifier']}", syste...
('/ambassador/v0/check_ready', methods=['GET']) def check_ready(): if (not app.ir): return ('ambassador waiting for config\n', 503) status = envoy_status(app.estatsmgr.get_stats()) if status['ready']: return (('ambassador readiness check OK (%s)\n' % status['since_update']), 200) else: ...
class Test_packet_in_filter(unittest.TestCase): def setUp(self): self.app = _PacketInFilterApp() def tearDown(self): pass def test_pkt_in_filter_pass(self): datapath = ProtocolDesc(version=ofproto_v1_3.OFP_VERSION) e = ethernet.ethernet(mac.BROADCAST_STR, mac.BROADCAST_STR, e...
def check_default_uv_set___fix(): all_meshes = pm.ls(type='mesh') for mesh in all_meshes: node = mesh.getParent() pm.select(node, r=1) uvsets = pm.polyUVSet(node, q=1, auv=1) if ((len(uvsets) == 1) and (uvsets[0] != 'map1')): pm.polyUVSet(rename=1, newUVSet='map1', uv...
def setup_chain_state(w3): coinbase = w3.eth.coinbase assert is_same_address(coinbase, common.COINBASE) math_contract_factory = w3.eth.contract(abi=MATH_CONTRACT_ABI, bytecode=MATH_CONTRACT_BYTECODE) math_deploy_receipt = common.deploy_contract(w3, 'math', math_contract_factory) assert is_dict(math_...
class ClassInput(GrpCls.ClassHtml): def css(self) -> AttrInput.AttrInput: if (self._css_struct is None): self._css_struct = AttrInput.AttrInput(self.component) return self._css_struct def css_class(self) -> Classes.CatalogInput.CatalogInput: if (self._css_class is None): ...
class SymbolTable(): def __init__(self, *args, **kwargs): self.binary = kwargs['binary'] self.content = bytearray() self.num_entries = 0 def debug_info(self): self.content += utils.encode_kbytes(0, 4) self.content += utils.encode_address(0, self.binary) self.conte...
def _add_general_information(fo, meta): meta['hid'] = fo.get_hid() meta['size'] = fo.size meta['number_of_included_files'] = (len(fo.files_included) if fo.files_included else 0) meta['included_files'] = (list(fo.files_included) if fo.files_included else []) meta['total_files_in_firmware'] = (len(fo....
class OptionSeriesTilemapSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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...
def _move_to_normcap_temp_dir(input_file: Path, postfix: str) -> None: if (not input_file.exists()): logger.debug('Skip moving file to temp dir, it does not exist: %s', input_file.resolve()) return normcap_temp_dir = (Path(tempfile.gettempdir()) / 'normcap') normcap_temp_dir.mkdir(exist_ok=T...
def focal_loss(gamma=2, alpha=0.75): def focal_loss_fixed(y_true, y_pred): eps = 1e-12 y_pred = K.clip(y_pred, eps, (1.0 - eps)) pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred)) pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred)) return ((- K...
def fasta_iterator(input_file): with myopen(input_file) as f: sequence = [] name = '' begun = False for line in f: line = line.strip() if line.startswith('>'): if begun: (yield Fasta(name, ''.join(sequence))) ...
('list-deps', 'lists the transitive deps for a given project') class ListDepsCmd(ProjectCmdBase): def run_project_cmd(self, args, loader, manifest): for m in loader.manifests_in_dependency_order(): print(m.name) return 0 def setup_project_cmd_parser(self, parser): parser.add_...
def test_anomalyless_all_columns_anomalies(test_id: str, dbt_project: DbtProject): utc_today = datetime.utcnow().date() data: List[Dict[(str, Any)]] = [{TIMESTAMP_COLUMN: cur_date.strftime(DATE_FORMAT), 'superhero': superhero} for cur_date in generate_dates(base_date=(utc_today - timedelta(1))) for superhero in...
def clean_env() -> tp.Iterator[None]: distrib_names = ('MASTER_ADDR', 'MASTER_PORT', 'RANK', 'WORLD_SIZE', 'LOCAL_RANK', 'LOCAL_WORLD_SIZE') cluster_env = {x: os.environ.pop(x) for x in os.environ if (x.startswith(('SLURM_', 'SLURMD_', 'SRUN_', 'SBATCH_', 'SUBMITIT_')) or (x in distrib_names))} try: ...
class OptionPlotoptionsVectorStatesSelectHalo(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def opacity(self): return self._config_get(0.25) def opacity(self, num: float): self._config(nu...
class OptionSeriesSolidgaugeSonificationContexttracksMappingHighpassFrequency(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: ...
class OptionPlotoptionsCylinderStates(Options): def hover(self) -> 'OptionPlotoptionsCylinderStatesHover': return self._config_sub_data('hover', OptionPlotoptionsCylinderStatesHover) def inactive(self) -> 'OptionPlotoptionsCylinderStatesInactive': return self._config_sub_data('inactive', OptionP...
class TestCloseableNamedTemporaryFile(): def test_usage_after_closing(self): with CloseableNamedTemporaryFile(mode='w', encoding='utf-8') as file: file.write('test') file.close() with open(file.name, 'r', encoding='utf-8') as reopened_file: assert (reopene...
class WinmmkeysPlugin(): def enable(self, exaile): self.exaile = exaile def on_gui_loaded(self): self.handler = HotkeyHandler_Pynput(self.exaile) def disable(self, exaile): if hasattr(self, 'handler'): self.handler.disable() del self.handler del self.e...
def apply_body(state: State, block_hashes: List[Hash32], coinbase: Address, block_number: Uint, base_fee_per_gas: Uint, block_gas_limit: Uint, block_time: U256, block_difficulty: Uint, transactions: Tuple[(Union[(LegacyTransaction, Bytes)], ...)], ommers: Tuple[(Header, ...)], chain_id: U64) -> Tuple[(Uint, Root, Root,...
def wck_ratio_subtests(testfunc): (testfunc) def wrapper(self): for wck_ck_ratio in [2, 4]: with self.subTest(wck_ck_ratio=wck_ck_ratio): Phy = (lambda *args, **kwargs: LPDDR5SimPHY(*args, wck_ck_ratio=wck_ck_ratio, **kwargs)) testfunc(self, Phy) return wr...
def run_up_to_down(mesh, DGDPC1, W): velocity = as_vector((0.0, (- 1.0))) u0 = project(velocity, W) xs = SpatialCoordinate(mesh) inflowexpr = (1 + xs[0]) inflow = Function(DGDPC1) inflow.interpolate(inflowexpr) n = FacetNormal(mesh) un = (0.5 * (dot(u0, n) + abs(dot(u0, n)))) D = Tri...
def test_import_reek_init(reek_run): gps = reek_run.get_init_properties(names=['PORO', 'PORV']) poro = gps.get_prop_by_name('PORO') porv = gps.get_prop_by_name('PORV') assert (poro.values.mean() == pytest.approx(0.1677402, abs=1e-05)) assert (porv.values.mean() == pytest.approx(13536.2137, abs=0.000...
() ('image', [nox.param('admin_ui', id='admin-ui'), nox.param('dev', id='dev'), nox.param('privacy_center', id='privacy-center'), nox.param('prod', id='prod'), nox.param('test', id='test')]) def build(session: nox.Session, image: str, machine_type: str='') -> None: if (image == 'prod'): try: imp...
def _fuse_gemm_ops(op_group: List[Operator], sorted_graph: List[Tensor]) -> List[Tensor]: assert op_group[0]._attrs['op'].startswith('gemm_rcr'), f"_fuse_gemm_ops only supports gemm_rcr family ops. {op_group[0]._attrs['op']} is not supported" op_group.sort(key=(lambda x: x._attrs['inputs'][1]._attrs['name'])) ...
def _set_provider(name): with _get_data_folder().joinpath('providers-config.yaml').open() as fp: providers = yaml.safe_load(fp) if (name not in providers.keys()): raise ValueError(f"Provider '{color('bright magenta')}{name}{color}' does not exist") with _get_data_folder().joinpath('network-c...
def _setup_argparser(): parser = argparse.ArgumentParser(description=f'{PROGRAM_NAME} - {PROGRAM_DESCRIPTION}') parser.add_argument('-V', '--version', action='version', version=f'{PROGRAM_NAME} {PROGRAM_VERSION}') parser.add_argument('-d', '--debug', action='store_true', default=False, help='print debug mes...
def get_updates(last_activity_date=''): try: url = (config.host + '/updates') r = requests.post(url, headers=headers, data=json.dumps({'last_activity_date': last_activity_date})) return r.json() except requests.exceptions.RequestException as e: print('Something went wrong with ge...
class IPv6FlowSpecDest(Destination, NonVrfPathProcessingMixin): ROUTE_FAMILY = RF_IPv6_FLOWSPEC def _best_path_lost(self): old_best_path = self._best_path NonVrfPathProcessingMixin._best_path_lost(self) self._core_service._signal_bus.best_path_changed(old_best_path, True) def _new_be...
class Cell(Html.Html): name = 'Python Cell Runner' requirements = ('codemirror',) def __init__(self, page: primitives.PageModel, vals: Union[(list, str)], language: str, width: tuple, height: tuple, html_code: Optional[str], options: Optional[dict], profile: Optional[Union[(dict, bool)]], verbose: bool=Fals...
def _policy(env: GymMazeEnv): distribution_mapper = DistributionMapper(action_space=env.action_space, distribution_mapper_config={}) policies = {0: FlattenConcatPolicyNet({'observation': (4,)}, {'action': (2,)}, hidden_units=[16], non_lin=nn.Tanh)} critics = {0: FlattenConcatStateValueNet({'observation': (4...
class OptionSeriesVectorStatesSelect(Options): def animation(self) -> 'OptionSeriesVectorStatesSelectAnimation': return self._config_sub_data('animation', OptionSeriesVectorStatesSelectAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self._co...
class OptionPlotoptionsSplineSonificationTracks(Options): def activeWhen(self) -> 'OptionPlotoptionsSplineSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsSplineSonificationTracksActivewhen) def instrument(self): return self._config_get('piano') def ...
def test(): assert ([(ent.text, ent.label_) for ent in doc1.ents] == [('amsterdem', 'GPE')]), 'Verifie les entites dans le premier exemple.' assert ([(ent.text, ent.label_) for ent in doc2.ents] == [('Paris', 'GPE')]), 'Verifie les entites dans le deuxieme exemple.' assert ([(ent.text, ent.label_) for ent i...
class BatteryLevelCharacteristic(Characteristic): BATTERY_LVL_UUID = '2a19' def __init__(self, bus, index, service): Characteristic.__init__(self, bus, index, self.BATTERY_LVL_UUID, ['read', 'notify'], service) self.notifying = False self.battery_lvl = 100 GObject.timeout_add(500...
def get_vt(api_key, filepe): hash_md5 = hashlib.md5() with open(filepe, 'rb') as f: for chunk in iter((lambda : f.read(4096)), b''): hash_md5.update(chunk) hmd5 = hash_md5.hexdigest() params = {'apikey': api_key, 'resource': hmd5} headers = {'Accept-Encoding': 'gzip, deflate', 'U...
def test_get_column_controls_reverse_current_selection(): columns = {'username': 'Username', 'email': 'Email'} url = URL('/?order=-username') controls = get_column_controls(url=url, columns=columns, order_by='-username') assert (controls == [ColumnControl(id='username', text='Username', url=URL('/'), is...
class TestMrtlibBgp4MpMrtRecord(unittest.TestCase): def test_parse_state_change_afi_ipv4(self): peer_ip = '10.0.0.1' local_ip = '10.0.0.2' buf = (((b'\x11\x11\x11\x11\x00\x10\x00\x00\x00\x00\x00\x14\xfd\xe9\xfd\xea""\x00\x01' + addrconv.ipv4.text_to_bin(peer_ip)) + addrconv.ipv4.text_to_bin(...
class OptionPlotoptionsColumnpyramidSonificationTracksMappingHighpass(Options): def frequency(self) -> 'OptionPlotoptionsColumnpyramidSonificationTracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsColumnpyramidSonificationTracksMappingHighpassFrequency) def reson...
class OptionSeriesPictorialTooltipDatetimelabelformats(Options): def day(self): return self._config_get('%A, %e %b %Y') def day(self, text: str): self._config(text, js_type=False) def hour(self): return self._config_get('%A, %e %b, %H:%M') def hour(self, text: str): self....
class PainterDialog(utils.Dialog): def __init__(self, main_window): super().__init__(_('Painter'), main_window, (_('_Close'), Gtk.ResponseType.CLOSE), modal=False) self.f = main_window.f self.connect('notify::visible', self.on_visible) self.paint_toggle = Gtk.ToggleButton.new_with_la...
def _from_same_src_op(gemm_ops: List[Operator], op_type: str) -> bool: if (len(gemm_ops) <= 1): return True src_ops = list(gemm_ops[0]._attrs['inputs'][0].src_ops()) if (len(src_ops) != 1): return False src_op = src_ops[0] if (src_op._attrs['op'] != op_type): return False ...
class UpdateEverythingChecker(DummyChecker, register=False): SIZE = 0 CHECKSUM = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' VERSION = '1.2.3.4' TIMESTAMP = dt.datetime(2019, 8, 28, 0, 0, 0) async def check(self, external_data): external_data.state |= external_data.Sta...
class FakeUserData(IFLUserData): def __init__(self, gen_batch: Callable[([int, Any], Any)], num_batches: int=1, batch_size: int=2, val: Optional[float]=None): self.gen_batch = gen_batch self._num_batches = num_batches self.batch_size = batch_size self.val = val def train_data(sel...
def identity_transpose_fixer(bmg: BMGraphBuilder, typer: LatticeTyper) -> NodeFixer: def fixer(node: bn.BMGNode) -> NodeFixerResult: if (not isinstance(node, bn.TransposeNode)): return Inapplicable in_node = node.inputs[0] if (not typer.is_matrix(in_node)): return in_...