code stringlengths 101 5.91M |
|---|
def mlp_gaussian_policy(x, act_dim, hidden, layers):
net = nn(x, ([hidden] * (layers + 1)))
mu = tf.compat.v1.layers.dense(net, act_dim, activation=None)
log_std = tf.compat.v1.layers.dense(net, act_dim, activation=tf.tanh)
log_std = (LOG_STD_MIN + ((0.5 * (LOG_STD_MAX - LOG_STD_MIN)) * (log_std + 1)))
... |
def run_training(model: nn.Module, optimizer: Optimizer, criterion: nn.Module, device: torch.device, train_loader: DataLoader, epochs: Tuple[(int, ...)], learning_rates: Tuple[(float, ...)], dev_loader: Optional[DataLoader]=None, test_loader: Optional[DataLoader]=None, batch_callback: Optional[Callable]=None, fp16: boo... |
def unpickle(file):
fp = open(file, 'rb')
if (sys.version_info.major == 2):
data = pickle.load(fp)
elif (sys.version_info.major == 3):
data = pickle.load(fp, encoding='latin-1')
fp.close()
return data |
def test_double_fault_ones_zeros(example_diversity_ones_zeros):
(y, y_pred_ones, y_pred_zeros) = example_diversity_ones_zeros
df = double_fault(y, y_pred_ones, y_pred_zeros)
assert (df == np.full((5,), 0)).all() |
def get_dataset(args):
(text_proc, raw_data) = get_vocab_and_sentences(args.dataset_file, args.max_sentence_len)
train_dataset = ANetDataset(args.feature_root, args.train_data_folder, args.slide_window_size, args.dur_file, args.kernel_list, text_proc, raw_data, args.pos_thresh, args.neg_thresh, args.stride_fact... |
class _ConstantPadNd(Module):
__constants__ = ['padding', 'value']
value: float
padding: Sequence[int]
def __init__(self, value: float) -> None:
super(_ConstantPadNd, self).__init__()
self.value = value
def forward(self, input: Tensor) -> Tensor:
return F.pad(input, self.padd... |
def run(keyword, title_matching=False):
per_search = 100
init_results = search(keyword, per_search, offset=0)
total = init_results['total']
total_search = (total // per_search)
insert_search_log(keyword, total)
output_dir = f'{dw_path}/{keyword}'
make_dir(output_dir)
keyword_id = get_key... |
_torch
class ScheduleInitTest(unittest.TestCase):
m = (nn.Linear(50, 50) if is_torch_available() else None)
optimizer = (AdamW(m.parameters(), lr=10.0) if is_torch_available() else None)
num_steps = 10
def assertListAlmostEqual(self, list1, list2, tol, msg=None):
self.assertEqual(len(list1), len... |
def rel_positions_grid(grid_sizes):
tensors = []
for size in grid_sizes:
tensors.append(torch.linspace((- 1), 1, steps=size))
relpos_grid = torch.stack(torch.meshgrid(*tensors), dim=(- 0))
return relpos_grid |
class ParasolJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, parasol.experiment.Experiment):
return obj.to_dict()
if isinstance(obj, deepx.core.Node):
o = {'__bytes__': base64.b64encode(pickle.dumps(obj)).decode('ascii'), 'readable': str(obj)}
... |
class Aggregator(AggregatorBase):
def __init__(self, storage, server, modelservice, control):
super().__init__(storage, server, modelservice, control)
self.name = 'fedavg'
def combine_models(self, helper=None, time_window=180, max_nr_models=100, delete_models=True):
data = {}
dat... |
def score_function(config, base_args, orig_dir=''):
os.chdir(orig_dir)
kwargs = copy.deepcopy(base_args)
kwargs.update(config)
pl.utilities.seed.seed_everything(kwargs.get('seed'))
dataset_name = kwargs['dataset_name']
data_dir = (Path('data/spec_datasets') / dataset_name)
labels = (data_dir... |
class LossWrapper(torch.nn.Module):
def __init__(self, threshold, DTU_filter=False):
super().__init__()
gpu = torch.device('cuda')
self.threshold = threshold
self.loss = torch.nn.BCELoss()
self.maxpool = torch.nn.MaxPool2d(kernel_size=3, stride=1, padding=1).to(gpu)
s... |
class FlaxRobertaPreLayerNormPreTrainedModel(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
class Options():
def __init__(self):
self.args = []
self.kvs = {}
self.tag_str = None
def set(self, *args, **kwargs):
for a in args:
self.args.append(a)
for (k, v) in kwargs.items():
self.kvs[k] = v
return self
def remove(self, *args):
... |
class Inception(nn.Module):
def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes):
super(Inception, self).__init__()
self.b1 = nn.Sequential(nn.Conv2d(in_planes, n1x1, kernel_size=1), nn.BatchNorm2d(n1x1), nn.LeakyReLU(True))
self.b2 = nn.Sequential(nn.Conv2d(in_plan... |
class S2TTransformerEncoder(FairseqEncoder):
def __init__(self, args):
super().__init__(None)
self.encoder_freezing_updates = args.encoder_freezing_updates
self.num_updates = 0
self.dropout_module = FairseqDropout(p=args.dropout, module_name=self.__class__.__name__)
self.embe... |
class Server(object):
def __init__(self, args, model, device, confidence_estimators, estimator_filenames, ned_model):
self.args = args
self.device = device
self.numericalizer = model.numericalizer
self.model = model
self.confidence_estimators = confidence_estimators
s... |
class LearningSwitch(object):
def __init__(self, connection, transparent):
self.connection = connection
self.transparent = transparent
self.macToPort = {}
connection.addListeners(self)
self.hold_down_expired = (_flood_delay == 0)
log.debug('Initializing LearningSwitch... |
def __create_source_from_ast(module_body: ast.stmt) -> str:
return ast.unparse(ast.fix_missing_locations(ast.Module(body=[module_body], type_ignores=[]))) |
def keypoint_losses(kps_pred, keypoint_locations_int32, keypoint_weights, keypoint_loss_normalizer=None):
device_id = kps_pred.get_device()
kps_target = Variable(torch.from_numpy(keypoint_locations_int32.astype('int64'))).cuda(device_id)
keypoint_weights = Variable(torch.from_numpy(keypoint_weights)).cuda(d... |
class AutoContrast(BaseAugmentation):
def _augment(self, img):
return ImageOps.autocontrast(img) |
def seconds_to_tokens(sec, sr, prior, chunk_size):
tokens = ((sec * hps.sr) // prior.raw_to_tokens)
tokens = (((tokens // chunk_size) + 1) * chunk_size)
assert (tokens <= prior.n_ctx), 'Choose a shorter generation length to stay within the top prior context'
return tokens |
def main():
vis_dir = sys.argv[(- 1)]
print('visualizing {}'.format(vis_dir))
vis_dir = sys.argv[(- 1)]
obj_files = glob(os.path.join(vis_dir, '*/*.obj'))
obj_files.sort()
for obj_file in obj_files:
print(obj_file)
for (camera_id, camera) in enumerate(cameras):
(obj_d... |
class JBluesDiluteBlackBody(ProcessingPlasmaProperty):
outputs = ('j_blues',)
latex_name = 'J_{\\textrm{blue}}'
def calculate(lines, nu, t_rad, w):
j_blues = (w * intensity_black_body(nu.values[np.newaxis].T, t_rad))
j_blues = pd.DataFrame(j_blues, index=lines.index, columns=np.arange(len(t_... |
(resources={'machine': 1})
def ray_allgather(args_dict, notification_address, world_size, world_rank, object_size):
object_id = ray.ObjectID(str((args_dict['seed'] + world_rank)).encode().rjust(20, b'\x00'))
array = np.random.rand((object_size // 4)).astype(np.float32)
ray.worker.global_worker.put_object(ar... |
_module()
class AOTBlockNeck(nn.Module):
def __init__(self, in_channels=256, dilation_rates=(1, 2, 4, 8), num_aotblock=8, act_cfg=dict(type='ReLU'), **kwargs):
super().__init__()
self.dilation_rates = list(dilation_rates)
self.model = nn.Sequential(*[AOTBlock(in_channels=in_channels, dilatio... |
def _get_sumo_net(cfg_file):
cfg_file = os.path.join(os.getcwd(), cfg_file)
tree = ET.parse(cfg_file)
tag = tree.find('//net-file')
if (tag is None):
return None
net_file = os.path.join(os.path.dirname(cfg_file), tag.get('value'))
logging.debug('Reading net file: %s', net_file)
sumo_... |
def pretty_time(orig_seconds):
(days, seconds) = divmod(round(orig_seconds), 86400)
(hours, seconds) = divmod(seconds, 3600)
(minutes, seconds) = divmod(seconds, 60)
out = []
if (days > 0):
out.append(f'{days}d')
if (hours > 0):
out.append(f'{hours}h')
if (minutes > 0):
... |
def wrap_fp16_model(model):
if ((TORCH_VERSION == 'parrots') or (digit_version(TORCH_VERSION) < digit_version('1.6.0'))):
model.half()
patch_norm_fp32(model)
for m in model.modules():
if hasattr(m, 'fp16_enabled'):
m.fp16_enabled = True |
def kldiv(x, xp, k=3, base=2):
assert (k <= (len(x) - 1)), 'Set k smaller than num. samples - 1'
assert (k <= (len(xp) - 1)), 'Set k smaller than num. samples - 1'
assert (len(x[0]) == len(xp[0])), 'Two distributions must have same dim.'
(x, xp) = to_np_array(x, xp)
d = len(x[0])
n = len(x)
... |
.parametrize('knn_methods', knn_methods)
def test_lca(knn_methods):
(pool_classifiers, X_dsel, y_dsel, X_test, y_test) = setup_classifiers()
lca = LCA(pool_classifiers, knn_classifier=knn_methods)
lca.fit(X_dsel, y_dsel)
assert np.isclose(lca.score(X_test, y_test), 0.) |
def DistributedFairseqModel(args, model):
assert isinstance(model, nn.Module)
if (args.ddp_backend == 'c10d'):
ddp_class = nn.parallel.DistributedDataParallel
init_kwargs = dict(module=model, device_ids=[args.device_id], output_device=args.device_id, broadcast_buffers=False, bucket_cap_mb=args.b... |
def process_line(line, data_folder, language, accented_letters):
mp3_path = ((data_folder + '/clips/') + line.split('\t')[1])
file_name = mp3_path.split('.')[(- 2)].split('/')[(- 1)]
spk_id = line.split('\t')[0]
snt_id = file_name
if (torchaudio.get_audio_backend() != 'sox_io'):
logger.warni... |
def _replace_ref_nodes_with_names(model: models.Model, model_list: List[optplan.ProblemGraphNode]) -> None:
def process_field(model: models.Model, child_model: models.Model) -> str:
if isinstance(child_model, str):
return child_model
ind = model_list.index(child_model)
return mod... |
def generate_task23(dataset, output, sampling_rate):
np.random.seed(42)
windowlen = (10 * sampling_rate)
labels = []
for idx in tqdm(range(len(dataset)), total=len(dataset)):
(waveforms, metadata) = dataset.get_sample(idx)
if ('split' in metadata):
trace_split = metadata['spl... |
def pad_same(x, k, s, d=(1, 1), value=0):
(ih, iw) = x.size()[(- 2):]
(pad_h, pad_w) = (get_same_padding(ih, k[0], s[0], d[0]), get_same_padding(iw, k[1], s[1], d[1]))
if ((pad_h > 0) or (pad_w > 0)):
x = F.pad(x, [(pad_w // 2), (pad_w - (pad_w // 2)), (pad_h // 2), (pad_h - (pad_h // 2))], value=va... |
def save_file(data, path, verbose=False):
dir = os.path.dirname(path)
if (not os.path.isdir(dir)):
os.makedirs(dir)
if verbose:
print('Saving: {}'.format(path))
(_, ext) = os.path.splitext(path)
if (ext == '.pkl'):
with open(path, 'wb') as f:
pickle.dump(data, f, ... |
def resnetv2sn152(**kwargs):
model = ResNetV2SN(Bottleneck, [3, 8, 36, 3], **kwargs)
return model |
(plot=False, auto=True)
def auto_td3_benchmarks():
td3_env_ids = [env_id for env_id in MuJoCo1M_ENV_SET if (env_id != 'Reacher-v2')]
iterate_experiments(td3_garage_tf, td3_env_ids) |
class XLMProphetNetTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['attention_mask']
def __init__(self, vocab_file, bos_token='[SEP]', eos... |
def test_nonzero_offset_fromarrow_ArrowRecordBatch_2():
a = pyarrow.RecordBatch.from_arrays([pyarrow.array([1.1, 2.2, 3.3, 4.4, 5.5]), pyarrow.array([[1, 2, 3], [], [], [4, 5], [6]])], ['a', 'b'])
assert (to_list(ak._connect.pyarrow.handle_arrow(a[2:])) == [{'a': 3.3, 'b': []}, {'a': 4.4, 'b': [4, 5]}, {'a': 5.... |
class AverageMeter():
def __init__(self):
self.reset()
def reset(self):
self._sum = 0
self._count = 0
def update(self, val, n=1):
self._sum += (val * n)
self._count += n
def value(self):
if (self._count == 0):
return 0
return (self._sum... |
class Controller(object):
def __init__(self, scenario, sessions, chat_id=None, allow_cross_talk=False, session_names=(None, None)):
self.lock = Lock()
self.scenario = scenario
self.sessions = sessions
self.session_names = session_names
self.chat_id = chat_id
assert (l... |
class MultiHeadAttentionV2(nn.Module):
def __init__(self, input_size, output_size, num_heads, weight_norm=False, groups=1, dropout=0, causal=False, add_bias_kv=False):
super(MultiHeadAttentionV2, self).__init__()
assert ((input_size % num_heads) == 0)
wn_func = (wn if weight_norm else (lambd... |
class SuperRunMode(Enum):
FullModel = 'fullmodel'
Candidate = 'candidate'
Default = 'fullmodel' |
(**njit_dict_no_parallel)
def update_line_estimators(estimators, r_packet, cur_line_id, distance_trace, time_explosion):
if (not nc.ENABLE_FULL_RELATIVITY):
energy = calc_packet_energy(r_packet, distance_trace, time_explosion)
else:
energy = calc_packet_energy_full_relativity(r_packet)
estim... |
class PolynomialDecayLRScheduleConfig(FairseqDataclass):
warmup_updates: int = field(default=0, metadata={'help': 'warmup the learning rate linearly for the first N updates'})
warmup_ratio: float = field(default=0, metadata={'help': 'warmup ratio'})
force_anneal: Optional[int] = field(default=None, metadata... |
def tf_efficientnet_lite3(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet_lite('tf_efficientnet_lite3', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)
return model |
def wigner_9j(j_1, j_2, j_3, j_4, j_5, j_6, j_7, j_8, j_9, prec=None):
imin = 0
imax = int(min((j_1 + j_9), (j_2 + j_6), (j_4 + j_8)))
sumres = 0
for kk in range(imin, (imax + 1)):
sumres = (sumres + (((((2 * kk) + 1) * racah(j_1, j_2, j_9, j_6, j_3, kk, prec)) * racah(j_4, j_6, j_8, j_2, j_5, k... |
def __filter_nodes(network, ip_address_hint, country_code_hint):
all_nodes = [{'id': node_id, **node} for (node_id, node) in network.nodes(data=True)]
if ((ip_address_hint is not None) and (not ip_address_hint.is_global)):
logging.debug(f'Ignoring non-global address {ip_address_hint}')
ip_addres... |
def register_Ns3DsrDsrOptionPadn_methods(root_module, cls):
cls.add_constructor([param('ns3::dsr::DsrOptionPadn const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetOptionNumber', 'uint8_t', [], is_const=True, is_virtual=True)
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
... |
def _test_vae(vae_trainer, epoch, replay_buffer, vae_save_period=1, uniform_dataset=None):
save_imgs = ((epoch % vae_save_period) == 0)
log_fit_skew_stats = (replay_buffer._prioritize_vae_samples and (uniform_dataset is not None))
if (uniform_dataset is not None):
replay_buffer.log_loss_under_unifor... |
def read_32(fobj, start_length, size):
(start, length) = start_length
fobj.seek(start)
pixel_size = ((size[0] * size[2]), (size[1] * size[2]))
sizesq = (pixel_size[0] * pixel_size[1])
if (length == (sizesq * 3)):
indata = fobj.read(length)
im = Image.frombuffer('RGB', pixel_size, ind... |
def _sample_indices(n_to_sample, n_available_tasks, with_replacement):
if with_replacement:
return np.random.randint(n_available_tasks, size=n_to_sample)
else:
blocks = []
for _ in range(math.ceil((n_to_sample / n_available_tasks))):
s = np.arange(n_available_tasks)
... |
def stdize(data, eps=1e-06):
return ((data - np.mean(data, axis=0)) / (np.std(data, axis=0) + eps)) |
(message='scipy.misc.extend_notes_in_docstring is deprecated in Scipy 1.3.0')
def extend_notes_in_docstring(cls, notes):
return _ld.extend_notes_in_docstring(cls, notes) |
def decode_arch_def(arch_def, depth_multiplier=1.0, depth_trunc='ceil', experts_multiplier=1, fix_first_last=False):
arch_args = []
for (stage_idx, block_strings) in enumerate(arch_def):
assert isinstance(block_strings, list)
stage_args = []
repeats = []
for block_str in block_st... |
def modularity_matrix(adj_matrix: np.ndarray) -> np.ndarray:
k_i = np.expand_dims(adj_matrix.sum(axis=1), axis=1)
k_j = k_i.T
norm = (1 / k_i.sum())
K = (norm * np.matmul(k_i, k_j))
return (norm * (adj_matrix - K)) |
class DoxygenTypeSub(supermod.DoxygenType):
def __init__(self, version=None, compounddef=None):
supermod.DoxygenType.__init__(self, version, compounddef)
def find(self, details):
return self.compounddef.find(details) |
class StatisticsAggregator():
def __init__(self, functions: dict=None):
super().__init__()
if (functions is None):
functions = {'MEAN': np.mean, 'STD': np.std}
self.functions = functions
def calculate(self, results: typing.List[evaluator.Result]) -> typing.List[evaluator.Resu... |
def main(args):
set_global_seed(args.seed)
tasks = args.tasks.split('.')
for task in tasks:
if (('n' in task) and (args.geo in ['box', 'vec'])):
assert False, 'Q2B and GQE cannot handle queries with negation'
if (args.evaluate_union == 'DM'):
assert (args.geo == 'beta'), "onl... |
def mock_xml_file():
root = ElementTree.Element('text')
root.text = plain_text_str
tree = ElementTree.ElementTree(root)
with tempfile.NamedTemporaryFile(mode='wb', delete=False, suffix='.xml') as f:
tree.write(f)
return f.name |
def get_edge_feature(point_cloud, nn_idx, k=20):
og_batch_size = point_cloud.get_shape().as_list()[0]
point_cloud = tf.squeeze(point_cloud)
if (og_batch_size == 1):
point_cloud = tf.expand_dims(point_cloud, 0)
point_cloud_central = point_cloud
point_cloud_shape = point_cloud.get_shape()
... |
def go(runs):
for run in runs:
for key in run.keys():
go.__globals__[key] = run[key]
print('')
print('CONFIG: ', run)
time_layer(numEpochs, batchSize, inputPlanes, inputSize, outputPlanes, filterSize) |
def extract_acos(dloader, transform, save_path, split):
for (bidx, batch) in tqdm.tqdm(enumerate(dloader, start=1), total=len(dloader)):
(wav, uttname, _) = batch
uttname = os.path.splitext(os.path.basename(uttname[0]))[0]
aco = transform(wav.view((- 1)))
for k in aco.keys():
... |
def test_case32():
url = (brokerIp + '/NGSI9/registerContext')
headers = {'Content-Type': 'appliction/json', 'fiware-service': 'openiot', 'fiware-servicepath': '/'}
r = requests.post(url, data=json.dumps(data_ngsi10.subdata52), headers=headers)
url = (brokerIp + '/ngsi10/updateContext')
headers = {'... |
def to_fast_pickable(l):
if (not l):
return [[], []]
f = l[0]
f = f.set()
r = f.ring()
one = r.one().navigation()
zero = r.zero().navigation()
nodes = set()
def find_navs(nav):
if ((nav not in nodes) and (not nav.constant())):
nodes.add(nav)
find_n... |
def pred_fn(pred_rng, params, batch, model):
return model.apply({'params': params}, batch['images'], training=False).argmax(axis=(- 1)) |
class DefaultQuant(QuantizeHandler):
def convert(self, quantizer, node):
assert self.all_nodes
root_module = quantizer.modules['']
return quantize_node(root_module, quantizer.quantized_graph, node, quantizer.activation_post_process_map[node.name]) |
def split_chinese_sentence(text: str) -> List[str]:
sentences = []
quote_mark_count = 0
sentence = ''
for (i, c) in enumerate(text):
sentence += c
if (c in {'', ''}):
sentences.append(sentence)
sentence = ''
elif (c in {'', '!', '?', '!', '?'}):
... |
class NRTRDataset_hdf5(Dataset):
def __init__(self, hdf5_file, transform=None):
self.data = dict()
self._transform = transform
self.hdf5_file = hdf5_file
def __len__(self):
with h5py.File(self.hdf5_file, 'r') as data:
lens = len(data['label'])
return lens
... |
class FourierMatDict(SpectralMatDict):
def __missing__(self, key):
measure = (1 if (len(key) == 2) else key[2])
c = functools.partial(FourierMatrix, measure=measure)
self[key] = c
return c |
class Net_mnist(nn.Module):
def __init__(self):
super(Net_mnist, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5, 1)
self.conv2 = nn.Conv2d(20, 50, 5, 1)
self.fc1 = nn.Linear(((4 * 4) * 50), 500)
self.fc2 = nn.Linear(500, 10)
def forward(self, x):
x = F.relu(self... |
class VGGBackbone(object):
def __init__(self, configer):
self.configer = configer
def __call__(self):
arch = self.configer.sub_arch
if (arch in ['vgg19_bn', 'vgg19']):
arch_net = VGG(arch, self.configer.pretrained_backbone)
else:
raise Exception('Architect... |
def test(model, queryloader, galleryloader, pool, use_gpu, ranks=[1, 5, 10, 20], return_distmat=False):
batch_time = AverageMeter()
model.eval()
with torch.no_grad():
(qf, q_pids, q_camids) = ([], [], [])
for (batch_idx, (imgs, pids, camids)) in enumerate(queryloader):
if use_gpu... |
class CoefficientOfDetermination(NumpyArrayMetric):
def __init__(self, metric: str='R2'):
super().__init__(metric)
def calculate(self):
y_true = self.reference.flatten()
y_predicted = self.prediction.flatten()
sse = sum(((y_true - y_predicted) ** 2))
tse = ((len(y_true) -... |
def _sympysage_polynomial_ring(self):
base_ring = self.domain._sage_()
variables = ','.join(map(str, self.gens))
return base_ring[variables] |
def _install_wheel(name, wheel_zip, wheel_path, scheme, pycompile=True, warn_script_location=True, direct_url=None, requested=False):
(info_dir, metadata) = parse_wheel(wheel_zip, name)
if wheel_root_is_purelib(metadata):
lib_dir = scheme.purelib
else:
lib_dir = scheme.platlib
installed ... |
(plot=False, auto=True)
def auto_ppo_benchmarks():
iterate_experiments(ppo_garage_pytorch, MuJoCo1M_ENV_SET)
iterate_experiments(ppo_garage_tf, MuJoCo1M_ENV_SET) |
def register_Ns3FlowProbeFlowStats_methods(root_module, cls):
cls.add_constructor([param('ns3::FlowProbe::FlowStats const &', 'arg0')])
cls.add_constructor([])
cls.add_instance_attribute('bytes', 'uint64_t', is_const=False)
cls.add_instance_attribute('bytesDropped', 'std::vector< unsigned long >', is_co... |
def aggregated_data_from_experiments(experiments, contains_err=False):
experiment_labels = list(experiments.keys())
protocol_labels = list(experiments[list(experiments.keys())[0]].keys())
metric_labels = []
for label in experiments[experiment_labels[0]][protocol_labels[0]].keys():
if (('mean' in... |
def _normalize_H(H, level):
H = [(ZZ(h) % level) for h in H]
for h in H:
if (gcd(h, level) > 1):
raise ArithmeticError(('The generators %s must be units modulo %s' % (H, level)))
H = {u for u in H if (u > 1)}
final_H = set()
for h in H:
inv_h = h.inverse_mod(level)
... |
class AggregatorGRPCServer(aggregator_pb2_grpc.AggregatorServicer):
def __init__(self, aggregator, agg_port, tls=True, disable_client_auth=False, root_certificate=None, certificate=None, private_key=None, **kwargs):
self.aggregator = aggregator
self.uri = f'[::]:{agg_port}'
self.tls = tls
... |
.service(data='Content-Type error', status=400, method='POST', path='/reports/upload/')
.openapi_version('3.0')
def test_unknown_error_on_upload(cli, schema_url, service, snapshot_cli):
assert (cli.run(schema_url, 'my-api', f'--schemathesis-io-token={service.token}', f'--schemathesis-io-url={service.base_url}', '--... |
class MM(Enum):
MM_NORMAL = 1
MM_WRQ = 2
MM_WRQ_RELU = 3
MM_NN = 4
MM_NT = 5
MM_TT = 6
UNKNOWN = (- 1) |
('/register', methods=['POST'])
def register():
username = request.form['username']
password = request.form['password']
db = MySQLdb.connect(host='localhost', user='root', passwd='root', db='user')
c = db.cursor()
c.execute(("SELECT username FROM user WHERE username = '%s'" % username))
rows = c... |
class TruePositive(ConfusionMatrixMetric):
def __init__(self, metric: str='TP'):
super().__init__(metric)
def calculate(self):
return self.confusion_matrix.tp |
class BitEncode(Model):
def __init__(self, bit_size=1, *, output_shape=None, input_shape=None, name=None, bin_dtype=bb.DType.FP32, real_dtype=bb.DType.FP32, core_model=None):
if (output_shape is None):
output_shape = []
if (core_model is None):
core_creator = search_core_mode... |
def _quota_exceeded(response: 'requests.models.Response') -> bool:
return ('Google Drive - Quota exceeded' in response.text) |
def register_Ns3GbrQosInformation_methods(root_module, cls):
cls.add_constructor([param('ns3::GbrQosInformation const &', 'arg0')])
cls.add_constructor([])
cls.add_instance_attribute('gbrDl', 'uint64_t', is_const=False)
cls.add_instance_attribute('gbrUl', 'uint64_t', is_const=False)
cls.add_instance... |
class ReplicationPad1d(_ReplicationPadNd):
padding: _size_2_t
def __init__(self, padding: _size_2_t) -> None:
super(ReplicationPad1d, self).__init__()
self.padding = _pair(padding) |
def create_pipeline_configuration(DEBUG=False, batch_size=8):
config = {'batch_dim': 0, 'depth': 10000, 'basic_blocks': (StatelessEmbedding, T5LayerNorm, Dropout, T5Block, Linear), 'model_inputs': {'attention_mask': {'shape': torch.Size([8, 320]), 'dtype': torch.int64, 'is_batched': True, 'used_by': [0, 8]}, 'decod... |
class domainAdaptationDataSet(data.Dataset):
def __init__(self, root, images_list_path, scale_factor, num_scales, curr_scale, set, get_image_label=False):
self.root = root
if (images_list_path != None):
self.images_list_file = osp.join(images_list_path, ('%s.txt' % set))
self... |
class LightHamHead(BaseSegHead):
cfg = {'t': ([64, 160, 256], 256, 256, 0.1), 's': ([128, 320, 512], 256, 256, 0.1), 'b': ([128, 320, 512], 512, 512, 0.1), 'l': ([128, 320, 512], 1024, 1024, 0.1)}
def __init__(self, ham_channels=256, dropout_ratio=0.1, ham_kwargs=dict(), conv_cfg=None, norm_cfg=dict(type='GN', ... |
_builder('snli_ve')
class SNLIVisualEntailmentBuilder(BaseDatasetBuilder):
train_dataset_cls = SNLIVisualEntialmentDataset
eval_dataset_cls = SNLIVisualEntialmentDataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/snli_ve/defaults.yaml'} |
class VietorisRipsComplex(SimplicialComplex):
def __init__(self, points, epsilon, labels=None, distfcn=distance.euclidean):
super(VietorisRipsComplex, self).__init__()
self.pts = points
self.labels = (list(range(len(self.pts))) if ((labels is None) or (len(labels) != len(self.pts))) else lab... |
def _create_var(name: str, value_expr: TfExpression) -> TfExpression:
assert (not _finalized)
name_id = name.replace('/', '_')
v = tf.cast(value_expr, _dtype)
if v.shape.is_fully_defined():
size = np.prod(v.shape.as_list())
size_expr = tf.constant(size, dtype=_dtype)
else:
si... |
class ShuffleBlock(nn.Module):
def __init__(self, groups):
super(ShuffleBlock, self).__init__()
self.groups = groups
def forward(self, x):
(N, C, H, W) = x.size()
g = self.groups
return x.view(N, g, (C / g), H, W).permute(0, 2, 1, 3, 4).contiguous().view(N, C, H, W) |
def stem_token(token, resources):
from snips_nlu_utils import normalize
if token.stemmed_value:
return token.stemmed_value
if (not token.normalized_value):
token.normalized_value = normalize(token.value)
token.stemmed_value = _stem(token.normalized_value, resources)
return token.stem... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.