code
stringlengths
281
23.7M
def run_hp_search_ray(trainer, n_trials: int, direction: str, **kwargs) -> BestRun: import ray def _objective(trial, local_trainer, checkpoint_dir=None): try: from transformers.utils.notebook import NotebookProgressCallback if local_trainer.pop_callback(NotebookProgressCallback):...
(HAS_ANNOTATED) def test_annotated(): class WithAnnotated(): annotated_field: typing.Annotated[(int, 'metadata')] assert (get_dataclass_shape(WithAnnotated) == Shape(input=InputShape(constructor=WithAnnotated, kwargs=None, fields=(InputField(type=typing.Annotated[(int, 'metadata')], id='annotated_field'...
def initialize_dict(dict, entries, separator): for entry in entries: hyphen_free = entry.replace(separator, '').lower() boundary_list = [1] i = 1 while (i < len(entry)): if (entry[i] == separator): boundary_list += [1] i += 1 el...
def test_index_query_scan() -> None: from pynamodb.attributes import NumberAttribute from pynamodb.models import Model from pynamodb.indexes import GlobalSecondaryIndex from pynamodb.pagination import ResultIterator class UntypedIndex(GlobalSecondaryIndex): bar = NumberAttribute(hash_key=Tru...
class TestShellCommand(): def klass(self): return configtypes.ShellCommand .parametrize('kwargs, val, expected', [({}, '[foobar]', ['foobar']), ({'placeholder': True}, '[foo, "{}", bar]', ['foo', '{}', 'bar']), ({'placeholder': True}, '["foo{}bar"]', ['foo{}bar']), ({'placeholder': True}, '[foo, "bar {}...
.change_flags(vm__lazy=True) def test_ifelse_lazy_c(): a = scalar() b = generic() c = generic() notimpl = NotImplementedOp() cloops = [True, False] if (pytensor.config.cxx == ''): cloops = [False] for use_cloop in cloops: for lazy in [True, None]: linker = pytenso...
def cache_features(features, num_shards): if (num_shards == 1): return (features, tf.no_op(name='init_queue')) flat_features = list(features.itervalues()) queue = tf.FIFOQueue(num_shards, dtypes=[v.dtype for v in flat_features]) flat_features = [tf.split(v, num_shards, axis=0) for v in flat_feat...
class BertDataset(Dataset): def __init__(self, name, indexed_dataset, data_prefix, num_epochs, max_num_samples, masked_lm_prob, max_seq_length, short_seq_prob, seed): self.name = name self.seed = seed self.masked_lm_prob = masked_lm_prob self.max_seq_length = max_seq_length s...
(scope='module', params=[(Arc, (0, 0, 5)), (Circle, (0, 0, 5)), (Ellipse, (0, 0, 0, 5)), (Sector, (0, 0, 3)), (Line, (0, 0, 7, 7)), (Rectangle, (0, 0, 20, 20)), (BorderedRectangle, (0, 0, 30, 10)), (Triangle, (0, 0, 2, 2, 5, 5)), (Star, (1, 1, 20, 11, 5)), (Polygon, ((0, 0), (1, 1), (2, 2)))]) def shape_and_positionals...
class ReplicaSetTelemetry(BaseModel, extra='forbid'): id: int = Field(..., description='') local: Optional['LocalShardTelemetry'] = Field(default=None, description='') remote: List['RemoteShardTelemetry'] = Field(..., description='') replicate_states: Dict[(str, 'ReplicaState')] = Field(..., description...
def create_vit(vit, image_size, use_grad_checkpointing=False, ckpt_layer=0, drop_path_rate=0): assert (vit in ['base', 'large']), 'vit parameter must be base or large' if (vit == 'base'): vision_width = 768 visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_w...
.usefixtures('config_stub', 'key_config_stub') class TestConfigPyModules(): def qbmodulepy(self, tmp_path): return ConfPy(tmp_path, filename='qbmodule.py') (autouse=True) def restore_sys_path(self): old_path = sys.path.copy() (yield) sys.path = old_path def test_bind_in_m...
class AddNewsForm(forms.ModelForm): name = HoneypotField() class Meta(): model = Item fields = ('link', 'section', 'title', 'language', 'description') def __init__(self, *args, **kwargs): kwargs['initial'] = {'section': 6} super().__init__(*args, **kwargs) self.fields...
class ValidationException(DomainException): def for_failed_validations(cls, failed_validation_constraints): detail_messages = [i.message for i in failed_validation_constraints] return cls(message=_.ngettext('An error occurred', 'Some errors occurred', len(detail_messages)), detail_messages=detail_me...
class SequentialNodeRewriter(NodeRewriter): def __init__(self, *rewriters: Rewriter, apply_all_rewrites: bool=False, profile: bool=False): super().__init__() self.rewrites: Sequence[Rewriter] = rewriters assert isinstance(self.rewrites, tuple) self.reentrant = any((getattr(rewrite, '...
def eval_directory(path): with open(os.path.join(path, 'config.json')) as fp: config = json.load(fp) one_shot_architectures = glob.glob(os.path.join(path, 'one_shot_architecture_*.obj')) one_shot_architectures.sort(key=natural_keys) test_errors = [] valid_errors = [] for model in one_sho...
class AllowedSmilesCharDictionary(object): def __init__(self) -> None: self.forbidden_symbols = {'Ag', 'Al', 'Am', 'Ar', 'At', 'Au', 'D', 'E', 'Fe', 'G', 'K', 'L', 'M', 'Ra', 'Re', 'Rf', 'Rg', 'Rh', 'Ru', 'T', 'U', 'V', 'W', 'Xe', 'Y', 'Zr', 'a', 'd', 'f', 'g', 'h', 'k', 'm', 'si', 't', 'te', 'u', 'v', 'y'}...
class QuestionSuggestionChainBase(Chain, BaseModel): llm_chain: LLMChain output_key: str = 'questions' class Config(): extra = Extra.forbid arbitrary_types_allowed = True def input_keys(self) -> List[str]: return self.llm_chain.prompt.input_variables def output_keys(self) -> ...
def test_db_reuse_simple(django_pytester: DjangoPytester) -> None: django_pytester.create_test_module('\n import pytest\n\n from .app.models import Item\n\n .django_db\n def test_db_can_be_accessed():\n assert Item.objects.count() == 0\n ') result = django_pytester.runp...
def interpolateables(state_a, state_b): animate = [] for (tag, path, values) in state_b.diff(state_a): if (tag == 'set'): ypath = path_to_str(path) v_new = get_elements(state_b, ypath)[0] v_old = values for type in [float, Color, Background]: ...
class RSSReader(Session): def __init__(self, factory, url, rate): self.url = url self.rate = rate self.factory = factory self.old_entries = {} def get_new(self): feed = feedparser.parse(self.url) new_entries = [] for entry in feed['entries']: i...
def init_ctx(f): (f) def wrapper(self, *args, **kw): if (self.manager.label is None): label_addr = self.ql.os.heap.alloc(ctypes.sizeof(label_t)) self.manager.label = label_t(self.ql, label_addr) self.manager.label.l_flags = 1 self.manager.label.updateToMem...
class DownSample(nn.Module): def __init__(self, in_channels, s_factor): super(DownSample, self).__init__() self.down = nn.Sequential(nn.Upsample(scale_factor=0.5, mode='bilinear', align_corners=False), nn.Conv2d(in_channels, (in_channels + s_factor), 1, stride=1, padding=0, bias=False)) def forw...
def test_matrix_variable_selection_duplicate_exclusion(hatch, helpers, temp_dir, config_file): config_file.model.template.plugins['default']['tests'] = False config_file.save() project_name = 'My.App' with temp_dir.as_cwd(): result = hatch('new', project_name) assert (result.exit_code == 0),...
class SimpleOxfordPetDataset(OxfordPetDataset): def __getitem__(self, *args, **kwargs): sample = super().__getitem__(*args, **kwargs) image = np.array(Image.fromarray(sample['image']).resize((256, 256), Image.LINEAR)) mask = np.array(Image.fromarray(sample['mask']).resize((256, 256), Image.N...
class ViewStageBase(object): def __init__(self, name, state_provider): self.name = name self.state_provider = state_provider self.datamodel = _datamodel self.view = None def schedule(self): raise NotImplementedError() def ready(self): raise NotImplementedError...
def main(argv): trainIds = False try: (opts, args) = getopt.getopt(argv, 'ht') except getopt.GetoptError: printError('Invalid arguments') for (opt, arg) in opts: if (opt == '-h'): printHelp() sys.exit(0) elif (opt == '-t'): trainIds = T...
def test_imbalance_penalty_at_insufficent_payer_balance(): imbalance_penalty = calculate_imbalance_fees(channel_capacity=TokenAmount(20), proportional_imbalance_fee=ProportionalFeeAmount(1)) (pair, _) = _foward_transfer_pair(TokenAmount(10), NettingChannelStateProperties(our_state=NettingChannelEndStateProperti...
def _to_sequence_example(set_info, decoder, vocab): set_id = set_info['set_id'] image_data = [] image_ids = [] caption_data = [] caption_ids = [] for image_info in set_info['items']: filename = os.path.join(FLAGS.image_dir, set_id, (str(image_info['index']) + '.jpg')) with open(f...
def time_info(exp, file_name='log.txt', runs=1, nbins=10, max_line_length=10000): time_list = [] config_file = f'./configs/{exp}.json' sweeper = Sweeper(config_file) for i in range((runs * sweeper.config_dicts['num_combinations'])): log_file = f'./logs/{exp}/{(i + 1)}/{file_name}' try: ...
def test_abi3(tmp_path): project_dir = (tmp_path / 'project') limited_api_project.generate(project_dir) actual_wheels = utils.cibuildwheel_run(project_dir, add_env={'CIBW_SKIP': 'pp* '}) expected_wheels = [w.replace('cp38-cp38', 'cp38-abi3') for w in utils.expected_wheels('spam', '0.1.0') if (('-pp' not...
class BM25Search(): def __init__(self, index_name: str, hostname: str='localhost', keys: Dict[(str, str)]={'title': 'title', 'body': 'txt'}, language: str='english', batch_size: int=128, timeout: int=100, retry_on_timeout: bool=True, maxsize: int=24, number_of_shards: int='default', initialize: bool=True): ...
class ZeroConfProcess(multiprocessing.Process): def __init__(self, signalk): self.name_type = False self.pipe = NonBlockingPipe('zeroconf', True) super(ZeroConfProcess, self).__init__(target=self.process, daemon=True) self.start() def remove_service(self, zc, type, name): ...
def get_bandpath_fcc(ase_atom, npoints=30): from ase.dft.kpoints import ibz_points, kpoint_convert, get_bandpath points = ibz_points['fcc'] G = points['Gamma'] X = points['X'] W = points['W'] K = points['K'] L = points['L'] (kpts_reduced, kpath, sp_points) = get_bandpath([L, G, X, W, K, ...
def _horizontal_datum_from_params(cf_params): datum_name = cf_params.get('horizontal_datum_name') if (datum_name and (datum_name not in ('undefined', 'unknown'))): try: return Datum.from_name(datum_name) except CRSError: pass ellipsoid = None ellipsoid_name = cf_p...
def euler2mat_tf(point_cloud, rotations): batch_size = rotations.get_shape()[0].value assert (rotations.get_shape()[1].value == 3) rotated_list = [] one = tf.constant([1.0]) zero = tf.constant([0.0]) for i in range(batch_size): x = rotations[(i, 0)] y = rotations[(i, 1)] ...
class PointGroup(BaseModel, extra='forbid'): hits: List['ScoredPoint'] = Field(..., description='Scored points that have the same value of the group_by key') id: 'GroupId' = Field(..., description='') lookup: Optional['Record'] = Field(default=None, description='Record that has been looked up using the grou...
class TestMsgFmt(unittest.TestCase): def test_ok(self): with pofile_from_entry(msgid='test string', msgstr='estay ingstray') as p: test_msgfmt(p.name) def test_busted_newlines(self): with pofile_from_entry(msgid='multi\nline\nstring', msgstr='ultimay\ninelay\ningstray\n') as p: ...
def test_deprecated_decorator(recwarn_always: pytest.WarningsRecorder) -> None: assert (deprecated_old() == 3) got = recwarn_always.pop(TrioDeprecationWarning) assert isinstance(got.message, Warning) assert ('test_deprecate.deprecated_old is deprecated' in got.message.args[0]) assert ('1.5' in got.m...
def gpt_collate_fn(data, tokenizer): batch_data = {} for key in data[0]: batch_data[key] = [d[key] for d in data] output_batch = tokenizer(batch_data['output_text'], padding=True, return_tensors='pt', add_special_tokens=False, return_attention_mask=False, truncation=True, max_length=1000) batch_...
class PipelinePackIterator(PipelineIterator): def __iter__(self): self.iterator = iter(self.loader) return self def __next__(self): is_last = False accumulator = [] if ((self._loader_batch_index is not None) and (self._loader_batch_index < self.loader_batch_size)): ...
def test_index_bits(): data = Bits(8, 202) x = Bits(4, 3) assert (data[x] == 1) y = Bits(4, (- 8)) with pytest.raises(IndexError): data[y] a = Bits(8, 4) assert (data[a] == 0) b = Bits(8, 20) with pytest.raises(IndexError): data[b] c = Bits(8, (- 1)) with pyte...
def down_pic(pic_urls, keyword): filepath = judge_filepath(keyword) for (i, pic_url) in enumerate(pic_urls): try: pic = requests.get(pic_url, timeout=15) name = (str((i + 1)) + '.jpg') filename = os.path.join(filepath, name) with open(filename, 'wb') as f:...
class TestDSSSSHSerialization(): def test_load_ssh_public_key_dss_too_short(self, backend): ssh_key = b'ssh-dss' with pytest.raises(ValueError): load_ssh_public_key(ssh_key, backend) def test_load_ssh_public_key_dss_comment_with_spaces(self, backend): ssh_key = b'ssh-dss AAAA...
def build(opt): dpath = os.path.join(opt['datapath'], opt['dataset']) embpath = os.path.join(opt['datapath'], 'embeddings') logpath = os.path.join(opt['datapath'], 'logs') modelpath = os.path.join(opt['datapath'], 'models') version = None if (not build_data.built(dpath, version_string=version)):...
class QuantLinear(nn.Linear): def __init__(self, in_features, out_features, bias=True): super(QuantLinear, self).__init__(in_features, out_features, bias) self.layer_type = 'QuantLinear' self.bit = 4 self.weight_quant = weight_quantize_fn(w_bit=self.bit, power=True) def forward(s...
class CacheMixin(): cache_timeout = 60 def get_cache_timeout(self): return self.cache_timeout def dispatch(self, *args, **kwargs): if (not settings.CACHE_PAGE_ENABLED): return super().dispatch(*args, **kwargs) return cache_page(self.get_cache_timeout())(super().dispatch)(...
def open_database_from_options_or_exit(db_options, quiet=False, apsw_warning=False): from .. import dbutils dbinfo = dbutils.get_dbinfo(db_options.database) try: return dbinfo.open_database(copy_to_memory=db_options.copy_to_memory, quiet=quiet, apsw_warning=apsw_warning) except dbutils.DBError a...
def test(model, args): print('Test') join = os.path.join if (not os.path.exists(join(args.save_dir, 'infer'))): os.mkdir(join(args.save_dir, 'infer')) if (not os.path.exists(join(args.save_dir, 'label'))): os.mkdir(join(args.save_dir, 'label')) split_dir = os.path.join(args.src_dir, ...
def get_markdown_header(category): header = f''' # Release Notes worksheet {category} The main goal of this process is to rephrase all the commit messages below to make them clear and easy to read by the end user. You should follow the following instructions to do so: * **Please cleanup, and format commit titles to...
def att_block_model(x_train): inputs = Input((x_train.shape[1],)) x = att_block(inputs) predictions = Dense(7, kernel_initializer=initializers.glorot_normal(seed=1), kernel_regularizer=regularizers.l2(1e-10), kernel_constraint=unit_norm(), activity_regularizer=regularizers.l2(1e-10), use_bias=True, bias_ini...
class StreamingPlayer(): description: str currentChapter: int = 0 movie: str = None def __init__(self, description: str, amplifier): self.description = description self.amplifier = amplifier def on(self) -> None: print(f'{self.description} on') def off(self) -> None: ...
class AsyncTakeTest(unittest.TestCase): def _test_async_take_with_error(path: str) -> None: tc = unittest.TestCase() dist.init_process_group(backend='gloo') with patch('torchsnapshot.storage_plugin.FSStoragePlugin', FaultyFSStoragePlugin): future = torchsnapshot.Snapshot.async_ta...
def unite_values(*values: Value) -> Value: if (not values): return NO_RETURN_VALUE hashable_vals = {} unhashable_vals = [] for value in values: if isinstance(value, MultiValuedValue): subvals = value.vals elif (isinstance(value, AnnotatedValue) and isinstance(value.va...
def _get_jupyter_python_script(subcommand='notebook'): dist = ('jupyterlab' if (subcommand == 'lab') else 'notebook') try: ep = _find_entry_point(dist, 'console_scripts', f'jupyter-{subcommand}') if (ep is None): _log.debug(f'Entry point {dist}.console_scripts.jupyter-{subcommand} no...
def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False, output_loading_info=False): try: import tensorflow as tf import torch except ImportError: logger.error('Loading a PyTorch model in TensorFlow, requires both PyTorch and T...
class DownsampleAvg(nn.Module): def __init__(self, in_chs, out_chs, stride=1, dilation=1, apply_act=False, layers: LayerFn=None): super(DownsampleAvg, self).__init__() layers = (layers or LayerFn()) avg_stride = (stride if (dilation == 1) else 1) if ((stride > 1) or (dilation > 1)): ...
class HourglassAEModule(nn.Module): def __init__(self, depth, stage_channels, norm_cfg=dict(type='BN', requires_grad=True)): norm_cfg = copy.deepcopy(norm_cfg) super().__init__() self.depth = depth cur_channel = stage_channels[0] next_channel = stage_channels[1] self....
class MaxExcessReturnPortfolio(Portfolio): def __init__(self, cov_matrix: QFDataFrame, variance_of_assets: QFSeries, upper_constraint: Union[(float, Sequence[float])]=None): self.cov_matrix = cov_matrix self.variance_of_assets = variance_of_assets self.upper_constraint = upper_constraint ...
class _LRScheduler(object): def __init__(self, optimizer, last_epoch=(- 1)): self.optimizer = optimizer if (last_epoch == (- 1)): for group in optimizer.param_groups: group.setdefault('initial_lr', group['lr']) else: for (i, group) in enumerate(optimiz...
def test_valid_oauth(app): user = model.user.get_user('devtable') app = model.oauth.list_applications_for_org(model.user.get_user_or_org('buynlarge'))[0] token_string = ('%s%s' % (('a' * 20), ('b' * 20))) (oauth_token, _) = model.oauth.create_user_access_token(user, app.client_id, 'repo:read', access_to...
class Migration(migrations.Migration): dependencies = [('adserver', '0021_publisher_record_ad_views')] operations = [migrations.RemoveField(model_name='adtype', name='publisher'), migrations.AddField(model_name='adtype', name='default_enabled', field=models.BooleanField(default=False, help_text='Whether this ad...
class KnownValues(unittest.TestCase): ((not has_spglib), 'spglib not found') def test_D4h_vs_spglib(self): dim = 3 magmom = [1, 1, (- 1), (- 1), 1, (- 1), 1, 1, (- 1), (- 1), 1, (- 1)] cell = make_cell_D4h(dim, magmom) sg = spg.SpaceGroup(cell) sg.backend = 'spglib' ...
def _torch_alloc(size, device_id): torch_stream_ptr = torch.cuda.current_stream().cuda_stream cupy_stream_ptr = cupy.cuda.get_current_stream().ptr if (torch_stream_ptr != cupy_stream_ptr): raise RuntimeError('The current stream set in PyTorch and CuPy must be same. Use `pytorch_pfn_extras.cuda.strea...
def main(): dsz.ui.Echo('Pulling Firefox browser data...', dsz.GOOD) dsz.control.echo.Off() dsz.cmd.Run('background log python windows/firefoxrip.py -args "-s 1000000"', dsz.RUN_FLAG_RECORD) dsz.control.echo.On() dsz.ui.Echo('\tNo IE Capability Available!', dsz.WARNING) dsz.ui.Echo('\tNo Chrome ...
def create_sky_temple_key(key_number: int, resource_database: ResourceDatabase) -> PickupEntry: return PickupEntry(name=f'Sky Temple Key {(key_number + 1)}', progression=((resource_database.get_item(echoes_items.SKY_TEMPLE_KEY_ITEMS[key_number]), 1),), model=PickupModel(game=resource_database.game_enum, name=echoes...
class InvalidBodyLengthError(ProtocolError): def __init__(self, expected, actual): self.expected_length = expected self.actual_length = actual def __str__(self): return ('InvalidBodyLengthError: Expected %d bytes, received %d' % (self.expected_length, self.actual_length))
def pblock_053(content): stage_number = int(get1(content, b'04')) pzs = sxml.PolesZeros(pz_transfer_function_type=ptftype(get1(content, b'03')), input_units=sxml.Units(name=punit(get1(content, b'05'))), output_units=sxml.Units(name=punit(get1(content, b'06'))), normalization_factor=float(get1(content, b'07')), ...
def train_model(model, train, test, num_classes): x_train = train[0].reshape(((train[0].shape[0],) + input_shape)) x_test = test[0].reshape(((test[0].shape[0],) + input_shape)) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train s...
def readData(segmentation_input): global numFrame, df, df_complete, time df = pd.read_csv(segmentation_input) numFrame = df.iloc[(- 1)]['Frame'] df = df[0:numFrame] dupl = [] df_complete = df[0:numFrame] df = df[(df.Visibility == 1)].reset_index(drop=True) time = df[['Time']] df = df...
def follow_redirects(link, sites=None): def follow(url): return ((sites == None) or (urlparse.urlparse(url).hostname in sites)) class RedirectHandler(urllib2.HTTPRedirectHandler): def __init__(self): self.last_url = None def redirect_request(self, req, fp, code, msg, hdrs, ne...
class Effect3774(BaseEffect): type = 'passive' def handler(fit, module, context, projectionRange, **kwargs): fit.ship.increaseItemAttr('hiSlots', module.getModifiedItemAttr('hiSlotModifier'), **kwargs) fit.ship.increaseItemAttr('medSlots', module.getModifiedItemAttr('medSlotModifier'), **kwargs)...
def get_cuda_info(device=None, unit='G', number_only=True): current_mem = get_gpu_memory_usage_by_current_program(device, unit, number_only) (all_mem, used, _, ratio) = get_gpu_memory_info(device, unit, number_only) utilization = get_gpu_utilization(device) return {'gpu_mem_ratio': ratio, 'gpu_mem': use...
def update(): for episode in range(100): observation = env.reset() action = RL.choose_action(str(observation)) while True: env.render() (observation_, reward, done) = env.step(action) action_ = RL.choose_action(str(observation_)) RL.learn(str(o...
def test_get_state_dict(): if (torch.__version__ == 'parrots'): state_dict_keys = set(['block.conv.weight', 'block.conv.bias', 'block.norm.weight', 'block.norm.bias', 'block.norm.running_mean', 'block.norm.running_var', 'conv.weight', 'conv.bias']) else: state_dict_keys = set(['block.conv.weight...
def _start_all_stats_collection_from_deltas(deltas: List[Delta], partition_value_string: Optional[str], partition_canonical_string: Optional[str], columns: Optional[List[str]]=None, trace_id: Optional[str]=None, file_count_per_cpu: Optional[int]=MANIFEST_FILE_COUNT_PER_CPU, cpus_per_instance: Optional[int]=DEFAULT_CPUS...
class ColdcardPlugin(HW_PluginBase): keystore_class = Coldcard_KeyStore minimum_library = (0, 7, 7) DEVICE_IDS = [(COINKITE_VID, CKCC_PID), (COINKITE_VID, CKCC_SIMULATED_PID)] SUPPORTED_XTYPES = ('standard', 'p2wpkh-p2sh', 'p2wpkh', 'p2wsh-p2sh', 'p2wsh') def __init__(self, parent, config, name): ...
class MetaTrainer(object): def __init__(self, args): self.args = args if (args.dataset == 'miniimagenet'): from dataloader.mini_imagenet import MiniImageNet as Dataset args.num_class = 64 print('Using dataset: miniImageNet, base class num:', args.num_class) ...
def test_is_debugging(monkeypatch): import pytest_timeout assert (not pytest_timeout.is_debugging()) from types import ModuleType module_name = 'custom.pydevd' module = ModuleType(module_name) monkeypatch.setitem(sys.modules, module_name, module) def custom_trace(*args): pass cus...
.end_to_end() def test_migrating_a_whole_task_with_persist(tmp_path): source = '\n import pytask\n\n .persist\n .depends_on("in.txt")\n .produces("out.txt")\n def task_dummy(depends_on, produces):\n produces.write_text(depends_on.read_text())\n ' tmp_path.joinpath('task_module.py').writ...
class DataConfig(): def __init__(self, path_config_json): path_config_json = Path(path_config_json) config_dict = utils.Json.load(path_config_json) dir_config = path_config_json.parent self.lm_name = config_dict['lm_name'] self.path_test = (dir_config / config_dict['path_test...
def conv_functional(): input_shape = (128, 28, 28, 1) inp = tf.keras.Input(shape=input_shape[1:]) x = tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu')(inp) x = tf.keras.layers.Conv2DTranspose(32, kernel_size=(3, 3), activation='relu')(x) x = tf.keras.layers.DepthwiseConv2D(depth_mul...
def test_addbug() -> None: int5A = Fsm(alphabet={Charclass('a'), Charclass('b'), Charclass('c'), (~ Charclass('abc'))}, states={0, 1}, initial=1, finals={1}, map={0: {(~ Charclass('abc')): 0, Charclass('a'): 0, Charclass('b'): 0, Charclass('c'): 0}, 1: {(~ Charclass('abc')): 0, Charclass('a'): 0, Charclass('b'): 1,...
('beeref.widgets.SceneToPixmapExporterDialog.exec') ('beeref.widgets.SceneToPixmapExporterDialog.value') ('PyQt6.QtWidgets.QFileDialog.getSaveFileName') def test_on_action_export_scene(file_mock, value_mock, exec_mock, view, tmpdir, qtbot): item = BeeTextItem('foo') view.scene.addItem(item) filename = os.pa...
def group_connections(connections): grouped_conns = defaultdict(list) if isinstance(connections, QuerySet): languages = connections.values_list('contact__language', flat=True) for language in languages.distinct(): lang_conns = connections.filter(contact__language=language) ...
class Pirate(cmd2.Cmd): def __init__(self): shortcuts = dict(cmd2.DEFAULT_SHORTCUTS) shortcuts.update({'~': 'sing'}) super().__init__(multiline_commands=['sing'], terminators=[MULTILINE_TERMINATOR, '...'], shortcuts=shortcuts) self.default_to_shell = True self.songcolor = 'bl...
def save_checkpoint(model, args, is_best=False): directory = os.path.expanduser(args.save_dir) if (not os.path.exists(directory)): os.makedirs(directory) filename = '{}_{}_{}.pth'.format(args.model, args.backbone, args.dataset) filename = os.path.join(directory, filename) if args.distributed...
def swap_gauge(stdscr, pos_y, pos_x, size, mem_data): values = ([(((mem_data['used'] / mem_data['tot']) * 100.0), NColors.red()), (((mem_data['cached'] / mem_data['tot']) * 100.0), NColors.yellow())] if (mem_data['tot'] > 0) else []) used = size_to_string(mem_data['used'], 'k') total = size_to_string(mem_da...
class LegacyIndex(Index): INDEX_FILENAME = 'hf_bert_base.hnswSQ8_correct_phi_128.c_index' PASSAGE_FILENAME = 'psgs_w100.tsv.pkl' def __init__(self, vector_size, index_path): self.index_id_to_db_id = [] self.index_path = index_path self.passages = self._load_passages() self.ve...
def seed_everything(seed, cudnn_deterministic=False): if (seed is not None): print(f'Global seed set to {seed}') random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) if cudnn_deterministic: torch.backends.cudnn.determinis...
class ISIC2018DatasetFast(Dataset): def __init__(self, mode, data_dir=None, one_hot=True, image_size=224, aug=None, aug_empty=None, transform=None, img_transform=None, msk_transform=None, add_boundary_mask=False, add_boundary_dist=False, logger=None, **kwargs): self.print = (logger.info if logger else print...
class CaptureBase(abc.ABC, Generic[AnyStr]): EMPTY_BUFFER: AnyStr def __init__(self, fd: int) -> None: raise NotImplementedError() def start(self) -> None: raise NotImplementedError() def done(self) -> None: raise NotImplementedError() def suspend(self) -> None: raise...
def get_patterns(graph_file, base_pattern): patterns_graph = read_graph(graph_file) prompts = [x.lm_pattern for x in list(patterns_graph.nodes)] no_base = [] for p in prompts: if (p.replace(' .', '.') == base_pattern.replace(' .', '.')): continue no_base.append(p) assert ...
.needs_connection def test_HITRAN_molecules_list(verbose=True, *args, **kwargs): from radis.db.classes import HITRAN_MOLECULES from radis.misc.basics import compare_lists molecules = fetch_HITRAN_molecules() if verbose: print('HITRAN molecules, fetched online ') print(molecules) ...
def _create_unless(terminals, g_regex_flags, re_, use_bytes): tokens_by_type = classify(terminals, (lambda t: type(t.pattern))) assert (len(tokens_by_type) <= 2), tokens_by_type.keys() embedded_strs = set() callback = {} for retok in tokens_by_type.get(PatternRE, []): unless = [] for...
class SingleAvatarPromotion(Struct): AvatarID: int Promotion: int PromotionCostList: List[PromotionCost] MaxLevel: int PlayerLevelRequire: Union[(int, None)] WorldLevelRequire: Union[(int, None)] AttackBase: PromotionAttr AttackAdd: PromotionAttr DefenceBase: PromotionAttr Defenc...
class BddOptions(SolverOptions): CUDD_ALL_REORDERING_ALGORITHMS = range(1, 23) (CUDD_REORDER_SAME, CUDD_REORDER_NONE, CUDD_REORDER_RANDOM, CUDD_REORDER_RANDOM_PIVOT, CUDD_REORDER_SIFT, CUDD_REORDER_SIFT_CONVERGE, CUDD_REORDER_SYMM_SIFT, CUDD_REORDER_SYMM_SIFT_CONV, CUDD_REORDER_WINDOW2, CUDD_REORDER_WINDOW3, CU...
def run_hp_search_ray(trainer, n_trials: int, direction: str, **kwargs) -> BestRun: import ray def _objective(trial, local_trainer, checkpoint_dir=None): try: from transformers.utils.notebook import NotebookProgressCallback if local_trainer.pop_callback(NotebookProgressCallback):...
def save_command_run_params(args): os.makedirs(args.out, exist_ok=True) with open(os.path.join(args.out, 'args.json'), 'w') as args_file: json.dump(args.__dict__, args_file) with open(os.path.join(args.out, 'command.sh'), 'w') as command_file: command_file.write(' '.join(sys.argv)) c...
def get_runtime_info(parsed=None): return {'exec': {'version': version, 'api_version': api_version, 'argv': sys.argv, 'parsed': parsed}, 'python': {'name': sys.implementation.name, 'executable': sys.executable, 'version': platform.python_version()}, 'system': {'platform': platform.platform(), 'fs_encoding': sys.get...