code
stringlengths
281
23.7M
class DictionaryParsingTests(unittest.TestCase): simple_dict_values = [('Test-String', 1, 'string'), ('Test-Octets', 2, 'octets'), ('Test-Integer', 3, 'integer'), ('Test-Ip-Address', 4, 'ipaddr'), ('Test-Ipv6-Address', 5, 'ipv6addr'), ('Test-If-Id', 6, 'ifid'), ('Test-Date', 7, 'date'), ('Test-Abinary', 8, 'abinary...
def do_train(cfg, model, resume=False): model = check_if_freeze_model(model, cfg) model.train() if cfg.SOLVER.USE_CUSTOM_SOLVER: optimizer = build_custom_optimizer(cfg, model) else: assert (cfg.SOLVER.OPTIMIZER == 'SGD') assert (cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE != 'full_model'...
def test_convoluted_quantities_units(*args, **kwargs): from radis.test.utils import getTestFile s = load_spec(getTestFile('CO_Tgas1500K_mole_fraction0.5.spec'), binary=True) s.update(verbose=False) assert (s.units['radiance_noslit'] == 'mW/cm2/sr/nm') assert (s.units['transmittance_noslit'] == '') ...
class TestLinkpred(): def teardown_method(self): smokesignal.clear_all() def config_file(self, training=False, test=False, **kwargs): config = {'predictors': ['Random'], 'label': 'testing'} for (var, name, fname, data) in ((training, 'training', 'foo.net', b'*Vertices 3\n1 A\n2 B\n3 C\n*...
() ('--config-name', '-cn', required=True, type=str) ('--config-dir', '-cd', default=None, type=str) ('--seeds', '-s', default='42,43,44', type=str) ('--monitor_key', '-k', multiple=True, default=['test/mean_score']) ('--ray_address', '-ra', default='auto') ('--num_cpus', '-nc', default=7, type=float) ('--num_gpus', '-...
def generate_latin_hypercube_points(num_points, domain_bounds): if (num_points == 0): return numpy.array([]) points = numpy.zeros((num_points, len(domain_bounds)), dtype=numpy.float64) for (i, interval) in enumerate(domain_bounds): subcube_edge_length = old_div(interval.length, float(num_poi...
_jit(nogil=True) def _ld_matrix_jit(x: ArrayLike, scores: ArrayLike, chunk_window_starts: ArrayLike, chunk_window_stops: ArrayLike, abs_chunk_start: int, chunk_max_window_start: int, index_dtype: DType, value_dtype: DType, threshold: float) -> List[Any]: rows = list() no_threshold = np.isnan(threshold) for ...
def lookup_secscan_notification_severities(repository_id): try: repo = Repository.get(id=repository_id) except Repository.DoesNotExist: return None event_kind = ExternalNotificationEvent.get(name='vulnerability_found') for event in RepositoryNotification.select().where((RepositoryNotific...
class Load_From_URL_To_File_TestCase(Load_From_URL_Test): def setUp(self): super(Load_From_URL_To_File_TestCase, self).setUp() (handle, self._target_path) = tempfile.mkstemp(prefix='testfile', text=True) os.close(handle) def runTest(self): target_path = load.load_to_file(self._ur...
def setup_handlers(web_app): host_pattern = '.*$' base_url = web_app.settings['base_url'] handlers = [] if (apps.gpu.ngpus > 0): route_pattern_gpu_util = url_path_join(base_url, URL_PATH, 'gpu_utilization') route_pattern_gpu_usage = url_path_join(base_url, URL_PATH, 'gpu_usage') ...
def main(data_dir, client, c, config): benchmark(read_tables, config, c) query_1 = '\n SELECT i_item_sk,\n CAST(i_category_id AS TINYINT) AS i_category_id\n FROM item\n ' item_df = c.sql(query_1) item_df = item_df.persist() wait(item_df) c.create_table('item_df', item...
('/json/load_config', endpoint='load_config') _required('SETTINGS') def load_config(): category = flask.request.args.get('category') section = flask.request.args.get('section') if ((category not in ('core', 'plugin')) or (not section)): return (jsonify(False), 500) conf = None api = flask.cu...
(simple_typed_classes(defaults=True)) def test_omit_default_roundtrip(cl_and_vals): converter = Converter(omit_if_default=True) (cl, vals, kwargs) = cl_and_vals class C(): a: int = 1 b: cl = Factory((lambda : cl(*vals, **kwargs))) inst = C() unstructured = converter.unstructure(inst)...
def get_contents(filename): documents = [] with bz2.open(filename, mode='rt') as f: for line in f: doc = json.loads(line) doc = preprocess_sentences(doc) if (not doc): continue documents.append((doc['title'], serialize_object(doc['sentences...
def build_trainer(args, device_id, model, optim, tokenizer): grad_accum_count = args.accum_count n_gpu = args.world_size if (device_id >= 0): gpu_rank = int(args.gpu_ranks[device_id]) else: gpu_rank = 0 n_gpu = 0 print(('gpu_rank %d' % gpu_rank)) tensorboard_log_dir = arg...
class NMTModel(nn.Module): def __init__(self, encoder, decoder): super(NMTModel, self).__init__() self.encoder = encoder self.decoder = decoder def forward(self, src, seg, speaker, adj_coo, edge_types, rels, tgt, lengths, bptt=False): tgt = tgt[:(- 1)] (enc_state, memory_...
.script def _update(input: torch.Tensor, target: torch.Tensor, sample_weight: Optional[torch.Tensor]) -> Tuple[(torch.Tensor, torch.Tensor)]: squared_error = torch.square((target - input)) if (sample_weight is None): sum_squared_error = squared_error.sum(dim=0) sum_weight = torch.tensor(target.s...
def test_get_function_call_str(): class TestObject(): def __str__(self): raise NotImplementedError() def __repr__(self): return 'test' def test_function(): pass function_str_kv = qcore.inspection.get_function_call_str(test_function, (1, 2, 3), {'k': 'v'}) ...
def test__torque_driven_ocp__minimize_segment_velocity(): from bioptim.examples.torque_driven_ocp import example_minimize_segment_velocity as ocp_module bioptim_folder = os.path.dirname(ocp_module.__file__) ocp_module.prepare_ocp(biorbd_model_path=(bioptim_folder + '/models/triple_pendulum.bioMod'), n_shoot...
class QUDevMonitorObserverMixin(MonitorObserverMixin): def _setup_notifier(self, monitor, notifier_class): MonitorObserverMixin._setup_notifier(self, monitor, notifier_class) self._action_signal_map = {'add': self.deviceAdded, 'remove': self.deviceRemoved, 'change': self.deviceChanged, 'move': self....
def get_assign_value(node): try: targets = node.targets except AttributeError: targets = [node.target] if (len(targets) == 1): target = targets[0] if isinstance(target, astroid.nodes.AssignName): name = target.name elif isinstance(target, astroid.nodes.Ass...
.parametrize('prefer_grpc', [False, True]) def test_record_upload(prefer_grpc): records = (Record(id=idx, vector=np.random.rand(DIM).tolist(), payload=one_random_payload_please(idx)) for idx in range(NUM_VECTORS)) client = QdrantClient(prefer_grpc=prefer_grpc, timeout=TIMEOUT) client.recreate_collection(col...
class BehavioralRTLIRTypeCheckVisitorL3(BehavioralRTLIRTypeCheckVisitorL2): def __init__(s, component, freevars, accessed, tmpvars, rtlir_getter): super().__init__(component, freevars, accessed, tmpvars, rtlir_getter) s.type_expect['Attribute'] = (('value', (rt.Component, rt.Signal), 'the base of an...
def mkl_spmv(A, x): (m, _) = A.shape data = A.data.ctypes.data_as(ndpointer(np.complex128, ndim=1, flags='C')) indptr = A.indptr.ctypes.data_as(POINTER(c_int)) indices = A.indices.ctypes.data_as(POINTER(c_int)) if (x.ndim == 1): y = np.empty(m, dtype=np.complex128, order='C') elif ((x.nd...
def convert_examples_to_features(examples: List[InputExample], label_list: List[str], max_length: int, tokenizer: PreTrainedTokenizer) -> List[InputFeatures]: label_map = {label: i for (i, label) in enumerate(label_list)} features = [] for (ex_index, example) in tqdm.tqdm(enumerate(examples), desc='convert ...
def _format_perf_breakdown(perf: Perf) -> str: breakdown = [perf.fwd_compute, perf.fwd_comms, perf.bwd_compute, perf.bwd_comms] breakdown_string = ','.join([(str(round(num)) if (num >= 1) else round_to_one_sigfig(num)) for num in breakdown]) return f'{str(round(perf.total, 3))} ({breakdown_string})'
(Grant) class GrantAdmin(ExportMixin, admin.ModelAdmin): change_list_template = 'admin/grants/grant/change_list.html' speaker_ids = [] resource_class = GrantResource form = GrantAdminForm list_display = ('user_display_name', 'country', 'is_speaker', 'conference', 'status', 'approved_type', 'ticket_a...
class PdfDocument(pdfium_i.AutoCloseable): def __init__(self, input, password=None, autoclose=False): if isinstance(input, str): input = Path(input) if isinstance(input, Path): input = input.expanduser().resolve() if (not input.is_file()): raise Fi...
def rescaleData(data, scale, offset, dtype, clip): data_out = np.empty_like(data, dtype=dtype) key = (data.dtype.name, data_out.dtype.name) func = rescale_functions.get(key) if (func is None): func = numba.guvectorize([f'{key[0]}[:],f8,f8,f8,f8,{key[1]}[:]'], '(n),(),(),(),()->(n)', nopython=Tru...
class DiscriminatorBlock(chainer.Chain): def __init__(self, in_channels, out_channels, hidden_channels=None, ksize=3, pad=1, activation=F.relu, downsample=False, sn=True): super(DiscriminatorBlock, self).__init__() initializer = chainer.initializers.GlorotUniform(np.sqrt(2)) initializer_sc =...
_commands.command(name='cluster-undeploy') ('--namespace', '-n', default='default', help='Kubernetes namespace [default]') ('--instance-name', default='reana', help='REANA instance name') def cluster_undeploy(namespace, instance_name): helm_releases = run_command(f'helm ls --short -n {namespace}', 'reana', return_o...
class CondenseLinear(nn.Module): def __init__(self, in_features, out_features, drop_rate=0.5): super(CondenseLinear, self).__init__() drop_in_features = int((in_features * drop_rate)) self.linear = nn.Linear(in_features=drop_in_features, out_features=out_features) self.register_buffe...
def get_context_with_bottleneck_to_question_model(rnn_dim: int, q2c: bool, res_rnn: bool, res_self_att: bool): recurrent_layer = CudnnGru(rnn_dim, w_init=TruncatedNormal(stddev=0.05)) answer_encoder = BinaryAnswerEncoder() res_model = get_res_fc_seq_fc(model_rnn_dim=rnn_dim, rnn=res_rnn, self_att=res_self_a...
def main(args): utils.init_distributed_mode(args) os.makedirs(args.output_dir, exist_ok=True) os.environ['output_dir'] = args.output_dir logger = setup_logger(output=os.path.join(args.output_dir, 'info.txt'), distributed_rank=args.rank, color=False, name='DAB-DETR') logger.info('git:\n {}\n'.format...
_handler('resource') def qute_resource(url: QUrl) -> _HandlerRet: path = url.path().lstrip('/') mimetype = utils.guess_mimetype(path, fallback=True) try: data = resources.read_file_binary(path) except FileNotFoundError as e: raise NotFoundError(str(e)) return (mimetype, data)
def preprocess(image): (w, h) = image.size (w, h) = map((lambda x: (x - (x % 32))), (w, h)) image = image.resize((w, h), resample=PIL_INTERPOLATION['lanczos']) image = (np.array(image).astype(np.float32) / 255.0) image = image[None].transpose(0, 3, 1, 2) image = torch.from_numpy(image) retur...
class _ConstantCumulativeRiskMetric(object): def __init__(self, field, value): self._field = field self._value = value def end_of_bar(self, packet, *args): packet['cumulative_risk_metrics'][self._field] = self._value def end_of_session(self, packet, *args): packet['cumulative...
def test_cyclonedx_fix(monkeypatch, vuln_data, fix_data): import pip_audit._format.cyclonedx as cyclonedx logger = pretend.stub(warning=pretend.call_recorder((lambda s: None))) monkeypatch.setattr(cyclonedx, 'logger', logger) formatter = CycloneDxFormat(inner_format=CycloneDxFormat.InnerFormat.Json) ...
def createCaseFromTemplate(output_path, source_path, backup_path=None): if (backup_path and os.path.isdir(output_path)): shutil.move(output_path, backup_path) if os.path.isdir(output_path): shutil.rmtree(output_path) os.makedirs(output_path) if (source_path.find('tutorials') >= 0): ...
class Effect1590(BaseEffect): type = 'passive' def handler(fit, container, context, projectionRange, **kwargs): level = (container.level if ('skill' in context) else 1) penalize = (False if (('skill' in context) or ('implant' in context) or ('booster' in context)) else True) fit.modules....
class AutoQuant(): def __init__(self, session: tf.compat.v1.Session, starting_op_names: List[str], output_op_names: List[str], dataset: tf.compat.v1.data.Dataset, eval_callback: Callable[([tf.compat.v1.Session], float)], param_bw: int=8, output_bw: int=8, quant_scheme: QuantScheme=QuantScheme.post_training_tf_enhan...
.parametrize('driver', [pytest.param('energy', id='energy'), pytest.param('gradient', id='gradient'), pytest.param('hessian', id='hessian')]) def test_full_run(driver, tmpdir, acetone): if (not GaussianHarness.found()): pytest.skip('Gaussian 09/16 not available test skipped.') with tmpdir.as_cwd(): ...
def _wil_update(input: Union[(str, List[str])], target: Union[(str, List[str])]) -> Tuple[(torch.Tensor, torch.Tensor, torch.Tensor)]: if isinstance(input, str): input = [input] if isinstance(target, str): target = [target] assert (len(input) == len(target)), f'Arguments must contain the sam...
def test_direct_junction_offsets_suc_pre_2_right(direct_junction_right_lane_fixture): (main_road, small_road, junction_creator) = direct_junction_right_lane_fixture main_road.add_successor(xodr.ElementType.junction, junction_creator.id) small_road.add_predecessor(xodr.ElementType.junction, junction_creator....
class LOSArrow(pg.GraphicsWidget, pg.GraphicsWidgetAnchor): def __init__(self, model): pg.GraphicsWidget.__init__(self) pg.GraphicsWidgetAnchor.__init__(self) self.model = model self.arrow = pg.ArrowItem(parent=self, angle=0.0, brush=(0, 0, 0, 180), pen=(255, 255, 255), pxMode=True) ...
class DetectionBlock(nn.Module): def __init__(self, in_channels, out_channels, conv_cfg=None, norm_cfg=dict(type='BN', requires_grad=True), act_cfg=dict(type='LeakyReLU', negative_slope=0.1)): super(DetectionBlock, self).__init__() double_out_channels = (out_channels * 2) cfg = dict(conv_cfg...
.parametrize('ds_order, lifted, dist_op, dist_params, size, rtol', [(('x',), True, normal, (np.array((- 10.0), dtype=np.float64), np.array(1e-06, dtype=np.float64)), (), 1e-07), ((0, 1, 2), True, normal, (np.array(0).astype(config.floatX), np.array(1e-06).astype(config.floatX)), (2, 1, 2), 0.001)]) def test_Dimshuffle_...
def test_cache_clear_all(tester: ApplicationTester, repository_one: str, repository_cache_dir: Path, cache: FileCache[T]) -> None: exit_code = tester.execute(f'cache clear {repository_one} --all', inputs='yes') repository_one_dir = (repository_cache_dir / repository_one) assert (exit_code == 0) assert (...
class PipeQueue1RTL(Component): def construct(s, Type): s.enq = RecvIfcRTL(Type) s.deq = SendIfcRTL(Type) s.buffer = m = RegEn(Type) m.en //= s.enq.en m.in_ //= s.enq.msg m.out //= s.deq.msg s.full = Reg(Bits1) def up_pipeq_use_deq_rdy(): s...
class TestDocumentWithoutRequest(TestDocumentBase): def test_slot_behaviour(self, document): for attr in document.__slots__: assert (getattr(document, attr, 'err') != 'err'), f"got extra slot '{attr}'" assert (len(mro_slots(document)) == len(set(mro_slots(document)))), 'duplicate slot' ...
class CoupledInputForgetGateLSTMCell(rnn_cell_impl.RNNCell): def __init__(self, num_units, use_peepholes=False, initializer=None, num_proj=None, proj_clip=None, num_unit_shards=1, num_proj_shards=1, forget_bias=1.0, state_is_tuple=True, activation=math_ops.tanh, reuse=None): super(CoupledInputForgetGateLSTM...
def test_wind(): w = OSC.Wind(0, 1) w2 = OSC.Wind(0, 1) w3 = OSC.Wind(1, 1) assert (w == w2) assert (w != w3) prettyprint(w) w4 = OSC.Wind.parse(w.get_element()) assert (w == w4) assert (version_validation('Wind', w, 0) == ValidationResponse.OSC_VERSION) assert (version_validatio...
def tracing_client_from_config(raw_config: config.RawConfig, log_if_unconfigured: bool=True) -> TracingClient: cfg = config.parse_config(raw_config, {'tracing': {'service_name': config.String, 'endpoint': config.Optional(config.Endpoint), 'queue_name': config.Optional(config.String), 'max_span_queue_size': config.O...
def add_tune_args(parser): group = parser.add_argument_group('Tune parameter parser.') group.add_argument('--n-grid', default=6, type=int, metavar='N', help='how many grid added to tune for each weight.') group.add_argument('--weight-lower-bound', default=0.0, type=float, help='lower bound for each weight.'...
def test_report_disconnect(mock_emit_session_update, solo_two_world_session): log = MagicMock() session_dict = {'user-id': 1234, 'worlds': [1]} a1 = database.WorldUserAssociation.get_by_instances(world=1, user=1234) a1.connection_state = GameConnectionStatus.InGame a1.save() world_api.report_dis...
def _parse_requirement_details(tokenizer: Tokenizer) -> Tuple[(str, str, Optional[MarkerList])]: specifier = '' url = '' marker = None if tokenizer.check('AT'): tokenizer.read() tokenizer.consume('WS') url_start = tokenizer.position url = tokenizer.expect('URL', expected=...
def direct(x_samp, y_samp, x_bl, y_bl, y_data, Rinv, baseline_as_mean=False, **kwargs): (nsamples, nx, ny, x_bl, y_bl, y_data, delta_x, delta_y, innovation) = _preproc(x_samp, y_samp, x_bl, y_bl, y_data, baseline_as_mean) dy = (delta_y np.linalg.pinv(delta_x)) return ((dy.T Rinv) innovation)
def _select_lstm_internal_ops_to_quantize(graph: tf.Graph, internal_ops: List[tf.Operation]) -> Tuple[(List[str], List[int], List[str])]: (curr_module_ops_with_param_names, curr_module_input_indices) = _get_internal_ops_to_quantize_params_for(graph, internal_ops) curr_module_activation_op_names = _get_internal_...
class MuteStream(Scaffold): async def mute_stream(self, chat_id: Union[(int, str)]): if (self._app is None): raise NoMTProtoClientSet() if (not self._is_running): raise ClientNotStarted() chat_id = (await self._resolve_chat_id(chat_id)) try: return...
class DwsConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, bias=False, use_bn=True, bn_eps=1e-05, activation=(lambda : nn.ReLU(inplace=True))): super(DwsConvBlock, self).__init__() self.dw_conv = dwconv_block(in_channels=in_channels, out_ch...
class UniSpeechConfig(PretrainedConfig): model_type = 'unispeech' def __init__(self, vocab_size=32, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout=0.1, activation_dropout=0.1, attention_dropout=0.1, feat_proj_dropout=0.0, feat_quantizer_d...
_tests('rsa_oaep_2048_sha1_mgf1sha1_test.json', 'rsa_oaep_2048_sha224_mgf1sha1_test.json', 'rsa_oaep_2048_sha224_mgf1sha224_test.json', 'rsa_oaep_2048_sha256_mgf1sha1_test.json', 'rsa_oaep_2048_sha256_mgf1sha256_test.json', 'rsa_oaep_2048_sha384_mgf1sha1_test.json', 'rsa_oaep_2048_sha384_mgf1sha384_test.json', 'rsa_oae...
def plot_reward_curves(yss: Iterable[Iterable[np.ndarray]], labels: Iterable[str], bs: int, title: str): (fig, ax) = plt.subplots(1, 1, sharey=True, figsize=(4, 4)) fmt = '-' (y_min, y_max) = (0, 0) for (ys, label) in zip(yss, labels): Y = np.stack(ys) y_mean = Y.mean(axis=0) y_s...
class ImagenetSpecificationTest(tf.test.TestCase): def validate_num_span_images(self, span_leaves, num_span_images): for (node, leaves) in span_leaves.items(): self.assertEqual(num_span_images[node], sum([num_span_images[l] for l in leaves])) def validate_splits(self, splits): train_...
def train_one_epoch(): stat_dict = {} adjust_learning_rate(optimizer, EPOCH_CNT) bnm_scheduler.step() net.train() for (batch_idx, batch_data_label) in enumerate(TRAIN_DATALOADER): for key in batch_data_label: batch_data_label[key] = batch_data_label[key].to(device) optimi...
def postprocess_dataset(dataset: List[DatasetEntry], remove_identical_pairs: bool=True, remove_duplicates: bool=True, add_sampled_pairs: bool=True, max_num_text_b_for_text_a_and_label: int=2, label_smoothing: float=0.2, seed: int=42, explanation=False) -> List[DatasetEntry]: postprocessed_dataset = [] num_text_...
class TransformerEmbedding(nn.Module): def __init__(self, args, embed_tokens): super().__init__() self.dropout = args.dropout embed_dim = embed_tokens.embedding_dim self.padding_idx = embed_tokens.padding_idx self.embed_tokens = embed_tokens self.embed_scale = math.sq...
def cibuildwheel_run(project_path, package_dir='.', env=None, add_env=None, output_dir=None, add_args=None): if (env is None): env = os.environ.copy() env.pop('MACOSX_DEPLOYMENT_TARGET', None) if (add_args is None): add_args = [] if (add_env is not None): env.update(add_env) ...
def calculate_remediations(vulns, db_full): remediations = defaultdict(dict) package_metadata = {} secure_vulns_by_user = set() if (not db_full): return remediations precompute_remediations(remediations, package_metadata, vulns, secure_vulns_by_user) compute_sec_ver(remediations, package...
class AdBaseAdmin(RemoveDeleteMixin, admin.ModelAdmin): readonly_fields = ('date', 'advertisement', 'publisher', 'page_url', 'keywords', 'country', 'browser_family', 'os_family', 'is_mobile', 'is_proxy', 'paid_eligible', 'user_agent', 'ip', 'div_id', 'ad_type_slug', 'client_id', 'modified', 'created') list_disp...
class _TestClassA(torch.nn.Module): def __init__(self, arg1, arg2, arg3=3): super().__init__() self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 assert (arg1 == 1) assert (arg2 == 2) assert (arg3 == 3) def from_config(cls, cfg): args = {'arg1': cf...
def get_xritdecompress_cmd(): cmd = os.environ.get('XRIT_DECOMPRESS_PATH', None) if (not cmd): raise IOError('XRIT_DECOMPRESS_PATH is not defined (complete path to xRITDecompress)') question = 'Did you set the environment variable XRIT_DECOMPRESS_PATH correctly?' if (not os.path.exists(cmd)): ...
class EncoderLayer(nn.Module): def __init__(self, attention, d_model, d_ff=None, dropout=0.1, activation='relu'): super(EncoderLayer, self).__init__() d_ff = (d_ff or (4 * d_model)) self.attention = attention self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=...
def calc_diversity(data_dir, num_samples=5): dir_list = os.listdir(data_dir) dir_list.sort() transform = transforms.Compose([transforms.ToTensor()]) total = len(dir_list) std = 0 for i in tqdm(range(total), total=total, smoothing=0.01): imgs = [] for j in range(num_samples): ...
def make_dataset(pos_pairs, neg_pairs, neg_pairs_asin, pct_dev=0): ds_train = [] ds_dev = [] def _add_to_ds(ds_train, ds_dev, array, label, pct_dev): split = int((len(array) * pct_dev)) for pair in array[:split]: ds_dev.append((*pair, label)) for pair in array[split:]: ...
class unknowns(plugin): def __init__(self, os, maxsize): plugin.__init__(self, os, maxsize, __name__) print(('loaded %s' % __name__)) def preGet(self): pass def postGet(self): pass def check(self, path): import ops.env import os, os.path __in = os....
def compute_faiss_kmeans(dim, num_partitions, kmeans_niters, shared_lists, return_value_queue=None): use_gpu = torch.cuda.is_available() kmeans = faiss.Kmeans(dim, num_partitions, niter=kmeans_niters, gpu=use_gpu, verbose=True, seed=123) sample = shared_lists[0][0] sample = sample.float().numpy() km...
def test_no_install(local_client: QdrantClient=None, collection_name: str='demo_collection', docs: Dict[(str, List[Union[(str, int, Any)]])]=None): if (local_client is None): local_client = QdrantClient(':memory:') if (docs is None): docs = {'documents': ['Qdrant has Langchain integrations', 'Qd...
def test_project__empty(): project = Project() assert (project.admins == []) assert isinstance(project.created_at, datetime) assert (project.location is None) assert (project.project_observation_rules == []) assert (project.search_parameters == []) assert (project.user is None)
def senet154(num_classes=1000, pretrained='imagenet'): model = SENet(SEBottleneck, [3, 8, 36, 3], groups=64, reduction=16, dropout_p=0.2, num_classes=num_classes) if (pretrained is not None): settings = pretrained_settings['senet154'][pretrained] initialize_pretrained_model(model, num_classes, s...
def test_parse_basic_remote_manifest(): manifest = OCIManifest(Bytes.for_string_or_unicode(SAMPLE_REMOTE_MANIFEST)) assert (not manifest.is_manifest_list) assert (manifest.digest == 'sha256:dd18ed87a00474aff683cee7160771e043f1f0eaddbc0678a984a5e') assert (manifest.blob_digests == ['sha256:9834876dcfb05c...
class SegToImageTransforms(TransformsConfig): def __init__(self, opts): super(SegToImageTransforms, self).__init__(opts) def get_transforms(self): transforms_dict = {'transform_gt_train': transforms.Compose([transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0....
def deprecated_alias(alias, func): (func) def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn('Call to deprecated function alias {}, use {} instead.'.format(alias, func.__name__), category=DeprecationWarning, stacklevel=2) warnings.simplefilte...
class BoolectorOptions(SolverOptions): def __init__(self, **base_options): SolverOptions.__init__(self, **base_options) if (self.random_seed is not None): raise PysmtValueError('BTOR Does not support Random Seed setting.') self.incrementality = True self.internal_options ...
def do_chopper(params): (ijob, datadir, nfiles, nsamples, tmin, (grouping, mult)) = params sq = squirrel.Squirrel(datadir, persistent='bla') sq.add(os.path.join(datadir, 'data')) ntr = 0 for tr in sq.get_waveforms(uncut=True): ntr += 1 assert (tr.data_len() == nsamples) assert (n...
class CompletionItemKind(): Text = 1 Method = 2 Function = 3 Constructor = 4 Field = 5 Variable = 6 Class = 7 Interface = 8 Module = 9 Property = 10 Unit = 11 Value = 12 Enum = 13 Keyword = 14 Snippet = 15 Color = 16 File = 17 Reference = 18 Fo...
class Effect5306(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Rockets')), 'kineticDamage', ship.getModifiedItemAttr('shipBonusCD1'), skill='Caldari Destroyer', **kwargs)
_vcs_handler('git', 'pieces_from_vcs') def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if (not os.path.exists(os.path.join(root, '.git'))): if verbose: print(('no .git in %s' % root)) raise NotThisMethod('no .git directory') GITS = ['git'] if (sys.pla...
class ModelArguments(): model_name_or_path: Optional[str] = field(default=None, metadata={'help': "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."}) model_type: Optional[str] = field(default=None, metadata={'help': ('If training from scratch, pass a model ty...
_canonicalize _specialize _rewriter([Elemwise]) def local_useless_composite_outputs(fgraph, node): if ((not isinstance(node.op, Elemwise)) or (not isinstance(node.op.scalar_op, ps.Composite))): return comp = node.op.scalar_op used_outputs_idxs = [i for (i, o_extern) in enumerate(node.outputs) if fgr...
def test_attribute(): sAttr = Attribute.getInstance() info = sAttr.getAttributeInfo('maxRange') assert (info.attributeID == 54) assert (type(info.attributeID) is int) assert (info.attributeName == 'maxRange') assert (type(info.attributeName) is str) assert (info.defaultValue == 0.0) asse...
def test_can_handle_nms_with_constant_maxnum(): class ModuleNMS(torch.nn.Module): def forward(self, boxes, scores): return nms(boxes, scores, iou_threshold=0.4, max_num=10) onnx_model = export_nms_module_to_onnx(ModuleNMS) preprocess_onnx_model = preprocess_onnx(onnx_model) for node ...
def test_prepare_sdist(config: Config, config_cache_dir: Path, artifact_cache: ArtifactCache, fixture_dir: FixtureDirGetter, mock_file_downloads: None) -> None: chef = Chef(artifact_cache, EnvManager.get_system_env(), Factory.create_pool(config)) archive = (fixture_dir('distributions') / 'demo-0.1.0.tar.gz').re...
class CoberturaReportSuite(Suite): .skipif((lxml is None), reason='Cannot import lxml. Is it installed?') def test_get_line_rate(self) -> None: assert_equal('1.0', get_line_rate(0, 0)) assert_equal('0.3333', get_line_rate(1, 3)) .skipif((lxml is None), reason='Cannot import lxml. Is it insta...
class TouchExecutor(ActionExecutor): def execute(self, script: Script, state: EnvironmentState, info: ExecutionInfo, char_index, modify=True, in_place=False): current_line = script[0] info.set_current_line(current_line) node = state.get_state_node(current_line.object()) if (node is N...
class F23_TestCase(F18_TestCase): def runTest(self): self.assert_parse(('timezone --utc Europe/Prague --ntpservers=ntp.cesnet.cz,0.fedora.pool.ntp.org,' + '0.fedora.pool.ntp.org,0.fedora.pool.ntp.org,0.fedora.pool.ntp.org'), ('timezone Europe/Prague --isUtc --ntpservers=ntp.cesnet.cz,0.fedora.pool.ntp.org,'...
class Annotation(NamedTuple): area: float image_id: str bbox: BoundingBox category_no: int category_id: str id: Optional[int] = None source: Optional[str] = None confidence: Optional[float] = None is_group_of: Optional[bool] = None is_truncated: Optional[bool] = None is_occlu...
class Color(): __slots__ = ['_val'] def __init__(self, *args): if (len(args) == 1): color = args[0] if isinstance(color, (int, float)): self._set_from_tuple(args) elif isinstance(color, str): self._set_from_str(color) else: ...
class HubertCriterionConfig(FairseqDataclass): pred_masked_weight: float = field(default=1.0, metadata={'help': 'weight for predictive loss for masked frames'}) pred_nomask_weight: float = field(default=0.0, metadata={'help': 'weight for predictive loss for unmasked frames'}) loss_weights: Optional[List[flo...
def U2NETP(input=(None, None, 3), out_ch=1): inp = Input(input) x = Lambda((lambda x: (x / 255)))(inp) x1 = RSU7(x, 16, 64) x = MaxPool2D(2, 2)(x1) x2 = RSU6(x, 16, 64) x = MaxPool2D(2, 2)(x2) x3 = RSU5(x, 16, 64) x = MaxPool2D(2, 2)(x3) x4 = RSU4(x, 16, 64) x = MaxPool2D(2, 2)(x...