code stringlengths 101 5.91M |
|---|
class DMMN(nn.Module):
def __init__(self, phase, base, head, extra):
super(DMMN, self).__init__()
self.phase = phase
self.num_classes = config['num_classes']
self.num_params = config['num_motion_model_param']
self.priorbox = PriorBox(config)
with torch.no_grad():
... |
def test_sort_strings():
content = ak.operations.from_iter(['one', 'two', 'three', 'four', 'five'], highlevel=False)
assert (to_list(ak.operations.sort(content, axis=0, ascending=True, stable=False)) == ['five', 'four', 'one', 'three', 'two'])
assert (to_list(ak.operations.sort(content, axis=0, ascending=Fa... |
_video_fx
def volumex(clip, factor):
return clip.fl((lambda gf, t: (factor * gf(t))), keep_duration=True) |
class LayoutLMTokenizer(BertTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES |
class Box(Space):
def __init__(self, low, high, shape=None):
if (shape is None):
assert (low.shape == high.shape)
self.low = low
self.high = high
else:
assert (np.isscalar(low) and np.isscalar(high))
self.low = (low + np.zeros(shape))
... |
def test_NumpyArray_shape():
v2a = ak.contents.numpyarray.NumpyArray(np.arange(((2 * 3) * 5), dtype=np.int64).reshape(2, 3, 5))
def f(out, obj):
out[0] = len(obj)
out[1] = len(obj[0])
out[2] = len(obj[0][0])
out[3] = obj[0][0][0]
out[4] = obj[0][0][1]
out[5] = obj... |
def contrast_epoch(pretrain_loader, model, optimizer, pretrain_meter, cur_epoch, global_step, num_steps, num_optimizer_steps, num_warmup_steps, cfg):
model.train()
pretrain_meter.iter_tic()
for (cur_step, (visual_clip, audio_clip)) in enumerate(pretrain_loader):
global_step += 1
for i in ran... |
_model_architecture('transformer_lm', 'transformer_lm_gpt2_big')
def transformer_lm_gpt2_big(args):
args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1600)
args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 6400)
args.decoder_layers = getattr(args, 'decoder_layers', 48)
args.d... |
def main(args):
audio_dataset = load_dataset(**DATASET_ARGS)
def gen():
i = 0
idxes = list(range(len(audio_dataset)))
random.shuffle(idxes)
for k in idxes:
try:
(yield _write_convo(k, audio_dataset[k]))
except ValueError:
pa... |
class SysbenchMemoryBenchmark(node.AppConfig):
def __init__(self, disagg_addr: int, disagg_size: int, disaggregated: bool, time_limit: int, num_threads=1):
self.disagg_addr = disagg_addr
self.disagg_size = disagg_size
self.disaggregated = disaggregated
self.time_limit = time_limit
... |
class MFVISemanticDependency(nn.Module):
def __init__(self, max_iter=3):
super().__init__()
self.max_iter = max_iter
def __repr__(self):
return f'{self.__class__.__name__}(max_iter={self.max_iter})'
_grad()
def forward(self, scores, mask, target=None):
logQ = self.mean_fi... |
def spacy_deps(doc):
tups = []
for (tki, token) in enumerate(doc):
dep = ((token.text + '_') + str(tki))
head = ((token.head.text + '_') + str(token.head.i))
arc = token.dep_
tups.append((dep, head, arc))
return tups |
(allow_output_mutation=True)
def init_bert_tokenizer():
tokenizer = BlipBase.init_tokenizer()
return tokenizer |
_utils.test()
def test_name_error():
with pytest.raises(ti.TaichiNameError, match='Name "a" is not defined'):
def foo():
(a + 1)
foo() |
()
def list():
_echo_run_names('Algorithms', _get_runs_dict(benchmark_algos))
_echo_run_names('Policies', _get_runs_dict(benchmark_policies))
_echo_run_names('Baselines', _get_runs_dict(benchmark_baselines))
_echo_run_names('Q Functions', _get_runs_dict(benchmark_q_functions))
_echo_run_names('Autom... |
def is_optional(ann):
if (ann is Optional):
raise RuntimeError('Attempted to use Optional without a contained type. Please add a contained type, e.g. Optional[int]')
def safe_is_subclass(the_type, super_type):
if (not inspect.isclass(the_type)):
return False
return issubclass... |
_selection.register('chunk')
def chunk_selection(doc: Doc) -> Iterable[Candidate]:
surface_forms = []
spans = list(doc.ents)
ent_words: Set[str] = set()
sentence_indices = []
for span in spans:
ent_words.update((token.i for token in span))
for np in doc.noun_chunks:
while ((len(n... |
_grad()
def final_test(data_loader, model, device, file, save_feature=False):
criterion = torch.nn.CrossEntropyLoss()
metric_logger = utils.MetricLogger(delimiter=' ')
header = 'Test:'
model.eval()
final_result = []
saved_features = {}
for batch in metric_logger.log_every(data_loader, 10, h... |
class AffinePermutationTypeG(AffinePermutation):
def check(self):
if (not self):
return
if (not (len(self) == 6)):
raise ValueError('length of list must be 6')
s = sum((((i // 6) - ((i % 6) == 0)) for i in self if (i > 6)))
if (s % 2):
raise ValueE... |
def collect_all_mutex_groups(groups, atoms):
all_groups = []
uncovered_facts = atoms.copy()
for group in groups:
uncovered_facts.difference_update(group)
all_groups.append(group)
all_groups += [[fact] for fact in uncovered_facts]
return all_groups |
def create_temp_tfrecords(sources, targets):
output_file = tempfile.NamedTemporaryFile()
writer = tf.python_io.TFRecordWriter(output_file.name)
for (source, target) in zip(sources, targets):
ex = tf.train.Example()
ex.features.feature['source'].bytes_list.value.extend([source.encode('utf-8')... |
class LlamaInt8(CausalInt8Model):
config_name: str = 'llama_int8'
def __init__(self, weights_path: Optional[str]=None):
super().__init__(LLamaInt8Engine.config_name, weights_path) |
class Text(object):
def __init__(self, ax):
self._ax = ax
self._text = None
def artists(self):
return [self._text]
def draw(self, x, y, text, **kwargs):
if (self._text is None):
self._text = self._ax.text(x, y, text, **kwargs)
else:
self._text.... |
def counter_to_file(cnt, filepath):
with open(filepath, 'w') as f:
output = '\n'.join(['{};{}'.format(c, c_count) for (c, c_count) in cnt.most_common()])
f.write(output) |
class SPNet(nn.Module):
def __init__(self, channel=32, ind=50):
super(SPNet, self).__init__()
self.relu = nn.ReLU(inplace=True)
self.upsample_2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
self.upsample_4 = nn.Upsample(scale_factor=4, mode='bilinear', align_corn... |
def md_tree_to_graph(root):
from itertools import product, combinations
from sage.graphs.graph import Graph
def tree_to_vertices_and_edges(root):
if (root.node_type == NodeType.NORMAL):
return (root.children, [])
children_ve = [tree_to_vertices_and_edges(child) for child in root.... |
def get_zenodo_json(doi):
request = requests.get(doi, headers={'accept': 'application/citeproc+json'})
base_url = request.json()['URL']
record = base_url.split('/')[(- 1)]
json_url = (' + record)
request = requests.get(json_url, headers={'accept': 'application/json'})
record_json = request.json(... |
def _fit_saga(X, y, eta, alpha, loss, penalty, max_iter, rng):
if sparse.issparse(X):
X = X.toarray()
(n_samples, n_features) = X.shape
n_vectors = y.shape[1]
g = np.empty((n_samples, n_features))
coef_ = np.zeros((n_vectors, n_features))
for i in range(n_samples):
p = coef_.dot(... |
_method
class Tableau(ClonableList, metaclass=InheritComparisonClasscallMetaclass):
def __classcall_private__(cls, t):
if isinstance(t, cls):
return t
try:
t = [tuple(_) for _ in t]
except TypeError:
raise ValueError('a tableau must be a list of iterables'... |
_module()
class FPNHead(BaseDecodeHead):
def __init__(self, feature_strides, **kwargs):
super(FPNHead, self).__init__(input_transform='multiple_select', **kwargs)
assert (len(feature_strides) == len(self.in_channels))
assert (min(feature_strides) == feature_strides[0])
self.feature_s... |
class ExecutionFlowBuilder():
def __init__(self, trace: ExecutionTrace, known_code_objects: dict[(int, CodeObjectMetaData)]):
self.trace = trace
self.known_code_objects = known_code_objects
def _finish_basic_block(self, instr_index: int, basic_block: list[Instr], import_instr: (UniqueInstruction... |
def test_set_get_limit(stopping_condition):
stopping_condition.set_limit(42)
assert (stopping_condition.limit() == 42) |
def finalize_autosummaries() -> None:
global _finalized
tfutil.assert_tf_initialized()
if _finalized:
return None
_finalized = True
tfutil.init_uninitialized_vars([var for vars_list in _vars.values() for var in vars_list])
with tf.device(None), tf.control_dependencies(None):
for ... |
def _update_model_cond(old_model, new_model):
for idx in range(0, len(new_model.WN)):
wavenet = new_model.WN[idx]
n_channels = wavenet.n_channels
n_layers = wavenet.n_layers
n_mel_channels = wavenet.cond_layers[0].weight.shape[1]
cond_layer = torch.nn.Conv1d(n_mel_channels, (... |
class DSPySuggestionError(AssertionError):
def __init__(self, id: str, msg: str, target_module: Any=None, state: Any=None) -> None:
super().__init__(msg)
self.id = id
self.msg = msg
self.target_module = target_module
self.state = state |
_logical_op_with_cast_to_and_from('Bool')
def __and_(g, input, other):
return g.op('And', input, other) |
.parametrize('GradientBoosting, X, y', [(HistGradientBoostingClassifier, X_classification, y_classification), (HistGradientBoostingRegressor, X_regression, y_regression)])
.parametrize('rng_type', ('none', 'int', 'instance'))
def test_random_seeds_warm_start(GradientBoosting, X, y, rng_type):
def _get_rng(rng_type)... |
class Evaluator(object):
def __init__(self):
self.reset()
def reset(self):
self.lm_vis_count_all = np.array(([0.0] * 8))
self.lm_dist_all = np.array(([0.0] * 8))
def add(self, output, sample):
landmark_vis_count = sample['landmark_vis'].cpu().numpy().sum(axis=0)
landm... |
.parametrize('lil_container', LIL_CONTAINERS)
def test_svc_with_custom_kernel(lil_container):
def kfunc(x, y):
return safe_sparse_dot(x, y.T)
X_sp = lil_container(X)
clf_lin = svm.SVC(kernel='linear').fit(X_sp, Y)
clf_mylin = svm.SVC(kernel=kfunc).fit(X_sp, Y)
assert_array_equal(clf_lin.pred... |
def OneHotEncoded(y_train):
y_t = np.zeros((len(y_train), Num_Class), dtype=int)
for (i, x) in enumerate(y_train):
y_t[i][(int(x) - 1)] = 1
return y_t |
def mp_join(*args):
dir_path = os.path.join(*args)
if (not os.path.exists(dir_path)):
os.makedirs(dir_path)
return dir_path |
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
config = Configuration('linalg', parent_package, top_path)
config.add_data_dir('tests')
src_dir = 'lapack_lite'
lapack_lite_src = [os.path.joi... |
class CscDataset(object):
def __init__(self, file_path):
self.data = json.load(open(file_path, 'r', encoding='utf-8'))
def load(self):
data_list = []
for item in self.data:
data_list.append(((item['original_text'] + '\t') + item['correct_text']))
return {'text': data_... |
class RandAugment(object):
def __init__(self, n, m):
self.n = n
self.m = m
self.count = 0
self.augment_pool = augment_pool()
def __call__(self, img):
ops = random.sample(self.augment_pool, k=self.n)
for (op, minval, maxval) in ops:
val = np.random.unif... |
def setup_seed(SEED):
setup_plain_seed(SEED)
torch.manual_seed(SEED)
torch.random.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False |
class Adadelta(Optimizer):
def __init__(self, lr=1.0, rho=0.95, epsilon=1e-08, decay=0.0, **kwargs):
super(Adadelta, self).__init__(**kwargs)
with K.name_scope(self.__class__.__name__):
self.lr = K.variable(lr, name='lr')
self.decay = K.variable(decay, name='decay')
... |
def test_as_numer_denom():
(x, y) = Rational(17, 26).as_numer_denom()
assert (x == Integer(17))
assert (y == Integer(26))
(x, y) = Integer((- 5)).as_numer_denom()
assert (x == Integer((- 5)))
assert (y == Integer(1)) |
def estimate_visib_mask_est(d_test, d_est, visib_gt, delta):
visib_est = estimate_visib_mask(d_test, d_est, delta)
visib_est = np.logical_or(visib_est, np.logical_and(visib_gt, (d_est > 0)))
return visib_est |
class RegNetPreTrainedModel(PreTrainedModel):
config_class = RegNetConfig
base_model_prefix = 'regnet'
main_input_name = 'pixel_values'
supports_gradient_checkpointing = True
def _init_weights(self, module):
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight,... |
def _circuit_parameter_shift(element: Union[(OpTreeCircuit, QuantumCircuit, OpTreeValue)], parameter: ParameterExpression) -> Union[(None, OpTreeSum, OpTreeValue)]:
if isinstance(element, OpTreeValue):
return OpTreeValue(0.0)
if isinstance(element, OpTreeCircuit):
circuit = element.circuit
... |
class TestFeatureAlign(unittest.TestCase):
def test_caffe_pytorch_feat_align(self):
caffe_feat_path = '/export/home/lxy/cvpalgo-fast-reid/tools/deploy/caffe_R50_output'
pytorch_feat_path = '/export/home/lxy/cvpalgo-fast-reid/demo/logs/R50_256x128_pytorch_feat_output'
feat_filenames = os.list... |
class ExtEnum():
def __init__(self, enum: Enum, *args, **kargs) -> None:
assert isinstance(enum, Enum)
self.enum = enum
self.args = args
self.__dict__.update(kargs)
self._member_ = kargs.keys()
def name(self):
return self.enum.name
def value(self):
ret... |
class Batch():
def __init__(self):
self.max_num_frames_per_slice = NumbersDict(0)
self.num_slices = 0
self.seqs = []
def __repr__(self):
return ('<Batch start_seq:%r, len(seqs):%i>' % (self.start_seq, len(self.seqs)))
def try_sequence_as_slice(self, length):
return [N... |
def create_log_df(search_string, log_file_path):
idx = [14, 16, 17, 18, 19, 20, 21, 22]
cols = ['fitness', 'up_time', 'x_dist', 'abs_y_dev', 'avg_footstep', 'var_alpha', 'var_beta', 'var_gamma']
file_list = list()
with open(log_file_path) as f:
for line in f:
if (search_string in lin... |
def test_two_compatible_by_ones_input_shapes():
data = [[[(1,), (3,)], (3,)], [[(1, 3), (3, 3)], (3, 3)], [[(3, 1), (3, 3)], (3, 3)], [[(1, 3), (3, 1)], (3, 3)], [[(1, 1), (3, 3)], (3, 3)], [[(1, 1), (1, 3)], (1, 3)], [[(1, 1), (3, 1)], (3, 1)], [[(1, 0), (0, 0)], (0, 0)], [[(0, 1), (0, 0)], (0, 0)], [[(1, 0), (0, ... |
class RegistrationCounter():
def __init__(self):
self.nb_calls = 0
def __call__(self, to_register_func):
self.nb_calls += 1
assert (to_register_func.func is _delete_folder) |
def read_jsonl(path: str):
with open(path) as fh:
return [json.loads(line) for line in fh.readlines() if line] |
class MSRVTTQADataset(BaseDataset):
def __init__(self, *args, split='', **kwargs):
assert (split in ['train', 'val', 'test'])
self.split = split
self.metadata = None
self.ans_lab_dict = None
if (split == 'train'):
names = ['msrvtt_qa_train']
elif (split ==... |
class FEVERSentenceFormatter(FeverFormatter):
def format_line(self, line):
annotation = line['label']
if (annotation is None):
annotation = line['verifiable']
pages = []
if ('evidence' in line):
pages = [[(ev[2], ev[3]) for ev in annotation if (ev[2] is not No... |
class ChainedScheduler(_LRScheduler):
def __init__(self, schedulers):
for scheduler_idx in range(1, len(schedulers)):
if (schedulers[scheduler_idx].optimizer != schedulers[0].optimizer):
raise ValueError('ChainedScheduler expects all schedulers to belong to the same optimizer, bu... |
def match_classes(views, sample_level):
(all_features, keys, dataset_size, subset_size, num_matched_classes, nclasses) = match_classes_with_shuffle(views, 0, None, False, False, return_class_dict=True, add_vid=True, align=sample_level, if_shuffle_each_view=False, if_shuffle_classes=True)
return all_features |
class DistilBertTokenizationTest(BertTokenizationTest):
tokenizer_class = DistilBertTokenizer
def get_tokenizer(self, **kwargs):
return DistilBertTokenizer.from_pretrained(self.tmpdirname, **kwargs)
.slow
def test_sequence_builders(self):
tokenizer = DistilBertTokenizer.from_pretrained('... |
def test_clone_2():
from sklearn.feature_selection import SelectFpr, f_classif
selector = SelectFpr(f_classif, alpha=0.1)
selector.own_attribute = 'test'
new_selector = clone(selector)
assert (not hasattr(new_selector, 'own_attribute')) |
def make_features(batch, side, data_type='text'):
assert (side in ['src', 'tgt'])
if isinstance(batch.__dict__[side], tuple):
data = batch.__dict__[side][0]
else:
data = batch.__dict__[side]
feat_start = (side + '_feat_')
keys = sorted([k for k in batch.__dict__ if (feat_start in k)]... |
class VecEnv(ABC):
num_envs: int
num_obs: int
num_privileged_obs: int
num_actions: int
max_episode_length: int
privileged_obs_buf: torch.Tensor
obs_buf: torch.Tensor
rew_buf: torch.Tensor
reset_buf: torch.Tensor
episode_length_buf: torch.Tensor
extras: dict
device: torch.... |
class PlyLogger(object):
def __init__(self, f):
self.f = f
def debug(self, msg, *args, **kwargs):
self.f.write(((msg % args) + '\n'))
info = debug
def warning(self, msg, *args, **kwargs):
self.f.write((('WARNING: ' + (msg % args)) + '\n'))
def error(self, msg, *args, **kwargs... |
def sysconfig_get_python_inc(plat_specific=0, prefix=None):
if (prefix is None):
prefix = sys.real_prefix
return old_get_python_inc(plat_specific, prefix) |
def find_max_matching(node_weights: Dict[(SimpleNode, float)], edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)]) -> Tuple[(Dict[(int, int)], float)]:
edges = list(edge_weights.keys())
edge_ratings = {e: edge_rating(e[0], e[1], edge_weights, node_weights) for e in edges}
random.shuffle(edges)
... |
def _evaluate(env, act, num_eval_ep=500, max_steps=100, verbose=False):
return evaluate(env, act, num_eval_ep, max_steps, verbose)[3] |
def train(rank, num_epochs, world_size):
worker_utils.init_process(rank, world_size)
torch.manual_seed(0)
model = create_model(smp.Unet, 'mobilenet_v2')
torch.cuda.set_device(rank)
model.cuda(rank)
model = DistributedDataParallel(model, device_ids=[rank])
optimizer = torch.optim.Adam(model.p... |
def test_numpyarray():
assert (ak_from_buffers(*ak_to_buffers(ak_Array([1, 2, 3, 4, 5]))).to_list() == [1, 2, 3, 4, 5])
assert (pickle.loads(pickle.dumps(ak_Array([1, 2, 3, 4, 5]), (- 1))).to_list() == [1, 2, 3, 4, 5]) |
def parse_csvy_density(csvy_model_config: Configuration, time_explosion: u.Quantity) -> u.Quantity:
if hasattr(csvy_model_config, 'velocity'):
velocity = quantity_linspace(csvy_model_config.velocity.start, csvy_model_config.velocity.stop, (csvy_model_config.velocity.num + 1)).cgs
else:
velocity_... |
def score_run_dot_product(run_pd_id_emb_agg: dict, q_ids_agg_emb: dict):
run_scores_aggregated_emb = {}
for (q_id, retrieved_list) in run_pd_id_emb_agg.items():
run_scores_aggregated_emb.update({q_id: {}})
q_emb = q_ids_agg_emb.get(q_id)
for (candidate_id, candidate_emb) in retrieved_lis... |
def randTAH3(shape: list[int]):
s2 = 0.
s3 = 0.
r3 = (s2 * tf.random.normal(shape, dtype=TF_FLOAT))
r8 = ((s2 * s3) * tf.random.normal(shape, dtype=TF_FLOAT))
m00 = tf.dtypes.complex(tf.cast(0.0, TF_FLOAT), (r8 + r3))
m11 = tf.dtypes.complex(tf.cast(0.0, TF_FLOAT), (r8 - r3))
m22 = tf.dtypes... |
def check_edges(graph, source, target, num, isExtra=None):
edges = [edge for edge in graph.edge if ((edge.source == source) and (edge.target == target))]
assert (len(edges) == num)
if (num == 1):
assert (edges[0].isExtra == isExtra) |
def create_optimizer(args, model: nn.Module, optimizer: Optional[optim.Optimizer]=None):
opt_model = model
if (optimizer is None):
decay_parameters = get_parameter_names(opt_model, ALL_LAYERNORM_LAYERS)
decay_parameters = [name for name in decay_parameters if ('bias' not in name)]
optimi... |
def _limit_lengths(seqs, max_length=None, max_tokens=None):
max_length = (max_length or float('inf'))
lengths = [min(s.nelement(), max_length) for s in seqs]
if (max_tokens is not None):
num_tokens = sum(lengths)
if (num_tokens > max_tokens):
max_length = int(floor((num_tokens / ... |
class RuleList(BayesianRuleList):
def __init__(self, min_rule_len=1, max_rule_len=2, min_support=0.02, lambda_=20, eta=1, iters=30000, n_chains=30, alpha=1, fim_method='eclat', feature_names=None, category_names=None, seed=None, verbose=0, discretize_method='mdlp', numeric_features=None):
super(RuleList, se... |
(python=ALL_PYTHONS, reuse_venv=True)
def tests(session):
session.install('-r', 'requirements-test-full.txt', './awkward-cpp', '.')
session.run('pytest', *(session.posargs if session.posargs else ['tests'])) |
def recursive_glob(rootdir='.', suffix=''):
image_paths = []
for (looproot, _, filenames) in os.walk(rootdir):
for filename in filenames:
if filename.endswith(suffix):
image_paths.append(os.path.join(looproot, filename))
return image_paths |
def generate_cubic():
generator = GenericCurveGenerator(width=img_width, height=img_height)
generator.saltpepper = 0.9
generator.curvetype = 'cubic'
generator.max_consecutive_distance = 15
prefix = generator.generate_filename_prefix()
generator.output_file = create_new_absolute_filename(('Cubic-... |
def handle_interrupted(context: ExecutionContext, event: events.Interrupted) -> None:
click.echo()
context.is_interrupted = True
display_section_name('KeyboardInterrupt', '!', bold=False) |
def EncoderTest(verbose=True):
shape = (2, 4, 224, 224)
encoder = WNet.UEnc(shape[1])
data = torch.rand((shape[0], 3, shape[2], shape[3]))
encoded = encoder(data)
assert (tuple(encoded.shape) == shape)
var = torch.var(encoded)
mean = torch.mean(encoded)
if verbose:
print(('Passed... |
def test_flatten_array_with_prefix():
result = flatten_array([['foo', 'bar'], 'tar'], prefix='test')
expected = {'test__0__0': 'foo', 'test__0__1': 'bar', 'test__1': 'tar'}
assert (result == expected) |
def segRead(fn, start, end):
fo = open(fn, 'r')
line = fo.readlines()[start:end]
fo.close()
return line |
class HyperbolicPlane(Parent, UniqueRepresentation):
def __init__(self):
Parent.__init__(self, category=Sets().Metric().WithRealizations())
self.a_realization()
def _repr_(self):
return 'Hyperbolic plane'
def a_realization(self):
return self.UHP()
UHP = HyperbolicModelUHP... |
class SpeakerClassifiDataset(Dataset):
def __init__(self, mode, file_path, meta_data, max_timestep=None):
self.root = file_path
self.speaker_num = 1251
self.meta_data = meta_data
self.max_timestep = max_timestep
self.usage_list = open(self.meta_data, 'r').readlines()
... |
def test_count_all_paths_with_label_seq_partly_dominated(recalc=False, check=False, check_with_factor=False):
fsa = get_std_fsa_1label()
n_ = 4
n = sympy.Symbol('n', integer=True, positive=True)
factor = sympy.Symbol('fact', real=True, positive=True)
res = count_all_paths_with_label_seq_partly_domin... |
def test_sign_synthetic_policy_continuous():
with pytest.raises(ValueError):
context = np.array([1.0, 1.0])
sign_synthetic_policy_continuous(context=context)
with pytest.raises(ValueError):
context = [1.0, 1.0]
sign_synthetic_policy_continuous(context=context)
n_rounds = 10
... |
def main(args):
verbose = args.verbose
num_threads = args.num_threads
from topaz.torch import set_num_threads
set_num_threads(num_threads)
use_cuda = topaz.cuda.set_device(args.device)
from topaz.model.factory import load_model
model = load_model(args.model)
model.eval()
model.fill()... |
def format_checker(input_folder_path):
input_files = glob.glob((input_folder_path + '*.jsonl'))
assert (len(input_files) == 5), 'missing prediction files - should be 5 files'
for each_file in input_files:
curr_category_name = each_file.split('/')[(- 1)].split('-')[(- 1)].replace('.jsonl', '')
... |
def parse(content):
header = content[0:1024]
header = MRCHeader._make(header_struct.unpack(content[:1024]))
extbytes = header.next
start = (1024 + extbytes)
extended_header = content[1024:start]
content = content[start:]
if (header.mode == 0):
dtype = np.int8
elif (header.mode ==... |
class CustomLoaderCallback(Callback):
def __init__(self, loading_dir: str):
super(CustomLoaderCallback, self).__init__()
self.loading_dir = loading_dir
def set_model(self, model):
self.model = model
print('-- Loading ', self.loading_dir)
self.model.load_weights(os.path.jo... |
def __stable_idx_answer(shape, zoom, tile_size=256):
dim0_tile_fraction = (shape[0] / tile_size)
dim1_tile_fraction = (shape[1] / tile_size)
if ((dim0_tile_fraction < 1) or (dim1_tile_fraction < 1)):
raise StopIteration()
num_tiles_dim0 = int(np.ceil(dim0_tile_fraction))
num_tiles_dim1 = int... |
class LispFunction(ExpectFunction):
def _instancedoc_(self):
M = self._parent
return M.help(self._name) |
class RCToMLTBijectionTypeB(RCToKRTBijectionTypeB):
def run(self):
letters = CrystalOfLetters(self.rigged_con.parent()._cartan_type.classical())
ret_crystal_path = []
while self.cur_dims:
dim = self.cur_dims[0]
ret_crystal_path.append([])
if (dim[0] == sel... |
def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False, output_loading_info=False, _prefix=None, tf_to_pt_weight_rename=None):
try:
import tensorflow as tf
import torch
except ImportError:
logger.error('Loading a PyTorch model in TensorFlo... |
def get_number_of_params_path(model, nodes, print_on=False, include_routers=True):
(names, params) = ([], [])
if include_routers:
for (name, param) in model.named_parameters():
if (((('.' + str(nodes[(- 1)])) + '.classifier') in name) or any([((('.' + str(node)) + '.transform') in name) for ... |
def TStrUtil_StripEnd(Str, SearchStr, NewStr):
return _snap.TStrUtil_StripEnd(Str, SearchStr, NewStr) |
def _default_generator_blocks():
return [Block(64, 0.5), Block(128, 0.5), Block(256, 0.5), Block(512, 0), Block(512, 0), Block(512, 0), Block(512, 0)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.