code
stringlengths
281
23.7M
class TestAviarySDK(): def test_get_backend(self, aviary_testing_model): backend = sdk.get_aviary_backend() assert backend def test_get_aviary(self, aviary_testing_model): completions = sdk.completions(model=aviary_testing_model, prompt='test') assert completions def test_lis...
_on_failure .parametrize('number_of_nodes', [2]) .parametrize('deposit', [0]) .parametrize('enable_rest_api', [True]) def test_api_channel_set_reveal_timeout(api_server_test_instance: APIServer, raiden_network: List[RaidenService], token_addresses, settle_timeout): (app0, app1) = raiden_network token_address = ...
def _call_return(call: Dict[(str, Any)]) -> Callable[([Optional[Callable[(..., Any)]], Optional[Callable[(..., Any)]]], Any)]: global _js_result_timeout call_id = call['call'] def return_func(callback: Optional[Callable[(..., Any)]]=None, error_callback: Optional[Callable[(..., Any)]]=None) -> Any: ...
def match_qdmr_arg_to_groundings(arg, grnds): matches = [] arg = clean_qdmr_arg(arg) for grnd in grnds: if (grnd.iscol() or grnd.istbl() or grnd.isval()): name = grnd.keys[(- 1)] if is_text_match(arg, name): matches.append(grnd) else: raise...
class ClipGradNorm(object): def __init__(self, start_iteration=0, end_iteration=(- 1), max_norm=0.5): self.start_iteration = start_iteration self.end_iteration = end_iteration self.max_norm = max_norm self.last_epoch = (- 1) def __call__(self, parameters): self.last_epoch...
_loss('label_smoothing_cross_entropy') class LabelSmoothingCrossEntropyLoss(ClassyLoss): def __init__(self, ignore_index=(- 100), reduction='mean', smoothing_param=None): super().__init__() self._ignore_index = ignore_index self._reduction = reduction self._smoothing_param = smoothin...
class VersionChange(enum.Enum): unknown = enum.auto() equal = enum.auto() downgrade = enum.auto() patch = enum.auto() minor = enum.auto() major = enum.auto() def matches_filter(self, filterstr: str) -> bool: allowed_values: Dict[(str, List[VersionChange])] = {'major': [VersionChange....
def get_operator(values): n = len(values) pauli_list = [] for i in range(n): for j in range(i): x_p = np.zeros(n, dtype=bool) z_p = np.zeros(n, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([((2.0 * values[i]) * values[j]), Paul...
def test_get_expected_output_filenames_for_example(): from reana.reana_dev.run import get_expected_output_filenames_for_example for (example, output) in (('', ('plot.png',)), ('reana-demo-helloworld', ('greetings.txt',)), ('reana-demo-root6-roofit', ('plot.png',)), ('reana-demo-alice-lego-train-test-run', ('plo...
class ModelParallel(nn.Module): def __init__(self, chunks, device_list): super(ModelParallel, self).__init__() self.chunks = chunks self.device_list = device_list def c(self, input, i): if ((input.type() == 'torch.FloatTensor') and ('cuda' in self.device_list[i])): in...
class RealGaborLayer(nn.Module): def __init__(self, in_features, out_features, bias=True, is_first=False, omega0=10.0, sigma0=10.0, trainable=False): super().__init__() self.omega_0 = omega0 self.scale_0 = sigma0 self.is_first = is_first self.in_features = in_features ...
(callback=triggered) (user='darren', host='radiant', key='/home/darren/.ssh/id_rsa.pub', python='/home/darren/venv/bin/python') def echo(e): print('echo: {}'.format(threading.current_thread().name)) with open('/tmp/echo.out', 'w') as pr: pr.write('Echo! {}'.format(e)) return 'Echo! {}'.format(e)
def test_map_iterator(): sm = m.StringMap({'hi': 'bye', 'black': 'white'}) assert (sm['hi'] == 'bye') assert (len(sm) == 2) assert (sm['black'] == 'white') with pytest.raises(KeyError): assert sm['orange'] sm['orange'] = 'banana' assert (sm['orange'] == 'banana') expected = {'hi'...
class AverageMeter(object): def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val * n) self.count += n self.avg = (self.sum / ...
def test(models, dataloaders, mode='val'): assert ((mode == 'val') or (mode == 'test')) models['backbone'].eval() total = 0 correct = 0 with torch.no_grad(): for (inputs, labels) in dataloaders[mode]: inputs = inputs.cuda() labels = labels.cuda() scores = ...
def test_follow_redirects_filtered_by_site_after_redirect(): link = '/resource' redirected = '/redirected' filtered = ' with start_server(Response(link, 301, {'Location': redirected}), Response(redirected, 301, {'Location': filtered})) as url: hosts = [socket.gethostname().lower()] asser...
.parametrize('prefix,path,expected', [('test', 'foo', 'test/foo'), ('test', 'bar', 'test/bar'), ('test', '/bar', 'test/bar'), ('test', '../foo', 'test/foo'), ('test', 'foo/bar/baz', 'test/baz'), ('test', 'foo/../baz', 'test/baz'), (None, 'foo', 'foo'), (None, 'foo/bar/baz', 'baz')]) def test_filepath(prefix, path, expe...
.parametrize('method', ['advi', 'ADVI+adapt_diag', 'advi_map', 'jitter+adapt_diag', 'adapt_diag', 'map', 'adapt_full', 'jitter+adapt_full']) def test_exec_nuts_init(method): if method.endswith('adapt_full'): with pytest.warns(UserWarning, match='experimental feature'): check_exec_nuts_init(metho...
.parametrize('rank, attn_axes, expected', quadratic_attention) def test_build_quadratic_attention(rank, attn_axes, expected): result = build_quadratic_attention_equation(rank, attn_axes) (dot_product_equation, combine_equation, attn_scores_rank) = result assert (dot_product_equation == expected[0]) asse...
class Migration(migrations.Migration): dependencies = [('api', '0050_remove_infractions_active_default_value')] operations = [migrations.AlterField(model_name='deletedmessage', name='embeds', field=django.contrib.postgres.fields.ArrayField(base_field=django.contrib.postgres.fields.jsonb.JSONField(validators=[])...
class ScratchPadBaseConfic(Config): auto_fullscreen = True screens = [] groups = [libqtile.config.ScratchPad('SCRATCHPAD', dropdowns=[libqtile.config.DropDown('dd-a', spawn_cmd('dd-a'), on_focus_lost_hide=False), libqtile.config.DropDown('dd-b', spawn_cmd('dd-b'), on_focus_lost_hide=False), libqtile.config....
class MinimumEigenOptimizationResult(OptimizationResult): def __init__(self, x: Union[(List[float], np.ndarray)], fval: float, variables: List[Variable], status: OptimizationResultStatus, samples: Optional[List[SolutionSample]]=None, min_eigen_solver_result: Optional[MinimumEigensolverResult]=None, raw_samples: Opt...
.functions (df=df_strategy()) (deadline=None, max_examples=10) def test_bin_numeric_expected_columns(df): df = df.bin_numeric(from_column_name='a', to_column_name='a_bin') expected_columns = ['a', 'Bell__Chart', 'decorated-elephant', '#$%^', 'cities', 'a_bin'] assert (set(df.columns) == set(expected_columns...
def test_assert_key_type_value_no_value_raises(): info = ContextItemInfo(key='key1', key_in_context=True, expected_type=str, is_expected_type=True, has_value=False) with pytest.raises(KeyInContextHasNoValueError) as err_info: Context().assert_key_type_value(info, 'mydesc') assert (str(err_info.value...
def main(params): imgs = json.load(open(params['input_json'], 'r')) imgs = imgs['images'] seed(123) vocab = build_vocab(imgs, params) itow = {(i + 1): w for (i, w) in enumerate(vocab)} wtoi = {w: (i + 1) for (i, w) in enumerate(vocab)} (L, label_start_ix, label_end_ix, label_length) = encode...
class Critic(nn.Module): def __init__(self, nb_states, nb_actions, hidden=256, init_w=0.3): super(Critic, self).__init__() self.fc1 = nn.Linear(nb_states, hidden) self.fc2 = nn.Linear((hidden + nb_actions), hidden) self.fc3 = nn.Linear(hidden, hidden) self.fc4 = nn.Linear(hid...
class ProcessTest(unittest.TestCase): def tearDown(self) -> None: current_process = psutil.Process() self.assertEqual(len(current_process.children()), 0, 'zombie children processes!') def test_returncode(self) -> None: with self.assertRaisesRegex(SystemExit, '^0$'): main(['--...
def mat2quat(mat): mat = np.asarray(mat, dtype=np.float64) assert (mat.shape[(- 2):] == (3, 3)), 'Invalid shape matrix {}'.format(mat) (Qxx, Qyx, Qzx) = (mat[(..., 0, 0)], mat[(..., 0, 1)], mat[(..., 0, 2)]) (Qxy, Qyy, Qzy) = (mat[(..., 1, 0)], mat[(..., 1, 1)], mat[(..., 1, 2)]) (Qxz, Qyz, Qzz) = (...
def update_shared_token_timestamp(message: Message, context: ContextTypes.DEFAULT_TYPE) -> str: chat_data = cast(Dict, context.chat_data) key = 'shared_token_timestamp' last_time = chat_data.get(key) current_time = message.date chat_data[key] = current_time if (last_time is None): return...
class EventsDialog(Factory.Popup): __events__ = ('on_release', 'on_press') def __init__(self, **kwargs): super(EventsDialog, self).__init__(**kwargs) def on_release(self, instance): pass def on_press(self, instance): pass def close(self): self.dismiss()
class EvenniaTest(TestCase): account_typeclass = DefaultAccount object_typeclass = DefaultObject character_typeclass = DefaultCharacter exit_typeclass = DefaultExit room_typeclass = DefaultRoom script_typeclass = DefaultScript ('evennia.scripts.taskhandler.deferLater', _mock_deferlater) ...
def test_get_news_articles_with_invalid_site(graphql_client): user = UserFactory() parent = GenericPageFactory() NewsArticleFactory(title='Article 1', parent=parent, owner=user, first_published_at=datetime.datetime(2010, 1, 1, 10, 0, 0)) SiteFactory(hostname='pycon2', root_page=parent) query = 'quer...
class IndexedDatasetBuilder(object): element_sizes = {np.uint8: 1, np.int8: 1, np.int16: 2, np.int32: 4, np.int64: 8, np.float: 4, np.double: 8} def __init__(self, out_file, dtype=np.int32): self.out_file = open(out_file, 'wb') self.dtype = dtype self.data_offsets = [0] self.dim_...
class TestTaskNeedsYield(TestNameCheckVisitorBase): _fails(ErrorCode.task_needs_yield) def test_constfuture(self): from asynq import asynq, ConstFuture () def bad_async_fn(): return ConstFuture(3) _fails(ErrorCode.task_needs_yield) def test_async(self): from a...
class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return ((now - datetime.timedelta(days=1)) <= self....
def _pbs_to_saga_jobstate(state): if (state == 'C'): return api.DONE elif (state == 'F'): return api.DONE elif (state == 'H'): return api.PENDING elif (state == 'Q'): return api.PENDING elif (state == 'S'): return api.PENDING elif (state == 'W'): r...
def test_transform_point_multi(runner): result = runner.invoke(main_group, ['transform', '--dst-crs', 'EPSG:32618', '--precision', '2'], '[-78.0, 23.0]\n[-78.0, 23.0]', catch_exceptions=False) assert (result.exit_code == 0) assert (result.output.strip() == '[192457.13, 2546667.68]\n[192457.13, 2546667.68]')
(allow_output_mutation=True, show_spinner=False, hash_funcs=HASH_FUNCS) _grad() def flow_w_to_z(flow_model, w, attributes, lighting): w_cuda = torch.Tensor(w) att_cuda = torch.from_numpy(np.asarray(attributes)).float().unsqueeze(0).unsqueeze((- 1)).unsqueeze((- 1)) light_cuda = torch.Tensor(lighting) fe...
class BasePjitPartitioner(BasePartitioner): _property def _local_chunker(self) -> LocalChunker: return LocalChunker(self.mesh) _property def mesh(self) -> Mesh: return default_mesh(self._num_partitions, self._model_parallel_submesh, self._backend) def partition(self, fn: Callable, in...
class GherkinTerminalReporter(TerminalReporter): def __init__(self, config: Config) -> None: super().__init__(config) def pytest_runtest_logreport(self, report: TestReport) -> Any: rep = report res = self.config.hook.pytest_report_teststatus(report=rep, config=self.config) (cat, ...
class PulseAudioOperation(PulseAudioMainloopChild): _state_name = {pa.PA_OPERATION_RUNNING: 'Running', pa.PA_OPERATION_DONE: 'Done', pa.PA_OPERATION_CANCELLED: 'Cancelled'} def __init__(self, callback_lump, pa_operation: pa.pa_operation) -> None: context = callback_lump.context assert (context.m...
def unique_config_sections(config_file): section_counters = defaultdict(int) output_stream = io.StringIO() with open(config_file) as fin: for line in fin: if line.startswith('['): section = line.strip().strip('[]') _section = ((section + '_') + str(section...
class Normal(Distribution): def __init__(self, name, mean, stdv, input_type=None, startpoint=None): super().__init__(name=name, mean=mean, stdv=stdv, startpoint=startpoint) self.dist_type = 'Normal' def pdf(self, x): z = ((x - self.mean) / self.stdv) p = (self.std_normal.pdf(z) /...
class TABlock(nn.Module): def __init__(self, block, num_segments, tam_cfg=dict()): super().__init__() self.tam_cfg = deepcopy(tam_cfg) self.block = block self.num_segments = num_segments self.tam = TAM(in_channels=block.conv1.out_channels, num_segments=num_segments, **self.ta...
class KinopoiskPage(object): content = None def __init__(self, source_name, instance, content=None, request=None): self.request = (request or Request()) self.source_name = source_name self.instance = instance if (content is not None): self.content = content def el...
_LAYERS.register_module(name='ConvAWS') class ConvAWS2d(nn.Conv2d): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True): super().__init__(in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bia...
def test_invalid_skip_keyword_parameter(pytester: Pytester) -> None: pytester.makepyfile('\n import pytest\n pytest.skip("skip_module_level", unknown=1)\n\n def test_func():\n assert 0\n ') result = pytester.runpytest() result.stdout.fnmatch_lines(["*TypeError:*['unknown']...
def _make_init(cls, attrs, pre_init, pre_init_has_args, post_init, frozen, slots, cache_hash, base_attr_map, is_exc, cls_on_setattr, attrs_init): has_cls_on_setattr = ((cls_on_setattr is not None) and (cls_on_setattr is not setters.NO_OP)) if (frozen and has_cls_on_setattr): msg = "Frozen classes can't ...
class HorizontalFlip(DualTransform): identity_param = False def __init__(self): super().__init__('apply', [False, True]) def apply_aug_image(self, image, apply=False, **kwargs): if apply: image = F.hflip(image) return image def apply_deaug_mask(self, mask, apply=False...
class PreviewContractViewTests(TestCase): def setUp(self): self.user = baker.make(settings.AUTH_USER_MODEL, is_staff=True, is_superuser=True) self.client.force_login(self.user) self.contract = baker.make_recipe('sponsors.tests.empty_contract', sponsorship__start_date=date.today()) se...
class MNIST(object): def __init__(self, **options): transform = transforms.Compose([transforms.Resize(32), transforms.ToTensor()]) batch_size = options['batch_size'] data_root = os.path.join(options['dataroot'], 'mnist') pin_memory = (True if options['use_gpu'] else False) tr...
def test_config_settings(tmp_path): pyproject_toml: Path = (tmp_path / 'pyproject.toml') pyproject_toml.write_text('[tool.cibuildwheel.config-settings]\nexample = "one"\nother = ["two", "three"]\n') options_reader = OptionsReader(config_file_path=pyproject_toml, platform='linux', env={}) assert (options...
def test_pretrainedinit(): modelA = FooModule() constant_func = ConstantInit(val=1, bias=2, layer=['Conv2d', 'Linear']) modelA.apply(constant_func) modelB = FooModule() funcB = PretrainedInit(checkpoint='modelA.pth') modelC = nn.Linear(1, 2) funcC = PretrainedInit(checkpoint='modelA.pth', pr...
class TestDurations(): source = '\n from _pytest import timing\n def test_something():\n pass\n def test_2():\n timing.sleep(0.010)\n def test_1():\n timing.sleep(0.002)\n def test_3():\n timing.sleep(0.020)\n ' def test_calls(sel...
class BinaryPrecision(MulticlassPrecision): def __init__(self: TBinaryPrecision, *, threshold: float=0.5, device: Optional[torch.device]=None) -> None: super().__init__(num_classes=2, device=device) self.threshold = threshold _mode() def update(self: TBinaryPrecision, input: torch.Tensor, ta...
class WnliProcessor(DataProcessor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) warnings.warn(DEPRECATION_WARNING.format('processor'), FutureWarning) def get_example_from_tensor_dict(self, tensor_dict): return InputExample(tensor_dict['idx'].numpy(), tensor_dic...
('pypyr.steps.dsl.fileinoutrewriter.StreamRewriter', spec=StreamRewriter) def test_streamreplacepairsrewriterstep_run_step_substitutions(mock_rewriter): context = Context({'k1': 'b', 'k2': 'd', 'k3': '{k2}', 'root': {'in': 'inpathhere', 'out': 'outpathhere', 'replacePairs': {'a': '{k1}', 'c': '{k3}'}, 'encodingIn':...
class GetCrtcTransform(rq.ReplyRequest): _request = rq.Struct(rq.Card8('opcode'), rq.Opcode(27), rq.RequestLength(), rq.Card32('crtc')) _reply = rq.Struct(rq.ReplyCode(), rq.Card8('status'), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Object('pending_transform', Render_Transform), rq.Bool('has_transforms...
def _permissions_actions(caller, raw_inp, **kwargs): choices = kwargs.get('available_choices', []) (perm, action) = _default_parse(raw_inp, choices, ('examine', 'e'), ('remove', 'r', 'delete', 'd')) if perm: if (action == 'examine'): return ('node_examine_entity', {'text': _display_perm(...
class Citadel(Ship): def validate(self, item): if (item.category.name != 'Structure'): pyfalog.error("Passed item '{0}' (category: {1}) is not under Structure category", item.name, item.category.name) raise ValueError(('Passed item "%s" (category: (%s)) is not under Structure categor...
class ConfirmButton(discord.ui.Button): def __init__(self): super().__init__(style=discord.ButtonStyle.green, label='Confirm') async def callback(self, interaction: discord.Interaction): (await interaction.response.defer()) self.view.proceed = True for child in self.view.children...
class ItemCondition(str, Enum): NEW_ITEM = 'NewItem' NEW_WITH_WARRANTY = 'NewWithWarranty' NEW_OEM = 'NewOEM' NEW_OPEN_BOX = 'NewOpenBox' USED_LIKE_NEW = 'UsedLikeNew' USED_VERY_GOOD = 'UsedVeryGood' USED_GOOD = 'UsedGood' USED_ACCEPTABLE = 'UsedAcceptable' USED_POOR = 'UsedPoor' ...
.wrap def apply_feature_processors_to_kjt(features: KeyedJaggedTensor, feature_processors: Dict[(str, nn.Module)]) -> KeyedJaggedTensor: processed_weights = [] features_dict = features.to_dict() for key in features.keys(): jt = features_dict[key] if (key in feature_processors): f...
(name='a') def fixture_a() -> FixtureA: return Fsm(alphabet={Charclass('a'), Charclass('b'), (~ Charclass('ab'))}, states={0, 1, 2}, initial=0, finals={1}, map={0: {Charclass('a'): 1, Charclass('b'): 2, (~ Charclass('ab')): 2}, 1: {Charclass('a'): 2, Charclass('b'): 2, (~ Charclass('ab')): 2}, 2: {Charclass('a'): 2...
def main(rag_example_args: 'RagExampleArguments', processing_args: 'ProcessingArguments', index_hnsw_args: 'IndexHnswArguments'): logger.info('Step 1 - Create the dataset') assert os.path.isfile(rag_example_args.csv_path), 'Please provide a valid path to a csv file' dataset = load_dataset('csv', data_files=...
def _load_header(fid, pointer): if ((pointer != 0) and (pointer is not None)): fid.seek(pointer) temp = dict() (temp['id'], reserved, temp['length'], temp['link_count']) = _HeaderStruct.unpack(fid.read(24)) temp['pointer'] = pointer return temp else: return None
def is_rectangle(face): angles = [(math.pi - l.calc_angle()) for l in face.loops] right_angles = len([a for a in angles if (((math.pi / 2) - 0.001) < a < ((math.pi / 2) + 0.001))]) straight_angles = len([a for a in angles if ((- 0.001) < a < 0.001)]) return ((right_angles == 4) and (straight_angles == (...
class MultinodeConstraintFcn(FcnEnum): STATES_EQUALITY = (MultinodeConstraintFunctions.Functions.states_equality,) CONTROLS_EQUALITY = (MultinodeConstraintFunctions.Functions.controls_equality,) ALGEBRAIC_STATES_EQUALITY = (MultinodeConstraintFunctions.Functions.algebraic_states_equality,) CUSTOM = (Mul...
def allocate_batch(indices, lengths, src_sizes, tgt_sizes, batch_size_words, batch_size_sents, batch_size_multiplier, max_src_len, max_tgt_len, min_src_len, min_tgt_len, cleaning=1): try: import pyximport cython_available = True except ModuleNotFoundError as e: cython_available = False ...
def from_pickle(data, db_obj=None): def process_item(item): dtype = type(item) if (dtype in (str, int, float, bool, bytes, SafeString, SafeBytes)): return item elif _IS_PACKED_DBOBJ(item): return unpack_dbobj(item) elif _IS_PACKED_SESSION(item): re...
def build_python_from_data(datas, save_path): result_code = 'from pymiere.core import PymiereBaseObject, PymiereBaseCollection, Array, _format_object_to_py, _format_object_to_es\n' for (name, data) in datas.items(): print("Generating object '{}'".format(name)) result_code += generate_class(data,...
def _pest_control_score(x, seed=None): U = 0.1 n_stages = x.size n_simulations = 100 init_pest_frac_alpha = 1.0 init_pest_frac_beta = 30.0 spread_alpha = 1.0 spread_beta = (17.0 / 3.0) control_alpha = 1.0 control_price_max_discount = {1: 0.2, 2: 0.3, 3: 0.3, 4: 0.0} tolerance_dev...
def test_normalize_percent_characters(): expected = '%3Athis_should_be_lowercase%DF%AB%4C' assert (expected == normalize_percent_characters('%3athis_should_be_lowercase%DF%ab%4c')) assert (expected == normalize_percent_characters('%3Athis_should_be_lowercase%DF%AB%4C')) assert (expected == normalize_per...
def test_unlock_account_with_passwordfile(keystore_mock): account_manager = AccountManager(keystore_mock) password_file_path = os.path.join(keystore_mock, 'passwordfile.txt') with open(password_file_path, 'r') as password_file: privkey = unlock_account_with_passwordfile(account_manager=account_manag...
class MPNetConfig(PretrainedConfig): model_type = 'mpnet' def __init__(self, vocab_size=30527, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, initializer_range=0.02,...
class PykickstartLintConfig(PocketLintConfig): def __init__(self): PocketLintConfig.__init__(self) self.falsePositives = [FalsePositive('^W1113.*: Keyword argument before variable positional arguments list in the definition of __init__ function$'), FalsePositive('W0707.*raise-missing-from'), FalsePo...
.parametrize('method', ['get_absolute_url', 'get_delete_url', 'get_down_vote_url', 'get_hashid', 'get_remove_vote_url', 'get_review_url', 'get_slug', 'get_up_vote_url', 'get_update_url', 'get_vote_url', '__str__']) def test_proposal_model_method_works(db, method): proposal = f.ProposalFactory() assert getattr(p...
def select_2(train_embs, test_embs, downstream_train_examples, downstream_test_examples, tag, phase2_selection): cos = nn.CosineSimilarity(dim=1, eps=1e-06) bar = tqdm(range(len(downstream_test_examples)), desc='phase 2 similar select') if (not os.path.isdir(f'{args.output_dir}/{tag}/prompts')): os....
_torch _vision class MaskFormerFeatureExtractionTest(FeatureExtractionSavingTestMixin, unittest.TestCase): feature_extraction_class = (MaskFormerFeatureExtractor if (is_vision_available() and is_torch_available()) else None) def setUp(self): self.feature_extract_tester = MaskFormerFeatureExtractionTeste...
class BenchmarkTestCase(unittest.TestCase): def tearDown(self): for file in glob.glob('{0}/moonshot*.pkl'.format(TMP_DIR)): os.remove(file) def test_complain_if_no_price_fields_for_benchmark(self): class BuyAndHold(Moonshot): CODE = 'buy-and-hold' DB = 'sample...
def get_config_from_root(root): setup_cfg = os.path.join(root, 'setup.cfg') parser = configparser.ConfigParser() with open(setup_cfg, 'r') as f: parser.read_file(f) VCS = parser.get('versioneer', 'VCS') def get(parser, name): if parser.has_option('versioneer', name): retu...
def setup() -> None: root_log = get_logger() if constants.FILE_LOGS: log_file = Path('logs', 'bot.log') log_file.parent.mkdir(exist_ok=True) file_handler = handlers.RotatingFileHandler(log_file, maxBytes=5242880, backupCount=7, encoding='utf8') file_handler.setFormatter(core_logg...
def create_fixtures(dev: SmartDevice, outputdir: Path): for (name, module) in dev.modules.items(): module_dir = (outputdir / name) if (not module_dir.exists()): module_dir.mkdir(exist_ok=True, parents=True) sw_version = dev.hw_info['sw_ver'] sw_version = sw_version.split(...
def get_fslocation_from_item(node: 'Node') -> Tuple[(Union[(str, Path)], Optional[int])]: location: Optional[Tuple[(str, Optional[int], str)]] = getattr(node, 'location', None) if (location is not None): return location[:2] obj = getattr(node, 'obj', None) if (obj is not None): return ge...
class RuleAPITests(AuthenticatedAPITestCase): def setUp(self): super().setUp() self.client.force_authenticate(user=None) def test_can_access_rules_view(self): url = reverse('api:rules') response = self.client.get(url) self.assertEqual(response.status_code, 200) se...
.parametrize('subcommand, text, completions', [('create', '', ['jazz', 'rock']), ('create', 'ja', ['jazz ']), ('create', 'foo', []), ('creab', 'ja', [])]) def test_subcommand_completions(ac_app, subcommand, text, completions): line = 'music {} {}'.format(subcommand, text) endidx = len(line) begidx = (endidx...
class JalaliDateFormatter(BaseFormatter): _post_parsers = ['persianday', 'persiandayzeropadded', 'persiandayofyear', 'persiandayofyearzeropadded', 'persianmonth', 'persianmonthzeropadded', 'persianyear', 'persianyearzeropadded', 'persianshortyear', 'persianshortyearzeropadded', 'localdateformat', 'monthabbr', 'mont...
def _get_package(pl_name, version, robust, use_v8): pl_dir = (DataDir / pl_name) pl_dir.mkdir(parents=True, exist_ok=True) prefix = 'pdfium-' if use_v8: prefix += 'v8-' fn = (prefix + f'{ReleaseNames[pl_name]}.tgz') fu = f'{ReleaseURL}{version}/{fn}' fp = (pl_dir / fn) print(f"'{...
def integration_value(direction: Direction, subsystem: Subsystem, partition: Cut, system_state: SystemStateSpecification, repertoire_distance: Optional[str]=None) -> float: repertoire_distance = fallback(repertoire_distance, config.REPERTOIRE_DISTANCE) cut_subsystem = subsystem.apply_cut(partition) if (repe...
_start_docstrings('The bare MGP-STR Model transformer outputting raw hidden-states without any specific head on top.', MGP_STR_START_DOCSTRING) class MgpstrModel(MgpstrPreTrainedModel): def __init__(self, config: MgpstrConfig): super().__init__(config) self.config = config self.embeddings = ...
def score_bw(args): if args.backwards1: scorer1_src = args.target_lang scorer1_tgt = args.source_lang else: scorer1_src = args.source_lang scorer1_tgt = args.target_lang if (args.score_model2 is not None): if args.backwards2: scorer2_src = args.target_lang...
def get_dist_info(): if (torch.__version__ < '1.0'): initialized = dist._initialized else: initialized = dist.is_initialized() if initialized: rank = dist.get_rank() world_size = dist.get_world_size() else: rank = 0 world_size = 1 return (rank, world_s...
def _image_file(path): abs_path = os.path.abspath(path) image_files = os.listdir(abs_path) for i in range(len(image_files)): if ((not os.path.isdir(image_files[i])) and _is_image_file(image_files[i])): image_files[i] = os.path.join(abs_path, image_files[i]) return image_files
def c_array_initializer(components: list[str], *, indented: bool=False) -> str: indent = ((' ' * 4) if indented else '') res = [] current: list[str] = [] cur_len = 0 for c in components: if ((not current) or ((((cur_len + 2) + len(indent)) + len(c)) < 70)): current.append(c) ...
def se_inception_v3(include_top=True, weights=None, input_tensor=None, input_shape=None, pooling=None, classes=1000): if (weights not in {'imagenet', None}): raise ValueError('The `weights` argument should be either `None` (random initialization) or `imagenet` (pre-training on ImageNet).') if ((weights ...
def timeout_exponential_backoff(retries: int, timeout: float, maximum: float) -> Iterator[float]: (yield timeout) tries = 1 while (tries < retries): tries += 1 (yield timeout) while (timeout < maximum): timeout = min((timeout * 2), maximum) (yield timeout) while True:...
def _make_system(N, system): gamma = 0.25 a = destroy(N) if (system == 'simple'): H = (a.dag() * a) sc_ops = [(np.sqrt(gamma) * a)] elif (system == '2 c_ops'): H = QobjEvo([(a.dag() * a)]) sc_ops = [(np.sqrt(gamma) * a), ((gamma * a) * a)] elif (system == 'H td'): ...
def run_main(): topdirs = [('/%s/' % d) for d in os.listdir('/')] def abs_path_start(path, pos): if (pos < 0): return False return ((pos == 0) or (path[(pos - 1)] == ':')) def fix_path(p): pp = None for pr in topdirs: pp2 = p.find(pr) if (a...
() ('--filename', default='samples/sample_wind_poitiers.csv', help='Input filename') ('--year', default=2014, help='Year') def main(filename, year): df_all = pd.read_csv(filename, parse_dates=['Timestamp']) df_all = df_all.set_index('Timestamp') f_year = get_by_func('year') df_all['by_page'] = df_all.in...
_fixtures(WebFixture, AddressAppFixture) def test_adding_an_address(web_fixture, address_app_fixture): browser = address_app_fixture.browser browser.open('/') browser.click(XPath.link().with_text('Add')) assert address_app_fixture.is_on_add_page() browser.type(XPath.input_labelled('Name'), 'John Doe...