code
stringlengths
281
23.7M
class ImportPlugin(MdfInfo): name = 'Import plugin' author = 'Aymeric Rateau' description = 'Import MDF files' promote_tab = 'MDF' file_extensions = set(['.dat', '.mf4', '.mdf']) def __init__(self): self.fields = [] def getPreview(self, params): info = MdfInfo() if (i...
def parse_input_update_spec(spec): for key in spec: assert (key not in {'action', 'buttons', 'code', 'inline', 'max_size', 'max_total_size', 'multiple', 'name', 'onchange', 'type', 'validate'}), ('%r can not be updated' % key) attributes = dict(((k, v) for (k, v) in spec.items() if (v is not None))) ...
def _convert_advanced_activation(inexpr, keras_layer, etab): act_type = type(keras_layer).__name__ if (act_type == 'Softmax'): axis = keras_layer.axis dims = len(keras_layer.input_shape) if isinstance(axis, list): raise tvm.error.OpAttributeUnImplemented('Softmax with axes {}...
def conv2d_transposed(x, shape, outshape, name, strides=[1, 1, 1, 1]): weight = weight_variable(shape, '{}_W'.format(name)) bias = bias_variable([shape[(- 2)]], '{}_b'.format(name)) return (tf.nn.conv2d_transpose(x, weight, output_shape=outshape, strides=strides, padding='SAME', name=name) + bias)
class JciHitachiMonthlyPowerConsumptionSensorEntity(JciHitachiEntity, SensorEntity): def __init__(self, thing, coordinator): super().__init__(thing, coordinator) def name(self): return f'{self._thing.name} Monthly Power Consumption' def native_value(self): monthly_data = self._thing....
class Iptables(InstanceModule): def __init__(self): super().__init__() self._has_w_argument = None def _iptables_command(self, version): if (version == 4): iptables = 'iptables' elif (version == 6): iptables = 'ip6tables' else: raise Ru...
class AsmCmdImportMulti(AsmCmdImportSingle): _id = 26 _menuText = QT_TRANSLATE_NOOP('asm3', 'Import as multi-document') _tooltip = QT_TRANSLATE_NOOP('asm3', 'Import assemblies from STEP file into separate document') _iconName = 'Assembly_ImportMulti.svg' def importMode(cls): params = FreeCAD...
_tokenizers class CpmTokenizationTest(XLNetModelTest): def test_pre_tokenization(self): tokenizer = CpmTokenizer.from_pretrained('TsinghuaAI/CPM-Generate') text = 'Hugging Face,' normalized_text = 'Hugging Face,<unk>' bpe_tokens = 'Hu gg ing F ace , '.split() token...
class QuoPageView(QuotientView): def __init__(self, ctx: Context, *, pages: T.List[PageLine], items: T.Optional[T.List[discord.ui.Item]]=None, embed: discord.Embed, show_count: bool, need_skip: bool): super().__init__(ctx, timeout=40) self.pages = pages self.items = items self.curren...
class DirectionalGridCRF(GridCRF, EdgeFeatureGraphCRF): def __init__(self, n_states=None, n_features=None, inference_method=None, neighborhood=4): self.neighborhood = neighborhood n_edge_features = (2 if (neighborhood == 4) else 4) EdgeFeatureGraphCRF.__init__(self, n_states, n_features, n_e...
class _NetD(nn.Module): def __init__(self): super(_NetD, self).__init__() self.features = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=64, kernel_size=5, stride=1, padding=2, bias=True), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(in_channels=64, out_channels=64, kernel_size=4, stride=2, paddi...
def menu_setattr(menu, choice, obj, string): attr = (getattr(choice, 'attr', None) if choice else None) if ((choice is None) or (string is None) or (attr is None) or (menu is None)): log_err(dedent('\n The `menu_setattr` function was called to set the attribute {} of object {} to {},\n ...
class TestOutputParser(TestCase): def setUp(self) -> None: self.parser = OutputParser([]) def test_parse_pytest(self): output = get_output('pytest') failed = list(self.parser.parse_failed('python#pytest', output)) self.assertEqual(failed, [ParseResult(name='test_d', namespaces=['...
class AlexNet(nn.Module): def __init__(self, num_classes=100): super(AlexNet, self).__init__() self.features = nn.Sequential(nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(64, 192, kernel_size=5, padding=2), nn.ReLU(inpla...
def is_html(ct_headers, url, allow_xhtml=False): if (not ct_headers): return is_html_file_extension(url, allow_xhtml) headers = split_header_words(ct_headers) if (len(headers) < 1): return is_html_file_extension(url, allow_xhtml) first_header = headers[0] first_parameter = first_head...
.parametrize('q', [quantize(symmetric=True, initialized=False), quantize_dequantize(symmetric=True, initialized=False)]) def test_compute_encodings_updates_parameters_upon_exit(q: _QuantizerBase, x: torch.Tensor): assert (q.get_min() is None) assert (q.get_max() is None) assert (q.get_scale() is None) a...
class Migration(migrations.Migration): dependencies = [('jobs', '0009_auto__1815')] operations = [migrations.AlterField(model_name='job', name='company_description_markup_type', field=models.CharField(max_length=30, choices=[('', '--'), ('html', 'HTML'), ('plain', 'Plain'), ('markdown', 'Markdown'), ('restructu...
def example_interaction_with_policy(policy='random'): assert (policy in ('random', 'user')) def random_policy(state): from helper import get_candidates lfs = get_candidates(state) path = random.choice(lfs)[0] return path def user_policy(state): from helper import get_...
def format_xlabel(wunit, plot_medium): if (wunit == 'cm-1'): xlabel = 'Wavenumber (cm-1)' elif (wunit == 'nm'): if (plot_medium and (plot_medium != 'vacuum_only')): xlabel = 'Wavelength [air] (nm)' else: xlabel = 'Wavelength (nm)' elif (wunit == 'nm_vac'): ...
def weight2subspace(weight, ratio=0.7, num=(- 1)): dim = len(weight) threshold = (ratio * np.sum(weight)) sorted_idx = np.argsort(weight) sorted_idx = [sorted_idx[((dim - i) - 1)] for i in range(dim)] if (num != (- 1)): exp_subspace = sorted_idx[:num] exp_subspace = list(np.sort(exp_...
def _test_sharding(tables: List[EmbeddingBagConfig], initial_state_dict: Dict[(str, Any)], rank: int, world_size: int, kjt_input_per_rank: List[KeyedJaggedTensor], sharder: ModuleSharder[nn.Module], backend: str, constraints: Optional[Dict[(str, ParameterConstraints)]]=None, local_size: Optional[int]=None, is_data_para...
def parse_fatal_stacktrace(text): lines = ['(?P<type>Fatal Python error|Windows fatal exception): (?P<msg>.*)', ' *', '(Current )?[Tt]hread [^ ]* \\(most recent call first\\): *', ' File ".*", line \\d+ in (?P<func>.*)'] m = re.search('\n'.join(lines), text) if (m is None): return ('', '') else...
(scope='class') def request_chat(): return KeyboardButtonRequestChat(TestKeyboardButtonRequestChatBase.request_id, TestKeyboardButtonRequestChatBase.chat_is_channel, TestKeyboardButtonRequestChatBase.chat_is_forum, TestKeyboardButtonRequestChatBase.chat_has_username, TestKeyboardButtonRequestChatBase.chat_is_create...
def adj_loglikelihood_scalar(disp, X, y, mu, sign): n = (1 / disp) p = (n / (n + mu)) loglik = sum(nbinom.logpmf(y, n, p)) diagVec = (mu / (1 + (mu * disp))) diagWM = np.diag(diagVec) xtwx = np.dot(np.dot(X.T, diagWM), X) coxreid = (0.5 * np.log(np.linalg.det(xtwx))) ret = ((loglik - cox...
def get_address_metadata(address: Address, route_states: List[RouteState]) -> Optional[AddressMetadata]: for route_state in route_states: recipient_metadata = route_state.address_to_metadata.get(address, None) if (recipient_metadata is not None): return recipient_metadata return None
def _decode(inputpath, coder, show, device, output=None): decode_func = {CodecType.IMAGE_CODEC: decode_image, CodecType.VIDEO_CODEC: decode_video} compressai.set_entropy_coder(coder) dec_start = time.time() with Path(inputpath).open('rb') as f: (model, metric, quality) = parse_header(read_uchars...
def get_ms(): try: client = docker.DockerClient(base_url=('tcp://%s:2376' % docker_host_ip)) for ms in client.containers.list(): if (ms.name == sys.argv[1]): cms.append(ms) return cms[0] except: print("Can't connect to docker API, Exiting!") ...
class FocalLoss(nn.Module): def __init__(self, num_classes, w, epsilon=0.1, use_gpu=True, label_smooth=True, gamma=0.5): super(FocalLoss, self).__init__() self.num_classes = num_classes self.epsilon = (epsilon if label_smooth else 0) self.use_gpu = use_gpu self.sigmoid = nn.S...
_fixtures(SqlAlchemyFixture, DeferredActionFixture) def test_deferred_action_completes_with_shared_requirements(sql_alchemy_fixture, deferred_action_fixture): fixture = deferred_action_fixture with sql_alchemy_fixture.persistent_test_classes(fixture.MyDeferredAction, fixture.SomeObject): requirements1 =...
def test_Array_dc_ohms_from_percent(mocker): mocker.spy(pvsystem, 'dc_ohms_from_percent') expected = 0.1425 array = pvsystem.Array(pvsystem.FixedMount(0, 180), array_losses_parameters={'dc_ohmic_percent': 3}, module_parameters={'I_mp_ref': 8, 'V_mp_ref': 38}) out = array.dc_ohms_from_percent() pvsys...
class DataTrainingArguments(): dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of the dataset to use (via the datasets library).'}) dataset_config_name: Optional[str] = field(default=None, metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}...
def create_table(table: str, namespace: Optional[str]=None, lifecycle_state: Optional[LifecycleState]=None, schema: Optional[Union[(pa.Schema, str, bytes)]]=None, schema_consistency: Optional[Dict[(str, SchemaConsistencyType)]]=None, partition_keys: Optional[List[Dict[(str, Any)]]]=None, primary_keys: Optional[Set[str]...
class PreviewForm(QDialog): def __init__(self, parent): super(PreviewForm, self).__init__(parent) self.encodingComboBox = QComboBox() encodingLabel = QLabel('&Encoding:') encodingLabel.setBuddy(self.encodingComboBox) self.textEdit = QTextEdit() self.textEdit.setLineWr...
def test_huge_dataset(): candidates = CompletedKeys((1024 * 1024)) start_time = datetime.now() iterations = 0 with pytest.raises(NoAvailableKeysError): while ((datetime.now() - start_time) < timedelta(seconds=10)): start = candidates.get_block_start_index(1024) assert can...
def make_rotating_equity_info(num_assets, first_start, frequency, periods_between_starts, asset_lifetime, exchange='TEST'): return pd.DataFrame({'symbol': [chr((ord('A') + i)) for i in range(num_assets)], 'start_date': pd.date_range(first_start, freq=(periods_between_starts * frequency), periods=num_assets), 'end_d...
class Effect11947(BaseEffect): type = ('projected', 'passive') def handler(fit, beacon, context, projectionRange, **kwargs): fit.modules.filteredItemMultiply((lambda mod: mod.item.requiresSkill('Vorton Projector Operation')), 'aoeCloudSize', beacon.getModifiedItemAttr('aoeCloudSizeMultiplier'), stacking...
class ProxySimple(ProxyDirect): def __init__(self, jump, protos, cipher, users, rule, bind, host_name, port, unix, lbind, sslclient, sslserver): super().__init__(lbind) self.protos = protos self.cipher = cipher self.users = users self.rule = (compile_rule(rule) if rule else N...
def test_load_backoff_callable_bare(): with pytest.raises(ValueError) as err: backoffcache.load_backoff_callable('local_test_arb_callable') assert (str(err.value) == "Trying to find back-off strategy 'local_test_arb_callable'. If this is a built-in back-off strategy, are you sure you got the name right?...
.skipif(kvikio.defaults.compat_mode(), reason='cannot test `set_compat_mode` when already running in compatibility mode') def test_set_compat_mode_between_io(tmp_path): with kvikio.defaults.set_compat_mode(False): f = kvikio.CuFile((tmp_path / 'test-file'), 'w') assert (not f.closed) assert ...
(ORDERS_PATH) def handle_create_order() -> dict[(str, Any)]: env_vars: MyHandlerEnvVars = get_environment_variables(model=MyHandlerEnvVars) logger.debug('environment variables', env_vars=env_vars.model_dump()) my_configuration = parse_configuration(model=MyConfiguration) logger.debug('fetched dynamic co...
class Instrument(): def __init__(self, ip_addr: str, timeout: Optional[float]=None, port: int=PORT, sub_address: str='hislip0') -> None: timeout = (timeout or 5.0) self._sync = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._sync.connect((ip_addr, port)) self._sync.settimeout...
.remote_data .flaky(reruns=RERUNS, reruns_delay=RERUNS_DELAY) def test_get_acis_station_data(): (df, meta) = get_acis_station_data('ORD', '2020-01-10', '2020-01-12', trace_val=(- 99)) expected = pd.DataFrame([[10.0, 2.0, 6.0, np.nan, 21.34, 0.0, 0.0, 0.0, 59.0, 0.0], [3.0, (- 4.0), (- 0.5), np.nan, 9.4, 5.3, 0....
def makefile(filepath, mode=448, size=None, exist_ok=False): (dirname, _) = os.path.split(filepath) makedirs(dirname, mode, exist_ok=True) try: mkfile(filepath, size) except OSError as exc: if ((not os.path.isfile(filepath)) or (not exist_ok)): raise OSError(exc)
def un_serialize(folder): txt_lst = [] msg = '' folder_lst = os.listdir(folder) for item in folder_lst: _file = os.path.join(folder, item) if os.path.isfile(_file): if _file.endswith('.txt'): txt_lst.append(_file) record_file = get_minimum_file(txt_lst) ...
class Question(): def __init__(self, data: QuestionData): self._data = data self._guesses: dict[(int, UserGuess)] = {} self._started = None def number(self) -> str: return self._data['number'] def description(self) -> str: return self._data['description'] def answ...
def build_encoder(cfg, default_args=None): backbone = build_from_cfg(cfg['backbone'], BACKBONES, default_args) enhance_cfg = cfg.get('enhance') if enhance_cfg: enhance_module = build_from_cfg(enhance_cfg, ENHANCE_MODULES, default_args) encoder = nn.Sequential(backbone, enhance_module) el...
class LimitTest(ConfigurableNodeTest, TestCase): def setUpClass(cls): cls.NodeType = bonobo.Limit def test_execution_default(self): object_list = [object() for _ in range(42)] with self.execute() as context: context.write_sync(*object_list) assert (context.get_buffer(...
class JpegXr(Codec): codec_id = 'imagecodecs_jpegxr' def __init__(self, level=None, photometric=None, hasalpha=None, resolution=None, fp2int=None): self.level = level self.photometric = photometric self.hasalpha = hasalpha self.resolution = resolution self.fp2int = fp2int...
class RatingOutcomeModelGenerator(keras.utils.Sequence): def __init__(self, data_root, phase, batch_size, use_feature=True, use_exposure=True, shuffle=True): assert (phase in ['train', 'val', 'test']) self.phase = phase self.batch_size = batch_size self.use_feature = use_feature ...
.ddblocal def test_transaction_write_with_version_attribute_condition_failure(connection): foo = Foo(21) foo.save() foo2 = Foo(21) with pytest.raises(TransactWriteError) as exc_info: with TransactWrite(connection=connection) as transaction: transaction.save(Foo(21)) assert (exc_i...
_db def test_cannot_propose_a_talk_as_unlogged_user(graphql_client, conference_factory): conference = conference_factory(topics=('my-topic',), languages=('it',), submission_types=('talk',), durations=('50',), audience_levels=('Beginner',)) (resp, _) = _submit_talk(graphql_client, conference) assert (resp['e...
def test_get_rect_from_points_given_topright_bottomleft(): rect = utils.get_rect_from_points(QtCore.QPointF(50, (- 20)), QtCore.QPointF((- 30), 40)) assert (rect.topLeft().x() == (- 30)) assert (rect.topLeft().y() == (- 20)) assert (rect.bottomRight().x() == 50) assert (rect.bottomRight().y() == 40)
def inception_v4_base(inputs, final_endpoint='Mixed_7d', scope=None): end_points = {} def add_and_check_final(name, net): end_points[name] = net return (name == final_endpoint) with tf.variable_scope(scope, 'InceptionV4', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, ...
def correlated_to_datum_inner(e): if isinstance(e, W_Correlated): return correlated_to_datum_inner(e.get_obj()) elif isinstance(e, W_List): a = correlated_to_datum_inner(e.car()) d = correlated_to_datum_inner(e.cdr()) if ((a is e.car()) and (d is e.cdr())): return e ...
('document.paragraphs is a list containing three paragraphs') def then_document_paragraphs_is_a_list_containing_three_paragraphs(context): document = context.document paragraphs = document.paragraphs assert isinstance(paragraphs, list) assert (len(paragraphs) == 3) for paragraph in paragraphs: ...
class Line(): def __init__(self, v1, v2): self.a = (v2.y - v1.y) self.b = (v1.x - v2.x) self.c = v2.cross(v1) def __call__(self, p): return (((self.a * p.x) + (self.b * p.y)) + self.c) def intersection(self, other): if (not isinstance(other, Line)): return...
def test_lambert_cylindrical_equal_area_scale_operation__defaults(): lceaop = LambertCylindricalEqualAreaScaleConversion() assert (lceaop.name == 'unknown') assert (lceaop.method_name == 'Lambert Cylindrical Equal Area') assert (_to_dict(lceaop) == {'Latitude of 1st standard parallel': 0.0, 'Longitude o...
class TestClique(QiskitOptimizationTestCase): def setUp(self): super().setUp() self.k = 5 self.seed = 100 aqua_globals.random_seed = self.seed self.num_nodes = 5 self.w = random_graph(self.num_nodes, edge_prob=0.8, weight_range=10) (self.qubit_op, self.offset)...
class MarkGenerator(): if TYPE_CHECKING: skip: _SkipMarkDecorator skipif: _SkipifMarkDecorator xfail: _XfailMarkDecorator parametrize: _ParametrizeMarkDecorator usefixtures: _UsefixturesMarkDecorator filterwarnings: _FilterwarningsMarkDecorator def __init__(self, ...
class TaggedInlineSingleAdminTest(AdminTestManager, TagTestManager, TestCase): admin_cls = test_admin.SimpleMixedTestSingletagAdmin tagged_model = test_models.SimpleMixedTest model = test_models.SimpleMixedTest.singletag.tag_model def setUpExtra(self): self.site = admin.AdminSite(name='tagulous_...
_params(node='x') def test_outside_if(condition: str, satisfy_val: (int | None), fail_val: (int | None)) -> None: nodes_ = builder.extract_node(f''' def f1(x = {fail_val}): if {condition}: pass return ( x # ) def f2(x = {satisfy_val}): if {condition}:...
def unit_impulse(shape, idx=None, dtype=float): shape = np.atleast_1d(shape) if (idx is None): idx = ((0,) * len(shape)) elif (idx == 'mid'): idx = tuple((shape // 2)) elif (not hasattr(idx, '__iter__')): idx = ((idx,) * len(shape)) return _unit_impulse_kernel(idx[0], size=sh...
def ql_syscall_socketpair(ql: Qiling, domain: int, socktype: int, protocol: int, sv: int): unpopulated_fd = (i for i in range(NR_OPEN) if (ql.os.fd[i] is None)) idx1 = next(unpopulated_fd, (- 1)) idx2 = next(unpopulated_fd, (- 1)) regreturn = (- 1) if ((idx1 != (- 1)) and (idx2 != (- 1))): v...
class MinValueConstraint(ValidationConstraint): name = 'minvalue' def __init__(self, min_value, error_message=None): error_message = (error_message or _('$label should be $min_value or greater')) super().__init__(error_message=error_message) self.min_value = min_value def validate_pa...
class AttrVI_ATTR_TCPIP_HOSTNAME(Attribute): resources = [(constants.InterfaceType.tcpip, 'INSTR'), (constants.InterfaceType.tcpip, 'SOCKET')] py_name = '' visa_name = 'VI_ATTR_TCPIP_HOSTNAME' visa_type = 'ViString' default = NotAvailable (read, write, local) = (True, False, False)
class VaultClientFactory(): def __init__(self, base_url: str, role: str, auth_type: Authenticator, mount_point: str): self.base_url = base_url self.role = role self.auth_type = auth_type self.mount_point = mount_point self.session = requests.Session() self.session.hea...
class SimpleMAStrategy(AbstractStrategy): def __init__(self, ts: BacktestTradingSession, ticker: Ticker): super().__init__(ts) self.broker = ts.broker self.order_factory = ts.order_factory self.data_handler = ts.data_handler self.ticker = ticker def calculate_and_place_or...
def test_run_shortcut_skip_parse(mock_pipe, monkeypatch): shortcuts = {'arb pipe': {'pipeline_name': 'sc pipe', 'skip_parse': True}} monkeypatch.setattr('pypyr.config.config.shortcuts', shortcuts) out = run(pipeline_name='arb pipe') assert (type(out) is Context) assert (out == {}) assert (not ou...
class TestParallel(TestNested): def setUp(self): super(TestParallel, self).setUp() self.states = ['A', 'B', {'name': 'C', 'parallel': [{'name': '1', 'children': ['a', 'b'], 'initial': 'a', 'transitions': [['go', 'a', 'b']]}, {'name': '2', 'children': ['a', 'b'], 'initial': 'a', 'transitions': [['go'...
def token_network_registry_state(chain_state, token_network_registry_address): token_network_registry = TokenNetworkRegistryState(token_network_registry_address, []) chain_state.identifiers_to_tokennetworkregistries[token_network_registry_address] = token_network_registry return token_network_registry
class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size self.i2h = nn.Linear((input_size + hidden_size), hidden_size) self.i2o = nn.Linear((input_size + hidden_size), output_size) self.softmax ...
def test_check_unique(): with pytest.raises(NameNonUniqueError): repair_names([np.nan], repair='check_unique') with pytest.raises(NameNonUniqueError): repair_names([''], repair='check_unique') with pytest.raises(NameNonUniqueError): repair_names(['a', 'a'], repair='check_unique') ...
def resnext101_32x8d(deconv, delinear, channel_deconv, pretrained=False, progress=True, **kwargs): kwargs['groups'] = 32 kwargs['width_per_group'] = 8 return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3], pretrained, progress, deconv=deconv, delinear=delinear, channel_deconv=channel_deconv, **kwargs...
def test_plugin_config_repo_override(hatch, devpi, temp_dir_cache, helpers, published_project_name, config_file): config_file.model.publish['index']['user'] = 'foo' config_file.model.publish['index']['auth'] = 'bar' config_file.model.publish['index']['ca-cert'] = 'cert' config_file.model.publish['index'...
def require_version(minver: str='0.0.0', maxver: str='4.0.0') -> Callable: def parse(python_version: str) -> tuple[(int, ...)]: try: return tuple((int(v) for v in python_version.split('.'))) except ValueError as e: msg = f'{python_version} is not a correct version : should be...
class OCIModel(RegistryDataInterface): def __init__(self): self._legacy_image_id_handler = SyntheticIDHandler() def set_id_hash_salt(self, id_hash_salt): self._legacy_image_id_handler = SyntheticIDHandler(id_hash_salt) def _resolve_legacy_image_id_to_manifest_row(self, legacy_image_id): ...
def BuildHON(InputFileName, OutputNetworkFile): RawTrajectories = ReadSequentialData(InputFileName) (TrainingTrajectory, TestingTrajectory) = BuildTrainingAndTesting(RawTrajectories) VPrint(len(TrainingTrajectory)) Rules = BuildRulesFastParameterFree.ExtractRules(TrainingTrajectory, MaxOrder, MinSupport...
def get_perturbation_results(args, data, mask_model, mask_tokenizer, base_model, base_tokenizer, span_length=10, n_perturbations=1, method='DetectGPT'): load_mask_model(args, mask_model) torch.manual_seed(0) np.random.seed(0) train_text = data['train']['text'] train_label = data['train']['label'] ...
def doctest(): extension = 'sphinx.ext.doctest' doctest_global_setup = '\nimport torch\nfrom torch import nn\n\nimport pystiche\n\nimport warnings\nwarnings.filterwarnings("ignore", category=FutureWarning)\n\nfrom unittest import mock\n\npatcher = mock.patch(\n "pystiche.enc.models.utils.ModelMultiLayerEncod...
def test_register_action(mocker): from solcore import registries mock_gr = mocker.patch('solcore.registries.generic_register') name = 'pre-process' overwrite = False reason_to_exclude = None _action(name, overwrite=overwrite, reason_to_exclude=reason_to_exclude) def solver(*args, **kwargs): ...
def color_jitter_nonrand(image, brightness=0, contrast=0, saturation=0, hue=0): with tf.name_scope('distort_color'): def apply_transform(i, x, brightness, contrast, saturation, hue): if ((brightness != 0) and (i == 0)): x = tf.image.random_brightness(x, max_delta=brightness) ...
def test_dataclass_with_field_init_is_false() -> None: (first, second, second_child, third_child, third) = astroid.extract_node('\n from dataclasses import dataclass, field\n\n\n \n class First:\n a: int\n\n \n class Second(First):\n a: int = field(init=False, default=1)\n\n \n cl...
def test_dependency_from_pep_508_with_not_in_op_marker() -> None: name = 'jinja2 (>=2.7,<2.8); python_version not in "3.0,3.1,3.2" and extra == "export"' dep = Dependency.create_from_pep_508(name) assert (dep.name == 'jinja2') assert (str(dep.constraint) == '>=2.7,<2.8') assert (dep.in_extras == ['e...
def _apply_bpe(model_path: str, in_path: str, out_path: str): Args = namedtuple('Args', ['sentencepiece_model']) args = Args(sentencepiece_model=model_path) tokenizer = SentencepieceBPE(args) with open(in_path) as f, open(out_path, 'w') as f_o: for s in f: f_o.write((tokenizer.encode...
.parametrize('converter_cls', [BaseConverter, Converter]) def test_structure_literal_enum(converter_cls): converter = converter_cls() class Foo(Enum): FOO = 1 BAR = 2 class ClassWithLiteral(): literal_field: Literal[Foo.FOO] = Foo.FOO assert (converter.structure({'literal_field':...
class DistModel(BaseModel): def name(self): return self.model_name def initialize(self, model='net-lin', net='alex', colorspace='Lab', pnet_rand=False, pnet_tune=False, model_path=None, use_gpu=True, printNet=False, spatial=False, is_train=False, lr=0.0001, beta1=0.5, version='0.1', gpu_ids=[0]): ...
def load_cpp_ext(ext_name): root_dir = os.path.join(os.path.split(__file__)[0]) src_dir = os.path.join(root_dir, 'cpp_ht2im') tar_dir = os.path.join(src_dir, 'build', ext_name) os.makedirs(tar_dir, exist_ok=True) srcs = (glob(f'{src_dir}/*.cu') + glob(f'{src_dir}/*.cpp')) with warnings.catch_war...
class LockTimeEdit(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) hbox = QHBoxLayout() self.setLayout(hbox) hbox.setContentsMargins(0, 0, 0, 0) hbox.setSpacing(0) self.locktime_raw_e = LockTimeRawEdit(self) self.locktime_height_e = L...
class LocalResource(SchemaBase): cores: PositiveInt = Field(4, description='The number of cores to be allocated to the computation.') memory: PositiveInt = Field(10, description='The amount of memory that should be allocated to the computation in GB.') def local_options(self) -> Dict[(str, int)]: re...
.parametrize('file_format, filename, content', [('json', 'foo.json', '{"a":\n'), ('yaml', 'foo.yaml', 'a: {b\n'), ('yaml', 'foo.yaml', 'a: b\nc\n'), ('json5', 'foo.json5', '{"a":\n'), ('toml', 'foo.toml', 'abc\n')]) def test_instanceloader_invalid_data(tmp_path, file_format, filename, content, open_wide): if ((file...
class ExecutionUsage(Usage): def __init__(self, asynchronous=False): super().__init__(asynchronous) self._recorder = dict() def render(self, flush: bool=False) -> dict: records = self._recorder if flush: self._recorder = dict() return records def usage_var...
def decode_train(example): features = tf.parse_single_example(example, features={'label': tf.FixedLenFeature([], tf.int64), 'FEA_SrcItemId': tf.FixedLenFeature([], tf.string), 'FEA_SrcItemCp': tf.FixedLenFeature([], tf.string), 'FEA_SrcItemFirstCat': tf.FixedLenFeature([], tf.string), 'FEA_SrcItemSecondCat': tf.Fix...
def test_get_trail(): exc = Exception() pytest.raises(AttributeError, (lambda : _raw_trail(exc))) assert (list(get_trail(exc)) == []) append_trail(exc, 'foo') assert (list(get_trail(exc)) == ['foo']) new_exc = Exception() append_trail(new_exc, 'bar') assert (list(get_trail(new_exc)) == [...
def random_in_unit_spherical_caps(shape, origin, importance_sampled_list): l = len(importance_sampled_list) mask = (np.random.rand(shape) * l).astype(int) mask_list = ([None] * l) cosmax_list = ([None] * l) ax_u_list = ([None] * l) ax_v_list = ([None] * l) ax_w_list = ([None] * l) for i ...
class MultiStepLrUpdater(BaseLrUpdater): def __init__(self, milestones=[], gamma=0.1, **kwargs): assert isinstance(milestones, (tuple, list)) self.milestones = milestones self.gamma = gamma super().__init__(**kwargs) def get_lr(self, base_lr, cur_step, steps): num_steps =...
def _x_and_y_from_pubkey_bytes(pubkey: bytes) -> Tuple[(int, int)]: assert isinstance(pubkey, bytes), f'pubkey must be bytes, not {type(pubkey)}' pubkey_ptr = create_string_buffer(64) ret = _libsecp256k1.secp256k1_ec_pubkey_parse(_libsecp256k1.ctx, pubkey_ptr, pubkey, len(pubkey)) if (not ret): ...
def Get_Visual_Response(generator, num_img, layer_id): LATENT_DIM = 512 noise_z = torch.randn(num_img, LATENT_DIM) if torch.cuda.is_available(): noise_z = noise_z.to('cuda') layer_response = Get_Layer_Output(generator, noise_z, layer_id) (img_tensor, _) = generator([noise_z]) generated_i...
def simulate_full_curve(parameters, Geff, Tcell, ivcurve_pnts=1000): sde_args = pvsystem.calcparams_desoto(Geff, Tcell, alpha_sc=parameters['alpha_sc'], a_ref=parameters['a_ref'], I_L_ref=parameters['I_L_ref'], I_o_ref=parameters['I_o_ref'], R_sh_ref=parameters['R_sh_ref'], R_s=parameters['R_s']) kwargs = {'bre...
def spatial_svd_cp_example(config: argparse.Namespace): data_pipeline = ImageNetDataPipeline(config) model = models.resnet18(pretrained=True) if config.use_cuda: model.to(torch.device('cuda')) model.eval() accuracy = data_pipeline.evaluate(model, use_cuda=config.use_cuda) logger.info('Or...
class TestHTTPJSONCollector(CollectorTestCase): def setUp(self): config = get_collector_config('HTTPJSONCollector', {}) self.collector = HTTPJSONCollector(config, None) def test_import(self): self.assertTrue(HTTPJSONCollector) (Collector, 'publish') def test_should_work_with_real...