code stringlengths 101 5.91M |
|---|
def compute_mdlp_all_intervals(mdlp_discretizer):
category_names = []
for (i, cut_points) in enumerate(mdlp_discretizer.cut_points_):
if (cut_points is None):
category_names.append(None)
continue
idxs = np.arange((len(cut_points) + 1))
names = mdlp_discretizer.ass... |
_module()
class YOLOXModeSwitchHook(Hook):
def __init__(self, num_last_epochs=15, skip_type_keys=('Mosaic', 'RandomAffine', 'MixUp')):
self.num_last_epochs = num_last_epochs
self.skip_type_keys = skip_type_keys
self._restart_dataloader = False
def before_train_epoch(self, runner):
... |
class TerminalController():
BOL = ''
UP = ''
DOWN = ''
LEFT = ''
RIGHT = ''
CLEAR_SCREEN = ''
CLEAR_EOL = ''
CLEAR_BOL = ''
CLEAR_EOS = ''
BOLD = ''
BLINK = ''
DIM = ''
REVERSE = ''
NORMAL = ''
HIDE_CURSOR = ''
SHOW_CURSOR = ''
COLS = None
LINES = ... |
class AnyNet(Backbone):
def __init__(self, *, stem_class, stem_width, block_class, depths, widths, group_widths, strides, bottleneck_ratios, se_ratio, activation_class, freeze_at=0, norm='BN', out_features=None):
super().__init__()
self.stem = stem_class(3, stem_width, norm, activation_class)
... |
def _find_dep_file_path(main_file, file_path, relative_path_search=False):
abs_path = os.path.abspath(file_path)
if ((not os.path.exists(abs_path)) and (file_path.endswith('.pxi') or relative_path_search)):
rel_file_path = os.path.join(os.path.dirname(main_file), file_path)
if os.path.exists(rel... |
class RandomActiveLearningNodeNB(LearningNodeNB, RandomActiveLeafClass):
def __init__(self, initial_stats=None, max_features=2, random_state=None):
super().__init__(initial_stats)
self.max_features = max_features
self.feature_indices = np.array([])
self.random_state = random_state
... |
def test_forward_combined_dummy(pretrain_file):
model = build_model(pretrain_file, '--combined_dummy_embedding')
run_forward_checks(model)
model = build_model(pretrain_file, '--no_combined_dummy_embedding')
run_forward_checks(model) |
class Dipole(BaseSrc):
def __init__(self, receiver_list=None, location_a=None, location_b=None, location=None, **kwargs):
if (location_a is not None):
if (location_b is None):
raise ValueError('For a dipole source both location_a and location_b must be set')
if (locat... |
class MarianOnnxConfig(OnnxSeq2SeqConfigWithPast):
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
if (self.task in ['default', 'seq2seq-lm']):
common_inputs = OrderedDict([('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'})])
... |
def test(key, model_type, seed=0, gpu=0):
dn = ('./%s_%s' % (key, model_type))
fn = ('%s/sgd%03d.dat' % (dn, seed))
if (not os.path.exists(dn)):
os.mkdir(dn)
device = ('cuda:%d' % (gpu,))
if (model_type == 'logreg'):
(module, (n_tr, n_val, n_test), (lr, decay, num_epoch, batch_size))... |
def build_keras_model():
query = Input(name='query', shape=(query_term_maxlen, 1))
doc = Input(name='doc', shape=(query_term_maxlen, hist_size))
z = doc
for i in range(num_layers):
z = Dense(hidden_sizes[i], kernel_initializer=initializer_fc)(z)
z = Activation('tanh')(z)
z = Permute(... |
def absorb_bn(module, bn_module):
w = module.weight.data
if (module.bias is None):
zeros = torch.Tensor(module.out_channels).zero_().type(w.type())
module.bias = nn.Parameter(zeros)
b = module.bias.data
invstd = bn_module.running_var.clone().add_(bn_module.eps).pow_((- 0.5))
w.mul_(i... |
(0.1)
def movies_being_shown(entities, *argv, **kargs):
message = "Here are the movies in theater now:\n - The Shawshank Redemption (1994)\n - The Godfather (1972)\n - The Godfather: Part II (1974)\n - The Dark Knight (2008)\n - 12 Angry Men (1957)\n - Schindler's List (1993)\n - ... |
def generate(args, g_ema, device, mean_latent):
with torch.no_grad():
g_ema.eval()
sample_z = torch.randn(args.sample, args.latent, device=device)
for i in tqdm(range(args.pics)):
truncation = ((args.truncation / (args.pics - 1)) * i)
print(truncation)
(sa... |
class Clusterer(kmeans.Clusterer):
def __init__(self, initialization=True, matching=True, **kwargs):
self.initialization = initialization
self.matching = matching
super().__init__(**kwargs)
def get_initialization(self, features, labels):
means = []
for i in range(self.k):... |
class Stack():
def __init__(self, dtype=np.dtype(np.int64), length=1024):
self.buffer = np.full(length, 999, dtype=dtype)
self.pointer = 0
def __str__(self):
return ' '.join(([str(x) for x in self.buffer[:self.pointer]] + ['<- top']))
def __repr__(self):
return '<Stack {0}>'.... |
class atlas_threads_info(atlas_info):
dir_env_var = ['PTATLAS', 'ATLAS']
_lib_names = ['ptf77blas', 'ptcblas'] |
def parse_args():
parser = argparse.ArgumentParser(description='Train a STREAM network')
parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default='cfg/STREAM/bird.yaml', type=str)
parser.add_argument('--gpu', dest='gpu_id', type=int, default=0)
parser.add_argument('--data_dir',... |
def RegisterModel(model_name):
def decorator(f):
MODEL_REGISTRY[model_name] = f
return f
return decorator |
def configuration(parent_package='', top_path=None):
from distutils.sysconfig import get_python_inc
from scipy._build_utils.system_info import get_info, NotFoundError, numpy_info
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
from scipy._build_utils import get_g77_abi_wrappe... |
.skip
def test_inline_lambda_array():
def lamb(A: dace.float64[20], B: dace.float64[20], C: dace.float64[20]):
f = (lambda a, b: (a + b))
A[:] = f(B, C)
A = np.random.rand(20)
B = np.random.rand(20)
C = np.random.rand(20)
lamb(A, B, C)
assert np.allclose(A, (B + C)) |
def distributions(sigma, q):
mu0 = (lambda y: pdf_gauss(y, sigma=sigma, mean=0.0))
mu1 = (lambda y: pdf_gauss(y, sigma=sigma, mean=1.0))
mu = (lambda y: (((1 - q) * mu0(y)) + (q * mu1(y))))
return (mu0, mu1, mu) |
_spec_function('entity_matching')
def get_entity_matching_spec(dataset: str) -> RunSpec:
scenario_spec = ScenarioSpec(class_name='helm.benchmark.scenarios.entity_matching_scenario.EntityMatchingScenario', args={'dataset': dataset})
adapter_spec = get_generation_adapter_spec(instructions='Are Product A and Produ... |
class CamembertForMaskedLM():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def mean_std(data):
data = data[(~ np.isnan(data))]
mean = np.mean(data)
std = np.std(data)
return (mean, std) |
class TestTreeFragments(CythonTest):
def test_basic(self):
F = self.fragment(u'x = 4')
T = F.copy()
self.assertCode(u'x = 4', T)
def test_copy_is_taken(self):
F = self.fragment(u'if True: x = 4')
T1 = F.root
T2 = F.copy()
self.assertEqual('x', T2.stats[0].... |
_driver.jit
def reset_log_mask(log_mask, episode_length):
tidx = numba_driver.threadIdx.x
if (tidx == 0):
for i in range((episode_length + 1)):
log_mask[i] = 0 |
def parse_bboxes_file(ann_filenames, ann_is_gt_box, detect_thresh, boxes_sample_rate=1):
all_boxes = {}
count = 0
unique_box_count = 0
for (filename, is_gt_box) in zip(ann_filenames, ann_is_gt_box):
with g_pathmgr.open(filename, 'r') as f:
for line in f:
row = line.st... |
def validate_auth(ctx: click.core.Context, param: click.core.Parameter, raw_value: (str | None)) -> (tuple[(str, str)] | None):
if (raw_value is not None):
with reraise_format_error(raw_value):
(user, password) = tuple(raw_value.split(':'))
if (not user):
raise click.BadParam... |
def create_initializer_tensors(parser, weight_file):
tensors = []
if (weight_file == None):
return tensors
initializer_ops = parser.get_initializer_op_names_n_shape_type()
npzfile = np.load(weight_file)
for op_name in initializer_ops:
if (op_name in npzfile.files):
mlir_t... |
def HanoiTowerGraph(pegs, disks, labels=True, positions=True):
from sage.rings.integer import Integer
pegs = Integer(pegs)
if (pegs < 2):
raise ValueError(('Pegs for Tower of Hanoi graph should be two or greater (not %d)' % pegs))
disks = Integer(disks)
if (disks < 1):
raise ValueErr... |
def cached_path(url_or_filename, cache_dir=None, force_download=False, proxies=None, resume_download=False, user_agent: Union[(Dict, str, None)]=None, extract_compressed_file=False, force_extract=False, local_files_only=False) -> Optional[str]:
if (cache_dir is None):
cache_dir = TRANSFORMERS_CACHE
if i... |
def MainOpFunctionThatThrowsCustomErrorInBuilder(inputs, _):
raise CustomError('This is an intentional exception in builder.') |
.skipif((platform.system() == 'Windows'), reason='Fails on Windows')
def test_cli(testdir, unique_hook, raw_schema, cli, openapi3_base_url, hypothesis_max_examples, snapshot_cli):
assert (run(testdir, cli, unique_hook, raw_schema, openapi3_base_url, hypothesis_max_examples) == snapshot_cli) |
def prc_auc(y_true, y_score):
(precision, recall, threshold) = precision_recall_curve(y_true, y_score)
auc = calculate_auc(recall, precision)
return auc |
class BenchmarkDiscreteTimeSeries(BenchmarkDiscreteTimeSeriesBase):
def __init__(self, algo_dict: Dict=None, kargs_dict: Dict=None, num_exp: int=20, custom_metric_dict: Optional[Dict]={}, **kargs):
BenchmarkDiscreteTimeSeriesBase.__init__(self, algo_dict=algo_dict, num_exp=num_exp, kargs_dict=kargs_dict, cu... |
class GroupOps(object):
def identity():
_res = ([0.0] * 4)
_res[0] = 0
_res[1] = 0
_res[2] = 0
_res[3] = 0
return sym.EquirectangularCameraCal.from_storage(_res)
def inverse(a):
_a = a.data
_res = ([0.0] * 4)
_res[0] = (- _a[0])
_re... |
class RawXXreverseDataset(data.Dataset):
def __init__(self, raw_file, list_file, audio_window):
self.raw_file = raw_file
self.audio_window = audio_window
self.utts = []
with open(list_file) as f:
temp = f.readlines()
temp = [x.strip() for x in temp]
self.h... |
_node_type()
class WaveguideModeSource(optplan.EmSource):
type = schema_utils.polymorphic_model_type('source.waveguide_mode')
center = optplan.vec3d()
extents = optplan.vec3d()
normal = optplan.vec3d()
mode_num = types.IntType()
power = types.FloatType() |
class ConvBnReluResidualTest(BaseKerasFeatureNetworkTest):
def __init__(self, unit_test):
super().__init__(unit_test, experimental_exporter=True)
def create_networks(self):
inputs = layers.Input(shape=self.get_input_shapes()[0][1:])
y = layers.Conv2D(7, 8)(inputs)
x = layers.Batc... |
class COIN(JoinFeature):
def __init__(self):
JoinFeature.__init__(self, 'sage_numerical_backends_coin', [MIPBackend('coin')], spkg='sage_numerical_backends_coin') |
class TraceHistory(_History):
def on_epoch_end(self, epoch, logs):
self._record_trace()
return super().on_epoch_end(epoch, logs) |
def inference(network, test_loader):
if torch.cuda.is_available():
network = network.to('cuda:0')
network.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for (data, target) in test_loader:
if torch.cuda.is_available():
data = data.to('cuda:0')
... |
def got() -> operations.GraphOfOperations:
operations_graph = operations.GraphOfOperations()
plans = operations.Generate(2, 1)
operations_graph.append_operation(plans)
for i in range(1, 3):
list_id = f'List {i}'
sub_list = operations.Selector((lambda thoughts, list_id=list_id: [thought f... |
class Resolver(BaseResolver):
_allowed_strategies = {'eager', 'only-if-needed', 'to-satisfy-only'}
def __init__(self, preparer, finder, wheel_cache, make_install_req, use_user_site, ignore_dependencies, ignore_installed, ignore_requires_python, force_reinstall, upgrade_strategy, py_version_info=None):
s... |
def feature_prop(feats, g, k):
assert (feats.shape[0] == g.num_nodes())
degs = g.in_degrees().float().clamp(min=1)
norm = torch.pow(degs, (- 0.5)).unsqueeze(1)
for _ in range(k):
feats = (feats * norm)
g.ndata['h'] = feats
g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))
... |
def resonant_secular_contribution_dictionary(j, k, Nmin, Nmax, G, mIn, mOut, MIn, MOut, Lambda0In, Lambda0Out):
extra_args = (G, mIn, mOut, MIn, MOut, Lambda0In, Lambda0Out)
Nmin = (2 * (Nmin // 2))
Nmax = (2 * (Nmax // 2))
all_dicts = []
nmax = ((Nmax + 2) // (2 * k))
for n in range(1, (nmax + ... |
class FBLASRoutine():
_blas_name = ''
_user_name = ''
_width = generator_definitions.DEFAULT_WIDTH
_type: fblas_types.RoutineType
_type_str: str
_uses_shift_registers = False
_size_shift_registers = 0
_codegen = None
_incx = 1
_incy = 1
_tile_n_size = generator_definitions.DE... |
def build_graph(deps):
nodes = []
edges = []
for d in deps.values():
if ((d.dst == no_parent) or (d.dep == no_parent)):
nodes.append((d.src, d.lemma))
else:
dst_ids = [int(dst_id) for dst_id in d.dst.split(sep_deps_list)]
dst_types = d.dep.split(sep_deps_l... |
class GIN(ScalableGNN):
def __init__(self, num_nodes: int, in_channels: int, hidden_channels: int, out_channels: int, num_layers: int):
super().__init__(num_nodes, hidden_channels, num_layers, pool_size=2, buffer_size=60000)
self.in_channels = in_channels
self.out_channels = out_channels
... |
def sample(dataset: datasets.Dataset, seed: int, n_examples_per_label: int) -> Dict[(str, List[Union[(str, int)]])]:
examples_by_label = collections.defaultdict(list)
hash_to_index = collections.defaultdict(list)
for (idx, row) in enumerate(dataset):
fingerprint = _hash(row['text'], seed)
ex... |
class PacifyFlushWrapper(object):
def __init__(self, wrapped):
self.wrapped = wrapped
def flush(self):
try:
self.wrapped.flush()
except IOError as e:
import errno
if (e.errno != errno.EPIPE):
raise
def __getattr__(self, attr):
... |
def test_iterations_max_constrained():
def fg(x):
n = len(x)
c = np.arange(n)
f = (x.dot(x) + c.dot(x))
g = ((2 * x) + c)
return (f, g)
def constraint_f(x):
f = (np.sum(x) - 1)
return f
def constraint_jac_prod(x, y):
g = np.ones_like(x)
... |
def test_replace_ref_nodes_with_names_nested():
class OuterModel(optplan.ProblemGraphNode.Schema):
type = types.StringType(default='Model')
value = optplan.ReferenceType(optplan.ProblemGraphNode.Schema)
class InnerModel(optplan.ProblemGraphNode.Schema):
type = types.StringType(default='M... |
def train(params):
assert params['training'], 'change training mode to true'
tf.compat.v1.logging.info('Building the model ...')
transformer = Transformer(num_layers=params['num_layers'], d_model=params['model_depth'], num_heads=params['num_heads'], dff=params['dff'], vocab_size=params['vocab_size'], batch_... |
def make_proba_distribution(action_space: gym.spaces.Space, use_sde: bool=False, dist_kwargs: Optional[Dict[(str, Any)]]=None) -> Distribution:
if (dist_kwargs is None):
dist_kwargs = {}
if isinstance(action_space, spaces.Box):
assert (len(action_space.shape) == 1), 'Error: the action space must... |
def format_csv(df, timestamp_column=None, value_columns=None):
timestamp_column_name = (df.columns[timestamp_column] if timestamp_column else df.columns[0])
value_column_names = (df.columns[value_columns] if value_columns else df.columns[1:])
data = dict()
data['timestamp'] = df[timestamp_column_name].a... |
def get_default_environments() -> List[str]:
cp = subprocess.run(['tox', '-l'], stdout=subprocess.PIPE)
return [str(s, 'utf-8') for s in cp.stdout.splitlines()] |
def overlaps(x, y):
if ((x.start == x.stop) or (y.start == y.stop)):
return False
return (((x.start < y.stop) and (x.stop > y.start)) or ((x.stop > y.start) and (y.stop > x.start))) |
class ExpressionNice(Expression):
def __init__(self, ex):
from sage.symbolic.ring import SR
self._parent = SR
Expression.__init__(self, SR, x=ex)
def _repr_(self):
d = self._parent._repr_element_(self)
list_d = []
_list_derivatives(self, list_d)
for m in l... |
def bbox_coco_to_center(bbox):
bbox[0] = (bbox[0] + (bbox[2] / 2))
bbox[1] = (bbox[1] + (bbox[3] / 2))
bbox[2] = bbox[2]
bbox[3] = bbox[3]
return bbox |
def test_setup(tmp_path):
logfile = str((tmp_path / 'testlog.log'))
setup(use_stdout=True, filename=logfile, log_level=logging.DEBUG) |
class FIDInceptionE_1(torchvision.models.inception.InceptionE):
def __init__(self, in_channels):
super(FIDInceptionE_1, self).__init__(in_channels)
def forward(self, x):
branch1x1 = self.branch1x1(x)
branch3x3 = self.branch3x3_1(x)
branch3x3 = [self.branch3x3_2a(branch3x3), self.... |
def do_striptags(value):
if hasattr(value, '__html__'):
value = value.__html__()
return Markup(text_type(value)).striptags() |
def _valid_data_column_names(features_list, target_columns):
valid_data_column_names = []
for feature in features_list:
if ((feature['name'] not in target_columns) and (feature['is_ignore'] != 'true') and (feature['is_row_identifier'] != 'true')):
valid_data_column_names.append(feature['name... |
class W2Vec(Txt2Vec):
def __init__(self, data_path, norm=0, clean=True):
super(W2Vec, self).__init__(data_path, norm, clean)
self.w2v = BigFile(data_path)
(vocab_size, self.ndims) = self.w2v.shape()
logger.info(('vob size: %d, vec dim: %d' % (vocab_size, self.ndims)))
def _encodi... |
class DebertaV2TokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
slow_tokenizer_class = Deb... |
class MultiGenerativeModel():
def __init__(self, generative_models: list, model_probs='equal', shared_context_gen=None):
self.generative_models = generative_models
self.num_models = len(generative_models)
self.model_prior = self._determine_model_prior(model_probs)
self.shared_context... |
def get_default_group() -> Optional[ProcessGroup]:
return torch_dist.distributed_c10d._get_default_group() |
def sample_categorical(n_cat, batchsize, distribution='uniform', xp=np):
if (distribution == 'uniform'):
return xp.random.randint(low=0, high=n_cat, size=batchsize).astype(xp.int32)
else:
raise NotImplementedError |
def parse_wheel(wheel_zip, name):
try:
info_dir = wheel_dist_info_dir(wheel_zip, name)
metadata = wheel_metadata(wheel_zip, info_dir)
version = wheel_version(metadata)
except UnsupportedWheel as e:
raise UnsupportedWheel('{} has an invalid wheel, {}'.format(name, str(e)))
che... |
class AuxiliaryHeadImageNet(nn.Module):
def __init__(self, C, num_classes):
super(AuxiliaryHeadImageNet, self).__init__()
self.features = nn.Sequential(nn.ReLU(inplace=True), nn.AvgPool2d(5, stride=2, padding=0, count_include_pad=False), nn.Conv2d(C, 128, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU... |
class AvoidOOM():
def __init__(self, to_cpu=True, test=False):
self.to_cpu = to_cpu
self.test = test
def retry_if_cuda_oom(self, func):
(func)
def wrapped(*args, **kwargs):
if (not self.test):
with _ignore_torch_cuda_oom():
return f... |
class A006318(SloaneSequence):
def __init__(self):
SloaneSequence.__init__(self, offset=0)
def _repr_(self):
return 'Large Schroeder numbers.'
def _eval(self, n):
if (n == 0):
return ZZ.one()
return ZZ((sum(((((2 ** k) * arith.binomial(n, k)) * arith.binomial(n, (... |
def get_lexer(environment):
key = (environment.block_start_string, environment.block_end_string, environment.variable_start_string, environment.variable_end_string, environment.comment_start_string, environment.comment_end_string, environment.line_statement_prefix, environment.line_comment_prefix, environment.trim_... |
class TrackedSpace(Space):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.visited_in_episode = False
def reset(self, agent_infos):
super().reset(agent_infos)
agent_infos['tracking_counter'] = 0
agent_infos['num_tracked_squares'] = (agent_infos... |
def _cuda_deserialize(obj, location):
if location.startswith('cuda'):
if (location[5:] == ''):
device = 0
else:
device = max(int(location[5:]), 0)
if (not torch.cuda.is_available()):
raise RuntimeError("Attempting to deserialize object on a CUDA device but... |
class NonBlocking(IterDataPipe):
not_available_hook = default_not_available_hook
def __iter__(self):
self.reset_iterator()
return self
def __next__(self):
while True:
try:
return self.nonblocking_next()
except StopIteration:
rai... |
class MedMNISTShardDataset(ShardDataset):
def __init__(self, x, y, data_type: str='train', rank: int=1, worldsize: int=1) -> None:
self.data_type = data_type
self.rank = rank
self.worldsize = worldsize
self.x = x[(self.rank - 1)::self.worldsize]
self.y = y[(self.rank - 1)::se... |
class MdpStepCollector(StepCollector):
def __init__(self, env, policy, max_num_epoch_paths_saved=None, render=False, render_kwargs=None):
if (render_kwargs is None):
render_kwargs = {}
self._env = env
self._policy = policy
self._max_num_epoch_paths_saved = max_num_epoch_p... |
class MaxRewardPriorityQueue():
def __init__(self):
self.elems = []
def __len__(self):
return len(self.elems)
def add_list(self, smis, scores):
new_elems = [StorageElement(smi=smi, score=score) for (smi, score) in zip(smis, scores)]
self.elems.extend(new_elems)
self.e... |
def is_in_index_region(lat, lon, index='ONI'):
(lat_bounds, lon_bounds) = get_region_bounds(index=index)
if (lat_bounds[0] <= lat <= lat_bounds[1]):
if (lon_bounds[0] <= lon <= lon_bounds[1]):
return True
return False |
class VariableEmbedder(Embedder):
def __init__(self, params, wd=0.0, initializer=None, name='variable_embedder'):
(V, d) = (params.vocab_size, params.hidden_size)
with tf.variable_scope(name):
self.emb_mat = tf.get_variable('emb_mat', dtype='float', shape=[V, d], initializer=initializer)... |
class LSTMwRecDropout(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, pad=False, rec_dropout=0):
super().__init__()
self.batch_first = batch_first
self.pad = pad
self.num_layers = num_layers
sel... |
def register_Ns3MmWaveMacSchedSapProvider_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::MmWaveMacSchedSapProvider const &', 'arg0')])
cls.add_method('SchedDlCqiInfoReq', 'void', [param('ns3::MmWaveMacSchedSapProvider::SchedDlCqiInfoReqParameters const &', 'params')], is... |
def test_regular_regular_axis1():
a1 = ak.from_json('[[0.0, 1.1], [2.2, 3.3]]')
a2 = ak.from_json('[[4.4, 5.5, 6.6], [7.7, 8.8, 9.9]]')
a1 = ak.to_regular(a1, axis=1)
a2 = ak.to_regular(a2, axis=1)
c = ak.concatenate([a1, a2], axis=1)
assert (c.to_list() == [[0.0, 1.1, 4.4, 5.5, 6.6], [2.2, 3.3,... |
class OutputInTheMiddleNet(torch.nn.Module):
def __init__(self):
super(OutputInTheMiddleNet, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 3, kernel_size=1, stride=1)
self.conv2 = torch.nn.Conv2d(3, 3, kernel_size=1, stride=1)
self.identity = torch.nn.Identity()
def forward(se... |
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__ns3NetDevice__gt___Ns3Time_Ns3Time_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet con... |
class Graph():
def __init__(self, layout='h36m', strategy='spatial', max_hop=1, dilation=1):
self.max_hop = max_hop
self.dilation = dilation
self.get_edge(layout)
self.hop_dis = get_hop_distance(self.num_node, self.edge, max_hop=max_hop)
self.get_adjacency(strategy)
def _... |
def sproot(tck, mest=10):
if isinstance(tck, BSpline):
if (tck.c.ndim > 1):
mesg = 'Calling sproot() with BSpline objects with c.ndim > 1 is not recommended.'
warnings.warn(mesg, DeprecationWarning)
(t, c, k) = tck.tck
sh = tuple(range(c.ndim))
c = c.transpose... |
def register_Ns3TwoRayGroundPropagationLossModel_methods(root_module, cls):
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_constructor([])
cls.add_method('SetFrequency', 'void', [param('double', 'frequency')])
cls.add_method('SetSystemLoss', 'void', [param('double', 'systemLoss')... |
def test_montage_simple_rgb():
(n_images, n_rows, n_cols, n_channels) = (2, 2, 2, 2)
arr_in = np.arange((((n_images * n_rows) * n_cols) * n_channels), dtype=float)
arr_in = arr_in.reshape(n_images, n_rows, n_cols, n_channels)
arr_out = montage(arr_in, channel_axis=(- 1))
arr_ref = np.array([[[0, 1],... |
def get_logger(name, log_dir, config_dir):
config_dict = json.load(open('{}/log_config.json'.format(config_dir)))
config_dict['handlers']['file_handler']['filename'] = '{}/{}'.format(log_dir, name.replace('/', '-'))
logging.config.dictConfig(config_dict)
logger = logging.getLogger(name)
std_out_form... |
class CnnC3(Convolution2DArchitectureBase, NeuralNetworkTrainingDefault):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def build_model(self, x_shape, y_shape):
self.assert_shapes(x_shape, y_shape)
assert (x_shape[1:] == (101, 6, 1))
n_classes = y_shape[1... |
def test_comments(foundation_cache):
pipe = stanza.Pipeline('en', model_dir=TEST_MODELS_DIR, processors='tokenize,pos,constituency', foundation_cache=foundation_cache)
doc = pipe(TEST_TEXT)
check_results(doc)
for sentence in doc.sentences:
assert any((x.startswith('# constituency = ') for x in s... |
(('Python' not in caffe.layer_type_list()), 'Caffe built without Python layer support')
class TestPythonLayer(unittest.TestCase):
def setUp(self):
net_file = python_net_file()
self.net = caffe.Net(net_file, caffe.TRAIN)
os.remove(net_file)
def test_forward(self):
x = 8
se... |
class BenchmarkArguments():
models: List[str] = list_field(default=[], metadata={'help': 'Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version of all available models'})
batch_sizes: List[int] = list_field(default=[8], metadata={'help': 'List of batch sizes for wh... |
class graph_dict_helper(object):
def __init__(self, properties_data=None, object_placing=None, object_states=None, max_nodes=300):
if (properties_data is None):
properties_data = load_properties_data()
if (object_placing is None):
object_placing = load_object_placing()
... |
class SentencepieceTokenizer(object):
def __init__(self, vocab, unk_token, do_lower_case=False, remove_space=True, keep_accents=True, sp_model_kwargs: Optional[Dict[(str, Any)]]=None):
self.vocab = vocab
self.unk_token = unk_token
self.do_lower_case = do_lower_case
self.remove_space ... |
class Params():
def __init__(self, **kwargs):
self.input_shape = kwargs.get('input_shape', (96, 1400))
self.input_channels = kwargs.get('input_channels', 1)
self.cnn_features_list = kwargs.get('cnn_features_list', [16, 32, 64, 96, 128])
self.cnn_kernel_size = kwargs.get('cnn_kernel_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.