code stringlengths 101 5.91M |
|---|
def parse_pkg_info(fn):
res = {}
for ln in open(fn).read().splitlines():
if ((not ln) or (not ln[:1].strip())):
continue
(key, value) = ln.split(': ', 1)
res[key] = value
return res |
class Evaluator():
def __init__(self) -> None:
self.results = defaultdict(dict)
self.iteration = (- 1)
self.threshold_end = 0.5
def update_iteration(self, iteration: int) -> None:
self.iteration = iteration
def update_result(self, metric: str, value: Union[(float, dict)]) -> ... |
def _url_encode_impl(obj, charset, encode_keys, sort, key):
from .datastructures import iter_multi_items
iterable = iter_multi_items(obj)
if sort:
iterable = sorted(iterable, key=key)
for (key, value) in iterable:
if (value is None):
continue
if (not isinstance(key, b... |
_dispatch
def dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, workers=None, orthogonalize=None):
return (Dispatchable(x, np.ndarray),) |
def make_command(*args):
command_args = []
for arg in args:
if isinstance(arg, list):
command_args.extend(arg)
else:
command_args.append(arg)
return command_args |
class MGridClass(nd_grid):
def __init__(self):
super(MGridClass, self).__init__(sparse=False) |
def test_output_size_check_dict():
r = model1_dict.forward(x1_dict.float())
assert (len(r[0][0]) == model1_dict.output_size) |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config', required=True)
parser.add_argument('--config-args')
parser.add_argument('--section', required=True)
parser.add_argument('--inferred', required=True)
parser.add_argument('--output')
parser.add_argument('--logdir')
... |
class AdaFactorWClonedWeightPredictionForAggregation(WeightPredictor):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
from optimizers.adafactor import Adafactor
self.optimizer: Adafactor
adafactor_init(self.optimizer)
def forward(self):
if (not self.n_step... |
class CrossEntropy(nn.Module):
def __init__(self):
super().__init__()
self.loss = nn.CrossEntropyLoss(ignore_index=(- 1))
def forward(self, output, target):
return self.loss(output, target) |
def get_root_document_iterator(file_path: str) -> Iterator[str]:
import pyarrow.parquet as pq
parquet_file = pq.ParquetFile(file_path)
for batch in parquet_file.iter_batches():
df = batch.to_pandas()
for row in df.iterrows():
(yield row[1].tolist()[0]) |
def process_corpus(bliss_corpus, char_vocab, silence_duration):
from recipe.text.bliss import ProcessBlissText
ljs = ProcessBlissText(bliss_corpus, [('end_token', {'token': '~'})], vocabulary=char_vocab)
from recipe.corpus.ffmpeg import BlissFFMPEGJob, BlissRecoverDuration
filter_string = ('-af "silence... |
def logistic_nll(x: Tensor, mean: Tensor, log_scale: Tensor):
bin_size = (1 / 256)
scale = log_scale.exp()
x_centered = (x - mean)
cdf1 = (x_centered / scale)
cdf2 = ((x_centered + bin_size) / scale)
p = ((torch.sigmoid(cdf2) - torch.sigmoid(cdf1)) + 1e-12)
return (- p.log()) |
class GanLoader(object):
def __init__(self, G, N=(10 ** 10), bs=64):
(self.G, self.N, self.bs) = (G, N, bs)
def __len__(self):
return self.N
def __iter__(self):
with torch.no_grad(), Eval(self.G):
for i in range((self.N // self.bs)):
(yield self.G.sample(s... |
def filter_words(sentences):
filters = [(lambda x: x.lower()), strip_numeric, strip_punctuation, remove_stopwords, stem_sentence]
apply_filters_to_token = (lambda token: apply_filters(token, filters))
return list(map(apply_filters_to_token, sentences)) |
class pAdicRingRelaxed(pAdicRelaxedGeneric, pAdicRingBaseGeneric):
def __init__(self, p, prec, print_mode, names):
from sage.rings.padics import padic_relaxed_element
(self._default_prec, self._halting_prec, self._secure) = prec
pAdicRingBaseGeneric.__init__(self, p, self._default_prec, prin... |
def register_Ns3FdBetFfMacScheduler_methods(root_module, cls):
cls.add_constructor([param('ns3::FdBetFfMacScheduler const &', 'arg0')])
cls.add_constructor([])
cls.add_method('DoDispose', 'void', [], is_virtual=True)
cls.add_method('GetFfMacCschedSapProvider', 'ns3::FfMacCschedSapProvider *', [], is_vir... |
def test_var_args_empty():
def arg_aot(*args):
return np.zeros([20])
arg_aot.compile() |
def compute_model_dim(cfg: DictConfig) -> int:
if ((cfg.name == 'pose_gen') or (cfg.name == 'motion_gen')):
return get_smplx_dimension_from_keys(cfg.dataset.modeling_keys)
elif (cfg.name == 'path_planning'):
return 2
elif (cfg.name == 'grasp_gen'):
return ((3 + 6) + 24)
else:
... |
_utils.test()
def test_reduce_merged():
a = ti.field(ti.f32, shape=16)
b = ti.field(ti.f32, shape=4)
c = ti.field(ti.f32, shape=())
ti.root.lazy_grad()
def reduce():
for i in range(16):
b[(i // 4)] += a[i]
for i in range(4):
c[None] += b[i]
c.grad[None] = ... |
def nvmlDeviceGetName(handle):
c_name = ctypes.create_string_buffer(NVML_DEVICE_NAME_BUFFER_SIZE)
fn = _get_nvml_function('nvmlDeviceGetName')
ret = fn(handle, c_name, ctypes.c_uint(NVML_DEVICE_NAME_BUFFER_SIZE))
_check_return(ret)
return c_name.value |
def figure1():
wb = Whitebox(WhiteboxSTResnet(stresnet101('../models/resnet101v4_28NOV17_train.pth')))
if (not os.path.exists('_vggface2_topk_frontal_nonmates.pkl')):
_vggface2_topk_frontal_nonmates(wb, topk=32)
n_subjects = 16
(matelist, nonmatelist, probelist) = _triplet_mate_frontalpose_nonma... |
class TrueWeightsStorage():
def __init__(self, optimizer):
self.true_weights = None
self.true_weights_exist = False
self.optimizer = optimizer
self.change_mode = None
self.restored_true_weights_to_the_model = False
def record_change_mode(self, mode):
if (self.chan... |
_file_in_work_dir(['file_name'])
_file_read_only(['file_name'])
_low_level_step
def write_file(file_name, content, work_dir='.', **kwargs):
try:
with open(os.path.join(work_dir, file_name), 'w') as f:
f.write(content)
observation = f'File {file_name} written successfully.'
return... |
def coco_eval_with_return(result_files, result_types, coco, max_dets=(100, 300, 1000)):
for res_type in result_types:
assert (res_type in ['proposal', 'bbox', 'segm', 'keypoints'])
if mmcv.is_str(coco):
coco = COCO(coco)
assert isinstance(coco, COCO)
eval_results = {}
for res_type in... |
class DistributedGroupSampler(Sampler):
def __init__(self, dataset, samples_per_gpu=1, num_replicas=None, rank=None, seed=0):
(_rank, _num_replicas) = get_dist_info()
if (num_replicas is None):
num_replicas = _num_replicas
if (rank is None):
rank = _rank
self.... |
def get_experiments_from_kwargs(**kwargs):
kwargs_coerced = {key: as_list(val) for (key, val) in kwargs.items()}
experiments = [{key: value for (key, value) in zip(kwargs_coerced.keys(), record_values)} for record_values in itertools.product(*kwargs_coerced.values())]
return experiments |
class AverageMeterSet(object):
def __init__(self, meters=None):
self.meters = (meters if meters else {})
def __getitem__(self, key):
if (key not in self.meters):
meter = AverageMeter()
meter.update(0)
return meter
return self.meters[key]
def update... |
class ASR(sb.Brain):
def compute_forward(self, batch, stage):
batch = batch.to(self.device)
(wavs, wav_lens) = batch.sig
(tokens, _) = batch.tokens
if self.hparams.gradient_checkpointing:
wavs.requires_grad_()
logits = torch.utils.checkpoint.checkpoint(self.mo... |
.parametrize('metric', METRICS)
def test_kd_tree_numerical_consistency(global_random_seed, metric):
(X_64, X_32, Y_64, Y_32) = get_dataset_for_binary_tree(random_seed=global_random_seed, features=50)
metric_params = METRICS.get(metric, {})
kd_64 = KDTree64(X_64, leaf_size=2, metric=metric, **metric_params)
... |
def match_allen_srl_structures(dataset, srl_data, is_gold):
matched_events_count = 0
matched_args_count = 0
for (topic_id, topic) in dataset.topics.items():
for (doc_id, doc) in topic.docs.items():
for (sent_id, sent) in doc.get_sentences().items():
if (not config_dict['u... |
class ConvNorm(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=None, dilation=1, bias=True, w_init_gain='linear'):
super(ConvNorm, self).__init__()
if (padding is None):
assert ((kernel_size % 2) == 1)
padding = int(((dilation ... |
def is_union(ann):
if (ann is Union):
raise_error_container_parameter_missing('Union')
return (hasattr(ann, '__module__') and (ann.__module__ == 'typing') and (getattr(ann, '__origin__', None) is Union)) |
def normalize_tensor(x):
map_size = x.size()
aggregated = x.view(map_size[0], map_size[1], (- 1))
(minimum, _) = torch.min(aggregated, dim=(- 1), keepdim=True)
(maximum, _) = torch.max(aggregated, dim=(- 1), keepdim=True)
normalized = torch.div((aggregated - minimum), (maximum - minimum))
normal... |
_scope
def ndarray(dtype, shape, needs_grad=False):
prog = get_runtime().prog
if (prog is None):
raise TaichiRuntimeError('Cannont create ndarray, maybe you forgot to call `ti.init()` first?')
if isinstance(shape, numbers.Number):
shape = (shape,)
if (not all((((isinstance(x, int) or isi... |
class FormalPolyhedraModule(CombinatorialFreeModule):
def __classcall__(cls, base_ring, dimension, basis, category=None):
if isinstance(basis, list):
basis = tuple(basis)
if isinstance(basis, tuple):
from sage.geometry.polyhedron.base import Polyhedron_base
for P ... |
def feat_extraction(dataroot_dir, mode):
DB = read_voxceleb_structure(dataroot_dir, data_type='wavs')
if ((mode != 'train') and (mode != 'test')):
raise mode_error
count = 0
for i in range(len(DB)):
extract_MFB(DB['filename'][i], mode=mode)
count = (count + 1)
filename = ... |
class BatchAE(Data):
def __init__(self, batch=None, **kwargs):
super(BatchAE, self).__init__(**kwargs)
self.batch = batch
def from_data_list(data_list):
keys = [set(data.keys) for data in data_list]
keys = list(set.union(*keys))
assert ('batch' not in keys)
batch ... |
def register_Ns3LteRrcSapMeasGapConfig_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteRrcSap::MeasGapConfig const &', 'arg0')])
cls.add_instance_attribute('gapOffsetValue', 'uint8_t', is_const=False)
return |
def OA_15_896():
from sage.rings.finite_rings.finite_field_constructor import FiniteField
A = [[(0, None), (0, None), (0, None), (0, None), (0, None), (0, None), (0, None), (0, None), (1, None), (4, None), (2, None), (2, None), (4, None), (1, None)], [(0, None), (1, None), (2, 17), (3, 20), (4, 49), (5, 4), (6,... |
class DatasetMapperTTA():
def __init__(self, cfg):
self.min_sizes = cfg.TEST.AUG.MIN_SIZES
self.max_size = cfg.TEST.AUG.MAX_SIZE
self.flip = cfg.TEST.AUG.FLIP
self.image_format = cfg.INPUT.FORMAT
def __call__(self, dataset_dict):
numpy_image = dataset_dict['image'].permut... |
def test_gen_cylinder_mesh(output_dir):
from sfepy.mesh.mesh_generators import gen_cylinder_mesh
mesh = gen_cylinder_mesh([0.5, 1, 2, 1.5, 3], [5, 4, 3], [0, 2, 1], axis='z', non_uniform=True, verbose=False)
filename = op.join(output_dir, 'gen_cylinder.mesh')
mesh.write(filename)
tst.report('cylinde... |
def acc_stat(accuracy):
length = 10
a = accuracy[(- length)]
a_stat = [((temp - stat.mean(a)) / stat.stdev(a)) for temp in a]
return ((sum((1 for temp in a_stat if (abs(temp) > 1))) / length) < 0.5) |
class Saver(object):
def __init__(self, savedir='.', savetitle=''):
self.savedir = savedir
self.savefile = os.path.join(savedir, savetitle)
self.saver = None
def save(self, sess, itr):
if (self.saver is None):
self.saver = tf.train.Saver(max_to_keep=10)
self.s... |
class ImageConv(nn.Module):
def __init__(self, base_channels, in_channels=3):
super(ImageConv, self).__init__()
self.base_channels = base_channels
self.out_channels = (8 * base_channels)
self.conv0 = nn.Sequential(Conv2d(in_channels, base_channels, 3, 1, padding=1), Conv2d(base_chann... |
def test_case37():
url = (brokerIp + '/ngsi-ld/v1/subscriptions/urn:ngsi-ld:Subscription:7')
r = requests.delete(url)
print(r.status_code)
assert (r.status_code == 204) |
class SimplicialComplexHomset(sage.categories.homset.Homset):
def __call__(self, f):
return SimplicialComplexMorphism(f, self.domain(), self.codomain())
def diagonal_morphism(self, rename_vertices=True):
mutable = self._codomain.is_mutable()
X = self._domain.product(self._domain, rename_... |
class ExpRNNCell(RNNCell):
name = 'exprnn'
def __init__(self, d_input, d_model, orthogonal=True, hidden_activation='modrelu', **kwargs):
super().__init__(d_input, d_model, orthogonal=orthogonal, hidden_activation=hidden_activation, **kwargs) |
def consolidate_edges_scope(state: SDFGState, scope_node: Union[(nd.EntryNode, nd.ExitNode)]) -> int:
if (scope_node is None):
return 0
data_to_conn = {}
consolidated = 0
if isinstance(scope_node, nd.EntryNode):
outer_edges = state.in_edges
inner_edges = state.out_edges
i... |
class VocabBuilder():
def __init__(self, min_freq=None, max_count=None):
self.word_freq = collections.Counter()
self.min_freq = min_freq
self.max_count = max_count
def add_word(self, word, count=1):
self.word_freq[word] += count
def finish(self, *args, **kwargs):
elig... |
class BertJapaneseCharacterTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = BertJapaneseTokenizer
def setUp(self):
super().setUp()
vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '', '', '', '', '', '', '', '', '', '']
self.vocab_file = os.path.join(self.tmpdirname... |
class SNLIEval(object):
def __init__(self, taskpath, seed=1111):
logging.debug('***** Transfer task : SNLI Entailment*****\n\n')
self.seed = seed
train1 = self.loadFile(os.path.join(taskpath, 's1.train'))
train2 = self.loadFile(os.path.join(taskpath, 's2.train'))
trainlabels ... |
def _seg_18():
return [(7813, 'V'), (7814, 'M', u'w'), (7815, 'V'), (7816, 'M', u'w'), (7817, 'V'), (7818, 'M', u'x'), (7819, 'V'), (7820, 'M', u'x'), (7821, 'V'), (7822, 'M', u'y'), (7823, 'V'), (7824, 'M', u'z'), (7825, 'V'), (7826, 'M', u'z'), (7827, 'V'), (7828, 'M', u'z'), (7829, 'V'), (7834, 'M', u'a'), (7835... |
def import_request_result(request: CritiqueRequest) -> Optional[CritiqueRequestResult]:
template: CritiqueTaskTemplate = request.template
with _importers_lock:
if (template.name not in _importer):
_importer[template.name] = _MechanicalTurkRequestImporter(template)
_importer[templ... |
class Generator(torch.nn.Module):
def __init__(self, input_size, vocab_size, pad_idx):
super(Generator, self).__init__()
self._generator = torch.nn.Sequential(torch.nn.Linear(input_size, vocab_size), torch.nn.LogSoftmax(dim=(- 1)))
self.criterion = torch.nn.NLLLoss(ignore_index=pad_idx, redu... |
class DanishStemmer(_ScandinavianStemmer):
__vowels = 'aeiouya'
__consonants = 'bcdfghjklmnpqrstvwxz'
__double_consonants = ('bb', 'cc', 'dd', 'ff', 'gg', 'hh', 'jj', 'kk', 'll', 'mm', 'nn', 'pp', 'qq', 'rr', 'ss', 'tt', 'vv', 'ww', 'xx', 'zz')
__s_ending = 'abcdfghjklmnoprtvyza'
__step1_suffixes = ... |
def get_model_params(model_name, override_params):
if model_name.startswith('efficientnet'):
(w, d, s, p) = efficientnet_params(model_name)
(blocks_args, global_params) = efficientnet(width_coefficient=w, depth_coefficient=d, dropout_rate=p, image_size=s)
else:
raise NotImplementedError(... |
class distill():
def __init__(self, args, model, teacher):
self.args = args
self.student = model
self.teacher = teacher
self.student_layers = self.sampled_layer(args.arch, self.student)
self.teacher_layers = self.sampled_layer(args.teacher_arch, self.teacher)
def kwar... |
class TFBaseModelOutput(ModelOutput):
last_hidden_state: tf.Tensor = None
hidden_states: Optional[Tuple[tf.Tensor]] = None
attentions: Optional[Tuple[tf.Tensor]] = None |
class LogWriter(object):
def __init__(self, save_path, log_types=['tensorboard', 'pkl']):
self.save_path = save_path
if (len(log_types) == 0):
raise ValueError('Please specify at least one log_type file to write to in the LogWriter!')
self.writers = []
for log_type in log... |
class ComplicatedSubArray(SubArray):
def __str__(self):
return 'myprefix {0} mypostfix'.format(self.view(SubArray))
def __repr__(self):
return '<{0} {1}>'.format(self.__class__.__name__, self)
def _validate_input(self, value):
if (not isinstance(value, ComplicatedSubArray)):
... |
def add_start_docstrings_to_model_forward(*docstr):
def docstring_decorator(fn):
class_name = ':class:`~transformers.{}`'.format(fn.__qualname__.split('.')[0])
intro = ' The {} forward method, overrides the :func:`__call__` special method.'.format(class_name)
note = '\n\n .. note::\n ... |
class HeaderContent(object):
def __init__(self, header, content):
self.header = header
self.content = content
def add_header(self, header):
self.header.append(header)
def add_paragraph(self, paragraph):
self.content.append(paragraph)
def get_num_headers(self):
ret... |
def find_missing_eduspan(node, misplaced_children, verbose=False):
if verbose:
print('\nMISSING CHILDREN\n', node.eduspan, [m.eduspan for m in node.nodelist])
eduCovered = sorted(list(set([m.eduspan[0] for m in node.nodelist])))
eduCovered.extend(list(set([m.eduspan[1] for m in node.nodelist])))
... |
class ConfigCache(object):
def __init__(self):
self._configs = {}
self._default_config = {}
def set_default_config(self, config):
self._default_config = dict(config)
def set_config(self, cls_or_env_id, config):
config_key = self._get_config_key(cls_or_env_id)
self._co... |
def test_signature_setup():
mG = BilinearGroupPair()
keypair = BBSPlusKeypair.generate(mG, 9)
messages = [Bn(30), Bn(31), Bn(32), Bn(12)]
(pk, sk) = (keypair.pk, keypair.sk)
(generators, h0) = (keypair.generators, keypair.h0)
creator = BBSPlusSignatureCreator(pk)
com = creator.commit(message... |
def concepts_to_adj_matrices_2step_relax_all_pair(data):
(qc_ids, ac_ids) = data
qa_nodes = (set(qc_ids) | set(ac_ids))
extra_nodes = set()
for qid in qc_ids:
for aid in ac_ids:
if ((qid != aid) and (qid in cpnet_simple.nodes) and (aid in cpnet_simple.nodes)):
extra_n... |
def untokenize(raw: str, tokens: List[str], return_mask: bool=False, token_sym: Any=True, untoken_sym: Any=False) -> T_untokenized:
mask = []
untokenized = []
pos = raw.find(tokens[0])
if (pos != 0):
untokenized.append(raw[:pos])
mask.append(untoken_sym)
raw = raw[pos:]
prev_... |
.operations('create_user', 'get_user', 'update_user')
.openapi_version('3.0')
def test_explicit_headers_reproduction(testdir, openapi3_base_url, app_schema):
testdir.make_test(f'''
schema.base_url = "{openapi3_base_url}"
class APIWorkflow(schema.as_state_machine()):
def get_call_kwargs(self, case):
retu... |
def get_abi_tag():
soabi = get_config_var('SOABI')
impl = get_abbr_impl()
if ((not soabi) and (impl in {'cp', 'pp'}) and hasattr(sys, 'maxunicode')):
d = ''
m = ''
u = ''
if get_flag('Py_DEBUG', (lambda : hasattr(sys, 'gettotalrefcount')), warn=(impl == 'cp')):
d ... |
class TestTimeSimulation(unittest.TestCase):
def setUp(self):
mesh = discretize.TensorMesh([10, 10])
self.sim = simulation.BaseTimeSimulation(mesh=mesh)
def test_time_simulation_time_steps(self):
self.sim.time_steps = [(1e-06, 3), 1e-05, (0.0001, 2)]
true_time_steps = np.r_[(1e-0... |
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Packet__gt___Ns3Ipv6Header_Unsigned_short_Ns3Ptr__lt__ns3Ipv6Interface__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6He... |
class TestCNNModel(TfGraphTestCase):
def setup_method(self):
super().setup_method()
self.batch_size = 5
self.input_width = 10
self.input_height = 10
self.obs_input = np.ones((self.batch_size, self.input_width, self.input_height, 3))
input_shape = self.obs_input.shape[... |
def time_to_minutes(time):
if (not isinstance(time, str)):
time = str(time)
d = {'days': 0, 'hours': 0, 'minutes': 0, 'seconds': 0}
regex = list(filter((lambda regex: (regex.match(time) is not None)), timeformats))
if (len(regex) == 0):
return
assert (len(regex) == 1), 'multiple time... |
def create_linear_transform(param_dim):
return transforms.CompositeTransform([transforms.RandomPermutation(features=param_dim), transforms.LULinear(param_dim, identity_init=True)]) |
def matches_dict(criteria_dict, test_dict):
for (k, v) in criteria_dict.items():
if (k not in test_dict):
return False
elif (test_dict[k] != v):
return False
return True |
def main(config, stdout_dir, args_str):
args_list = ['train.py']
args_list += (args_str.split(' ') if (len(args_str) > 0) else [])
args_list.append('--config={}'.format(config))
num_gpus = torch.cuda.device_count()
args_list.append('--num_gpus={}'.format(num_gpus))
args_list.append('--group_name... |
def validate_il_idnr(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]:
if isinstance(df, (pd.Series, dd.Series)):
return df.apply(idnr.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
... |
class DepthWiseConv2dImplicitGEMM(nn.Conv2d):
def __init__(self, channels, kernel, bias=False):
super().__init__(channels, channels, kernel, groups=channels, bias=bias)
def forward(self, x):
if (x.dtype == torch.float32):
x = _DepthWiseConv2dImplicitGEMMFP32.apply(x, self.weight)
... |
def test_fortran_frontend_merge_comparison_arrays():
test_string = '\n PROGRAM merge_test\n implicit none\n double precision, dimension(7) :: input1\n double precision, dimension(7) :: input2\n double precision, dimension... |
class BlobAlgebra(CombinatorialFreeModule):
def __classcall_private__(cls, k, q1, q2, q3, base_ring=None, prefix='B'):
if (base_ring is None):
base_ring = get_coercion_model().common_parent(q1, q2, q3)
q1 = base_ring(q1)
q2 = base_ring(q2)
q3 = base_ring(q3)
retur... |
def build(log_file, session_file):
cluster_file = (log_file + '.cacb-clst.pkl')
if os.path.isfile(cluster_file):
logger.info('Cluster file already detected skipping')
else:
build_cluster(log_file, cluster_file)
build_cacb(cluster_file, session_file) |
def threshold_func(item, class_index, classes, threshold):
class_name = classes[class_index]
if (item[class_index] >= threshold):
return class_name
_classes = classes[:]
_classes.remove(class_name)
return _classes[0] |
def register_Ns3CallbackImplBase_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True)
cls.add_method('IsEqual', 'bool', [param('ns3::Pt... |
def labeled_unlabeled_split(labels, num_labeled, sample_mode, incl_labeled_in_unlabeled):
labels = np.array(labels)
(classes, class_counts) = np.unique(labels, return_counts=True)
num_classes = len(classes)
class_dist = (class_counts / class_counts.sum())
if (sample_mode == 'equal'):
if ((nu... |
class EnergyPower(BaseDataset):
def __init__(self, rootdir=None):
super().__init__()
if (rootdir is None):
fdir = os.path.dirname(os.path.abspath(__file__))
merlion_root = os.path.abspath(os.path.join(fdir, '..', '..', '..'))
rootdir = os.path.join(merlion_root, '... |
def extract_celeb(data_dir, data_type):
state_type_file_path = os.path.join(data_dir, (data_type + '_state_type.txt'))
context_text_file_path = os.path.join(data_dir, (data_type + '_context_text.txt'))
celeb_out_file_path = os.path.join(data_dir, (data_type + '_raw_celebs.txt'))
state_file = open(state_... |
_experiment
def vpg_garage_pytorch(ctxt, env_id, seed):
deterministic.set_seed(seed)
runner = LocalRunner(ctxt)
env = GarageEnv(normalize(gym.make(env_id)))
policy = PyTorch_GMP(env.spec, hidden_sizes=hyper_parameters['hidden_sizes'], hidden_nonlinearity=torch.tanh, output_nonlinearity=None)
value_f... |
def run_chatgpt_prediction(test_file):
print('Running ChatGPT on test file: {}'.format(test_file))
output_file = test_file.replace('.json', '.json.chatgpt')
if os.path.exists(output_file):
passed_cases = open(output_file, 'r').readlines()
if (not passed_cases[(- 1)].endswith('\n')):
... |
class TestScipyOptimizer(unittest.TestCase):
def setUp(self):
self.methods = ['Nelder-Mead', 'Powell', 'CG', 'L-BFGS-B', 'TNC', 'SLSQP']
def test_single_variable_quadratic(self):
for method in self.methods:
(obj, param, optimum) = problems.build_single_variable_quadratic()
... |
def infer_data_type(feature):
if isinstance(feature, np.ndarray):
if ((feature.dtype == np.float32) or (feature.dtype == np.float64)):
return 'float32'
elif ((feature.dtype == np.int32) or (feature.dtype == np.int64)):
return 'int64'
else:
raise ValueError... |
class DummyImpl():
def __init__(self) -> None:
self.fc1 = torch.nn.Linear(100, 100)
self.fc2 = torch.nn.Linear(100, 100)
self.optim = torch.optim.Adam(self.fc1.parameters())
self.modules = DummyModules(self.fc1, self.optim)
self.device = 'cpu:0'
_api
def train_api_fun... |
_class(removal_version='0.19.0', future_warn=True)
class Simple(WeightedLeastSquares):
def __init__(self, mesh=None, alpha_x=1.0, alpha_y=1.0, alpha_z=1.0, **kwargs):
super().__init__(mesh=mesh, length_scale_x=alpha_x, length_scale_y=alpha_y, length_scale_z=alpha_z, **kwargs) |
_utils.polymorphic_model()
class GdsMeshEps(EpsilonSpec):
type = schema_utils.polymorphic_model_type('gds_mesh')
gds = types.StringType()
background = types.ModelType(Material)
mesh_list = types.ListType(types.PolyModelType(Mesh))
stack_normal = optplan.vec3d() |
class TestFixedKeyConfigDictionary(unittest.TestCase):
def setUp(self):
self.dictionary = {'zero': 0, 'zeroStr': 'zero', '1': 'one', '2': '', 'None': None}
def test_config_correct_attributes(self):
class SomeTestConfigClass(FixedKeyConfigDictionary):
_REQUIRED_ATTRIBUTES = {'zero': i... |
class SyncTestCase(TorchTestCase):
def _syncParameters(self, bn1, bn2):
bn1.reset_parameters()
bn2.reset_parameters()
if (bn1.affine and bn2.affine):
bn2.weight.data.copy_(bn1.weight.data)
bn2.bias.data.copy_(bn1.bias.data)
def _checkBatchNormResult(self, bn1, bn2... |
def train(model, device, train_loader, optimizer):
loss_func = torch.nn.CrossEntropyLoss()
all_loss = []
prog_iter = tqdm(train_loader, desc='Training', leave=False)
for (batch_idx, batch) in enumerate(prog_iter):
(input_x, input_y) = tuple((t.to(device) for t in batch))
pred = model(inp... |
def random_input_ids(batch_size: int, sequence_length: int, vocab_size: int) -> ['tf.Tensor']:
rng = random.Random()
values = [rng.randint(0, (vocab_size - 1)) for i in range((batch_size * sequence_length))]
return tf.constant(values, shape=(batch_size, sequence_length), dtype=tf.int32) |
def _linear_to_mel(spectogram):
global _mel_basis
if (_mel_basis is None):
_mel_basis = _build_mel_basis()
return np.dot(_mel_basis, spectogram) |
def square_dist(X, X2):
Xs = tf.reduce_sum(tf.square(X), 1)
X2s = tf.reduce_sum(tf.square(X2), 1)
return ((((- 2) * tf.matmul(X, X2, transpose_b=True)) + tf.reshape(Xs, ((- 1), 1))) + tf.reshape(X2s, (1, (- 1)))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.