code
stringlengths
101
5.91M
def filesys_decode(path): if isinstance(path, six.text_type): return path fs_enc = (sys.getfilesystemencoding() or 'utf-8') candidates = (fs_enc, 'utf-8') for enc in candidates: try: return path.decode(enc) except UnicodeDecodeError: continue
def save_as_rust(mlp, dataset, output): with open(output, 'w') as f: (mrs, nrs) = dataset.get_mr_nr_values() params = {} for (name, tensor) in mlp.named_parameters(): params[name] = tensor.detach().numpy() (big_product_mkn_threshold, big_product_kernel_choice) = dataset.b...
def test_loop_description(): C = sq.Capacitor(1) loop1 = sq.Loop(id_str='loop1') JJ1 = sq.Junction(1, loops=[loop1], cap=C, id_str='JJ1') JJ2 = sq.Junction(1, loops=[loop1], cap=C, id_str='JJ2') L = sq.Inductor(1, loops=[loop1], cap=C, id_str='ind') elements = {(0, 1): [JJ1], (0, 2): [JJ2], (1, ...
def dummy_lower5(context, builder, sig, args): def compute(left): return abs(left.x) return context.compile_internal(builder, compute, sig, args)
def run_mlp(_trainMode, _dataType, _oRate, _var, _GPU_ID): (_n, _oRange, _hdims, _actv, _maxEpoch, _PLOT_EVERY, _SAVE_NET, _SAVE_FIG) = get_common_config() (x, y, t) = data4reg(_type=_dataType, _n=_n, _oRange=_oRange, _oRate=_oRate, measVar=_var) xtest = np.linspace(start=(- 3), stop=3, num=500).reshape(((-...
class Model(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, input_to_constant): super(Model, self).__init__() self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size) if input_to_constant: self.conv.weight.data.fill...
def _make_sparse(grad, grad_indices, values): size = grad.size() if ((grad_indices.numel() == 0) or (values.numel() == 0)): return torch.empty_like(grad) return torch.sparse_coo_tensor(grad_indices, values, size)
class BasicConv2d(nn.Module): def __init__(self, input_channels, output_channels, **kwargs): super().__init__() self.conv = nn.Conv2d(input_channels, output_channels, bias=False, **kwargs) self.bn = nn.BatchNorm2d(output_channels) self.relu = nn.ReLU(inplace=True) def forward(sel...
def create_emb_layer(weights_matrix=None, voc_size=None, embed_dim=None, trainable_embeds=True) -> torch.nn.Embedding: assert ((weights_matrix is not None) or ((voc_size is not None) and (embed_dim is not None))), 'Please define anything: weights_matrix or voc_size & embed_dim' if (weights_matrix is not None): ...
def split_core_object_name(core_object_name): args = core_object_name.split('_') dtypes = [] for dtype_name in args[1:]: dtypes.append(bb.dtype_from_name(dtype_name)) return (args[0], dtypes)
class BaseModel(nn.Module): def __init__(self, config): super(BaseModel, self).__init__() self.config = config self.use_cuda = torch.cuda.is_available()
def load_weights(model, yolo_weight_file): data = np.fromfile(yolo_weight_file, np.float32) data = data[4:] index = 0 for layer in model.layers: shape = [w.shape for w in layer.get_weights()] if (shape != []): (kshape, bshape) = shape bia = data[index:(index + np....
class GenericEnum(GenericAccessibleObject): def __init__(self, owner: TypeInfo): super().__init__(owner) self._generated_type = Instance(owner) self._names = [e.name for e in typing.cast(list[enum.Enum], list(typing.cast(type[enum.Enum], owner.raw_type)))] def generated_type(self) -> Pro...
class ArgPackType(CompoundType): def __init__(self, **kwargs): self.members = {} elements = [] for (k, dtype) in kwargs.items(): if isinstance(dtype, StructType): self.members[k] = dtype elements.append([dtype.dtype, k]) elif isinstance...
def format_stat(stat): if isinstance(stat, Number): stat = '{:g}'.format(stat) elif isinstance(stat, AverageMeter): stat = '{:.3f}'.format(stat.avg) elif isinstance(stat, TimeMeter): stat = '{:g}'.format(round(stat.avg)) elif isinstance(stat, StopwatchMeter): stat = '{:g}...
def register_Ns3RrcConnectionReestablishmentRejectHeader_methods(root_module, cls): cls.add_constructor([param('ns3::RrcConnectionReestablishmentRejectHeader const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'bIterator')], is_virtual=True) ...
class MNISTLeaveOut(MNIST): img_size = (28, 28) def __init__(self, root, l_out_class, split='training', transform=None, target_transform=None, download=False): super(MNISTLeaveOut, self).__init__(root, transform=transform, target_transform=target_transform, download=download) if ((split == 'trai...
def FoF_search(array, threshold): def cycle_through_options(coord): for i in range(len(coord)): for j in [(- 1), 1]: new_coordinate = [k for k in coord] new_coordinate[i] += j (yield tuple(new_coordinate)) out_map = np.zeros(array.shape, dtype=...
def get_getbuffer_call(code, obj_cname, buffer_aux, buffer_type): ndim = buffer_type.ndim cast = int(buffer_type.cast) flags = get_flags(buffer_aux, buffer_type) pybuffernd_struct = buffer_aux.buflocal_nd_var.cname dtype_typeinfo = get_type_information_cname(code, buffer_type.dtype) code.globals...
def load_loggers(cfg): log_path = cfg.General.log_path Path(log_path).mkdir(exist_ok=True, parents=True) log_name = Path(cfg.config).parent version_name = Path(cfg.config).name[:(- 5)] cfg.log_path = (((Path(log_path) / log_name) / version_name) / f'fold{cfg.Data.fold}') print(f'---->Log dir: {c...
def comp(a, b, op): if b.isTime(): if (op == '='): return b.contains(a) elif (op == '!='): return (not b.contains(a)) if (op == '='): return (a == b) elif (op == '<'): return (a < b) elif (op == '>'): return (a > b) elif (op == '!='): ...
class ElementWiseArrayOperation2D(pm.SingleStateTransformation): map_entry = pm.PatternNode(nodes.MapEntry) def expressions(cls): return [sdutil.node_path_graph(cls.map_entry)] def can_be_applied(self, graph: dace.SDFGState, expr_index: int, sdfg: dace.SDFG, permissive: bool=False): map_entr...
def assert_dict_keys_equal(dictionary, target_keys): assert isinstance(dictionary, dict) assert (set(dictionary.keys()) == set(target_keys))
.parametrize('knn_methods', knn_methods) def test_kne_proba(knn_methods): (pool_classifiers, X_dsel, y_dsel, X_test, y_test) = setup_classifiers() kne = KNORAE(pool_classifiers, knn_classifier=knn_methods, voting='soft') kne.fit(X_dsel, y_dsel) probas = kne.predict_proba(X_test) expected = np.load('...
class HalfCheetahEnv(HalfCheetahEnv_): def _get_obs(self): return np.concatenate([self.sim.data.qpos.flat[1:], self.sim.data.qvel.flat, self.get_body_com('torso').flat]).astype(np.float32).flatten() def viewer_setup(self): camera_id = self.model.camera_name2id('track') self.viewer.cam.ty...
class InMemoryDemoDatabase(DemoDatabase): def __init__(self): self.data: List[Permadata] = [] def add_result(self, headers: JsonDict, model_name: str, inputs: JsonDict, outputs: JsonDict) -> Optional[int]: self.data.append(Permadata(model_name, inputs, outputs)) return (len(self.data) - ...
def test_detect_col_types_consistent(): df1 = pd.DataFrame({'num': rng.random(5), 'cat': list('abcde')}) df2 = pd.DataFrame({'num': rng.random(5), 'cat': list('fghil')}) assert (detect_consistent_col_types(df1, df2) == {'cat': ['cat'], 'num': ['num']})
((not have_working_shmget()), 'shmget does not work') def test_pickle_unpickle_auto_unused(): old_num_servers = None for i in range(10): m = numpy.random.randn(((i * 2) + 1), ((i * 3) + 2)) p = pickle_dumps((m, m, m)) new_num_servers = len(SharedNumpyArray.ServerInstances) if (ol...
def _handle_PacketIn(event): event_info(event) ALL_PORTS = of.OFPP_FLOOD packet = event.parsed src_key = (event.connection, packet.src) table[src_key] = event.port dst_key = (event.connection, packet.dst) dst_port = table.get(dst_key) if (dst_port is None): packet_out = of.ofp_pa...
class AttrCheck(object): def __init__(self, attrs: list=[], func=(lambda x: x)): self.attrs = attrs self.func = func
def setup_module(module): if (not Path('mobilenetv2-7.onnx').exists()): urllib.request.urlretrieve(' 'mobilenetv2-7.onnx') if (not Path('mobilenet_v2_1.0.onnx.nnef.tgz').exists()): urllib.request.urlretrieve(' 'mobilenet_v2_1.0.onnx.nnef.tgz')
class qCommutingPolynomials(qCommutingPolynomials_generic): def __init__(self, q, B, names): indices = FreeAbelianMonoid(len(names), names) qCommutingPolynomials_generic.__init__(self, q, B, indices, indices.variable_names()) def _repr_(self): names = ', '.join(self.variable_names()) ...
_function() def lf_carry_subject(x): if (x.object_category == 'person'): if (x.subject_category in ['chair', 'bike', 'snowboard', 'motorcycle', 'horse']): return CARRY return ABSTAIN
def get_dataset_name(config): name_map = dict(CityscapesDataset='Cityscapes', CocoDataset='COCO', CocoPanopticDataset='COCO', DeepFashionDataset='Deep Fashion', LVISV05Dataset='LVIS v0.5', LVISV1Dataset='LVIS v1', VOCDataset='Pascal VOC', WIDERFaceDataset='WIDER Face', OpenImagesDataset='OpenImagesDataset', OpenIma...
def inc_dec_constructor(is_prefix, operator): return (lambda pos, **kwds: DecrementIncrementNode(pos, is_prefix=is_prefix, operator=operator, **kwds))
def _distributed_main(i, main, args, kwargs): args.device_id = i if (torch.cuda.is_available() and (not args.cpu)): torch.cuda.set_device(args.device_id) if (args.distributed_rank is None): args.distributed_rank = (kwargs.get('start_rank', 0) + i) args.distributed_rank = distributed_init...
def crop_xml(xml, sub_set_crop_path, instanc_size=511): xmltree = ET.parse(xml) objects = xmltree.findall('object') frame_crop_base_path = join(sub_set_crop_path, xml.split('/')[(- 1)].split('.')[0]) if (not isdir(frame_crop_base_path)): makedirs(frame_crop_base_path) img_path = xml.replace(...
class omniglot(Dataset): def __init__(self, root='data/meta-dataset/omniglot', transform=None): self.transform = transform self.dataset = Omniglot(root, 'test', transform) self.label = [] for pair in self.dataset._flat_character_images: self.label.append(pair[1]) def ...
_model('wav2vec2', dataclass=Wav2Vec2Config) class Wav2Vec2Model(BaseFairseqModel): def __init__(self, cfg: Wav2Vec2Config): super().__init__() self.cfg = cfg feature_enc_layers = eval(cfg.conv_feature_layers) self.embed = feature_enc_layers[(- 1)][0] self.feature_extractor =...
.parametrize('T', [x for x in np.typecodes['All'] if (x not in 'eGUVOMm')]) def test_bandwidth_square_inputs(T): n = 20 k = 4 R = np.zeros([n, n], dtype=T, order='F') R[([x for x in range(n)], [x for x in range(n)])] = 1 R[([x for x in range((n - k))], [x for x in range(k, n)])] = 1 R[([x for x ...
def hyperbolic_triangle(a, b, c, model='UHP', **options): return hyperbolic_polygon((a, b, c), model, **options)
_utils.test() def test_matrix_arg_insertion_pos(): rgba8 = ti.types.vector(4, ti.u8) def _render(color_attm: ti.types.ndarray(rgba8, ndim=2), camera_pos: ti.math.vec3, camera_up: ti.math.vec3): up = ti.math.normalize(camera_up) for (x, y) in color_attm: o = camera_pos color_attm ...
def camPosToQuaternion(cx, cy, cz): q1a = 0 q1b = 0 q1c = (math.sqrt(2) / 2) q1d = (math.sqrt(2) / 2) camDist = math.sqrt((((cx * cx) + (cy * cy)) + (cz * cz))) cx = (cx / camDist) cy = (cy / camDist) cz = (cz / camDist) t = math.sqrt(((cx * cx) + (cy * cy))) tx = (cx / t) ty...
def drn_d_24(BatchNorm, pretrained=True): model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 2, 2], arch='D', BatchNorm=BatchNorm) if pretrained: pretrained = model_zoo.load_url(model_urls['drn-d-24']) del pretrained['fc.weight'] del pretrained['fc.bias'] model.load_state_dict(pretrained...
def sentence_ppx(num_symbols, output_logits, targets, masks): batch_size = tf.shape(output_logits)[0] local_masks = tf.reshape(masks, [(- 1)]) one_hot_targets = tf.one_hot(targets, num_symbols) ppx_prob = tf.reduce_sum((tf.nn.log_softmax(output_logits) * one_hot_targets), axis=2) sent_ppx = tf.reduc...
class LifelongSAGE(SAGE): def __init__(self, args, feat_len, num_class, k=1): super().__init__(feat_len, num_class) self.args = args self.register_buffer('adj', torch.zeros(1, feat_len, feat_len)) self.register_buffer('inputs', torch.Tensor(0, 1, feat_len)) self.register_buff...
class Job(): def __init__(self, func, args, kwds, apply_result): self._func = func self._args = args self._kwds = kwds self._result = apply_result def __call__(self): try: result = self._func(*self._args, **self._kwds) except: self._result....
def main(): parser = argparse.ArgumentParser() parser.add_argument('-d', '--dataset', type=str, default='~/t7/ScanNet') parser.add_argument('-v', '--video', type=str, default='scene0208_00') parser.add_argument('--mode', type=str, default='validation') args = parser.parse_args() git_repo = Path(...
def build_inference_based_loaders(cfg: CfgNode, model: torch.nn.Module) -> Tuple[(List[InferenceBasedLoader], List[float])]: loaders = [] ratios = [] embedder = build_densepose_embedder(cfg).to(device=model.device) for dataset_spec in cfg.BOOTSTRAP_DATASETS: dataset_cfg = get_bootstrap_dataset_c...
class Record(): def __init__(self, field_pairs, parameters): assert (len(field_pairs) != 0) self.field_pairs_ = {pair.name: pair for pair in field_pairs} self.first_content_ = field_pairs[0].content self.parameters_ = parameters self.set_id(Ref(0)) def field(self, name): ...
class ListForm(ListMeta[Form], Form): _content: Form def __init__(self, starts, stops, content, *, parameters=None, form_key=None): if (not isinstance(starts, str)): raise TypeError("{} 'starts' must be of type str, not {}".format(type(self).__name__, repr(starts))) if (not isinstanc...
def write_augmented_dataset(input_conllu, output_conllu, augment_function): random.seed(1234) sents = read_sentences_from_conllu(input_conllu) new_sents = augment_function(sents) write_sentences_to_conllu(output_conllu, new_sents)
.hypothesis_nested def test_is_valid_query_strategy(): strategy = st.sampled_from([{'key': '1'}, {'key': '\udcff'}]).filter(is_valid_query) (strategy) (max_examples=10) def test(value): assert (value == {'key': '1'}) test()
class TestSuiteChromosomeComputation(ChromosomeComputation, metaclass=abc.ABCMeta): def _run_test_suite_chromosome(self, individual) -> list[ExecutionResult]: results: list[ExecutionResult] = [] for test_case_chromosome in individual.test_case_chromosomes: if (test_case_chromosome.change...
def hiddens(layer, hidden_sizes, hidden_func=nonlin.relu, hidden_keep_prob=1.0): layer_shape = nn.get_sizes(layer) input_size = layer_shape.pop() weights = [] for (i, hidden_size) in enumerate(hidden_sizes): weights.append(tf.get_variable(('Weights-%d' % i), shape=[input_size, hidden_size])) ...
def convert_transfo_xl_checkpoint_to_pytorch(tf_checkpoint_path, transfo_xl_config_file, pytorch_dump_folder_path, transfo_xl_dataset_file): if transfo_xl_dataset_file: with open(transfo_xl_dataset_file, 'rb') as fp: corpus = pickle.load(fp, encoding='latin1') pytorch_vocab_dump_path = (...
def compute_lnsr(real, adve, norm_L2=True): real = real.reshape(real.shape[0], (- 1)) adve = adve.reshape(adve.shape[0], (- 1)) l2 = np.linalg.norm((real - adve), ord=2) if norm_L2: l2 /= np.linalg.norm(real, ord=2) return l2
class ClassicalWeylSubgroup(WeylGroup_gens): _method def cartan_type(self): return self.domain().cartan_type().classical() def simple_reflections(self): return Family({i: self.from_morphism(self.domain().simple_reflection(i)) for i in self.index_set()}) def __repr__(self): domain...
def train_index(data, quantizer_path, trained_index_path, fine_quant='SQ8', cuda=False): quantizer = faiss.read_index(quantizer_path) if (fine_quant == 'SQ8'): trained_index = faiss.IndexIVFScalarQuantizer(quantizer, quantizer.d, quantizer.ntotal, faiss.METRIC_L2) elif fine_quant.startswith('PQ'): ...
class QuiverMutationTypeFactory(SageObject): def __call__(self, *args): if (len(args) == 1): data = args[0] else: data = args if isinstance(data, QuiverMutationType_Irreducible): return data elif isinstance(data, QuiverMutationType_Reducible): ...
def constant_symbols(sdfg: SDFG) -> Set[str]: interstate_symbols = {k for e in sdfg.edges() for k in e.data.assignments.keys()} return (set(sdfg.symbols) - interstate_symbols)
class TensorWrapper(object): def __init__(self, **kwargs): self.add_attributes(**kwargs) def add_attributes(self, **kwargs): for (name, possible_attr) in kwargs.items(): if (possible_attr is None): continue elif (_is_tensor_like(possible_attr) or _is_strin...
class GenerationMultimodalAdapter(InContextLearningMultimodalAdapter): def generate_requests(self, eval_instance: Instance, train_trial_index: int, training_instances: List[Instance]) -> List[RequestState]: prompt: MultimodalPrompt = self.construct_prompt(training_instances, eval_instance, include_output=Fa...
def stdout_to_string(s): return ecl_eval(('(with-output-to-string (*standard-output*)\n (maxima-eval #$%s$))' % s)).python()[1:(- 1)]
def _getencoder(mode, encoder_name, args, extra=()): if (args is None): args = () elif (not isinstance(args, tuple)): args = (args,) try: encoder = ENCODERS[encoder_name] except KeyError: pass else: return encoder(mode, *(args + extra)) try: encode...
.parametrize('x', [0.1, 3]) .parametrize('allclose', [test_utils.allclose, (lambda x, y: (x == test_utils.approx(y)))]) _utils.test() def test_allclose_rel_reordered2(x, allclose): rel = test_utils.get_rel_eps() assert (not allclose((x + ((x * rel) * 3.0)), x)) assert (not allclose((x + ((x * rel) * 1.2)), ...
class EmpiricalALPComputer(): def __init__(self, task_size, max_size=None, buffer_size=500): self.alp_knn = BufferedDataset(1, task_size, buffer_size=buffer_size, lateness=0, max_size=max_size) def compute_alp(self, task, reward): alp = 0 if (len(self.alp_knn) > 5): (dist, id...
class CloudpickleWrapper(): def __init__(self, x): self.x = x def __getstate__(self): import cloudpickle return cloudpickle.dumps(self.x) def __setstate__(self, ob): import pickle self.x = pickle.loads(ob)
_converter_regitstry('sPorD') def sPorD_converter(context: 'BM1688Context', reg: sPorD_reg): (n, c, h, w) = (reg[f'res0_{d}'] for d in 'nchw') opd0 = dict(address=reg.opd0_addr, dtype=(reg.opt_opd0_prec, reg.opt_opd0_sign), shape=(n, c, reg.opd0_h, reg.opd0_w), layout=Layout.alignEU) res0 = dict(address=reg...
def set_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
def load_syn(): with open('{}/smallworld.pkl'.format(dirname), 'rb') as file: graphs = pickle.load(file) for graph in graphs: print(nx.average_clustering(graph), nx.average_shortest_path_length(graph))
class Model(object): def __init__(self, mode): self.mode = mode self._build_model() def add_internal_summaries(self): pass def _stride_arr(self, stride): return [1, stride, stride, 1] def _build_model(self): assert ((self.mode == 'train') or (self.mode == 'eval'))...
class WedgeOfSimplicialSets_finite(WedgeOfSimplicialSets, PushoutOfSimplicialSets_finite): def __init__(self, factors=None): if (not factors): PushoutOfSimplicialSets_finite.__init__(self, [Point().identity()]) else: if any(((not space.is_pointed()) for space in factors)): ...
def signed_distance_between_cartesian_angles(a0, a1): distance = (a1 - a0) if (distance < 0): distance += (2 * np.pi) return distance
def test_keras_ensemble_network_raises_on_incorrect_tensor_spec() -> None: with pytest.raises(ValueError): _DummyKerasEnsembleNetwork([1], tf.TensorSpec(shape=(1,), dtype=tf.float32), tf.keras.losses.MeanSquaredError()) with pytest.raises(ValueError): _DummyKerasEnsembleNetwork(tf.TensorSpec(sha...
def eval(args): e_common = E_common(args.sep, int((args.resize / 64))) e_separate_A = E_separate_A(args.sep, int((args.resize / 64))) e_separate_B = E_separate_B(args.sep, int((args.resize / 64))) decoder = Decoder(int((args.resize / 64))) if torch.cuda.is_available(): e_common = e_common.cu...
def bilinear_classifier_nary(inputs1, inputs2, n_classes, keep_prob, add_bias1=True, add_bias2=True): input_shape1 = tf.shape(inputs1) input_shape2 = tf.shape(inputs2) batch_size1 = input_shape1[0] batch_size2 = input_shape2[0] bucket_size1 = input_shape1[1] bucket_size2 = input_shape2[1] in...
class Tanh(Module): def updateOutput(self, input): self._backend.Tanh_updateOutput(self._backend.library_state, input, self.output) return self.output def updateGradInput(self, input, gradOutput): self._backend.Tanh_updateGradInput(self._backend.library_state, gradOutput, self.gradInput,...
def cli_main(parser, args): global return_value return_value = False if ('func' not in args): parser.print_help(sys.stderr) sys.exit((- 1)) if args.mpi: from nnabla.utils.communicator_util import create_communicator comm = create_communicator() try: re...
class SentenceBleuScorer(Scorer): def __init__(self, argument_string): Scorer.__init__(self, argument_string) if (not ('n' in self._arguments.keys())): self._arguments['n'] = 4 def set_reference(self, reference_tokens): self._reference = SentenceBleuReference(reference_tokens...
def slerp(z1, z2, t): omega = tf.math.acos((tf.reduce_sum((z1 * z2)) / (tf.norm(z1) * tf.norm(z2)))) a = (tf.sin(((1 - t) * omega)) / tf.sin(omega)) b = (tf.sin((t * omega)) / tf.sin(omega)) return ((a * z1) + (b * z2))
def _is_cur_v_passive(v): for tok in v.children: if (tok.dep_ == 'auxpass'): return True return False
(resources={'machine': 1}) class RayBenchmarkWorker(): def __init__(self, notification_address, world_size, world_rank, object_size): self.notification_address = notification_address self.notification_port = 7777 self.world_size = world_size self.world_rank = world_rank self....
def single_ellipsis_index(names, fn_name): ellipsis_indices = [i for (i, name) in enumerate(names) if is_ellipsis(name)] if (len(ellipsis_indices) >= 2): raise RuntimeError("{}: More than one Ellipsis ('...') found in names ({}). This function supports up to one Ellipsis.".format(fn_name, names)) if...
def set_location_header(request): target = request.args.get('target') response = HttpResponse('') response.headers['Location'] = target return response
def check_modules(): global dpdk_drivers mods = [{'Name': driver, 'Found': False} for driver in dpdk_drivers] for mod in mods: if module_is_loaded(mod['Name']): mod['Found'] = True if ((True not in [mod['Found'] for mod in mods]) and (b_flag is not None)): print('Warning: no ...
def test(): W.set(120) A = dace.ndarray([W]) stats = dace.ndarray([2]) A[:] = np.random.normal(3.0, 5.0, W.get()) stats[:] = 0.0 multi_output_scope(A, stats, W=W) mean = (stats[0] / W.get()) variance = ((stats[1] / W.get()) - (mean * mean)) print(('Mean: %f, Variance: %f' % (mean, va...
class Newpipe(StableDiffusionPipeline): def _encode_prompt(self, *args, **kwargs): embedding = super()._encode_prompt(*args, **kwargs) return (embedding + (self.noiselam * torch.randn_like(embedding)))
def scrape_all_channels(in_fp, out_fp, aws_access_key_id, aws_secret_access_key): if os.path.exists(out_fp): already_scraped = set([l.split('\t')[0] for l in open(out_fp)]) of = open(out_fp, 'a') print('ALREADY SCRAPED:', len(already_scraped)) else: already_scraped = set([]) ...
class TestTempitaUtilityLoader(TestUtilityLoader): expected_tempita = (TestUtilityLoader.expected[0].replace('{{loader}}', 'Loader'), TestUtilityLoader.expected[1].replace('{{loader}}', 'Loader')) required_tempita = (TestUtilityLoader.required[0].replace('{{loader}}', 'Loader'), TestUtilityLoader.required[1].re...
class Histogram(object): def __init__(self, bucket_limits=None): if (bucket_limits is None): bucket_limits = default_buckets() self.bucket_limits = bucket_limits self.clear() def clear(self): self.min = self.bucket_limits[(- 1)] self.max = self.bucket_limits[0...
def GetShellCommandOutput(cmd): return gmock_test_utils.Subprocess(cmd, capture_stderr=False).output
def calc_ping_slots(dev_addr, ping_nb, beacon_ts=None, gps=True): if (beacon_ts is None): beacon_ts = next_beacon_ts(gps=True) beacon_reserved = 2.12 slot_len = 0.03 ping_period = int(((2 ** 12) / ping_nb)) beacon_ts_raw = [((beacon_ts >> s) & 255) for s in [24, 16, 8, 0]] key = [0 for _...
def _expand_globals(config): _ensure_cfg_read() if config.has_section('globals'): globals = config.items('globals') else: globals = tuple() sections = config.sections() for section in sections: if (section == 'globals'): continue for (option, value) in glo...
def init_logs(opt): log_dir = './explogs{}'.format(opt.exp_id) if (not os.path.exists(log_dir)): os.mkdir(log_dir) if opt.istrain: img_logs = os.path.join(log_dir, 'train') else: img_logs = os.path.join(log_dir, 'eval') weight_logs = os.path.join(log_dir, 'weights') if (n...
def has_dspec(dname, given_dnames): clean_dname = ''.join((i for i in dname if (not i.isdigit()))) return (clean_dname in given_dnames)
def get_trainer_and_epoch_itr(epoch, epoch_size, num_updates, iterations_in_epoch): tokens = torch.LongTensor(list(range(epoch_size))) tokens_ds = data.TokenBlockDataset(tokens, sizes=[len(tokens)], block_size=1, pad=0, eos=1, include_targets=False) trainer = mock_trainer(epoch, num_updates, iterations_in_e...
class SmartPointerTransformation(typehandlers.TypeTransformation): def __init__(self): super(SmartPointerTransformation, self).__init__() self.rx = re.compile('(ns3::|::ns3::|)Ptr<([^>]+)>\\s*$') print('{0!r}'.format(self), file=sys.stderr) def _get_untransformed_type_traits(self, name):...
class Vocab(object): def __init__(self, counter: Counter, max_size=None, min_freq=1, specials=('<unk>', '<pad>'), specials_first=True): self.freqs = counter counter = counter.copy() min_freq = max(min_freq, 1) itos = [] if specials_first: itos = list(specials) ...
class ValueListVar(TemplateVar): def __init__(self, values, *args, **kwargs): self.values = values return super().__init__(*args, **kwargs) def __len__(self): return len(self.values) def __getitem__(self, index): return self.values[index] def __iter__(self): (yiel...