code stringlengths 101 5.91M |
|---|
def test_mscn(dataset: str, version: str, workload: str, params: Dict[(str, Any)], overwrite: bool) -> None:
torch.set_num_threads(NUM_THREADS)
assert (NUM_THREADS == torch.get_num_threads()), torch.get_num_threads()
L.info(f'torch threads: {torch.get_num_threads()}')
model_file = ((MODEL_ROOT / dataset... |
def test_has_notebooks():
assert (len(get_notebooks()) >= 2), 'there are probably some notebooks that were not discovered' |
def write_entries(cmd, basename, filename):
ep = cmd.distribution.entry_points
if (isinstance(ep, six.string_types) or (ep is None)):
data = ep
elif (ep is not None):
data = []
for (section, contents) in sorted(ep.items()):
if (not isinstance(contents, six.string_types)):... |
def test_product_combiner(create_pool_classifiers):
query = np.array([[1, (- 1)]])
ensemble_classifiers = create_pool_classifiers
expected = 0
result = product_combiner(ensemble_classifiers, query)
assert np.allclose(expected, result) |
class FixedBundleAdjustmentProblem():
def __init__(self, num_views: int, num_landmarks: int) -> None:
self.num_views = num_views
self.num_landmarks = num_landmarks
self.values = build_values(num_views=num_views, num_landmarks=num_landmarks)
self.residual = self._build_residual()
... |
def add_hostvuln_to_allvuln(host_vulners, all_vulners):
if isinstance(host_vulners, list):
all_vulners.extend(host_vulners)
elif isinstance(host_vulners, str):
all_vulners.append(host_vulners) |
def insert_bn(names):
names_bn = []
for name in names:
names_bn.append(name)
if ('conv' in name):
position = name.replace('conv', '')
names_bn.append(('bn' + position))
return names_bn |
_properties
class TaskletFusion(transformation.SingleStateTransformation):
tsk1 = transformation.PatternNode(nd.Tasklet)
data = transformation.PatternNode(nd.AccessNode)
tsk2 = transformation.PatternNode(nd.Tasklet)
def expressions(cls):
return [node_path_graph(cls.tsk1, cls.data, cls.tsk2), nod... |
def rand_x(num):
correct = [[0, 0], [2, 2], [5, 5], [(- 15), 15], [15, (- 15)], [0, 0], [2, 2], [5, 0], [0, 0], [24, (- 15)], [17.5, (- 15)], [15, (- 15)], [18, (- 15)], [3.7, 5], [5, 5], [17.5, (- 15)], [15, (- 15)]]
if ((num > 0.33) and (num < 0.66)):
x = random.uniform((61.3 + correct[map_num][0]), 9... |
class DocBuilder():
def __init__(self, name, lang='en'):
doc = name.split(os.path.sep)
if (doc[0] in build_options.LANGUAGES):
lang = doc[0]
doc.pop(0)
self.name = os.path.join(*doc)
self.lang = lang
self.dir = os.path.join(SAGE_DOC_SRC, self.lang, sel... |
def setup_context(setup_dir):
temp_dir = os.path.join(setup_dir, 'temp')
with save_pkg_resources_state():
with save_modules():
hide_setuptools()
with save_path():
with save_argv():
with override_temp(temp_dir):
with push... |
class GCNConv_MLP(MessagePassing):
_cached_edge_index: Optional[Tuple[(Tensor, Tensor)]]
_cached_adj_t: Optional[SparseTensor]
def __init__(self, in_channels: int, out_channels: int, improved: bool=False, cached: bool=False, add_self_loops: bool=True, normalize: bool=True, bias: bool=True, **kwargs):
... |
def main(opts):
data_folder = opts.data_root
file_lst = opts.file_list
file_out = opts.file_out
save_path = opts.out_root
copy_folder(opts.data_root, opts.out_root)
if (not os.path.exists(file_out)):
print('VADing signals to build {} list...'.format(file_out))
pool = mp.Pool(opts... |
class WordpieceTokenizer(object):
def __init__(self, vocab, unk_token='[UNK]', max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
text = convert_to_unicode(text)
o... |
def show_average():
dataset = 4
result = [RESULT[dataset] for RESULT in RESULTS]
Y = [(num - result[0]) for num in result][1:]
plt.bar(X, Y, color=color)
plt.yticks(fontsize=18, rotation=90)
plt.xticks(X, fontsize=18)
plt.title(DATASETS[dataset], {'fontsize': 30})
plt.ylim((- 10), 20)
... |
def load_hdf5_tree(hdf5_file_name):
out_dict = {}
def add_item(name, obj):
if (not isinstance(obj, h5py.Group)):
tmp = {}
if (type(obj.value) == numpy.ndarray):
tmp['value'] = 'array shape = {}'.format(obj.shape)
else:
tmp['value'] = ob... |
_pydub_effect
def speedup(seg, playback_speed=1.5, chunk_size=150, crossfade=25):
atk = (1.0 / playback_speed)
if (playback_speed < 2.0):
ms_to_remove_per_chunk = int(((chunk_size * (1 - atk)) / atk))
else:
ms_to_remove_per_chunk = int(chunk_size)
chunk_size = int(((atk * chunk_size)... |
def time_synchronized():
if torch.cuda.is_available():
torch.cuda.synchronize()
return time.time() |
class UnpoolingDataGrad(UnaryDataGrad):
def __init__(self, ctx, kernel, channel_last=False):
super(UnpoolingDataGrad, self).__init__(ctx)
self._func = _F.Unpooling(ctx, kernel, channel_last) |
def test_fsaf_head_loss():
s = 256
img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3)}]
cfg = dict(reg_decoded_bbox=True, anchor_generator=dict(type='AnchorGenerator', octave_base_scale=1, scales_per_octave=1, ratios=[1.0], strides=[8, 16, 32, 64, 128]), bbox_coder=dict(type='TB... |
def certify_director(token):
subprocess.check_call(['fx', 'pki', 'certify', '-n', DIRECTOR_SUBJECT_NAME, '-t', token, '-c', f"{(CA_PATH / 'cert')}", '-p', str(CA_PATH)]) |
def register_Ns3MqQueueDisc_methods(root_module, cls):
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_constructor([])
cls.add_method('GetWakeMode', 'ns3::QueueDisc::WakeMode', [], is_const=True, is_virtual=True)
cls.add_method('DoEnqueue', 'bool', [param('ns3::Ptr< ns3::QueueDisc... |
def pointnet_fp_module(xyz1, xyz2, points1, points2, mlp, is_training, bn_decay, scope, bn=True, bn2=False):
with tf.variable_scope(scope) as sc:
(dist, idx) = three_nn(xyz1, xyz2)
dist = tf.maximum(dist, 1e-10)
norm = tf.reduce_sum((1.0 / dist), axis=2, keep_dims=True)
norm = tf.til... |
def make_tokenizer(tokenizer_type, corpus, model_path=None, vocab_size=None, model_type='bpe', pad_token=0, character_coverage=1.0, command_tokens=None, type_tokens=None, **kwargs):
tokenizer_class = tokenizer_type
if isinstance(tokenizer_class, str):
tokenizer_class = eval(tokenizer_class)
if (toke... |
_model('masked_lm')
class MaskedLMModel(BaseFairseqModel):
def __init__(self, args, encoder):
super().__init__()
self.args = args
self.encoder = encoder
if getattr(args, 'apply_bert_init', False):
self.apply(init_bert_params)
def add_args(parser):
parser.add_a... |
class Layer(nn.Module):
def __init__(self, config, d_model, n_head):
super(Layer, self).__init__()
self.config = config
self.d_model = d_model
self.n_head = n_head
self.attn_network = MultiHeadAttention.MultiHeadAttention(config, d_model, n_head)
self.ffn = FeedForwar... |
def _fundamental_constant_implicit_function_(phi):
from sage.symbolic.ring import SR
u = SR('u')
positive_solution = [s for s in (phi(u) - (u * phi(u).diff(u))).solve(u) if (s.rhs() > 0)]
if (len(positive_solution) == 1):
return positive_solution[0].rhs()
raise ValueError('Fundamental consta... |
class OxfordFlowers102Dataset(Dataset):
def __init__(self, root='data/meta-dataset/VGGFlower', mode='test', backbone_name='resnet12', transform=None):
self.root = root
(_, train_process, val_process) = load(backbone_name, jit=False)
if ((mode == 'val') or (mode == 'test')):
trans... |
def get_bn_modules(model: nn.Module) -> List[nn.Module]:
bn_layers = [m for m in model.modules() if (m.training and isinstance(m, BN_MODULE_TYPES))]
return bn_layers |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data... |
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3MobilityModel__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::MobilityModel const >, ns3::empty, ns3::empty... |
class TestNCCL(TestCase):
(IS_WINDOWS, "NCCL doesn't support Windows")
def test_unique_id(self, device):
uid = nccl.unique_id()
self.assertIsInstance(uid, bytes)
self.assertGreater(len(uid), 1)
((TEST_WITH_ROCM and (HIP_VERSION < 3.5)), 'Skip NCCL tests for ROCm')
(IS_WINDOWS, "N... |
class ThreeDPW(Dataset3D):
def __init__(self, load_opt, set, seqlen, overlap=0.75, debug=False, target_vid=''):
db_name = '3dpw'
print('3DPW Dataset overlap ratio: ', overlap)
super(ThreeDPW, self).__init__(load_opt=load_opt, set=set, folder=THREEDPW_DIR, seqlen=seqlen, overlap=overlap, data... |
def get_module_name(frame):
modulename = frame.f_globals.get('__name__', None)
if (modulename is None):
if (frame.f_code.co_filename == '<__array_function__ internals>'):
modulename = 'numpy.__array_function__'
else:
modulename = 'unkown'
typeobject = frame.f_locals.g... |
def iob2bioes(tags: List[str]) -> List[str]:
new_tags = []
for (i, tag) in enumerate(tags):
if (tag == 'O'):
new_tags.append(tag)
else:
split = tag.split('-')[0]
if (split == 'B'):
if (((i + 1) != len(tags)) and (tags[(i + 1)].split('-')[0] == ... |
class TestUtils(test_util.TestCase):
def testArgsToDict(self):
args = [utils.MakeArgument('int1', 3), utils.MakeArgument('float1', 4.0), utils.MakeArgument('string1', 'foo'), utils.MakeArgument('intlist1', np.array([3, 4])), utils.MakeArgument('floatlist1', np.array([5.0, 6.0])), utils.MakeArgument('stringl... |
def downsample_basic_block(x, planes, stride):
out = F.avg_pool3d(x, kernel_size=1, stride=stride)
zero_pads = torch.Tensor(out.size(0), (planes - out.size(1)), out.size(2), out.size(3), out.size(4)).zero_()
if isinstance(out.data, torch.cuda.FloatTensor):
zero_pads = zero_pads.cuda()
out = Vari... |
def validate_variable(f):
if isinstance(f, (sciann.Variable, sciann.functionals.RadialBasis, sciann.functionals.RNNVariable)):
return True
else:
raise ValueError('These operations can only be applied to the `Variable` object. Use `Keras` or `TensorFlow` functions when applying to tensors or laye... |
class CheckpointIO(object):
def __init__(self, checkpoint_dir='./chkpts', **kwargs):
self.module_dict = kwargs
self.checkpoint_dir = checkpoint_dir
if (not os.path.exists(checkpoint_dir)):
os.makedirs(checkpoint_dir)
def register_modules(self, **kwargs):
self.module_d... |
def __main__():
if (cfg.TEST.WEIGHTS == ''):
print('no test weights exist!!')
else:
model = setup_model()
checkpoint.load_checkpoint(cfg.TEST.WEIGHTS, model)
test_model(model, cfg.TEST.DATA_DIR, cfg.TEST.DATASET_LIST, cfg.TEST.SCALE_LIST, cfg.TEST.TOPK_LIST) |
class DepthDecoder(nn.Module):
def __init__(self, num_ch_enc, scales=range(4), num_output_channels=1, use_skips=True):
super(DepthDecoder, self).__init__()
self.num_output_channels = num_output_channels
self.use_skips = use_skips
self.upsample_mode = 'nearest'
self.scales = s... |
class Temporal_Basic_Block(nn.Module):
def __init__(self, channels, temporal_window_size, stride=1, residual=False, **kwargs):
super(Temporal_Basic_Block, self).__init__()
padding = (((temporal_window_size - 1) // 2), 0)
if (not residual):
self.residual = (lambda x: 0)
el... |
def merge_flows(flow_list):
result = defaultdict(float)
for ((u, v), l) in flow_list:
result[(u, v)] += l
return [((u, v), l) for ((u, v), l) in result.items()] |
def main():
args = parse_args()
if (args is None):
exit()
with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:
gan = AttnGAN(sess, args)
gan.build_model()
show_all_variables()
if (args.phase == 'train'):
gan.train()
print(... |
def _percentile(a, q, *, method='linear', **kwargs):
return np.percentile(a, q, interpolation=method, **kwargs) |
class ActivationsAndGradients():
def __init__(self, model, target_layers, reshape_transform):
self.model = model
self.gradients = []
self.activations = []
self.reshape_transform = reshape_transform
self.handles = []
for target_layer in target_layers:
self.... |
def get_token(name, ca_url, ca_path='.'):
ca_path = Path(ca_path)
step_config_dir = (ca_path / CA_STEP_CONFIG_DIR)
pki_dir = (ca_path / CA_PKI_DIR)
(step_path, _) = get_ca_bin_paths(ca_path)
if (not step_path):
raise Exception('Step-CA is not installed!\nRun `fx pki install` first')
priv... |
def _nanmedian_dispatcher(a, axis=None, out=None, overwrite_input=None, keepdims=None):
return (a, out) |
def load_experiment_config(experiments_file, experiment_tags):
with open(experiments_file, 'r') as f:
data = json.load(f)
d = {}
for tag in experiment_tags:
_inject_items(build_dict(data, tag), d)
return d |
def process_image(encoded_image, is_training, height, width, resize_height=346, resize_width=346, thread_id=0, image_format='jpeg'):
def image_summary(name, image):
if (not thread_id):
tf.image_summary(name, tf.expand_dims(image, 0))
with tf.name_scope('decode', values=[encoded_image]):
... |
def cross_entropy_calc(TOP, P, POP):
try:
result = 0
for i in TOP.keys():
reference_likelihood = (P[i] / POP[i])
response_likelihood = (TOP[i] / POP[i])
if ((response_likelihood != 0) and (reference_likelihood != 0)):
result += (reference_likelihoo... |
class PseudoDataParallel(nn.Module):
def __init__(self, model):
super().__init__()
self.module = model |
class FeatureFusionModule(nn.Module):
def __init__(self, higher_in_channels, lower_in_channels, out_channels, conv_cfg=None, norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU'), align_corners=False):
super(FeatureFusionModule, self).__init__()
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cf... |
class GroupAlgebraFunctor(ConstructionFunctor):
def __init__(self, group):
self.__group = group
from sage.categories.rings import Rings
ConstructionFunctor.__init__(self, Rings(), Rings())
def group(self):
return self.__group
def _apply_functor(self, base_ring):
retur... |
def CppExtension(name, sources, *args, **kwargs):
include_dirs = kwargs.get('include_dirs', [])
include_dirs += include_paths()
kwargs['include_dirs'] = include_dirs
if (sys.platform == 'win32'):
library_dirs = kwargs.get('library_dirs', [])
library_dirs += library_paths()
kwargs... |
def register_optimizer(name):
if (name in OPTIMIZERS):
return
if (name == 'Ranger'):
from lib.torch_utils.solver.ranger import Ranger
OPTIMIZERS.register_module()(Ranger)
elif (name in ['AdaBelief', 'RangerAdaBelief']):
from lib.torch_utils.solver.AdaBelief import AdaBelief
... |
class TransducerLoss(Module):
def __init__(self, blank=0, reduction='mean'):
super(TransducerLoss, self).__init__()
self.blank = blank
self.reduction = reduction
self.loss = Transducer.apply
try:
cuda.cuda_paths
except ImportError:
err_msg = 'c... |
.unit
.convert
def test_slice_idx_generator_z1():
shape = (4305, 9791)
zoom = 1
tile_size = 256
given = convert.slice_idx_generator(shape, zoom, tile_size)
expected = helpers.get_slice_idx_generator_solution(zoom)
comparable_given = set(map(helpers.covert_idx_to_hashable_tuple, given))
compa... |
def load_goals(para_config, intent_utterance_dir, intent_name, mode, number_utterances=(- 1)):
if (number_utterances > 0):
para_config = ((para_config + '_utt_') + str(number_utterances))
else:
para_config = (para_config + '_utt_all')
goal_path = (((((intent_utterance_dir + '/') + intent_nam... |
def benchmark(args):
print('Batch size: {}'.format(args.batch_size))
mf = ModelDownloader()
(init_net, pred_net, value_info) = mf.get_c2_model(args.model)
input_shapes = {k: ([args.batch_size] + v[(- 1)][1:]) for (k, v) in value_info.items()}
print('input info: {}'.format(input_shapes))
external... |
def check_equal(x, y, logger):
if (x != y):
exception = ValueError(f'{x} != {y}')
logger.exception(repr(exception))
raise exception |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input_dir', required=True)
parser.add_argument('--save_dir', required=True, help='path to save checkpoints and logs')
parser.add_argument('--lr', default=0.001, type=float)
parser.add_argument('--weight_decay', default=1e-05, type... |
def reduce_by_model(logs, error_filter=None):
logs = [(x[0], x[1], get_model(x[2])) for x in logs]
logs = [x for x in logs if (x[2] is not None)]
tests = {x[2] for x in logs}
r = {}
for test in tests:
counter = Counter()
counter.update([x[1] for x in logs if (x[2] == test)])
... |
class TestNLPLabelingFunction(unittest.TestCase):
def _run_lf(self, lf: NLPLabelingFunction) -> None:
x = SimpleNamespace(num=8, title='Great film!', article='The movie is really great!')
self.assertEqual(lf(x), (- 1))
x = SimpleNamespace(num=8, title='Nice movie!', article='Jane Doe acted w... |
class detect_anomaly(object):
def __init__(self):
self.prev = torch.is_anomaly_enabled()
def __enter__(self):
torch.set_anomaly_enabled(True)
def __exit__(self, *args):
torch.set_anomaly_enabled(self.prev)
return False |
class RequestTimeout(HTTPException):
code = 408
description = "The server closed the network connection because the browser didn't finish the request within the specified time." |
class FuncContiguousArgs():
def forward(self, input_ids, token_type_ids, attention_mask):
return None |
def classification_eval(model: tf.keras.Model, data_loader: tf.data.Dataset, limit=None):
logging.info(f'Start classification evaluation')
acc = tf.keras.metrics.Accuracy()
total = 0
for data in tqdm(data_loader, desc='Classification evaluation'):
(images, labels) = data
outputs = model(... |
def _check_polynomials_P3(quadratic1, quadratic2, variables):
if (quadratic1.parent() is not quadratic2.parent()):
raise ValueError('the two quadratics must be in the same polynomial ring')
if (variables is None):
variables = (quadratic1.variables() + quadratic2.variables())
variables = ... |
def get_linear_schedule_with_warmup(*args, **kwargs):
requires_pytorch(get_linear_schedule_with_warmup) |
class RCAN(nn.Module):
def __init__(self, args, conv=common.default_conv):
super(RCAN, self).__init__()
n_resgroups = args.n_resgroups
n_resblocks = args.n_resblocks
n_feats = args.n_feats
kernel_size = 3
reduction = args.reduction
scale = args.scale[0]
... |
def test_birch_duck_typing_meta():
birch = Birch(n_clusters=AgglomerativeClustering(n_clusters=3))
html_output = estimator_html_repr(birch)
with config_context(print_changed_only=True):
assert (f'<pre>{html.escape(str(birch.n_clusters))}' in html_output)
assert ('AgglomerativeClustering</lab... |
def _fractional_power_pade(R, t, m):
if ((m < 1) or (int(m) != m)):
raise ValueError('expected a positive integer m')
if (not ((- 1) < t < 1)):
raise ValueError('expected -1 < t < 1')
R = np.asarray(R)
if ((len(R.shape) != 2) or (R.shape[0] != R.shape[1])):
raise ValueError('expe... |
def test_schema_not_available_wsgi(cli, loadable_flask_app, snapshot_cli):
assert (cli.run('unknown.yaml', f'--app={loadable_flask_app}') == snapshot_cli) |
def entropy(x, k=3, base=2):
assert (k <= (len(x) - 1)), 'Set k smaller than num. samples - 1'
d = len(x[0])
N = len(x)
intens = 1e-10
x = [list((p + (intens * nr.rand(len(x[0]))))) for p in x]
tree = ss.cKDTree(x)
nn = [tree.query(point, (k + 1), p=float('inf'))[0][k] for point in x]
co... |
class ReparamPolicy(ReparamModule):
def sample(self, *args, **kwargs):
return self.module.sample(*args, **kwargs)
def log_prob(self, *args, **kwargs):
return self.module.log_prob(*args, **kwargs)
def kl_divergence(self, *args, **kwargs):
return self.module.kl_divergence(*args, **kwar... |
def pq_group_bitrade_generators(p, q):
assert is_prime(p)
assert is_prime(q)
assert ((q % p) == 1)
F = FiniteField(q)
fgen = F.multiplicative_generator()
beta = (fgen ** ((q - 1) / p))
assert (beta != 1)
assert (((beta ** p) % q) == 1)
Q = tuple(range(1, (q + 1)))
P = []
seen... |
def test_read_vi_tree():
text = VI_TREEBANK.split('\n')[0]
trees = tree_reader.read_trees(text)
assert (len(trees) == 1)
assert (str(trees[0]) == text)
node = trees[0].children[0].children[0].children[2]
assert node.is_preterminal()
assert (node.children[0].label == 'ai Loan') |
class MatchingPipe(Pipe):
def __init__(self, lower=False, tokenizer: str='raw'):
super().__init__()
self.lower = bool(lower)
self.tokenizer = get_tokenizer(tokenize_method=tokenizer)
def _tokenize(self, data_bundle, field_names, new_field_names):
for (name, dataset) in data_bundl... |
class ZincConfig(BaseGraphConfig):
def __init__(self, num_samples=50) -> None:
super().__init__(debug_mode=False)
self.num_samples = num_samples
def settings(self) -> ExperimentSettings:
return ExperimentSettings('zinc', final_repeats=REPEATS, final_max_iterations=ITERS)
def resource... |
class Uniform(Initializer):
def __init__(self, low=0.0, high=1.0):
super().__init__()
self.low = low
self.high = high
def initialize(self, shape):
return np.random.uniform(size=shape, low=self.low, high=self.high) |
def vmap(func: Callable, in_dims: in_dims_t=0, out_dims: out_dims_t=0) -> Callable:
warnings.warn('torch.vmap is an experimental prototype that is subject to change and/or deletion. Please use at your own risk.')
(func)
def wrapped(*args):
_check_out_dims_is_int_or_int_tuple(out_dims, func)
... |
def specialize_types(f: SymbolicFunction, type_replacements: T.Mapping[(T.Type, T.Type)]) -> SymbolicFunction:
(f)
def specialized_function(*args: T.Any, **kwargs: T.Any) -> T.Any:
return f(*args, **kwargs)
specialized_function.__annotations__ = f.__annotations__.copy()
for (annotation, cls) in ... |
class Pretrainer():
def __init__(self, collect_in='./model_checkpoints', loadables=None, paths=None, custom_hooks=None, conditions=None):
self.loadables = {}
self.collect_in = pathlib.Path(collect_in)
if (loadables is not None):
self.add_loadables(loadables)
self.paths = ... |
def test_matlab_like_resize():
results = {}
results['lq'] = np.ones((16, 16, 3))
imresize = MATLABLikeResize(keys=['lq'], scale=0.25)
results = imresize(results)
assert (results['lq'].shape == (4, 4, 3))
results['lq'] = np.ones((16, 16, 3))
imresize = MATLABLikeResize(keys=['lq'], output_sha... |
class IntersectionTester():
def __init__(self, mesh: fenics.Mesh) -> None:
self.mesh = mesh
cells = self.mesh.cells()
flat_cells = cells.flatten().tolist()
self.cell_counter: collections.Counter = collections.Counter(flat_cells)
self.occurrences = np.array([self.cell_counter[... |
def distiller_local(ckpt, *args, **kwargs):
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs) |
def denoise_image(mic, models, lowpass=1, cutoff=0, gaus=None, inv_gaus=None, deconvolve=False, deconv_patch=1, patch_size=(- 1), padding=0, normalize=False, use_cuda=False):
if (lowpass > 1):
mic = dn.lowpass(mic, lowpass)
mic = torch.from_numpy(mic)
if use_cuda:
mic = mic.cuda()
mu = m... |
class sage__libs__gap(JoinFeature):
def __init__(self):
JoinFeature.__init__(self, 'sage.libs.gap', [PythonModule('sage.libs.gap.libgap'), PythonModule('sage.interfaces.gap'), PythonModule('sage.groups.matrix_gps.finitely_generated_gap'), PythonModule('sage.groups.matrix_gps.group_element_gap'), PythonModul... |
class TestTimeSeriesData(unittest.TestCase):
def test_data_class(self):
data = np.array([[(- 0.), 0., (- 2.)], [(- 0.), (- 0.6893588), (- 1.)], [0., 1., 0.], [(- 0.), 0., 1.], [(- 1.), (- 0.), (- 0.)]])
data_obj = TimeSeriesData(data, var_names=['A', 'B', 'C'])
(x, y, z) = data_obj.extract_a... |
def tldr_metrics(src_file, pred_file):
src_list = []
pred_list = []
with open(src_file, 'r') as f:
for line in f:
src_list.append(line.strip())
with open(pred_file, 'r') as f:
for line in f:
pred_list.append(line.strip())
assert (len(src_list) == len(pred_list... |
def iri_to_uri(iri, charset='utf-8', errors='strict', safe_conversion=False):
if isinstance(iri, tuple):
iri = url_unparse(iri)
if safe_conversion:
try:
native_iri = to_native(iri)
ascii_iri = native_iri.encode('ascii')
if (len(ascii_iri.split()) == 1):
... |
class HausdorffDistance(DistanceMetric):
def __init__(self, percentile: float=100.0, metric: str='HDRFDST'):
super().__init__(metric)
self.percentile = percentile
def calculate(self):
if ((self.distances.distances_gt_to_pred is not None) and (len(self.distances.distances_gt_to_pred) > 0)... |
class ConvPnPNetCls(nn.Module):
def __init__(self, nIn, num_regions=8, mask_attention_type='none', featdim=128, rot_dim=6, num_stride2_layers=3, num_extra_layers=0, norm='GN', num_gn_groups=32, act='relu', drop_prob=0.0, dropblock_size=5, flat_op='flatten', final_spatial_size=(8, 8)):
super().__init__()
... |
class ResNet(nn.Module):
def __init__(self, block, layers, strides=(2, 2, 2, 2), dilations=(1, 1, 1, 1)):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=strides[0], padding=3, bias=False)
self.bn1 = FixedBatchNorm(64)
sel... |
class PlayerShip(PhysicalObject):
def __init__(self, *args, **kwargs):
super(PlayerShip, self).__init__('ship.png', *args, **kwargs)
def create_physical_entity(self):
body = self._engine.CreateDynamicBody(position=self.physical_position, linearDamping=0.99, fixedRotation=True)
body.Creat... |
def train_wrapper_reg(_paramsList, _GPU_ID):
for (pIdx, params) in enumerate(_paramsList):
print(('===[%d/%d]===' % (pIdx, len(_paramsList))))
(_trainMode, _dataType, _oRate, _var) = (params[0], params[1], params[2], params[3])
if (_trainMode == 'CN'):
run_cn(_trainMode, _dataTyp... |
class DataCollatorMixin():
def __call__(self, features, return_tensors=None):
if (return_tensors is None):
return_tensors = self.return_tensors
if (return_tensors == 'tf'):
return self.tf_call(features)
elif (return_tensors == 'pt'):
return self.torch_call... |
def DepRound(weights_p, k=1, isWeights=True):
p = np.array(weights_p)
K = len(p)
assert (k < K), 'Error: k = {} should be < K = {}.'.format(k, K)
if (not np.isclose(np.sum(p), 1)):
p = (p / np.sum(p))
assert (np.all((0 <= p)) and np.all((p <= 1))), 'Error: the weights (p_1, ..., p_K) should ... |
def make_monic(f):
R = f.parent()
n = f.degree()
lc = f[n]
d = ZZ.one()
for i in range(n):
expo = (n - i)
den = (((d ** expo) * f[i]) / lc).denominator()
for (p, e) in factor_trial_division(den, 1000000):
d *= (p ** (((e + expo) - 1) // expo))
g = R([(((d ** (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.