code stringlengths 101 5.91M |
|---|
def is_borcherds_cartan_matrix(M):
if (not is_Matrix(M)):
return False
if (not M.is_square()):
return False
n = M.ncols()
for i in range(n):
if (M[(i, i)] == 0):
return False
if ((M[(i, i)] % 2) == 1):
return False
for j in range((i + 1), n... |
def make_dataset(dir, max_dataset_size=float('inf')):
images = []
dir = dir.replace(dir.split('/')[(- 1)], '')
assert os.path.isdir(dir), ('%s is not a valid directory' % dir)
dir_ = dir
sub_list = [os.path.join(dir_, o) for o in os.listdir(dir_) if os.path.isdir(os.path.join(dir_, o))]
images =... |
class MSRVTTChoiceDataModule(BaseDataModule):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def dataset_cls(self):
return MSRVTTChoiceDataset
def dataset_cls_no_false(self):
return MSRVTTChoiceDataset
def dataset_name(self):
return 'msrvtt_choice' |
def perform_distributed_training(setup_trainer_and_train, config, results_dir=None):
assert (config['trainer']['num_gpus'] > 1)
num_devices = config['trainer']['num_gpus']
e = event_messenger
procs = []
if (results_dir is None):
results_dir = f'{time.time():10.0f}'
for device_id in range... |
def plot_step_current_response(cur_in, mem_rec, vline1):
(fig, ax) = plt.subplots(2, figsize=(8, 6), sharex=True)
ax[0].plot(cur_in, c='tab:orange')
ax[0].set_ylim([0, 0.2])
ax[0].set_ylabel('Input Current ($I_{in}$)')
ax[0].set_title("Lapicque's Neuron Model With Step Input")
ax[1].plot(mem_rec... |
class TestLearningRate(serial.SerializedTestCase):
(**hu.gcs_cpu_only)
(deadline=None, max_examples=50)
def test_alter_learning_rate_op(self, gc, dc):
iter = np.random.randint(low=1, high=100000.0, size=1)
active_period = int(np.random.randint(low=1, high=1000.0, size=1))
inactive_pe... |
def visualize_hands(frame, hands_bboxes, hands_kps, hands_kp_scores, vis_thres=0.05):
img = frame.copy()
for (bbox, kps, kp_scores) in zip(hands_bboxes, hands_kps, hands_kp_scores):
part_line = {}
cv2.rectangle(img, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), RED, 1)
for ... |
_model_architecture('transformer_lm', 'transformer_lm_gpt3_2_7')
def transformer_lm_gpt3_2_7(args):
args.decoder_layers = safe_getattr(args, 'decoder_layers', 32)
args.decoder_embed_dim = safe_getattr(args, 'decoder_embed_dim', 2560)
args.decoder_attention_heads = safe_getattr(args, 'decoder_attention_heads... |
def process_variant(variant):
rl_variant = variant['rl_variant']
if args.debug:
rl_variant['algo_kwargs']['base_kwargs']['num_epochs'] = 4
rl_variant['algo_kwargs']['base_kwargs']['batch_size'] = 128
rl_variant['vis_kwargs']['num_samples_for_video'] = 2
rl_variant['vis_kwargs']['... |
class BayesianNetwork(nn.Module):
def __init__(self, inputSize, CLASSES, layers, activations, SAMPLES, BATCH_SIZE, NUM_BATCHES, hasScalarMixturePrior, PI, SIGMA_1, SIGMA_2, GOOGLE_INIT=False):
super().__init__()
self.inputSize = inputSize
self.activations = activations
self.CLASSES =... |
def weighted_kappa_calc(classes, table, P, TOP, POP, weight):
p_e = 0
p_a = 0
try:
w_max = max(map((lambda x: max(x.values())), weight.values()))
for i in classes:
for j in classes:
v_i_j = (1 - (weight[i][j] / w_max))
p_e += (((P[i] * TOP[j]) * v_... |
class Control(Consumer):
def __init__(self, network, action_size, include_state=False):
self.network = network
self.action_size = action_size
self.include_state = include_state
super().__init__()
def consume(self, inputs):
s = self.get(inputs, 'sentences')
ctrnet_... |
def to_pretty_midi_key_signature(key_signature: KeySignature, map_time: Callable=None) -> Optional[PmKeySignature]:
if (key_signature.root is None):
return None
if (key_signature.mode not in ('major', 'minor')):
return None
key_name = f'{PITCH_NAMES[key_signature.root]} {key_signature.mode}'... |
def read_dtype(mat_stream, a_dtype):
num_bytes = a_dtype.itemsize
arr = np.ndarray(shape=(), dtype=a_dtype, buffer=mat_stream.read(num_bytes), order='F')
return arr |
class Tokenizer(nn.Module):
def __init__(self, args, nchars, emb_dim, hidden_dim, dropout, feat_dropout):
super().__init__()
self.args = args
feat_dim = args['feat_dim']
self.embeddings = nn.Embedding(nchars, emb_dim, padding_idx=0)
self.rnn = nn.LSTM((emb_dim + feat_dim), hi... |
def initialize(N):
from numpy.random import default_rng
rng = default_rng(42)
(t0, p0, t1, p1) = (rng.random((N,)), rng.random((N,)), rng.random((N,)), rng.random((N,)))
return (t0, p0, t1, p1) |
def cb_pose(data):
t = data.header.stamp
image = vf.get_latest(t, remove_older=True)
if (image is None):
rospy.logwarn('No received images.')
return
(h, w) = image.shape[:2]
if (resize_ratio > 0):
image = cv2.resize(image, (int((resize_ratio * w)), int((resize_ratio * h))), i... |
class VSRCaptionEvalDataset(VSRCaptionDataset):
def __getitem__(self, index):
data = super().__getitem__(index)
if (data != None):
del data['text_input']
return data |
class TestDeepModels(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.n_past = 16
self.max_forecast_steps = 8
self.early_stop_patience = 4
self.num_epochs = 2
self.use_gpu = True
self.batch_size = 32
df = ... |
def plot_hl(pred_json, save_dir_i, base_json=None):
pred_saliency = np.array(pred_json['pred'])
pred_saliency = norm(pred_saliency)
gt_saliency = np.array(pred_json['gt'])
gt_saliency = norm(gt_saliency)
duration = pred_json['duration']
(t_min, t_max) = (0, duration)
x = np.arange(t_min, t_m... |
def url_decode(s, charset='utf-8', decode_keys=False, include_empty=True, errors='replace', separator='&', cls=None):
if (cls is None):
from .datastructures import MultiDict
cls = MultiDict
if (isinstance(s, text_type) and (not isinstance(separator, text_type))):
separator = separator.de... |
def gt_lesion_segm_stat_sbct(args):
stat_save_path = 'lesion_stat'
if (not os.path.exists(stat_save_path)):
os.makedirs(stat_save_path)
with open(args.set_txt_path) as f:
case_list = [x.strip() for x in f.readlines()]
bins = list(range(args.hist_bin_min, (args.hist_bin_max + 1), args.his... |
class NadamOptimizer(tf_compat.v1.train.AdamOptimizer):
def _apply_dense(self, grad, var):
from tensorflow.python.training import training_ops
from tensorflow.python.ops import math_ops
m = self.get_slot(var, 'm')
v = self.get_slot(var, 'v')
(beta1_power, beta2_power) = self.... |
class LookAtObjInLightTask(BaseTask):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def goal_satisfied(self, state):
pcs = self.goal_conditions_met(state)
return (pcs[0] == pcs[1])
def goal_conditions_met(self, state):
ts = 2
s = 0
tar... |
def assert_allclose(actual, desired, rtol=1e-07, atol=0, equal_nan=True, err_msg='', verbose=True):
__tracebackhide__ = True
import numpy as np
def compare(x, y):
return np.core.numeric.isclose(x, y, rtol=rtol, atol=atol, equal_nan=equal_nan)
(actual, desired) = (np.asanyarray(actual), np.asanya... |
class NNPolicy(object):
def __init__(self):
pass
def multi_state_policy(self, states, agent_indices):
raise NotImplementedError()
def multi_obs_policy(self, states):
raise NotImplementedError() |
class GPT2LoraInt8Engine(CausalLoraEngine):
config_name: str = 'gpt2_lora_engine_int8'
def __init__(self, weights_path: Optional[Union[(str, Path)]]=None):
super().__init__(model_name='gpt2', weights_path=weights_path, load_8bit=True, target_modules=['c_attn'])
self.tokenizer.pad_token = self.to... |
_module()
class SOLOv2(SingleStageInstanceSegmentor):
def __init__(self, backbone, neck=None, bbox_head=None, mask_head=None, train_cfg=None, test_cfg=None, init_cfg=None, pretrained=None):
super().__init__(backbone=backbone, neck=neck, bbox_head=bbox_head, mask_head=mask_head, train_cfg=train_cfg, test_cfg... |
def run_episodic_random_agent(args, worker_idx=None):
if args.do_testing:
fout = open('result/{}_random_{}.csv'.format(args.env_name, args.seed), 'w')
env = make_env(args.env_name, worker_idx=worker_idx)
env.seed(((args.seed + 0) if (worker_idx is None) else worker_idx))
obs_dim = env.observatio... |
class CenterLoss(nn.Module):
def __init__(self, num_classes=751, feat_dim=2048, use_gpu=True):
super(CenterLoss, self).__init__()
self.num_classes = num_classes
self.feat_dim = feat_dim
self.use_gpu = use_gpu
if self.use_gpu:
self.centers = nn.Parameter(torch.rand... |
def register_Ns3GlobalRouteManagerImpl_methods(root_module, cls):
cls.add_constructor([])
cls.add_method('DeleteGlobalRoutes', 'void', [], is_virtual=True)
cls.add_method('BuildGlobalRoutingDatabase', 'void', [], is_virtual=True)
cls.add_method('InitializeRoutes', 'void', [], is_virtual=True)
cls.ad... |
class ExtraData(UnpackValueError):
def __init__(self, unpacked, extra):
self.unpacked = unpacked
self.extra = extra
def __str__(self):
return 'unpack(b) received extra data.' |
def make_layers(cfg, batch_norm=False, filter_size=1):
layers = []
in_channels = 3
for v in cfg:
if (v == 'M'):
layers += [nn.MaxPool2d(kernel_size=2, stride=1), Downsample(filt_size=filter_size, stride=2, channels=in_channels)]
else:
conv2d = nn.Conv2d(in_channels, v... |
class SpacyPreprocessorParameters(NamedTuple):
text_field: str
doc_field: str
language: str
disable: Optional[List[str]]
pre: List[BasePreprocessor]
memoize: bool
memoize_key: Optional[HashingFunction]
gpu: bool |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input-dir', required=True)
args = parser.parse_args()
parse(args.input_dir) |
class TestDiverseBeamSearch(TestSequenceGeneratorBase):
def setUp(self):
d = test_utils.dummy_dictionary(vocab_size=2)
self.assertEqual(d.pad(), 1)
self.assertEqual(d.eos(), 2)
self.assertEqual(d.unk(), 3)
self.eos = d.eos()
self.w1 = 4
self.w2 = 5
sel... |
def run_epoch(model, train_loader, optimizer, center, device, is_angular):
(total_loss, total_num) = (0.0, 0)
for ((img1, img2), _) in tqdm(train_loader, desc='Train...'):
(img1, img2) = (img1.to(device), img2.to(device))
optimizer.zero_grad()
out_1 = model(img1)
out_2 = model(im... |
def get_all_fsps_in_sent(sent, sentann, fspno, lex_unit, frame, isfulltextann, corpus):
numannosets = 0
fsps = {}
fspset = set([])
for anno in sent.findall('fn:annotationSet', ns):
annotation_id = anno.attrib['ID']
if ((annotation_id == '2019791') and (VERSION == '1.5')):
con... |
def strlist2multihot(strlist, classlist):
return np.sum(np.eye(len(classlist))[strlist2indlist(strlist, classlist)], axis=0) |
class YolosFeatureExtractor(metaclass=DummyObject):
_backends = ['vision']
def __init__(self, *args, **kwargs):
requires_backends(self, ['vision']) |
class _BFS(Function):
def forward(ctx, edge_index, max_adj_per_vertex):
(sorted_index, sorted_parent, sorted_child) = _C.bfs_forward(edge_index, max_adj_per_vertex)
return (sorted_index, sorted_parent, sorted_child) |
def gradient_penalty(output, on):
gradients = tf.gradients(output, [on])[0]
grad_l2 = tf.sqrt(tf.reduce_sum(tf.square(gradients), axis=[1, 2, 3]))
return tf.reduce_mean(((grad_l2 - 1) ** 2)) |
class ScalableGNN(torch.nn.Module):
def __init__(self, num_nodes: int, hidden_channels: int, num_layers: int, pool_size: Optional[int]=None, buffer_size: Optional[int]=None, device=None):
super().__init__()
self.num_nodes = num_nodes
self.hidden_channels = hidden_channels
self.num_la... |
def config_dict(config_path=CONFIG_PATH):
config = configparser.ConfigParser()
config.read(config_path)
d = dict()
for section_key in config.sections():
sd = dict()
section = config[section_key]
for key in section:
val = section[key]
try:
s... |
def _get_read_cursor(source, parallelism=None):
from . import _fmm_core
ret_stream_to_close = None
if (parallelism is None):
parallelism = PARALLELISM
try:
source = os.fspath(source)
is_path = True
except TypeError:
is_path = False
if is_path:
path = str(s... |
def img_mask_pad(image, mask, target=(288, 288)):
padding = PadIfNeeded(p=1.0, min_height=target[0], min_width=target[1])
paded = padding(image=image, mask=mask)
return (paded['image'], paded['mask']) |
_utils.test(require=ti.extension.data64)
def test_global_buffer_misalignment():
def test(x: ti.f32):
a = x
b = ti.cast(0.12, ti.f64)
for i in range(8):
b += a
for i in range(8):
test(0.1) |
def save_images(images, index, outdir, classes, labels):
images_ = ((images.cpu().detach().permute((0, 2, 3, 1)) * std) + mean)
for (i, image) in enumerate(images_):
plt.imsave(os.path.join(outdir, f'{((index + i) + 1)}_image_{classes[labels[i].item()]}.jpg'), image.numpy()) |
def worker_func(model_cls, model_kwargs, checkpoint, dataset, data_func, gpu_id, idx_queue, result_queue):
model = model_cls(**model_kwargs)
load_checkpoint(model, checkpoint, map_location='cpu')
torch.cuda.set_device(gpu_id)
model.cuda()
model.eval()
with torch.no_grad():
while True:
... |
def load_state_epoch(model_dir, model, epoch):
model_path = ((model_dir + '/model.pth-') + str(epoch))
checkpoint = torch.load(model_path, map_location='cuda:{}'.format(torch.cuda.current_device()))
model.load_state_dict(checkpoint['state_dict'], strict=False)
ckpt_keys = set(checkpoint['state_dict'].ke... |
def tsne_by_gender(vecs, labels, title, words=None):
tsne = TSNE(n_components=2, random_state=0)
vecs_2d = tsne.fit_transform(vecs)
num_labels = len(set(labels.tolist()))
names = ['class {}'.format(i) for i in range(num_labels)]
plt.figure(figsize=(6, 5))
colors = ('r', 'b', 'orange')
for (i... |
class BiSeNet(nn.Module):
def __init__(self, n_classes, *args, **kwargs):
super(BiSeNet, self).__init__()
self.cp = ContextPath()
self.ffm = FeatureFusionModule(256, 256)
self.conv_out = BiSeNetOutput(256, 256, n_classes)
self.conv_out16 = BiSeNetOutput(128, 64, n_classes)
... |
def register_types_ns3_Hash(module):
root_module = module.get_root()
module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
typehandlers.add_type_alias(u'uint32_t ( *... |
def resnext34(baseWidth, cardinality, **unused):
model = ResNeXt(baseWidth, cardinality, BasicBlock, [3, 4, 6, 3], 1000)
return model |
class CVAE(nn.Module):
def __init__(self, input_dim, context_dim, latent_dim, hidden_dims, encoder_full_cov=True, decoder_full_cov=True, activation='elu', iaf=None, decoder_maf=None, prior_maf=None, decoder_zcontext=False, encoder_xcontext=False, encoder_ycontext=False, batch_norm=False, prior_gaussian_nn=False, pr... |
def HS_all_minimal(f, return_transformation=False, D=None):
MS = MatrixSpace(ZZ, 2)
m = MS.one()
F = copy(f)
F.normalize_coordinates()
if (F.degree() == 1):
raise ValueError('function must be degree at least 2')
if ((f.degree() % 2) == 0):
if return_transformation:
re... |
class RandomNegP(tfk.layers.Layer):
def __init__(self, num_updates=2000, min_prob=0.0, max_prob=0.5, **kwargs):
self.num_updates = num_updates
self.min_prob = min_prob
self.max_prob = max_prob
super().__init__(**kwargs)
def get_config(self):
return dict(num_updates=self.n... |
def unpickle(file):
import pickle
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict |
def test_RecordArray():
array = ak.Array([{'x': 0}, {'x': 1}, {'x': 2}, {'x': 3}, {'x': 4}, {'x': 5}], backend='cuda')
results = nb_cuda.to_device(np.empty(6, dtype=np.int32))
pass_record_through[(1, 6)](array, results)
nb_cuda.synchronize()
host_results = results.copy_to_host()
assert (ak.Array... |
def read_document(lines, spaces_after, split_clauses):
document = []
sentence = []
for line in lines:
line = line.strip()
if (not line):
if sentence:
if spaces_after:
sentence[(- 1)] = (sentence[(- 1)][0], True)
document.append(... |
class Scale(nn.Module):
def __init__(self, init_value=1.0):
super(Scale, self).__init__()
self.scale = nn.Parameter(torch.FloatTensor([init_value]))
def forward(self, x):
return (x * self.scale) |
def processNlToks(nlToks):
return [tok.encode('ascii', 'replace').decode().strip() for tok in nlToks if ((tok != '-RCB-') and (tok != '-LCB-') and (tok != '-LSB-') and (tok != '-RSB-') and (tok != '-LRB-') and (tok != '-RRB-') and (tok != '') and (tok != '') and (tok != '') and (tok.encode('ascii', 'replace').decod... |
def get_optimizer(training_args, model):
if training_args.train_model_params:
params = [{'params': model.get_codebook_params(), 'lr': training_args.learning_rate, 'weight_decay': 0.0}, {'params': model.get_model_params(), 'lr': (training_args.model_lr_factor * training_args.learning_rate), 'weight_decay': t... |
def my_main(_config, cnn):
print(_config)
print('[*] Building CNN')
network = resnet50(pretrained=True, **cnn['cnn'])
network.load_state_dict(torch.load(weights))
network.eval()
network.cuda()
print('[*] Initializing Dataloader')
dataloader = cnn['dataloader']
dataloader['transform']... |
def findNode(id_, allNodes):
for n in allNodes:
if (n._id == id_):
return n
return None |
class LockFile():
def __init__(self, fname: str):
self._fname = fname
self._fd = None
def acquire(self):
self._fd = open(self._fname, 'w')
try:
os.chmod(self._fname, 511)
except PermissionError:
pass
while True:
try:
... |
class Linear(torch.nn.Module):
def __init__(self, n_neurons, input_shape=None, input_size=None, bias=True, max_norm=None, combine_dims=False):
super().__init__()
self.max_norm = max_norm
self.combine_dims = combine_dims
if ((input_shape is None) and (input_size is None)):
... |
def get_data(dataset, data_path, batch_size, num_workers):
assert (dataset in ['CIFAR10', 'CIFAR100'])
print('Loading dataset {} from {}'.format(dataset, data_path))
if (dataset in ['CIFAR10', 'CIFAR100']):
ds = getattr(datasets, dataset.upper())
path = os.path.join(data_path, dataset.lower(... |
def run(turns, searcher, num_passages):
results = []
conversation = []
conversation_no = (- 1)
for turn in tqdm(turns):
if (turn['Conversation_no'] != conversation_no):
conversation_no = turn['Conversation_no']
conversation = []
results.append(run_for_turn(turn, c... |
def is_value_with_epsilon_correct(func: T.Callable[([sf.Scalar, sf.Scalar], sf.Expr)], singularity: sf.Scalar=0, limit_direction: str='+', display_func: T.Callable[([T.Any], None)]=_default_display_func, expected_value: sf.Scalar=None) -> bool:
assert (symforce.get_symbolic_api() == 'sympy')
x = sf.Symbol('x', ... |
class GroupMorphism_libgap(Morphism):
def __init__(self, homset, gap_hom, check=True):
if check:
if (not gap_hom.IsGroupHomomorphism()):
raise ValueError('not a group homomorphism')
if (homset.domain().gap() != gap_hom.Source()):
raise ValueError('doma... |
_properties
class ControlGraphView(BlockGraphView, abc.ABC):
def nodes(self) -> List['ControlFlowBlock']:
...
def edges(self) -> List[Edge['dace.sdfg.InterstateEdge']]:
...
def all_nodes_recursive(self) -> Iterator[Tuple[(NodeT, GraphT)]]:
for node in self.nodes():
(yield... |
(TEST_WITH_TSAN, 'Fails with TSAN with the following error: starting new threads after multi-threaded fork is not supported. Dying (set die_after_fork=0 to override)')
class TestDictDataLoader(TestCase):
def setUp(self):
super(TestDictDataLoader, self).setUp()
self.dataset = DictDataset()
def te... |
class PhaseShiftUpper(PairwiseUnitary):
def __init__(self, phase_shift: float, dtype=NP_COMPLEX):
super(PhaseShiftUpper, self).__init__(dtype=dtype)
self.phase_shift = phase_shift
def matrix(self) -> np.ndarray:
return np.array([[np.exp((1j * self.phase_shift)), 0], [0, 1]], dtype=self.d... |
class TFAutoModelForCausalLM():
def __init__(self):
raise EnvironmentError('TFAutoModelForCausalLM is designed to be instantiated using the `TFAutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path)` or `TFAutoModelForCausalLM.from_config(config)` methods.')
_list_option_in_docstrings(TF_MOD... |
class CPPTestsFile(pytest.File):
def collect(self):
cpptests = yaml.safe_load(open(self.path).read())
for suite in cpptests:
sname = suite['name']
binary = suite['binary']
if (platform.system() == 'Windows'):
binary += '.exe'
binary = (... |
def categorical_sample(probs):
int_acs = torch.multinomial(probs, 1)
acs = torch.zeros(probs.shape, device=probs.device).scatter_(1, int_acs, 1)
return (int_acs, acs) |
def space_priority(char):
return {'L': 7, 'M': 7, 'N': 5, 'S': 3, 'P': 1, 'Z': (- 1), 'C': (- 3)}[unicodedata.category(char)[0]] |
def are_mcfarland_1973_parameters(v, k, lmbda, return_parameters=False):
if ((v <= k) or (k <= lmbda)):
return ((False, None) if return_parameters else False)
k = ZZ(k)
lmbda = ZZ(lmbda)
(qs, r) = (k - lmbda).sqrtrem()
if (r or ((qs * (qs - 1)) % lmbda)):
return ((False, None) if ret... |
_optimizer('adadelta')
class Adadelta(FairseqOptimizer):
def __init__(self, args, params):
super().__init__(args)
self._optimizer = torch.optim.Adadelta(params, **self.optimizer_config)
def add_args(parser):
parser.add_argument('--adadelta-rho', type=float, default=0.9, metavar='RHO', he... |
class TestTranslation(unittest.TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)
def tearDown(self):
logging.disable(logging.NOTSET)
def test_fconv(self):
with contextlib.redirect_stdout(StringIO()):
with tempfile.TemporaryDirectory('test_fconv') as data_dir:
... |
class Permutations_setk(Permutations_set):
def __classcall_private__(cls, s, k):
return super().__classcall__(cls, tuple(s), k)
def __init__(self, s, k):
Permutations_set.__init__(self, s)
self._k = k
def __contains__(self, x):
if (len(x) != self._k):
return False... |
class BaseEstimator():
def _get_param_names(cls):
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
if (init is object.__init__):
return []
init_signature = inspect.signature(init)
parameters = [p for p in init_signature.parameters.values() if ((p.name != ... |
class SquashDones(gym.Wrapper):
def step(self, action):
(observation, reward, done, info) = self.env.step(action)
return (observation, reward, all(done), info) |
class AnomalibCLI(LightningCLI):
def add_arguments_to_parser(self, parser: LightningArgumentParser) -> None:
parser.add_argument('--export_mode', type=str, default='', help='Select export mode to ONNX or OpenVINO IR format.')
parser.add_argument('--nncf', type=str, help='Path to NNCF config to enabl... |
def test_mesh():
N = 4
F = FunctionSpace(N, 'F', dtype='d', coordinates=((x,), rv))
xj = F.mesh()
xx = F.cartesian_mesh()
assert (np.sum((abs((xx[0] - np.cos(xj))) * abs((xx[1] - np.sin(xj))))) < 1e-12) |
def get_mnist_config(_processID=0, _maxProcessID=8, _maxGPU=8, _DO_SHUFFLE=False):
_G = grid_maker(methodList, useMixupList, outlierRatioList, errTypeList, tau_invList)
_ids = get_properIdx(_processID, _maxProcessID, _nTask=_G.nIter)
_paramsList = list((_G.paramList[i] for i in _ids))
_GPU_ID = (_proces... |
class LinearWarmupScheduler(_BaseWarmupScheduler):
def __init__(self, optimizer, successor, warmup_epoch, min_lr, last_epoch=(- 1), verbose=False):
self.min_lr = min_lr
super().__init__(optimizer, successor, warmup_epoch, last_epoch, verbose)
def get_lr(self):
if (self.last_epoch >= self... |
class AggregationLayer(nn.Module):
def __init__(self) -> None:
super().__init__()
self.left1 = nn.Sequential(nn.Conv2d(128, 128, 3, 1, 1, groups=128, bias=False), nn.BatchNorm2d(128), nn.Conv2d(128, 128, 1, 1, 0, bias=False))
self.left2 = nn.Sequential(nn.Conv2d(128, 128, 3, 2, 1, bias=False... |
class AdamWeightDecay(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def _rebuild_sparse_tensor(layout, data):
if (layout == torch.sparse_coo):
(indices, values, size) = data
result = torch._sparse_coo_tensor_unsafe(indices, values, size)
_sparse_tensors_to_validate.append(result)
return result
raise NotImplementedError(('rebuilding sparse tensor ... |
class DummyEncoderModel(FairseqEncoderModel):
def __init__(self, encoder):
super().__init__(encoder)
def build_model(cls, args, task):
return cls(DummyEncoder())
def get_logits(self, net_output):
return torch.log(torch.div(net_output['encoder_out'], (1 - net_output['encoder_out'])))
... |
def main(args):
verbose = args.verbose
form = args._from
from_forms = [form for _ in range(len(args.files))]
if (form == 'auto'):
try:
from_forms = [file_utils.detect_format(path) for path in args.files]
except file_utils.UnknownFormatError as e:
print((('Error: u... |
class TabRegrTask(BaseTask):
def __init__(self, target, features=None, metadata=None):
self._case = 'CSR'
super(TabRegrTask, self).__init__(target, features=features, metadata=metadata) |
def test_append_to_file_uses_checksum_from_appended_file(test_file_path: Path, agent: Agent):
append_text = 'This is appended text.\n'
file_ops.append_to_file(test_file_path, append_text, agent=agent)
file_ops.append_to_file(test_file_path, append_text, agent=agent)
with open(agent.config.file_logger_pa... |
def add_md_help_argument(parser):
parser.add_argument('-md', action=MarkdownHelpAction, help='print Markdown-formatted help text and exit.') |
def RandomBipartite(n1, n2, p, set_position=False, seed=None):
if (not ((p >= 0) and (p <= 1))):
raise ValueError('parameter p is a probability, and so should be a real value between 0 and 1')
if (not ((n1 > 0) and (n2 > 0))):
raise ValueError('n1 and n2 should be integers strictly greater than ... |
def test_store_not_overwrite(tensor_db):
origin_tensor = tensor_db.tensor_db.copy(deep=True)
_store(tensor_db.tensor_db, 'tensor_name', 'agg', 0, False, ('col1',), np.array([5, 6, 7, 8, 9]), overwrite=False)
assert_frame_equal(origin_tensor, tensor_db.tensor_db) |
def rollback_env_variables(environ, env_var_subfolders):
lines = []
unmodified_environ = copy.copy(environ)
for key in sorted(env_var_subfolders.keys()):
subfolders = env_var_subfolders[key]
if (not isinstance(subfolders, list)):
subfolders = [subfolders]
for subfolder in... |
def build_def(ctx, py_def, type_line, def_name, self_name=None):
body = py_def.body
r = ctx.make_range((py_def.lineno + len(py_def.decorator_list)), py_def.col_offset, (py_def.col_offset + len('def')))
param_list = build_param_list(ctx, py_def.args, self_name)
return_type = None
if (getattr(py_def, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.