sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
364ca2f16ecf322ba87719e04b5f859fa6fcb2b105ffab8df8fc9d511342ffd6
Python
1,570
50
import unittest from pathlib import Path from tempfile import TemporaryDirectory from scripts.validate_gmx_MMPBSA_test_docs import ( _command_signature, _parse_bundled_test_command, _parse_serial_command, _test_selector, ) class GmxMmpbsaTestDocumentationValidatorTest(unittest.TestCase): def test...
5d331e09ce590d3accfd1f689b8fb248c9e704a8eb4c219fbcedaded3ba6ab3b
Python
1,570
63
# import theano.tensor as T # import theano import numpy as np from keras import backend as K from keras.constraints import Constraint class OneToOne(Constraint): def __call__(self, p): # p = theano.shared(p) # n, m =p.shape # print n, m # p *= T.identity_like(p) # TODO: re...
2a53058244e2831b62b1469cbab80d30133520e32fb7eaf2f7ed169bb3515321
Python
1,571
46
#!/usr/bin/env python import os import gzip import sqlite3 import shutil selected=["ENSG00000107937.14", "ENSG00000107959.11", "ENSG00000234745.5"] def copy_covariance(ip, op): with gzip.open(ip) as infile: header = infile.readline() with gzip.open(op, "w") as outfile: outfile.write(he...
ffc3c7bfaa22ded8d644cc195f33a8fa0031d251c1924ca6da9fc7583d586a9e
Python
1,571
49
import os import pandas as pd import random dat = pd.read_csv("../../data/11M_dataset.csv") all_ref_tcrs = [] for i in range(len(dat)): tcr = dat["junction_aa"][i] all_ref_tcrs.append(tcr) def get_all_pos(filename, epi): all_pos = [] f = open(filename, 'r') for line in f: ...
0d5f5ae1c3b5622081e7248a16391f2ecacf6831c78a3b98ab17a453bdec6d39
Python
1,573
36
from pathlib import Path DOCS_DIR = Path('docs/source') USER_GUIDE = DOCS_DIR / 'user_guide.rst' GUI_GUIDE = DOCS_DIR / 'user_guide_gui.rst' def test_user_guide_examples_use_current_api_names_and_paths(): # The guides contain non-ASCII characters (e.g. Polars table-repr box-drawing glyphs), so the # encoding...
97e09c81e2bebb8ab11b2bc2de20df99c4157989655a8bb2599a36e9fe5e16d0
Python
1,573
39
# niceumap import scanpy as sc import datamapplot from anndata.experimental import concat_on_disk from umap import UMAP import os name = "o2uniqsx" # Assuming the data files are in the "./data/" directory data_directory = "./data/" file_list = os.listdir(data_directory) ## Filter out only the files with the 'h5ad' ...
39df0493b99aed8e3442b90a7c0d809c29de8b225b4200c9fb6aaabd5d89568b
Python
1,574
49
import logging import os import anndata import numpy as np from scvi.data._download import _download logger = logging.getLogger(__name__) def _load_breast_cancer_dataset(save_path: str = "data/"): save_path = os.path.abspath(save_path) url = "https://exampledata.scverse.org/scvi-tools/Layer2_BC_count_matri...
59bac7e2aaae78bb307346773f26c0edecfd7435cfc702569a2f5c5c4bf8af18
Python
1,575
65
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Name: Robert Kim # Date: October 11, 2019 # Email: robert.f.kim@gmail.com # Description: Contains several general-purpose utility functions import os import tensorflow as tf if tf.__version__[0] == '2': import tensorflow.compat.v1 as tf tf.dis...
1cc77eac999fdd36de546160761894c17b6b341b2dde82fcfb70e9db541345a2
Python
1,576
35
# Source code: # https://github.com/zbmed-semtec/doc2vec-doc-relevance-training/blob/main/code/train_model/train.py # This file includes the modifications to the source codes according to this project! import os import time import logging import utilities as utilities def run(best_params, args): # 1) Load t...
7147e6ef8d1294c0736ebc05813e5fb44eff4c8e1c01ae2284685301bce57819
Python
1,577
46
import unittest from unittest.mock import patch from pyecharts import options as opts from pyecharts.charts import Grid, Liquid from pyecharts.commons.utils import JsCode class TestLiquidChart(unittest.TestCase): @patch("pyecharts.render.engine.write_utf8_html_file") def test_liquid_base(self, fake_writer): ...
dbcfb1c48bc16784e62b4add0e9c48081d030b8bb57f2fcc8622fcb137aea7bb
Python
1,577
52
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import json from dataclasses import dataclass from typing import Sequence import numpy as np from emmet.core.material import PropertyOrigin from mattergen.common.utils.globals import PROPERTY_SOURCE_IDS PropertySourceId = str TargetProperty = ...
06361a48682c83599fe4572c5ee7d3511f3e57194315ada5dec4024a42fc4d31
Python
1,578
32
import matplotlib.pyplot as plt import numpy as np plt.style.use(['science','nature']) x_ax = np.load('noisesw_x.npy')*100 y_ax = np.load('noisesw_y.npy')*100 # y2_ax = np.load('ideal_quant_y.npy') hline = np.load('noisesw_single.npy')*100 hline2 = np.load('noisesw_d2d.npy')*100 # hline2 = np.array([94.275,94.037,94....
3a1800b5f33347a18f5ebdd17d7c2a8344d8a8a159989e6e5a0f78a450a3f80d
Python
1,578
49
""" """ from __future__ import annotations import torch from .. import metrics, nets from .decorator import model from .frame_classification_model import FrameClassificationModel @model(family=FrameClassificationModel) class ED_TCN: """Encoder-Decoder Temporal Convolutional Network model for the frame clas...
b55a152b202038830bcb86fb03117c51d2ac6a5869cfe30239e9eee8e4a8a4b4
Python
1,578
60
from importlib import metadata, util import pytest @pytest.mark.parametrize( "module", ( "gpn.ss.filter_assemblies", "gpn.ss.finetune", "gpn.ss.train_tokenizer_ss", ), ) def test_archived_dataset_and_finetuning_modules_are_not_packaged(module): assert util.find_spec(module) is...
b81b52f45dd292f9309c7e4d75511ced4adf58a5500810cd36a4df60a8f66da7
Python
1,578
50
import pickle import numpy as np def save_dict2pkl(fn,data_dict): with open(fn, 'wb') as f: pickle.dump(data_dict, f) f.close() return fn def load_pkl2dict(fn): with open(fn, 'rb') as f: loaded_dict = pickle.load(f) f.close() return loaded_dict def find_video_name(f...
72f486a9b82618b8e61904b4c455bd4ce5e63f726239a35c72d9410d40f1586b
Python
1,579
56
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from poetry.core.packages.package import Package from poetry.repositories import RepositoryPool class VersionSelector: def __init__(self, pool: RepositoryPool) -> None: self._pool = pool def find_best_ca...
f913cf3bd8e384eb4769a633203a4309cbc3364115695fc875223f0145bc807c
Python
1,579
40
"""Cross-session CV scorers and score-mode dispatch (kfold / loso / pairwise).""" import numpy as np import pytest from crossda.pipelines.scoring import score_session_cv, _normalize_score_mode from crossda.pipelines.pipeline_utils import ( extract_features_train, extract_features_test, get_classifier, ) ...
ff8c0540825e0fa38cd88cae7573ac21311b809bd496ebea4c5983a38f094871
Python
1,581
55
import sys,getopt,random,subprocess import pandas as pd try: opts, args = getopt.getopt(sys.argv[1:],"hi:o:w:b:",["ifile=","ofile="]) except getopt.GetoptError: print ('windows_MBB.py -i <input csv file> -o <output> -w <window size> -b <block size>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('wind...
7f493872293ec72be481d008e409691a4abcb1d06563eaaa5aa253855116929a
Python
1,585
57
#!/usr/bin/env python # Author_and_contribution: Niklas Mueller-Boetticher; created script import argparse parser = argparse.ArgumentParser( description="Calculate Adjusted Rand Index (scikit-learn)" ) parser.add_argument( "-l", "--labels", help="Labels from domain clustering.", required=True ) parser.add_a...
fc1eb1533e89738843e4306eb365a6ed350c69fbc500e8ba051a048c8303c6f1
Python
1,585
46
import pandas as pd import matplotlib.pyplot as plt import os import ast target_folder = "foldername" # specify folder name in "param_estimation_result" path_base = os.path.join("param_search", "param_estimation_result", target_folder) # Get a SEED_num filename = os.path.join(path_base, "hyperparams.csv") df = pd.rea...
6a81d3d918911ada56cdf529ea9585aaa8c73c12e2eab031f62c616a8c29f0de
Python
1,586
42
from __future__ import annotations import numpy as np from sklearn.neighbors import NearestNeighbors def knn_indices(coords: np.ndarray, k: int) -> np.ndarray: """Return k nearest neighbor indices for each coordinate row.""" coords = np.asarray(coords, dtype=float) if coords.ndim != 2: raise Valu...
cdbd4dfbbfc3c462a635c75699412f2ea16cb929cea712db9adaa249d6b37687
Python
1,586
65
""" Simulated expression dataset script For a complete documentatio please see https://github.com/PMBio/peer/wiki/ """ import sys import scipy as SP def simulate_data(N,K,sigma): X = SP.random.randn(N,K) W = SP.random.randn(K,G) Y = SP.dot(X,W) #simulate mean effect #mean = SP.rand(N) Y += Y #add noise Y+= s...
f022b1d4d9067b428327a794f90caf6a6278337a9e5b54b7877f3cc9c30f1de8
Python
1,587
63
from multiprocessing import Pool import copy import argparse from process_pretrain_data import Process # filenames = ['xaa', 'xab', 'xac', 'xad', 'xae', 'xaf', 'xag', 'xah', 'xai', 'xaj', 'xak', 'xal', 'xam', 'xan', 'xao', 'xap', 'xaq', 'xar', 'xas', 'xat', 'xau', 'xav', 'xaw'] # filenames = ['xaa', 'xab'] def main(...
28ea1778b2848c086f070397c00e7626d1b53e62b971a044c844abd89ee768f4
Python
1,588
38
"""Various methods to estimating if a GO term is more specific than another GO term.""" __copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" def get_most_specific_dcnt(goids, go2nt): """Get the GO ID with the lowest descendants count.""" # go...
3d0607fa94f01f83de313977110cde8310afe4772c4f6583aa0345dff63368ac
Python
1,588
54
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from typing import Protocol, Sequence import torch from pymatgen.core import Composition from mattergen.common.data.chemgraph import ChemGraph from mattergen.common.utils.data_utils import ( compute_lattice_polar_decomposition, get_elem...
bac2fe5e645c561579af13522313ae7636f1de1b21615e4fc77d15d42d0ddbb6
Python
1,588
48
import numpy as np def Ent_Symbolic(X, L): """ SymEnt = Ent_Symbolic20180320(X, L) symbolicEnt Calculates the Symbolic Entropy for given data. Input - X: 1-Dimensional binary array of data L: Word length Output - NCSE: Normalized Corrected Shannon Entropy Remarks - This cod...
a71fe58963db71742a021bc0817cf04dca5df04775d5368e6961426bbc879c62
Python
1,592
42
# Copyright 2020 The TensorStore Authors # # 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 agreed to...
b80116d12f8b1f05ab215f68ade9ed8a0c5b7b1c58697cadc80225975ce96d15
Python
1,592
70
#!/usr/bin/python # Copyright (c) 2014 Kyle Lutz <kyle.r.lutz@gmail.com> # Distributed under the Boost Software License, Version 1.0 # See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt # # See http://boostorg.github.com/compute for more information. import os import sys import py...
dde087850923727af051b90e7ce33b0e42df4de5dd2e386f512771dbf792a230
Python
1,593
46
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from anndata import AnnData from .. import utils from ._utils import get_categorical_color_palette def domains_proportions( adata: AnnData | list[AnnData], obs_key: str | None = None, slide_name_key: str | None = None, figsize:...
93d324b74961696cc7eec94ab7d1d0a85cb4982a6a31972cad394a17aaf704bb
Python
1,594
33
import torch from nnunetv2.training.loss.deep_supervision import DeepSupervisionWrapper from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer from nnunetv2.training.loss.robust_ce_loss import RobustCrossEntropyLoss import numpy as np class nnUNetTrainerCELoss(nnUNetTrainer): def _build_loss(self...
30ac3a7000be5b15cf9285c216a14dfdeedf842a4cda7b2a039a21908d75487c
Python
1,595
41
""" session_roles.py — shared schema for the per-session provenance table. Each pipeline emits a flat list of role rows with a fixed schema: stage, local_idx, session_abs_idx, session_label, role, is_best, weight, plus five distance fields. The per-stage role assignment is genuinely family-specific and stays in each p...
c3994502e2b3f687fd39bf89c3f126564b1ffc3c15342d32b9db6621d36dafd7
Python
1,595
47
"""Wrappers around standard library multiprocessing executors.""" import concurrent.futures import multiprocessing import threading class _Executor(object): def submit(self, fn, *args, **kwargs): self.semaphore.acquire() future = super().submit(fn, *args, **kwargs) future.add_done_callbac...
fa9f2bd87bd3c16194dc185c595b308edf30014c69b02470b9b508e36a586f72
Python
1,596
54
"""Validators for frame classification datasets""" from __future__ import annotations import pandas as pd def validate_and_get_frame_dur( dataset_df: pd.DataFrame, input_type: str ) -> float: """Validate that there is a single, unique value for the frame duration for all samples (audio signals / spectro...
728415b2a0850e4a2fb223d152864127087c03204c02aeb865e07d914229a5bd
Python
1,598
39
from mdt import CompartmentTemplate, FreeParameterTemplate from mdt.model_building.parameter_functions.transformations import ScaleTransform __author__ = 'Robbert Harms' __date__ = "2015-06-21" __maintainer__ = "Robbert Harms" __email__ = "robbert@xkls.nl" class TimeDependentZeppelin(CompartmentTemplate): """Imp...
a6dfbda03328bbf7d2832c4ece185abda180b58cb32006e0a424d5c2b459f2ac
Python
1,598
37
# totalseg_interface.py import os, shutil, subprocess, sys class TotalSegInterface: def __init__(self, exe_name=None): candidates = [] scripts_dir = os.path.dirname(sys.executable) # 例: ...\Python312 scripts_dir = os.path.join(scripts_dir, "Scripts") candidates += [ exe...
b82b33dfef527d5211668a27974aee7c884647828793269c29a95893c384c9f6
Python
1,598
49
import matplotlib.pyplot as plt import numpy as np import seaborn as sns from anndata import AnnData from .._constants import Keys def get_categorical_color_palette( adatas: list[AnnData], obs_key: str, palette: str | None = None ) -> tuple[list[str], list[str]]: key_added = f"{obs_key}_colors" all_doma...
ca99f6d1b4dd02577cee12e659997d438f917c93a95666eab91f65b37a23fd48
Python
1,598
37
"""Run Simulation preprocess before training when required by config or empty outputs.""" from __future__ import annotations from omegaconf import DictConfig, OmegaConf from pytorch_lightning.utilities.rank_zero import rank_zero_info from datasets.preprocess.gate import ( Simulation_both_output_dirs_empt...
eeba6a6c48e8ac5176520a4150834b4a805f1ff423a0ac5568fe90f9dac6b505
Python
1,598
41
import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm samples = 10000 val=np.random.multivariate_normal((4, 4), [[5, 3.3],[3.3, 5]], samples) draw_1, draw_2 = np.zeros(samples), np.zeros(samples) for i in tqdm(range(samples)): # chasing rank draw_1[i] = np.argmax(np.random.multinomial(1, [6...
8ed0fc60893d29443b2d9e12641f791d3f8c9f8d218464012f213a96c9b211c2
Python
1,599
35
from nnunetv2.training.data_augmentation.compute_initial_patch_size import get_patch_size from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer import numpy as np class nnUNetTrainer_noDummy2DDA(nnUNetTrainer): def configure_rotation_dummyDA_mirroring_and_inital_patch_size(self): do_dumm...
11449e14920c46cda386f76679097c66d719b46a85032dae748bfd753c4e6d6f
Python
1,600
49
"""Set a random seed.""" __copyright__ = "Copyright (C) 2015-present, DV Klopfenstein, Haibao Tang. All rights reserved." __author__ = "DV Klopfenstein" import sys import numpy as np class RandomSeed32: """Manage a random seed.""" def __init__(self, seed=None): self.max_val = int("0xffffffff", 0) ...
344324ecda923a60ea6db1ee1d7525048a1fbd926488ed3f1f0dd4c2add44eb4
Python
1,600
39
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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 cop...
6659cdb966eb937ea91b0b9acab2a23a869347e9e425b1ff40061df6e33b4762
Python
1,600
50
import itertools import networkx as nx import numpy as np import pandas as pd from reactome import Reactome, ReactomeNetwork reactome = Reactome() names_df = reactome.pathway_names hierarchy_df = reactome.hierarchy genes_df = reactome.pathway_genes print (names_df.head()) print (hierarchy_df.head()) print (genes_df....
c25ba14840d6ef8f858ca0deb5d5f13e1a72ff8112375a44bbbd60e7d6b337d9
Python
1,600
66
import sys ROOT_DIR = __file__.rsplit("/", 2)[0] if ROOT_DIR not in sys.path: sys.path.append(ROOT_DIR) import os import multiprocessing as mp import time from utils.server_tool import check_port_in_use BASE_DIR = os.path.dirname(__file__) def system_call(cmd: str): os.system(cmd) def start_process(cmd:...
c476aa9ea0225f366ef70d618aca11bf1dee994d5799e05915750f061fac35bf
Python
1,600
51
"""Local Zarr alignment access for deprecated GPN-MSA inference.""" from typing import Any import numpy as np import zarr from gpn.data import ReverseComplementer, Tokenizer, slice_alignment class GenomeMSA: def __init__( self, path: str, subset_chroms: list[str] | None = None, ...
c7efd87da91925daf86e4dfeb1802f5a9628861c32ad2557f3d72899da1b3ac3
Python
1,600
42
from typing import Union, Optional from pathlib import Path import pandas as pd from sklearn.model_selection import KFold DATASETS = ['Muscle', 'pc3', 'HEK'] def prepare_te_and_el_data( data_root: Optional[Union[Path, str]], kfold_splits: int = 10 ): data_root = Path(data_root) for dataset in DATASE...
425e6e09bac879d890a5c76b85333522e0949085db330a6560da6cbf7f0acc75
Python
1,601
40
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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 cop...
ffec7f2a70b99863a58e466b54e617b5002369b0f1948a1f538a6327748187a8
Python
1,602
45
import sys sys.path.append("/lustre/home/mlang/2D_Structure_ENV/lib/python3.9/site-packages") sys.path.append("/lustre/software/anaconda/anaconda3-2019.10-py37/lib/python3.7/site-packages/") import numpy as np from Bio import SeqIO import re from pathlib import Path def get_chain_sequence(fasta_file): """ inpu...
a81c076053a4d61ec77ded5a2ba7d746c1800c7f40df8cc0e80f91c2c619f979
Python
1,604
39
"""Loss functions shared by GPN-SS and GPN-MSA.""" from jaxtyping import Float, Int from torch import Tensor from torch.nn import CrossEntropyLoss def masked_lm_loss( logits: Float[Tensor, "... vocabulary"], labels: Int[Tensor, "..."] | None, output_probs: Float[Tensor, "... vocabulary"] | None, loss...
70bdb4a8d7a56841f37d2c6dd4edab4c12a51e6d695f12c27102de119ac25726
Python
1,605
62
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from glob import glob from vlpp.utils import save_json from jinja2 import Environment, FileSystemLoader from vlpp.qamosaic import Mosaic def main(): # Usefull directories os.mkdir("data") # Informations participant_id = "${sub.sub}" # I...
11052400b087d233106872adfa8b63d135ed0d409b3a3acc6d0bc60bc4a9b8ea
Python
1,607
62
from __future__ import annotations import os import re from typing import TYPE_CHECKING from anndata import read_h5ad from scvi.utils import dependencies if TYPE_CHECKING: from anndata import AnnData def _parse_dataset_id(url: str): match = re.search(r"/e/(.+)", url) if match: return match.gro...
5690da9e5b40501c959602e1d59f999bd6a85df11ab8020674ff824b57da6178
Python
1,608
57
from __future__ import annotations from typing import TYPE_CHECKING from torch.distributions import Normal as NormalTorch if TYPE_CHECKING: import torch class Normal(NormalTorch): """Normal distribution. Parameters ---------- mu loc of the Normal distribution. scale scale o...
a2f8af8f5184e11a9addcc1c133671d41ea6a24f5adc0e1ed40ee0996eea4d62
Python
1,608
45
""" The test below was taken from the sima package http://www.losonczylab.org/sima version 1.3.0 https://github.com/losonczylab/sima/blob/6d2cd4f071e4/sima/tests/test_ROI.py License ------- This file is Copyright (C) 2014 The Trustees of Columbia University in the City of New York. This program is free software; you...
0821f377be40a5fab85f5d6f1293fa10c457924ad161bbecf59d5cf15ed9abb4
Python
1,609
51
from ... import options as opts from ... import types from ...charts.chart import Chart3D from ...globals import ChartType from ...options import InitOpts, RenderOpts class GraphGL(Chart3D): """ <<< GraphGL Relational graphs using WebGL to support the layout and drawing of large-scale network/relational d...
67b9ac989dbc00cd82bd9ee5f869d0fe1a39edfc71aa9ddda1e3d4115eec02ee
Python
1,610
40
# import sys # sys.path.append('tacotron2') import torch from .layers import STFT class Denoiser(torch.nn.Module): """ Removes model bias from audio produced with waveglow """ def __init__(self, waveglow, filter_length=1024, n_overlap=4, win_length=1024, mode='zeros'): super(Denoiser...
960209fe08f93c79f71754782a982ab98b10aae9f57aac6b0c9e77cc5e119afa
Python
1,610
30
import matplotlib.pyplot as plt import numpy as np plt.style.use(['science','nature']) x_ax = np.load('inf_comp_x.npy') y_ax = (1-np.load('inf_sotmram_y.npy'))*100 y2_ax = (1-np.load('inf_rram_y.npy'))*100 hline = (1-np.load('./accs_saved/ecram_runs/LeNet5_ecram8bit_accs.npy'))*100 hline2 = (1-np.load('./accs_saved/e...
961b81ba54dd91f68106427a94d8172537e7d814f7bfe418d461ecdb97806d06
Python
1,610
64
# Copyright 2022 InstaDeep Ltd # # Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://creativecommons.org/licenses/by-nc-sa/4.0/ # # Unless required by applicable law or a...
bbbeb8b13bfc4dcc2e8a3e92f3f5d7773d86b7165524f9658a8ec659c024e7ad
Python
1,610
46
import torch @torch.jit.script def gaussian(x, mean, std): pi = 3.14159 a = (2*pi) ** 0.5 return torch.exp(-0.5 * (((x - mean) / std) ** 2)) / (a * std) # From Graphormer class GaussianRadialBasisLayer(torch.nn.Module): def __init__(self, num_basis, cutoff): super().__init__() self.n...
2389bcb71a777b7da2d3719b2eba8526307fa779a131a384f8238ec260ce07b2
Python
1,611
53
import itertools import pytest import vak LABELSETS = [] for labelset in ( 'abcde', '12345', [1, 2, 3, 4, 5], 'mo', 'po', 'ta', ): LABELSETS.append( vak.common.converters.labelset_to_set(labelset) ) LABELMAPS = [] for labelset in LABELSETS: LABELMAPS.append( vak.common.la...
6fd87cc0d66da86ed77f59354c99524858efef236845629616ec610d4cbc5182
Python
1,612
59
import numpy as np import matplotlib.pyplot as plt # plots 4D data as a 3D scatter plot def plot4D(data, cmap="Reds", dpi=500, save_name=False, logartihmic=False): print(f'(max, min)=({np.min(data)}, {np.max(data)})') data += np.abs(np.min(data)) ...
a2a287191585872d8e56f4940312959014803ecf122180c7d960d6844fabda37
Python
1,612
48
import time import RPi.GPIO as GPIO class mainprogram: # Main while loop condition keepalive = True # DEFINE NUMBER OF BUTTONS AND ORDER IN ARRAY # setup GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # DEFINE EMERGENCY STOP and hard wired buttons #testA = 26 testB = 14 ...
bb8452875c303c676560edde5ddf49e17a6c591924af096f55a7e4205e9deb62
Python
1,612
63
from __future__ import annotations from typing import TYPE_CHECKING import pytest from cleo.testers.application_tester import ApplicationTester from poetry.console.application import Application if TYPE_CHECKING: from tests.types import CommandFactory @pytest.fixture def tester() -> ApplicationTester: r...
dfa1b30e6da09bb25f7c1c05c9d5f41a4a26799f8b250b87f0d187c4373b286c
Python
1,612
43
# Copyright 2023 BioMap (Beijing) Intelligence Technology Limited import torch import torch.nn as nn import torch.nn.functional as F class pytorchTransformerModule(nn.Module): def __init__(self, max_seq_len, dim, depth, heads, f...
1a42e02d1191d23f393b2463d2205c3597c86ddd8d790ef934a5339321b19fdd
Python
1,614
46
import ast import pathlib import pytest import scvi _SRC = pathlib.Path(scvi.__file__).parent def _find_noop_warning_statements(): """Return ``file:lineno`` for every bare ``*Warning(...)`` statement in the source. A statement such as ``Warning("msg")`` merely constructs a warning object and immediate...
6aaa498f99738a6f6545f9105cd2f39472d024cc1f84875a87376a5f49257009
Python
1,614
23
from predify.modules import PCoderN from predify.networks import PNetSeparateHP from torch.nn import Sequential, ReLU, ConvTranspose2d class PVGG16SeparateHP(PNetSeparateHP): def __init__(self, backbone, build_graph=False, random_init=False, ff_multiplier=(0.3,0.4), fb_multiplier=(0.3,0.0), er_multiplier=(0.01,0.0...
39306cac52231b77299fc985bd8b358ac66f791b43fc92ccc514363b05290155
Python
1,615
27
"""Internal functions for file manipulation.""" import datetime import h5py import bpreveal from bpreveal import logUtils def addH5Metadata(h5fp: h5py.File, **kwargs: str) -> None: """Adds some metadata to your hdf5 file for reproducibility. :param h5fp: The opened hdf5 file that you want to add metadata to....
693b3c04364c3b8db1e0f07110d425bb4d34d6920d11c42f13cd99872a8e374b
Python
1,615
56
#!/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...
44570eb9e73005c290c9b86e01e5a4dd98022ddc7b282f0a15394ac59c3af377
Python
1,616
59
from __future__ import annotations from typing import TYPE_CHECKING from typing import ClassVar from cleo.helpers import argument from poetry.console.commands.command import Command if TYPE_CHECKING: from cleo.io.inputs.argument import Argument class SearchCommand(Command): name = "search" descriptio...
d6a91a05e60395244fdcd8100ecbefee755db81e2530c7c22cab4b4d0ef6d946
Python
1,616
23
from predify.modules import PCoderN from predify.networks import PNetSeparateHP from torch.nn import Sequential, ReLU, ConvTranspose2d class PVGG16SeparateHP(PNetSeparateHP): def __init__(self, backbone, build_graph=False, random_init=False, ff_multiplier=(0.35,0.4), fb_multiplier=(0.25,0.0), er_multiplier=(0.01,0...
ec12c264a74938063fb9be79721a8b55cc9078bfd4fc5a9620251e9ce364f9f9
Python
1,616
54
#!/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. """ Split a large file into shards while respecting document boundaries. Documents should be separated by a single empty...
20e867b64324a61082754e589d1d8e59a6df28d359f59eb314d8d6619b69a711
Python
1,617
59
from __future__ import annotations import pytest from tomlkit.container import Container from tomlkit.items import Table from tomlkit.items import Trivia from poetry.config.source import Source from poetry.repositories.repository_pool import Priority @pytest.mark.parametrize( "source,table_body", [ ...
5b9a863dde28423cb78a5792036fbeeb1963e7c756627b610959e9b9d4647eb3
Python
1,617
54
import numpy as np import pylab as plt import skfmm X, Y = np.meshgrid(np.linspace(-1,1,201), np.linspace(-1,1,201)) phi = -1*np.ones_like(X) phi[X>-0.5] = 1 phi[np.logical_and(np.abs(Y)<0.25, X>-0.75)] = 1 plt.contour(X, Y, phi,[0], linewidths=(3), colors='black') plt.title('Boundary location: the zero contour of ph...
5ffb7596687eadb88e9e48415cdf37bccf2459963cd9e05038ffe2142716cb14
Python
1,617
34
#!/usr/bin/env python import polars as pl def read_gtf(file, attributes=["transcript_id"], keep_attributes=True): if keep_attributes: return pl.read_csv(file, separator="\t", comment_prefix="#", schema_overrides = {"seqname": pl.String}, has_header = False, new_columns=["seqname","source","feature","start"...
003f64ce26c296455cbc31a2c578361a1d26984a50b0179e9d0adb851322aca3
Python
1,618
48
"""Experiment directory layout helpers (DLBase-style four segments for future task routing).""" from __future__ import annotations import os from typing import Any, Dict, Optional def tensorboard_log_dir(net_sub_path: str) -> str: """TensorBoard event files under the run leaf, matching common DLBase la...
4001e19758aeea466977d1fc47997b4a2b5fcb8b06ba7e5d835ff7466031e14f
Python
1,618
55
# encoding: utf-8 """ @author: Jiayang Chen @contact: yjcmydkzgj@gmail.com """ import numpy as np def record_item(summary_writer, tag, item, step): if isinstance(item, int) or isinstance(item, float): # scalar summary_writer.add_scalar(tag, item, step) elif isinstance(item, dict): # sc...
89602962a80be5937196c18fb54d47d048c11fb94239eb9290db6c3a4127b1d2
Python
1,618
50
from __future__ import annotations import os import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if ROOT not in sys.path: sys.path.insert(0, ROOT) from gpu_runtime import ( # noqa: E402 compatibility_result, get_cuda_diagnostics, get_optional_attention_status, ) def main...
ef649dafa06dbd92c29bb6033f146258472edaa7d00f3ab5d8b37ef1c7c77d1e
Python
1,618
67
from pgmpy.datasets._base import BaseDataset class StudentPerformance(BaseDataset): """ References ---------- - :footcite:t:`uci_student_performance` """ _tags = { "name": "student_performance", "n_variables": 33, "n_samples": 395, "has_ground_truth": False, ...
2c2f937bdc242526a791579853bfae933d90deb422ff5cc4aeedf2ff829b35d5
Python
1,619
48
"""Regression test for `update_pmc_open` opening the document database.""" import asyncio from tinydb import TinyDB from tinydb.storages import JSONStorage from scripts import update_pmc_open class _FakeNCBI: """Stands in for `AsyncNCBIAdapter`; no network involved.""" async def __aenter__(self) -> "_Fake...
85ec1b2c68826649b44b62d95e7801e32aeab47c1df662cb963395419d383cc8
Python
1,619
50
from HierarchiaPy import Hierarchia import matplotlib.pyplot as plt import numpy as np import igraph as ig import networkx as nx import pandas as pd import os import sys import pandas as pd import seaborn as sns from scipy.stats import ttest_ind from weighted_rc import weighted_rich_club sys.path.append('..\\src\\') fr...
463b3213d04eb1d4acdb4763b10ed71754429621ddf085b0a454161349735f98
Python
1,621
47
import pytest import vak.metrics.distance.functional LEV_PARAMETRIZE = [ # adapted from https://github.com/toastdriven/pylev/blob/master/tests.py ("kitten", "sitting", 3), ("kitten", "kitten", 0), ("", "", 0), ("kitten", "", 6), ("", "sitting", 7), ("meilenstein", "levenshtein", 4), (...
4c7b7932d693c2424918778ace8ba530d7d76e74625f379c0b7e1fb57bf9b9db
Python
1,623
55
""" """ """ Copyright (c) 2019, 2022 [copyright holders here] This file is part of NoSeMaze. NoSeMaze is free software: you can redistribute it and/or modify it under the terms of GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) at any l...
a2e49627238b43719e0031483c1b3e4bd192f3a8d8e632ed2128cdc89f90c43f
Python
1,623
63
from enum import Enum from typing import Dict, List, Optional, Sequence import torch from fairseq.data import Dictionary class EncoderLangtok(Enum): """ Prepend to the beginning of source sentence either the source or target language token. (src/tgt). """ src = "src" tgt = "tgt" class Lang...
c370d1decf9522ed2b42b830c2ada46519ad2d13f5ac1ee6b093e8171a45116b
Python
1,624
58
# 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 Any, Dict from fairseq.distributed import utils try: from fairscale.optim import OSS _has_fairscale = True exce...
d2d79a74d80e33711eb02ba8d7ff763be9edb0168e9b4e6b217784bbe5ed413d
Python
1,625
14
# utils/__init__.py from .file_utils import get_directories, read_batch, get_file_data_by_index, get_display_data, save_seg_class_recfile, get_files_for_day, get_files_for_experiment, get_files_for_bird, filter_segmented_files, filter_classified_files, save_features, remove_pkl_suffix, find_batch_files, create_batch_f...
920f051c0abe171333a5c00362ad31fd04965377d0a7bbb77b289fb97bb36399
Python
1,626
55
import numpy as np from src.dfer.df_plots import mpl_options_figure, mpl_results_figure def test_mpl_single_options_figure_renders_all_five_rows(): trace = np.arange(4, dtype=float) data = { "file_type": "single", "t_min": trace, "smooth_465": trace, **{f"smooth_adj_{index}": ...
e0e68bc874c3575c1b095ae36294b08f0ea0d0e05af0ed3d1348c404ddf2734c
Python
1,627
56
""" hippie-wf3dacg =========== Conditional VAE with NEMO's feature representations (90-sample waveform MLP + 3D ACG convolutional encoder) fused with HIPPIE's conditioning framework (source, super_region, technology, layer, decoder-only class label). Public API: HippieWF3DACGConfig — hyperparameter dataclas...
a91cde5c05cd37c36602d0735fe9de88d7cdb254c3f4313edd9e867d665a23d5
Python
1,628
71
from matplotlib import pyplot as plt from figure_1 import figure_1, figure_1_d_auc_prc, figure_1_e_confusion_matrix from figure_2 import figure_2, figure_2_a_pnet_vs_dense, figure_2_b_external_validation, figure_2_c_survival from figure_3 import prepare_data, figure_3_sankey, figure3_b_gene_importance, figure3_c_activ...
ceca0c72f21873719a1a7c9b51eb8fac87ce2723b450e362273020a724c53df2
Python
1,629
37
import pytest import torch import vak class TestConvEncoderUMAP: @pytest.mark.parametrize( 'input_shape', [ (1, 32, 32), (1, 64, 64), ] ) def test_from_instances(self, input_shape): network = { 'encoder': vak.models.ConvEncoderUMAP.defin...
3a4545b8b1ae04141b3c1cabf0b4fd5fddc47c3f05ebe71690e501f4b7d621d1
Python
1,630
49
from pgmpy.base import DAG from pgmpy.metrics import BaseUnsupervisedMetric from pgmpy.structure_score import get_scoring_method class StructureScore(BaseUnsupervisedMetric): """ Uses the standard model scoring methods to give a score for each structure. The score doesn't have very straight forward interp...
b09817c07d5902089a139a3e6f0555ca55841a0289e3a5b67b546961de8c14ff
Python
1,630
59
# @license # Copyright 2017 Google Inc. # 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 agreed to in...
3ba63d9c82448b44b741724706df5541034b19954889e86aee7205617019ce45
Python
1,631
33
"""Unit tests for the CI test-tier auto-classification in conftest.py (`_tier_markers_for`).""" import pytest from tests.conftest import _tier_markers_for @pytest.mark.parametrize( 'module,fixturenames,availability_skip,expected', [ # GUI modules and any qtbot-using test -> e2e ('test_gui', ...
f1c300c80e9994533317b263cb15207ef33593a1b84718a1b3ee2bfc4616f2b0
Python
1,632
64
from __future__ import annotations from typing import TYPE_CHECKING import dulwich.repo import pytest from tests.vcs.git.git_fixture import TempRepoFixture if TYPE_CHECKING: from pathlib import Path @pytest.fixture() def temp_repo(tmp_path: Path) -> TempRepoFixture: """Temporary repository with 2 commits...
80ea7df95cb60c89712ee53f11414a5b9342efe265d68e0c757d2fdee1d9d797
Python
1,633
42
"""Compare two or more sets of GO IDs. Best done using sections.""" from __future__ import print_function __copyright__ = "Copyright (C) 2016-2019, DV Klopfenstein, H Tang. All rights reserved." __author__ = "DV Klopfenstein" from goatools.grouper.read_goids import read_sections from goatools.grouper.grprdflts impo...
d3e1cbca13a5b5fec687a32a4e8300752df793ebdd1193dae461fb1ceeda6364
Python
1,633
32
import re from pathlib import Path import pytest DOCS_SOURCE = Path(__file__).resolve().parent.parent / 'docs' / 'source' # Since the v4.0 migration off pandas, RNAlysis returns polars objects (see issue #100). The # hand-written user guides must not describe function outputs or underlying data structures as # panda...
710c3c8a7c8500a5ae0c6b48ae7200be3a891c710ca51fff28f9c70753d41bbc
Python
1,634
58
import warnings from scvi import settings from scvi.utils import error_on_missing_dependencies from ._archesmixin import ArchesMixin from ._base_model import ( BaseMinifiedModeModelClass, BaseModelClass, BaseMudataMinifiedModeModelClass, ) from ._differential import DifferentialComputation from ._embeddin...
fcddc5a6e64641cbf178acd0d415d52934a22a229a7eab8db7dcf7bd7cf20603
Python
1,635
59
from selenium.webdriver.common.by import By rec.begin( { "layers": [ { "type": "image", "source": "precomputed://gs://neuroglancer-public-data/flyem_fib-25/image", "tab": "source", "name": "image", } ], ...
18a41c7955454603303f5a9e5643cab13a1716b990a5d9cf4577284d7a1632ac
Python
1,636
68
from anndata import read_h5ad from anndata.io import read_csv, read_loom, read_text from ._anntorchdataset import AnnTorchDataset from ._datasets import ( annotation_simulation, brainlarge_dataset, breast_cancer_dataset, cellxgene, cortex, dataset_10x, frontalcortex_dropseq, heart_cell_...
a77bcdbe33e436a369510189bd793d996b3687b24b3c8cf8bd8f807bb8c5f88b
Python
1,636
49
from typing import Union import numpy as np import scipy.sparse as sparse from tqdm import tqdm import loompy class NeighborhoodEnrichment: def __init__(self, epsilon: float = 0.1) -> None: self.epsilon = epsilon def fit(self, X: np.ndarray, knn: sparse.csr_matrix, k: int) -> np.ndarray: """ Args: X ...
1443c8aaa696fb97006b875d59c5c3020b0eb36b7c3deff7ee7604801f3fa518
Python
1,637
63
#!/usr/bin/env python # Made by Paul Kiessling pakiessling@ukaachen.de import os import argparse import tempfile import shutil from pypdl import Downloader LINKS = { "https://zenodo.org/records/13944111/files/concordex_sim.zip":"fb7c79fd9cec2c79e3b74fb50be40ff4" } def download_links(links, temp_dir): head...
1bce28dc8eb54b28cf32bc48947d64a4119ff95b38378ba44463c1b5f438fbe8
Python
1,637
54
import uuid from jinja2 import Environment from ... import types from ...charts.basic_charts.map import MapMixin from ...charts.chart import Chart3D from ...commons import utils from ...globals import CurrentConfig, NotebookType from ...options import InitOpts, RenderOpts from ...render.display import HTML from ...re...
f5dc6bf0ebda564707341de1bc816e3b7924bd9bbba9867675dd2e674aebd42e
Python
1,637
35
from typing import Union, Tuple, List import numpy as np from batchgeneratorsv2.helpers.scalar_type import RandomScalar from batchgeneratorsv2.transforms.base.basic_transform import BasicTransform from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer class nnUNetTrainerNoDA(nnUNetTrainer): @st...