code stringlengths 101 5.91M |
|---|
def test():
a = ak.operations.to_numpy(ak.highlevel.Array({'A': [1, 2, 3], 'B': [4, None, 5]}))
assert (a['A'].data.tolist() == [1, 2, 3])
assert (a['A'].mask.tolist() == [False, False, False])
assert (a['B'].data[0] == 4)
assert (a['B'].data[2] == 5)
assert (a['A'].mask.tolist() == [False, Fals... |
class ConditionalDecoder(nn.Module):
def __init__(self, input_size, hidden_size, ctx_size_dict, ctx_name, n_vocab, rnn_type, tied_emb=False, dec_init='zero', dec_init_activ='tanh', dec_init_size=None, att_type='mlp', att_activ='tanh', att_bottleneck='ctx', att_temp=1.0, transform_ctx=True, mlp_bias=False, dropout_o... |
def _conv_type_shape(im):
(typ, extra) = _MODE_CONV[im.mode]
if (extra is None):
return ((im.size[1], im.size[0]), typ)
else:
return ((im.size[1], im.size[0], extra), typ) |
def suppress_output():
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
if ('force' in kwargs):
force = kwargs.pop('force')
if force:
builtin_print(*args, **kwargs)
__builtin__.print = print |
class SwishX(nn.Module):
def __init__(self, maxvalue=2.72):
super(SwishX, self).__init__()
self.maximal = nn.Parameter(torch.FloatTensor([maxvalue]))
def forward(self, x):
output = (x * torch.sigmoid(x))
output = output.sub(self.maximal).clamp(max=0.0).add(self.maximal)
r... |
def collate_fn(batch):
(seq, label) = zip(*batch)
seql = [x.reshape((- 1)) for x in seq]
data = rnn_utils.pad_sequence(seql, batch_first=True, padding_value=0)
label = torch.tensor(list(label))
return (data, label) |
def pairwise_circleloss(embedding: torch.Tensor, targets: torch.Tensor, margin: float, gamma: float) -> torch.Tensor:
embedding = F.normalize(embedding, dim=1)
dist_mat = torch.matmul(embedding, embedding.t())
N = dist_mat.size(0)
is_pos = targets.view(N, 1).expand(N, N).eq(targets.view(N, 1).expand(N, ... |
def randn(g, shapes, dtype, *options):
dtype = sym_help._get_const(dtype, 'i', 'dtype')
if (dtype is None):
dtype = 6
if sym_help._is_packed_list(shapes):
shape_const = g.op('ConstantOfShape', shapes, value_t=torch.tensor([0], dtype=sym_help.scalar_type_to_pytorch_type[6]))
return g.... |
def plot_prior_grad_RS(teacher, student):
df = check_prior_grad_RS(teacher, student)
(fig, axs) = plt.subplots(1, 3, figsize=(12, 4))
axs[0].plot(df['mx_hat'], df['mx'], '-', label='$m_x$')
axs[0].plot(df['mx_hat'], df['grad_mx_hat_A'], '--', label='$\\partial_{\\widehat{m}_x^-} A$')
axs[0].set(xlab... |
class LoggerFactory(object):
def create(path, module_name):
logger = logging.getLogger(module_name)
logger.setLevel(logging.DEBUG)
try:
os.makedirs(path)
except OSError as e:
if (e.errno != errno.EEXIST):
raise
fh = RotatingFileHandler(... |
class IsotropicMorphology2D():
param_names = ['shape', 'radius']
params = [((512, 512),), (1, 3, 5, 15, 25, 40)]
def setup(self, shape, radius):
rng = np.random.default_rng(123)
self.image = (rng.standard_normal(shape) < 3.5)
def time_erosion(self, shape, radius, *args):
morpholo... |
def test_basic_pytest_graphql(testdir, graphql_path, graphql_url):
testdir.make_test(f'''
schema = schemathesis.graphql.from_url('{graphql_url}')
()
(max_examples=10, deadline=None, suppress_health_check=[HealthCheck.too_slow, HealthCheck.filter_too_much])
def test_(request, case):
request.config.HYPOTHESIS_CAS... |
class randint_gen(rv_discrete):
def _shape_info(self):
return [_ShapeInfo('low', True, ((- np.inf), np.inf), (False, False)), _ShapeInfo('high', True, ((- np.inf), np.inf), (False, False))]
def _argcheck(self, low, high):
return (((high > low) & _isintegral(low)) & _isintegral(high))
def _ge... |
class ConcatDataset(Dataset):
def __init__(self, datasets, total_samples, weights=None):
if (weights is None):
weights = [(1.0 / float(len(datasets))) for _ in range(len(datasets))]
assert (abs((sum(weights) - 1.0)) < 1e-06), 'Sum of weights is {}. Should be 1'.format(sum(weights))
... |
def sig_for_ops(opname):
assert (opname.endswith('__') and opname.startswith('__')), 'Unexpected op {}'.format(opname)
name = opname[2:(- 2)]
if (name in binary_ops):
return ['def {}(self, other: Any) -> Tensor: ...'.format(opname)]
elif (name in comparison_ops):
return ['def {}(self, ot... |
def commit_loss(x1, x2):
norm = np.prod(x1.shape[1:])
loss = nn.MSELoss(reduction='sum')(x1, x2)
return (loss / norm) |
class TotalVariationDistance(Layer):
def call(self, x):
diff_dist = Subtract()([x[0], x[1]])
return K.sum(K.abs(diff_dist), axis=1) |
class Data2VecAudioForCTC(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class BaseTrainer():
def __init__(self, args: argparse.Namespace):
self.args = args
self._debug = self.args.debug
name = str(datetime.datetime.now()).replace(' ', '_')
self._log_path = os.path.join(self.args.log_path, self.args.label, name)
util.create_directories_dir(self._l... |
def validateaxis(axis) -> None:
if (axis is None):
return
axis_type = type(axis)
if (axis_type == tuple):
raise TypeError("Tuples are not accepted for the 'axis' parameter. Please pass in one of the following: {-2, -1, 0, 1, None}.")
if (not np.issubdtype(np.dtype(axis_type), np.integer)... |
class SLayerNorm(nn.LayerNorm):
def __init__(self, normalized_shape: int, eps: float=1e-05, elementwise_affine: bool=True) -> None:
super(SLayerNorm, self).__init__(normalized_shape, eps, elementwise_affine)
self.staticize()
def staticize(self):
self.sample_normalized_shape = self.normal... |
_paths
def parse_args(args=None, namespace=None):
parser = argparse.ArgumentParser(description='Extract audio from videos.')
parser.add_argument('-i', '--in_dir', type=pathlib.Path, required=True, help='input directory')
parser.add_argument('-o', '--out_dir', type=pathlib.Path, required=True, help='output d... |
class IndexedFreeAbelianMonoid(IndexedMonoid):
def _repr_(self):
return 'Free abelian monoid indexed by {}'.format(self._indices)
def _element_constructor_(self, x=None):
if isinstance(x, (list, tuple)):
d = dict()
for (k, v) in x:
if (k in d):
... |
class Embedding(Layer):
def __init__(self, input_dim, output_dim, init='uniform', name=None):
super(Embedding, self).__init__()
self.init = initializations.get(init)
self.input_dim = input_dim
self.output_dim = output_dim
self.W = self.init((self.input_dim, self.output_dim), ... |
class miniImageNet(ImageFolder):
def __init__(self, root: str, mode: str, backbone_name='resnet12', image_sz=84) -> None:
assert (mode in ['train', 'val', 'test'])
self.mode = mode
(_, train_process, val_process) = load(backbone_name, jit=False)
IMAGE_PATH = os.path.join(root, mode)
... |
_module()
class SRFolderRefDataset(BaseSRDataset):
def __init__(self, pipeline, scale, ref_folder, gt_folder=None, lq_folder=None, test_mode=False, filename_tmpl_gt='{}', filename_tmpl_lq='{}'):
super().__init__(pipeline, scale, test_mode)
assert (gt_folder or lq_folder), 'At least one of gt_folder ... |
class ModularSymbolsSubspace(sage.modular.modsym.space.ModularSymbolsSpace, hecke.HeckeSubmodule):
def __init__(self, ambient_hecke_module, submodule, dual_free_module=None, check=False):
self.__ambient_hecke_module = ambient_hecke_module
A = ambient_hecke_module
sage.modular.modsym.space.Mo... |
class BaseMetric(ABC):
def __init__(self, recommendations, config, params, evaluation_objects, additional_data=None):
self._recommendations: t.Dict[(int, t.List[t.Tuple[(int, float)]])] = recommendations
self._config = config
self._params = params
self._evaluation_objects = evaluatio... |
def base_prob2pianoroll(probs):
base_list = [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
index = np.argmax(probs, axis=0)
pianoroll = [0 for i in range(128)]
pianoroll[base_list[index]] = 1
pianoroll = np.asarray(pianoroll)
return pianoroll |
def save_csv_notes(filename, data):
assert (data.shape[1] == 5)
np.savetxt(filename, data, fmt='%d', delimiter=',', header='beat,position,pitch,duration,program', comments='') |
_quant_pattern(torch.nn.AdaptiveAvgPool1d)
_quant_pattern(torch.nn.AdaptiveAvgPool2d)
_quant_pattern(torch.nn.AdaptiveAvgPool3d)
_quant_pattern(torch.nn.AvgPool1d)
_quant_pattern(torch.nn.AvgPool2d)
_quant_pattern(torch.nn.AvgPool3d)
_quant_pattern(torch.nn.Dropout)
_quant_pattern(torch.nn.Hardsigmoid)
_quant_pattern(t... |
class SBMCDCEig(SBMCLUSTEREval, BaseEigModelScheme):
def get_default_config(self):
config_dict = super().get_default_config()
config_dict.update(dataset_name='sbm_cluster', class_sizes=[19695, 19222, 19559, 19417, 19801, 20139])
return config_dict
def get_dataset_config(self, splits=['tr... |
def create_jsonl_candidates_for_pyserini(train_dir):
list_dir = [x for x in os.walk(train_dir)]
for sub_dir in list_dir[0][1]:
with jsonlines.open(os.path.join(train_dir, sub_dir, 'candidates.jsonl'), mode='w') as writer:
list_sub_dir_paragraphs = [x for x in os.walk(os.path.join(train_dir, ... |
.parametrize('beam_size,expected', [(1, False), (2, False), (5, True)])
def test_beam_search(beam_size, expected):
start_node = 'Arad'
goal_fn = (lambda x: (x == 'Fagaras'))
(goal, _, path) = generalized_a_star_search(start_node=start_node, expand_fn=expand_fn, goal_fn=goal_fn, beam_size=beam_size, return_p... |
def call_ChatGPT(message, model_name='gpt-3.5-turbo', max_len=1024, temp=0.7, verbose=False):
response = None
received = False
num_rate_errors = 0
while (not received):
try:
response = openai.ChatCompletion.create(model=model_name, messages=message, max_tokens=max_len, temperature=te... |
def skipCUDAMemoryLeakCheckIf(condition):
def dec(fn):
if getattr(fn, '_do_cuda_memory_leak_check', True):
fn._do_cuda_memory_leak_check = (not condition)
return fn
return dec |
def test_ByteMaskedArray_NumpyArray():
array = ak.Array(ak.contents.ByteMaskedArray(ak.index.Index(np.array([1, 0, 1, 0, 1], np.int8)), ak.contents.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])), valid_when=True), backend='cuda')
results = nb_cuda.to_device(np.empty(5, dtype=np.float64))
pass_through[... |
class PatchImageDiscriminator(nn.Module):
def __init__(self, n_channels, ndf=64, use_noise=False, noise_sigma=None):
super(PatchImageDiscriminator, self).__init__()
self.use_noise = use_noise
self.main = nn.Sequential(Noise(use_noise, sigma=noise_sigma), nn.Conv2d(n_channels, ndf, 4, 2, 1, b... |
def validation_transforms(sample, image_shape):
if (len(image_shape) > 0):
sample['rgb'] = resize_image(sample['rgb'], image_shape)
sample = to_tensor_sample(sample)
return sample |
class DatasetOnlineLoad(torchdata.Dataset):
def __init__(self, files, n_max_samples=(- 1)):
self.files = files
self.n_samples = len(self.files)
if (n_max_samples != (- 1)):
self.n_samples = min(self.n_samples, n_max_samples)
def __len__(self):
return self.n_samples
... |
def _minkan(state: State):
c_p = state.current_player
l_p = state._last_player
state = _accept_riichi(state)
src = ((l_p - c_p) % 4)
meld = Meld.init(Action.MINKAN, state._target, src)
state = _append_meld(state, meld, c_p)
hand = state._hand.at[c_p].set(Hand.minkan(state._hand[c_p], state._... |
def test():
net = MobileNet()
x = torch.randn(1, 3, 32, 32)
y = net(x)
print(y.size()) |
def anisotropic_scaling(img, p):
if (random.random() < (1 - p)):
return img
s = np.random.lognormal(0, (0.2 * np.log(2)))
if (s < 1):
s = (2 - s)
(H, W) = (img.size()[(- 2)], img.size()[(- 1)])
if (random.random() > 0.5):
img = transforms.functional.resize(img, (int((H * s)),... |
class RaiseStatNode(StatNode):
child_attrs = ['exc_type', 'exc_value', 'exc_tb', 'cause']
is_terminator = True
def analyse_expressions(self, env):
if self.exc_type:
exc_type = self.exc_type.analyse_types(env)
self.exc_type = exc_type.coerce_to_pyobject(env)
if self.ex... |
class ResnetDownsampleBlock3D(nn.Module):
def __init__(self, in_channels: int, out_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, resnet_pre_norm: bool=True, output_scale_fa... |
class StdoutTee(Tee):
def set_stream(self, stream):
sys.stdout = stream
def get_stream(self):
return sys.stdout |
def main():
args = parse_args()
set_seed(args.seed)
if (args.data == 'lba'):
log = Logger(f'{args.save_path}pdbbind_{args.split}/', f"pdbind_{strftime('%Y-%m-%d_%H-%M-%S', localtime())}.log")
else:
log = Logger(f'{args.save_path}lep/', f"lep_{strftime('%Y-%m-%d_%H-%M-%S', localtime())}.l... |
def convert_diarization(base_model_name, hf_config, downstream_dict):
model = UniSpeechSatForAudioFrameClassification.from_pretrained(base_model_name, config=hf_config)
model.classifier.weight.data = downstream_dict['model.linear.weight']
model.classifier.bias.data = downstream_dict['model.linear.bias']
... |
class TestSignal(TestCore):
SIGNALS = [(IntegerSignal, 99), (FloatSignal, 55.3), (DoubleSignal, 22.2), (StringSignal, 'hello')]
def test_set_get_clear_signals(self):
for (signal_class, test_value) in TestSignal.SIGNALS:
with self.subTest(signal=str(signal_class)):
sig = signa... |
class ExtRandomRotation(object):
def __init__(self, degrees, resample=False, expand=False, center=None):
if isinstance(degrees, numbers.Number):
if (degrees < 0):
raise ValueError('If degrees is a single number, it must be positive.')
self.degrees = ((- degrees), degr... |
def build_err_msg(arrays, err_msg, header='Items are not equal:', verbose=True, names=('ACTUAL', 'DESIRED'), precision=8):
msg = [('\n' + header)]
if err_msg:
if ((err_msg.find('\n') == (- 1)) and (len(err_msg) < (79 - len(header)))):
msg = [((msg[0] + ' ') + err_msg)]
else:
... |
def maybe_download_and_extract(data_url):
dest_directory = FLAGS.model_dir
if (not os.path.exists(dest_directory)):
os.makedirs(dest_directory)
filename = data_url.split('/')[(- 1)]
filepath = os.path.join(dest_directory, filename)
if (not os.path.exists(filepath)):
def _progress(cou... |
class VisionTextDualEncoderModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class GIN(torch.nn.Module):
def __init__(self, args):
super(GIN, self).__init__()
self.args = args
self.layers = torch.nn.ModuleList([])
for i in range((args['num_layers'] + 1)):
dim_input = (args['num_features'] if (i == 0) else args['hidden_dim'])
nn = Seque... |
def main(_):
config = flags.FLAGS
config.out_dir = os.path.join(config.out_base_dir, config.model_name, str(config.run_id).zfill(2))
m(config) |
()
def assigner():
Assigner.define_task_assignments = mock.Mock()
assigner = Assigner(None, None, None)
assigner.define_task_assignments = mock.Mock()
return assigner |
def register_statistics(name: str, stats_cls: Type[Stats]):
AVAILBALE_STATS[name] = stats_cls
AVAILBALE_STATS[(name + '_loss_per_batch')] = stats_cls |
def create_error_vector_with_count_above_vector(target_vector=None, argsort_vector=None, rank_weighting_vector=None, count_above_vector=None):
assert (target_vector is not None)
assert (argsort_vector is not None)
assert (rank_weighting_vector is not None)
assert (count_above_vector is not None)
ass... |
class GCNPropagate(tnn.MessagePassing):
def __init__(self, improved: bool=False, cached: bool=False, add_self_loops: bool=True, normalization: str='sym', **kwargs):
kwargs.setdefault('aggr', 'add')
super().__init__(**kwargs)
self.improved = improved
self.cached = cached
self.... |
_module()
class PascalContextDataset(CustomDataset):
CLASSES = ('background', 'aeroplane', 'bag', 'bed', 'bedclothes', 'bench', 'bicycle', 'bird', 'boat', 'book', 'bottle', 'building', 'bus', 'cabinet', 'car', 'cat', 'ceiling', 'chair', 'cloth', 'computer', 'cow', 'cup', 'curtain', 'dog', 'door', 'fence', 'floor', ... |
class BatchNormalization(ModelLayer):
def __init__(self, model, input_record, name='batch_normalization', scale_optim=None, bias_optim=None, momentum=0.9, order='NCHW', scale_init_value=1.0, **kwargs):
super(BatchNormalization, self).__init__(model, name, input_record, **kwargs)
assert isinstance(in... |
def init_segmentor(config, checkpoint=None, device='cuda:0', classes=None, palette=None, revise_checkpoint=[('^module\\.', '')]):
if isinstance(config, str):
config = mmcv.Config.fromfile(config)
elif (not isinstance(config, mmcv.Config)):
raise TypeError('config must be a filename or Config obj... |
class QAttentionStackAgent(Agent):
def __init__(self, qattention_agents: List[QAttentionAgent], rotation_resolution: float, camera_names: List[str], rotation_prediction_depth: int=0):
super(QAttentionStackAgent, self).__init__()
self._qattention_agents = qattention_agents
self._rotation_reso... |
def add_attached_file(filename):
sage.repl.inputhook.install()
fpath = os.path.abspath(filename)
attached[fpath] = os.path.getmtime(fpath) |
def get_image_list(train_list_path):
with open(train_list_path) as f:
imgs = f.readlines()
imgs = [img.replace('\n', '') for img in imgs]
return imgs |
class PieriFactors_type_A_affine(PieriFactors_affine_type):
def __classcall__(cls, W, min_length=0, max_length=infinity, min_support=frozenset([]), max_support=None):
assert (W.cartan_type().is_affine() and (W.cartan_type().letter == 'A'))
min_support = frozenset(min_support)
if (max_support... |
def test_list_real():
a = ak.highlevel.ArrayBuilder()
a.begin_list()
a.real(1.1)
a.real(2.2)
a.real(3.3)
a.end_list()
a.begin_list()
a.end_list()
a.begin_list()
a.real(4.4)
a.real(5.5)
a.end_list()
assert (to_list(a.snapshot()) == [[1.1, 2.2, 3.3], [], [4.4, 5.5]])
... |
.parametrize('pd_dtype', ['Int8', 'Int16', 'UInt8', 'UInt16', 'Float32', 'Float64'])
.parametrize('dtype, expected_dtype', [([np.float32, np.float64], np.float32), (np.float64, np.float64), ('numeric', np.float64)])
def test_check_array_pandas_na_support(pd_dtype, dtype, expected_dtype):
pd = pytest.importorskip('p... |
def all_gather_list(data, group=None, max_size=16384):
SIZE_STORAGE_BYTES = 4
enc = pickle.dumps(data)
enc_size = len(enc)
if ((enc_size + SIZE_STORAGE_BYTES) > max_size):
raise ValueError('encoded data exceeds max_size, this can be fixed by increasing buffer size: {}'.format(enc_size))
rank... |
def _init():
global _plugin
if (_plugin is None):
_plugin = custom_ops.get_plugin(module_name='filtered_lrelu_plugin', sources=['filtered_lrelu.cpp', 'filtered_lrelu_wr.cu', 'filtered_lrelu_rd.cu', 'filtered_lrelu_ns.cu'], headers=['filtered_lrelu.h', 'filtered_lrelu.cu'], source_dir=os.path.dirname(__f... |
def register_Ns3AnimPacketInfo_methods(root_module, cls):
cls.add_constructor([param('ns3::AnimPacketInfo const &', 'arg0')])
cls.add_constructor([])
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice const >', 'tx_nd'), param('ns3::Time const &', 'fbTx'), param('ns3::Time const &', 'lbTx'), param('ns3::V... |
class Tanh_GoogLeNet(nn.Module):
def __init__(self):
super(Tanh_GoogLeNet, self).__init__()
self.pre_layers = nn.Sequential(nn.Conv2d(3, 192, kernel_size=3, padding=1), nn.BatchNorm2d(192), nn.Tanh())
self.a3 = Inception(192, 64, 96, 128, 16, 32, 32)
self.b3 = Inception(256, 128, 128... |
def template_simulation_with_mtls(spec, scene, sim_props, delete_on_clean=False, caching=False, save_maya_scene=False):
shd_names = list(scene.Mtls.material_types)
num_body = 1
sim_names = list(sim_props.keys())
names = list(set(shd_names).intersection(sim_names))
for name in names:
print('=... |
def load_transform_data_fn(path):
labels = []
data = []
max_trace_len = (- 1)
for fn in tqdm(os.listdir(path)):
file_path = os.path.join(path, fn)
if os.path.isfile(file_path):
cell_list = load_cell(file_path)
if ('-' in str(fn)):
labels.append(1)
... |
class BiaffineScorer(nn.Module):
def __init__(self, input1_size, input2_size, output_size):
super().__init__()
self.W_bilin = nn.Bilinear((input1_size + 1), (input2_size + 1), output_size)
self.W_bilin.weight.data.zero_()
self.W_bilin.bias.data.zero_()
def forward(self, input1, i... |
def quantile(arr, q, weights=None):
q = np.clip(q, 0, 1)
if (len(arr) == 0):
return (np.zeros(len(q)) if hasattr(q, '__len__') else 0)
if (weights is None):
return np.quantile(arr, q, method='inverted_cdf')
assert (len(weights) == len(arr))
idx = np.argsort(arr)
weights = np.cums... |
class DataMixin():
def load_data(self, file_path, nrows=None):
if (nrows is None):
self.logger.info('Loading the time series...')
df = pd.read_csv(file_path, nrows=nrows)
index_type = df.dtypes[df.columns[0]]
df = df.set_index(df.columns[0])
df.index = pd.to_datet... |
def freq_calc(create_loss, nbins=None):
(loss, (_, __, mean, ___)) = create_loss(npeak=80, nbins=nbins)
calculator = FrequentistCalculator.from_yaml(f'{notebooks_dir}/toys/ci_freq_zfit_toys.yml', loss, Minuit())
return (mean, calculator) |
class FFN(nn.Module):
def __init__(self, hidden_size, ff_size, dropout):
super(FFN, self).__init__()
self.mlp = MLP(in_size=hidden_size, mid_size=ff_size, out_size=hidden_size, dropout_r=dropout, use_relu=True)
def forward(self, x):
return self.mlp(x) |
def _get_dataset(sets, feature_dir, is_train=False):
return TransformDataset(LoadData(sets, feature_dir), TransformData(is_train)) |
.unit
.convert
def test_slice_idx_generator_z0():
shape = (4305, 9791)
zoom = 0
tile_size = 256
given = convert.slice_idx_generator(shape, zoom, tile_size)
expected = helpers.get_slice_idx_generator_solution(zoom)
comparable_given = set(map(helpers.covert_idx_to_hashable_tuple, given))
compa... |
def action_prob_detection(bbox):
center_point = np.array([((bbox[0] + bbox[2]) / 2), ((bbox[1] + bbox[3]) / 2)])
left_prob = np.linalg.norm((center_point - np.array([0, 150])))
right_prob = np.linalg.norm((center_point - np.array([300, 150])))
up_prob = np.linalg.norm((center_point - np.array([150, 0]))... |
class VariantDict(AttrDict):
def __init__(self, d, hidden_keys):
super(VariantDict, self).__init__(d)
self._hidden_keys = hidden_keys
def dump(self):
return {k: v for (k, v) in self.items() if (k not in self._hidden_keys)} |
def warning_message(message: str) -> None:
click.secho((click.style('', fg='yellow') + f' {message}')) |
def read_pfm(path):
with open(path, 'rb') as file:
color = None
width = None
height = None
scale = None
endian = None
header = file.readline().rstrip()
if (header.decode('ascii') == 'PF'):
color = True
elif (header.decode('ascii') == 'Pf'):... |
()
def azure_get_valid_skus(regions: List[str]=typer.Option(compute.AzureCloudProvider.region_list(), '--regions', '-r'), prefix: str=typer.Option('', '--prefix', help='Filter by prefix'), top_k: int=typer.Option((- 1), '--top-k', help='Print top k entries')):
auth = compute.AzureAuthentication()
client = auth.... |
def ter(hyps: List[Union[(str, List[str])]], refs: List[Union[(str, List[str])]]) -> float:
error_tokens = 0
total_tokens = 0
for (h, r) in zip(hyps, refs):
error_tokens += ed.eval(h, r)
total_tokens += len(r)
return (float(error_tokens) / float(total_tokens)) |
def find_meta(_meta, string):
l_match = re.search((('^' + string) + '\\s*=\\s*"(.*)"'), _meta, re.M)
if l_match:
return l_match.group(1)
raise RuntimeError(f'Unable to find {string} string.') |
def typetracer_from_form(form: ((Form | str) | Mapping), *, highlevel: bool=True, behavior: (Mapping | None)=None, attrs: (Mapping[(str, Any)] | None)=None) -> (Array | Content):
if isinstance(form, str):
if is_primitive(form):
form = awkward.forms.NumpyForm(form)
else:
form ... |
def main(argv=None):
tf.reset_default_graph()
keep_prob = tf.placeholder(tf.float32, name='keep_probabilty')
image = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image')
ROIMap = tf.placeholder(tf.int32, shape=[None, None, None, 1], name='ROIMap')
GTLabel = tf.placeholder(tf.i... |
def setup_buckets(region, n_files=1, file_size_mb=1, write=False):
(provider, zone) = region.split(':')
if (provider == 'azure'):
bucket_name = f"integration{zone}/{str(uuid.uuid4()).replace('-', '')}"
else:
bucket_name = f'skyplane-integration-{zone}-{str(uuid.uuid4())[:8]}'
logger.debu... |
def test_get_ontology_path_cost():
o = basic_ontology
s0 = Function('5', [], o.types['number'])
s1 = Function('O', [], o.types['reference'])
oo = augment_ontology(o, {s0.name: s0, s1.name: s1})
s2 = o.functions['equal']
s3 = o.functions['radiusOf']
s4 = o.functions['isRadiusOf']
s5 = o.f... |
def _bad_tensor_splits(draw):
lengths = draw(st.lists(st.integers(4, 6), min_size=4, max_size=4))
batch_size = 4
element_pairs = [(batch, r) for batch in range(batch_size) for r in range(len(lengths))]
perm = draw(st.permutations(element_pairs))
ranges = [([(0, 0)] * len(lengths)) for _ in range(bat... |
class ParserElement(object):
DEFAULT_WHITE_CHARS = ' \n\t\r'
verbose_stacktrace = False
def setDefaultWhitespaceChars(chars):
ParserElement.DEFAULT_WHITE_CHARS = chars
def inlineLiteralsUsing(cls):
ParserElement._literalStringClass = cls
def __init__(self, savelist=False):
se... |
def binary_logloss(p, y):
epsilon = 1e-15
p = sp.maximum(epsilon, p)
p = sp.minimum((1 - epsilon), p)
res = sum(((y * sp.log(p)) + (sp.subtract(1, y) * sp.log(sp.subtract(1, p)))))
res *= ((- 1.0) / len(y))
return res |
class PerEpochLoader():
def __init__(self, loader, func, do_tqdm=True):
self.orig_loader = loader
self.func = func
self.do_tqdm = do_tqdm
self.data_loader = self.compute_loader()
self.loader = iter(self.data_loader)
def compute_loader(self):
return TransformedLoad... |
('drwiki-te')
class TextualEntailmentPredictor(Predictor):
def _batch_json_to_instances(self, json: List[JsonDict]) -> List[Instance]:
instances = []
for blob in json:
instances.extend(self._json_to_instances(blob))
return instances
def set_docdb(self, db):
self.db = ... |
class RoIAlignFunction(Function):
def __init__(self, aligned_height, aligned_width, spatial_scale):
self.aligned_width = int(aligned_width)
self.aligned_height = int(aligned_height)
self.spatial_scale = float(spatial_scale)
self.rois = None
self.feature_size = None
def fo... |
class StandardRibbonShapedTableaux_shape(StandardRibbonShapedTableaux):
def __classcall_private__(cls, shape):
return super(StandardRibbonShapedTableaux, cls).__classcall__(cls, tuple(shape))
def __init__(self, shape):
self.shape = shape
StandardRibbonShapedTableaux.__init__(self, Finite... |
def dummy_diff(*args):
f = args[0]
args = list(args[1:])
for i in range(1, len(args), 2):
args[i] = Integer(args[i])
return f.diff(*args) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.