code stringlengths 101 5.91M |
|---|
def get_model(point_cloud, is_training, num_class, bn_decay=None, gripper_feat=None, env_feat=None):
batch_size = point_cloud.get_shape()[0].value
num_point = point_cloud.get_shape()[1].value
end_points = {}
l0_xyz = point_cloud
l0_points = None
end_points['l0_xyz'] = l0_xyz
(l1_xyz, l1_poin... |
class LongPoleCartPole(ModifiableCartPoleEnv):
def __init__(self):
super(LongPoleCartPole, self).__init__()
self.length = self.EXTREME_UPPER_LENGTH
self._followup()
def parameters(self):
parameters = super(LongPoleCartPole, self).parameters
parameters.update({'length': se... |
def scp_file(file, ip, path, ssh_key=None):
if (ssh_key is None):
scp_cmd_str = ('scp %s %s:%s' % (file, ip, path))
else:
scp_cmd_str = ('scp -i %s %s %s:%s' % (ssh_key, file, ip, path))
return scp_cmd_str |
def save_rollouts(rollout_dir: str, s_obs_vecs: Union[(np.ndarray, List[np.ndarray])], s_ach_goal_vecs: Union[(np.ndarray, List[np.ndarray])], a_vecs: Union[(np.ndarray, List[np.ndarray])], base_actions: Optional[np.ndarray]=None) -> None:
obs_file = os.path.join(rollout_dir, s_obs_vecs_file)
ach_goal_file = os... |
class _MarkupEscapeHelper(object):
def __init__(self, obj, escape):
self.obj = obj
self.escape = escape
def __getitem__(self, item):
return _MarkupEscapeHelper(self.obj[item], self.escape)
def __str__(self):
return text_type(self.escape(self.obj))
__unicode__ = __str__
... |
class KGEServer(KVServer):
def _push_handler(self, name, ID, data, target):
original_name = name[0:(- 6)]
state_sum = target[(original_name + '_state-data-')]
grad_sum = (data * data).mean(1)
state_sum.index_add_(0, ID, grad_sum)
std = state_sum[ID]
std_values = std.s... |
class Client(object):
def __init__(self, config):
self.config = config
def _base_params(self):
ts = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
nonce = ''.join(random.sample(string.ascii_letters, 32))
return {'Timestamp': ts, 'AccessKeyId': self.config.pop_access_id, 'Sign... |
def extract_quotes_and_entities(sample_text):
text = utils.preprocess_text(sample_text)
doc = spacy_lang(text)
quotes = extractor.extract_quotes(doc)
annotation = annotator.run(DB_CLIENT, text, [], quotes, '')
people = annotation['people']
sources = annotation['sources']
unified_nes = annota... |
class CIFAR10DataLoader(BaseDataLoader):
def __init__(self, data_dir, batch_size, shuffle=True, validation_split=0.0, num_batches=0, training=True, num_workers=4, pin_memory=True):
config = ConfigParser.get_instance()
cfg_trainer = config['trainer']
if cfg_trainer['do_adv']:
prin... |
def _make_hist_name(channel, sample, modifier='', prefix='hist', suffix=''):
middle = '_'.join(filter((lambda x: x), [channel, sample, modifier]))
return f'{prefix}{middle}{suffix}' |
def add_cross_val_metrics_parser(subparsers, formatter_class):
subparser = subparsers.add_parser('cross-val-metrics', formatter_class=formatter_class, help='Compute cross-validation metrics on a given dataset')
subparser.add_argument('dataset_path', type=str, help='Path to the dataset file')
subparser.add_a... |
def pad_and_cat(a, padding_value, padding_dim=1):
max_dim_size = max([x.size()[padding_dim] for x in a])
padded_a = []
for x in a:
if (x.size()[padding_dim] < max_dim_size):
res_len = (max_dim_size - x.size()[1])
pad = nn.ConstantPad1d((0, res_len), padding_value)
... |
def _compute_metrics(metric, eval_preds, tokenizer):
(preds, labels) = eval_preds
if isinstance(preds, tuple):
preds = preds[0]
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
labels = np.where((labels != IGNORE_INDEX), labels, tokenizer.pad_token_id)
decoded_labels =... |
def print_tensors_in_checkpoint_file(file_name, tensor_name, all_tensors):
try:
reader = tf_compat.v1.train.NewCheckpointReader(file_name)
if all_tensors:
var_to_shape_map = reader.get_variable_to_shape_map()
for key in sorted(var_to_shape_map):
print('tensor_... |
def GetPageRank_v1(tspec, *args):
if (type(tspec) == PUNGraph):
return GetPageRank_v1_PUNGraph(tspec, *args)
if (type(tspec) == PUndirNet):
return GetPageRank_v1_PUndirNet(tspec, *args)
if (type(tspec) == PDirNet):
return GetPageRank_v1_PDirNet(tspec, *args)
if (type(tspec) == PN... |
def iterate_over_json_files_in_dir(dir_path):
pathlist = Path(dir_path).glob('*.json')
return [str(path) for path in pathlist] |
def test_computation_cache_fitness_compute_order(cache):
func = MagicMock()
func.is_maximisation_function.return_value = False
func.compute_fitness.return_value = 0
func.compute_is_covered.return_value = True
cache.add_fitness_function(func)
cache._chromosome.has_changed.return_value = False
... |
.parametrize('observation_shape', [(100,)])
.parametrize('batch_size', [32])
.parametrize('eps', [32])
def test_standard_observation_scaler_with_trajectory_slicer(observation_shape: Sequence[int], batch_size: int, eps: float) -> None:
shape = (batch_size, *observation_shape)
observations = np.random.random(shap... |
def get_norm_layer(opt, norm_nc):
if (opt.param_free_norm == 'instance'):
return nn.InstanceNorm2d(norm_nc, affine=False)
if (opt.param_free_norm == 'syncbatch'):
return SynchronizedBatchNorm2d(norm_nc, affine=False)
if (opt.param_free_norm == 'batch'):
return nn.BatchNorm2d(norm_nc,... |
class LossScaler():
def __init__(self, scale=1):
self.cur_scale = scale
def has_overflow(self, params):
return False
def _has_inf_or_nan(x):
return False
def update_scale(self, overflow):
pass
def loss_scale(self):
return self.cur_scale
def scale_gradient(... |
def _analyze_and_unparse_code(func: DaceProgram) -> str:
(src_ast, _, _, _) = astutils.function_to_ast(func.f)
resolved = {k: v for (k, v) in func.global_vars.items() if (k not in func.argnames)}
src_ast = GlobalResolver(resolved).visit(src_ast)
src_ast = ConditionalCodeResolver(resolved).visit(src_ast)... |
def betas_for_alpha_bar(num_diffusion_timesteps, max_beta=0.999):
def alpha_bar(time_step):
return (math.cos(((((time_step + 0.008) / 1.008) * math.pi) / 2)) ** 2)
betas = []
for i in range(num_diffusion_timesteps):
t1 = (i / num_diffusion_timesteps)
t2 = ((i + 1) / num_diffusion_tim... |
def tplus_time(s, time):
if (time == 0):
return Symbol((str(s) + '_{t}'))
return Symbol((((str(s) + '_{t+') + f'{time}') + '}')) |
def assert_structured_array_dtype(arr, event, time, num_events):
assert (arr.dtype.names == (event, time))
assert np.issubdtype(arr.dtype.fields[event][0], np.bool_)
assert np.issubdtype(arr.dtype.fields[time][0], np.float_)
assert (arr[event].sum() == num_events) |
def read_fasta_check_dna(f):
seq_list = []
for e in read_fasta_yield(f):
res = is_under_alphabet(e.seq, ALPHABET)
if res:
seq_list.append(e)
else:
raise ValueError(' '.join(['Sorry, sequence', str(e.no), 'has character', str(res), '(The character must be A or C or... |
class AreaUnderCurve(ConfusionMatrixMetric):
def __init__(self, metric: str='AUC'):
super().__init__(metric)
def calculate(self):
specificity = (self.confusion_matrix.tn / (self.confusion_matrix.tn + self.confusion_matrix.fp))
false_positive_rate = (1 - specificity)
if ((self.con... |
def register_Ns3LteNetDevice_methods(root_module, cls):
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_constructor([])
cls.add_method('DoDispose', 'void', [], is_virtual=True)
cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True)
cls.add_me... |
def main(dataset_name='qags_xsum', aspect='consistency', aligner_type='disc', disc_init=None, bleurt_init=None, relevance_y_x_init=None, bert_model_type='roberta-large', bert_num_layers=None, dialog_context='fact_history', aggr_type='mean', remove_stopwords=False, n_references=11):
if (aligner_type == 'disc'):
... |
def get_pix2cam(focals, width, height):
fx = np.array(focals)
fy = np.array(focals)
cx = (np.array(width) * 0.5)
cy = (np.array(height) * 0.5)
arr0 = np.zeros_like(cx)
arr1 = np.ones_like(cx)
k_inv = np.array([[(arr1 / fx), arr0, ((- cx) / fx)], [arr0, ((- arr1) / fy), (cy / fy)], [arr0, arr... |
def load_transformer(gpt_ckpt, vqgan_ckpt, stft_vqgan_ckpt='', device=torch.device('cpu')):
from pytorch_lightning.utilities.cloud_io import load as pl_load
checkpoint = pl_load(gpt_ckpt)
checkpoint['hyper_parameters']['args'].vqvae = vqgan_ckpt
if stft_vqgan_ckpt:
checkpoint['hyper_parameters']... |
class VertexAITextClient(VertexAIClient):
def make_request(self, request: Request) -> RequestResult:
parameters = {'temperature': request.temperature, 'max_output_tokens': request.max_tokens, 'top_k': request.top_k_per_token, 'top_p': request.top_p, 'stop_sequences': request.stop_sequences, 'candidate_count... |
def glibc_version_string():
process_namespace = ctypes.CDLL(None)
try:
gnu_get_libc_version = process_namespace.gnu_get_libc_version
except AttributeError:
return None
gnu_get_libc_version.restype = ctypes.c_char_p
version_str = gnu_get_libc_version()
if (not isinstance(version_s... |
def voxel_downsample(points, voxel_size, normals=None):
pcd = make_open3d_point_cloud(points, normals=normals)
pcd = pcd.voxel_down_sample(voxel_size)
points = np.asarray(pcd.points)
if (normals is not None):
normals = np.asarray(pcd.normals)
return (points, normals)
else:
re... |
class SU3(Group):
def __init__(self):
self._nc = 3
self._free_params = 8
super().__init__(dim=4, shape=[3, 3], dtype=tf.complex128)
def update_gauge(self, x: Tensor, p: Tensor) -> Tensor:
return tf.matmul(tf.linalg.expm(p), x)
def checkSU(self, x: Tensor) -> tuple[(Tensor, Te... |
def test_get_wsgi_auth():
with pytest.raises(ValueError, match='Digest auth is not supported for WSGI apps'):
get_wsgi_auth(('test', 'test'), 'digest') |
class DistributedDocker(Docker):
def __init__(self, namingScheme: str='as{asn}{role}-{name}-{primaryIp}'):
super().__init__(namingScheme)
def getName(self) -> str:
return 'DistributedDocker'
def __compileIxNetMaster(self, net) -> str:
(scope, _, _) = net.getRegistryInfo()
ret... |
def test_too_many_dimensions():
cb = [1, 2, 3, 4]
A = np.random.rand(4, 4)
bad2D = [[1, 2], [3, 4]]
bad3D = np.random.rand(4, 4, 4)
assert_raises(ValueError, _clean_inputs, c=bad2D, A_ub=A, b_ub=cb)
assert_raises(ValueError, _clean_inputs, c=cb, A_ub=bad3D, b_ub=cb)
assert_raises(ValueError,... |
def grads(func, so_fact=1, side=1):
so = (func.space_order // so_fact)
comps = [getattr(func, ('d%s' % d.name))(x0=(d + ((side * d.spacing) / 2)), fd_order=so) for d in func.dimensions if d.is_Space]
st = tuple(([None] * func.grid.dim))
return VectorFunction(name=('grad_%s' % func.name), space_order=fun... |
class ExponentialDecay(LearningRateSchedule):
def __init__(self, initial_rate, decay_rate, decay_steps, staircase=True):
self.initial_rate = initial_rate
self.decay_rate = decay_rate
self.decay_steps = decay_steps
self.staircase = staircase
def _create_tensor(self, global_step):
... |
def random_bivariate_skew_Gaussian_center(kernel_size, sigma_x_range, sigma_y_range, rotation_range, noise_range=None, strict=False):
assert ((kernel_size % 2) == 1), 'Kernel size must be an odd number.'
assert (sigma_x_range[0] < sigma_x_range[1]), 'Wrong sigma_x_range.'
assert (sigma_y_range[0] < sigma_y_... |
def inception_v1(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.8, prediction_fn=slim.softmax, spatial_squeeze=True, reuse=None, scope='InceptionV1'):
with tf.variable_scope(scope, 'InceptionV1', [inputs, num_classes], reuse=reuse) as scope:
with slim.arg_scope([slim.batch_norm, slim.dropou... |
def eval_func_mp(distmat, q_pids, g_pids, q_camids, g_camids, max_rank=50, remove_junk=True):
(num_q, num_g) = distmat.shape
if (num_g < max_rank):
max_rank = num_g
print('Note: number of gallery samples is quite small, got {}'.format(num_g))
all_cmc = []
all_AP = []
print('Generatin... |
def main():
args = TrainOptions().parse()
args.distributed = ((args.world_size > 1) or args.multiprocessing_distributed)
args.world_batch_size = args.batchSize
ngpus_per_node = torch.cuda.device_count()
if args.multiprocessing_distributed:
args.world_size = (ngpus_per_node * args.world_size)... |
def nccl_skip_if_lt_x_gpu(backend, x):
def decorator(func):
(func)
def wrapper(*args, **kwargs):
if (backend != 'nccl'):
return func(*args, **kwargs)
if (torch.cuda.is_available() and (torch.cuda.device_count() >= x)):
return func(*args, **kwar... |
class DatasetFolder(VisionDataset):
def __init__(self, root: str, loader: Callable[([str], Any)], extensions: Optional[Tuple[(str, ...)]]=None, transform: Optional[Callable]=None, target_transform: Optional[Callable]=None, is_valid_file: Optional[Callable[([str], bool)]]=None, client: Optional[Any]=None) -> None:
... |
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(64, 128, 3, 1, 1)
self.relu1 = nn.ReLU()
self.conv2 = nn.Conv2d(128, 32, 3, 1, 1)
self.relu2 = nn.ReLU()
def forward(self, x):
y = (x.float() * 0.5)
a = self... |
def test_powermod_list():
assert (powermod_list(15, (Integer(1) / 6), 21) == [3, 6, 9, 12, 15, 18])
assert (powermod_list(2, (Integer(5) / 2), 11) == []) |
def parse_conf(parser, input):
args = parser.parse_args([])
d = (input if (type(input) == dict) else input.__dict__)
args.__dict__.update({k: v for (k, v) in d.items() if (k in args.__dict__)})
return args |
def add_single_scale_rpn_outputs(model, blob_in, dim_in, spatial_scale):
anchors = generate_anchors(stride=(1.0 / spatial_scale), sizes=cfg.RPN.SIZES, aspect_ratios=cfg.RPN.ASPECT_RATIOS)
num_anchors = anchors.shape[0]
dim_out = dim_in
model.Conv(blob_in, 'conv_rpn', dim_in, dim_out, kernel=3, pad=1, st... |
def check_model_table(overwrite=False):
(current_table, start_index, end_index, lines) = _find_text_in_file(filename=os.path.join(PATH_TO_DOCS, 'index.mdx'), start_prompt='<!--This table is updated automatically from the auto modules', end_prompt='<!-- End table-->')
new_table = get_model_table_from_auto_module... |
def _is_exception(obj) -> bool:
if (not inspect.isclass(obj)):
return False
return issubclass(obj, Exception) |
def main(args):
cfg = Config.fromfile(args.config)
for d in [cfg, cfg.data.test]:
d.update(dict(report_speed=args.report_speed))
if (args.score_threshold is not None):
cfg.test_cfg.min_score = args.score_threshold
print(json.dumps(cfg._cfg_dict, indent=4))
sys.stdout.flush()
data... |
.parametrize('inspecs', reduction_inspecs_params())
.parametrize('reduction', ['sum', 'mean', 'max', 'min', 'prod'])
.parametrize('axis', [None, 1])
def test_reduction_axis(inspecs, reduction, axis, nnabla_opts):
func = getattr(F, reduction)
fb = FunctionBenchmark(func, inspecs, [], dict(axis=axis), nnabla_opts... |
def safe_readline(f):
pos = f.tell()
while True:
try:
return f.readline()
except UnicodeDecodeError:
pos -= 1
f.seek(pos) |
def topic_coherence(dataset, beta, feature_names, n_top_words=10):
word_counts = {}
word_combination_counts = {}
length = len(dataset)
coherence_sum = 0.0
coherence_count = 0
topic_coherence_sum = 0.0
for i in range(len(beta)):
top_words = [j for j in beta[i].argsort()[:((- n_top_wor... |
_level_function()
def corr(x, y, weight=None, axis=None, *, keepdims=False, mask_identity=False, highlevel=True, behavior=None, attrs=None):
(yield (x, y, weight))
return _impl(x, y, weight, axis, keepdims, mask_identity, highlevel, behavior, attrs) |
def get_sex_threshold_plotting():
thresholds = {genome: get_param(keys=['sex_inference', genome, 'thresholds'], def_value='list( "XX"=c(0.8, 1), "XY"=c(0, 0.6), "consistent with XX but not XY"=c(0.6, 1), "consistent with XY but not XX"=c(0, 0.8) )') for genome in GENOMES}
sex_thresholds = 'list({pair})'.format(... |
def get_fed_loss_cls_weights_v2(dataset_names: Union[(str, List[str])], freq_weight_power=1.0):
if isinstance(dataset_names, str):
dataset_names = [dataset_names]
logger = logging.getLogger(__name__)
class_freq_weight_list = []
for dataset_name in dataset_names:
if (MetadataCatalog.get(d... |
class ResBlockDiscriminator(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(ResBlockDiscriminator, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, 1, padding=1)
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, padding=1)
nn.ini... |
def concatenate_tensors(tensor1, tensor2):
diff_height = (tensor2.size()[2] - tensor1.size()[2])
diff_width = (tensor2.size()[3] - tensor1.size()[3])
tensor1 = F.pad(tensor1, [(diff_width // 2), (diff_width - (diff_width // 2)), (diff_height // 2), (diff_height - (diff_height // 2))])
return torch.cat([... |
def test_flatten_labels_1():
y = pd.DataFrame({'Product': ['Debt collection', 'Checking or savings account'], 'Sub-product': ['I do not know', 'Checking account']})
flat_y = flatten_labels(y)
ground_truth = pd.Series(['Debt collection:sep:I do not know', 'Checking or savings account:sep:Checking account'])
... |
class PayoffTable():
identify: AgentID
agents: Sequence[AgentID]
shared_simulation_flag: SimulationFlag
table: Any = None
def __post_init__(self):
self._policy_idx = {agent: {} for agent in self.agents}
if (self.table is not None):
assert (len(self.table.shape) == len(sel... |
class A001109(RecurrenceSequence2):
def __init__(self):
SloaneSequence.__init__(self, offset=0)
self._params = (0, 1, 6, (- 1))
self._b = []
self._precompute(2)
def _repr_(self):
return 'a(n)^2 is a triangular number: a(n) = 6*a(n-1) - a(n-2) with a(0)=0, a(1)=1' |
def skip_in_ci(test_function):
return pytest.mark.skipif((os.environ.get('CI') == 'true'), reason="This test doesn't work on GitHub Actions.")(test_function) |
def time_multihead_attention(q, num_heads, k=None, v=None, mask=False, mode='self', bias=True, do_backprop=True, fp='fp32', use_apex=False, num_iters=100, num_warmups=5):
if use_apex:
from apex import amp
embed_size = q.size(2)
attn = torch.nn.MultiheadAttention(embed_size, num_heads, bias=bias).to(... |
def test_in_order_unary():
check_reproduce_tree(transition_scheme=TransitionScheme.IN_ORDER_UNARY) |
def get_deepspeech(device: torch.device) -> GetterReturnType:
sample_rate = 16000
window_size = 0.02
window = 'hamming'
audio_conf = dict(sample_rate=sample_rate, window_size=window_size, window=window, noise_dir=None)
N = 10
num_classes = 10
spectrogram_size = 161
seq_length = 500
t... |
class DPRContextEncoderState(DPRState):
def load_dpr_model(self):
model = DPRContextEncoder(DPRConfig(**BertConfig.get_config_dict('bert-base-uncased')[0]))
print(f'Loading DPR biencoder from {self.src_file}')
saved_state = load_states_from_checkpoint(self.src_file)
(encoder, prefix)... |
.parametrize('image_shape', [(111,), (33, 44), (22, 55, 11), (6, 5, 4, 3)])
.parametrize('order', ['C', 'F'])
def test_offsets_to_raveled_neighbors_highest_connectivity(image_shape, order):
footprint = np.ones(((3,) * len(image_shape)), dtype=bool)
center = ((1,) * len(image_shape))
offsets = _util._offsets... |
def process(source_sent, target_sent, hypo_sent, metric):
source_bpe = ' '.join(sp.EncodeAsPieces(source_sent))
hypo_bpe = [' '.join(sp.EncodeAsPieces(h)) for h in hypo_sent]
if (metric == 'bleu'):
score_str = [get_bleu(h, target_sent) for h in hypo_sent]
else:
score_str = [get_ter(h, ta... |
def setup_file_observer():
file_obs_path = os.path.join(results_path, 'sacred')
logger.info('FileStorageObserver path: {}'.format(file_obs_path))
logger.info('Using the FileStorageObserver in results/sacred')
ex.observers.append(FileStorageObserver.create(file_obs_path))
pass |
def fricas_integrator(expression, v, a=None, b=None, noPole=True):
if (not isinstance(expression, Expression)):
expression = SR(expression)
from sage.interfaces.fricas import fricas
e_fricas = fricas(expression)
v_fricas = fricas(v)
if (a is None):
result = e_fricas.integrate(v_frica... |
class POXL2Learning(Controller):
def start(self):
self.pox = ('%s/pox/pox.py' % POX_PATH)
pox_opts = set_pox_opts('forwarding.l2_learning', 'DEBUG', (('logs/' + type(self).__name__) + '.log,w'))
self.cmd(self.pox, pox_opts)
def stop(self):
self.cmd(('kill %' + self.pox)) |
def correctedProgram(input_program, init_state, final_state, exception_str, verbose=True, id_mapping={}):
instructions_program = input_program[4:]
program_header = input_program[:4]
try:
(line_exception, exception, argument_exception) = parseException(exception_str, verbose)
except ValueError:
... |
.slow
def test_train_eval(tmp_path, cfg_train, cfg_eval):
assert (str(tmp_path) == cfg_train.paths.output_dir == cfg_eval.paths.output_dir)
with open_dict(cfg_train):
cfg_train.trainer.max_epochs = 1
cfg_train.test = True
HydraConfig().set_config(cfg_train)
(train_metric_dict, _) = train... |
_module()
class SingleStageTextDetector(SingleStageDetector):
def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None, init_cfg=None):
SingleStageDetector.__init__(self, backbone, neck, bbox_head, train_cfg, test_cfg, pretrained, init_cfg)
def forward_train(self, img... |
.parametrize('ty,num', sub_table)
_utils.test(arch=[ti.cpu, ti.cuda, ti.vulkan], debug=True)
def test_sub_overflow_i(capfd, ty, num):
if (not supports_overflow(ti.lang.impl.current_cfg().arch)):
return
capfd.readouterr()
def foo(num: ty) -> ty:
a = ty(num)
b = ty((- num))
ret... |
_model_architecture('transformer_lm', 'transformer_lm_gpt2_big')
def transformer_lm_gpt2_big(args):
args.decoder_embed_dim = safe_getattr(args, 'decoder_embed_dim', 1600)
args.decoder_ffn_embed_dim = safe_getattr(args, 'decoder_ffn_embed_dim', 6400)
args.decoder_layers = safe_getattr(args, 'decoder_layers',... |
class HourOfDay(TimeFeature):
def __call__(self, index: pd.DatetimeIndex) -> np.ndarray:
return ((index.hour / 23.0) - 0.5) |
def readFile(fileName):
fileExist = os.path.exists(fileName)
if (fileExist == False):
print('The file is not available in the directory')
return
readFile = open(fileName, 'r')
readContent = readFile.read()
readFile.close()
print(readContent)
readFile = open(fileName, 'r+')
... |
def FriendshipGraph(n):
if (n < 1):
raise ValueError('n must be a positive integer')
if (n == 1):
from sage.graphs.generators.basic import CycleGraph
G = CycleGraph(3)
G.name('Friendship graph')
return G
N = ((2 * n) + 1)
center = (2 * n)
G = Graph(N, name='Fr... |
class Test_density(TestCase):
def test_works_water(self):
M = (1 * aq.kg)
R = (1 * aq.m)
answer = ((0.2387 * aq.kg) / (aq.m ** 3))
result = Density(M, R).density.rescale((aq.kg / (aq.m ** 3)))
self.assertAlmostEqual(answer, result, 3)
def test_works_hd189(self):
M... |
def entity_linking(e_spans, verbose=False, cutoff=500, threshold=0):
guessed_ids = []
for span in e_spans:
span_ids = e_index.label_scores(span, top=cutoff, threshold=threshold, verbose=verbose, scale=0.3, max_degree=100000)
guessed_ids.append(span_ids)
return guessed_ids |
class SetVariable(goos.Action):
node_type = 'goos.action.set_variable'
def __init__(self, var: Variable, value: Function) -> None:
super().__init__(var)
self._var = var
self._value = value
if ((not isinstance(value, numbers.Number)) and (not isinstance(value, Function))):
... |
def list_files(root: str, suffix: str, prefix: bool=False):
root = os.path.expanduser(root)
files = [p for p in os.listdir(root) if (os.path.isfile(os.path.join(root, p)) and p.endswith(suffix))]
if (prefix is True):
files = [os.path.join(root, d) for d in files]
return files |
def tqdm_report_hook():
def report_hook(pbar, count, block_size, total_size):
if ((pbar.total is None) and total_size):
pbar.total = total_size
progress_bytes = (count * block_size)
pbar.update((progress_bytes - pbar.n))
pbar = tqdm(total=None)
return partial(report_hook,... |
def get_multiclass_recall(preds, y_label, n_classes):
label_cat = range(n_classes)
labels_accu = {}
for la in label_cat:
idx_of_cat = (y_label == la)
cat_preds = preds[idx_of_cat]
if (cat_preds.size != 0):
accu = np.mean((cat_preds == la))
labels_accu[la] = [a... |
class AutoDirect(AutoFallbackSolver):
name = 'ls.auto_direct'
_ls_solvers = [('ls.mumps', {}), ('ls.scipy_umfpack', {}), ('ls.scipy_superlu', {})] |
def load_state_dict(model, state_dict, prefix='', ignore_missing='relative_position_index'):
missing_keys = []
unexpected_keys = []
error_msgs = []
metadata = getattr(state_dict, '_metadata', None)
state_dict = state_dict.copy()
if (metadata is not None):
state_dict._metadata = metadata
... |
def vgg_19(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_19', fc_conv_padding='VALID', global_pool=False):
with tf.variable_scope(scope, 'vgg_19', [inputs], reuse=tf.AUTO_REUSE) as sc:
end_points_collection = (sc.original_name_scope + '_end_points')
... |
def pytest_collection_modifyitems(config, items):
skip_doctests = False
if (np_base_version >= parse_version('2')):
reason = 'Due to NEP 51 numpy scalar repr has changed in numpy 2'
skip_doctests = True
for item in items:
if isinstance(item, DoctestItem):
item.dtest.globs... |
def get_within_circle_constraint(r: float) -> Callable[([List[float]], float)]:
def _constraint(x_y: List[float]) -> float:
(x, y) = x_y
return ((np.square(r) - np.square(x)) - np.square(y))
return _constraint |
_fusion('linear_sum')
class LinearSum(nn.Module):
def __init__(self, input_dims, output_dim, mm_dim=1200, activ_input='relu', activ_output='relu', normalize=False, dropout_input=0.0, dropout_pre_lin=0.0, dropout_output=0.0):
super().__init__()
self.input_dims = input_dims
self.output_dim = o... |
def register_Ns3MmWaveMacCschedSapProvider_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::MmWaveMacCschedSapProvider const &', 'arg0')])
cls.add_method('CschedCellConfigReq', 'void', [param('ns3::MmWaveMacCschedSapProvider::CschedCellConfigReqParameters const &', 'params... |
class NormalBlock(Block):
def __init__(self, x=0, y=0, h=1, w=1, value=(- 0.1)):
super(NormalBlock, self).__init__(x, y, h, w)
self.color = '#FFFFFFFF'
self.name = 'NormalBlock'
self.value = value |
def create_pipeline(context, mode, exclude_classes=()):
assert (mode in ('pyx', 'py', 'pxd'))
from .Visitor import PrintTree
from .ParseTreeTransforms import WithTransform, NormalizeTree, PostParse, PxdPostParse
from .ParseTreeTransforms import ForwardDeclareTypes, InjectGilHandling, AnalyseDeclarations... |
_task('laser')
class LaserTask(LegacyFairseqTask):
def add_args(parser):
parser.add_argument('configfile', metavar='PATH', help='dataset configuration file in json')
parser.add_argument('--weighting-alpha', type=float, default=None, help='alpha for automatic weighting')
parser.add_argument('... |
def main():
args_parser = ArgumentParser()
args_parser.add_argument('--lexicon', required=True)
args_parser.add_argument('--input', required=True)
args_parser.add_argument('--disamb_map', required=True)
args_parser.add_argument('--disamb', action='store_true')
args_parser.add_argument('--output'... |
def make_update_fn():
def _update_step(runner_state):
step_fn = jax.vmap(auto_reset(env.step, env.init))
def _env_step(runner_state, unused):
(params, opt_state, env_state, last_obs, rng) = runner_state
(rng, _rng) = jax.random.split(rng)
(logits, value) = forward... |
class Params(MutableMapping):
DEFAULT = object()
def __init__(self, params: Dict[(str, Any)], history: str='', loading_from_archive: bool=False, files_to_archive: Dict[(str, str)]=None) -> None:
self.params = _replace_none(params)
self.history = history
self.loading_from_archive = loadin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.