sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
3c5e98479bf838ee909bce4c9f2072f7cc3059c3540cb44b6fd7241303f6e2c9
Python
1,220
37
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.nn as nn class LSTMCellWithZoneOut(nn.Module): """ Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations...
0a9a423a4ef2c707d5d5abf02237efd28ebb904c87d7824ef771b7a844e15e95
Python
1,221
37
# encoding: utf-8 """ @author: Jiayang Chen @contact: yjcmydkzgj@gmail.com """ from torch.utils.data.distributed import DistributedSampler from torch.utils.data.sampler import SequentialSampler from torch.utils.data.sampler import RandomSampler def build_sampler(sampler_name, data_source, is_train=True, distributed_...
26ba882984495f6745a7a825b058ee7a97c3e4db58da4b619f934b1022bf4bd9
Python
1,221
38
from __future__ import annotations from typing import TYPE_CHECKING import torch from scvi import REGISTRY_KEYS from scvi.module.base import EmbeddingModuleMixin if TYPE_CHECKING: import numpy as np from anndata import AnnData class EmbeddingMixin: """Mixin class for initializing and using embeddings ...
58def0d1d9c51bae57d86ef1a0932dfebb5613bb130c8995310a6ad88aa58ae3
Python
1,221
41
#!/usr/bin/python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import fileinput import hashlib import sys from multiprocessing import Pool def get_hashes_and_lines(raw_...
ea6e9e1b8a877f0c24754b00bc023548ed7be849605122eae78e80d546fe75e5
Python
1,221
35
import numpy as np class Material: def __init__(self, material_name): """ Material of optical elements and its refractive index. Args: material name: name of the material. So far, we provide PDMS, FUSED_SILICA, VACCUM. """ self.material_name = material_name ...
c81b3fadf4ddf9e0190bd32086fa56e344e2b99fd5dda6d725a74821043929dc
Python
1,222
21
import os import torch from nnunetv2.training.nnUNetTrainer.variants.pathology.nnUNetTrainer_WSD_undefined_dataloader import nnUNetTrainer_WSD_undefined_dataloader class nnUNetTrainer_WSD_bal_nnunet_aug_TIME(nnUNetTrainer_WSD_undefined_dataloader): def __init__(self, plans: dict, configuration: str, fold: int, dat...
deb7967c45c477a7e15f18ba83ffc307a9c6409ecbf10403e888b04645d109e9
Python
1,222
21
import os import torch from nnunetv2.training.nnUNetTrainer.variants.pathology.nnUNetTrainer_WSD_undefined_dataloader import nnUNetTrainer_WSD_undefined_dataloader class nnUNetTrainer_WSD_wei_nnunet_aug_TIME(nnUNetTrainer_WSD_undefined_dataloader): def __init__(self, plans: dict, configuration: str, fold: int, dat...
eb1ff68278ba6bf7807af12ef3f6a3c7632114cbd8334c8ada5e102cfd629673
Python
1,222
33
import jax import jax.numpy as jnp from folx import forward_laplacian, register_function from folx.api import FwdJacobian, FwdLaplArray @jax.jit def custom_logsumexp(log_determinants, sign_determinants): return jax.nn.logsumexp(log_determinants, b=sign_determinants, return_sign=True) def custom_logsumexp_forwar...
5eb8dc25ae7a162df091a8fe3703a39522d49b181906958772c50bd8bbac4815
Python
1,223
42
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """This script prints a list of all the models MDT can find in your home directory.""" import argparse import mdt import mdt.utils from mdt.lib.shell_utils import BasicShellApplication __author__ = 'Robbert Harms' __date__ = "2015-08-18" __maintainer__ = "Robbert Harms" __...
e64ec392a2be1c706afee0eee41cfbe39c2b7fa1dad864c364fbe3be3689cfdc
Python
1,223
40
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
111676582f6b1d93e0e2fca5037209a46eb352108d07cfd17daaf6877ad1fb29
Python
1,224
21
import os import torch from nnunetv2.training.nnUNetTrainer.variants.pathology.nnUNetTrainer_WSD_undefined_dataloader import nnUNetTrainer_WSD_undefined_dataloader class nnUNetTrainer_WSD_wei_i0_nnunet_aug_TIME(nnUNetTrainer_WSD_undefined_dataloader): def __init__(self, plans: dict, configuration: str, fold: int, ...
5b6ac4466d196dd6fc9483032e89a46227a367cad12ea89b04aa5787487f510c
Python
1,224
37
# encoding: utf-8 """ @author: chenjiayang @contact: sychenjiayang@163.com """ from PIL import Image #import torchvision.transforms as T from . import cla_transforms as CT def build_transforms(dataset_type, cfg, is_train=True): if dataset_type == "sequence-classification": transforms = build_transforms_se...
f6c1324b561ea98aebd00ae20bcf183aa67e9072685f37fe447aa7fdf2cbf207
Python
1,224
33
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from dataclasses import dataclass, field from typing import Any @dataclass class Config: # This is for CLI applications that need to reuse a CLI parameter in multiple places # in the config file. The idea is that you use `my_cli params...
1a21f37fdaad6bd6de0e101d8dc8b6945b557fd763c8eb4d5c099055154f343e
Python
1,225
28
import argparse from msi_visual.extract.bruker_tsf_to_numpy import BrukerTsfToNumpy def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--start_mz', type=int, default=300) parser.add_argument('--id', type=str, required=True) parser.add_argument('--end_mz', type=int, default=1...
5cbbb2791a6c02cc90c2fae03d78371d7c84f1cf7e83f7f64bf04078b455818c
Python
1,226
33
"""GO-DAG constants.""" __copyright__ = "Copyright (C) 2010-2019, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" NAMESPACE2NS = { 'biological_process' : 'BP', 'molecular_function' : 'MF', 'cellular_component' : 'CC'} NS2NAMESPACE = { 'BP': 'biological_process', 'MF...
7ebeb9e3b181eddd57b2a0f33d3f1830fefda353fe43ee42df2c75dc09353224
Python
1,226
41
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from fairseq.tasks import register_task from fairseq.tasks.speech_to_text import SpeechToTextTask from fairseq.tasks.translatio...
bb5660926ac740e9444f3b6b8fb7e9171a89149bdca17202830636ccc3d65918
Python
1,228
21
import os import torch from nnunetv2.training.nnUNetTrainer.variants.pathology.nnUNetTrainer_WSD_undefined_dataloader import nnUNetTrainer_WSD_undefined_dataloader class nnUNetTrainer_WSD_wei_nnunet_aug_json(nnUNetTrainer_WSD_undefined_dataloader): def __init__(self, plans: dict, configuration: str, fold: int, dat...
bbfab4535afd72e18482c2379989fcb8ee0f59f153b91e21d9e13c433fef7f19
Python
1,229
32
import torch def broadcast_labels(o, n_broadcast=-1): """Utility for the semi-supervised setting. If y is defined(labelled batch) then one-hot encode the labels (no broadcasting needed) If y is undefined (unlabelled batch) then generate all possible labels (and broadcast other arguments if not None) ...
e8df1d0a6e14c931aa65e88d0759996084233870a582dcbd07a917ce4cc9ed5b
Python
1,229
47
import matplotlib.pyplot as plt import numpy as np # 设置全局字体为新罗马字体 plt.rcParams['font.family'] = 'serif' plt.rcParams['font.serif'] = 'Times New Roman' # 设置全局字体大小 plt.rcParams.update({'font.size': 12}) # Data scenarios = ['Playground', 'City', 'Canyon'] methods = ['SAC+RAE', 'SAC+CFS', 'Our method'] succes...
3cdb51bd3d44fab602b82d0514a5338483b271ccab6613448a791719bc1ff00b
Python
1,230
21
import os import torch from nnunetv2.training.nnUNetTrainer.variants.pathology.nnUNetTrainer_WSD_undefined_dataloader import nnUNetTrainer_WSD_undefined_dataloader class nnUNetTrainer_WSD_wei_i0_nnunet_aug_json(nnUNetTrainer_WSD_undefined_dataloader): def __init__(self, plans: dict, configuration: str, fold: int, ...
4c1c7363b09ae61b105f313b528e7b04a4a2ef5ab5918f05c94945d8bdcc7205
Python
1,230
44
from __future__ import annotations from types import MappingProxyType import pytest from scvi.train._config import TrainerConfig, TrainingPlanConfig, merge_kwargs def test_merge_kwargs_prefers_overrides(): config = TrainingPlanConfig(lr=1e-3, weight_decay=1e-2, loss_kwargs={"foo": "bar"}) overrides = {"lr"...
cf53e995df971cea54d4a0c4771bee302fe329a586aa8861a345700c636e703e
Python
1,230
28
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer class nnUNetTrainerNoMirroring(nnUNetTrainer): def configure_rotation_dummyDA_mirroring_and_inital_patch_size(self): rotation_for_DA, do_dummy_2d_data_aug, initial_patch_size, mirror_axes = \ super().configure_rotation_dum...
28e14ba8203aad41737cf976b70a7f07da5477cd723c47faced72813271bd82d
Python
1,231
34
import torch import numpy as np from torch.utils.data import Dataset import skimage.io as skio class BatchDatasetFromTIFFAndZernike(Dataset): def __init__(self, tif_path, coeff_path, device='cuda'): self.device = device super().__init__() # === Load raw intensity images phase_adde...
29b81a5130ece743b6b325e0b3549a952fa723fb1010ee54038e8e7db651a540
Python
1,231
37
__author__ = 'Robbert Harms' __date__ = "2016-06-25" __maintainer__ = "Robbert Harms" __email__ = "robbert@xkls.nl" class ProtocolIOError(Exception): """Custom exception class for protocol input output errors. This can be raised if a protocol is inconsistent or incomplete. It should not be raised for general...
74587490deeac9cb0b8b26f4c64f890e7dcdfdf5895d4e25682cedb23055baaf
Python
1,231
37
# Do this here to suppress warnings before we import vak import logging import warnings from numba.core.errors import NumbaDeprecationWarning warnings.simplefilter('ignore', category=NumbaDeprecationWarning) import vak from . import constants logger = logging.getLogger(__name__) def run_prep(): """Run ``vak ...
624c28916ae265e85acd9931d25d6b2539fc13b1cbd096b767abbc831a3c1c90
Python
1,232
28
from argschema import ArgSchema, ArgSchemaParser from argschema.schemas import DefaultSchema from argschema.fields import Nested, InputDir, String, Float, Dict, Int from ...common.schemas import EphysParams, Directories class PostprocessingParams(DefaultSchema): within_unit_overlap_window = Float(required=False,...
b486229fa64d8b1cf4a7c91f473c836bc31970746246461d9ddf333571133e00
Python
1,232
21
import os import torch from nnunetv2.training.nnUNetTrainer.variants.pathology.nnUNetTrainer_WSD_undefined_dataloader import nnUNetTrainer_WSD_undefined_dataloader class nnUNetTrainer_WSD_wei_nnunet_aug_json_TIME(nnUNetTrainer_WSD_undefined_dataloader): def __init__(self, plans: dict, configuration: str, fold: int...
8d6067eb59f95bce5392946bdc53c58c68928850717224baf52fdce0add903bf
Python
1,234
21
import os import torch from nnunetv2.training.nnUNetTrainer.variants.pathology.nnUNetTrainer_WSD_undefined_dataloader import nnUNetTrainer_WSD_undefined_dataloader class nnUNetTrainer_WSD_wei_i0_nnunet_aug_json_TIME(nnUNetTrainer_WSD_undefined_dataloader): def __init__(self, plans: dict, configuration: str, fold: ...
52c5caab4426bbb86f3b7d7c9816d3aacd178cc6401acd6b79a956a5dd426f0a
Python
1,235
51
from pathlib import Path import pytest HERE = Path(__file__).parent TEST_DATA_ROOT = HERE.joinpath("..", "data_for_tests") @pytest.fixture def test_data_root(): """Path that points to root of data_for_tests directory""" return TEST_DATA_ROOT SOURCE_TEST_DATA_ROOT = TEST_DATA_ROOT.joinpath("source") @p...
9f6b050eef5592dee7fe4e36779316d69e7c448b363c8564d78edcf323b5d53e
Python
1,235
43
def cli_main(): pl.seed_everything(1234) # ------------ # args # ------------ parser = ArgumentParser() parser.add_argument('--batch_size', default=32, type=int) parser = pl.Trainer.add_argparse_args(parser) parser = LitClassifier.add_model_specific_args(parser) args = parser.parse...
61c03c6b2abb1d996d1f50dee39d2cfe6debafc1656eccdbb3f532ea47eac4b3
Python
1,236
40
import torch from torch.linalg import svdvals def old_topk(similarities, labels, k=5): if k > similarities.shape[0]: k = similarities.shape[0] topsum = 0 for i in range(k): topsum += torch.sum( torch.argsort(similarities, axis=1)[:, -(i + 1)] == labels ) / len(labels) ...
200ec0b3a0f67a1a0d30516cee53f1e9e6b4174897e73ba256d0134941d7311a
Python
1,238
41
import torch from torch.distributions.constraints import Constraint class _Optional(Constraint): def __init__(self, constraint: Constraint): self.constraint = constraint def check(self, value: torch.Tensor) -> torch.Tensor: if value is None: return torch.ones(1, dtype=torch.bool) ...
8fe35807e846e682a12bd382b28dc53bae8aa8d80fda9b0bf4d625c561cfd47a
Python
1,238
52
import numpy as np import pandas as pd import pytest from pgmpy.estimators import MmhcEstimator @pytest.fixture def mmhc_estimator(): data = pd.DataFrame(np.random.randint(0, 2, size=(int(1e5), 3)), columns=list("XYZ")) data["sum"] = data.sum(axis=1) est = MmhcEstimator(data) return est def test_es...
9e42d06ea12b47683e5cf84f4e9ebcd072b70762b009429bb745e15aa27c6bf5
Python
1,238
35
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Layer norm done in fp32 (for fp16 training) """ import torch.nn as nn import torch.nn.functional as F class Fp32InstanceNorm(nn.Instance...
29f84feb2c193e9e9e101be02db7a7c76e09d1631306cbca95a7a693dd3c5331
Python
1,240
49
from importlib.metadata import metadata import pytest import scvi from scvi.hub._url import validate_colab_notebook, validate_url info = metadata("scvi-tools") @pytest.mark.internet def test_validate_homepage_url(): valid = "https://scvi-tools.org/" assert validate_url(valid) invalid = "scvi-tools.org...
e0bce3d81dd3be511bcb9ee1dbfc052a8f4e79eccaa0fa38b5a07c9e9a59d8ba
Python
1,241
40
import torch import torch.nn as nn class ConvMLP(nn.Module): def __init__(self, input_size=256): super(ConvMLP, self).__init__() self.audio_encoder = nn.Sequential( nn.Conv1d(1, 16, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv1d(16, ...
85b2e909eb22143bd28f92950e57ae124f57d43b0f104063636369d21d8388a6
Python
1,242
43
from typing import Union, NamedTuple, Optional from pathlib import Path import torch PathLike = Union[str, Path] class NamedTensorTuple(NamedTuple): def to(self, *args, **kwargs) -> "NamedTensorTuple": return self.__class__( *(tensor.to(*args, **kwargs) for tensor in self) # type: ignore ...
49f2b1c7ca20a33667808d37f336ba428812c64fc7830442b753c05ebc4ee961
Python
1,243
43
import unittest class TestInstalledModules(unittest.TestCase): # GPU dependent library installations: def test_opencv(self): try: import cv2 except ImportError: self.fail('OpenCV not installed') try: _ = cv2.__version__ except Exception as e: ...
c379d225c01ac2e00b0e514ce4c6837f5202587de9289ef0a96bfc0a2a631ea1
Python
1,245
32
import os from pathlib import Path def find_project_root(marker_file_or_dir="setup.py"): """ Finds the project root by searching for a marker file/directory up the directory tree from the current file's location. """ current_path = Path(os.path.abspath(os.path.dirname(__file__))) for parent in ...
19e545ba339df5c977cd87973c95273eafc3bed883bc6d3a3bb82a388d5b1be6
Python
1,246
39
import argparse import webbrowser import neuroglancer import neuroglancer.cli if __name__ == "__main__": ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) viewer = neuroglancer.Viewer() with viewer.tx...
ba45435300a029b73043cf0b5ea59753e908e9f4b6a44fde8a8ff39410684137
Python
1,246
53
import os from fairseq.data.audio import ( AudioTransform, CompositeAudioTransform, import_transforms, register_audio_transform, ) class AudioDatasetTransform(AudioTransform): pass AUDIO_DATASET_TRANSFORM_REGISTRY = {} AUDIO_DATASET_TRANSFORM_CLASS_NAMES = set() def get_audio_dataset_transform...
ebec1387fee6e5d491a9e9b2ede397d726e711f2cc884a08a793d6914fa58e19
Python
1,246
35
from typing import Tuple import numpy as np import loompy from cytograph.species import Species class CellCycleAnnotator: def __init__(self, species: Species) -> None: self.species = species def fit(self, ds: loompy.LoomConnection) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: g1_indices = np.isin(ds.ra.Gene...
10eeebaf11a9ab1b2006906fba6a67e9703b713fabdb9158a1a94215aa7ee853
Python
1,247
29
"""The process-wide CPU embeddings cache must not leak across tests. `base.cpu_embeddings_cache` is module state keyed by base model and document id, and fixtures across the suite reuse small integer pmids for unrelated documents — so on a machine whose `config.toml` enables the cache, one test's entry could be read b...
1c0bd8e74d966cf9418d2cbdb615b4417bd278dbbe425543d88f51d1feb7d78b
Python
1,248
29
from dataclasses import dataclass, field @dataclass class LossData: """Dataclass to store loss values for training, validation, and testing from different loss functions.""" losses_train: dict[str, list[float]] = field(default_factory=dict) losses_val: dict[str, list[float]] = field(default_factory=dict)...
d27d1e01427e32c7dc71c89335f913de75fe0f5a669a31f39efef97af93f206d
Python
1,248
39
import pytest from pymatgen.core import Element from pymatgen.entries.computed_entries import ComputedEntry, EnergyAdjustment from mattergen.evaluation.reference.correction_schemes import TRI110Compatibility2024 def test_tri_pbe_correction_uses_uncorrected_energy() -> None: entry = ComputedEntry( composi...
206697b88fb7eb088f8aded04db9c9518ab8668849c0352e925dc08b512e4fdb
Python
1,249
39
import os import pandas as pd def get_git_directory(config): if config.get("GIT_DIR") is not None: git_dir = config["GIT_DIR"] else: # Should change the SpaceHack directory. git_dir = os.getenv("GIT_DIR", "/home/ubuntu/workspace/SpaceHack2023") if not git_dir.endswith("/"): ...
364ce654af07329c224f8316f444eb79f63cba6fd5a0cb42f7b992d7a37bbde6
Python
1,250
46
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
57e055a1b96c9a42a08f0006408914e1eda3a74d1e741313e3fa25f78a53e435
Python
1,250
30
from argparse import ArgumentParser from transformers.commands import BaseTransformersCLICommand def download_command_factory(args): return DownloadCommand(args.model, args.cache_dir, args.force) class DownloadCommand(BaseTransformersCLICommand): @staticmethod def register_subcommand(parser: ArgumentPa...
750795eff57a78098e868022b02500b64f5f6c9fc4ca404848378343126d1c61
Python
1,251
41
"""Single-image inference script.""" import argparse import torch from PIL import Image from torchvision import transforms from configs.config import Config from models.hybrid_model import HybridTransformerModel from utils.checkpoints import load_checkpoint def predict_image(image_path: str): config = Config() ...
bb7aa8f184dd61da00d2bd6523a220c6bcb6a60030287597a09d4510e4e47bc0
Python
1,251
29
# Generate sql script to extract patient followup for each condition # Requires tables containing patients for inclusion from A0_global_vars_py import * s = '' for pln in ['gold', 'aurum']: s += f'--- {pln.upper()}\n' for condition in conditions: s += f'-- {condition.upper()} {pln}\n' s += f''...
3be37c408053c734ba6e23163fb9af2bbfdd1e08e188404ec28cf71dcff1820b
Python
1,252
40
"""Smoke test for scripts/ssn/train_bm.py. Uses tests/fixtures/ssn_smoke.yaml: 11 epochs, dur=100 (vs 1000 in the minimal_working_example), to keep runtime well under the 60 s timeout. Note: first run includes numba JIT compilation (~10-15 s overhead). """ import shutil import subprocess import sys from pathlib impor...
65d801bdfa0a37ca654ba1dcdea5e39122fdaa25033bac38bacc4bdb551ab9f8
Python
1,253
28
import argparse from msi_visual.extract.pymzml_to_numpy import PymzmlToNumpy def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--start_mz', type=int, default=None) parser.add_argument('--id', type=str, required=True) parser.add_argument('--end_mz', type=int, default=None) ...
a8b301d8ac6894730a5a07bdc49033555d722ae6c4b197339fe391ae4bdad762
Python
1,254
40
import torch.nn as nn import math import torch class GhostModule(nn.Module): def __init__(self, inp, oup, kernel_size=1, ratio=2, dw_size=3, stride=1, relu=True): super(GhostModule, self).__init__() self.oup = oup init_channels = math.ceil(oup / ratio) new_channels = init_channels*(...
ff6017bcbd920f8c8e6e4fc1b5a357130ae1ccd7679782c26c488263bba87f5c
Python
1,256
36
"""module for functions that deal with vector of times from a spectrogram, i.e. where elements are the times at bin centers""" import numpy as np def timebin_dur_from_vec(time_bins, n_decimals_trunc=5): """compute duration of a time bin, given the vector of time bin centers associated with a spectrogram ...
e3be15d704da345680f8c519184bf28e59e57cb98b5da8a6d0b4b147abde9ab5
Python
1,257
34
"""Checkpoint resume must not graft cached accuracies onto the wrong rows.""" import numpy as np from crossda.core.method_bank import generate_method_bank from crossda.core import workers as W def test_checkpoint_resumes_when_method_bank_matches(tmp_path): mb = generate_method_bank("smoke") cached = mb.copy...
ec2362ea49568650d0bb2ff08cbb5925cb6813a69ad71eb1082e31c121f13223
Python
1,257
40
import argparse import copy import time import neuroglancer import neuroglancer.cli from example import add_example_layers if __name__ == "__main__": ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) view...
6ee7e33c7f0392073ecd5cf43765492d2be44683238e8e4d3ecdef8fe1dc2836
Python
1,262
32
import torch from pathlib import Path import gdown import json from rinalmo.data.alphabet import Alphabet from rinalmo.model.model import RiNALMo from rinalmo.config import model_config DEFAULT_CACHE_DIR = Path.home() / ".cache" / "rinalmo_pretrained" with open(Path(__file__).parent / "resources" / "model2gdisk.json...
d1dccc88b7c55a19312a0b55b180848e5dbd35cb978a2e3e33d0ad57a8b9ea07
Python
1,262
49
#!/usr/bin/env python3 import argparse import os import shutil import subprocess import sys script_dir = os.path.dirname(sys.argv[0]) src_dir = os.path.join(script_dir, "ext/src") dest_openmesh_dir = os.path.join(script_dir, "ext/third_party/openmesh/OpenMesh") ap = argparse.ArgumentParser() ap.add_argument("openmes...
1f9eab770ba5c6fc1193be4c3af039d71300706693e0e16883a27b7cda31a068
Python
1,263
37
import numpy as np import scipy class ObjectDetector: def __init__(self, size=3, peak_multiply=1000): self.size = size self.peak_multiply = peak_multiply print(self.size, self.peak_multiply) def get_mask(self, img): img = np.float32(img) normalized = img ...
4d09a9e2d9d7bb04918f32c6ace625d83b251273f04766e7490014d7a7915c4b
Python
1,263
30
""" Function to compute spatial weights for the neighborhood extensions. """ def spatial_weights(adata_sp, standardized, self_inclusion): import collections import sklearn import libpysal import numpy as np if not set(["spatial_connectivities", "spatial_distances"]).issubset(set(adata_sp.obsp.keys...
64d7641e9e7371331fe33405e2c8c112daf12d59bd760bb23292ad642520f0fc
Python
1,263
34
from __future__ import annotations from typing import TYPE_CHECKING from scvi.utils import error_on_missing_dependencies if TYPE_CHECKING: from ._experiment import AutotuneExperiment, ScibTuneReportCheckpointCallback from ._tune import run_autotune __all__ = ["AutotuneExperiment", "ScibTuneReportCheckpointC...
9230f2e20a50eaa087b588aef8576017d4ffe7b2c720d390775ec05b64d5ba14
Python
1,263
47
import os import tarfile import pytest import scanpy as sc from scvi.data import dataset_10x, organize_cite_seq_10x from .utils import unsupervised_training_one_epoch def test_populate_and_train_one_v1(save_path): sp = os.path.join(save_path, "10X") dataset = dataset_10x( dataset_name="cd4_t_helper...
2462097bd840dde601f48e2c2b1bb3c553189061d81f44e374036cfd31150d01
Python
1,268
42
from argparse import ArgumentParser from pathlib import Path import nibabel as nib import numpy as np import pandas as pd def parse_args(): parser = ArgumentParser() parser.add_argument("residual_dir", type=Path) parser.add_argument("atlas", type=Path) parser.add_argument("output", type=Path) par...
6c09c225f3e306affaf5afb332f18c05e52360ffd85885440c56c9ce99fbb2cf
Python
1,268
51
import warnings from scvi import settings from scvi.utils import error_on_missing_dependencies from . import utils from ._amortizedlda import AmortizedLDA from ._autozi import AUTOZI from ._condscvi import CondSCVI from ._destvi import DestVI from ._linear_scvi import LinearSCVI from ._multivi import MULTIVI from ._p...
9dd631f3a9facd23af916dfeadb8cb7ae130e3742515b2296ae6bcda8bf93fb6
Python
1,271
53
from __future__ import annotations import os from pathlib import Path from PySide6.QtGui import QFont, QFontDatabase from src.gui.framework.qt_view_styles import ( APP_FONT_FAMILY, APP_FONT_POINT_SIZE, MONO_FONT_FAMILY, ) FONT_FILES = ( "DejaVuSans.ttf", "DejaVuSans-Bold.ttf", "DejaVuSansMon...
66fd51a56431e64cecd63c4a53f790002a4ca87534b91fc91f44f3f133f82dcf
Python
1,272
32
from argparse import ArgumentParser from transformers.commands import BaseTransformersCLICommand def download_command_factory(args): return DownloadCommand(args.model, args.cache_dir, args.force) class DownloadCommand(BaseTransformersCLICommand): @staticmethod def register_subcommand(parser: ArgumentPa...
cdd1a5820cc879943352edd7a69d66a29e3ba5ee9c25dd344c72017188c53f23
Python
1,272
55
import anndata import numpy as np import pandas as pd from anndata import AnnData import novae domains = [ ["D1", "D2", "D3", "D4", "D5"], ["D1", "D1", "D2", "D2", "D3"], ["D1", "D1", "D1", "D2", np.nan], ] spatial_coords = np.array([ [[0, 0], [0, 1], [0, 2], [3, 3], [1, 1]], [[0, 0], [0, 1], [0,...
66071efe0e12f5432f9f590ba9395bd997a64fdd85067dfd139bc0bd43a32517
Python
1,273
42
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def plot_prob_density_func(csv_path, col_name, out_path): # Load the CSV file data = pd.read_csv(csv_path) # Replace with your file path # Assuming the predicted probabilities are in a column called 'predicted_probability' pred...
b5f5f262492f9dc297c467e33a50bdb14257e54e52b7e195e0e1ac5ca5c9da53
Python
1,273
35
"""Used to operate on a sub-graph of a larger GO DAG.""" from collections import defaultdict __copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" class GODagSmall(object): """Contains a sub-graph of the original obo from geneontology.org.""" ...
3edc6b0e5c09797480e321bd9b2d1fb2aeb7f71aa79a5732564b1893f54770ac
Python
1,274
44
import os import re import pandas as pd import requests from bs4 import BeautifulSoup from tqdm import tqdm import config import enzymes with open(config.species_list) as species_list: bacteria = set(s.strip() for s in species_list.readlines()) for enzyme in tqdm(enzymes.enzymes): references = [] url =...
e7c5264163ba16dd818266e390dcd114ef01043911dff379165f89a1ee51deba
Python
1,275
33
# Shared Config class class Config(object): """ A shared configuration class for managing device settings, data paths, and training parameters in SemanticST. Attributes: use_cuda (bool): Whether to use CUDA (GPU) acceleration. Default is True. device (str): The computing device to be ...
9079eb45c796c9120b2c6b5f0b027f308cbb87e1baa698f53a39664ed50c4952
Python
1,276
63
""" Neural Network Models for Medical Imaging Core model architectures including transformers, MIL pooling, projection heads, and positional encodings for 3D medical imaging. """ # Transformer Components from .vit import ( SelfAttention, CrossAttention, Block, TransformerEncoder, VisionPredictor, ...
cbee68e094dd27c7cd5f1baf79daa4883af7a50a9ba2f6d190e183281804909a
Python
1,276
47
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
e76029c065a5982cb5f260984025b53efef4f44040ea6674d4b2417cde0ba2b7
Python
1,276
49
"""Classes to deal with codon sequences.""" import abc from Bio.Seq import Seq from typing import Union, List def _split_into_codons(seq: str): """Yield successive 3-letter chunks of a string/sequence.""" for i in range(0, len(seq), 3): yield seq[i:i + 3] class Sequence(abc.ABC): """Abstract bas...
e2bad14912c674071d25cd91dce1b42b1a17898e85b56fe133182838ee3b18cc
Python
1,279
40
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.optim from . import LegacyFairseqOptimizer, register_optimizer @register_optimizer("adagrad") class Adagrad(LegacyFairseqOptim...
425dce87ccb86db760e331053d355b09a820219a8eb6a0d2a97c00089dde77e2
Python
1,280
50
from __future__ import annotations from typing import TYPE_CHECKING from typing import ClassVar from cleo.helpers import argument from tomlkit.items import AoT from poetry.console.commands.command import Command if TYPE_CHECKING: from cleo.io.inputs.argument import Argument class SourceRemoveCommand(Command)...
fddbfdd111c8e3cf9892c002234aa2ee78380f1075700b1bf05ff167ee61ba53
Python
1,281
35
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from typing import Any, Dict, Type import pytest import torch from mattergen.diffusion.corruption.multi_corruption import MultiCorruption from mattergen.diffusion.corruption.sde_lib import SDE from mattergen.diffusion.tests.conftest import SDE_...
ed7d013ccca3a83dc32ccdb03d6f034ba64a627dc9eb240df94520005f19f711
Python
1,283
38
import math import unittest from unittest.mock import patch from pyecharts import options as opts from pyecharts.charts import Line3D from pyecharts.faker import Faker class TestLine3DChart(unittest.TestCase): @patch("pyecharts.render.engine.write_utf8_html_file") def test_line3d_base(self, fake_writer): ...
ab0efeb6a5bcdbfdea1f4c0842b5bc18ba48bb93f0bb79868e3352711ffbf9eb
Python
1,284
35
import importlib import os from beartype.typing import Any from omegaconf import OmegaConf def resolve_omegaconf_variable(variable_path: str) -> Any: """Resolve an OmegaConf variable path to its value.""" # split the string into parts using the dot separator parts = variable_path.rsplit(".", 1) # ge...
bd7c581eda6ffceee4bae55a09cde3b6edce3431a5083c91b700575874cbabbc
Python
1,284
28
from argschema import ArgSchema, ArgSchemaParser from argschema.schemas import DefaultSchema from argschema.fields import Nested, InputDir, String, Float, Dict, Int from ...common.schemas import EphysParams, Directories, CommonFiles class ExtractFromNpxParams(DefaultSchema): npx_directory = String(help='Path to N...
0c00f22e51d312dd115c5460b42700a1153a0cec70e0c5d4d108b6d1b28cccad
Python
1,285
46
import argparse from gsMap import __version__ from gsMap.config import cli_function_registry def main(): parser = create_parser() try: import argcomplete argcomplete.autocomplete(parser) except ImportError: pass args = parser.parse_args() if args.subcommand is None: ...
6fcce53559f49dd9d85d8e1f2b9542433d19b530ec5620df7db9b3c8f97a3639
Python
1,285
48
#!/usr/bin/env python # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import absolute_import from __future__ import division from __future__ import print_fu...
78f83d69c4b7ce2a499d77c19e04cf0a3aa17257c347c886d4cf534249983b4a
Python
1,285
43
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from fairseq.distributed import utils class TPUDistributedDataParallel(nn.Module): def __init__(self,...
e90be7bf695fef64133aace60830f9aef4366bf2986475e858ae75e482f21b87
Python
1,286
45
from __future__ import annotations from typing import TYPE_CHECKING import pytest from cleo.exceptions import CleoNoSuchOptionError from poetry.console.commands.sync import SyncCommand # import all tests from the install command # and run them for sync by overriding the command fixture from tests.console.commands....
16bb95bbaf2a6fbfc1d99d1ac988066b22ec7fe8c5506ed6c90fef572b87f26d
Python
1,287
23
import os import torch from nnunetv2.training.nnUNetTrainer.variants.pathology.nnUNetTrainer_WSD_undefined_dataloader import nnUNetTrainer_WSD_undefined_dataloader class nnUNetTrainer_WSD_bal_i0_alb_aug_TIME(nnUNetTrainer_WSD_undefined_dataloader): def __init__(self, plans: dict, configuration: str, fold: int, dat...
2f34061291bb9aa169b007dacad5743185461dcbc6adde0a7907b962dc2c4c22
Python
1,287
30
#!/usr/bin/env python3 # MIT License # # Copyright 2023 Broad Institute # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use...
4b1ee80a0872010ea1d00aabc7b72cad46351c4408fa4b52bfa7a6c27187f36d
Python
1,287
23
import os import torch from nnunetv2.training.nnUNetTrainer.variants.pathology.nnUNetTrainer_WSD_undefined_dataloader import nnUNetTrainer_WSD_undefined_dataloader class nnUNetTrainer_WSD_bal_i0_nnunet_aug(nnUNetTrainer_WSD_undefined_dataloader): def __init__(self, plans: dict, configuration: str, fold: int, datas...
a59d7f0dcd6314a9fae9fb3492fb72a10c554ad5d9f72c1d3d47658c97da33b0
Python
1,287
27
import os import random # dior # input_folder_path = r'D:\FangX24\code\LO-Det-main\mnt\Datasets\DIOR\ImageSets\train_s1_cat\novel_all' # output_folder_path = r'D:\FangX24\code\LO-Det-main\mnt\Datasets\DIOR\ImageSets\random4\novel10' # nwpu input_folder_path = r'D:\Projects\LFODet-main\mnt\Datasets\NWPU\ImageSet...
e4358a80d685e14f7c1bd81e2c593b8f2ae0af92c022a4e230c8deef245134df
Python
1,287
48
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import absolute_import from __future__ import division from _...
363491f7f10b3f672d2fe4d8b3f882bdd3036bd3d689c8aa1445b1dcfb4c1aca
Python
1,288
33
import pytest import torch import scvi.model.base._rnamixin as rnamixin_module from scvi.data import synthetic_iid from scvi.model import SCVI def _make_trained_model(gene_likelihood: str = "nb"): adata = synthetic_iid() SCVI.setup_anndata(adata, batch_key="batch") model = SCVI(adata, gene_likelihood=gen...
abf1d38146b0896095d72cdb0a3301cdb0ad835bcdf4bdff33f6ed80d16bbd52
Python
1,289
45
#!/usr/bin/env python # Author_and_contribution: Jieran Sun & Mark Robinson; implmented method # Author_and_contribution: Peiying Cai; created template # Author_and_contribution: ENTER YOUR NAME AND CONTRIBUTION HERE import argparse import pandas as pd from pathlib import Path # TODO adjust description description =...
49e0365fe13db91892e805923a24efc529f6667d5ad1b81874fc6a228c4031fe
Python
1,290
40
import sys import argparse from tqdm import tqdm from build_emov_translation_manifests import dedup, remove_under_k if __name__ == "__main__": """ this is a standalone script to process a km file specifically, to dedup or remove tokens that repeat less than k times in a row """ parser = argpar...
a35e674a597482428cb695fa6d207b3fea69091def9539b5d9f9f08c275f7c5e
Python
1,290
40
"""TensorBoard scalar logging for manual training loops (DLBase-style train/*, val/* names).""" from __future__ import annotations import os from typing import Any, Dict, Optional try: from torch.utils.tensorboard import SummaryWriter except ImportError: # pragma: no cover SummaryWriter = None # ...
8f367a2951fd8cfd61bdfb13890bb26754e98744e274347539f3f20487e2e691
Python
1,291
23
import os import torch from nnunetv2.training.nnUNetTrainer.variants.pathology.nnUNetTrainer_WSD_undefined_dataloader import nnUNetTrainer_WSD_undefined_dataloader class nnUNetTrainer_WSD_bal_i0_nnunet_aug_TIME(nnUNetTrainer_WSD_undefined_dataloader): def __init__(self, plans: dict, configuration: str, fold: int, ...
872630230a38fad409b3e2cebb402957a28a7298c11db91728754b4ff860688f
Python
1,293
35
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.nn as nn from .learned_positional_embedding import LearnedPositionalEmbedding from .sinusoidal_positional_embedding import Sinus...
3fc74c92ba6b11ea853ca9837f314a89c97a7d0536d087f3065d54d79b92c723
Python
1,294
50
from __future__ import annotations from typing import TYPE_CHECKING from typing import Any from typing import ClassVar from cleo.commands.command import Command as BaseCommand from cleo.exceptions import CleoValueError if TYPE_CHECKING: from poetry.console.application import Application from poetry.poetry i...
4e9613684a3ea5377db00446ed868887d41f8fc476921050385927cad5aa9a21
Python
1,294
39
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass from fairseq.data.legacy.masked_lm_dictionary import MaskedLMDictionary from fairseq.tasks.translation impor...
b834b6c9655f135bd9efaed5e8fdd9ef8f41a67d3fca9137d286c52de5a92670
Python
1,294
33
import argparse import json from collections import defaultdict import os import soundfile as sf from tqdm import tqdm if __name__ == "__main__": parser = argparse.ArgumentParser(description='Example argument parser') parser.add_argument('--exp', type=str) parser.add_argument('--dump', type=str) args =...
9a1b4f418fa3967d5aefc2435d1da9d7eb028a867e881df6bf388b8181f2f29f
Python
1,295
34
import torch.nn as nn import torch # using in EffcientDet class WeightedFeatureFusion(nn.Module): # weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 def __init__(self, layers, weight=False): super(WeightedFeatureFusion, self).__init__() self.layers = layers # layer indices ...
3542ca5fbae580769b12704af87b347f0b28806d961810d1b12f0eb33aa0166c
Python
1,296
26
import matplotlib.pyplot as plt import numpy as np plt.style.use(['science','nature']) x_ax = np.array([0.00,0.01,0.05,0.10,0.15,0.20,0.25]) y_ax = np.array([[0.9566, 0.9566, 0.9566, 0.9566, 0.9566, 0.9566, 0.9566, 0.9566, 0.9566, 0.9566], [0.957, 0.9578, 0.9568, 0.9554, 0.9576, 0.957, 0.956, 0.9556,...