code stringlengths 101 5.91M |
|---|
class RandomSubsetTrainingSampler(TrainingSampler):
def __init__(self, size: int, subset_ratio: float, shuffle: bool=True, seed_shuffle: Optional[int]=None, seed_subset: Optional[int]=None):
super().__init__(size=size, shuffle=shuffle, seed=seed_shuffle)
assert (0.0 < subset_ratio <= 1.0)
se... |
def validate(a_l, b_l, c_l, a_u, b_u, c_u, x_minus, x_plus, y_minus, y_plus, verify_and_modify_all=False, max_iter=100, plot=False, eps=1e-05, print_info=True):
original_shape = c_l.shape
a_l_new = a_l.view((- 1))
b_l_new = b_l.view((- 1))
c_l_new = c_l.view((- 1))
a_u_new = a_u.view((- 1))
b_u_... |
def prepare_dataset(training_file: str, K: int=None):
sessions = read_sessions_from_training_file(training_file, K)
(x, y) = prepare_training_data(sessions)
return {'X': x, 'y': y} |
_registry
class MSETuneStrategy(TuneStrategy):
def __init__(self, model, conf, q_dataloader=None, q_func=None, eval_func=None, eval_dataloader=None, eval_metric=None, resume=None, q_hooks=None):
super().__init__(model=model, conf=conf, q_dataloader=q_dataloader, q_func=q_func, eval_func=eval_func, eval_data... |
class MsfClient():
def __init__(self, password, lhost, host='127.0.0.1', port=55553):
self.logger = logging.getLogger('MsfClient')
self.logger.info(f'Connecting to msfrpcd at {host}:{port}')
self.client = MsfRpcClient(password, host=host, port=port, ssl=True)
self.lhost = lhost
... |
def dobldobl_solve(pols, verbose=True, tasks=0, dictionary_output=False, verbose_level=0):
from phcpy.phcpy2c3 import py2c_syscon_clear_dobldobl_Laurent_system
from phcpy.phcpy2c3 import py2c_syscon_initialize_number_of_dobldobl_Laurentials
from phcpy.phcpy2c3 import py2c_syscon_store_dobldobl_Laurential
... |
class CascadingBandit(Environment):
def __init__(self, num_items, num_positions, a0, b0):
assert (num_items >= num_positions)
self.num_items = num_items
self.num_positions = num_positions
self.a0 = a0
self.b0 = b0
self.probs = np.array([np.random.beta(a0, b0) for a in... |
class SimpleDatasetPredictor(DatasetPredictorBase):
def __init__(self, config, dataset):
super(SimpleDatasetPredictor, self).__init__(config, dataset)
self.predictor = OfflinePredictor(config)
def get_result(self):
self.dataset.reset_state()
try:
sz = self.dataset.siz... |
def get_bound_for_relu(l, u, adaptive=False):
device = l.device
ku = torch.zeros(u.shape, device=device)
bu = torch.zeros(u.shape, device=device)
kl = torch.zeros(l.shape, device=device)
bl = torch.zeros(l.shape, device=device)
idx = (l >= 0)
kl[idx] = 1
ku[idx] = 1
idx = ((l < 0) * ... |
def four_models(df, name, startday, k, three=False, c0=1, mu=0.5):
lin_future_predictions = []
sep_exp_future_predictions = []
shared_exp_future_predictions = []
ensemble = []
for i in range(startday, ((df.shape[0] - k) + 1)):
tmp = df[:i]
d = {'Name': [name], 'hospitalizations': [tm... |
def build_ox_model2():
A = helper.make_tensor_value_info('A', TensorProto.FLOAT, [1, 5, 5])
D = helper.make_tensor_value_info('D', TensorProto.FLOAT, [1, 5, 2])
H = helper.make_tensor_value_info('H', TensorProto.FLOAT, [1, 5, 2])
F = helper.make_tensor_value_info('F', TensorProto.FLOAT, [1, 5, 2])
e... |
class Classifier(object):
def __init__(self, D_layers):
self.D_layers = D_layers
self.params = []
for layer in self.D_layers:
self.params = (self.params + layer.params)
def encode(self, input):
output = input
for layer in self.D_layers:
output = la... |
class CyclicLR(_LRScheduler):
def __init__(self, optimizer, base_lr, max_lr, step_size_up=2000, step_size_down=None, mode='triangular', gamma=1.0, scale_fn=None, scale_mode='cycle', cycle_momentum=True, base_momentum=0.8, max_momentum=0.9, last_epoch=(- 1)):
self.optimizer = optimizer
base_lrs = sel... |
def main():
app = gui.Application.instance
app.initialize()
pcd_data = o3d.data.DemoICPPointClouds()
cloud = o3d.io.read_point_cloud(pcd_data.paths[0])
ex = ExampleApp(cloud)
app.run() |
def unique(results):
total_dupes = 0
total = 0
for res in results:
original_num = len(res)
test_data = set(res)
new_num = len(test_data)
total_dupes += (original_num - new_num)
total += original_num
return (1 - (total_dupes / float(total))) |
def parse_guidance_query(query):
messages = []
start_tokens = ['{{#system~}}', '{{#assistant~}}', '{{#user~}}']
position = (- 1)
next_token = None
for token in start_tokens:
next_position = query.find(token)
if ((next_position != (- 1)) and ((position == (- 1)) or (next_position < po... |
def output_ranklist(img_results, img_infos, out_file):
assert utils.is_type_list(img_results, dict)
assert utils.is_type_list(img_infos, dict)
assert isinstance(out_file, str)
assert out_file.endswith('json')
sorted_results = []
for (idx, result) in enumerate(img_results):
name = img_inf... |
def load_adaptive_records(path, algo):
records = []
for (i, subdir) in tqdm.tqdm(list(enumerate(os.listdir(path))), ncols=80, leave=False):
results_path = os.path.join(path, subdir, 'results_{}.jsonl'.format(algo))
try:
with open(results_path, 'r') as f:
for line in f... |
class TqdmProgressFileReader():
def __init__(self, f: io.BufferedReader):
self.f = f
self.total_size = os.fstat(f.fileno()).st_size
self.pbar = tqdm(total=self.total_size, leave=False)
self.read = f.read
f.read = self._read
def _read(self, n=(- 1)):
self.pbar.upda... |
class ApproxExploitabilityP2SROManagerLogger(SimpleP2SROManagerLogger):
def __init__(self, p2sro_manger, log_dir: str, scenario: PSROScenario):
super(ApproxExploitabilityP2SROManagerLogger, self).__init__(p2sro_manger=p2sro_manger, log_dir=log_dir)
self._scenario = scenario
self._exploitabil... |
def get_diapreresnet_cifar(num_classes, blocks, bottleneck, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
assert (num_classes in [10, 100])
if bottleneck:
assert (((blocks - 2) % 9) == 0)
layers = ([((blocks - 2) // 9)] * 3)
else:
assert ((... |
def check_has_downloaded():
global iPER_images_dir, iPER_train_txt, iPER_val_txt
has_download = (os.path.exists(iPER_train_txt) and os.path.exists(iPER_val_txt))
if has_download:
train_vid_names = get_video_dirs(iPER_train_txt)
val_vid_names = get_video_dirs(iPER_val_txt)
all_vid_nam... |
class TFRobertaPreLayerNormForSequenceClassification(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class DumbSpotVideo(Video):
def __init__(self, video_path: (str | Path), fps: int, num_frames: int, num_decode: int=1, min_clip_duration: float=0, **kwargs) -> None:
self._fps = fps
self._num_frames = num_frames
self._video_path = video_path
self._name = (Path(Path(self._video_path).... |
def parse_args():
parser = argparse.ArgumentParser(description='Finetune a transformers model on a summarization task')
parser.add_argument('--dataset_name', type=str, default=None, help='The name of the dataset to use (via the datasets library).')
parser.add_argument('--dataset_config_name', type=str, defa... |
def maxpool(x, dim=(- 1), keepdim=False):
(out, _) = x.max(dim=dim, keepdim=keepdim)
return out |
def compute_moco_loss(q: Tensor, k: Tensor, k_global: Tensor, use_keys: bool, queue: Tensor, temp: float=0.2, rank: int=0) -> Tensor:
batch_size = q.shape[0]
if use_keys:
labels = (torch.arange(batch_size, dtype=torch.long, device=q.device) + (batch_size * rank))
sim_k = torch.einsum('nc,mc->nm'... |
def get_options(args=None):
parser = argparse.ArgumentParser(description='Adaptive Multi-Distribution Knowledge Distillation (AMDKD) scheme for AM')
parser.add_argument('--problem', default='cvrp', help="The problem to solve, or 'tsp'")
parser.add_argument('--graph_size', type=int, default=20, help='The siz... |
def main(train_set_dir, val_set_dir):
if ((not os.path.exists(train_set_dir)) and os.path.exists(val_set_dir)):
print('ERROR: Target Dir Does Not Exist')
return
train_csv_list = os.listdir((os.getcwd() + train_set_dir))
val_csv_list = os.listdir((os.getcwd() + val_set_dir))
i = 0
for... |
class Network(nn.Module):
def __init__(self, network_config):
super(Network, self).__init__()
self.network_config = network_config
def forward(self, input):
raise NotImplementedError
def step(self):
pass
def re_init(self):
pass |
class ProofExtractor():
lean_file: LeanFile
relative_file_path: Path
tactic_instance_data: List[Dict[(str, Any)]]
tactic_position_data: List[Dict[(str, Any)]]
tactic_pos_data: List[Dict[(str, Any)]]
tactic_data: Dict[(str, Dict[(str, Any)])]
tactic_pos_trace_keys: Dict[(Tuple[(str, int, int,... |
class AveragePooling3D(ZooKerasLayer):
def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='th', input_shape=None, **kwargs):
if (border_mode != 'valid'):
invalidInputError(False, "For AveragePooling3D, only border_mode='valid' is supported for now")
s... |
def _unflatten_dense_tensors(flat, tensors):
outputs = []
offset = 0
for tensor in tensors:
numel = tensor.numel()
outputs.append(flat.narrow(0, offset, numel).view_as(tensor))
offset += numel
return tuple(outputs) |
def mel_spectrogram_torch_data(y, data):
return mel_spectrogram_torch(y, data.filter_length, data.n_mel_channels, data.sampling_rate, data.hop_length, data.win_length, data.mel_fmin, data.mel_fmax, center=False) |
def cross_entropy(logits, target, weight=None, ignore_index=(- 100), reduction='mean', smooth_eps=None, smooth_dist=None):
'cross entropy loss, with support for target distributions and label smoothing
smooth_eps = (smooth_eps or 0)
if (_is_long(target) and (smooth_eps == 0)):
return F.cross_entrop... |
def set_restricted_game_conversions_for_all_workers_openspiel(trainer: Trainer, tmp_base_env: MultiAgentEnv, delegate_policy_id: PolicyID, agent_id_to_restricted_game_specs: Dict[(AgentID, List[StrategySpec])], load_policy_spec_fn):
local_delegate_policy = trainer.workers.local_worker().policy_map[delegate_policy_i... |
class MLP(nn.Module):
def __init__(self, ninput=200, nhidden=150, nclass=2, dropout=0):
super(MLP, self).__init__()
self.fc1 = nn.Linear(ninput, nhidden)
self.fc2 = nn.Linear(nhidden, nclass)
self.dropout = dropout
def forward(self, x):
out = F.relu(self.fc1(x))
o... |
def get_config(parse=True, **optional_kwargs):
parser = argparse.ArgumentParser()
parser.add_argument('--mode', type=str, default='train')
parser.add_argument('--verbose', type=str2bool, default='true')
parser.add_argument('--preprocessed', type=str2bool, default='True')
parser.add_argument('--video... |
class DeformConvFunction(Function):
def forward(ctx, input, offset, weight, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, im2col_step=64):
if ((input is not None) and (input.dim() != 4)):
raise ValueError('Expected 4D tensor as input, got {}D tensor instead.'.format(input.dim()... |
class LinearResidual(nn.Module):
def __init__(self, input_size=1024, output_size=1024, n_resmods=1, dropout=False):
super(LinearResidual, self).__init__()
thisname = self.__class__.__name__
self.dropout_prob = 0.5
self.n_mods = n_resmods
print('[INFO] ({}) Initializing module... |
class BertTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, do_lower... |
.register('GhostNet')
def build_ghostnet_backbone(cfg):
in_channels = cfg.MODEL.BACKBONE.IN_PLANES
base_channels = cfg.MODEL.BACKBONE.BASE_PLANES
width_multiplier = cfg.MODEL.COMPRESSION.WIDTH_MULTIPLIER
round_nearest = cfg.MODEL.COMPRESSION.ROUND_NEAREST
attention_type = cfg.MODEL.ATTENTION.ATTENTI... |
def test(test_loader, model, epoch):
model.eval()
Eval = Eval_thread()
n = 0
mae_ls = []
fmax_ls = []
with torch.no_grad():
for (j_batch, test_data) in enumerate(test_loader):
X_test = Variable(test_data[0])
y_test = Variable(test_data[1])
X_test = X_t... |
def remove_punctuation(x):
x = ''.join([c for c in x if (c not in string.punctuation)])
x = [s for s in x.split() if s]
x = ' '.join(x)
return x |
def VarLSTMCell(input, hidden, w_ih, w_hh, b_ih=None, b_hh=None, noise_in=None, noise_hidden=None):
input = (input.expand(4, *input.size()) if (noise_in is None) else (input.unsqueeze(0) * noise_in))
(hx, cx) = hidden
hx = (hx.expand(4, *hx.size()) if (noise_hidden is None) else (hx.unsqueeze(0) * noise_hid... |
class TranslationEnToDePipelineTests(MonoInputPipelineCommonMixin, unittest.TestCase):
pipeline_task = 'translation_en_to_de'
small_models = ['patrickvonplaten/t5-tiny-random']
large_models = [None]
invalid_inputs = [4, '<mask>']
mandatory_keys = ['translation_text'] |
class PabeeTests(TestCasePlus):
def test_run_glue(self):
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f'''
run_glue_with_pabee.py
--model_type albert
--mode... |
def test_get_git_hash():
with patch('mmcv.utils.version_utils._minimal_ext_cmd', _mock_cmd_success):
assert (get_git_hash() == '3b46d33e90c397869adfdfc9812aa0')
assert (get_git_hash(digits=6) == '3b46d3')
assert (get_git_hash(digits=100) == get_git_hash())
with patch('mmcv.utils.version_... |
class Rag(object):
def __init__(self, labels: np.ndarray, connectivity: int=1):
self.labels = labels
self.graph = fast_rag(labels, connectivity)
self.tree = tree.Ultrametric(init_nodes=self.graph.nodes())
def merge_subgraph(self, subgraph: Iterable={}, source: int=None):
subgraph... |
def test_dcn_center_head():
if (not torch.cuda.is_available()):
pytest.skip('test requires GPU and CUDA')
set_random_seed(0)
tasks = [dict(num_class=1, class_names=['car']), dict(num_class=2, class_names=['truck', 'construction_vehicle']), dict(num_class=2, class_names=['bus', 'trailer']), dict(num_... |
def gradient_check():
kernel_size_list = [1, 3]
len_list = [8, 10]
for i in range(10):
B = random.randint(1, 4)
C = (i + 1)
K = random.choice(kernel_size_list)
H = random.choice(len_list)
W = random.choice(len_list)
input = torch.randn(B, C, ((H + K) - 1), ((W... |
class LogisticRegressionNetwork(Model):
def __init__(self) -> None:
super().__init__()
self.dense1 = Dense(1)
self.dense2 = Dense(1)
self.sigmoid = tf.nn.sigmoid
def call(self, x1, x2):
x1 = self.dense1(x1)
x2 = self.dense2(x2)
x = tf.stack([x1, x2])
... |
class ClevrQuestion(torch.utils.data.Dataset):
def __init__(self, img_folder, ann_file, transforms):
super(ClevrQuestion, self).__init__()
self.transforms = transforms
self.root = img_folder
with open(ann_file, 'r') as f:
self.questions = json.load(f)['questions']
def... |
def read_rdf(fp):
with open(fp, 'r', encoding='utf-8') as f:
lines = f.readlines()
items = [line.strip().split('\t') for line in lines]
return items |
def draw_in_poincare_ball(embeddings: np.ndarray, label: Optional[np.ndarray]=None, dim: int=2, reduce_method: str='pca', cmap='viridis') -> plt.figure:
emb_low = project_to_poincare_ball(embeddings, dim, reduce_method)
if (dim == 2):
plot_2d_embedding(emb_low, label, cmap=cmap)
elif (dim == 3):
... |
def resnet_v2_50(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, centered_stride=False, reuse=None, scope='resnet_v2_50'):
c = [False, False, False]
if centered_stride:
i_last = (int(np.round(np.log2(output_stride))) - 3)
if (i_last >= 0):
c[i_last] ... |
class Zencoder(nn.Module):
def __init__(self, input_nc, ngf=64, norm='instance', act='LeakyReLU', use_spect=True):
super(Zencoder, self).__init__()
norm_layer = get_norm_layer(norm_type=norm)
acti = get_nonlinearity_layer(activation_type=act)
self.block0 = EncoderBlock(input_nc, (ngf... |
def _HamiltonianCarrying(q, p, g, s):
for t in range(10):
(q, p, g) = [(q + (0.1 * _dp_Hqp(q, p, s))), (p - (0.1 * _dq_Hqp(q, p, s))), (g + ((0.1 * _k(g, q, s)) p))]
return (q, p, g) |
def write_demo(fn, data, names, bpm=90.0, shift_second=None, shift_beat=None):
midi = demo_to_midi(data, names, bpm, shift_second, shift_beat)
midi.write(fn) |
class DenseBlock(nn.Module):
def __init__(self, in_channels, out_channels, add_bias=True, use_wscale=True, wscale_gain=_WSCALE_GAIN, lr_mul=1.0, activation_type='lrelu'):
super().__init__()
weight_shape = (out_channels, in_channels)
wscale = (wscale_gain / np.sqrt(in_channels))
if us... |
def test_digits_cosine_greedi_ln_object():
model = GraphCutSelection(100, 'cosine', optimizer=GreeDi(optimizer1='lazy', optimizer2='naive', random_state=0))
model.fit(X_digits)
assert_array_equal(model.ranking, digits_cosine_greedi_ranking)
assert_array_almost_equal(model.gains, digits_cosine_greedi_gai... |
def select_skeleton(coords_src, joint_info_src, skeleton_type_dst):
if (skeleton_type_dst == ''):
return coords_src
def get_index(name):
if (((name + '_') + skeleton_type_dst) in joint_info_src.names):
return joint_info_src.names.index((name + '_h36m'))
else:
retu... |
def mask_tube_in_sequence(mask_ratio: float, tube_size: int, len_sequence: int, device: (str | torch.device)='cpu'):
num_masked = floor((len_sequence * mask_ratio))
indices_permuted = ((torch.randperm((len_sequence // tube_size), device=device) * tube_size).repeat_interleave(tube_size) + torch.arange(tube_size,... |
def main(config, args):
set_seed(config.TRAIN.manualSeed)
Mission = TextSR(config, args)
if args.test:
if (not os.path.exists(config.TRAIN.ckpt_dir)):
os.mkdir(config.TRAIN.ckpt_dir)
result_path = os.path.join(config.TRAIN.ckpt_dir, 'test_result.csv')
if (not os.path.exis... |
class SquadDataTrainingArguments():
model_type: str = field(default=None, metadata={'help': ('Model type selected in the list: ' + ', '.join(MODEL_TYPES))})
data_dir: str = field(default=None, metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'})
max_seq_length: int = ... |
def parse_synthesize_args():
parser = ArgumentParser(description='Wolf Synthesize')
parser.add_argument('--mode', choices=['sample', 'reconstruct', 'interpolate', 'switch', 'classify'], help='synthesis mode', required=True)
parser.add_argument('--seed', type=int, default=None, metavar='S', help='random seed... |
def get_config():
config = ml_collections.ConfigDict()
config.actor_lr = 0.0003
config.value_lr = 0.0003
config.critic_lr = 0.0003
config.hidden_dims = (256, 256)
config.discount = 0.99
config.expectile = 0.7
config.temperature = 0.5
config.dropout_rate = 0.1
config.tau = 0.005
... |
def indice_conv_backward(features, filters, out_bp, indice_pairs, indice_pair_num, inverse=False, subm=False):
if (filters.dtype == torch.float32):
return sparse_conv_ext.indice_conv_backward_fp32(features, filters, out_bp, indice_pairs, indice_pair_num, int(inverse), int(subm))
elif (filters.dtype == t... |
def generate_threats():
generate_fixes_table('Number of correct fixes by removing bugs with overlapping developer fixes in the CodeT5 training data', ALL_FIXES, (D4J1_OVERLAPPING_BUGS | D4J2_OVERLAPPING_BUGS)) |
def save_model(iter_, model_dir, filename, model, optimizer):
torch.save({'iteration': iter_, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict()}, os.path.join(model_dir, filename)) |
def plot_roc(tpr_list, fpr_list, attack_name):
plt.figure(figsize=(10, 6))
plt.plot(fpr_list, tpr_list, '-', label=attack_name)
plt.title(f'ROC_{attack_name}_Attack')
plt.legend(loc=4)
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.grid()
plt.savefig(f'{attack_nam... |
def test_glorot_1d_not_supported():
from lasagne.init import GlorotNormal
with pytest.raises(RuntimeError):
GlorotNormal().sample((100,)) |
def cat_desc_to_id(cat_desc):
if isinstance(cat_desc, (list, tuple)):
return tuple((_cat_ids[c] for c in cat_desc))
else:
return _cat_ids[cat_desc] |
def set_empty_labels(doc):
labels = ([0] * len(list(doc.sents)))
doc._.Labels = labels
doc._.CLPR_Labels = labels
return doc |
class HDFShardDataset(Dataset):
def __init__(self, shard_dir, shard_names=None, primary_key=None, stride=1):
super().__init__()
self.shard_dir = shard_dir
self.shard_names = shard_names
if (not shard_names):
self.shard_names = sorted(os.listdir(shard_dir))
self.pr... |
class ReinitFL():
def __init__(self, config, server, client_list):
self.max_round = config.MAX_ROUND
self.server = server
self.client_list = client_list
(self.list_loss, self.list_acc, self.list_est_time, self.list_model_size) = ([], [], [], [])
def main(self):
start = ti... |
def randint(low: IntNumType, high: Optional[IntNumType]=None, size: Optional[Size]=None, dtype: Type=np.int32, random_state: Optional[np.random.RandomState]=None) -> Any:
if (random_state is None):
random_state = get_random_state()
return random_state.randint(low, high, size, dtype) |
def test_mildnonaxi_sigmat2_direct():
idf = dehnendf(beta=0.0)
pot = [LogarithmicHaloPotential(normalize=1.0)]
edf = evolveddiskdf(idf, pot=pot, to=(- 10.0))
st2 = edf.sigmaT2(0.9, phi=0.2, integrate_method='rk6_c', grid=False)
ist2 = idf.sigmaT2(0.9)
assert (numpy.fabs((numpy.log(st2) - numpy.l... |
class ConvLayer(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, IN=False):
super(ConvLayer, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=False, groups=groups)
if IN:
... |
def filter_data(df, header, restraints={}):
filtered = []
for row in df:
to_add = True
for r in restraints.keys():
idx = header[r]
val = row[(- 1)][idx]
to_add = (to_add and (val in restraints[r]))
if to_add:
filtered.append(row)
return... |
def on_draw():
window.clear()
fps_display.draw()
for line in static_lines:
body = line.body
pv1 = (body.position + line.a.rotated(body.angle))
pv2 = (body.position + line.b.rotated(body.angle))
pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2f', (pv1.x, pv1.y, pv2.x, pv2.y)),... |
def normal_entropy(std):
var = std.pow(2)
entropy = (0.5 + (0.5 * torch.log(((2 * var) * math.pi))))
return entropy.sum(1, keepdim=True) |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('input')
parser.add_argument('--num-shards', type=int)
args = parser.parse_args()
assert ((args.num_shards is not None) and (args.num_shards > 1))
with open(args.input, 'r', encoding='utf-8') as h:
with contextlib.ExitSta... |
def main():
if (not os.path.exists(opt.output_path)):
os.makedirs(opt.output_path)
sys.stdout.write(('loading %s...' % opt.filename))
sd = SensorData(opt.filename)
sys.stdout.write('loaded!\n')
if opt.export_depth_images:
sd.export_depth_images(os.path.join(opt.output_path, 'depth'))... |
def get_parsed_sent(xml_file, sent_num, map, nlp):
catalan = False
conllu = ''
mark_xml = open(xml_file).read().encode('utf8')
base_root = fromstring(mark_xml, xmlparser)
tokens = {}
sents = {}
terms = {}
for annotation in base_root:
if (annotation.tag == 'text'):
for... |
def test_cif_realnvp_config():
config = get_config(dataset='mnist', model='realnvp', use_baseline=False)
true_config = {'schema_type': 'multiscale-realnvp', 'use_cond_affine': True, 'pure_cond_affine': False, 'g_hidden_channels': [64, 64, 64, 64], 'num_u_channels': 1, 'st_nets': [8, 8], 'p_nets': [64, 64], 'q_n... |
def fetch_history_for_many_ags(ags_list):
AG_RKI_SUMS_QUERY_BASE_URL = os.environ['AG_RKI_SUMS_QUERY_BASE_URL']
md = 'Meldedatum'
ts = 'timestamp'
idlk = 'IdLandkreis'
t_start = '2020-05-01 22:00:00'
d_end = (datetime.today() - timedelta(days=0))
t_end = f"{d_end.strftime('%Y-%m-%d')} 23:59:... |
def convert_beit(ckpt):
new_ckpt = OrderedDict()
for (k, v) in ckpt.items():
if k.startswith('blocks'):
new_key = k.replace('blocks', 'layers')
if ('norm' in new_key):
new_key = new_key.replace('norm', 'ln')
elif ('mlp.fc1' in new_key):
... |
class DepthEstimatorOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
predicted_depth: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None |
def linelistPath(linelist, dr=None):
if (dr is None):
dr = 'current'
specReduxPath = apogeeSpectroReduxDirPath(dr=dr)
return os.path.join(specReduxPath, 'speclib', 'linelists', linelist) |
class KAF(Layer):
def __init__(self, num_parameters, D=20, boundary=3.0, conv=False, init_fcn=None, kernel='gaussian', **kwargs):
self.num_parameters = num_parameters
self.D = D
self.boundary = boundary
self.init_fcn = init_fcn
self.conv = conv
if self.conv:
... |
def rotate_and_shift_coordination(orig_x, orig_y, orig_d, coordi_shift_x, coordi_shift_y, coordi_rotate_d):
(shift_x, shift_y, transformed_d) = rotate_coordination(orig_x, orig_y, orig_d, coordi_rotate_d)
(transformed_x, transformed_y) = shift_coordination(shift_x, shift_y, coordi_shift_x, coordi_shift_y)
r... |
def train_one(task, model, opt, args, grad):
model['ebd'].train()
model['clf'].train()
opt.zero_grad()
(support, query) = task
XS = model['ebd'](support)
YS = support['label']
XQ = model['ebd'](query)
YQ = query['label']
(_, loss) = model['clf'](XS, YS, XQ, YQ)
if (loss is not No... |
def fed_test(fed, running_model, val_loaders, verbose, adversary=None):
mark = ('s' if (adversary is None) else 'r')
val_acc_list = [None for _ in range(fed.client_num)]
val_loss_mt = AverageMeter()
for client_idx in range(fed.client_num):
fed.download(running_model, client_idx)
(val_los... |
def prepare_query_box(boxes_list, q, scene):
def get_boxes_idx(box):
if (box in boxes_list):
return boxes_list.index(box)
else:
boxes_list.append(box)
return (len(boxes_list) - 1)
def add_boxes_by_rids(rids):
def get_box_xyxy(obj):
(x, y, w... |
def standard_pole_step():
from phcpy.phcpy2c3 import py2c_padcon_standard_pole_step
return py2c_padcon_standard_pole_step() |
def cg(Ax, b, cg_iters=100):
x = np.zeros_like(b)
r = b.copy()
p = r.copy()
r_dot_old = np.dot(r, r)
for _ in range(cg_iters):
z = Ax(p)
alpha = (r_dot_old / (np.dot(p, z) + EPS))
x += (alpha * p)
r -= (alpha * z)
r_dot_new = np.dot(r, r)
p = (r + ((r_... |
class UCM(ImageFolder):
def __init__(self, root: str='.data/UCMerced_LandUse', transform: T.Compose=T.Compose([T.ToTensor()])):
super().__init__(root=os.path.join(root, 'Images'), transform=transform) |
def BasicTransposeConv2d(in_channels, out_channels, kernel_size, stride, pad, dilation):
output_pad = ((((stride + (2 * pad)) - (kernel_size * dilation)) + dilation) - 1)
return nn.Sequential(nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, pad, output_pad, dilation, bias=False), nn.BatchNorm2... |
def main(config='config/finetune/agnews/train.json'):
cfg = Config(**json.load(open(config, 'r')))
cfg_data = data.Config(**json.load(open(cfg.cfg_data, 'r')))
cfg_model = models.Config(**json.load(open(cfg.cfg_model, 'r')))
cfg_optim = trainer.Config(**json.load(open(cfg.cfg_optim, 'r')))
set_seeds... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.