code stringlengths 101 5.91M |
|---|
def _get_threadpool_controller():
if (not hasattr(threadpoolctl, 'ThreadpoolController')):
return None
if (not hasattr(sklearn, '_sklearn_threadpool_controller')):
sklearn._sklearn_threadpool_controller = threadpoolctl.ThreadpoolController()
return sklearn._sklearn_threadpool_controller |
def DM_33_6_1():
M = [[0, 0, 0, 0, 0, 0], [15, 11, 22, 4, 17, 8], [19, 7, 14, 32, 22, 18], [22, 19, 8, 24, 21, 6], [9, 12, 15, 7, 26, 14], [14, 28, 23, 2, 19, 3]]
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing as AdditiveCyclic
G = AdditiveCyclic(33)
Mb = [[0, 0, 0, 0, 0, 0], [1, 4,... |
('Performing dryrun')
def do_dry_run(dryrun_suite: str, conf_path: str, max_eval_instances: int, priority: int, models: Optional[List[str]]) -> str:
output_path: str = OUTPUT_PATH_TEMPLATE.format(suite=dryrun_suite)
shutil.rmtree(output_path, ignore_errors=True)
hlog(f'Deleted old results at path: {output_p... |
class TestSphericalBoundariesIntersections(TestCase):
def test_2d_sphere_constraints(self):
(ta, tb, intersect) = sphere_intersections([0, 0], [1, 0], 0.5)
assert_array_almost_equal([ta, tb], [0, 0.5])
assert_equal(intersect, True)
(ta, tb, intersect) = sphere_intersections([2, 0], [... |
def get_vectors_norm(vectors):
transposed = tf.transpose(vectors)
v_mag = tf.sqrt(tf.math.reduce_sum((transposed * transposed), axis=0))
return tf.transpose(tf.math.divide_no_nan(transposed, v_mag)) |
.parametrize('action_size', [3])
.parametrize('observation_shape', [(100,)])
.parametrize('epsilon', [0.5])
def test_constant_epsilon_greedy(action_size: int, observation_shape: Sequence[int], epsilon: float) -> None:
explorer = ConstantEpsilonGreedy(epsilon)
ref_x = np.random.random((1, *observation_shape))
... |
def conv2da(input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name='conv2d', reuse=False, padding='SAME'):
with tf.variable_scope(name, reuse=reuse):
w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[(- 1)], output_dim], initializer=tf.contrib.layers.xavier_initializer())
conv = tf.n... |
def _latex_file_(objects, title='SAGE', debug=False, sep='', tiny=False, math_left='\\[', math_right='\\]', extra_preamble=''):
process = True
if has_latex_attr(objects):
objects = [objects]
if (not isinstance(objects, list)):
objects = [objects]
if tiny:
size = '\\tiny\n'
el... |
def init_seed(seed):
torch.cuda.manual_seed_all(seed)
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed) |
def SetDel(s, e):
ctx = _ctx_from_ast_arg_list([s, e])
e = _py2expr(e, ctx)
return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx) |
class ReasoningQAPromptHelper(PromptHelper):
few_shot_examples = REASONING_QA_FEWSHOT_EXAMPLES
def get_chatgpt_query(self, metadata: Dict[(str, Any)]) -> Dict[(str, Any)]:
return metadata
def postprocess_response_text(self, text: str, query, uri) -> Dict[(str, Any)]:
response = self.check_ch... |
def build_lightning_optimizers(model, config):
optimizer = build_optimizer(model, config)
if config.training.lr_scheduler:
lr_scheduler = build_scheduler(optimizer, config)
return {'optimizer': optimizer, 'lr_scheduler': {'scheduler': lr_scheduler, 'interval': 'step'}}
else:
return o... |
class mask_rcnn_outputs(nn.Module):
def __init__(self, dim_in):
super().__init__()
self.dim_in = dim_in
n_classes = (cfg.MODEL.NUM_CLASSES if cfg.MRCNN.CLS_SPECIFIC_MASK else 1)
if cfg.MRCNN.USE_FC_OUTPUT:
self.classify = nn.Linear(dim_in, (n_classes * (cfg.MRCNN.RESOLUTI... |
def handler(event):
size = event.get('size')
graph_generating_begin = datetime.datetime.now()
graph = igraph.Graph.Barabasi(size, 10)
graph_generating_end = datetime.datetime.now()
process_begin = datetime.datetime.now()
result = graph.spanning_tree(None, False)
process_end = datetime.dateti... |
class Translator_difftok_tail(nn.Module):
def __init__(self, num_tok, num_tok_out, dim, dim_out, mult=2, depth=5):
super().__init__()
self.blocks = nn.ModuleList([translator_base(num_tok, dim, dim, mult=2) for d in range(depth)])
self.gelu = nn.GELU()
self.tail = translator_difftok(n... |
class SpeechRecognitionModel(nn.Module):
def __init__(self, n_cnn_layers, n_rnn_layers, rnn_dim, n_class, n_feats, stride=2, dropout=0.1):
super(SpeechRecognitionModel, self).__init__()
n_feats = (n_feats // 2)
self.cnn = nn.Conv2d(1, 32, 3, stride=stride, padding=(3 // 2))
self.resc... |
.parametrize('y_pred', [np.array(y_pred_list), y_pred_list])
def test_residual_normalised_conformity_score_get_conformity_scores(y_pred: NDArray) -> None:
residual_norm_score = ResidualNormalisedScore(random_state=random_state)
conf_scores = residual_norm_score.get_conformity_scores(X_toy, y_toy, y_pred)
ex... |
def test_iht_fit_resample_class_obj():
est = GradientBoostingClassifier(random_state=RND_SEED)
iht = InstanceHardnessThreshold(estimator=est, random_state=RND_SEED)
(X_resampled, y_resampled) = iht.fit_resample(X, Y)
assert (X_resampled.shape == (12, 2))
assert (y_resampled.shape == (12,)) |
def ndim_tensor2im(image_tensor, imtype=np.uint8, batch=0):
image_numpy = image_tensor[batch].cpu().float().numpy()
result = np.argmax(image_numpy, axis=0)
return result.astype(imtype) |
class docURLLink(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None):
self.url = url
if (mixedclass_ is None):
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
... |
def normalize_final_sql(format_sql_5):
format_sql_final = format_sql_5.replace('\n', ' ').replace(' . ', '.').replace('group by', 'group_by').replace('order by', 'order_by').replace('! =', '!=').replace('limit value', 'limit_value')
if (('t1' in format_sql_final) or ('t2' in format_sql_final) or ('t3' in format... |
def do_slice(value, slices, fill_with=None):
seq = list(value)
length = len(seq)
items_per_slice = (length // slices)
slices_with_extra = (length % slices)
offset = 0
for slice_number in range(slices):
start = (offset + (slice_number * items_per_slice))
if (slice_number < slices_... |
def densenet169(**kwargs):
model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 32, 32), **kwargs)
return model |
class JointExtractionDecoder(DecoderBase, JointExtractionDecoderMixin):
def __init__(self, config: JointExtractionDecoderConfig):
super().__init__()
self.ck_decoder = config.ck_decoder.instantiate()
self.ck_loss_weight = config.ck_loss_weight
if config.has_attr_decoder:
s... |
def cost_matrix(width=16, dist=2):
size = (width ** 2)
C = np.zeros([size, size], dtype=np.float32)
for m_i in range(size):
i1 = (m_i // width)
j1 = (m_i % width)
for m_j in range(size):
i2 = (m_j // width)
j2 = (m_j % width)
C[(m_i, m_j)] = ((abs(... |
def batcher(params, batch):
batch = [(' '.join(sent) if (sent != []) else '.') for sent in batch]
embeddings = params['google_use'](batch)
return embeddings |
def build_datasets(dataset_list: List[str], dataset_config: DictConfig, dataset_type='train'):
datasets = []
for dataset in dataset_list:
if (dataset in dataset_config):
dataset_config = dataset_config[dataset]
else:
warnings.warn((f'Dataset {dataset} is missing from data... |
def get_data_fields(mode, cfg):
points_transform = data.SubsamplePoints(cfg['data']['points_subsample'])
input_type = cfg['data']['input_type']
fields = {}
if (cfg['data']['points_file'] is not None):
if (input_type != 'pointcloud_crop'):
fields['points'] = data.PointsField(cfg['data... |
class ChooseInfoSubprocVecEnv(ShareVecEnv):
def __init__(self, env_fns, spaces=None):
self.waiting = False
self.closed = False
nenvs = len(env_fns)
self._mp_ctx = mp.get_context('forkserver')
(self.remotes, self.work_remotes) = zip(*[self._mp_ctx.Pipe(duplex=True) for _ in ra... |
class Vertex(Vrepresentation):
def type(self):
return self.VERTEX
def is_vertex(self):
return True
def _repr_(self):
return ('A vertex at ' + repr(self.vector()))
def homogeneous_vector(self, base_ring=None):
v = (list(self._vector) + [1])
return vector((base_ring... |
def process_quote_data(quote_data):
results = []
for threshold_data in quote_data:
summed_data = [sum(col) for col in zip(*threshold_data)]
quote_precision = rounding(((100 * summed_data[0]) / (summed_data[0] + summed_data[2])))
quote_recall = rounding(((100 * summed_data[0]) / (summed_d... |
class Statistics(object):
def __init__(self, loss=0, n_words=0, n_correct=0):
self.loss = loss
self.n_words = n_words
self.n_correct = n_correct
self.n_src_words = 0
self.start_time = time.time()
def update(self, stat):
self.loss += stat.loss
self.n_words ... |
def repr_short_to_parent(s):
from sage.groups.misc_gps.argument_groups import ArgumentGroup
from sage.misc.sage_eval import sage_eval
def extract(s):
try:
return ArgumentGroup(specification=s)
except Exception as e:
e_ag = e
e_ag.__traceback__ = None
... |
def TranslateY(img, v):
assert ((- 0.45) <= v <= 0.45)
if (random_mirror and (random.random() > 0.5)):
v = (- v)
v = (v * img.size[1])
return img.transform(img.size, PIL.Image.AFFINE, (1, 0, 0, 0, 1, v)) |
def assert_warn_len_equal(mod, n_in_context, py34=None, py37=None):
try:
mod_warns = mod.__warningregistry__
except AttributeError:
mod_warns = {}
num_warns = len(mod_warns)
if ('version' in mod_warns):
num_warns -= 1
if (sys.version_info[:2] >= (3, 7)):
if (p... |
def prepare_raw_data(path_to_raw_csv):
df = pd.read_csv(path_to_raw_csv)
df = df.drop(columns=['section'])
df = df.drop(columns=['section_id'])
df = df.drop(columns=['attempt'])
df.rename(columns={'69192: Vanligen fyll i den individuella sifferkoden som du fatt pa mail tillsammans med lanken till de... |
.parametrize('reference, observations, anti_ref, expected', [(tf.constant([1.0, 1.0]), None, tf.constant([(- 1.0), (- 1.0)]), (tf.constant([[(- 1.0), (- 1.0)]]), tf.constant([[1.0, 1.0]]))), (tf.constant([1.0, 1.0]), None, tf.constant([1.0, (- 1.0)]), (tf.constant([[1.0, (- 1.0)]]), tf.constant([[1.0, 1.0]]))), (tf.con... |
def autobatch(model, imgsz=640, fraction=0.9, batch_size=16):
prefix = colorstr('AutoBatch: ')
LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}')
device = next(model.parameters()).device
if (device.type == 'cpu'):
LOGGER.info(f'{prefix}CUDA not detected, using default CPU b... |
class LeanPreprocessedTempVarAlloc(LeanPreprocessedCodeElement):
identifier: TypedIdentifier
resolved_type: CairoType
add_ap_instr: Optional[LeanPreprocessedAddAp]
expr: Expression
def get_exprs(self) -> List[Expression]:
return ([self.expr] if (self.expr is not None) else []) |
def _is_hardcoded_xy(args):
is_hardcoded_xy = (args.dataset in HARDCODED_JUST_XY)
return is_hardcoded_xy |
def resize_pinhole_camera(pinhole_cam, tgt_size):
(_h, _w) = tgt_size
scale_h = (_h / pinhole_cam.shape[0])
scale_w = (_w / pinhole_cam.shape[1])
(_cx, _cy) = ((pinhole_cam.cx * scale_w), (pinhole_cam.cy * scale_h))
(_fx, _fy) = ((pinhole_cam.fx * scale_w), (pinhole_cam.fy * scale_h))
cropped_pi... |
class StrLiteralBuilder(object):
def __init__(self, target_encoding):
self._bytes = BytesLiteralBuilder(target_encoding)
self._unicode = UnicodeLiteralBuilder()
def append(self, characters):
self._bytes.append(characters)
self._unicode.append(characters)
def append_charval(se... |
def pixel_cross_entropy(gt, pred, lengths):
batch_size = int(gt.shape[0])
individual_loss = []
pred = torch.sigmoid(pred)
for i in range(batch_size):
length = int(lengths[i].cpu())
g = gt[i][:length]
p = pred[i][:length]
epsilon = 1e-20
individual_loss.append((- t... |
class RobertaForTokenClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class SparseDropoutWithReplacementTest(hu.HypothesisTestCase):
(**hu.gcs_cpu_only)
def test_no_dropout(self, gc, dc):
X = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).astype(np.int64)
Lengths = np.array([2, 2, 2, 2, 2]).astype(np.int32)
replacement_value = (- 1)
self.ws.create_blob(... |
.serializable
class MapExit(ExitNode):
def __init__(self, map: 'Map'):
super(MapExit, self).__init__()
if (map is None):
raise ValueError('Map for MapExit can not be None.')
self._map = map
def map_type():
return Map
def from_json(cls, json_obj, context=None):
... |
def train_one_epoch(run_manager, args, epoch, warmup_epochs=0, warmup_lr=0):
dynamic_net = run_manager.net
dynamic_net.train()
run_manager.run_config.train_loader.sampler.set_epoch(epoch)
MyRandomResizedCrop.EPOCH = epoch
nBatch = len(run_manager.run_config.train_loader)
data_time = AverageMeter... |
(scope='module')
def continuum_compare_data(continuum_compare_data_fname, request):
compare_data = pd.HDFStore(continuum_compare_data_fname, mode='r')
def fin():
compare_data.close()
request.addfinalizer(fin)
return compare_data |
def __GCD_sequence(v, **kwargs):
if (len(v) == 0):
return ZZ(0)
if hasattr(v, 'universe'):
g = v.universe()(0)
else:
g = ZZ(0)
for vi in v:
g = vi.gcd(g, **kwargs)
return g |
def splantider(tck, n=1):
if (n < 0):
return splder(tck, (- n))
(t, c, k) = tck
sh = ((slice(None),) + ((None,) * len(c.shape[1:])))
for j in range(n):
dt = (t[(k + 1):] - t[:((- k) - 1)])
dt = dt[sh]
c = (np.cumsum((c[:((- k) - 1)] * dt), axis=0) / (k + 1))
c = n... |
def gen_config(config_file):
cfg_dict = {}
_edict2dict(cfg_dict, cfg)
with open(config_file, 'w') as f:
yaml.dump(cfg_dict, f, default_flow_style=False) |
class GradientAccumulator(object):
def __init__(self):
self._gradients = []
self._accum_steps = None
def step(self):
if (self._accum_steps is None):
self._accum_steps = tf.Variable(tf.constant(0, dtype=tf.int64), trainable=False, synchronization=tf.VariableSynchronization.ON_... |
class SSIM(object):
def __init__(self):
pass
def evaluate(self, data_path_real, data_path_fake):
path_list_real = glob.glob(os.path.join(data_path_real, '*.jpg'))
path_list_fake = glob.glob(os.path.join(data_path_fake, '*.jpg'))
path_list_real = sorted(path_list_real)
pat... |
def _Call(t, symbols, inferred_symbols):
inf_type = _dispatch(t.func, symbols, inferred_symbols)
arg_types = [_dispatch(e, symbols, inferred_symbols) for e in t.args]
for e in t.keywords:
_dispatch(e, symbols, inferred_symbols)
if inf_type:
return inf_type
name = dace.frontend.python... |
def write_list_to_file(strings, list_file):
with open(list_file, 'w') as f:
for s in strings:
f.write(('%s\n' % s))
pass |
class BaselineModelChunked(BaselineModel):
mp_states: List[List[nets.MessagePassingStateChunked]]
init_mp_states: List[List[nets.MessagePassingStateChunked]]
def _create_net_fns(self, hidden_dim, encode_hints, processor_factory, use_lstm, encoder_init, dropout_prob, hint_teacher_forcing, hint_repred_mode):
... |
def show_ipython_images_slider(image_pathes_list, slider_label='', first_arg=0):
def display_f(**kwargs):
display(Image(image_pathes_list[kwargs[slider_label]]))
display(interactive(display_f, **{slider_label: IntSlider(min=0, max=(len(image_pathes_list) - 1), step=1)})) |
def generate_list_of_planets(number):
planetList = []
for i in range(number):
planetList.append(genExamplePlanet())
return planetList |
def load(data_dir, config, splits):
if (config['data.dataset'] == 'omniglot'):
ds = load_omniglot(data_dir, config, splits)
else:
raise ValueError(f"Unknow dataset: {config['data.dataset']}")
return ds |
def measure_table(rows):
widths = {}
for row in rows:
for (idx, col) in enumerate(row):
widths[idx] = max(widths.get(idx, 0), term_len(col))
return tuple((y for (x, y) in sorted(widths.items()))) |
def reduce_sum(layers, embed_keep_prob=1.0, drop_func=dropout, reuse=True):
layer = tf.add_n(layers)
if (embed_keep_prob < 1):
layer = drop_func(layer, embed_keep_prob)
return layer |
def residual_block(cnn, depth, stride, pre_activation):
input_layer = cnn.top_layer
in_size = cnn.top_size
if (in_size != depth):
shortcut = cnn.apool(1, 1, stride, stride, input_layer=input_layer, num_channels_in=in_size)
padding = ((depth - in_size) // 2)
if (cnn.channel_pos == 'ch... |
(help='Initialize ADE20K dataset.')
('download_dir', type=str)
def main(download_dir):
dataset_dir = (Path(download_dir) / 'ade20k')
download_ade(dataset_dir, overwrite=False) |
def test_available_if_unbound_method():
est = AvailableParameterEstimator()
AvailableParameterEstimator.available_func(est)
est = AvailableParameterEstimator(available=False)
with pytest.raises(AttributeError, match="This 'AvailableParameterEstimator' has no attribute 'available_func'"):
Availab... |
class MLP_LeNet(nn.Module):
def __init__(self, input_nc, input_width, input_height, no_classes=10, **kwargs):
super(MLP_LeNet, self).__init__()
assert (((input_nc * input_width) * input_height) > 120)
self.fc1 = nn.Linear(((input_nc * input_width) * input_height), 120)
self.fc2 = nn.... |
class MinecraftHoleyDungeonConfig(MinecraftConfig):
problem: str = 'minecraft_3D_dungeon_holey'
weights: Dict[(str, int)] = field(default_factory=(lambda : {'regions': 0, 'path-length': 100, 'chests': 300, 'n_jump': 100, 'enemies': 100, 'nearest-enemy': 200})) |
def build_run_environment(para_dict, dl_name, dp_name, model_name, runner_name):
if (type(para_dict) is str):
para_dict = eval(para_dict)
if (type(dl_name) is str):
dl_name = eval(dl_name)
if (type(dp_name) is str):
dp_name = eval(dp_name)
if (type(model_name) is str):
mo... |
def pytest_addoption(parser: Parser) -> None:
parser.addoption('--level', action='store', default=None, type=int, help='Specify test level')
parser.addoption('--beat-challenges', action='store_true', help='Spepcifies whether the test suite should attempt to beat challenges') |
def fit_model(config_data, model, train_iterator, valid_iterator=None):
if (not config_data.get('cross_valid')):
return fit_model_single(config_data, model, train_iterator, valid_iterator)
elif (config_data.get('cross_valid') == 'true'):
return fit_model_cv(config_data, model, train_iterator, va... |
class HumanoidCfg(LeggedRobotCfg):
class env(LeggedRobotCfg.env):
num_envs = 4096
num_observations = 38
num_actions = 10
episode_length_s = 5
class terrain(LeggedRobotCfg.terrain):
curriculum = False
mesh_type = 'plane'
measure_heights = False
class co... |
def create_random_join(schema, no_relationships):
assert (no_relationships >= 0), 'No_relationships must be greater equal 0'
start_tables = list(schema.tables)
random.shuffle(start_tables)
start_table_obj = start_tables[0]
merged_tables = {start_table_obj.table_name}
relationships = set()
fo... |
.dataclass
class TrainState():
step: int
variables: flax.core.FrozenDict[(str, Any)]
dynamic_scale: flax.optim.DynamicScale
opt_tx: optax.GradientTransformation = flax.struct.field(pytree_node=False)
opt_state: optax.OptState
ema: EmaState |
class ManifoldSubsetFiniteFamily(ManifoldObjectFiniteFamily):
def from_subsets_or_families(cls, *subsets_or_families):
def generate_subsets():
from sage.manifolds.subset import ManifoldSubset
for arg in subsets_or_families:
if isinstance(arg, ManifoldSubset):
... |
def random_hparams(algorithm, dataset, seed, larger_batch=False):
return {a: c for (a, (b, c)) in _hparams(algorithm, dataset, seed, larger_batch=larger_batch).items()} |
_utils.test(require=ti.extension.assertion, debug=True, gdb_trigger=False)
def test_cpu_debug_snode_writer_out_of_bound_negative():
x = ti.field(ti.f32, shape=3)
with pytest.raises(AssertionError):
x[(- 1)] = 10.0 |
class Segmentation(Chunk):
def __init__(self, array: np.ndarray, **kwargs):
super().__init__(array, **kwargs)
assert (array.ndim == 3)
assert np.issubdtype(array.dtype, np.integer)
def from_chunk(cls, chunk):
assert isinstance(chunk, Chunk)
return cls(chunk.array, voxel_o... |
class Baseline(object):
def __init__(self, target, config={}):
(self.X_pos, self.y_pos) = ([], [])
(self.X_neg, self.y_neg) = ([], [])
self.intmd_path = 'intermediate/'
self.target = target
def load_data(self):
with open(((self.intmd_path + self.target) + '.pos.mat.pkl'),... |
_class(removal_version='0.19.0', future_warn=True)
class SimpleSmoothDeriv(SmoothnessFirstOrder):
pass |
def get_inference_trainer_params():
return d(cls=LatentInferenceTrainer, params=d(train_every_n_steps=(1 if USE_LATENT else 0), latent_learning_rate=0.0005, log_every_n_steps=100.0, save_every_n_steps=0, train_min_buffer_size=2, max_steps_per_rollout=100, obs_to_output_obs_fn=obs_to_output_obs_fn)) |
class EvaluateOptions(TestBaseOptions):
def __init__(self):
super().__init__()
parser = self.parser
parser.add_argument('--dataset', type=str, default='mixamo', choices=['mixamo', 'humanact12'], help='on which dataset to evaluate')
parser.add_argument('--rot_only', action='store_true... |
def parse_function(*metrics, directory='', args=None, end_signal=None):
print(f'Parsing files in {directory}')
subdirs = listdir_nohidden(directory, sort=True)
outputs = []
for subdir in subdirs:
fpath = osp.join(directory, subdir, 'log.txt')
assert check_isfile(fpath)
good_to_go... |
def run_simulator(agents, config, treatment_assignment, seed):
population = []
for (agent, treated) in zip(agents, treatment_assignment):
agent = copy.deepcopy(agent)
if treated:
agent.risk_aversion = 0.9
population.append(agent)
return civil_violence.simulate(population,... |
def concatenate_two_boxes(box_a: spaces.Box, box_b: spaces.Box) -> spaces.Box:
if ((not isinstance(box_a, spaces.Box)) or (not isinstance(box_b, spaces.Box))):
raise ValueError('This method will only concatenate Box spaces')
lows = np.concatenate([box_a.low, box_b.low])
highs = np.concatenate([box_a... |
def has_module(module_name):
if (sys.version_info > (3, 4)):
import importlib
name_parts = module_name.split('.')
for i in range(len(name_parts)):
if (importlib.util.find_spec('.'.join(name_parts[:(i + 1)])) is None):
return False
return True
else:
... |
class VocabularyShared(VocabularyBase):
def __init__(self, vocab_path, data_raw_src=None, data_raw_tgt=None, lower=True):
self.lower = lower
self.id2tok = {}
self.tok2id = {}
if (not check_file_exists(vocab_path)):
assert ((data_raw_src is not None) and (data_raw_tgt is n... |
class TensorRef():
def __init__(self, tensor, dtype, layout) -> None:
if isinstance(tensor, np.ndarray):
ptr = cuda.CUdeviceptr(tensor.__array_interface__['data'][0])
elif (torch_available and isinstance(tensor, torch.Tensor)):
ptr = cuda.CUdeviceptr(tensor.data_ptr())
... |
class IMECEncoder():
def __init__(self, medium, block_size=(2 ** 8), **kwargs):
self.medium = medium
self.context = kwargs.get('context', None)
self.block_size = block_size
self.send_block_size_header = kwargs.get('send_block_size_header', None)
self.send_n_chunks_header = kw... |
class Resnet_Imb_YOTO_ep100_cifar100_2():
def __init__(self):
self.set_config()
def set_config(self):
self.filename_head = (self.__class__.__name__ + '_')
self.checkpoint_path = None
def get_model(self):
param_ranges = ((0.9, 0.99999),)
params = (0.999,)
param... |
def test_malformed1():
fname = pjoin(TEST_DATA_PATH, 'malformed1.mat')
with open(fname, 'rb') as f:
assert_raises(ValueError, loadmat, f) |
class QAData(object):
def __init__(self, logger, args, data_path, is_training):
self.data_path = data_path
if args.debug:
self.data_path = data_path.replace('train', 'dev')
with open(self.data_path, 'r') as f:
self.data = json.load(f)
if (type(self.data) == di... |
class AmazonViewSavedAddresses(VirtualFunctionTool):
name = 'AmazonViewSavedAddresses'
summary = "View the user's saved addresses."
parameters: List[ArgParameter] = []
returns: List[ArgReturn] = [{'name': 'addresses', 'type': 'array', 'description': "A list of objects, each containing 'remark', 'name', ... |
class AEModule(nn.Module):
def __init__(self, n_features, sequence_length, hidden_size, activation=nn.Tanh):
super().__init__()
input_length = (n_features * sequence_length)
dec_steps = (2 ** np.arange(max(np.ceil(np.log2(hidden_size)), 2), np.log2(input_length))[1:])
dec_setup = np.... |
def check_scalar(x, name, target_type, *, min_val=None, max_val=None, include_boundaries='both'):
def type_name(t):
module = t.__module__
qualname = t.__qualname__
if (module == 'builtins'):
return qualname
elif (t == numbers.Real):
return 'float'
elif... |
def render_requirements(filename):
pinned = get_pinned_packages()
with open(filename) as fin:
contents = ''.join(fin.readlines())
return contents.format(**pinned) |
def convert_tokens_to_ids(vocab, tokens):
ids = []
for token in tokens:
if (token in SPECIAL_TOKEN_MAPPING):
token = SPECIAL_TOKEN_MAPPING[token]
ids.append(vocab[token])
return ids |
def test_copy_touch():
form = ak.forms.NumpyForm('int64', form_key='buffer')
(layout, report) = typetracer_with_report(form)
typetracer.asarray(layout.data, dtype=np.int32)
assert (report.data_touched == ['buffer']) |
class TFSpeech2TextPreTrainedModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def is_valid_data(object):
is_sampled_data = hasattr(object, 'resample')
try:
has_nevents = hasattr(object, 'nevents')
except RuntimeError:
if is_sampled_data:
object.resample()
has_nevents = hasattr(object, 'nevents')
else:
has_nevents = False
... |
class NormalisedRastriginBenchmark(Benchmark):
def __init__(self, nb_features: int=2):
self.nb_features = nb_features
ind_domain = (0.0, 1.0)
super().__init__(fn=algorithms.partial(illumination_rastrigin_normalised, nb_features=nb_features), ind_domain=ind_domain, fitness_domain=((0.0, 1.0),... |
class UniversalImageQualityIndexMetric(Metric):
def __init__(self):
self._metric = None
self._device = get_torch_device()
def __repr__(self):
return 'UniversalImageQualityIndexMetric()'
def evaluate(self, scenario_state: ScenarioState, metric_service: MetricService, eval_cache_path: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.