code
stringlengths
101
5.91M
.parametrize('constraint_declaration, expected_constraint_class', [(Interval(Real, 0, 1, closed='both'), Interval), (StrOptions({'option1', 'option2'}), StrOptions), (Options(Real, {0.42, 1.23}), Options), ('array-like', _ArrayLikes), ('sparse matrix', _SparseMatrices), ('random_state', _RandomStates), (None, _NoneCons...
class SchemaNode(ASTNode): def __init__(self, val, data_type, fields): super().__init__('SCHEMA', val, data_type, fields) def textual_form_core(self): return self.val
def parse_int_from_env(key, default=None): try: value = os.environ[key] except KeyError: _value = default else: try: _value = int(value) except ValueError: raise ValueError('If set, {} must be a int.'.format(key)) return _value
def run_cn(_trainMode, _dataType, _oRate, _var, _GPU_ID): (_n, _oRange, _hdims, _actv, _maxEpoch, _PLOT_EVERY, _SAVE_NET, _SAVE_FIG) = get_common_config() (x, y, t) = data4reg(_type=_dataType, _n=_n, _oRange=_oRange, _oRate=_oRate, measVar=_var) xtest = np.linspace(start=(- 3), stop=3, num=1000).reshape(((-...
class SpeedMonitor(Callback): def __init__(self, intra_step_time: bool=True, inter_step_time: bool=True, epoch_time: bool=True, verbose=False): super().__init__() self._log_stats = AttributeDict({'intra_step_time': intra_step_time, 'inter_step_time': inter_step_time, 'epoch_time': epoch_time}) ...
def iter_corpus(filename, callback, skip_empty_lines=True): if _is_bliss(filename): _iter_bliss(filename=filename, callback=callback) else: _iter_txt(filename=filename, callback=callback, skip_empty_lines=skip_empty_lines)
class CyExec(CythonCommand, libpython.PyExec, EvaluateOrExecuteCodeMixin): name = '-cy-exec' command_class = gdb.COMMAND_STACK completer_class = gdb.COMPLETE_NONE def invoke(self, expr, from_tty): (expr, input_type) = self.readcode(expr) executor = libpython.PythonCodeExecutor() ...
def check_ppf_private(distfn, arg, msg): ppfs = distfn._ppf(np.array([0.1, 0.5, 0.9]), *arg) npt.assert_((not np.any(np.isnan(ppfs))), (msg + 'ppf private is nan'))
class LLVMCodeGenExecuted(ExecutionCounter): def __init__(self): super(LLVMCodeGenExecuted, self).__init__('llvm_codegen_executed')
class ImagesDataset(Dataset): def __init__(self, source_root, target_root, target_transform=None, source_transform=None, mode='train', num_imgs=1000): self.source_paths = sorted(make_dataset(source_root))[:num_imgs] self.target_paths = sorted(make_dataset(target_root))[:num_imgs] self.source...
class ServeCommand(BaseTransformersCLICommand): def register_subcommand(parser: ArgumentParser): serve_parser = parser.add_parser('serve', help='CLI tool to run inference requests through REST and GraphQL endpoints.') serve_parser.add_argument('--task', type=str, choices=get_supported_tasks(), help=...
class StandfordCars(CoOp): def __init__(self, data_root: str, mode: str, backbone_name='resnet12', image_root='', split_path='splits/split_zhou_StanfordCars.json', image_sz=84) -> None: self.image_root = os.path.join(data_root, 'stanford_cars', image_root) super().__init__(data_root, mode, backbone_...
def get_parser(disable: List[str]=None, lang: str='en', merge_terms: Optional[Set]=None, max_sent_len: Optional[int]=None) -> Callable: disable = (['ner', 'parser', 'tagger', 'lemmatizer'] if (not disable) else disable) merge_terms = ({} if (not merge_terms) else merge_terms) nlp = spacy.load(lang, disable=...
def main(): args = config.args train_conf = config.train checkpoint = train_conf.checkpoint start_epoch = train_conf.start_epoch epochs = train_conf.epochs phase = 'Multispectral' if (checkpoint is None): model = SSD300(n_classes=args.n_classes) biases = list() not_bi...
class PromptTrainer(): def __init__(self, model, config, train_loader, valid_loader, test_loader) -> None: self.model = model self.config = config (self.train_loader, self.valid_loader, self.test_loader) = (train_loader, valid_loader, test_loader) self.save_name = os.path.join(config...
class RegularArray(Content): def __init__(self, content, size): assert isinstance(content, Content) assert isinstance(size, int) assert (size > 0) self.content = content self.size = size def random(minlen=0, choices=None): size = random_length(1, 5) return...
class Decoder(nn.Module): def __init__(self, z_dim, c_dim, img_size): super(Decoder, self).__init__() self.img_4 = (img_size / 4) self.fc = nn.Sequential(nn.Linear(z_dim, int(((self.img_4 * self.img_4) * 64))), nn.ReLU()) self.model = nn.Sequential(nn.ConvTranspose2d(64, 64, 4, strid...
def make_batch(image, mask, device): image = np.array(Image.open(image).convert('RGB')) image = (image.astype(np.float32) / 255.0) image = image[None].transpose(0, 3, 1, 2) image = torch.from_numpy(image) mask = np.array(Image.open(mask).convert('L')) mask = (mask.astype(np.float32) / 255.0) ...
def append_to_bib(bib_entery): global _BIBLIOGRAPHY global _BIBLIOGRAPHY_TO_OUTPUT for bib_entery_i in to_list(bib_entery): bib = _BIBLIOGRAPHY.entries[bib_entery_i] if (bib not in _BIBLIOGRAPHY_TO_OUTPUT): _BIBLIOGRAPHY_TO_OUTPUT.append(bib)
def spawn_3D_doors(map, entrance, exit, base_pos=5): border_size = (1, 1, 1) (i, k, j) = (len(map[0][0]), len(map), len(map[0])) CLIENT.fillCube(FillCubeRequest(cube=Cube(min=Point(x=(- border_size[0]), y=(base_pos + 1), z=(- border_size[1])), max=Point(x=((i + border_size[0]) - 1), y=(((base_pos + k) + bor...
class ReversibleField(Field): def __init__(self, **kwargs): if (kwargs.get('tokenize') is list): self.use_revtok = False else: self.use_revtok = True if (kwargs.get('tokenize') is None): kwargs['tokenize'] = 'revtok' if ('unk_token' not in kwargs):...
def launch(main_func, num_gpus_per_machine, num_machines=1, machine_rank=0, dist_url=None, args=(), timeout=DEFAULT_TIMEOUT): world_size = (num_machines * num_gpus_per_machine) if (world_size > 1): if (dist_url == 'auto'): assert (num_machines == 1), 'dist_url=auto not supported in multi-mac...
_grad() def convert_s3prl_checkpoint(base_model_name, config_path, checkpoint_path, model_dump_path): checkpoint = torch.load(checkpoint_path, map_location='cpu') downstream_dict = checkpoint['Downstream'] hf_config = WavLMConfig.from_pretrained(config_path) hf_feature_extractor = Wav2Vec2FeatureExtract...
def selected_cols(conn, select): if (conn.driver == 'paiio'): name_and_type = conn.query().column_info() else: name_and_type = selected_columns_and_types(conn, select) return [item[0] for item in name_and_type]
class FusedFunc(Func): def __init__(self, name, signatures): super(FusedFunc, self).__init__(name, signatures) self.doc = ('See the documentation for scipy.special.' + self.name) (self.incodes, self.outcodes) = self._get_codes() self.fused_types = set() (self.intypes, infused...
def parse_args(): parser = argparse.ArgumentParser(description='Model Ensemble with logits result') parser.add_argument('--config', type=str, nargs='+', help='ensemble config files path') parser.add_argument('--checkpoint', type=str, nargs='+', help='ensemble checkpoint files path') parser.add_argument(...
_keyword(color='rgbcolor') (width=0.5, rgbcolor=(0, 0, 1), legend_label=None, aspect_ratio='automatic') def bar_chart(datalist, **options): dl = len(datalist) if (dl == 3): datalist = (datalist + [0]) g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) ind = list(range...
def add_speech_generation_args(parser): group = parser.add_argument_group('Speech Generation') add_common_eval_args(group) group.add_argument('--eos_prob_threshold', default=0.5, type=float, help='terminate when eos probability exceeds this') return group
.parametrize('knn_methods', knn_methods) def test_mcb_proba(knn_methods): (pool_classifiers, X_dsel, y_dsel, X_test, y_test) = setup_classifiers() rng = np.random.RandomState(123456) mcb = MCB(pool_classifiers, random_state=rng, knn_classifier=knn_methods) mcb.fit(X_dsel, y_dsel) probas = mcb.predic...
def get_barren_layer_plot(var, num_layers, plt): if isinstance(num_layers, int): num_layers_ = np.arange(1, (num_layers + 1), 5) else: num_layers_ = num_layers handles = {} for i in var.keys(): handles[i] = plt.semilogy(num_layers_, var[i]) return handles
def abstract2ids(abstract_words, vocab, article_oovs): ids = [] unk_id = vocab.word2id(UNKNOWN_TOKEN) for w in abstract_words: i = vocab.word2id(w) if (i == unk_id): if (w in article_oovs): vocab_idx = (vocab.size() + article_oovs.index(w)) ids.app...
def adaptive_max_pool1d(input, output_size, return_indices=False): ret = torch.adaptive_max_pool1d(input, output_size) return (ret if return_indices else ret[0])
def parse(): parser = argparse.ArgumentParser(description='EfficientFormer Toolbox') parser.add_argument('--model', metavar='ARCH', default='efficientformerv2_l') parser.add_argument('--ckpt', default='weights/eformer_l_450.pth', type=str, metavar='PATH', help='path to checkpoint') parser.add_argument('...
class MpiAdamOptimizer(tf.train.AdamOptimizer): def __init__(self, **kwargs): self.comm = MPI.COMM_WORLD tf.train.AdamOptimizer.__init__(self, **kwargs) def compute_gradients(self, loss, var_list, **kwargs): grads_and_vars = super().compute_gradients(loss, var_list, **kwargs) gra...
class Function_sin(GinacFunction): def __init__(self): GinacFunction.__init__(self, 'sin', latex_name='\\sin', conversions=dict(maxima='sin', mathematica='Sin', giac='sin', fricas='sin', sympy='sin'))
class AverageMeter(object): def __init__(self, name, fmt=':f', summary_type=Summary.AVERAGE): self.name = name self.fmt = fmt self.summary_type = summary_type self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 d...
def test_getSubscription5(): url = (brokerIp + '/ngsi10/updateContext') headers = {'Content-Type': 'application/json'} r = requests.post(url, data=json.dumps(data_ngsi10.subdata8), headers=headers) resp_content = r.content resInJson = resp_content.decode('utf8').replace("'", '"') resp = json.loa...
def spol(g1, g2): (a1, a2) = (g1.lc(), g2.lc()) a = a1.lcm(a2) (b1, b2) = ((a // a1), (a // a2)) (t1, t2) = (g1.lm(), g2.lm()) t = t1.parent().monomial_lcm(t1, t2) (s1, s2) = ((t // t1), (t // t2)) return (((b1 * s1) * g1) - ((b2 * s2) * g2))
def _rendezvous_error(msg): return ValueError(('Error initializing torch.distributed using ' + msg))
class L1RegressionModel(MLPModel, ModelIOKeysMixin): def __init__(self, input_dim, output_dim, hidden_dims, device, batch_norm=None, dropout=None, activation='relu', sigma=1.0, lam=0.1): super().__init__(input_dim, output_dim, hidden_dims, batch_norm=batch_norm, dropout=dropout, activation=activation) ...
class PermuteCallMethod(common.BaseSubstitution): def __init__(self): nodes = NodeOperationMatcher(permute) super().__init__(matcher_instance=nodes) def substitute(self, graph: Graph, node: BaseNode) -> Graph: if (node.op_call_args and (not isinstance(node.op_call_args[0], tuple))): ...
def compute_value_loss(agent, batch, network_params): batch['masks'] = (1.0 - batch['rewards']) batch['rewards'] = (batch['rewards'] - 1.0) (next_v1, next_v2) = agent.network(batch['next_observations'], batch['goals'], method='target_value') next_v = jnp.minimum(next_v1, next_v2) q = (batch['rewards...
def collect_trainable_weights(layer): trainable = getattr(layer, 'trainable', True) if (not trainable): return [] weights = [] if (layer.__class__.__name__ == 'Sequential'): for sublayer in layer.flattened_layers: weights += collect_trainable_weights(sublayer) elif (layer...
def generate_sequences(l): if (len(l) == 0): return [] subsequent = generate_sequences(l[1:]) answer = list() if (len(subsequent) > 0): answer += subsequent for elem in l[0]: answer.append([elem]) for elem2 in subsequent: answer.append(([elem] + elem2)) ...
class PeriodicPointIterator(): def __init__(self, m, cycle): self._m = m self._image = m.image self._cycle = tuple(cycle) self._cache = [lazy_list(self.get_iterator(i)) for i in range(len(cycle))] def __reduce__(self): return (PeriodicPointIterator, (self._m, self._cycle)...
def _get_entity_placeholders(dataset, language): return {e: _get_entity_name_placeholder(e, language) for e in dataset[ENTITIES]}
class Agent(AbstractPlayer): def __init__(self): AbstractPlayer.__init__(self) self.lastSsoType = LEARNING_SSO_TYPE.JSON '\n * Public method to be called at the start of every level of a game.\n * Perform any level-entry initialization here.\n * sso Phase Observation of the current gam...
def _compress_array(lat_lng_dtime_other, spatial_radius): if (len(lat_lng_dtime_other) < 2): return lat_lng_dtime_other measure_distance = gislib.getDistance compressed_traj = [] (lat_0, lon_0) = lat_lng_dtime_other[0][:2] (sum_lat, sum_lon) = ([lat_0], [lon_0]) t_0 = lat_lng_dtime_other...
def get_current_tensors(): for obj in gc.get_objects(): try: if (torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_tensor(obj.data))): print(type(obj), obj.size()) except Exception: pass
class TransparentDataParallel(nn.DataParallel): def set_best(self, *args, **kwargs): return self.module.set_best(*args, **kwargs) def recover_best(self, *args, **kwargs): return self.module.recover_best(*args, **kwargs) def save(self, *args, **kwargs): return self.module.save(*args, ...
class base_peripheral(nn.Module): def __init__(self): super(base_peripheral, self).__init__()
class Phrase(object): def __init__(self, phrase_idx, start_idx, end_idx, size, label, text, parent_idx, align_idx): super(Phrase, self).__init__() self.start_idx = start_idx self.end_idx = end_idx self.label = label self.size = size self.text = text self.paren...
def main(args): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('destination_dir', help='destination directory') parser.add_argument('header_files', nargs='+', help='One or more header files to parse') pargs = parser.parse_args(args) ...
class NCSymDualBases(Category_realization_of_parent): def super_categories(self): return [NCSymOrNCSymDualBases(self.base())] def _repr_(self): return 'Category of bases of dual symmetric functions in non-commuting variables over the {}'.format(self.base().base_ring())
def format_invalid_values_string(invalid_values, num_values): if isinstance(invalid_values, pd.DataFrame): if (len(invalid_values) > num_values): return f'''{invalid_values.head(num_values)} +{(len(invalid_values) - num_values)} more''' if isinstance(invalid_values, set): invalid_val...
class EnumAction(Action): def __init__(self, **kwargs): _enum = kwargs.pop('type', None) if (_enum is None): raise ValueError('type must be assigned an Enum when using EnumAction') if (not issubclass(_enum, enum.Enum)): raise TypeError('type must be an Enum when using...
class JaxBaseModuleClass(TunableMixin, flax.linen.Module): def configure(self) -> None: self.training = None self.train_state = None self.seed = (settings.seed if (settings.seed is not None) else 0) self.seed_rng = device_selecting_PRNGKey()(self.seed) self._set_rngs() de...
class LabelSpacePartitioningClassifier(BinaryRelevance): def __init__(self, classifier=None, clusterer=None, require_dense=None): super(LabelSpacePartitioningClassifier, self).__init__(classifier, require_dense) self.clusterer = clusterer self.copyable_attrs = ['clusterer', 'classifier', 're...
def get_input_fn(vocab, data_config, data_files, batch_size, num_epochs, shuffle, shuffle_buffer_multiplier=1, embedding_files=None): vocab_lookup_ops = vocab.create_vocab_lookup_ops(embedding_files) return dataset.get_data_iterator(data_files, data_config, vocab_lookup_ops, batch_size, num_epochs, shuffle, shu...
def apply_augmentations(batch, conf): if ((conf.gauss_augment is not None) or conf.z_rotate): batch = batch.copy() if (conf.gauss_augment is not None): mu = conf.gauss_augment['mu'] sigma = conf.gauss_augment['sigma'] batch += np.random.normal(mu, sigma, batch.shape) if conf....
class RandomNetworkDensity(mrl.Module): def __init__(self, item, optimize_every=1, batch_size=256, layers=(256, 256)): super().__init__('{}_rnd'.format(item), required_agent_modules=['replay_buffer'], locals=locals()) self.step = 0 self.item = item self.layers = layers self.o...
class GroupOps(object): def identity(): _res = ([0.0] * 5) _res[0] = 0 _res[1] = 0 _res[2] = 0 _res[3] = 0 _res[4] = 0 return sym.ATANCameraCal.from_storage(_res) def inverse(a): _a = a.data _res = ([0.0] * 5) _res[0] = (- _a[0]) ...
def secs_to_str(secs): s = str(datetime.timedelta(seconds=int(round(secs)))) s = re.sub('^0:', '', s) s = re.sub('^0', '', s) s = re.sub('^0:', '', s) s = re.sub('^0', '', s) return s
class Plus(): calculations = 0 def plus_three(self, number): self.calculations += 1 return (number + 3) def plus_four(self, number): self.calculations += 1 return (number + 4)
class ROIAlignRotated(nn.Module): def __init__(self, output_size, spatial_scale, sampling_ratio): super(ROIAlignRotated, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale self.sampling_ratio = sampling_ratio def forward(self, input, rois): ...
class GNNClassifier(BaseGNN): def __init__(self, dims: Optional[Union[(int, list)]]=None, layer_types: Union[(str, list)]='Conv', activations: Union[(str, list)]='ReLu', use_bias: Union[(bool, list)]=True, normalizations: Union[(str, list)]='both', self_embeddings: Union[(bool, list)]=True, sample_sizes: Union[(int...
def conv_bn(inp, oup, stride, padding=1): return nn.Sequential(nn.Conv2d(inp, oup, 3, stride, padding, bias=False), nn.BatchNorm2d(oup), nn.ReLU6(inplace=True))
class DukeMTMCreID(BaseImageDataset): dataset_dir = 'DukeMTMC-reID' def __init__(self, root='data', verbose=True, **kwargs): super(DukeMTMCreID, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir) self.dataset_url = ' self.train_dir = osp.join(self.dataset_dir, '...
class PlusSAINTModule(pl.LightningModule): def __init__(self): super(PlusSAINTModule, self).__init__() self.loss = nn.BCEWithLogitsLoss() self.encoder_layer = StackedNMultiHeadAttention(n_stacks=Config.NUM_DECODER, n_dims=Config.EMBED_DIMS, n_heads=Config.DEC_HEADS, seq_len=Config.MAX_SEQ, n...
class Brightness(object): def __init__(self, var): self.var = var def __call__(self, img): gs = img.new().resize_as_(img).zero_() alpha = random.uniform(0, self.var) return img.lerp(gs, alpha)
class MultiCore(Node): def __init__(self, core_id, core_nums, mlir_cmds: List[BaseTpuCmd], indent=0): self.core_id = core_id self.core_nums = core_nums self.mlir_cmds = mlir_cmds self.indent = indent self.core_split_cmds = [] self.core_split_rets = [] self.msg...
def test_score_one_tree_tuples(): treebank = build_one_tree_treebank(True) with EvaluateParser() as ep: response = ep.process(treebank) assert (response.f1 == pytest.approx(1.0))
def build_transforms(cfg, is_train=True): if is_train: min_size = cfg.INPUT.MIN_SIZE_TRAIN max_size = cfg.INPUT.MAX_SIZE_TRAIN flip_horizontal_prob = cfg.INPUT.HORIZONTAL_FLIP_PROB_TRAIN flip_vertical_prob = cfg.INPUT.VERTICAL_FLIP_PROB_TRAIN brightness = cfg.INPUT.BRIGHTNESS...
def sel_or_init(collection: Sequence[IndividualLike], base_ind: IndividualLike, sel_fn: Callable, sel_pb: float, init_fn: Callable, init_pb: float=0.0, return_flag: bool=True): def ret(res, f): return ((res, f) if return_flag else res) if (len(collection) == 0): return ret(init_fn(base_ind), Fal...
def plot_loss(inner_loop_loss, name='Loss Curve'): plt.plot(inner_loop_loss, label=name) plt.legend()
class SequenceCrossEntropyLoss(tf.keras.losses.Loss): eps = 1e-08 def call(self, y_true, y_pred): return (- tf.reduce_mean(((y_true * tf.math.log((y_pred + self.eps))) + ((1 - y_true) * tf.math.log(((1 - y_pred) + self.eps))))))
class ToTHWC(object): def __init__(self): pass def __call__(self, tensor): return tensor.permute(1, 2, 3, 0) def __repr__(self): return self.__class__.__name__
def resnet_v2(inputs, blocks, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, reuse=None, scope=None): with tf.variable_scope(scope, 'resnet_v2', [inputs], reuse=reuse) as sc: end_points_collection = (sc.name + '_end_points') with slim.arg_scope([sl...
def read_file(filename: str) -> Dict[(str, Any)]: with (CURRENT_DIR / filename).open() as fd: return json.load(fd)
def load_checkpoints(path, gpu): if (gpu is None): ckpt = torch.load(path) else: loc = 'cuda:{}'.format(gpu) ckpt = torch.load(path, map_location=loc) return ckpt
class BertTokenizerFast(metaclass=DummyObject): _backends = ['tokenizers'] def __init__(self, *args, **kwargs): requires_backends(self, ['tokenizers'])
(Output('link-table', 'children'), Input('select-domain', 'value'), Input('add-link-btn', 'n_clicks'), Input('delete-link-btn', 'n_clicks'), [State('add-node-A', 'value'), State('add-node-B', 'value'), State('link_radio_button', 'value'), State('link-table', 'children')]) def add_link(domain_file, add_click, delete_cli...
def _wrap_header_guess_version(header): try: return _wrap_header(header, (1, 0)) except ValueError: pass try: ret = _wrap_header(header, (2, 0)) except UnicodeEncodeError: pass else: warnings.warn('Stored array in format 2.0. It can only beread by NumPy >= 1.9...
_function def ncube_isometry_group_cosets(n, orientation_preserving=True): from sage.misc.misc_c import prod from sage.matrix.constructor import diagonal_matrix G = ncube_isometry_group(n, orientation_preserving) it = itertools.product((1, (- 1)), repeat=n) if orientation_preserving: H = [di...
def register_Ns3LteRrcSapRrcConnectionSetupCompleted_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::LteRrcSap::RrcConnectionSetupCompleted const &', 'arg0')]) cls.add_instance_attribute('rrcTransactionIdentifier', 'uint8_t', is_const=False) return
def ufunc_add_outer_simple2(A: dace.int32[(2, 2, 2, 2, 2)], B: dace.int32[(2, 2, 2, 2, 2)]): return np.add.outer(A, B)
class CartanType_decorator(UniqueRepresentation, SageObject, CartanType_abstract): def __init__(self, ct): self._type = ct def is_irreducible(self): return self._type.is_irreducible() def is_finite(self): return self._type.is_finite() def is_crystallographic(self): return...
def filter_desc_df_cv(desc): df = desc return df[[(i, j) for i in ['acc', 'total_time'] for j in ['mean', 'max', 'min', 'std']]]
def _apply_bpe(model_path: str, in_path: str, out_path: str): Args = namedtuple('Args', ['sentencepiece_vocab']) args = Args(sentencepiece_vocab=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...
def scalar_search_wolfe1(phi, derphi, phi0=None, old_phi0=None, derphi0=None, c1=0.0001, c2=0.9, amax=50, amin=1e-08, xtol=1e-14): if (phi0 is None): phi0 = phi(0.0) if (derphi0 is None): derphi0 = derphi(0.0) if ((old_phi0 is not None) and (derphi0 != 0)): alpha1 = min(1.0, (((1.01 ...
class TestIndexHashOps(serial.SerializedTestCase): (indices=st.sampled_from([np.int32, np.int64]).flatmap((lambda dtype: hu.tensor(min_dim=1, max_dim=1, dtype=dtype))), seed=st.integers(min_value=0, max_value=10), modulo=st.integers(min_value=100000, max_value=200000), **hu.gcs_cpu_only) (deadline=10000) de...
_test(assert_ii_1=False) def test_4_interface_to_2_banks_ddr_non_decoupled_interfaces(): return four_interface_to_2_banks(mem_type='DDR', decouple_interfaces=False)
def test_clean_remove_bracketed(df_text: pd.DataFrame) -> None: pipeline_all = [{'operator': 'remove_bracketed', 'parameters': {'brackets': {'angle', 'curly', 'round', 'square'}}}] df_clean_all = clean_text(df_text, 'text', pipeline=pipeline_all) df_check_all = df_text.copy() df_check_all['text'] = ["'Z...
def _is_day_first(date: Union[(str, dd.Series)]) -> Optional[bool]: if isinstance(date, dd.Series): judge_col = date.apply(_check_is_day_first, meta=object) return (judge_col.unique() == True).any().compute() return _check_is_day_first(date)
def main(dataset, cls_path, out_path, index=0): global DEVICE DEVICE = torch.device(('cuda' if torch.cuda.is_available() else 'cpu')) utils.set_seed(seed=(2019 + index)) num_epochs = 200 save_every = 100 viz_every = 10 assert (num_epochs >= save_every) if (dataset == 'mnist'): de...
def test_encode_timedelta(): def ensure_roundtrip(td_str, expected_seconds): td = parse_timedelta(td_str) assert (td.total_seconds() == expected_seconds) assert (parse_timedelta(encode_timedelta(td)) == td), f'Failed to roundtrip {td_str}: {encode_timedelta(td)}' ensure_roundtrip('1d', 8...
class ASTHelperMixin(): def generic_visit_filtered(self, node: ast.AST, filter: Optional[Set[str]]=None): filter = (filter or set()) for (field, old_value) in ast.iter_fields(node): if (field in filter): continue if isinstance(old_value, list): ...
class SetPartitionsBk_k(SetPartitionsAk_k): def _repr_(self): return (SetPartitionsAk_k._repr_(self) + ' with block size 2') def __contains__(self, x): if (not SetPartitionsAk_k.__contains__(self, x)): return False for part in x: if (len(part) != 2): ...
def test_get_request_with_body(testdir, cli, base_url, hypothesis_max_examples, schema_with_get_payload, snapshot_cli): schema_file = testdir.makefile('.yaml', schema=yaml.dump(schema_with_get_payload)) assert (cli.run(str(schema_file), f'--base-url={base_url}', f'--hypothesis-max-examples={(hypothesis_max_exam...
class KoalaScenario(Scenario): name = 'koala' description = 'Koala eval dataset' tags = ['instructions'] def get_instances(self, output_path: str) -> List[Instance]: source_url = ' data_path: str = os.path.join(output_path, 'Koala_prompts.jsonl') ensure_file_downloaded(source_url...