code stringlengths 101 5.91M |
|---|
def train_and_val(config, model, callbacks, mixture_num, sub_model_name):
print(('training %s %s model' % (model_name, sub_model_name)))
train_size = int((((num_mon_sites * num_mon_inst_train) + num_unmon_sites_train) * 0.95))
train_steps = (train_size // batch_size)
val_size = int((((num_mon_sites * nu... |
_ASSIGNERS.register_module()
class UniformAssigner(BaseAssigner):
def __init__(self, pos_ignore_thr, neg_ignore_thr, match_times=4, iou_calculator=dict(type='BboxOverlaps2D')):
self.match_times = match_times
self.pos_ignore_thr = pos_ignore_thr
self.neg_ignore_thr = neg_ignore_thr
se... |
def check_cdf_logcdf(distfn, args, msg):
points = np.array([0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0])
vals = distfn.ppf(points, *args)
vals = vals[np.isfinite(vals)]
cdf = distfn.cdf(vals, *args)
logcdf = distfn.logcdf(vals, *args)
cdf = cdf[(cdf != 0)]
logcdf = logcdf[np.isfinite(logcdf)]... |
def eval_file_stats(target_db):
count = 0
no_results = []
for i in target_db.find():
if (i['results'] != []):
count += 1
else:
no_results.append(i['id'])
return (count, no_results) |
class Filter(abc.ABC):
def __init__(self):
self.verbose = False
def execute(self, image: sitk.Image, params: FilterParams=None) -> sitk.Image:
raise NotImplementedError() |
def main():
cmdclass = dict()
version = None
init_path = ((_pwd / 'lidarnerf') / '__init__.py')
with open(init_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
match_res = re.match('^__version__ = "(.*)"', line)
if match_res:
... |
def leaky_integrate_and_fire(mem, cur=0, threshold=1, time_step=0.001, R=5.1, C=0.005):
tau_mem = (R * C)
spk = (mem > threshold)
mem = (mem + ((time_step / tau_mem) * ((- mem) + (cur * R))))
return (mem, spk) |
def _subdivide_interval(args):
(interval, f, norm_func, _quadrature) = args
(old_err, a, b, old_int) = interval
c = (0.5 * (a + b))
if (getattr(_quadrature, 'cache_size', 0) > 0):
f = functools.lru_cache(_quadrature.cache_size)(f)
(s1, err1, round1) = _quadrature(a, c, f, norm_func)
dnev... |
def read_test_file(test_file, prediction_topk):
test_data = []
for line in open(test_file, encoding='utf-8'):
line = line.strip('\n').split('\t')
rank = int(line[2])
if (rank <= prediction_topk):
test_data.append((line[0], line[1]))
return test_data |
def test_hyperkalemia(tmp_path: pathlib.Path):
outcome_codes = {'child_1_1', 'child_2', 'child_1', 'LOINC/LP386618-5', 'LOINC/LG10990-6', 'LOINC/LG7931-1', 'LOINC/6298-4', 'LOINC/2823-3'}
labeler = _create_specific_labvalue_labeler(HyperkalemiaLabValueLabeler, 'severe', outcome_codes)
_assert_value_to_label... |
class Test_Frontend(unittest.TestCase):
def setUp(self) -> None:
cc = device_cc()
math_inst = MathInstruction([1, 1, 1], cutlass.float32, cutlass.float32, cutlass.float32, cutlass.OpClass.Simt, MathOperation.multiply_add)
stages = 2
tile_description = TileDescription([128, 128, 8], s... |
def produceImgList():
root_path = '/home/lmin/data/portrait/'
stages = ['train', 'val']
for stage in stages:
seg_txt = open(((root_path + stage) + '_2.txt'), 'a')
imgpath = glob(os.path.join(root_path, stage, 'images/*.png'))
for imgline in imgpath:
print(imgline.replace(... |
def _cfg(url='', **kwargs):
return {'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7), 'crop_pct': 0.875, 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'conv_stem', 'classifier': 'classifier', **kwargs} |
def convert_file(input_file, output_file):
fasta = pyfaidx.Fasta(input_file)
h5 = h5py.File(output_file, 'w')
for k in fasta.keys():
s = str(fasta[k][:].seq).upper()
ds = h5.create_dataset(k, (len(s),), dtype='S1')
for i in range(len(s)):
ds[i] = numpy.string_(s[i])
h... |
def register_Ns3EpcX2SapHandoverRequestParams_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::EpcX2Sap::HandoverRequestParams const &', 'arg0')])
cls.add_instance_attribute('bearers', 'std::vector< ns3::EpcX2Sap::ErabToBeSetupItem >', is_const=False)
cls.add_instance_... |
def interpolant_attempt():
s = ss.create_msat_solver(False)
s.set_opt('produce-models', 'true')
s.set_opt('incremental', 'true')
(prop, fts) = build_simple_alu_fts(s)
print('\n Running Interpolant-based Model Checking ')
print('INIT\n\t{}'.format(fts.init))
print('TRANS\n\t{}'.format(fts.tra... |
def prepare_dir(ted_dir):
converted_dir = os.path.join(ted_dir, 'converted')
wav_dir = os.path.join(converted_dir, 'wav')
if (not os.path.exists(wav_dir)):
os.makedirs(wav_dir)
txt_dir = os.path.join(converted_dir, 'txt')
if (not os.path.exists(txt_dir)):
os.makedirs(txt_dir)
cou... |
def simulate_from_network_attr(arclist_filename, param_func_list, labels, theta, binattr_filename=None, contattr_filename=None, catattr_filename=None, sampler_func=basicALAAMsampler, numSamples=100, iterationInStep=None, burnIn=None):
assert (len(param_func_list) == len(labels))
G = Graph(arclist_filename, bina... |
def _paired_bootstrap_trial(per_doc1, per_doc2):
indices = [random.randint(0, (len(per_doc1) - 1)) for i in range(len(per_doc1))]
pseudo1 = sum((per_doc1[i] for i in indices), Matrix())
pseudo2 = sum((per_doc2[i] for i in indices), Matrix())
return _result_diff(pseudo1, pseudo2) |
def init_cuda_not_in_main_proc_check():
import theano.sandbox.cuda as cuda
if (cuda.use.device_number is not None):
print(('CUDA already initialized in proc %i' % os.getpid()))
return
use_original = cuda.use
def use_wrapped(device, **kwargs):
print(('CUDA.use %s in proc %i' % (de... |
.parametrize('wrapper', [_ArrayAPIWrapper, _NumPyAPIWrapper])
def test_get_namespace_array_api_isdtype(wrapper):
if (wrapper == _ArrayAPIWrapper):
xp_ = pytest.importorskip('numpy.array_api')
xp = _ArrayAPIWrapper(xp_)
else:
xp = _NumPyAPIWrapper()
assert xp.isdtype(xp.float32, xp.fl... |
class CamembertOnnxConfig(OnnxConfig):
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
if (self.task == 'multiple-choice'):
dynamic_axis = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
dynamic_axis = {0: 'batch', 1: 'sequence'}
return OrderedDict([('input_id... |
def get_sparse_lookup_trainer_version(version):
assert (version in {'fp32', 'fp16'}), 'Unexpected version of sparse_lookup layer {0}'.format(version)
return version |
class FakeRegNetVisslWrapper(nn.Module):
def __init__(self, model: nn.Module):
super().__init__()
feature_blocks: List[Tuple[(str, nn.Module)]] = []
feature_blocks.append(('conv1', model.stem))
for (k, v) in model.trunk_output.named_children():
assert k.startswith('block'... |
def batch_llm_generate(template_file: str, prompt_parameter_values: List[dict], engine, max_tokens, temperature, stop_tokens, top_p=0.9, frequency_penalty=0, presence_penalty=0, postprocess=True, max_tries=1, ban_line_break_start=False, max_num_threads=10):
f = partial(_generate, engine=engine, max_tokens=max_token... |
def start_training():
cfg = shared_configs.get_sparse_pretraining_args()
set_random_seed(cfg.seed)
n_gpu = hvd.size()
os.environ['CUDA_VISIBLE_DEVICES'] = str(hvd.local_rank())
device = torch.device('cuda', 0)
torch.cuda.set_device(0)
if (hvd.rank() != 0):
LOGGER.disabled = True
... |
def test_unbox():
def f1(x):
x
return 3.14
growablebuffer = GrowableBuffer(np.int32)
f1(growablebuffer) |
class DummySurvivalRegressor(DummyRegressor):
def __init__(self, strategy='mean', constant=None, quantile=None):
super().__init__(strategy=strategy, constant=constant, quantile=quantile)
if hasattr(DummyRegressor, 'n_features_in_'):
delattr(DummyRegressor, 'n_features_in_')
def fit(s... |
def parse_opt():
parser = argparse.ArgumentParser(description='Regressor Model Training')
parser.add_argument('--epochs', type=int, default=10, help='Number of epochs')
parser.add_argument('--batch_size', type=int, default=32, help='Number of batch size')
parser.add_argument('--alpha', type=float, defau... |
def get_state_embedding_network_args(env, embedding_dim):
network_args = dict(name='state_embedding_network', input_shape=env.observation_space.shape, output_dim=embedding_dim, hidden_sizes=(64, 32), hidden_nonlinearity=get_nonlinearity_for_embedding(), output_nonlinearity=None, batch_normalization=False)
retur... |
def get_name_scope_ops(ops, scope):
if (scope and (scope[(- 1)] == '/')):
scope = scope[:(- 1)]
return filter_ops_from_regex(ops, '^{}(/.*)?$'.format(scope)) |
def test_find_by_tag(testdir):
testdir.make_petstore_test('\(endpoint="/pet/findByTags$")\(max_examples=5, deadline=None)\ndef test_(request, case):\n request.config.HYPOTHESIS_CASES += 1\n assert_list(case.query["tags"])\n assert_requests_call(case)\n')
testdir.assert_petstore() |
def _get_format_from_name(name: str) -> str:
try:
int(name)
return 'numeric'
except ValueError:
return ('alpha-2' if (len(name) == 2) else ('alpha-3' if (len(name) == 3) else 'regex')) |
class TestDistanceRepresentation(TestCase):
def test_call_value_should_be_distance(self):
p1s = tf.constant([[[[1, 2, 3]]]], dtype=tf.float32)
p2s = tf.constant([[[[4, 5, 6]]]], dtype=tf.float32)
distances = representation(p1s, p2s)
self.assertAlmostEqual(float(distances[0][0][0]), m... |
def add_to_total_cost(amount: float):
global total_cost
with thread_lock:
total_cost += amount |
def AFM(linear_feature_columns, dnn_feature_columns, fm_group=DEFAULT_GROUP_NAME, use_attention=True, attention_factor=8, l2_reg_linear=1e-05, l2_reg_embedding=1e-05, l2_reg_att=1e-05, afm_dropout=0, seed=1024, task='binary'):
features = build_input_features((linear_feature_columns + dnn_feature_columns))
input... |
def _triplet_mate_frontalpose_nonmate_top1_probe_mixedpose(n_subjects=32):
np.random.seed(42)
vggface2 = VGGFace2('/proj/janus6/vggface2')
frontalset = [im for im in vggface2.frontalset(n_frontal=1)]
matelist = frontalset[0:n_subjects]
if (n_subjects == 16):
matelist[3] = frontalset[(n_subje... |
def init_np_seed(worker_id):
seed = torch.initial_seed()
np.random.seed(((seed * worker_id) % )) |
def groupwise(iterable: Iterable[_UT0], n: int, fill: bool=True, fillvalue: _UT1=None) -> Iterator[Tuple[(Union[(_UT0, _UT1)], ...)]]:
iterable_copies = []
for (ni, it) in enumerate(itertools.tee(iterable, n)):
if (not fill):
for _ in range(ni):
next(it, None)
if (fil... |
def get_model():
n = 2
depth = ((n * 9) + 2)
n_blocks = (((depth - 2) // 9) - 1)
inputs = layers.Input(shape=(32, 32, 3))
data_augmentation = get_augmentation_layers()
augmented = data_augmentation(inputs)
x = resnet20.stem(augmented)
x = resnet20.learner(x, n_blocks)
outputs = resne... |
def lr_func_steps_with_relative_lrs(cfg, cur_epoch):
ind = get_step_index(cfg, cur_epoch)
return (cfg.SOLVER.LRS[ind] * cfg.SOLVER.BASE_LR) |
def word_tokenize(tokens):
return [token.replace("''", '"').replace('``', '"') for token in nltk.word_tokenize(tokens)] |
def vec_vec_wise_multiplication(q, p):
(q_r, q_i, q_j, q_k) = make_wise_quaternion(q)
qp_r = get_quaternion_wise_mul((q_r * p))
qp_i = get_quaternion_wise_mul((q_i * p))
qp_j = get_quaternion_wise_mul((q_j * p))
qp_k = get_quaternion_wise_mul((q_k * p))
return torch.cat([qp_r, qp_i, qp_j, qp_k],... |
def rebuild_tensor(cls, storage, metadata):
(storage_offset, size, stride, requires_grad) = metadata
t = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)
if (cls == torch.nn.parameter.Parameter):
t = torch.nn.parameter.Parameter(t, requires_grad=requires_grad)
else:
t.... |
def VFE():
os.chdir('./medirl-master/Code/')
VideoDir = './medirl-master/videos/crash-video'
videos = glob.glob((VideoDir + '/*.mp4'))
pathOut = './medirl-master/videos/crash-video/output'
for v in videos:
objectDection(v, VideoDir)
generateFrame(v, VideoDir)
combineCSV(v, Vi... |
class ViT(nn.Module):
def __init__(self, img_size=1024, patch_size=16, in_chans=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, drop_path_rate=0.0, init_values=None, norm_pre_=False, norm_post=True, norm_layer=nn.LayerNorm, act_layer=nn.GELU, swiglu=False, use_abs_pos=True, use_rel_pos=False... |
def test_assert_file_exists():
with tempfile.TemporaryDirectory(dir=TEST_WORKING_DIR) as test_dir:
filename = os.path.join(test_dir, 'test.txt')
with pytest.raises(FileNotFoundError):
common.assert_file_exists(filename)
with open(filename, 'w', encoding='utf-8') as fout:
... |
def test():
pytest.importorskip('pyarrow')
this = ak.str.to_categorical(['one', 'two', 'one', 'three', 'one', 'four'])
assert ak.is_categorical(this)
this_packed = ak.to_packed(this)
assert (this_packed.type == this.type)
assert ak.all((ak.categories(this_packed) == ak.categories(this)))
thi... |
_to_string
class TemplateNotFound(IOError, LookupError, TemplateError):
message = None
def __init__(self, name, message=None):
IOError.__init__(self, name)
if (message is None):
from .runtime import Undefined
if isinstance(name, Undefined):
name._fail_with... |
def from_pretty_midi_time_signature(time_signature: PmTimeSignature) -> TimeSignature:
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=RuntimeWarning)
return TimeSignature(time=float(time_signature.time), numerator=time_signature.numerator, denominator=time_signature.denom... |
def resample_folder(input_folder, output_folder, fs, regex):
files = get_all_files(input_folder, match_and=[regex])
for f in tqdm.tqdm(files):
(audio, fs) = torchaudio.sox_effects.apply_effects_file(f, [['rate', str(fs)]])
audio = (audio / torch.max(torch.abs(audio), dim=(- 1), keepdim=True)[0])... |
class PAN(nn.Module):
def __init__(self, cfg):
super(PAN, self).__init__()
self.backbone = build_backbone(cfg.MODEL_BACKBONE)
self.backbone_layers = self.backbone.get_layers()
input_channel = 1024
self.aspp = ASPP(dim_in=input_channel, dim_out=cfg.MODEL_ASPP_OUTDIM, resolutio... |
def search(keyword, per_search=100, offset=0):
payload = {'count': per_search, 'recordEvent': 'false', 'q': keyword, 'fq': 'attribute:categories:domain:string=="Industrial";binaryNames=exists=true', 'showBinaryMetadata': 'true', 'showAttributes': 'false', 'showBinaryAttributes': 'true', 'offset': offset, 'contentTy... |
def train_epoch_with_interactions(interaction_batches, params, model, randomize=True):
if randomize:
random.shuffle(interaction_batches)
progbar = get_progressbar('train ', len(interaction_batches))
progbar.start()
loss_sum = 0.0
for (i, interaction_batch) in enumerate(interaction_batche... |
class BaseYOLODetect(BaseDetDetect):
def __init__(self, subtype='yolov6_s', cfg=None, num_classes=80, in_channels=None, channels=None, out_channels=None, num_blocks=None, depthwise=False, conv_cfg=None, norm_cfg=dict(type='BN', requires_grad=True), act_cfg=dict(type='ReLU')):
super(BaseYOLODetect, self).__i... |
def collect_vocabs(all_instances):
all_src_words = Counter()
all_tgt_words = Counter()
all_edge_types = Counter()
for (sent1, sent2) in all_instances:
all_src_words.update(sent1.graph['backbone_sequence'])
all_tgt_words.update(sent2.graph['backbone_sequence'])
for edge in sent1.g... |
def PercentDegree_PDirNet(Graph, Threshold=0):
return _snap.PercentDegree_PDirNet(Graph, Threshold) |
class MyScriptModuleWithRRefs(torch.jit.ScriptModule):
def __init__(self, dst_worker):
super().__init__()
self.rrefs = []
for _ in range(4):
self.rrefs.append(rpc_return_rref(dst_worker))
.script_method
def forward(self) -> Tensor:
res_tensor = torch.ones(2, 2)
... |
def compute_f1(a_gold, a_pred):
gold_toks = get_tokens(a_gold)
pred_toks = get_tokens(a_pred)
common = (collections.Counter(gold_toks) & collections.Counter(pred_toks))
num_same = sum(common.values())
if ((len(gold_toks) == 0) or (len(pred_toks) == 0)):
return int((gold_toks == pred_toks))
... |
def register_Ns3MultiModelSpectrumChannel_methods(root_module, cls):
cls.add_constructor([param('ns3::MultiModelSpectrumChannel const &', 'arg0')])
cls.add_constructor([])
cls.add_method('AddRx', 'void', [param('ns3::Ptr< ns3::SpectrumPhy >', 'phy')], is_virtual=True)
cls.add_method('GetDevice', 'ns3::P... |
def main(file_path):
(pred_s0, pred_s1, test_label_s0, test_label_s1) = test_model(file_path)
r = []
acc0 = metrics.accuracy_score(test_label_s0, pred_s0)
acc1 = metrics.accuracy_score(test_label_s1, pred_s1)
print('SVM:', 's0', (acc0 * 100), 's1', (acc1 * 100), 'mean', (((acc0 + acc1) / 2) * 100)) |
def make_mujoco_environment(task: str, use_envpool: bool=False, use_vec_env=False, num_envs: int=2):
env_wrappers = []
if use_envpool:
env = envpool.make(task, env_type='gym', num_envs=num_envs)
env_wrappers.append(BatchEnvWrapper)
elif use_vec_env:
env = make_vec_env(task, n_envs=nu... |
def test_NCF():
model_name = 'NCF'
(x, y, user_feature_columns, item_feature_columns) = get_xy_fd_ncf(False)
model = NCF(user_feature_columns, item_feature_columns)
model.compile('adam', 'binary_crossentropy')
model.fit(x, y, batch_size=10, epochs=2, validation_split=0.5) |
class PermutoFunction(torch.autograd.Function):
def forward(ctx, q_in, features):
q_out = permuto_cpp.forward(q_in, features)[0]
ctx.save_for_backward(features)
return q_out
def backward(ctx, grad_q_out):
feature_saved = ctx.saved_tensors[0]
grad_q_back = permuto_cpp.back... |
class CellAssignModule(BaseModuleClass):
def __init__(self, n_genes: int, rho: torch.Tensor, basis_means: torch.Tensor, b_g_0: Optional[torch.Tensor]=None, random_b_g_0: bool=True, n_batch: int=0, n_cats_per_cov: Optional[Iterable[int]]=None, n_continuous_cov: int=0):
super().__init__()
self.n_genes... |
def _apply_commands(custom_options, ebase, images_dir):
for (key, val) in custom_options.items():
if key.startswith('command'):
cmd = custom_options[key]
subprocess.run(cmd.split()).check_returncode()
if key.startswith('image'):
shutil.copy(val, os.path.join(image... |
def _seg_35():
return [(13270, 'M', u'mol'), (13271, 'M', u'ph'), (13272, 'X'), (13273, 'M', u'ppm'), (13274, 'M', u'pr'), (13275, 'M', u'sr'), (13276, 'M', u'sv'), (13277, 'M', u'wb'), (13278, 'M', u'vm'), (13279, 'M', u'am'), (13280, 'M', u'1'), (13281, 'M', u'2'), (13282, 'M', u'3'), (13283, 'M', u'4'), (13284, ... |
def test_significance(estimate: float, simulations: List) -> float:
mean_refute_value = np.mean(simulations)
std_dev_refute_values = np.std(simulations)
z_score = ((estimate - mean_refute_value) / std_dev_refute_values)
if (z_score > 0):
p_value = (1 - st.norm.cdf(z_score))
else:
p_v... |
class PunktSentenceSplitter():
def __init__(self, language='en', punkt_data_path=None):
self.lang2datapath = {'en': 'tokenizers/punkt/english.pickle'}
self.log = log.get_global_console_logger()
try:
import nltk.data
except ImportError:
self.log.error("Cannot i... |
class SMORE(AbstractFormulation):
def new_max_link_util(cls, num_paths, out=sys.stdout):
return cls(objective=Objective.MIN_MAX_LINK_UTIL, num_paths=num_paths, DEBUG=True, VERBOSE=False, out=out)
def new_total_flow(cls, num_paths, out=sys.stdout):
return cls(objective=Objective.TOTAL_FLOW, num_p... |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
... |
def load_generated_package(name: str, path: T.Openable, evict: bool=True) -> T.Any:
if (not evict):
if (name.split('.')[0] == 'sym'):
raise ValueError('Attempted to hotload a generated package called `sym` - see `help(load_generated_package)` for more information')
return _load_generated... |
def tbLogWritter(summaryInfo):
createDir(summaryInfo['Path'])
writer = SummaryWriter((summaryInfo['Path'] + 'epoch_{}'.format(summaryInfo['Epoch'])))
for k in summaryInfo:
if ('Image' in k):
writer.add_image(k, torchvision.utils.make_grid(summaryInfo[k]), summaryInfo['Step'])
eli... |
def test_dace_unroll():
def tounroll(A: dace.float64[1]):
for i in dace.unroll(range(1, 4)):
A[0] += (i * i)
(src_ast, fname, _, _) = astutils.function_to_ast(tounroll.f)
lu = LoopUnroller(tounroll.global_vars, fname, None)
unrolled = lu.visit(src_ast)
assert (len(unrolled.body[0... |
def warm_start_model(checkpoint_path, model, ignore_layers):
assert os.path.isfile(checkpoint_path)
print(f"Warm starting model from checkpoint '{checkpoint_path}'")
checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
model_dict = checkpoint_dict['state_dict']
if (len(ignore_layers) > ... |
.skip(reason='Shared function')
def run_quota_tests(tests):
for test in tests:
(quota_limits, expected_vm_types, expected_n_instances) = test
with open(QUOTA_FILE, 'w') as f:
f.write(json.dumps(quota_limits, indent=2))
transfer_config = TransferConfig()
planner = Multicas... |
def fibonacci_sphere(N: int, *, dtype=np.float32) -> Tuple[(np.ndarray, np.ndarray)]:
gr = ((np.sqrt(5.0) + 1.0) / 2.0)
ga = ((2 - gr) * (2 * np.pi))
i = np.arange(1, (N + 1), dtype=dtype)
lat = np.arcsin(((- 1) + ((2 * i) / (N + 1))))
lon = np.remainder((ga * i), (2 * np.pi))
return (lat, lon) |
def test_dont_blow_up_without_validation_set():
with tempfile.TemporaryDirectory() as tmpdir:
config = LMDatasetConfig(train_urls=['kaa'], validation_urls=[], cache_dir=tmpdir)
assert (config.validation_set(10) is None) |
class TemporalDifferenceModel(TorchRLAlgorithm, metaclass=abc.ABCMeta):
def __init__(self, max_tau=10, max_tau_for_rollout=None, epoch_max_tau_schedule=None, vectorized=True, cycle_taus_for_rollout=True, dense_rewards=False, finite_horizon=True, tau_sample_strategy='uniform', goal_reached_epsilon=0.001, terminate_w... |
def cythonize_extensions(extension):
_check_cython_version()
from Cython.Build import cythonize
basic_check_build()
sklearn._OPENMP_SUPPORTED = check_openmp_support()
n_jobs = 1
with contextlib.suppress(ImportError):
import joblib
n_jobs = joblib.cpu_count()
cython_enable_deb... |
def get_2hop_relations_from_2entities(entity0: str, entity1: str):
query = ((((((('\n PREFIX rdf: < PREFIX rdfs: < PREFIX : < SELECT distinct ?x0 as ?r0 ?y as ?r1 WHERE {\n ?x1 ?x0 ' + ':') + entity0) + ' .\n') + '?x1 ?y ') + ':') + entity1) + ' .\n ... |
_nplike
class Numpy(ArrayModuleNumpyLike['NDArray']):
is_eager: Final = True
supports_structured_dtypes: Final = True
def __init__(self):
self._module = numpy
def ma(self):
return self._module.ma
def char(self):
return self._module.char
def ndarray(self):
return s... |
def test_case45():
url = (brokerIp + '/ngsi-ld/v1/entities/urn:ngsi-ld:Vehicle:B990')
headers = {'Content-Type': 'application/ld+json', 'Accept': 'application/ld+json'}
r = requests.get(url, headers=headers)
print(r.content)
resp_content = r.content
resInJson = resp_content.decode('utf8').replac... |
_clip_fps_by_default
def find_video_period(clip, fps=None, tmin=0.3):
frame = (lambda t: clip.get_frame(t).flatten())
tt = np.arange(tmin, clip.duration, (1.0 / fps))[1:]
ref = frame(0)
corrs = [np.corrcoef(ref, frame(t))[(0, 1)] for t in tt]
return tt[np.argmax(corrs)] |
def reduce_dict(input_dict, average=True):
world_size = comm.world_size
if (world_size < 2):
return input_dict
with torch.no_grad():
names = []
values = []
for k in sorted(input_dict.keys()):
names.append(k)
values.append(input_dict[k])
values ... |
def get_depth_gasda(dataset, file, phase=None):
if (not phase):
raise NotImplementedError('phase value is none!!')
depth = cv2.imread(str(file), flags=cv2.IMREAD_ANYDEPTH).astype(np.float32)
depth = cv2.resize(depth, tuple(dataset.labels_size), interpolation=cv2.INTER_NEAREST)
if (phase == 'test... |
def filter_recursive(x_or_iterable):
if isinstance(x_or_iterable, list):
new_items = []
for sub_elem in x_or_iterable:
filtered_sub_elem = filter_recursive(sub_elem)
if ((filtered_sub_elem is not None) and (not (isinstance(filtered_sub_elem, list) and (len(filtered_sub_elem) ... |
def match(speech, mode):
global label, lastLabel
for entry in os.scandir('Keypoints'):
if entry.is_file():
if (os.path.splitext(entry)[1] == '.json'):
filePlotName = entry.name
try:
js = json.loads(open(('Keypoints\\' + filePlotName)).read())
for items in ... |
def test_check_symmetric():
arr_sym = np.array([[0, 1], [1, 2]])
arr_bad = np.ones(2)
arr_asym = np.array([[0, 2], [0, 2]])
test_arrays = {'dense': arr_asym, 'dok': sp.dok_matrix(arr_asym), 'csr': sp.csr_matrix(arr_asym), 'csc': sp.csc_matrix(arr_asym), 'coo': sp.coo_matrix(arr_asym), 'lil': sp.lil_matr... |
def register_Ns3SequentialRandomVariable_methods(root_module, cls):
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_constructor([])
cls.add_method('GetMin', 'double', [], is_const=True)
cls.add_method('GetMax', 'double', [], is_const=True)
cls.add_method('GetIncrement', 'ns3::... |
class InceptionE(nn.Module):
def __init__(self, input_channels):
super().__init__()
self.branch1x1 = BasicConv2d(input_channels, 320, kernel_size=1)
self.branch3x3_1 = BasicConv2d(input_channels, 384, kernel_size=1)
self.branch3x3_2a = BasicConv2d(384, 384, kernel_size=(1, 3), paddin... |
def _onnx_unsupported(op_name):
raise RuntimeError('Unsupported: ONNX export of operator {}. Please open a bug to request ONNX export support for the missing operator.'.format(op_name)) |
def test_false_str_estimator() -> None:
with pytest.raises(ValueError, match='.*Please provide a string in*'):
mapie_cal = MapieCalibrator(calibrator='not_estimator')
mapie_cal.fit(X, y) |
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
zip_filename = (base_name + '.zip')
archive_dir = os.path.dirname(base_name)
if (not os.path.exists(archive_dir)):
if (logger is not None):
logger.info('creating %s', archive_dir)
if (not dry_run):
... |
class MMFToPLCheckpointUpdater():
def __init__(self):
pass
def update_checkpoint(self, checkpoint: Dict[(str, Any)], model: torch.nn.Module) -> None:
if is_model_only_checkpoint(checkpoint):
self._update_model_checkpoint(checkpoint=checkpoint, model=model)
return
... |
class Unexpectedness(Metric):
def _get_enriched_recommendations(self, recommendations: SparkDataFrame, base_recommendations: SparkDataFrame) -> SparkDataFrame:
sorted_by_score_recommendations = self._get_items_list_per_user(recommendations)
sorted_by_score_base_recommendations = self._get_items_list... |
def build_argparse():
parser = argparse.ArgumentParser()
parser.add_argument('--txt_file', type=str, help='Input plaintext file')
parser.add_argument('--label_file', type=str, default=None, help='Character-level label file')
parser.add_argument('--mwt_json_file', type=str, default=None, help='JSON file ... |
class KVT_Dataset(Dataset):
def __init__(self, data_path, split, sr, duration, num_chunks):
self.data_path = data_path
self.split = split
self.sr = sr
self.input_length = int((sr * duration))
self.num_chunks = num_chunks
self.get_split()
self.get_file_list()
... |
def test_hashtag_container(tweet_segmenter):
original_tweet = 'esto es #UnaGenialidad'
(hashtag_container, word_segmenter_output) = tweet_segmenter.build_hashtag_container([original_tweet])
assert all([(hashtag_container.hashtags == [['UnaGenialidad']]), (hashtag_container.hashtag_set == ['UnaGenialidad']),... |
class TableSemanticParsingExample(Example):
def __init__(self, dataset_id, db_name, db_id):
super().__init__(dataset_id)
self.db_name = db_name
self.db_id = db_id
self.schema_features = None
self.schema_M = None
self.M = None
self.gt_tables_list = []
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.