sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
a418ebe2867256cffc7536098845b2e3fb0b1a2b802b81e6bc0829b2848eaca3
Python
634
22
"""Create individual experiment files for a parameter sweep.""" from pathlib import Path import yaml FNAME = Path("exp.yaml") with open(FNAME, "r") as f: data = yaml.safe_load(f) NUM_SIMS = 20 for i in range(NUM_SIMS): data["student_simulation_settings"]["weights_init_seed"] += 1 data["student_simulati...
e83bee87ce812ac8b65f8291e03ec335c5fd5125bd06577ae3521ff3497a1063
Python
634
21
from __future__ import annotations from poetry.config.config import Config from poetry.console.commands.command import Command class CacheListCommand(Command): name = "cache list" description = "List Poetry's caches." def handle(self) -> int: config = Config.create() if config.repository...
38772dae00ff9484b5f32c492a268b4fae27084fe41379702ff1c2f84e0f4243
Python
635
24
# encoding: utf-8 """ @author: Jiayang Chen @contact: yjcmydkzgj@gmail.com """ # import fm # def choose_backbone(backbone_name): # if backbone_name == 'rna-fm': # backbone, backbone_alphabet = fm.pretrained.rna_fm_t12() # else: # raise Exception("Wrong Backbone Type! {}".format(backbone_name))...
92f684855f57bc87e3bfd9cdbfe13d107034fad55a6cac040722257ed51cf3d4
Python
636
23
# 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 unittest from tests.speech import TestFairseqSpeech class TestS2TTransformer(TestFairseqSpeech): def setUp(self): self.se...
0a17ab747d3cc252235b425a8dd150f7843b2b28dfd9761839aa0f455f8db0c7
Python
637
19
# # setup.py # Copyright (c) 2020 Daisuke Endo # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php # #-------------------------------- # 作成者:Daisuke Endo # 連絡先:daisuke.endo96@gmail.com # 最終更新日 2020/5/17 #-------------------------------- from distutils.core import setup, E...
1b64d3e180e9b83f9d8c109ba9e940f09831ede9229d139df353f0ff80f1fac4
Python
637
17
from src.utils.eval_utils import Ontology import pandas as pd ont = Ontology('data/go-basic-2020-06-01.obo') MF_terms = pd.read_csv('data/GeneOntology/MF_mapping.csv', header=None) BP_terms = pd.read_csv('data/GeneOntology/BP_mapping.csv', header=None) CC_terms = pd.read_csv('data/GeneOntology/CC_mapping.csv', heade...
b2303cc517dbe727238d91aecde9047be04537226e9cb33197cb234e4ca83628
Python
637
20
from mdt import CompartmentTemplate __author__ = 'Robbert Harms' __date__ = "2015-06-21" __maintainer__ = "Robbert Harms" __email__ = "robbert@xkls.nl" class CylinderGPD(CompartmentTemplate): parameters = ('g', 'b', 'G', 'Delta', 'delta', 'd', 'theta', 'phi', 'R') dependencies = ('VanGelderenCylinder', 'Sph...
265b903afe0795a800071d1e46513a2f595ea946ee950b534b85d8f00484af39
Python
639
23
# 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 unittest from tests.speech import TestFairseqSpeech class TestS2TConformer(TestFairseqSpeech): def setUp(self): self.set_...
99b6dc388add0ed76fba35e40cf36a64f17e88f5b830dd7eaee48853c92f4c31
Python
639
14
# 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...
45de42d027d3accc847ef3a017485fc90ede4b337941b5bbd11f25f04d7180c2
Python
640
27
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from tractseg.experiments.base_legacy.tract_seg_legacy import Config as TractSegConfig class Config(TractSegConfig): EXP_NAME = os.path.basename(__file__).split(".")[0] NUM_EPOCHS = 250 DATA_AUGMENTATION = True # DATA_AUGMENTATION = False M...
c9c4ab022bad39427765f8aa524382b1890df4682490e24f232c125eaf249aed
Python
641
28
#!/usr/bin/env python3 import math import torch from torch import Tensor def batched_outer(a: Tensor, b: Tensor) -> Tensor: return a.unsqueeze(2) * b.unsqueeze(1) def asym_var(a: Tensor, b: Tensor) -> Tensor: return (a - b).var() def asym_angle(a: Tensor, b: Tensor) -> Tensor: assert a.shape == b.s...
db1ad3a42aecf597d9566eabb7b6394bb8b48aa8472cf98323057a9781ade6d2
Python
642
17
from __future__ import annotations from poetry.console.commands.lock import LockCommand from poetry.console.commands.self.self_command import SelfCommand class SelfLockCommand(SelfCommand, LockCommand): name = "self lock" description = "Lock the Poetry installation's system requirements." help = f"""\ Th...
ce142bcdf31cc519c552cd002bd74e8c054b3cd22b27e0f5f85c323ca3c77e46
Python
643
20
import argparse 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) # Specifying a token disable...
6631bfecb4c373262661c8956d514200fba66e15621ca47c3cb39333396f360d
Python
647
20
# 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 . import BaseWrapperDataset class StripTokenDataset(BaseWrapperDataset): def __init__(self, dataset, id_to_strip): super()....
71c65d0f62d514324d2224ca179ebb6f85afa1b291ceaefa84f089b9c18f8e76
Python
647
23
"""Register Simulation dataset (standalone Simulation + CID package).""" from __future__ import annotations from dlbase.registry import register_dataset from datasets.Simulation.datamodule_setup import ( simulation_eval_split_note, setup_simulation_datamodule, ) from datasets.Simulation.dataset_tas...
4eca160be556da2639ba9b6abd83208dddc6052cf23b4549e7eb6bf2a000c639
Python
648
21
from ._attrdict import attrdict from ._decorators import unsupported_if_adata_minified from ._dependencies import dependencies, error_on_missing_dependencies, is_package_installed from ._docstrings import de_dsp, setup_anndata_dsp from ._mlflow import mlflow_log_artifact, mlflow_log_table, mlflow_log_text, mlflow_logge...
9ce050b96db979e9955bb139ea136986780398dc3c4794227e59347f11e41255
Python
649
31
"""scvi-tools.""" # Set default logging handler to avoid logging with logging.lastResort logger. import logging from ._constants import REGISTRY_KEYS from ._settings import settings # this import needs to come after prior imports to prevent circular import from . import data, model, external, utils, criticism from ...
22eb336c48259a2e16b22260a80469d708a86250af781126d933cadeb952b511
Python
652
23
# 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 .processor import * from .how2processor import * from .how2retriprocessor import * from .dsprocessor import * try: from .rawvideopr...
ae33bd884435d83210ece0e3bdff1be3d068dd7c050aae92e8dcd918387ba11a
Python
652
23
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from dataclasses import dataclass, field from hydra.core.config_store import ConfigStore from hydra_plugins.hydra_submitit_launcher.config import SlurmQueueConf @dataclass class DependencySubmititConf(SlurmQueueConf): """Slurm configuration ...
8b784a9fdcafcb6d0e35c8b164977edbe3ad700950d109ed9542b527706fbfa7
Python
653
24
import os import glob root = r"D:\Projects\LFODet-main\mnt\Datasets\NWPU\ImageSets" old_prefix = r"D:\FangX24\code\LO-Det-main\mnt\Datasets\NWPU" new_prefix = r"D:\Projects\LFODet-main\mnt\Datasets\NWPU" txt_files = glob.glob(os.path.join(root, "random*", "**", "*.txt"), recursive=True) print("Found txt f...
144c001f817a11c018cb618354e7fb67e52cd76d01b74667b02fc0657a5874e7
Python
655
14
# 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...
77f201aa00b9e435554c096a42406cfcbcfa40d9562ef763dd77f3ed0b4f6eea
Python
656
22
# # 09/19 11:34 - {builders_utils.py:208} - n_genes, n_pathways 9229 1387 # 09/19 11:34 - {builders_utils.py:208} - n_genes, n_pathways 1387 1066 # 09/19 11:34 - {builders_utils.py:208} - n_genes, n_pathways 1066 447 # 09/19 11:34 - {builders_utils.py:208} - n_genes, n_pathways 447 147 # 09/19 11:34 - {builders_utils.p...
b8a13f8b64dfdc5805f6e88c5db0fd50263ccef88266315607c8fed92ee6c38f
Python
657
21
import numpy as np def calculateMeanCoefficients(trialCoefficients): """ calculate mean coefficients for each trial. parameters: - trialCoefficients: dictionary with trial coefficients returns: - dictionary with mean coefficients per trial """ meanCoefficients = {} for tsN...
a18f9f091ca3349f6326e7ca8dffeb41fa6c2c39810b6e3a912a80f5a5ff22ee
Python
658
26
from . import decorator, definition, factory, registry from .convencoder_umap import ConvEncoderUMAP from .decorator import model from .ed_tcn import ED_TCN from .factory import ModelFactory from .frame_classification_model import FrameClassificationModel from .get import get from .parametric_umap_model import Parametr...
bc6c5b54c01570b1437a110b752d03f579fc8300af1569ef7fe05a0cb42fbaf8
Python
658
19
"""Generic cfg-level assertions (no hard-coded dataset / model / task names).""" from __future__ import annotations from typing import FrozenSet from omegaconf import DictConfig def assert_task_in(cfg: DictConfig, allowed: FrozenSet[str], context: str) -> None: t = str(cfg.task.name) if t not in...
2cb2ab98627b3e2b0c3ea9a10328ff36a55a614ea71c1eebd91f64befead05a1
Python
659
17
from chanfig import Config, Variable class BaseConfig(Config): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.input_file = Variable(str, default="./tests/fasta/single_sequence.fasta") self.save_path = Variable(str, default="../results") self.auto_fix = ...
5e0dbbdb89a7a61883dcf1f0147c52e11aabb9b79e552567170ce6a3ff1e9a68
Python
659
19
import shutil from batchgenerators.utilities.file_and_folder_operations import isdir, join from nnunetv2.paths import nnUNet_raw, nnUNet_results, nnUNet_preprocessed if __name__ == '__main__': # deletes everything! dataset_names = [ 'Dataset996_IntegrationTest_Hippocampus_regions_ignore', 'Da...
948faf9ef59dc9adb2ac758bbf76a69e8f0a8c99dd668b821fe35e553bca4f16
Python
659
17
"""Filtro das copias por simetria (543 das 1784). SEM_COPIAS=0 desliga (controle).""" import json, os from pathlib import Path _G = json.loads((Path("/home/david/atual/new-methods/submissions/oce-jpcc-perovskites/REVISAO_R1/calculos/eos_cenapad") / "duplicatas_simetria_1784.json").read_text()) COPIAS =...
9c5a3818939c8cc44afd5e02dbe8c1b23990ff073877a5de2dfad6bd43834e08
Python
659
22
# 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_function from __future__ ...
4b2a472f1a4b4b11f97dd79ed7b7aae7760d81e97e9b46a136009d4cf9eae224
Python
660
22
import qrcode # URL var: enter link/url for the pdf pdf_url = "https://drive.google.com/u/0/uc?id=1Uvs7RSEbtPUsUvyRcrEEizRhAgqhlElH&export=download" # QR code instance qr = qrcode.QRCode( version=1, # QR code version (adjust as needed) error_correction=qrcode.constants.ERROR_CORRECT_L, # Error correction le...
51dc0519ffd7c1adc2aa46bf39f7df4521beb07a14ef1f888db821454c8f3b77
Python
660
35
from .utils import ( WINDOW_LENGTH, WINDOW_STRIDE, Pointer, Token, aggregate_embeddings, embed_document, load_fast_tokenizer, log_config, merge_off_tokens, merge_predictions, merge_tokens, repr_sequence, split_and_tokenize, token_merge, tokenize_and_align, ) ...
b1b1ee3a3d6868e108ccca1c9503d5a7824c1997d4bb239999f1a6241f37e16b
Python
660
29
from dataclasses import dataclass, field from typing import Any, Optional @dataclass class DatasetParams: loader: str image_dir: str image_size: int channels: list[str] batch_size: int val_split: float test_split: float keys: list[str] name: Optional[str] = None labels: Optiona...
5f7244d77ef3fee41dd8078507ed87f3317ea9109a937674fc8dd26cf466540d
Python
661
20
import numpy as np class CrossSessionLeaveOneOut: """ K-Fold by held-out sessions. Provides train/test indeces stratified by session. Useful for Allen dataset """ def __init__(self, session_labels: np.ndarray): self.session_labels = session_labels self.unique_sessions = np.uni...
81d285f77e444308aaf387bf06ecbbf7ccca4461d62db3e9ad9fe462393e5d82
Python
663
14
# 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...
72df66c996cd559fa6a67b909de787123fea2f816173d2e3f9cb0a9cc9dc0f68
Python
664
31
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import shutil from glob import glob from vlpp.utils import gzipd, run_shell, run_matlab, TPL_PATH def main(): niigz = "${petInputNii}" nii = gzipd(niigz) dst = nii.replace("_input_", "_").replace("_copy", "") shutil.move(nii, dst) tags = ...
90bfadedc63b26b61934964dfb27156269a8eab52ab9293c591cc651736baa9b
Python
664
26
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from tractseg.data import dataset_specific_utils from tractseg.experiments.base_legacy.tract_seg_legacy import Config as TractSegConfig class Config(TractSegConfig): EXP_NAME = os.path.basename(__file__).split(".")[0] DATASET_FOLDER = "HCP_preproc_all"...
c0a0c60e671d2b2a433f06d61778a966c87d94493059e6550222bdce3af2c566
Python
665
23
# 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 os import importlib from fairseq import registry ( build_monotonic_attention, register_monotonic_attention, MONOTONIC_ATT...
dd785f4231bb626af74669c13b67fbc8e277a0b5637de6bc38926b7656522c93
Python
666
20
from rnalysis.utils.feature_counting import * def test_create_featurecounts_script(): expected_path = 'tests/test_files/featurecounts_tests/expected_featurecounts_script.R' output_dir = Path('tests/test_files/featurecounts_tests/outdir') kwargs = {'arg': True, 'arg2': None, 'arg3': 'string', 'arg4': ['str...
2d7f7a8faf41e26d05eb16f82fe843a4a180497565dd6841f644891dc7a3b383
Python
668
27
from __future__ import annotations from poetry.console.commands.command import Command class AboutCommand(Command): name = "about" description = "Shows information about Poetry." def handle(self) -> int: from importlib import metadata self.line( f"""\ <info>Poetry - Package...
e1d6bf30574f4e9b17aef158d9bd5c31ff2d61d495d43b5989cfa54e50d7751a
Python
668
24
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="mmpt", version="0.0.1", author="Hu Xu, Po-yao Huang", author_email="huxu@fb.com", description="A package for multimodal pretraining.", long_description=long_description, long_descr...
5742888af6570c79b1af7e46fe5e846f373c22f70522f8961bdd665e15e378e3
Python
669
27
#!/usr/bin/env python import re import requests from packaging import version def get_most_recent_version(name): request = requests.get( "https://api.anaconda.org/package/conda-forge/" + name ) request.raise_for_status() pkg = max( request.json()["files"], key=lambda x: version.parse(...
f39ec4a065bbde7f867e683ba490a7e3019248d6c85744e8be5febbcb15ee9c9
Python
669
19
# 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 importlib import os # automatically import any Python files in the current directory cur_dir = os.path.dirname(__file__) for file in o...
cd7929ec8ecb5cdfd97814a4cc19ec60a3f7843a934df819d47fe80dbe3314f6
Python
670
24
from msi_visual.base_dim_reduction import BaseDimReduction import pacmap import numpy as np import joblib from msi_visual.utils import normalize class PACMAC3D(): def __init__(self): self.model = pacmap.PaCMAP(n_components=3) def __repr__(self): return f"PACMAC-3D" ...
cda8fe5886fc44e41e6469d802be15bc436ff03586b00173bd99044e909d9acf
Python
670
30
from __future__ import annotations from typing import TYPE_CHECKING import pytest from cleo.io.buffered_io import BufferedIO from poetry.utils.env import EnvManager if TYPE_CHECKING: from poetry.poetry import Poetry from tests.types import FixtureDirGetter from tests.types import ProjectFactory @pyt...
aee147dfa11a620fee2a4171c38a77fe7ab0f2d06b37c7278b1b8c6dce98c759
Python
671
22
from typing import NamedTuple class _CYTOVI_REGISTRY_KEYS_NT(NamedTuple): X_KEY: str = "X" BATCH_KEY: str = "batch" LABELS_KEY: str = "labels" SAMPLE_KEY: str = "sample_id" CAT_COVS_KEY: str = "extra_categorical_covs" CONT_COVS_KEY: str = "extra_continuous_covs" INDICES_KEY: str = "ind_x" ...
15d13418b0ede38ed80ba91f62d635c2ddf0cf22039eb6de19b7b0287693cb8b
Python
672
22
from gtfparse import read_gtf from transcript_transformer.data import parse_transcriptome, save_transcriptome_to_h5 import h5py import time data_dict = parse_transcriptome("export/final_transcripts_RiboTIE.gtf", "/Users/xunuo/Genomic_references/GENCODE/GRCh38.primary_assembly.genome.fa") no_handle = True max_wait = 90...
5f2a31195f51e2195f60cc9893a887beb81f08b563b47b9f753715e90d57c745
Python
673
28
import torch import msprime import stdpopsim import os import numpy as np import pickle from dadi_simulators import * datadir = snakemake.params.datadir posteriordir = snakemake.params.posteriordir num_simulations = snakemake.params.num_simulations if not os.path.isdir(f"{datadir}"): os.mkdir(f"{datadir}") dem...
f8fc4f9241043358aa81fd7f09643321e6343860eb33e93670c809a549a564eb
Python
673
23
import ctypes from functools import partial from typing import Tuple import jax import jax.numpy as jnp import numpy as np from pyscf import lib from pyscf.dft import gen_grid @partial(jax.jit, static_argnums=0) def spherical_grid(lebedev_order=7) -> Tuple[jax.Array, jax.Array]: r"""Return the spherical Lebedev ...
5270f7b19e889251e36b24bc488b5e03ee9f2bff6de64f157bc08447021a20c8
Python
674
23
import soundfile as sf import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(description='Example argument parser') parser.add_argument('--src', type=str) parser.add_argument('--dst', type=str) args = parser.parse_args() wavs = [x.strip() for x in open(args.src, "r").readline...
dff7a4c0cf5347a5c402595b4cbcf97bc7d8ab7f7dd71b68a7dbdd62ab9d75de
Python
674
21
# -*- coding: utf-8 -*- import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="working-memory-eeg-analysis", version="0.0.1", author="Marius Keute and Silvana Miranda Montenegro", description="Analysis functions for working-memo...
23833682bef7db82e711f99f106717dfecd42aa6bbfb17ac55220ee729139e19
Python
676
28
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from poetry.core.packages.package import Package from poetry.core.packages.project_package import ProjectPackage class SolverResult: def __init__( self, root: ProjectPackage, packages: list[Pac...
05ce2b15899ccd353a35b38d93869591b5dd1937ca782d2d5650ec0b52e87991
Python
677
31
import os def get_volume_name( fullname_volume: str, dir_prefix: str = None, ) -> str: """ Get name of volume (with directory prefix and plane suffix). Parameters ---------- fullname_volume : str Full name of volume. dir_prefix : str (optional) Prefix for directory. De...
5e47ec9ddb1f0c3a959cad122f423a50c93d029bad66c6fa5084b254daac0f01
Python
677
17
OrderList = ['1234', '1324', '2134', '2314', '3124', '3214'] for i in range(6): for j in range(2): with open('Training_dataset_R%s.txt' % (i*2 + j +1), 'r') as fin: lines = fin.readlines() with open('Training_dataset_R%s_%s.txt' % ((i*2 + j +1), OrderList[i]), 'w') as fout: for m in OrderList[i]: for k i...
3da520b5ee83b1b048241d819c6b99ac73e302b177b80664d8084f0667f234de
Python
679
24
#!/usr/bin/env python # -*- coding: utf-8 -*- """Outputs analysis results""" try: import numpy as _ # noqa F401 F811 import matplotlib as _ # noqa F401 F811 import nd2 as _ # noqa F401 F811 except ImportError: raise ImportError("Must install numpy, matplotlib, and nd2") from . import basic_analyse...
0c76ee07509d4e5d2f03d5ab71fbf9b57dac3f437d1a79a655c94b071614203f
Python
680
21
# 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 math import torch.nn.functional as F def pad_to_multiple(x, multiple, dim=-1, value=0): # Inspired from https://github.com/lucidr...
8c9e457307bab5b5f1a92b94c513b7b9e978e2d1cfe77bd549ca2396eb347013
Python
680
18
# Copyright 2015 Google Inc. All Rights Reserved. # # 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 a...
a87a738b55afac2fe2e93ad5aefb92e78ebc8d62859fe3755ff68cf8577df902
Python
681
26
import math import numpy as np def point_to_line_distance(x1, y1, x2, y2, xp, yp): # 计算斜率 if x2 - x1 == 0: # 防止除以零的情况(垂直线) m = float('inf') distance = abs(xp - x1) else: m = (y2 - y1) / (x2 - x1) # 计算点P到直线的垂直距离 distance = abs(m * xp - yp + y1 - m * x1) /...
d5f34a1c73f4ae59dcac69aa478a9c0bcffef42c1a6f882c0e86603101ed6a5f
Python
681
31
#!/usr/bin/env python3 import os import numpy as np import tensorstore as ts example_dir = os.path.abspath(os.path.dirname(__file__)) def write_single_res(): store = ts.open( { "driver": "zarr3", "kvstore": { "driver": "file", "path": os.path.join...
18c59276f5d4e3bc805f0adc3206e95b5424639021480e168188e1ce25b345ec
Python
684
23
"""assertions common to cli functions""" import vak def toml_config_file_copied_to_results_path(results_path, toml_path): assert results_path.joinpath(toml_path.name).exists() return True def log_file_created(command, output_path): log_file = sorted(output_path.glob(f"{command}*.log")) assert len(lo...
8fa8dfd201c15fc0f799bd9a3b47d53bc03d68058c52cde63989800fdf8357eb
Python
684
30
# 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 fairseq.data.encoders import register_bpe SPACE = chr(32) SPACE_ESCAPE = chr(9601) @register_bpe("characters") class Characters(obje...
28a1e8e5f7446c0bc8ca48be844781daae625ab0eb0045108c9d8ae4a6040f3e
Python
685
24
from mdt.component_templates.compartment_models import CompartmentTemplate __author__ = 'Robbert Harms' __date__ = "2018-08-28" __maintainer__ = "Robbert Harms" __email__ = "robbert@xkls.nl" class AstroCylinders(CompartmentTemplate): parameters = ('b', 'G', 'Delta', 'delta', 'd', 'R') dependencies = ['VanGe...
45718ac64a5eeb5fa67236791753a69604e3526c82c8acabc8c39fdff063edb2
Python
685
25
import torch def test_model(model, dataloader, device, log_dir): test_log = open(f'{log_dir}/test_log.csv', 'w') test_log.write("Label,Probability\n") model.eval() with torch.no_grad(): for i_batch, sample_batched in enumerate(dataloader): inputs, labels = sample_batched['mat...
ee1c191ea80110b22c49cb6f0c153052b86cc7d6296870d1c6394565e698be1c
Python
685
16
from transformers.models.bert.configuration_bert import BertConfig config = BertConfig.from_pretrained("zhihan1996/DNABERT-2-117M") model = AutoModel.from_pretrained("zhihan1996/DNABERT-2-117M", trust_remote_code=True, config=config) dna = "ACGTAGCATCGGATCTATCTATCGACACTTGGTTATCGATCTACGAGCATCTCGTTAGC" inputs = tokeniz...
835d09eca984d34a6ea3e061ecd54c0a09d73c97a5ecc1db2dc45a351bf6b83a
Python
687
27
from __future__ import annotations from typing import TYPE_CHECKING from poetry.plugins.base_plugin import BasePlugin if TYPE_CHECKING: from poetry.console.application import Application from poetry.console.commands.command import Command class ApplicationPlugin(BasePlugin): """ Base class for app...
a41bce0b15f50e5bff70ce8b3c2b7aeb504b7bc018e8c1a7c5a3050e574aeab5
Python
687
26
# kNN with neighbors=4 benchmark for Kuzushiji-MNIST # Acheives 92.10% test accuracy from sklearn.neighbors import KNeighborsClassifier import numpy as np def load(f): return np.load(f)['arr_0'] # Load the data x_train = load('kmnist-train-imgs.npz') x_test = load('kmnist-test-imgs.npz') y_train = load('kmnist-t...
4f93076c72ed10def3657f2fc37e928f22552af33b55723616dc0b2e4c18de73
Python
689
25
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from torch import Tensor def rowwise_max_excluding_diagonal(matrix: Tensor) -> Tensor: """Get the rowwise maximum of a matrix excluding the diagonal.""" import torch assert matrix.ndim == 2 num_cols = matrix.s...
b70884b86b2ef284fc527f1e25981aee0eaad509d75b24337be3f9d47782ea13
Python
689
29
project = "Moove" copyright = "2025, Nils Riekers, Franziska Heubach, Jacqueline Laura Goebl, Lena Veit" author = "Nils Riekers, Franziska Heubach, Jacqueline Laura Goebl, Lena Veit" release = "1.1.0" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.viewcode", "sphinx.ext.intersphinx", ] templates_path = ...
4ed0eb8ed6c57e13f770958c956ac2c19c89b829988ad0f341e54a73e1cfed0e
Python
691
26
"""Feature-local view state for behaviour alignment.""" from __future__ import annotations from dataclasses import dataclass @dataclass class BehaviourViewState: file_path: str = "" pre_behaviour_time: str = "" post_behaviour_time: str = "" synchronize_start_time: str = "" duration_box_placement...
7bec4a1b73cb98692f8662c59d0f790f10f2ee2dd24875ac5825318d10f8b36c
Python
691
29
from apiadapters.straininfo import normalize_strain_names def test_parse_standard() -> None: standard_names = ("Delft L 40", "STAFF 1027", "DSMZ 2213") assert normalize_strain_names(standard_names) == set(standard_names) def test_parse_non_standard() -> None: names = ( "544 / ATCC 23448", ...
d87f1ab847b18d43c042f124ec0e614d7fb24faf4538282493da9f0531f0636f
Python
695
29
import torch from torch.utils.data import Dataset import pandas as pd from typing import Union from pathlib import Path from rinalmo.data.alphabet import Alphabet class TranslationEffDataset(Dataset): def __init__( self, csv_path: Union[Path, str], alphabet: Alphabet ): self...
043d100fe5016302eada1f9515763fee5228ca26c30763fd272a540507a787a2
Python
696
17
import torch from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("zhihan1996/DNABERT-2-117M", trust_remote_code=True) model = AutoModel.from_pretrained("zhihan1996/DNABERT-2-117M", trust_remote_code=True) dna = "ACGTAGCATCGGATCTATCTATCGACACTTGGTTATCGATCTACGAGCATCTCGTTAGC" input...
8f3f394ef74987cf0302dc62e08c10808ab5b20aa96db4cf441cda1f323199a6
Python
696
30
from __future__ import annotations import ast import os from setuptools import setup def read_version(): with open(os.path.join(os.path.dirname(__file__), "demo", "__init__.py")) as f: for line in f: if line.startswith("__version__ = "): return ast.literal_eval(line[len("__ve...
7010e87b8781f7f55ca8aa381675c8f857cce6e6519332db329993f61865968f
Python
697
21
"""Regression test for the deadline profile `tests/conftest.py` loads. None of the suite's property tests measure timing, so a slow machine tripping Hypothesis's 200ms default deadline is a flake, not a signal. """ import time from hypothesis import given, settings from hypothesis import strategies as st @given(st...
a4197c7c5c026be4f92b255c066e1fde3a27e954739f9a0fe3bb24f624291603
Python
697
22
import glob import os import pickle from sbi.utils.posterior_ensemble import NeuralPosteriorEnsemble import torch import numpy as np posteriordir = snakemake.params.posteriordir n_train = snakemake.params.n_train posterior_files = glob.glob(f"{posteriordir}/n_train_{n_train}/posterior_rep_*.pkl") posteriors = [] for ...
1a643a8da2d1b5e284b654ba7270f5e577eae78725ae2c631776f20326517612
Python
698
27
#!/usr/bin/env 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 sys from sacremoses.normalize import MosesPunctNormalizer def main(args): normalizer = MosesPunctNormal...
7034b2c057e017f47a2296e430634ad5bdd290cddf5de31111d5e940f8c084ca
Python
698
24
import lmdb from tqdm import tqdm import pickle as pkl from pathlib import Path from tape.data_utils import PFAM_VOCAB import numpy as np vocab = {v: k for k, v in PFAM_VOCAB.items()} files = Path('data').rglob('*.lmdb') for lmdbfile in files: print(lmdbfile) env = lmdb.open(str(lmdbfile), map_size=50e9) ...
322e8dfc8e2c8392466a7d2cff42df7bc4eb8e55ed6253d62bb161f24a865c8f
Python
701
31
from __future__ import annotations from typing import TYPE_CHECKING import pytest if TYPE_CHECKING: from tests.types import HTMLPageGetter @pytest.fixture def html_page_content() -> HTMLPageGetter: def _fixture(content: str, base_url: str | None = None) -> str: base = f'<base href="{base_url}"' if...
5a93138b4ca174c53ac781d91d3988d5b139239570754cd0dc0a4233954bd9bb
Python
701
20
# 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 typing import List, Tuple def get_audio_files(manifest_path: str) -> Tuple[str, List[str], List[int]]: fnames, sizes = [], [] w...
ac4fb8554c0df22670fa8e3c403a40a20109bb5a49f3c2a640b5f20d0289cb1e
Python
701
20
# 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 importlib import os # automatically import any Python files in the models/ directory models_dir = os.path.dirname(__file__) for file ...
bc77cdf0f5c07d4a466ee832f312b9ea42d9c3a3503e13516a5a2a829078da41
Python
701
33
import numpy as np from pyfaidx import Fasta import logging # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) logger = logging.getLogger(__name__) def fasta2list(fasta_file): data = Fasta(fasta_file...
49ce0bf57161f87d00f011f56c3919dd09f769c932f8432e18da2b4fb66eff0d
Python
704
23
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="DSTG", version="0.0.1", author="QSong", author_email="wasqqdyx@gmail.com", description= "Deconvoluting Spatial Transcriptomics data through Graph-based convolutional networks (DSTG)", ...
c7d32482bc1cb6cebce9457900701282aff91ed7b701971a010cb4e813f20983
Python
704
34
# adopted from attrs library # https://github.com/python-attrs/attrs/blob/master/tests/utils.py from attr import Attribute from attr._make import NOTHING def simple_attr( name, default=NOTHING, validator=None, repr=True, eq=True, hash=None, init=True, converter=None, kw_only=False,...
b3f446baa962c3764ab8865bfeeaa0d06c48f100e02a11a200c51e8bd74799fe
Python
705
24
#!/usr/bin/env 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 torch from typing import List, Dict from .base_decoder import BaseDecoder class ViterbiDecoder(BaseDecoder)...
b1e8efc40d2c5aefaa49ac72cb2c169c172539085570005ffc98f3029333d763
Python
706
25
# 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. """ See "Gaussian Error Linear Units (GELUs)" by Dan Hendrycks and Kevin Gimpel with the corresponding GitHub repo: https://github.com/hendryck...
edcd129ff6966605bdff7baa493630c1704951f567208f81a19c0b453f85136b
Python
706
17
from brenda_references.collection_numbers import is_collection_number def test_admits_real_collection_numbers() -> None: for designation in ("ATCC 9202", "DSM 4252", "NCTC8511", "CBS 111.30"): assert is_collection_number(designation), designation def test_rejects_generic_designations() -> None: for ...
eef46a006a786a3452c54f86a013a1281beb1585a816f2ca79d478a0a56ca077
Python
706
29
import torch from torch.utils.data import Dataset import pandas as pd from typing import Union from pathlib import Path from rinalmo.data.alphabet import Alphabet class ExpressionLevelDataset(Dataset): def __init__( self, csv_path: Union[Path, str], alphabet: Alphabet ): sel...
623f97e7d40dbbeb7a1c0b4fad0664d119ab1e9ec8e942e7fde91e9090e6bffb
Python
707
23
try: from d3text.excepthook import install as _install_excepthook _install_excepthook(style="darkbg2") except ModuleNotFoundError: print( "pip install stackprinter if you want stackprinter's exception messages." ) try: from beartype.claw import beartype_this_package beartype_this_pack...
d4bf22f3ffec8578bd0051c04b5b04d2e35997c041d601a1e8ce4936a3060f85
Python
708
18
from batchgenerators.utilities.file_and_folder_operations import * from nnunetv2.batch_running.collect_results_custom_Decathlon import collect_results, summarize from nnunetv2.paths import nnUNet_results if __name__ == '__main__': use_these_trainers = { 'nnUNetTrainer': ('nnUNetPlans', ), } all_re...
b64a9368daf430d6632a6a688e0f07620194555a5fafac827a61ee64b66ffd26
Python
709
21
"""Regression test for the shared NCBI merged-taxid forwarding helper.""" import pandas as pd import pytest from taxonomy.ncbitax import ncbitax from d3text.taxonomy import merged_taxids def test_merged_taxids_maps_a_retired_id_to_its_current_one( monkeypatch: pytest.MonkeyPatch, ) -> None: """A caller impo...
7059e9ca7471b693f9271f777cd411cfbb5d05b81e1e58d093ff9ca9d3b04599
Python
710
20
# 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 importlib import os # automatically import any Python files in the models/huggingface/ directory models_dir = os.path.dirname(__file_...
9af73c32a31be54829eb9ae93ef64cba03fce207a6a6d08e6c0a39c5db1dc1d5
Python
710
28
def seq2kmer(seq, k_mer, max_length=None): kmer_text = "" i = 0 upper = len(seq) - k_mer + 1 if max_length: upper = min(upper, max_length) while i < upper: kmer_text += (seq[i: i + k_mer] + " ") i += 1 kmer_text = kmer_text.strip() return kmer_text def seq2input_id...
00852a1fcf3d86ce84cdf3e8db889fd9acec533777bb560988ec24317a2614a0
Python
711
26
import pytest import numpy as np import os #from ecephys_spike_sorting.modules.automerging.automerging import automerging #import ecephys_spike_sorting.common.utils as utils #DATA_DIR = os.environ.get('ECEPHYS_SPIKE_SORTING_DATA', False) def test_automerging(): sample_rate = 30000.0 params = {} params['merge_th...
49624487b3bac7cfe2974436d19e7ef04a11d04746a93235e4c9105507298d98
Python
711
23
""" PyTorch Dataset and Batch Sampler ImageDataset: Loads individual images with augmentation and tokenization StudyAwareBatchSampler: Groups images from same study into batches MultiViewCollator: Collates batches with background filtering MultiBlockCollator: JEPA-style mask generation collator ImageDataModule: PyTorc...
397454407043ebd0962e07ff33c1f399855b84fcd7aa5a24deffbc2406147576
Python
713
24
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...
c7094eab27073cf33d352a5b0a5960bd2fd06f1fb1c69dad4b4082522e33f1f9
Python
714
23
import gradio as gr import subprocess def run_command(cmd: str) -> str: p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if stdout: return f"[Output]\n{stdout.decode()}" if stderr: return f"[Error]\n{stderr.decode()...
f5e0024bd0baee8713c3480fb849751c0416c27f8d344265c7c12361d96ccd54
Python
714
31
import numpy as np from skfmm import distance import time import pylab as pl def p(m): pl.matshow(m); pl.colorbar(); pl.show() def c(m): pl.contour(m); pl.colorbar(); pl.show() def cf(m): pl.contourf(m); pl.colorbar(); pl.show() def test0(): "circular level" N = 1500 X, Y = np.meshgrid(np.linspace(-1,1,N...
14d7b8f24bfb2f2e2b7d19714880c4f3a8e7b2c61858224ea035847f59b29602
Python
716
19
# python setup_cmmcost_omp.py build_ext --inplace # export OMP_NUM_THREADS=6 from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension import numpy srcfiles = ["cmmcost_omp.pyx", "_cmmcost_omp.c"] includedirs = ["/mnt/seagate10/gsl/include", numpy.get_include()] # pa...
d1a1bc68ff130b94230a607405744d50ea0ce0fb64511a4e31d6a0578d46d0b3
Python
716
23
#!/usr/bin/env python # -*- coding: utf-8 -*- """utils""" from . import color_maps # noqa F401 from . import types # noqa F401 from .decorators import timer_s # noqa F401 from .filter import ( # noqa F401 filter_edge, filter_no_eccentricity, filter_tile_scan, filter_low_pixels, filter_cells_ge...
31114f08e3d6c08da15345d60014a86cbcdf9115b343f399ac25d20887454975
Python
717
21
"""Build ``torch.nn.Module`` from Hydra config (plugins registered in ``models.plugins``).""" from __future__ import annotations from omegaconf import DictConfig def construct_model(cfg: DictConfig): """Construct weights only (call :func:`build_model` for compatibility checks).""" from dlbase.regis...
afe7a0545016d0d338d76f6ebb022208d16bec5ca87385cfd063f9b991f0bbb5
Python
718
18
""" from https://github.com/keithito/tacotron """ ''' Defines the set of symbols used in text input to the model. The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. ''' from . i...