code stringlengths 101 5.91M |
|---|
def _exact_1_norm(A):
if scipy.sparse.isspmatrix(A):
return max(abs(A).sum(axis=0).flat)
elif is_pydata_spmatrix(A):
return max(abs(A).sum(axis=0))
else:
return np.linalg.norm(A, 1) |
class ContentAttrParser(object):
def __init__(self, data):
assert isinstance(data, bytes)
self.data = data
def parse(self):
try:
self.data.jumpTo(b'charset')
self.data.position += 1
self.data.skip()
if (not (self.data.currentByte == b'=')):... |
class ContextNet(Sequential):
def __init__(self, input_shape, out_channels=640, conv_channels=None, kernel_size=3, strides=None, num_blocks=21, num_layers=5, inner_dim=12, alpha=1, beta=1, dropout=0.15, activation=Swish, se_activation=torch.nn.Sigmoid, norm=BatchNorm1d, residuals=None):
super().__init__(inp... |
class ResBlock(nn.Module):
def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):
super(ResBlock, self).__init__()
self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)
def build_conv_block(self, dim, padding_type, norm_layer, use_dropou... |
class CachedProperty(object):
def __init__(self, wrapped):
self.wrapped = wrapped
try:
self.__doc__ = wrapped.__doc__
except:
pass
def __get__(self, instance, instance_type=None):
if (instance is None):
return self
value = self.wrapped(... |
class BacktranslationDataset(FairseqDataset):
def __init__(self, tgt_dataset, tgt_dict, backtranslation_model, max_len_a, max_len_b, remove_eos_at_src=False, generator_class=sequence_generator.SequenceGenerator, **kwargs):
self.tgt_dataset = language_pair_dataset.LanguagePairDataset(src=tgt_dataset, src_siz... |
class TestPostTrainingDynamic(QuantizationTestCase):
def test_single_layer(self):
for dtype in [torch.qint8, torch.float16]:
model = SingleLayerLinearDynamicModel().eval()
qconfig = (float16_dynamic_qconfig if (dtype == torch.float16) else default_dynamic_qconfig)
qconfig... |
def coords_in_U_mod_p(u, U, p):
coords = U.log(u)
start = (1 - int(p.divides(U.zeta_order())))
return [(c % p) for c in coords[start:]] |
class Graph(Printable):
name: str
directed: bool
vertices: Dict[(str, Vertex)]
edges: List[Edge]
def __init__(self, name: str, directed: bool):
self.name = name
self.directed = directed
self.vertices = {}
self.edges = []
def copy(self, graph: Graph):
self.... |
def main(args):
cfg = get_cfg()
cfg.merge_from_file(args.cfg_file)
cfg.merge_from_list(args.opts)
cfg = infer_cfg(cfg)
cfg.freeze()
if (not os.path.isdir(cfg.CKPT)):
mkdir_p(cfg.CKPT)
setup_logging(cfg.CKPT)
(n_params, conv_flops, model_flops, conv_activs, model_activs) = (0, 0, ... |
def regenerate_lextab(py_ver, write=False):
tokenizer_path = os.path.join(SKYMARSHAL_DIR, 'tokenizer.py')
generated_path = os.path.join(SKYMARSHAL_DIR, 'lextab.py')
try:
env = os.environ.copy()
env['PYTHONDONTWRITEBYTECODE'] = '1'
env['SKYMARSHAL_REGENERATE_LEXER'] = '1'
if o... |
def get_spacy_model(spacy_model_name: str, pos_tags: bool, parse: bool, ner: bool) -> SpacyModelType:
options = (spacy_model_name, pos_tags, parse, ner)
if (options not in LOADED_SPACY_MODELS):
disable = ['vectors', 'textcat']
if (not pos_tags):
disable.append('tagger')
if (n... |
def test_hook():
tracer = ExecutionTracer()
tracer.current_thread_identifier = threading.current_thread().ident
with install_import_hook('tests.fixtures.instrumentation.mixed', tracer):
module = importlib.import_module('tests.fixtures.instrumentation.mixed')
importlib.reload(module)
... |
def test_arr2sym():
N = dace.symbol('N', dace.float64)
def symarg(A: dace.float64[20]):
A[:] = N
def scalarg(A: dace.float64[20], arr: dace.float64[2]):
symarg(A, N=arr[1])
sdfg = scalarg.to_sdfg(simplify=False)
A = np.random.rand(20)
sc = np.array([2.0, 3.0])
sdfg(A, sc)
... |
class FontFile():
bitmap = None
def __init__(self):
self.info = {}
self.glyph = ([None] * 256)
def __getitem__(self, ix):
return self.glyph[ix]
def compile(self):
if self.bitmap:
return
h = w = maxwidth = 0
lines = 1
for glyph in self:
... |
class LogisticRegression(nn.Module):
def __init__(self, vocab_size, embed_dim, n_classes, pad_idx):
super(LogisticRegression, self).__init__()
self.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embed_dim, padding_idx=pad_idx)
self.fc = nn.Linear(embed_dim, n_classes)
... |
def dump_pickle(data, path):
ensure_parents(path)
with open(str(path), 'wb') as f:
pickle.dump(data, f)
return |
def calc_one_map(data):
relcnt = 0
score = 0.0
data = sorted(data, key=(lambda d: d[1]), reverse=True)
for (idx, item) in enumerate(data):
if (int(item[0][2]) == 1):
relcnt = (relcnt + 1)
score = (score + ((1.0 * relcnt) / (idx + 1)))
if (relcnt == 0):
return ... |
def encoder_forecaster_build_networks(factory, context, shared_encoder_net=None, shared_forecaster_net=None, shared_loss_net=None, for_finetune=False):
encoder_net = MyModule(factory.encoder_sym(), data_names=[ele.name for ele in factory.encoder_data_desc()], label_names=[], context=context, name='encoder_net')
... |
class RegularMeta(Meta, Generic[T]):
is_list = True
is_regular = True
size: ShapeItem
_content: T
def purelist_parameters(self, *keys: str) -> JSONSerializable:
if (self._parameters is not None):
for key in keys:
if (key in self._parameters):
r... |
class ResNet(nn.Module):
def __init__(self, block, layers, sample_size, sample_duration, shortcut_type='B', num_classes=400, last_fc=True):
self.last_fc = last_fc
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv3d(3, 64, kernel_size=7, stride=(1, 2, 2), padding=... |
(scope='function')
def problem_ctx():
ctx = CategoricalLpProblemContext(clf=FakeModel(), target_class=1, target_confidence=0.5, lp_space=1)
return ctx |
def build_model(X, num_inducing, num_layers):
config = Config(num_inducing=num_inducing, inner_layer_qsqrt_factor=1e-05, between_layer_noise_variance=0.01, likelihood_noise_variance=0.01, white=True)
model = build_constant_input_dim_deep_gp(X, num_layers, config=config)
return model |
def changeBipartiteAlterTwoStar1_SLOW(mode, G, A, i):
delta3 = (sum([G.twoPaths(i, v) for v in G.nodeModeIterator(mode)]) if (G.bipartite_node_mode(i) == mode) else 0)
return delta3 |
def _remove_qconfig(module):
for child in module.children():
_remove_qconfig(child)
if hasattr(module, 'qconfig'):
del module.qconfig |
_GENERATOR_REGISTRY.register()
class RotatedAnchorGenerator(nn.Module):
box_dim: int = 5
def __init__(self, *, sizes, aspect_ratios, strides, angles, offset=0.5):
super().__init__()
self.strides = strides
self.num_features = len(self.strides)
sizes = _broadcast_params(sizes, self... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, plugins=None):
super(BasicBlock, self).__init__()
assert (dcn is None), 'Not implemented yet.'... |
def get_indexing_from_db(db_path: str, shuffle=True) -> Dict[(str, List[Dict[(str, Any)]])]:
(table_column_properties, _, _) = get_all_db_info_path(db_path)
all_tables_names = {t_c[0] for t_c in table_column_properties}
table_name2indexes = {}
for table_name in all_tables_names:
column_names = [... |
def _impl(array, axis, keepdims, mask_identity, highlevel, behavior, attrs):
axis = regularize_axis(axis)
with HighLevelContext(behavior=behavior, attrs=attrs) as ctx:
layout = ctx.unwrap(array, allow_record=False, primitive_policy='error')
reducer = ak._reducers.Sum()
out = ak._do.reduce(layout... |
def resize_flow(flow, shape):
scale = [(n / o) for (n, o) in zip(shape, flow.shape[1:])]
scale_factor = np.array(scale, dtype=flow.dtype)
for _ in shape:
scale_factor = scale_factor[(..., np.newaxis)]
rflow = (scale_factor * ndi.zoom(flow, ([1] + scale), order=0, mode='nearest', prefilter=False)... |
def is_torch_fx_proxy(x):
if is_torch_fx_available():
import torch.fx
return isinstance(x, torch.fx.Proxy)
return False |
def matmul(mat_x, mat_y):
shape_x = static(mat_x.get_shape())
shape_y = static(mat_y.get_shape())
if static(((len(shape_x) == 1) and (len(shape_y) == 2))):
return _matmul_helper(transpose(mat_y), mat_x)
return _matmul_helper(mat_x, mat_y) |
def register_Ns3PointerChecker_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::PointerChecker const &', 'arg0')])
cls.add_method('GetPointeeTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True)
return |
def test_classes():
assert (list(CityscapesDataset.CLASSES) == get_classes('cityscapes'))
assert (list(PascalVOCDataset.CLASSES) == get_classes('voc') == get_classes('pascal_voc'))
assert (list(ADE20KDataset.CLASSES) == get_classes('ade') == get_classes('ade20k'))
with pytest.raises(ValueError):
... |
class DataLoader(object):
def parse_data_args(parser):
parser.add_argument('--path', type=str, default='../dataset/', help='Input data dir.')
parser.add_argument('--dataset', type=str, default='ml100k-1-5', help='Choose a dataset.')
parser.add_argument('--sep', type=str, default='\t', help='... |
class WeightSetting(object):
def __init__(self, solver_type='ECOS'):
self._solver_type = solver_type
def obtain_weights(self, power_signals_d):
try:
from solardatatools.clear_day_detection import find_clear_days
except ImportError:
print('Weights not set!')
... |
def save_info(path, info):
for im_id in sorted(info.keys()):
im_info = info[im_id]
if ('cam_K' in im_info.keys()):
im_info['cam_K'] = im_info['cam_K'].flatten().tolist()
if ('cam_R_w2c' in im_info.keys()):
im_info['cam_R_w2c'] = im_info['cam_R_w2c'].flatten().tolist()... |
('sdmetrics.visualization.get_column_pair_plot')
def test_get_column_pair_plot_with_continous_data(mock_get_plot):
columns = ['amount', 'date']
real_data = pd.DataFrame({'amount': [1, 2, 3], 'date': ['2021-01-01', '2022-01-01', '2023-01-01']})
synthetic_data = pd.DataFrame({'amount': [1.0, 2.0, 3.0], 'date'... |
def _seg_64():
return [(120420, 'M', u'o'), (120421, 'M', u'p'), (120422, 'M', u'q'), (120423, 'M', u'r'), (120424, 'M', u's'), (120425, 'M', u't'), (120426, 'M', u'u'), (120427, 'M', u'v'), (120428, 'M', u'w'), (120429, 'M', u'x'), (120430, 'M', u'y'), (120431, 'M', u'z'), (120432, 'M', u'a'), (120433, 'M', u'b'),... |
def mk_lean_code_def_name(fn_name: str, namespaces: List[ScopedName]):
prefix = 'code_'
return get_name_in_open_scopes(ScopedName.from_string(fn_name), namespaces, prefix) |
def cat(g, *tensors, **kwargs):
dim = kwargs.pop('dim')
assert (not kwargs)
return g.op('Concat', *tensors, axis_i=dim) |
def test_setting_default_requests():
test_cases = dict()
class ExplicitRequest(BaseEstimator):
__metadata_request__fit = {'prop': None}
def fit(self, X, y, **kwargs):
return self
test_cases[ExplicitRequest] = {'prop': None}
class ExplicitRequestOverwrite(BaseEstimator):
... |
class Transform(object):
def __init__(self):
self.conf = utils.get_default_conf()
self.cn2an = Cn2An().cn2an
self.an2cn = An2Cn().an2cn
def transform(self, inputs, mode='cn2an'):
if (mode == 'cn2an'):
pattern = (('[' + ''.join((self.conf['number_low'] + list(set(self.... |
def int64_feature(values):
if (not isinstance(values, (tuple, list))):
values = [values]
return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) |
def RefreshRegisteredOperators(trigger_lazy=True):
if trigger_lazy:
TriggerLazyImport()
global _REGISTERED_OPERATORS
_REGISTERED_OPERATORS = _GetRegisteredOperators() |
def test_field_statement_eq_clone(default_test_case, field_mock):
ref = vr.VariableReference(default_test_case, default_test_case.test_cluster.type_system.convert_type_hint(int))
statement = stmt.FieldStatement(default_test_case, field_mock, ref)
memo = {ref: ref}
clone = statement.clone(default_test_ca... |
class Softplus_VGG(nn.Module):
def __init__(self, vgg_name):
super(Softplus_VGG, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
self.classifier = nn.Linear(512, 10)
def forward(self, x):
out = self.features(x)
out = out.view(out.size(0), (- 1))
... |
def load_img_future_de_rain(filepath, nFrames, img_id):
tt = int((nFrames / 2))
img_id = (img_id + tt)
(target, input, neigbor) = (None, None, None)
if (filepath.split('/')[3].split('-')[0] == 'SPAC'):
targetPath = (((os.path.dirname(filepath) + '/') + filepath.split('/')[5].split('_')[0]) + '_G... |
def data_prep(data_folder, hparams):
train_data = sb.dataio.dataset.DynamicItemDataset.from_json(json_path=(data_folder / '../annotation/ASR_train.json'), replacements={'data_root': data_folder})
valid_data = sb.dataio.dataset.DynamicItemDataset.from_json(json_path=(data_folder / '../annotation/ASR_dev.json'), ... |
def test_method_name_and_count() -> None:
current_file: str = os.path.basename(__file__)
test_files: List[str] = get_python_files(CHALLENGES_DIR, current_file)
for test_file in test_files:
module = load_module_from_file(test_file)
functions_list = get_test_functions(module)
assert_si... |
def signed_log_add(x, y, sign_x, sign_y):
(a, b) = (x, y)
(sign_a, sign_b) = (sign_x, sign_y)
if (y > x):
(a, b) = (y, x)
(sign_a, sign_b) = (sign_y, sign_x)
if (sign_a != sign_b):
val = log_minus(a, b)
else:
val = log_add(a, b)
return (sign_a, val) |
def test_run_phmmer():
input = ['MTFKLPDLPFDAGALEPYISALTMKTHHGKHHAAYIKNMNAILAERADAQTSLEAVVSLAAREANKKLFNNAAQAWNHGFFWQSLSADAQNGPSGDLRAAIMNSFGSLEAFNDEAKAKGVGHFASGWLWLVSDESGALSLCDLHDADTPITDPSLTPLLVCDLWEHAYYIDYANERPRFVDAFLTKLANWRFAQAQYQAARSGSGA', 'FAVSATKIHTKATLPALDYAYEALEPILSSHLLHLHHDKHHQTYVNNLNAAEEKLKDPSLDLHTQIALQSAIK... |
class SkeletonUnpool(nn.Module):
def __init__(self, pooling_list, output_joints_num):
super(SkeletonUnpool, self).__init__()
self.pooling_list = pooling_list
self.input_joints_num = len(pooling_list)
self.output_joints_num = output_joints_num
self.weight = torch.zeros(self.ou... |
def multiprocess(stream, fun, queue_size=10, worker_count=5):
in_queue = multiprocessing.JoinableQueue(maxsize=queue_size)
out_queue = multiprocessing.JoinableQueue(maxsize=queue_size)
end_marker = object()
def producer():
for item in stream:
in_queue.put(item)
for _ in range... |
def main():
print('Begin Proposal Generation Module')
args = parse_args()
cfg = mmcv.Config.fromfile(args.config)
tem_results_dir = cfg.tem_results_dir
pgm_proposals_dir = cfg.pgm_proposals_dir
pgm_features_dir = cfg.pgm_features_dir
if (args.mode == 'test'):
generate_proposals(cfg.a... |
class GmailOrganizeEmail(VirtualFunctionTool):
name = 'GmailOrganizeEmail'
summary = 'Move an email to a specific folder or update its labels.'
parameters: List[ArgParameter] = [{'name': 'email_id', 'type': 'string', 'description': 'The unique identifier of the email.', 'required': True}, {'name': 'folder',... |
def _number_field_elements_from_algebraics_list_of_lists_of_lists(listss, **kwds):
from sage.rings.qqbar import number_field_elements_from_algebraics
numbers = []
for lists in listss:
for list in lists:
numbers.extend(list)
(K, K_numbers, hom) = number_field_elements_from_algebraics(... |
class TMMNetModeNetI(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.TMMNetModeNetI_swiginit(self, _snap.new_TMMNetModeNetI(*args))
def Next(self):
return _snap.TMM... |
def make_batch_roberta(sessions):
(batch_input, batch_labels, batch_speaker_tokens) = ([], [], [])
for session in sessions:
data = session[0]
label_list = session[1]
(context_speaker, context, emotion, sentiment) = data
now_speaker = context_speaker[(- 1)]
speaker_utt_lis... |
def test_image_to_text_single():
class MockImageExplanation():
def __init__(self, data, values, output_names):
self.data = data
self.values = values
self.output_names = output_names
test_image_height = 500
test_image_width = 500
test_word_length = 4
test_d... |
def load_data(prompt_file, continuation_file, unigram_file):
print('Reading lines...')
prompts = []
prompt_f = open(prompt_file, 'r')
prompt_lines = prompt_f.readlines()
for prompt in prompt_lines:
prompts.append(prompt.strip('\n').strip('\ufeff'))
continuations = []
f = open(continu... |
_function_dispatch(_rec_drop_fields_dispatcher)
def rec_drop_fields(base, drop_names):
return drop_fields(base, drop_names, usemask=False, asrecarray=True) |
def homchain(complex=None, **kwds):
deprecation(33777, 'the CHomP interface is deprecated')
from sage.homology.chain_complex import ChainComplex_class
help = kwds.get('help', False)
if help:
return CHomP().help('homchain')
if isinstance(complex, ChainComplex_class):
return CHomP()('h... |
def test_case157():
url = (brokerIp + '/ngsi-ld/v1/entityOperations/upsert')
headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'}
r = requests.post(url, data=json.dumps(ld_data.subdata156), headers=headers)
print(r.conten... |
def create_permutation_instruction(item=None, rank_start=0, rank_end=100, model_name='gpt-3.5-turbo'):
query = item['query']
num = len(item['hits'][rank_start:rank_end])
max_length = 300
while True:
messages = get_prefix_prompt(query, num)
rank = 0
for hit in item['hits'][rank_st... |
class MinimizerWrapper(object):
def __init__(self, minimizer, func=None, **kwargs):
self.minimizer = minimizer
self.func = func
self.kwargs = kwargs
def __call__(self, x0):
if (self.func is None):
return self.minimizer(x0, **self.kwargs)
else:
retu... |
def get_list_of_highlevel_actions(traj_data, test=False, test_dict=None, args_nonsliced=False, appended=False):
if (not test):
(language_goal, task_type, mrecep_target, obj_target, parent_target, sliced) = get_arguments(traj_data)
if test:
r_idx = traj_data['repeat_idx']
instruction = tr... |
class DATASET_MODES():
train = 'train'
val = 'val'
test = 'test'
trainval = 'trainval' |
.parametrize('likelihood', LIKELIHOODS)
def test_separable_likelihood_vectorization(likelihood):
assert (not likelihood.isotropic)
N = np.prod(likelihood.size)
az = np.linspace(1, 2, N)
az = az.reshape(likelihood.size)
bz = np.linspace((- 2), 2, N)
bz = bz.reshape(likelihood.size)
(rz, vz) =... |
def random_hermitian_matrix(l, *batches, **kwargs):
dtype = kwargs.get('dtype', torch.double)
device = kwargs.get('device', 'cpu')
A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device)
A = (A + A.transpose((- 2), (- 1)).conj()).div_(2)
return A |
class AttackNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(NUM_CLASSES, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 64)
self.softmax = nn.Linear(64, 1)
def forward(self, x, **kwargs):
del kwargs
x = F.relu(self.... |
class CrossAttention(nn.Module):
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
super().__init__()
inner_dim = (dim_head * heads)
context_dim = default(context_dim, query_dim)
self.scale = (dim_head ** (- 0.5))
self.heads = heads
s... |
def r_pow_scalar_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, val=1):
dy = grad_inputs[0]
x0 = inputs[0]
dx0 = ((dy * (val ** x0)) * np.log(val))
return dx0 |
class BLUR(BuiltinFilter):
name = 'Blur'
filterargs = ((5, 5), 16, 0, (1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1)) |
class ParallelDroplessMLP(moe.ParallelMLP):
def __init__(self, args: Arguments):
super(ParallelDroplessMLP, self).__init__(args)
self.hidden_size = args.hidden_size
self.ffn_hidden_size = mpu.features_per_rank(args)
self.blocking = 128
self.mlp = dmlp_registry.get(args)
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_file', required=True, type=str)
parser.add_argument('-n', '--repeat_times', required=True, type=int)
parser.add_argument('-o', '--output_file', required=False)
parser.add_argument('-f', '--func', required=False, defaul... |
class NormalizedMeanSquaredError2D(keras.losses.Loss):
def __init__(self, denom_nonzero=1e-05, **kwargs):
self.denom_nonzero = denom_nonzero
super().__init__(**kwargs)
def call(self, y_true, y_pred):
mse = tf.reduce_mean(tf.reduce_mean(tf.square((y_pred - y_true)), axis=(- 1)), axis=(- 1... |
def write_pip_lock_file(build_metadata):
build_name = build_metadata['build_name']
python_version = build_metadata['python_version']
environment_name = f'pip-tools-python{python_version}'
command = f'conda create -c conda-forge -n pip-tools-python{python_version} python={python_version} pip-tools -y'
... |
class inner_GNN(MessagePassing):
def __init__(self, dim, hidden_layer):
super(inner_GNN, self).__init__(aggr='mean')
self.lin1 = nn.Linear(dim, hidden_layer)
self.lin2 = nn.Linear(hidden_layer, dim)
self.act = nn.ReLU()
self.drop = nn.Dropout(p=0.5)
def forward(self, x, e... |
def s3_iterator(client, resource, root, dir, bucket, action):
paginator = client.get_paginator('list_objects')
for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dir):
if (result.get('CommonPrefixes') is not None):
for subdir in result.get('CommonPrefixes'):
... |
class data_prefetcher():
def __init__(self, loader, fp16=True):
self.loader = iter(loader)
self.fp16 = fp16
self.stream = torch.cuda.Stream()
self.mean = torch.tensor([0.485, 0.456, 0.406]).cuda().view(1, 3, 1, 1)
self.std = torch.tensor([0.229, 0.224, 0.225]).cuda().view(1, ... |
def asgi_test(case: Case, checks: Iterable[CheckFunction], targets: Iterable[Target], result: TestResult, store_interactions: bool, headers: (dict[(str, Any)] | None), feedback: Feedback, max_response_time: (int | None), data_generation_methods: list[DataGenerationMethod], dry_run: bool, errors: list[Exception]) -> Non... |
.parametrize('fname,val,low,high', [('workspace_no_parameter_inits.json', '1', '-5', '5'), ('workspace_no_parameter_bounds.json', '5', '0', '10')], ids=['no_inits', 'no_bounds'])
def test_issue1814(datadir, mocker, fname, val, low, high):
with open((datadir / fname), encoding='utf-8') as spec_file:
spec = j... |
class TensorflowCropFlipImagePipeline(BaseImagePipeline):
def __init__(self, output_image_size: Tuple, extra_pixels: int):
super(TensorflowCropFlipImagePipeline, self).__init__(output_image_size, extra_pixels)
self.img_manipulation_list = [(random_flip, {}), (random_crop, {'height_crop': output_imag... |
def get_run_id(run_info=None):
if (run_info is None):
run_info = get_run_info()
keys = ['hostname', 'pid', 'timestamp']
val = [str(run_info[key]) for key in keys if (key in run_info)]
return '_'.join(val) |
class DeepNN(nn.Module):
def __init__(self, lr, width, depth, version):
super(DeepNN, self).__init__()
self.linear_input = nn.Linear(((3 * 32) * 32), width)
self.linear_layers = nn.ModuleList([nn.Linear(width, width) for i in range(depth)])
self.linear_output = nn.Linear(width, 10)
... |
def incremental_sent_bleu(hypothesis, references, max_n=4):
(clip_count, count, total_len_hyp, total_len_ref) = incremental_bleu_count([hypothesis], [references], max_n=max_n)
clip_count = clip_count[0]
count = count[0]
total_len_hyp = total_len_hyp[0]
total_len_ref = total_len_ref[0]
n_len = le... |
class modules(_TestParametrizer):
def __init__(self, module_info_list):
super().__init__(handles_dtypes=True)
self.module_info_list = module_info_list
def _parametrize_test(self, test, generic_cls, device_cls):
for module_info in self.module_info_list:
for dtype in floating_t... |
class _HalfOpenInterval(Constraint):
def __init__(self, lower_bound, upper_bound):
self.lower_bound = lower_bound
self.upper_bound = upper_bound
def check(self, value):
return ((self.lower_bound <= value) & (value < self.upper_bound))
def __repr__(self):
fmt_string = self.__c... |
class NumpyKernel(BaseKernel):
def _cast(cls, x, t):
if issubclass(t, ctypes._Pointer):
if numpy.is_own_array(x):
assert numpy.is_c_contiguous(x), 'kernel expects contiguous array'
if (x.ndim > 0):
return ctypes.cast(x.ctypes.data, t)
... |
class UnpairedImageTrain(UnpairedImageBase):
def __init__(self, size=None, random_crop=False, folder1=None, folder2=None, numpy_folder1=None, numpy_folder2=None, wikiart_info1=None, wikiart_key1=None, wikiart_info2=None, wikiart_key2=None):
super().__init__()
self.data = UnpairedImagePaths(size=size... |
def read_tb(path):
import pandas
import numpy as np
from glob import glob
from collections import defaultdict
import tensorflow as tf
if osp.isdir(path):
fnames = glob(osp.join(path, 'events.*'))
elif osp.basename(path).startswith('events.'):
fnames = [path]
else:
... |
def _sum2(cp1, cp2, length):
size = 2
total = 0
for i in range(length):
total += (getsample(cp1, size, i) * getsample(cp2, size, i))
return total |
def compute_and_write_labels(output_path, qid2answers, qid2rankings):
cutoffs = [1, 5, 10, 20, 30, 50, 100, 1000, 'all']
success = {cutoff: 0.0 for cutoff in cutoffs}
counts = {cutoff: 0.0 for cutoff in cutoffs}
with open(output_path, 'w') as f:
for qid in qid2answers:
if (qid not in... |
def slice_module_at_return(module_name: str) -> list[UniqueInstruction]:
config.configuration.statistics_output.coverage_metrics = [config.CoverageMetric.CHECKED]
tracer = ExecutionTracer()
tracer.current_thread_identifier = threading.current_thread().ident
with install_import_hook(module_name, tracer):... |
_metaclass(abc.ABCMeta)
class Configurable(object):
def __init__(self, params, mode):
self._params = _parse_params(params, self.default_params())
self._mode = mode
self._print_params()
def _print_params(self):
classname = self.__class__.__name__
tf.logging.info('Creating ... |
class CustomInit(InitialConditions):
def __init__(self, a_init=None, b_init=None, a=0, b=0):
a_init = (a_init or [])
self.a_init = {id: {direction: a} for (id, direction, a) in a_init}
b_init = (b_init or [])
self.b_init = {id: {direction: b} for (id, direction, b) in b_init}
... |
def save_son(filename, d, is_metadata=False):
son.dump(d, normalize_extension(filename, '.son'), is_metadata=is_metadata, dumper=yaml.dump) |
def native_to_byteorder(array, byteorder: str):
assert (byteorder in '<>')
if (byteorder != native_byteorder):
return array.byteswap(inplace=False)
else:
return array |
def gamma_grad_logr(epsilon, alpha):
b = (alpha - (1.0 / 3.0))
c = (1.0 / tf.sqrt((9.0 * b)))
v = (1.0 + (epsilon * c))
return (((- 0.5) / b) + (((9.0 * epsilon) * (c ** 3)) / v)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.