code stringlengths 101 5.91M |
|---|
class PriorBox(object):
def __init__(self, config):
super(PriorBox, self).__init__()
self.frame_size = config['frame_size']
self.num_priors = len(config['frame_work']['aspect_ratios'])
self.variance = (config['frame_work']['variance'] or [0.1])
self.feature_maps = config['fra... |
def _nbool_correspond_ft_tf(u, v, w=None):
if ((u.dtype == v.dtype == bool) and (w is None)):
not_u = (~ u)
not_v = (~ v)
nft = (not_u & v).sum()
ntf = (u & not_v).sum()
else:
dtype = np.result_type(int, u.dtype, v.dtype)
u = u.astype(dtype)
v = v.astype(d... |
class LNNP(LightningModule):
def __init__(self, hparams, prior_model=None, mean=None, std=None):
super(LNNP, self).__init__()
self.save_hyperparameters(hparams)
if self.hparams.load_model:
self.model = load_model(self.hparams.load_model, args=self.hparams)
elif self.hpara... |
def create_model(model_name: str, pretrained: str='', precision: str='fp32', device: torch.device=torch.device('cpu'), force_quick_gelu: bool=False):
model_name = model_name.replace('/', '-')
if (model_name in _MODEL_CONFIGS):
logging.info(f'Loading {model_name} model config.')
model_cfg = deepc... |
class CycleGANDAGModel(BaseModel):
def modify_commandline_options(parser, is_train=True):
parser.set_defaults(no_dropout=True)
if is_train:
parser.add_argument('--lambda_A', type=float, default=10.0, help='weight for cycle loss (A -> B -> A)')
parser.add_argument('--lambda_B'... |
class FlavaTextConfig(PretrainedConfig):
model_type = 'flava_text_model'
def __init__(self, vocab_size: int=30522, type_vocab_size: int=2, max_position_embeddings: int=512, position_embedding_type: str='absolute', hidden_size: int=768, num_hidden_layers: int=12, num_attention_heads: int=12, intermediate_size: i... |
def parallel_forward(model, *args, **kwargs):
device_ids = range(min(torch.cuda.device_count(), args[0].size(0)))
return parallel.data_parallel(model, args, device_ids=device_ids, module_kwargs=kwargs) |
def annotate_instance(image, mask, color, text_label, font_size=0.5, draw_bbox=True):
assert (image.shape[:2] == mask.shape), 'Shape mismatch between image {} and mask {}'.format(image.shape, mask.shape)
color = tuple(color)
overlayed_image = overlay_mask_on_image(image, mask, mask_color=color)
bbox = b... |
class Vector():
def __init__(self, pa, pb):
self.x = (int(pb.x) - int(pa.x))
self.y = (int(pb.y) - int(pa.y))
def __str__(self):
return ((str(self.x) + ',') + str(self.y)) |
def main():
configs = collect_configurations()
train(configs)
statistics_file = eval(configs)
make_plots(statistics_file) |
class Tardis(QtWidgets.QMainWindow):
def __init__(self, tablemodel, config=None, atom_data=None, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.path = os.path.join(tardis.__path__[0], 'gui', 'images')
self.mode = 'passive'
if (config is not None):
self.mo... |
def register_all_pascal_voc(root):
SPLITS = [('voc_2007_trainval', 'VOC2007', 'trainval'), ('voc_2007_train', 'VOC2007', 'train'), ('voc_2007_val', 'VOC2007', 'val'), ('voc_2007_test', 'VOC2007', 'test'), ('voc_2012_trainval', 'VOC2012', 'trainval'), ('voc_2012_train', 'VOC2012', 'train'), ('voc_2012_val', 'VOC2012... |
def get_rank():
if (not torch.distributed.is_initialized()):
return 0
return torch.distributed.get_rank() |
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--redd_location', type=str, default=None)
parser.add_argument('--ukdale_location', type=str, default=None)
parser.add_argument('--refit_location', type=str, default=None)
parser.add_argument('--export_root', type=str, default='r... |
class SparseMap3D(genpy.Message):
_md5sum = 'a20102f0b3a02e95070dab4140b78fb5'
_type = 'multi_map_server/SparseMap3D'
_has_header = True
_full_text = "Header header\nnav_msgs/MapMetaData info\nVerticalOccupancyGridList[] lists\n\n\n\nMSG: std_msgs/Header\n# Standard metadata for higher-level stamped dat... |
def plot(net_name, load_path, plot_path):
print('')
print(net_name)
print(load_path)
print(plot_path)
start = time.time()
args.net = net_name
net = get_model(args, device)
if (torch.cuda.device_count() > 1):
net.module.load_state_dict(torch.load(load_path))
else:
net.... |
def _get_func_info(func_module):
(module_name, func_name) = func_module.rsplit('.', 1)
module = import_module(module_name)
func = getattr(module, func_name)
func_sig = signature(func)
func_params = [p.name for p in func_sig.parameters.values() if (p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD))]
... |
.parametrize('current_line_length', (0, 20))
.parametrize('operations_processed, percentage', ((0, '[ 0%]'), (1, '[100%]')))
def test_display_percentage(capsys, execution_context, after_execution, swagger_20, current_line_length, operations_processed, percentage):
execution_context.current_line_length = current_li... |
class InfNanRemoveLogitsProcessor(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def make_plots(statistics_file):
print('\n Make Plots')
with open(statistics_file, 'r') as f:
stats = json.load(f)
output_folder = os.path.split(statistics_file)[0]
FILETYPE = 'eps'
latex = io.StringIO()
LATEX_SHOW_STD = False
numStepsizes = len(STEPSIZES)
numTFs = len(CONFIG_FIL... |
class VarValueRenaming():
def __init__(self):
self.new_var_nos = []
self.new_values = []
self.new_sizes = []
self.new_var_count = 0
self.num_removed_values = 0
def dump(self):
old_var_count = len(self.new_var_nos)
print(('variable count: %d => %d' % (old_v... |
class NormalTranslationDataset(datasets.TranslationDataset):
def __init__(self, path, exts, fields, load_dataset=False, prefix='', **kwargs):
if (not isinstance(fields[0], (tuple, list))):
fields = [('src', fields[0]), ('trg', fields[1])]
(src_path, trg_path) = tuple((os.path.expanduser(... |
def test_sdca_squared(bin_train_data):
(X_bin, y_bin) = bin_train_data
clf = SDCAClassifier(loss='squared', random_state=0)
clf.fit(X_bin, y_bin)
assert (not hasattr(clf, 'predict_proba'))
assert (clf.score(X_bin, y_bin) == 1.0) |
class NONLOCALBAN(BAN):
def __init__(self, in_channels=256, out_channels=256, cls_out_channels=2):
super(NONLOCALBAN, self).__init__()
self.head = CARHead(in_channels, out_channels, cls_out_channels)
def forward(self, z_f, x_f):
features = non_local_xcorr(z_f, x_f)
(cls, reg) = s... |
class DMA():
def __init__(self, dirpath, dmaType):
self.dirpath = dirpath
self.dmaType = dmaType
self.chipArgs = dict()
self.linecount = 0
self.actual_corenum = 0
self.regList = []
self.total_time_dict = {'start': [], 'end': []}
self.dma_cycle_list = [... |
def generate_doc(name, specs):
tab = (' ' * 4)
doc = ['- :py:func:`~scipy.special.{}`::\n'.format(name)]
for spec in specs:
(incodes, outcodes) = spec.split('->')
incodes = incodes.split('*')
intypes = list(map((lambda x: CY_TYPES[x]), incodes[0]))
if (len(incodes) > 1):
... |
_datapipe('collate')
class CollatorIterDataPipe(MapperIterDataPipe):
def __init__(self, datapipe: IterDataPipe, collate_fn: Callable=_utils.collate.default_collate, fn_args: Optional[Tuple]=None, fn_kwargs: Optional[Dict]=None) -> None:
super().__init__(datapipe, fn=collate_fn, fn_args=fn_args, fn_kwargs=fn... |
def hmdb(omninet, videos, targets=None, mode='train', return_str_preds=False, num_steps=1):
batch_size = videos.shape[0]
omninet.reset(batch_size)
omninet.encode_videos(videos, domain='IMAGE')
if (mode in ['train', 'val']):
predictions = omninet.decode_from_targets('HMDB', targets=targets)
e... |
def relative_order_from_ring_generators(gens, check_is_integral=True, check_rank=True, is_maximal=None, allow_subfield=False, is_maximal_at=()):
if (check_is_integral and (not each_is_integral(gens))):
raise ValueError('each generator must be integral')
gens = Sequence(gens)
K = gens.universe()
... |
def train():
x_train = load_data()
with tf.Session(config=TF_CONFIG) as sess:
gan = GAN(sess, MODEL_CONFIG)
gan.init_all()
gan.load_latest(EXP_CONFIG['first_stage_dir'])
refine_gan = RefineGAN(sess, MODEL_CONFIG, gan)
refine_gan.init_all()
if (EXP_CONFIG['pretrain... |
def enable_power_on_by_usb_plug_in(bledevice):
asyncio.get_event_loop().run_until_complete(aenable_power_on_by_usb_plug_in(bledevice)) |
def setup_environment():
custom_module_path = os.environ.get('TORCH_DETECTRON_ENV_MODULE')
if custom_module_path:
setup_custom_environment(custom_module_path)
else:
pass |
('/api/spellcheck', methods=['POST', 'GET'])
def do_spellcheck():
result = {}
if (request.method == 'POST'):
text = request.json.get('text')
else:
text = request.args.get('text')
text = text.strip()
words = regex.split('(\\s+)', text)
result = {}
for windex in range(len(words... |
def main(args, config):
utils.init_distributed_mode(args)
device = torch.device(args.gpu)
seed = (args.seed + utils.get_rank())
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
cudnn.benchmark = True
cudnn.deterministic = True
print('Creating dataset')
datasets = [c... |
def filename_to_imagebind_modality(fn: str) -> str:
from imagebind.models.imagebind_model import ModalityType
(_, ext) = os.path.splitext(fn)
if (ext in {'.wav'}):
return ModalityType.AUDIO
elif (ext in {'.jpg', '.png', '.jpeg'}):
return ModalityType.VISION
else:
return Modal... |
class GradedModules(GradedModulesCategory):
class ParentMethods():
pass
class ElementMethods():
pass |
def test_ArrayBuilder_of_complex():
def add_a_complex(builder, complex):
builder.complex(complex)
return builder
builder = add_a_complex(ak.ArrayBuilder(), (1.0 + 0.1j))
out = builder.snapshot()
assert (out.to_list() == [(1.0 + 0.1j)])
builder = add_a_complex(builder, (2.0 + 0.2j))
... |
def get_latest_price_for_worker_type_aws(worker_type, current_time, per_instance_type_spot_prices):
if (worker_type == 'v100'):
instance_type = 'p3.2xlarge'
elif (worker_type == 'p100'):
instance_type = 'p2.xlarge'
elif (worker_type == 'k80'):
instance_type = 'p2.xlarge'
timestam... |
class HLOptions(OptionsEnv):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _after_choice(self):
self.obs = {'obs': np.copy(self.s), 'mask': np.copy(self.m)}
self.r = 0
self.steps = 0
def _after_step(self):
self.r += ((self.discount ** self... |
class LogisticRegressionMaskOutput(mx.operator.CustomOp):
def __init__(self, ignore_label):
super(LogisticRegressionMaskOutput, self).__init__()
self.ignore_label = ignore_label
def forward(self, is_train, req, in_data, out_data, aux):
self.assign(out_data[0], req[0], (1.0 / (1.0 + nd.ex... |
def mask_tokens(inputs, tokenizer, args):
labels = inputs.clone()
masked_indices = torch.bernoulli(torch.full(labels.shape, args.mlm_probability)).bool()
labels[(~ masked_indices)] = (- 1)
indices_replaced = (torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices)
inputs[indices_repl... |
def random_normal(dims: Sequence[Dim], *, dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None, mean: Optional[Union[(int, float, Tensor)]]=0.0, stddev: Optional[Union[(int, float, Tensor)]]=1.0, seed: Optional[Union[(int, Sequence[int], numpy.ndarray)]]... |
def stream(stream):
if (stream is None):
(yield)
return
prev_stream = current_stream()
torch._C._cuda_setStream(stream._cdata)
try:
(yield)
finally:
torch._C._cuda_setStream(prev_stream._cdata) |
def deserialize_model(package, strict=False):
klass = package['class']
if strict:
model = klass(*package['args'], **package['kwargs'])
else:
sig = inspect.signature(klass)
kw = package['kwargs']
for key in list(kw):
if (key not in sig.parameters):
... |
class MSDataLoader(DataLoader):
def __init__(self, args, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, collate_fn=default_collate, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None):
super(MSDataLoader, self).__init__(dataset, batch_size=batch_size, shuffle=shuffle,... |
class BiLSTMCRF(BaseModel):
def __init__(self, embed, num_classes, num_layers=1, hidden_size=100, dropout=0.5, target_vocab=None):
super().__init__()
self.embed = get_embeddings(embed)
if (num_layers > 1):
self.lstm = LSTM(self.embed.embedding_dim, num_layers=num_layers, hidden_s... |
def COS(data_A, data_B):
print('AVG ', np.average(data_A), np.average(data_B))
print('STD ', np.std(data_A), np.std(data_B))
print('MEDIAN ', np.median(data_A), np.median(data_B))
print('MIN ', np.min(data_A), np.min(data_B))
print('MAX ', np.max(data_A), np.max(data_B)) |
.parametrize('n_actions, len_list, base_classifier, description', valid_input_of_ipw_learner_init)
def test_ipw_learner_init_using_valid_inputs(n_actions, len_list, base_classifier, description):
ipw_learner = IPWLearner(n_actions=n_actions, len_list=len_list, base_classifier=base_classifier)
assert (ipw_learne... |
.usefixtures('spark')
()
def gt_spark(spark):
return spark.createDataFrame(gt_data, schema=['uid', 'iid']) |
def wrap_layout(content: T, behavior: (Mapping | None)=None, highlevel: bool=True, like: Any=None, allow_other: bool=False, attrs: (Mapping | None)=None) -> ((T | Array) | HighLevelRecord):
import awkward.highlevel
from awkward.contents import Content
from awkward.record import Record
assert (isinstance... |
def test_downsample():
from topaz.commands import downsample
parser = downsample.add_arguments() |
class CacheCommand(Command):
ignore_require_venv = True
usage = '\n %prog dir\n %prog info\n %prog list [<pattern>]\n %prog remove <pattern>\n %prog purge\n '
def run(self, options, args):
handlers = {'dir': self.get_cache_dir, 'info': self.get_cache_info, 'list... |
def test_cannot_read_outside_length_of_dotfiles():
(train, _) = load_toy_cancer()
bkg = Background(modes=train.modes)
clf = BoostedRDNClassifier(target='cancer', background=bkg)
clf.fit(train)
for test_input in [(- 10), (- 5), (- 1), 10]:
with pytest.raises(IndexError):
_ = expor... |
def schema_encoding(preds_hidden, preds_len, pwords_hidden, pwords_len):
masked_preds_hidden = seq_hidden_masking_before_pooling(seq_hidden_input=preds_hidden, len_input=preds_len)
masked_pwords_hidden = seq_hidden_masking_before_pooling(seq_hidden_input=pwords_hidden, len_input=pwords_len)
masked_merge_hid... |
def load_data(data_downsample, data_dirs, validate_only, render_only, **kwargs):
od: Dict[(str, Any)] = {}
if (not validate_only):
od.update(init_tr_data(data_downsample, data_dirs, **kwargs))
else:
od.update(tr_loader=None, tr_dset=None)
test_split = ('render' if render_only else 'test'... |
def compute_line_coverage(trace: ExecutionTrace, subject_properties: SubjectProperties) -> float:
existing = len(subject_properties.existing_lines)
if (existing == 0):
coverage = 1.0
else:
covered = len(trace.covered_line_ids)
coverage = (covered / existing)
assert (0.0 <= covera... |
def parse_arguments():
ap = argparse.ArgumentParser()
ap.add_argument('-c', '--classifier', required=True, help='Using `cls` token or GAP for the vit representation.')
ap.add_argument('-p', '--position', required=True, help='Learned or sincos for positional embedding.')
ap.add_argument('-m', '--use-mp',... |
def evaluate(args, model, fold, output_file=None):
(dataloader, examples, features, processor) = load_examples(args, fold)
label_list = processor.get_labels()
all_predictions = defaultdict(dict)
for batch in tqdm(dataloader, desc='Eval'):
model.eval()
inputs = {k: v.to(args.device) for (... |
class TrainTransform():
def __init__(self, size):
self.size = size
self.augment = Compose([ConvertFromInts(), PhotometricDistort(), Expand(), RandomSampleCrop(), RandomFlipping(), ToPercentCoords(), Resize(self.size), Normalize(), ToTensor()])
def __call__(self, img, boxes, labels):
retu... |
def stochasticApproximation(G, Aobs, changestats_func_list, theta0, Zobs, sampler_func=basicALAAMsampler):
epsilon = np.finfo(float).eps
n = len(changestats_func_list)
A = np.copy(Aobs)
theta = np.copy(theta0)
iterationInStep = (10 * G.numNodes())
phase1steps = (7 + (3 * n))
numSubphases = 5... |
class cifar100(cifar10):
base_folder = 'cifar-100-python'
url = '
filename = 'cifar-100-python.tar.gz'
tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'
train_list = [['train', '16019d7e3df5f24257cddd939b257f8d']]
test_list = [['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc']]
meta = {'filename': 'met... |
class ResumeZhProcessor(QueryNERProcessor):
def get_labels(self):
return ['ORG', 'LOC', 'NAME', 'RACE', 'TITLE', 'EDU', 'PRO', 'CONT', 'O'] |
class ByteMaskedForm(ByteMaskedMeta[Form], Form):
_content: Form
def __init__(self, mask, content, valid_when, *, parameters=None, form_key=None):
if (not isinstance(mask, str)):
raise TypeError(f"{type(self).__name__} 'mask' must be of type str, not {mask!r}")
if (not isinstance(con... |
class TestFromrecords(object):
def test_fromrecords(self):
r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]], names='col1,col2,col3')
assert_equal(r[0].item(), (456, 'dbe', 1.2))
assert_equal(r['col1'].dtype.kind, 'i')
if (sys.version_info[0] >= 3):
assert_equal(... |
class Data():
def __init__(self, args, mode='train'):
if (mode == 'train'):
data_file = args.train_data_file
elif (mode == 'test'):
data_file = args.test_data_file
elif (mode == 'dev'):
data_file = args.dev_data_file
elif (mode == 'test_noise'):
... |
def register_Ns3RraaWifiManager_methods(root_module, cls):
cls.add_constructor([param('ns3::RraaWifiManager const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_method('SetupMac', 'void', [param('ns3::Ptr< ns3::WifiMac > const', 'mac')], is_v... |
class TestTVAE():
('ctgan.synthesizers.tvae._loss_function')
('ctgan.synthesizers.tvae.tqdm')
def test_fit_verbose(self, tqdm_mock, loss_func_mock):
epochs = 1
def mock_iter():
for i in range(epochs):
(yield i)
def mock_add(a, b):
mock_loss = M... |
def load_examples_hyp(path, args):
hypotheses = [' neutral', ' partisan']
label2synonym = {0: [' neutral', ' fair', ' objective'], 1: [' partisan', ' biased', ' unfair']}
prompt = '\n neutral or partisan? Answer:'
icl_str = ''
if (args.k_shot > 0):
train_examples = []
train_path = pa... |
_on_pypy
.skipif((not hasattr(m, 'NCVirt')), reason='NCVirt test broken on ICPC')
def test_move_support():
class NCVirtExt(m.NCVirt):
def get_noncopyable(self, a, b):
nc = m.NonCopyable((a * a), (b * b))
return nc
def get_movable(self, a, b):
self.movable = m.Mova... |
class Normalizer(mrl.Module):
def __init__(self, normalizer):
super().__init__('state_normalizer', required_agent_modules=[], locals=locals())
self.normalizer = normalizer
self.lazy_load = None
def __call__(self, *args, **kwargs):
if self.training:
self.normalizer.rea... |
class Scatter(BenchmarkItem):
name = 'scatter'
def __init__(self):
self._items = {'scatter': True, 'gether': False} |
def test_fit_predict_on_pipeline_without_fit_predict():
scaler = StandardScaler()
pca = PCA(svd_solver='full')
pipe = Pipeline([('scaler', scaler), ('pca', pca)])
error_regex = "'PCA' object has no attribute 'fit_predict'"
with raises(AttributeError, match=error_regex):
getattr(pipe, 'fit_pr... |
def JvecAdjointTest_1D(sigmaHalf, formulation='PrimSec'):
frequencies = np.logspace(0, 4, 21)
receivers_list = [nsem.receivers.PointNaturalSource(component='real'), nsem.receivers.PointNaturalSource(component='imag'), nsem.receivers.PointNaturalSource(component='app_res'), nsem.receivers.PointNaturalSource(comp... |
def main(args):
mp.set_start_method('spawn')
args.dist_url = f'tcp://{args.node}:{args.port}'
print('Using url {}'.format(args.dist_url))
ngpus_per_node = torch.cuda.device_count()
if args.multiprocessing_distributed:
args.world_size = ngpus_per_node
mp.spawn(main_worker, nprocs=ngpu... |
class BanditPolicySimulator():
policy: Any
environment: BanditEnvironmentSimulator = None
reward_round_lookup: defaultdict = None
_selected_actions: List[int] = None
_obtained_rewards: List[int] = None
_ground_truth_rewards: List[np.ndarray] = None
_contexts: List[np.ndarray] = None
tota... |
def load_checkpoint(filepath, device):
assert os.path.isfile(filepath)
print(f"Loading '{filepath}'")
checkpoint_dict = torch.load(filepath, map_location=device)
print('Complete.')
return checkpoint_dict |
(Output('forecasting-select-features', 'options'), Input('forecasting-select-features-parent', 'n_clicks'), [State('forecasting-select-file', 'value'), State('forecasting-select-target', 'value'), State('forecasting-select-exog', 'value')])
def select_features(n_clicks, filename, target_name, exog_names):
options =... |
def savitzky_golay(y, window_size, order, deriv=0, rate=1):
from math import factorial
try:
window_size = np.abs(np.int(window_size))
order = np.abs(np.int(order))
except ValueError:
raise ValueError('window_size and order have to be of type int')
if (((window_size % 2) != 1) or ... |
def DuadicCodeOddPair(F, S1, S2):
from sage.misc.stopgap import stopgap
stopgap('The function DuadicCodeOddPair has several issues which may cause wrong results', 25896)
from .cyclic_code import CyclicCode
n = ((len(S1) + len(S2)) + 1)
if (not _is_a_splitting(S1, S2, n)):
raise TypeError(('%... |
class ModuleDict(BaseModule, nn.ModuleDict):
def __init__(self, modules: Optional[dict]=None, init_cfg: Optional[dict]=None):
BaseModule.__init__(self, init_cfg)
nn.ModuleDict.__init__(self, modules) |
def petersen_graph() -> StellarGraph:
nxg = nx.petersen_graph()
return StellarGraph.from_networkx(nxg, node_features=node_features()) |
class Seq2SeqQuestionAnsweringModelOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
start_logits: torch.FloatTensor = None
end_logits: torch.FloatTensor = None
past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
... |
class RGNNConv(ChainableGCNConv):
def __init__(self, mean='soft_k_medoid', mean_kwargs: Dict[(str, Any)]=dict(k=64, temperature=1.0, with_weight_correction=True), **kwargs):
super().__init__(**kwargs)
self._mean = ROBUST_MEANS[mean]
self._mean_kwargs = mean_kwargs
def message_and_aggrega... |
class EvalHook(_EvalHook):
greater_keys = ['mIoU', 'mAcc', 'aAcc']
def __init__(self, *args, by_epoch=False, efficient_test=False, pre_eval=False, **kwargs):
super().__init__(*args, by_epoch=by_epoch, **kwargs)
self.pre_eval = pre_eval
self.latest_results = None
if efficient_test... |
def load_json_dataset(fpath, tokenizer, tag_fmt='IO', contiguous_only=False):
(documents, entities) = ([], {})
fopen = (gzip.open if (fpath.split('.')[(- 1)] == 'gz') else open)
with fopen(fpath, 'rb') as fp:
for line in fp:
d = json.loads(line)
doc = Document(d['name'], [Sen... |
class Args():
concat = 1
crop_size = 216
dis_norm = None
dis_scale = 3
dis_spectral_norm = False
dataroot = 'data'
gpu = 1
input_dim = 3
nThreads = 4
num_domains = 5
nz = 8
resume = 'gan_weights.pth' |
def augment(image, label):
img = tf.image.rot90(image)
img = tf.image.flip_left_right(img)
return (img, label) |
class MediumPayloadCustomMode2():
SIZE = 34
def from_reader(reader: _ResponseReader):
assert (reader.remaining() >= MediumPayloadCustomMode2.SIZE)
rv = MediumPayloadCustomMode2()
rv.timestamp = Timestamp.from_reader(reader)
rv.euler = EulerAngles.from_reader(reader)
rv.fr... |
class PerColHeader(object):
def __init__(self, header):
self.percentile_0 = header[0]
self.percentile_25 = header[1]
self.percentile_75 = header[2]
self.percentile_100 = header[3] |
def unpack_sim_data(result):
headers = ['time', 'x', 'y', 'z', 'xdot', 'ydot', 'zdot', 'qx', 'qy', 'qz', 'qw', 'wx', 'wy', 'wz', 'windx', 'windy', 'windz', 'r1', 'r2', 'r3', 'r4', 'xdes', 'ydes', 'zdes', 'xdotdes', 'ydotdes', 'zdotdes', 'xddotdes', 'yddotdes', 'zddotdes', 'xdddotdes', 'ydddotdes', 'zdddotdes', 'xdd... |
def test_profiler(cl):
frame = cl.io.Input([NamedVideoStream(cl, 'test1')])
hist = cl.ops.Histogram(frame=frame)
ghist = cl.streams.Gather(hist, [[0]])
output_op = cl.io.Output(ghist, [NamedStream(cl, '_ignore')])
time_start = time.time()
job_id = cl.run(output_op, PerfParams.estimate(), show_pr... |
def proper_subterms(term):
seen = set()
return itertools.chain.from_iterable((subterms(a, seen) for a in term.args())) |
def _validate_state(state: State):
assert (state.env_id in get_args(EnvId))
assert (state.current_player.dtype == jnp.int32), state.current_player.dtype
assert (state.terminated.dtype == jnp.bool_), state.terminated.dtype
assert (state.rewards.dtype == jnp.float32), state.rewards.dtype
assert (state... |
def check_version(new_version):
if (version.parse(__version__) < version.parse(new_version)):
print("A new version of the GENO solver is available. You should consider upgrading it via 'pip install --upgrade genosolver'.") |
def filter_logdirs(logdirs: list, beta: Optional[float]=None, group: Optional[str]=None, nlf: Optional[int]=None, merge_directions: Optional[bool]=None, framework: Optional[str]=None, latvolume: Optional[list[int]]=None) -> list[os.PathLike]:
matches = []
for logdir in logdirs:
if _match_beta(logdir, be... |
def handle_failed_request(api_type: str, response: Dict):
error_message: str = f'AI21 {api_type} API error -'
if ('detail' in response):
error_message += f" Detail: {response['detail']}"
if ('Error' in response):
error_message += f" Error: {response['Error']}"
raise AI21RequestError(erro... |
def main_test():
kwargs = {'num_workers': 1, 'pin_memory': True}
test_loader = torch.utils.data.DataLoader(datasets.MNIST('./data', train=False, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])), batch_size=args.test_batch_size, shuffle=True, **kwargs)
model ... |
def register_Ns3LteRrcSapReestabUeIdentity_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteRrcSap::ReestabUeIdentity const &', 'arg0')])
cls.add_instance_attribute('cRnti', 'uint16_t', is_const=False)
cls.add_instance_attribute('physCellId', 'uint16_t', is_const=Fa... |
def load_and_cache_examples(args, tokenizer, evaluate=False):
file_path = (args.eval_data_file if evaluate else args.train_data_file)
if args.line_by_line:
return LineByLineTextDataset(tokenizer, args, file_path=file_path, block_size=args.block_size)
else:
return TextDataset(tokenizer, args,... |
def test_shapes():
seed = 300
np.random.seed(seed)
dp_encoder = DirectlyParameterizedNormalDiag(num_data, latent_dim)
assert np.all((tf.shape(dp_encoder.means) == (num_data, latent_dim)))
assert np.all((tf.shape(dp_encoder.stds) == (num_data, latent_dim)))
np.random.seed(seed)
expected_means... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.