code stringlengths 101 5.91M |
|---|
def get_span_score_pairs(ypi, yp2i):
span_score_pairs = []
for (f, (ypif, yp2if)) in enumerate(zip(ypi, yp2i)):
for j in range(len(ypif)):
for k in range(j, len(yp2if)):
span = ((f, j), (f, (k + 1)))
score = (ypif[j] * yp2if[k])
span_score_pair... |
def get_ground_truths(answer):
return (answer['NormalizedAliases'] + [normalize_answer(ans) for ans in answer.get('HumanAnswers', [])]) |
def test_is_nonpositive():
assert (not Rational(1, 2).is_nonpositive)
assert Rational((- 2), 3).is_nonpositive
assert (Symbol('x').is_nonpositive is None) |
def distillation(y, teacher_scores, labels, T, alpha):
p = F.log_softmax((y / T), dim=1)
q = F.softmax((teacher_scores / T), dim=1)
l_kl = ((F.kl_div(p, q, size_average=False) * (T ** 2)) / y.shape[0])
l_ce = F.cross_entropy(y, labels)
return ((l_kl * alpha) + (l_ce * (1.0 - alpha))) |
_module()
class Res2Net(ResNet):
arch_settings = {50: (Bottle2neck, (3, 4, 6, 3)), 101: (Bottle2neck, (3, 4, 23, 3)), 152: (Bottle2neck, (3, 8, 36, 3))}
def __init__(self, scales=4, base_width=26, style='pytorch', deep_stem=True, avg_down=True, pretrained=None, init_cfg=None, **kwargs):
self.scales = sc... |
def mark_observed_custom_module(module, custom_module_class):
module._is_observed_custom_module = True
module._FLOAT_MODULE = custom_module_class |
def process_book(break_probs_dir, para_to_sent_dir, gt_dir, output_dir, book_id):
with open(os.path.join(break_probs_dir, (book_id + '.pkl')), 'rb') as f:
break_probs = pickle.load(f)
with open(os.path.join(para_to_sent_dir, (book_id + '.pkl')), 'rb') as f:
para_to_sent = pickle.load(f)
peak... |
class ODOC_seg_edge(nn.Module):
def __init__(self, channel=64):
super(ODOC_seg_edge, self).__init__()
self.resnet = res2net50_v1b_26w_4s(pretrained=False)
self.rfb2_1 = BasicConv2d(256, channel, 1)
self.rfb3_1 = BasicConv2d(512, channel, 1)
self.rfb4_1 = BasicConv2d(1024, cha... |
def fork_rng(devices=None, enabled=True, _caller='fork_rng', _devices_kw='devices'):
import torch.cuda
global _fork_rng_warned_already
if (not enabled):
(yield)
return
if (devices is None):
num_devices = torch.cuda.device_count()
if ((num_devices > 1) and (not _fork_rng_w... |
class BSDSD1orp1mat(SpectralMatrix):
def assemble(self, method):
(test, trial) = (self.testfunction, self.trialfunction)
assert isinstance(test[0], SD)
assert isinstance(trial[0], SD)
assert (test[0].quad == 'LG')
k = np.arange((test[0].N - 2))
d = {0: (((2 * ((2 * k)... |
def pythran_indexing_type(type_, indices):
return type_remove_ref(('decltype(std::declval<%s>()%s)' % (pythran_type(type_), _index_access(_index_type_code, indices)))) |
class FDST(NWPU):
def __init__(self, root, list_path, num_samples=None, num_classes=1, multi_scale=True, flip=True, ignore_label=(- 1), base_size=2048, crop_size=(512, 1024), min_unit=(32, 32), center_crop_test=False, downsample_rate=1, scale_factor=(0.5, (1 / 0.5)), mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0... |
def kl_loss(mu, logvar):
loss = (0.5 * tf.reduce_sum((((tf.square(mu) + tf.exp(logvar)) - 1) - logvar), axis=(- 1)))
loss = tf.reduce_mean(loss)
return loss |
def test_binary_target() -> None:
with pytest.raises(ValueError, match='Please provide y_true as a bina*'):
check_binary_zero_one(np.array([0, 5, 4])) |
class Softplus_SENet(nn.Module):
def __init__(self, block, num_blocks, num_classes=100):
super(Softplus_SENet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 = self._... |
def partial(f, *args, **kwargs):
p = functools.partial(f, *args, **kwargs)
functools.update_wrapper(p, f)
return p |
class NLUEngineConfig(FromDict, ProcessingUnitConfig):
def __init__(self, intent_parsers_configs=None, random_seed=None):
from snips_nlu.intent_parser import IntentParser
if (intent_parsers_configs is None):
from snips_nlu.pipeline.configs import ProbabilisticIntentParserConfig, Determin... |
def create_scheduler(args, optimizer):
num_epochs = args.epochs
if (getattr(args, 'lr_noise', None) is not None):
lr_noise = getattr(args, 'lr_noise')
if isinstance(lr_noise, (list, tuple)):
noise_range = [(n * num_epochs) for n in lr_noise]
if (len(noise_range) == 1):
... |
class Prompter(ABC):
def aggregation_prompt(self, state_dicts: List[Dict], **kwargs) -> str:
pass
def improve_prompt(self, **kwargs) -> str:
pass
def generate_prompt(self, num_branches: int, **kwargs) -> str:
pass
def validation_prompt(self, **kwargs) -> str:
pass
def... |
(resources={'machine': 1})
def allgather(args_dict, notification_address, world_size, world_rank, object_size):
store = utils.create_store_using_dict(args_dict)
object_id = utils.object_id_from_int(world_rank)
array = np.random.rand((object_size // 4)).astype(np.float32)
buffer = store_lib.Buffer.from_b... |
def argParse():
parser = ArgumentParser(prog=__applicationName__)
parser.add_argument('--version', action='version', version=('%(prog)s ' + __version__))
parser.add_argument('--autobrief', action='store_true', help='use the docstring summary line as \\brief description')
parser.add_argument('--debug', a... |
def get_model_33(params):
inputs = Input(shape=(params['n_metafeatures'],))
reg = Lambda((lambda x: K.l2_normalize(x, axis=1)))
x1 = reg(inputs)
inputs2 = Input(shape=(params['n_metafeatures2'],))
reg2 = Lambda((lambda x: K.l2_normalize(x, axis=1)))
x2 = reg2(inputs2)
inputs3 = Input(shape=(... |
_utils.test(require=ti.extension.adstack, ad_stack_size=1, arch=[ti.cpu, ti.gpu])
def test_large_for_loops_fixed_stack_size():
x = ti.field(dtype=float, shape=(), needs_grad=True)
arr = ti.field(dtype=float, shape=2, needs_grad=True)
loss = ti.field(dtype=float, shape=(), needs_grad=True)
def test_large... |
def test_is_invertible_module_shared_outputs():
fnb = MultiSharedOutputs()
X = torch.rand(1, 2, 5, 5, dtype=torch.float32).requires_grad_()
with pytest.warns(UserWarning):
assert is_invertible_module(fnb, test_input_shape=(X.shape,), atol=1e-06) |
class SpeakerVerifi_test(Dataset):
def __init__(self, vad_config, file_path, meta_data):
self.root = file_path
self.meta_data = meta_data
self.necessary_dict = self.processing()
self.vad_c = vad_config
self.dataset = self.necessary_dict['spk_paths']
self.pair_table = ... |
class BertOnlyMLMHead(nn.Module):
def __init__(self, config, decoder_model_embedding_weights):
super(BertOnlyMLMHead, self).__init__()
self.predictions = BertLMPredictionHead(config, decoder_model_embedding_weights)
def forward(self, sequence_output):
prediction_scores = self.predictions... |
class ULIPWithImageLoss(nn.Module):
def __init__(self):
super().__init__()
self.labels = None
self.last_local_batch_size = None
def forward(self, outputs):
pc_embed = outputs['pc_embed']
text_embed = outputs['text_embed']
image_embed = outputs['image_embed']
... |
class DeformConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, bias=False):
super(DeformConv, self).__init__()
self.with_bias = bias
assert ((in_channels % groups) == 0), 'in_channels {} cannot be divisi... |
class KITTI(BaseDataset):
def __init__(self, data_path='./data/', is_train=True, image_limitation=50, crop_size=(512, 512), scale_size=None, depth_scale=80):
super().__init__(crop_size)
self.is_train = is_train
self.size = 512
self.image_limitation = image_limitation
self.dat... |
def eval(params, model, epoch, eval_loader, writer=None):
model.eval()
device = params['device']
loss_meter = Meter()
(word_right, struct_right, exp_right, length, cal_num) = (0, 0, 0, 0, 0)
with tqdm(eval_loader, total=len(eval_loader)) as pbar, torch.no_grad():
for (batch_idx, (images, ima... |
def loss_chimera_psa(output, label):
[embedding, mask_A, mask_B] = output
[one_hot_label, mag_mix, mag_s1, mag_s2, cos_s1, cos_s2] = label
(batch_size, frame, frequency) = mask_A.shape
loss_embedding = loss_dc([embedding], [one_hot_label, mag_mix])
loss_mask1 = (norm_1d(((mask_A * mag_mix) - torch.m... |
def get_free_gpus():
output = subprocess.check_output('nvidia-smi --query-gpu=memory.free --format=csv,nounits,noheader', shell=True)
free_memory = [int(x) for x in output.decode().strip().split('\n')]
free_gpus = [i for (i, memory) in enumerate(free_memory) if (memory > 10000)]
free_gpus = sorted(free_... |
class RhombusPiece(PuzzlePiece):
def __init__(self, north_piece, south_piece):
self._north_piece = north_piece
self._south_piece = south_piece
self._edge_labels = dict(north_west=north_piece['north_west'], north_east=north_piece['north_east'], south_east=south_piece['south_east'], south_west... |
class Meteor():
def __init__(self):
self.meteor_cmd = ['java', '-jar', '-Xmx2G', METEOR_JAR, '-', '-', '-stdio', '-l', 'en', '-norm']
self.meteor_p = subprocess.Popen(self.meteor_cmd, cwd=os.path.dirname(os.path.abspath(__file__)), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIP... |
def maxima_version():
with os.popen('{} --version'.format(MAXIMA)) as p:
return p.read().split()[(- 1)] |
class LDMPipeline(DiffusionPipeline):
def __init__(self, vqvae: VQModel, unet: UNet2DModel, scheduler: DDIMScheduler):
super().__init__()
scheduler = scheduler.set_format('pt')
self.register_modules(vqvae=vqvae, unet=unet, scheduler=scheduler)
_grad()
def __call__(self, batch_size: i... |
class RandomSampler(Sampler):
def __init__(self, data_source):
self.data_source = data_source
def __iter__(self):
return iter(torch.randperm(len(self.data_source)).tolist())
def __len__(self):
return len(self.data_source) |
def test_cond_param_assign3():
time_dim = Dim(Tensor('time', [batch_dim], dtype='int32'))
in_dim = Dim(7, name='in')
extern_data = TensorDict({'data': Tensor('data', [batch_dim, time_dim, in_dim], dtype='float32')})
class _Net(rf.Module):
def __init__(self):
super().__init__()
... |
def register_Ns3CallbackImpl__Void_Unsigned_long_Unsigned_short_Unsigned_short_Ns3LteUeRrcState_Ns3LteUeRrcState_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, unsigned long long, unsigned short, unsigned short, ns3::Lt... |
class FactorizationMachineModel(keras.Model):
def __init__(self, num_users, num_items, num_features, factors, lambda_weights, learning_rate=0.01, random_seed=42, name='FM', **kwargs):
super().__init__(name=name, **kwargs)
tf.random.set_seed(random_seed)
self.num_users = num_users
sel... |
def _read_pretrained_word2vec_format_embedding_file(embeddings_filename: str, embedding_dim: int, vocab: Vocabulary, namespace: str='tokens') -> torch.FloatTensor:
words_to_keep = set(vocab.get_index_to_token_vocabulary(namespace).values())
vocab_size = vocab.get_vocab_size(namespace)
embeddings = {}
lo... |
class CifarResNeXt(nn.Module):
def __init__(self, block, depth, cardinality, base_width, num_classes, dropout):
super(CifarResNeXt, self).__init__()
self.num_classes = num_classes
assert (((depth - 2) % 9) == 0), 'depth should be one of 29, 38, 47, 56, 101'
layer_blocks = ((depth - 2... |
class HolisticIndexBlock(nn.Module):
def __init__(self, in_channels, norm_cfg=dict(type='BN'), use_context=False, use_nonlinear=False):
super().__init__()
if use_context:
(kernel_size, padding) = (4, 1)
else:
(kernel_size, padding) = (2, 0)
self.index_block = ... |
class UpdateReadme(Step):
def action(self, context):
self.instruct(f"Update README for version: {context['version']}") |
def init_signal_handler():
signal.signal(signal.SIGUSR1, sig_handler)
signal.signal(signal.SIGTERM, term_handler) |
class PowerParameter(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _POWERPARAMETER |
def untar_file(filename, location):
ensure_dir(location)
if (filename.lower().endswith('.gz') or filename.lower().endswith('.tgz')):
mode = 'r:gz'
elif filename.lower().endswith(BZ2_EXTENSIONS):
mode = 'r:bz2'
elif filename.lower().endswith(XZ_EXTENSIONS):
mode = 'r:xz'
elif ... |
class DGNNet(nn.Module):
def __init__(self, net_params):
super().__init__()
hidden_dim = net_params['hidden_dim']
out_dim = net_params['out_dim']
decreasing_dim = net_params['decreasing_dim']
in_feat_dropout = net_params['in_feat_dropout']
dropout = net_params['dropou... |
def test_write_background_to_file_1(tmpdir):
_bk = Background()
_bk.write(filename='train', location=pathlib.Path(tmpdir))
assert (tmpdir.join('train_bk.txt').read() == str(_bk)) |
class MinkUNet18_MCMC(nn.Module):
def __init__(self, seg_model, p_drop=0.5):
super().__init__()
self.seg_model = seg_model
self.dropout = ME.MinkowskiDropout(p=p_drop)
def forward(self, x, is_train=True):
(out_backbone, out_bottle) = self.seg_model(x, is_seg=False)
out_ba... |
def stable_var(x, mean=None, dim=1):
if (mean is None):
mean = x.mean(dim, keepdim=True)
mean = mean.view((- 1), 1)
res = torch.pow((x - mean), 2)
max_sqr = torch.max(res, dim, keepdim=True)[0]
var = (torch.mean((res / max_sqr), 1, keepdim=True) * max_sqr)
var = var.view((- 1))
var[(... |
def dir_type(path):
if (path and (not pth.isdir(path))):
raise argparse.ArgumentTypeError("'{0}' is not a directory".format(path))
return path |
def get_data(d, bgp=False, airports=False):
if airports:
dataset = Airports(root=('original_datasets/airports_dataset/' + d), dataset_name=d)
original = dataset[0]
elif bgp:
dataset = BGP(root='original_datasets/bgp_dataset')
original = dataset[0]
else:
if (d in ['cor... |
def _reroute_t(t0, t1, consumers1, can_modify=None, cannot_modify=None):
nb_update_inputs = 0
if (can_modify is not None):
consumers1 &= can_modify
if (cannot_modify is not None):
consumers1 -= cannot_modify
consumers1_indices = {}
for consumer1 in consumers1:
consumers1_indi... |
class SE(object):
def __init__(self, params, batcher, prepare=None):
params = utils.dotdict(params)
params.usepytorch = (True if ('usepytorch' not in params) else params.usepytorch)
params.seed = (1111 if ('seed' not in params) else params.seed)
params.batch_size = (128 if ('batch_si... |
.usefixtures('enable_slep006')
def test_transformer_fit_transform_with_metadata_in_transform():
class CustomTransformer(BaseEstimator, TransformerMixin):
def fit(self, X, y=None, prop=None):
return self
def transform(self, X, prop=None):
return X
with pytest.warns(UserWar... |
class MaxTestExecutionsStoppingCondition(StoppingCondition):
def __init__(self, max_test_executions: int):
super().__init__(observes_execution=True)
self._num_executed_tests = 0
assert (max_test_executions > 0.0)
self._max_test_executions = max_test_executions
def current_value(s... |
def segment(text):
seg = [1 for _ in range(len(text))]
idx = text.index('sep')
seg[:idx] = [0 for _ in range(idx)]
return seg |
class BaseTransformer(pl.LightningModule):
def __init__(self, hparams, num_labels=None):
super(BaseTransformer, self).__init__()
self.hparams = hparams
self.hparams.model_type = self.hparams.model_type.lower()
(config_class, model_class, tokenizer_class) = MODEL_CLASSES[self.hparams.... |
def test_simple_movement_up(env_single_agent):
env = env_single_agent
env.agents[0].x = 4
env.agents[0].y = 25
env.agents[0].dir = Direction.UP
env._recalc_grid()
env.step([Action.FORWARD])
assert (env.agents[0].x == 4)
assert (env.agents[0].y == 24) |
def prepare_maestro(target_dir: str, cache_dir: str, dataset_root: str, test_fold: int=0, get_path_only: bool=False):
target_dir: Path = Path(target_dir)
train_csv = (target_dir / 'train.csv')
valid_csv = (target_dir / 'valid.csv')
test_csv = (target_dir / 'test.csv')
if get_path_only:
retur... |
def concepts_to_adj_matrices_2hop_all_pair__use_LM__Part1(data):
(qc_ids, ac_ids, question) = data
qa_nodes = (set(qc_ids) | set(ac_ids))
extra_nodes = set()
for qid in qa_nodes:
for aid in qa_nodes:
if ((qid != aid) and (qid in cpnet_simple.nodes) and (aid in cpnet_simple.nodes)):
... |
def group_by_generator(mock_database):
generator = GroupByGenerator(mock_database)
return generator |
class TMMNetCrossNetI(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
_snap.TMMNetCrossNetI_swiginit(self, _snap.new_TMMNetCrossNetI(*args))
def Next(self):
return _snap.... |
.experimental
.parametrize('als_model, metric', [(ALSWrap(seed=SEED), 'euclidean_distance_sim'), (ALSWrap(seed=SEED), 'dot_product'), (ALSWrap(seed=SEED), 'cosine_similarity')], ids=['als_euclidean', 'als_dot', 'als_cosine'])
def test_get_nearest_items(log, als_model, metric):
als_model.fit(log.filter((sf.col('item... |
def get_vectorized_gym_env(base_env, gym_env_name, agent_idx, featurize_fn=None, **kwargs):
def gym_env_fn():
gym_env = gym.make(gym_env_name)
if (kwargs['RUN_TYPE'] == 'joint_ppo'):
gym_env.custom_init(base_env, joint_actions=True, featurize_fn=featurize_fn, baselines=True, agent_idx=ag... |
class ExceptionInfo():
ex: Optional[BaseException]
tb: tblib.Traceback
def restore(self):
if (self.ex is not None):
exc_value = self.ex.with_traceback(self.tb.as_traceback())
return (self.ex.__class__, exc_value, self.tb.as_traceback())
else:
return (Excep... |
def make_window(seed, static_out=True):
if (not isinstance(seed, (tuple, list))):
raise ValueError('seed must be tuple or list')
if isinstance(seed[0], (tuple, list)):
if static_out:
seed = ([[1]] + list(seed))
max_len = max([len(coefficients) for coefficients in seed])
... |
def get_numeracy_metric_specs(run_solver: bool=False) -> List[MetricSpec]:
metric_specs: List[MetricSpec] = get_basic_metric_specs(['exact_match', 'quasi_exact_match', 'absolute_value_difference'])
if run_solver:
metric_specs += [MetricSpec(class_name='helm.benchmark.metrics.numeracy_metrics.DistanceMet... |
def test_fit_digraph(digraph_logistic_regression):
classifiers = [LogisticRegression(), LogisticRegression()]
digraph_logistic_regression.n_jobs = 2
digraph_logistic_regression.local_classifiers_ = classifiers
digraph_logistic_regression._fit_digraph(local_mode=True)
for classifier in digraph_logist... |
def easy_linear_polynomials_via_interpolation(p):
res = []
p_vars = p.vars_as_monomial()
space = p_vars.divisors()
zeros = p.zeros_in(space)
lex_leads = variety_lex_leading_terms(zeros, p_vars)
for m in lex_leads:
if (m.deg() == 1):
red = (m + nf_lex_points(m, zeros))
... |
def _save_to_state_dict(module, destination, prefix, keep_vars):
for (name, param) in module._parameters.items():
if (param is not None):
destination[(prefix + name)] = (param if keep_vars else param.detach())
for (name, buf) in module._buffers.items():
if (buf is not None):
... |
class GTSRB(Dataset):
base_folder = 'GTSRB'
def __init__(self, train=False, transform=None):
self.root_dir = './data'
self.sub_directory = ('trainingset' if train else 'testset')
self.csv_file_name = ('training.csv' if train else 'test.csv')
csv_file_path = os.path.join(self.root... |
def uniform_quantizer(tensor_data: np.ndarray, n_bits: int, signed: bool, quantization_params: dict, per_channel: bool, output_channels_axis: int) -> np.ndarray:
range_min = quantization_params.get(RANGE_MIN)
range_max = quantization_params.get(RANGE_MAX)
if ((range_min is None) or (range_max is None)):
... |
def get_category_from_img_vector(img_vector, image_vectors):
minimum = 2
cat = ''
for image_vector in image_vectors.keys():
curr = cosine(img_vector, image_vectors[image_vector])
if (curr < minimum):
minimum = curr
cat = image_vector
return cat |
def lattice_paths(t1, t2, length=None):
t1 = tuple(t1)
t2 = tuple(t2)
if (length is None):
if ((len(t1) == 0) or (len(t2) == 0)):
return [[]]
elif (len(t1) == 1):
return [[(t1[0], w) for w in t2]]
elif (len(t2) == 1):
return [[(v, t2[0]) for v in t... |
.parametrize('GradientBoosting, X, y', [(HistGradientBoostingClassifier, X_classification, y_classification), (HistGradientBoostingRegressor, X_regression, y_regression)])
def test_warm_start_yields_identical_results(GradientBoosting, X, y):
rng = 42
gb_warm_start = GradientBoosting(n_iter_no_change=100, max_it... |
def find_first_capital_letter(answer):
letter_set = {'A', 'B', 'C', 'D', 'E', 'F'}
for c in answer:
if (c in letter_set):
return c
return '' |
class SelfParentPolicy(SetFactoryPolicy):
def __init__(self, factory, Element):
self._Element = Element
SetFactoryPolicy.__init__(self, factory)
def element_constructor_attributes(self, constraints):
return self.self_element_constructor_attributes(self._Element)
def _repr_(self):
... |
def getSegmentList(corpusName, segmentList, **kwargs):
print(('SprintExternInterface: getSegmentList(%r), num segments: %i' % (corpusName, len(segmentList))))
global segmentOrderList
segmentOrderList = segmentList
return segmentList |
def download_permanent_water(date, bounds):
year = date.year
if (year >= 2019):
year = 2019
return ee.Image(f'JRC/GSW1_2/YearlyHistory/{year}').clip(bounds) |
def scheduler(epoch, learning_rate):
if (epoch > 0):
if ((epoch % LEARING_RATE_DECAY_EVERY_N_EPOCHS) == 0):
learning_rate = (learning_rate * LEARNING_RATE_DECAY)
print('Change learning rate to', '{0:.6f}'.format(learning_rate))
return learning_rate |
def cosine_rampdown(current, rampdown_length):
'Cosine rampdown from
current = np.clip(current, 0.0, rampdown_length)
return float((0.5 * (np.cos(((np.pi * current) / rampdown_length)) + 1))) |
class ModelPlugin():
def __init__(self, dataset, logfilepath, args):
self.args = args
selectGpuById(self.args.gpu)
self.logfilepath = logfilepath
self.logger = LoggerManager(self.logfilepath, __name__)
self.set_dataset(dataset)
def set_dataset(self, dataset):
self... |
class Logger(mrl.Module):
def __init__(self, average_every=100):
super().__init__('logger', required_agent_modules=['env'], locals=locals())
self.average_every = average_every
self.writer = None
def _setup(self):
self.rewards_per_env = np.zeros((self.env.num_envs,))
self.... |
class Stream_derivative(Stream_unary):
def __init__(self, series, shift, is_sparse):
self._shift = shift
super().__init__(series, is_sparse, False)
_attribute
def _approximate_order(self):
if (0 <= self._series._approximate_order <= self._shift):
return 0
return (... |
def load_sickr_test(dirpath: str) -> Dict[(str, List[Tuple[(Tuple[(str, str)], float)]])]:
filepath = os.path.join(dirpath, 'SICK_test_annotated.txt')
return {'test': load_data_sickr(filepath)} |
def train(segmentation_module, loader_train, optimizers, history, epoch, args):
batch_time = AverageMeter()
data_time = AverageMeter()
ave_total_loss = AverageMeter()
ave_acc = AverageMeter()
ave_jaccards = []
for i in range((args.num_class - 1)):
ave_jaccards.append(AverageMeter())
... |
def get_augmentation(augmentation_type: Augmentation, crop_size: int=32, padding_size: int=4, resize_size: int=256, distributed=True, enable_auto_augmentation=False):
train_transform = transforms.Compose([])
if (augmentation_type in [Augmentation.CropAndHorizontalFlip, Augmentation.CropAndHorizontalFlipVertical... |
def set_seeds(seed=0, fully_deterministic=True):
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
if fully_deterministic:
torch.backends.cudnn.deterministic = Tru... |
class ExperimentStats():
def __init__(self, total_epoch, total_itr, total_env_steps, last_path):
self.total_epoch = total_epoch
self.total_itr = total_itr
self.total_env_steps = total_env_steps
self.last_path = last_path |
class PyObjectPtrPrinter():
def __init__(self, gdbval):
self.gdbval = gdbval
def to_string(self):
pyop = PyObjectPtr.from_pyobject_ptr(self.gdbval)
if True:
return pyop.get_truncated_repr(MAX_OUTPUT_LEN)
else:
proxyval = pyop.proxyval(set())
re... |
def dumps(plan: optplan.OptimizationPlanSchema) -> str:
plan = copy.deepcopy(plan)
validate_references(plan)
model_list = []
_extract_nodes(plan, model_list)
_replace_ref_nodes_with_names(plan, model_list)
plan.nodes = model_list
validate(plan)
return json.dumps(plan.to_primitive()) |
def test_enum_statement_delta(test_case_mock):
enum_ = MagicMock(names=['FOO', 'BAR', 'BAZ'])
statement = stmt.EnumPrimitiveStatement(test_case_mock, enum_)
prev = statement.value
statement.delta()
assert (statement.value != prev)
assert (0 <= statement.value <= 2) |
def dict_matches(span, dictionary):
matches = []
toks = span.get_attrib_tokens('words')
for i in range(len(toks)):
for j in range((i + 1), len(toks)):
term = ' '.join(toks[i:j]).lower()
if (term in dictionary):
matches.append(term)
return matches |
def split_on_punct(doc):
start = 0
seen_period = False
for (i, word) in enumerate(doc):
if (seen_period and (not word.is_punct)):
(yield doc[start:word.i])
start = word.i
seen_period = False
elif (word.text in ['.', '!', '?']):
seen_period = Tr... |
def download_power(data_folder):
recreate_folder(data_folder)
url = '
base_path = os.path.join(data_folder, 'household_power_consumption')
zip_path = (base_path + '.zip')
csv_path = (base_path + '.txt')
output_path = os.path.join(data_folder, 'power.csv')
download_and_unzip(url, zip_path, cs... |
def test_poly_intersection():
with pytest.raises(AssertionError):
utils.poly_intersection(0, 1)
points = [0, 0, 0, 1, 1, 1, 1, 0]
points1 = [10, 20, 30, 40, 50, 60, 70, 80]
points2 = [0, 0, 0, 0, 0, 0, 0, 0]
points3 = [0, 0, 0, 1, 1, 0, 1, 1]
points4 = [0.5, 0, 1.5, 0, 1.5, 1, 0.5, 1]
... |
class TensorFieldModule(UniqueRepresentation, ReflexiveModule_tensor):
Element = TensorField
def __init__(self, vector_field_module, tensor_type, category=None):
domain = vector_field_module._domain
dest_map = vector_field_module._dest_map
kcon = tensor_type[0]
lcov = tensor_type... |
def put_acquire_memoryviewslice(lhs_cname, lhs_type, lhs_pos, rhs, code, have_gil=False, first_assignment=True):
assert rhs.type.is_memoryviewslice
pretty_rhs = (rhs.result_in_temp() or rhs.is_simple())
if pretty_rhs:
rhstmp = rhs.result()
else:
rhstmp = code.funcstate.allocate_temp(lhs_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.