code stringlengths 101 5.91M |
|---|
def start_processes(fn, args=(), nprocs=1, join=True, daemon=False, start_method='spawn'):
_python_version_check()
mp = multiprocessing.get_context(start_method)
error_queues = []
processes = []
for i in range(nprocs):
error_queue = mp.SimpleQueue()
process = mp.Process(target=_wrap,... |
def lookup_function(val):
type = val.type
if (type.code == gdb.TYPE_CODE_REF):
type = type.target()
type = type.unqualified().strip_typedefs()
typename = type.tag
if (typename == None):
return None
for function in pretty_printers_dict:
if function.search(typename):
... |
def _get_builtin_metadata(dataset_name):
return _get_flickr30k_metadata([])
raise KeyError('No built-in metadata for dataset {}'.format(dataset_name)) |
def test_pair_confusion_matrix():
n = 10
N = (n ** 2)
clustering1 = np.hstack([([(i + 1)] * n) for i in range(n)])
clustering2 = np.hstack([([(i + 1)] * (n + 1)) for i in range(n)])[:N]
expected = np.zeros(shape=(2, 2), dtype=np.int64)
for i in range(len(clustering1)):
for j in range(len... |
def _impl(array, highlevel, behavior, attrs):
with HighLevelContext(behavior=behavior, attrs=attrs) as ctx:
layout = ctx.unwrap(array, allow_record=True, primitive_policy='error')
fields = ak.operations.fields(layout)
def check_for_union(layout, **kwargs):
if isinstance(layout, (ak.contents.... |
class SubGoalAttachment():
def __init__(self, config, vehicle, street_map):
self.config = config
self.vehicle = vehicle
self.street_map = street_map
self._nav_config = self.config.navigation
self._sub_goals = None
def reset(self):
self._sub_goals = []
for ... |
def find_comparable_simulations(sxs_id, catalog, catalog_resolutions):
mass1 = catalog[sxs_id]['initial_mass1']
mass2 = catalog[sxs_id]['initial_mass2']
spin1 = catalog[sxs_id]['initial_dimensionless_spin1']
spin2 = catalog[sxs_id]['initial_dimensionless_spin2']
mass_ratio = (mass1 / mass2)
spin... |
class Evaluator(object):
def __init__(self, model):
self.model = model
self.global_step = model.global_step
self.build_summary()
self.writer = tf.summary.FileWriter(cfg.summary_dir)
def get_evaluation(self, sess, dataset_obj, global_step=None):
_logger.add()
_logg... |
def decode_param_command(args, **kwargs):
os.makedirs(args.outdir, exist_ok=True)
logger.log(99, 'Loading parameters...')
load_parameters(args.param)
params = get_parameters(grad_only=False)
for (key, variable) in params.items():
logger.log(99, key)
file_path = os.path.join(args.outd... |
class ArgumentBase():
def __init__(self, A: 'Union[cuda.CUdeviceptr, np.ndarray, torch.Tensor, cp.ndarray]', B: 'Union[cuda.CUdeviceptr, np.ndarray, torch.Tensor, cp.ndarray]', C: 'Union[cuda.CUdeviceptr, np.ndarray, torch.Tensor, cp.ndarray]', D: 'Union[cuda.CUdeviceptr, np.ndarray, torch.Tensor, cp.ndarray]', **k... |
.parametrize('batch_size', [1, 2, 5, 100])
.parametrize('mask_distance,expected', [(1, ((- 2.), (- 2.))), (2, ((- 0.), (- 0.))), (5, ((- 0.), (- 0.)))])
def test_likelihood_batch_handles_batch_sizes(msa_sampler, msa_batch_example, batch_size, mask_distance, expected):
result = list(msa_sampler.log_likelihood_batch(... |
def _make_leducHoldem_dwg(dwg, state: LeducHoldemState, config):
GRID_SIZE = config['GRID_SIZE']
BOARD_SIZE = config['BOARD_WIDTH']
color_set = config['COLOR_SET']
dwg.add(dwg.rect((0, 0), ((BOARD_SIZE * GRID_SIZE), (BOARD_SIZE * GRID_SIZE)), fill=color_set.background_color))
board_g = dwg.g()
b... |
class LinearReLU(nnqat.Linear):
_FLOAT_MODULE = torch.nn.intrinsic.LinearReLU
def __init__(self, in_features, out_features, bias=True, qconfig=None):
super(LinearReLU, self).__init__(in_features, out_features, bias, qconfig)
def forward(self, input):
return F.relu(F.linear(input, self.weight... |
class TestNetwork(unittest.TestCase):
def setUp(self):
self.network = Network('test_net')
self.network.set_input_layer(InputLayer(3, 224))
self.network.add('c1', ConvLayer(3, 64, 224, 3))
self.network.add('p1', PoolingLayer(64, 7, 32))
self.network.add('f1', FCLayer(64, 1000,... |
def main():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--model', type=str, required=True, help='The type of model to train', choices=['hanrnn', 'hanconv', 'flanrnn', 'flanconv', 'han_encless', 'flan_encless'])
parser.add_argument('--dataset-... |
class PreHook(abc.ABC):
def __call__(self, node: Node, function: Callable, args: tuple, kwargs: dict) -> Tuple[(Optional[Tuple], Optional[Dict])]:
pass |
def phn2txt(phn, phoneme_map):
value = ''.join((phoneme_map[phoneme] for phoneme in phn)).strip()
value = MULTI_SPACE.sub('', value)
return value |
def get_device_option(device):
m = {DeviceType.CPU: caffe2_pb2.CPU, DeviceType.CUDA: workspace.GpuDeviceType}
return core.DeviceOption(m[device.type], device.device_id) |
def get_left_tokens(c, window=3, attrib='words', n_max=1, case_sensitive=False):
(left, right) = ((c[0], c[1]) if (c[0].char_start < c[1].char_start) else (c[1], c[0]))
span = get_left_span(left, window=window)
tokens = span.get_attrib_tokens(attrib)
return ([t.lower() for t in tokens] if (not case_sens... |
def remove_spectral_norm(module, name='weight'):
for (k, hook) in module._forward_pre_hooks.items():
if (isinstance(hook, SpectralNorm) and (hook.name == name)):
hook.remove(module)
del module._forward_pre_hooks[k]
return module
raise ValueError("spectral_norm of '{}'... |
def module_build_impl(a):
source_path = a.SOURCE
module_path = a.output
source_path = Path(source_path)
assert source_path.name.endswith('.py'), 'Source must be a Python script.'
if (module_path is None):
module_path = f'{source_path.name[:(- 3)]}.tcm'
module_path = Path(module_path)
... |
class Network(object):
def __init__(self, n_length, base_filters, kernel_size, n_block, n_channel):
use_cuda = torch.cuda.is_available()
n_samples = 1000
n_length = n_length
n_classes = 2
batch_size = 64
(data, label) = read_data_generated(n_samples=n_samples, n_lengt... |
def get_data_correlated(with_input_blocks, corr_coef=0.6):
np.random.seed(111)
n = 5000
p = 4
beta_a = np.array([0, 0, 0, 0]).astype('float32')
beta_i = np.array(((([0, 3, 0, 0] + ([0] * 3)) + [0, (- 2)]) + [0])).astype('float32')
cov_mat = (np.eye(4) * 1.0)
cov_mat[(0, 2)] = cov_mat[(2, 0)]... |
_utils.in_tempdir
def test_dory_search_nomatch(location):
copy_dory_catlas()
testdata = relative_file('data/random-query-nomatch.fa')
shutil.copyfile(testdata, 'random-query.fa')
args = '-k 21 dory_k21 --contigs-db dory_k21/bcalm.unitigs.db'.split()
print('** running index_cdbg_by_kmer')
assert ... |
class TransHeadNet(nn.Module):
def __init__(self, in_channels, num_layers=3, num_filters=256, kernel_size=3, output_dim=3, freeze=False, norm='BN', num_gn_groups=32):
super().__init__()
self.freeze = freeze
if (kernel_size == 3):
padding = 1
elif (kernel_size == 2):
... |
def get_split_list(data_list):
out1 = []
out2 = []
for item in data_list:
out1.append(item[0::2])
out2.append(item[1::2])
out = (out1 + out2)
return out |
class Window():
def __init__(self, window_size):
self.window_size = window_size
self.window = []
def update(self, num):
self.window.append(num)
if (len(self.window) > self.window_size):
self.window = self.window[1:]
def get(self):
return self.window |
class TestDetector():
def setup(self):
self.detector_id = '-detector-'
self.temp_dir = mkdtemp(prefix='mubench-detector_')
def teardown(self):
remove_tree(self.temp_dir)
def test_raises_on_missing_file(self):
assert_raises(ValueError, Detector, self.temp_dir, '-detector-', []... |
def get_random_data(num_samps=1000):
x = np.random.sample(((10 * 4) * num_samps)).reshape((num_samps, 10, 4))
y = np.random.sample(num_samps)
return (x, y) |
class SubprocessTimeoutTest(unittest.TestCase):
def setUp(self):
self._path = os.path.dirname(os.path.realpath(__file__))
def test_normal_exec_no_timeout(self):
cmdline = 'sleep 1; echo Done'
(return_code, output, err) = sub.run(cmdline, {}, cwd=self._path, stdout=subprocess.PIPE, stderr... |
def c2du(u):
u = np.clip(u, ((- UMAX) + 0.001), (UMAX - 0.001))
return int(np.floor(((u + UMAX) / DU))) |
def main(config, args):
del config.module_replay
config.module_replay = OldReplayBuffer()
torch.set_num_threads(min(4, args.num_envs))
torch.set_num_interop_threads(min(4, args.num_envs))
agent = mrl.config_to_agent(config)
num_eps = max((args.num_eval_envs * 3), 10)
res = np.mean(agent.eval... |
class Llama2LoraKbit(CausalLoraKbitModel):
config_name: str = 'llama2_lora_kbit'
def __init__(self, weights_path: Optional[str]=None):
super().__init__(LLama2LoraKbitEngine.config_name, weights_path) |
.mpi
def test_eq_commworld_1():
from mpi4py import MPI
comm = MPI.COMM_WORLD
comm2 = comm.Dup()
def eq_commworld_1(out: dace.bool[1]):
out[0] = (comm2 == MPI.COMM_WORLD)
res = np.zeros((1,), dtype=np.bool_)
eq_commworld_1(res)
assert (res[0] == (comm2 == MPI.COMM_WORLD)) |
.parametrize('ratio, user_answer, item_answer, split_by_fraqtions', [(0.5, [[1, 1, 2, 2, 3, 3], [1, 1, 1, 2, 2, 2, 3, 3, 3]], [[1, 2, 1, 2, 1, 5], [3, 4, 5, 3, 9, 10, 3, 1, 2]], True), (0.1, [[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3], [1, 2, 3]], [[1, 2, 3, 4, 1, 2, 3, 9, 1, 5, 3, 1], [5, 10, 2]], True), (0.5, [[1, 1, 1, 2,... |
def test_dot_matrix_vector_product():
a_raw = torch.tensor([[1.0, 2.0, 3.0], [(- 1.0), (- 2.0), (- 3.0)]])
b_raw = torch.tensor([4.0, 5.0])
a_feature_dim = Dim(dimension=3)
reduce_dim = Dim(dimension=2)
a = Tensor(name='a', dims=[reduce_dim, a_feature_dim], dtype='float32', raw_tensor=a_raw)
b =... |
class PreTrainedTokenizer(object):
vocab_files_names = {}
pretrained_vocab_files_map = {}
pretrained_init_configuration = {}
max_model_input_sizes = {}
SPECIAL_TOKENS_ATTRIBUTES = ['bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', 'additional_special_tokens'... |
def factor_product(*args):
if (not all((isinstance(phi, BaseFactor) for phi in args))):
raise TypeError('Arguments must be factors')
elif (len(set(map(type, args))) != 1):
raise NotImplementedError('All the args are expected to be instances of the same factor class.')
return reduce((lambda p... |
def torch_cat(tensors, dim=None, axis=None, *, out=None):
if ((dim is None) and (axis is None)):
dim = 0
if ((dim is None) and (axis is not None)):
dim = axis
if (dim < 0):
dim = (tensors[0].dim() + dim)
shapes = [t.shape for t in tensors]
shape = list(shapes[0])
concaten... |
def __getattr__(name):
return _sub_module_deprecation(sub_package='integrate', module='lsoda', private_modules=['_lsoda'], all=__all__, attribute=name) |
def is_crnn_config(filename):
if filename.endswith('.gz'):
return False
try:
config = Config()
config.load_file(filename)
return True
except Exception:
pass
return False |
def convert_cache_to_csv(dataset_cache, output_dir):
data = torch.load(dataset_cache)
train_data = data['train']
valid_data = data['valid']
test_data = data['test']
train_data.to_csv(join(output_dir, (dataset_cache + 'train.csv')), columns=['Dialogue_ID', 'Utterance_ID', 'Speaker', 'Sentiment', 'Emo... |
class SummaryWriter(object):
def __init__(self, path: str, reduce_func=None):
if (reduce_func is None):
reduce_func = (lambda values: ((sum(values) / len(values)) if (len(values) > 0) else None))
self.tb_writer = _SummaryWriter(path)
self.reduce_func = reduce_func
self.cl... |
def svg_dendrogram(dendrogram: np.ndarray, names: Optional[np.ndarray]=None, rotate: bool=False, width: float=400, height: float=300, margin: float=10, margin_text: float=5, scale: float=1, line_width: float=2, n_clusters: int=2, color: str='black', colors: Optional[Iterable]=None, font_size: int=12, reorder: bool=Fals... |
_function_from_c_func_and_dispatcher(_multiarray_umath.packbits)
def packbits(a, axis=None, bitorder='big'):
return (a,) |
class NoiseScheduleVP():
def __init__(self, schedule='discrete', betas=None, alphas_cumprod=None, continuous_beta_0=0.1, continuous_beta_1=20.0):
if (schedule not in ['discrete', 'linear', 'cosine']):
raise ValueError("Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear... |
class RandomIdentitySampler(Sampler):
def __init__(self, data_source, batch_size, num_instances):
if (batch_size < num_instances):
raise ValueError('batch_size={} must be no less than num_instances={}'.format(batch_size, num_instances))
self.data_source = data_source
self.batch_s... |
class PytorchLUTFakeQuant(torch.nn.Module):
def __init__(self, quantization_params: Dict[(str, np.ndarray)]):
super(PytorchLUTFakeQuant, self).__init__()
self.quantization_params = quantization_params
self.activation_is_signed = self.quantization_params.get(SIGNED)
self.lut_values = ... |
class SemiemoClassificationHead(nn.Module):
def __init__(self, input_dim, inner_dim, num_classes, activation_fn, pooler_dropout, args):
super().__init__()
self.dropout = nn.Dropout(p=pooler_dropout)
self.out_proj = nn.Linear(inner_dim, num_classes)
self.args = args
def forward(se... |
def _load_sut(tracer: ExecutionTracer) -> bool:
try:
tracer.current_thread_identifier = threading.current_thread().ident
importlib.import_module(config.configuration.module_name)
except ImportError as ex:
_LOGGER.exception('Failed to load SUT: %s', ex)
return False
return Tru... |
def register_Ns3LteRrcSapAsConfig_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteRrcSap::AsConfig const &', 'arg0')])
cls.add_instance_attribute('sourceDlCarrierFreq', 'uint16_t', is_const=False)
cls.add_instance_attribute('sourceMasterInformationBlock', 'ns3::Lte... |
class RNNDecoderBase(DecoderBase):
def __init__(self, rnn_type, bidirectional_encoder, num_layers, hidden_size, attn_type='general', attn_func='softmax', coverage_attn=False, context_gate=None, copy_attn=False, dropout=0.0, embeddings=None, reuse_copy_attn=False, copy_attn_type='general'):
super(RNNDecoderB... |
def get_predicted_instances(scene_graph, feature_name='feature'):
node_features = []
node_masks = []
n_pts = scene_graph.graph['n_pts']
for node in scene_graph.nodes:
node_features.append(scene_graph.nodes[node][feature_name])
node_mask = np.zeros(n_pts, dtype=np.bool_)
node_mask... |
def get_adjacency_matrix(edges, num_nodes):
A = np.zeros((num_nodes, num_nodes), dtype=np.float32)
for edge in edges:
A[edge] = 1.0
return A |
class SWALR(_LRScheduler):
def __init__(self, optimizer, swa_lr, anneal_epochs=10, anneal_strategy='cos', last_epoch=(- 1)):
swa_lrs = self._format_param(optimizer, swa_lr)
for (swa_lr, group) in zip(swa_lrs, optimizer.param_groups):
group['swa_lr'] = swa_lr
if (anneal_strategy n... |
def resnext(width, height, frame_count, lr, output=9, model_name='sentnet_color.model'):
net = input_data(shape=[None, width, height, 3], name='input')
net = tflearn.conv_2d(net, 16, 3, regularizer='L2', weight_decay=0.0001)
net = tflearn.layers.conv.resnext_block(net, n, 16, 32)
net = tflearn.resnext_b... |
def test_same_input_shapes():
data = [(), (1,), (3,), (0, 1), (0, 3), (1, 0), (3, 0), (1, 3), (3, 1), (3, 3)]
for shape in data:
input_shapes = [shape]
assert_shapes_correct(input_shapes, shape)
input_shapes2 = [shape, shape]
assert_shapes_correct(input_shapes2, shape)
in... |
def check_vocab(vocab_file, out_dir, check_special_token=True, sos=None, eos=None, unk=None):
if tf.gfile.Exists(vocab_file):
utils.print_out(('# Vocab file %s exists' % vocab_file))
vocab = []
with codecs.getreader('utf-8')(tf.gfile.GFile(vocab_file, 'rb')) as f:
vocab_size = 0
... |
def copy_attrs(orig, dest, names, only_if_set=False):
for a in Utils.to_list(names):
u = getattr(orig, a, ())
if (u or (not only_if_set)):
setattr(dest, a, u) |
class NanoDetPlusAuxHead(nn.Module):
def __init__(self, num_classes, input_channel, feat_channels=256, stacked_convs=4, strides=[8, 16, 32], conv_cfg=None, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True), activation='LeakyReLU', reg_max=16, **kwargs):
super(NanoDetPlusAuxHead, self).__init__()
... |
class HomeWorkAttack(Attack):
def __init__(self, knowledge_length=1):
super(HomeWorkAttack, self).__init__(knowledge_length)
def _generate_instances(self, single_traj):
return [single_traj[:2].values]
def assess_risk(self, traj, targets=None, force_instances=False, show_progress=False):
... |
def filter_items(items, filter_expr, order_by, is_desc, max_size, columns=[]):
new_items = []
for i in items:
if (type(i) != dict):
i = i._asdict()
if eval(filter_expr, i):
new_items.append(i)
def key_func(a):
return [a[o] for o in order_by if (a.get(o) is not... |
class ClevrDataLoader():
def __init__(self, **kwargs):
if ('question_pt' not in kwargs):
raise ValueError('Must give question_pt')
if ('scene_pt' not in kwargs):
raise ValueError('Must give scene_pt')
if ('vocab_json' not in kwargs):
raise ValueError('Must... |
def _limit_signed_rational(val, max_val, min_val):
frac = Fraction(val)
n_d = (frac.numerator, frac.denominator)
if (min(n_d) < min_val):
n_d = _limit_rational(val, abs(min_val))
if (max(n_d) > max_val):
val = Fraction(*n_d)
n_d = _limit_rational(val, max_val)
return n_d |
class SubwordField(Field):
def __init__(self, *args, **kwargs):
self.fix_len = (kwargs.pop('fix_len') if ('fix_len' in kwargs) else 0)
super().__init__(*args, **kwargs)
def build(self, dataset, min_freq=1, embed=None):
if hasattr(self, 'vocab'):
return
sequences = get... |
def test_logvar_same():
a = model.forward(x1.float())[2]
b = model.encode(x1.float())[1]
assert torch.all(a.eq(b)) |
def generate_content(index: int, task_ids: list, base_filename: str, level: int) -> str:
task_id = task_ids[(index - 1)]
noise = generate_noise(NOISE)
if (index != level):
if (level == 1):
return f'''{noise}
The current task_id is {task_id}.
{noise}
Write all the task_ids into the file o... |
_numpy_output(check_dtype=True)
def test_ufunc_signbit_u(A: dace.uint32[10]):
return np.signbit(A) |
def get_parameters():
parser = get_parser()
base_args = parser.parse_args()
if (base_args.options_type != 'generic'):
raise NotImplementedError
if (base_args.deprecated is not None):
if (base_args.deprecated == 'vgg_cifar'):
args = get_deprecated_params_vgg_cifar()
... |
def structure_loss(pred, mask):
weit = (1 + (5 * torch.abs((F.avg_pool2d(mask, kernel_size=31, stride=1, padding=15) - mask))))
wbce = F.binary_cross_entropy_with_logits(pred, mask, reduction='none')
wbce = ((weit * wbce).sum(dim=(2, 3)) / weit.sum(dim=(2, 3)))
pred = torch.sigmoid(pred)
inter = ((p... |
_if_pypy
def test_hashingvectorizer_nan_in_docs():
message = 'np.nan is an invalid document, expected byte or unicode string.'
exception = ValueError
def func():
hv = HashingVectorizer()
hv.fit_transform(['hello world', np.nan, 'hello hello'])
with pytest.raises(exception, match=message)... |
def repeat_expr(params: {}):
agent_type = params['agent']
num_tasks = params['num_tasks']
num_showings = params['num_showings']
step_size = params['step_size']
replacement_rate = 0.0001
decay_rate = 0.99
maturity_threshold = 100
util_type = 'contribution'
opt = params['opt']
weig... |
def save_video(label, step, tensor, fps=15, n_cols=None):
def _to_uint8(t):
if (t.dtype != np.uint8):
t = (t * 255.0).astype(np.uint8)
return t
if (tensor.dtype in [object]):
tensor = [_to_uint8(prepare_video(t, n_cols)) for t in tensor]
else:
tensor = prepare_vid... |
(params=[{'application/json': {'schema': {'type': 'object', 'properties': {'foo': {'type': 'string'}}}}}, {'application/json': {'schema': {'type': 'integer'}}}, {'multipart/form-data': {'schema': {'type': 'object', 'additionalProperties': False, 'properties': {'data': {'type': 'string', 'format': 'binary'}}, 'required'... |
class _CustomClusterer(BaseEstimator):
def __init__(self, n_clusters=1, expose_cluster_centers=True):
self.n_clusters = n_clusters
self.expose_cluster_centers = expose_cluster_centers
def fit(self, X, y=None):
if self.expose_cluster_centers:
self.cluster_centers_ = np.random.... |
class SentenceTransformersEncoder():
def __init__(self, model_name='shibing624/text2vec-base-chinese'):
self.model = SentenceTransformer(model_name)
def encode(self, sentences, convert_to_numpy=True):
sentence_embeddings = self.model.encode(sentences, convert_to_numpy=convert_to_numpy)
r... |
class MetadataCatalog():
_NAME_TO_META = {}
def get(name):
assert len(name)
if (name in MetadataCatalog._NAME_TO_META):
ret = MetadataCatalog._NAME_TO_META[name]
if hasattr(ret, 'dataset_name'):
logger = logging.getLogger()
logger.warning("... |
class DDPG(RLAlgorithm):
def __init__(self, env, policy, qf, es, batch_size=32, n_epochs=200, epoch_length=1000, min_pool_size=10000, replay_pool_size=1000000, discount=0.99, max_path_length=250, qf_weight_decay=0.0, qf_update_method='adam', qf_learning_rate=0.001, policy_weight_decay=0, policy_update_method='adam'... |
class ImageNetValidation(ImageNetBase):
NAME = 'ILSVRC2012_validation'
URL = '
AT_HASH = '5d6d0df7ed81efd49ca99ea4737e0ae5e3a5f2e5'
VS_URL = '
FILES = ['ILSVRC2012_img_val.tar', 'validation_synset.txt']
SIZES = [, 1950000]
def __init__(self, process_images=True, data_root=None, **kwargs):
... |
def _get_do_arguments(do_op):
assert (do_op.type == 'Do'), 'Expected Do op'
args = {}
for arg in do_op.arg:
if (not arg.name):
continue
if (arg.name == 'net'):
assert arg.n, 'Expected non empty net argument'
args['net'] = arg.n
elif (arg.name == 'r... |
class CyclicCodePolynomialEncoder(Encoder):
def __init__(self, code):
if (not isinstance(code, CyclicCode)):
raise ValueError('code has to be a CyclicCode')
self._polynomial_ring = code._polynomial_ring
super().__init__(code)
def __eq__(self, other):
return (isinstanc... |
def backtrace(vf: ti.template(), p, dt_: ti.template()):
v1 = bilerp(vf, p)
p1 = (p - ((0.5 * dt_) * v1))
v2 = bilerp(vf, p1)
p2 = (p - ((0.75 * dt_) * v2))
v3 = bilerp(vf, p2)
p -= (dt_ * ((((2 / 9) * v1) + ((1 / 3) * v2)) + ((4 / 9) * v3)))
return p |
def test_missing_content_type_header(case, response_factory):
response = response_factory.requests(content_type=None)
with pytest.raises(CheckFailed, match='Missing Content-Type header'):
content_type_conformance(response, case) |
def get_models(args, BERT_PT_PATH, trained=False, path_model_bert=None, path_model=None):
agg_ops = ['', 'MAX', 'MIN', 'COUNT', 'SUM', 'AVG']
cond_ops = ['=', '>', '<', 'OP']
print(f'Batch_size = {(args.bS * args.accumulate_gradients)}')
print(f'BERT parameters:')
print(f'learning rate: {args.lr_ber... |
def show_result_pyplot(model, img, result, palette=None, fig_size=(15, 10)):
if hasattr(model, 'module'):
model = model.module
img = model.show_result(img, result, palette=palette, show=False)
plt.figure(figsize=fig_size)
plt.imshow(mmcv.bgr2rgb(img))
plt.show() |
class EqualNumPyDataSplitter(NumPyDataSplitter):
def __init__(self, shuffle=True, seed=0):
self.shuffle = shuffle
self.seed = seed
def split(self, data, num_collaborators):
np.random.seed(self.seed)
idx = range(len(data))
if self.shuffle:
idx = np.random.permu... |
def test_cross_nn_distances():
X = np.array([0, 0.1, 0.3, 0.55]).reshape((- 1), 1)
X_new = np.array([0.1, 0.9]).reshape((- 1), 1)
maxk = 3
expected_indices = [[1, 0, 2], [3, 2, 1]]
expected_distances = [[0, 0.1, 0.2], [0.35, 0.6, 0.8]]
(distances, indices) = utils.compute_cross_nn_distances(X_ne... |
def test_utils_public_api():
assert (dir(pyhf.utils) == ['EqDelimStringParamType', 'citation', 'digest', 'options_from_eqdelimstring']) |
def token_char_tokenize(text):
text = char_regex.sub(' \\g<0> ', text)
tokens = num_regex.sub(DIGIT_WORD, text).split()
chars = []
for token in tokens:
if (token == DIGIT_WORD):
chars.append(token)
else:
chars.extend(list(token))
return chars |
def _get_torchscript_builtins():
functions = []
builtins = filter((lambda fn: (not _is_math_fn(fn[0]))), _get_builtins_helper())
builtins_list = list(builtins)
for (fn, _builtin_name) in builtins_list:
mod = inspect.getmodule(fn)
if (not mod):
raise RuntimeError(f'Module for ... |
class PixDADiscriminator(nn.Module):
def __init__(self, num_classes):
super(PixDADiscriminator, self).__init__()
self.n_classes = num_classes
self.ndf = 64
self.conv1 = nn.Conv2d(self.n_classes, self.ndf, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(self.ndf, (s... |
class TestMaskedTensor(TestCase):
def test_float_graph_execution_fails(self):
with tf.Graph().as_default():
assert (tf.executing_eagerly() is False)
input_shape = (1,)
(tensor, mask) = create_random_numpy_tensor_and_mask(shape=input_shape, probability_for_masked=0.1)
... |
class ModelCheckpointMine(pl.callbacks.model_checkpoint.ModelCheckpoint):
def __init__(self, *args, fault_tolerant=False, **kwargs):
super().__init__(*args, **kwargs)
self.fault_tolerant = fault_tolerant
def on_exception(self, trainer: 'pl.Trainer', *_: Any, **__: Any) -> None:
if self.f... |
class NestedDataClassProperty(Property):
def __get__(self, obj, objtype=None) -> 'Data':
return super().__get__(obj, objtype)
def dtype(self):
from dace import data as dt
return dt.Data
def from_string(s):
from dace import data as dt
dtype = getattr(dt, s, None)
... |
class SplitDataset(data.Dataset):
def __init__(self, ds, split_inds, **kwargs):
self.split_inds = list(split_inds)
self.wrapped_data = ds
self.is_lazy = (isinstance(ds, lazy_array_loader) or (hasattr(ds, 'is_lazy') and ds.is_lazy))
if self.is_lazy:
self.lens = itemgetter(... |
def CalculateTotalPCharge(mol):
Hmol = Chem.AddHs(mol)
GMCharge.ComputeGasteigerCharges(Hmol, iter_step)
res = []
for atom in Hmol.GetAtoms():
res.append(float(atom.GetProp('_GasteigerCharge')))
if (res == []):
return 0
else:
cc = numpy.array(res, 'd')
return sum(... |
(Output('data-download', 'options'), Input('data-download-parent', 'n_clicks'))
def select_download_parent(n_clicks):
options = []
ctx = dash.callback_context
prop_id = ctx.triggered_id
if (prop_id == 'data-download-parent'):
models = file_manager.get_model_list()
options += [{'label': s... |
def compact(x):
if isinstance(x, dict):
return dict(((k, v) for (k, v) in x.items() if (v is not None)))
elif isinstance(x, list):
return [elem for elem in x if (elem is not None)]
return x |
(frozen=True)
class LanguageLogicalStatement():
subject: str
subject_category: str
specifier_type: Literal[('a', 'the')]
def generate_specified_subject(self, upper=False, specifier_type=None) -> str:
specifier_type = (self.specifier_type if (specifier_type is None) else specifier_type)
i... |
def stringify(val):
if True:
return repr(val)
else:
from pprint import pformat
return pformat(val) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.