sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
35904f15d53bd9fe5748625b127f05d8b93b5cc94b4f6f1d3c0e378d01d22732
Python
4,203
116
import importlib.resources from PyQt6 import uic, QtWidgets, QtCore, QtGui from ... import meta_tool from ... import pipeline class MatrixDataset(QtWidgets.QWidget): active_toggled = QtCore.pyqtSignal() enabled_toggled = QtCore.pyqtSignal(bool) option_action = QtCore.pyqtSignal(str) modify_clicked =...
38dfe0fd7fd407a31025b4d102bb06bf9bc5152e792f021697580cd7b7c2c213
Python
4,204
121
"""Tests for Rearrange Operator.""" from collections.abc import Sequence import pytest import torch from mrpro.operators.PatchOp import PatchOp from mrpro.utils import RandomGenerator from tests import autodiff_test, dotproduct_adjointness_test TESTCASES = pytest.mark.parametrize( ('input_shape', 'arguments', '...
eb9586a8cf2f6502929198ff5ecf9de7ef83c1e5af0a3d0d28e2c9f6f4c9530f
Python
4,206
129
''' Created on Mar 30, 2012 @author: regger ''' from neuron import h from collections import Sequence import numpy as np class Synapse(object): ''' Synapse base class Contains information about pre- and postsynaptic cell type, branch ID of postsynaptic cell, branch pt ID, and xyz-coordinates of sy...
ec5c49aaa071b00a43ef065ff42ff8e369438f4c46a2466fb11b84d56cac30d1
Python
4,206
133
import gzip import numpy as np import scipy from scipy.spatial.distance import squareform, pdist from sequence_models.constants import IUPAC_CODES def get_dihedrals(a, b, c, d): b0 = -1.0 * (b - a) b1 = c - b b2 = d - c b1 /= np.linalg.norm(b1, axis=-1)[:, None] v = b0 - np.sum(b0 * b1, axis=-1...
e9aac48cdf0e08d13407db8337d7bf55b6017a2e85f62296279bb68270a4b514
Python
4,207
114
import os import numpy as np import pandas as pd def allign_alleles(df): """Look for reversed alleles and inverts the z-score for one of them. Here, we take advantage of numpy's vectorized functions for performance. """ d = {'A': 0, 'C': 1, 'G': 2, 'T': 3} alleles = [] for colname in ['A1_x',...
03416f453bceccb4686d7bde80f98e05c050575086ed028c88882f37c7bcdb07
Python
4,212
152
""" Tests that work on both the Python and C engines but do not have a specific classification into the other test modules. """ from io import StringIO import pytest import pandas as pd import pandas._testing as tm def test_iterator(all_parsers): # see gh-6607 data = """index,A,B,C,D foo,2,3,4,5 bar,7,8,9,...
22e98a8fd66180c0b9c9a0d0650ef0ed710f2c4b73c0c32eeb3c9c6b79aa26a3
Python
4,212
121
import numpy as np import pandas as pd from sklearn.mixture import GaussianMixture def footprint( peak_data: pd.DataFrame, qbed_data: pd.DataFrame, fixed_number: float = 50, compress_number: float = 0, min_insertions: int = 15, delete_unfound: bool = False, resultname: list = ["Chr_footpri...
35ca99794654a9afcc610ef2e06b84d6eee761eff000074c767f06b3e8963765
Python
4,212
137
from __future__ import annotations import functools from typing import TYPE_CHECKING import numpy as np from pandas.compat._optional import import_optional_dependency if TYPE_CHECKING: from collections.abc import Callable @functools.cache def generate_online_numba_ewma_func( nogil: bool, parallel: boo...
a13d32b436f42b37a7501afa5c640a47965dae139bf8351934f448bf6df138d1
Python
4,212
96
import os, sys, re sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts')) from tree import Tree SS = [ ] ## derivation fragments (partial trees) derived at each storestate IDENTIFY_EXTRACTIONS = True #False ## attach children to base category of derivation fragment... def a...
b398a975470dba1f53fdef47ef5fe2a43ce645169e6220b6d1f828aed2250e63
Python
4,213
139
import multiprocessing as mp import numpy as np import pandas as pd import scipy as sp import time import datetime from scipy import stats from .esw_star import esw_star from ..utils.compute_pvalues import compute_pvalues from ..summarydata import SummaryData def _nsi(mean: pd.DataFrame, verbose: bool=False): """C...
19a0dd16b43b04b4edf9e9f6c29544d8de95954532cf2998f3e0b9324730ee54
Python
4,214
107
import hashlib from pathlib import Path import pandas as pd import pytest import torch import pyaging as pya pytestmark = pytest.mark.full_catalog WEIGHTS_DIR = Path(__file__).resolve().parents[2] / "clocks" / "weights" def _beta(feature): digest = int(hashlib.sha256(feature.encode()).hexdigest()[:8], 16) ...
85bf555169af3e7535ff5cfe947023c687b041ac015d6e3318af854f0b68c548
Python
4,214
94
from pathlib import Path from typing import Iterable, Tuple import numpy as np import matplotlib.pyplot as plt from matplotlib.figure import Figure from matplotlib.widgets import Slider, Button, RadioButtons import torch from .emulator import load_default_emulator_model, APEmulator import pandas as pd from functools im...
ae9c8318a018d97211e5d5cbaea6af29619cb5e50c94f9b7652fa92dcad2be96
Python
4,216
144
import numpy as np import pandas as pd import scipy def maximo_comun_divisor(a, b): temporal = 0 while b != 0: temporal = b b = a % b a = temporal return a def minimo_comun_multiplo(a, b): return (a * b) / maximo_comun_divisor(a, b) def f_loss_Corr(x, stim, y, a...
4d8c18d7f2dd70a1f7176ffec768c0ddd64678f510f6d78d6adede91bd83e024
Python
4,217
112
"""Native allocation failures through PeakModel.build(), isolated from pytest. The session build takes roughly 15 seconds; each small child run takes about one second. Run explicitly with --run-slow. Cython and a C compiler are needed. """ import importlib.util import json from pathlib import Path import shutil impor...
f0c0165544c95d6cc4cc996ff63f5ecc63aa84103acb2ddb9742fc0c5de27626
Python
4,217
129
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Federica.Magnabosco@mrc-cbu.cam.ac.uk based on semnet/decoding by setare10 """ import sys import os import mne import time import pickle import numpy as np import sn_config as C from joblib import Parallel, delayed from SN_semantic_ROIs import SN_semantic_RO...
9cb1b8ace26b8195eef28d3a25345f6be279355401acdf7deceef84bfd96a9dd
Python
4,218
137
import os import shutil from pathlib import Path from tempfile import gettempdir import numpy as np import pytest from test.fixtures.data_fixtures import ( generate_batch_effects, generate_covariates, generate_response_vars, ) """This file contains pytest fixtures for file paths in the PCNtoolkit. The f...
fb44ee54c598c962ec32bbf1048453eea00b75c87c0d2d2c686813e608173ebd
Python
4,219
132
from pathlib import Path import numpy as np import pandas as pd from scipy.spatial import distance from fmriprep_denoise.dataset.atlas import fetch_atlas_path, ATLAS_METADATA from nilearn.image import index_img from nilearn.plotting import find_probabilistic_atlas_cut_coords def get_atlas_pairwise_distance(atlas_na...
0bb6cd620b5c5463297ee05dccd757dfd3bbe8f6be4c58a697d4beb8c3706d0e
Python
4,220
120
# Copyright 2026 Xanadu Quantum Technologies 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 agre...
dde761836a1225fc2791d0522918e3447acda2ae3c5065810c9cb433e8412043
Python
4,220
121
import functools import itertools import logging from multiprocessing import Pool, TimeoutError import os import signal import time import warnings from Bio.PDB import PDBList, PDBParser from Bio.PDB.mmtf import MMTFParser from Bio.PDB.PDBExceptions import PDBConstructionWarning import h5py import numpy as np import p...
e7bc4842a875bf3bc2774f313c43f1e302d7ce40c8086cbcceec631b197fd221
Python
4,223
112
#!/usr/bin/env python3 import numpy as np import csv from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt plt.rcParams.update({ "text.usetex": True, "font.family": "serif", #"font.serif": ["Palatino"], "font.size": 16}) import seaborn as sns import sys, getopt import os ...
b824e43828e28750c067e8ffb6ec568ccb6111b67cf82cca9c5941f689e65fbf
Python
4,224
89
import torch import torch.nn as nn class DPMSolverDiffuser: """Specialized DPM implementation based on the paper titled 'DPM-Solver: A Fast ODE Solver for Diffusion Probabilistic Model Sampling in Around 10 Steps'. Reference: https://arxiv.org/pdf/2206.00927.pdf """ def __init__(self, schedule='l...
51322e4ec03e9050a16118261ee859dac1ddcc21b921f55720703b965767db6b
Python
4,225
162
from tensorflow.keras import activations from tensorflow.keras.initializers import HeNormal from tensorflow.keras.models import Model from tensorflow.keras.layers import ( Input, Dense, Flatten, BatchNormalization, Conv3D, Activation, Add, MaxPool3D, ) from tensorflow.keras.regularizers...
b50af0c8d0b37996f28c776e7f574d8f01b942cf2183131a2bff93fd082fa462
Python
4,225
91
#import numpy as np #import logging from base.surfaces import Surface from base import gaussianDiffeons as gd from base import conjugateGradient as cg, diffeo, kernelFunctions as kfun, pointEvolution as evol, bfgs, loggingUtils from base.gaussianDiffeonsSurfaceMatching import * from base import examples def compute(cr...
c70cb50a8d8488362197818590ae17595e4cfdf24110fa5b83629d7bfc503d86
Python
4,225
86
import os import pandas as pd import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) from config.globals import ENVIRONMENT from app import create_app, db from app.models import SourceDataset, Subject,...
32a5d13a353f64289ab0e650385102222b6d10232ee00911ecb73a666b78485d
Python
4,227
98
import os import logging import argparse import numpy as np from scipy.io import loadmat, savemat from pathlib import Path from collections import defaultdict from local.common import EnergyBasedVad from local.common import SelectElectrodesFromBothGrids from local.common import SelectElectrodesOverSpeechAreas logger =...
860a10ab2b0c3111afcd927ab62a550a6b40e881b4b7b177af586e82aa43a53c
Python
4,227
109
import pytest import pandas as pd @pytest.mark.parametrize( "td, expected_repr", [ (pd.Timedelta(10, unit="D"), "Timedelta('10 days 00:00:00')"), (pd.Timedelta(10, unit="s"), "Timedelta('0 days 00:00:10')"), (pd.Timedelta(10, unit="ms"), "Timedelta('0 days 00:00:00.010000')"), ...
1888ab72c3958f13eb0c034b681c2f4a61e6bafa749d238620cb50b8cb7543f2
Python
4,229
133
# Copyright 2018-2024 Xanadu Quantum Technologies 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 ...
d9e36a45d34dfbf3b33329b6657c131d9474017fc5a91e4676fdd91892d7754d
Python
4,229
93
import torch import torch.nn as nn import torch.nn.functional as F import torchtext """ From the Kim CNN model.py from the Hedwig repository """ class CNN(nn.Module): def __init__(self, config): super().__init__() dataset = config.dataset output_channel = config.output_channel ta...
416d5dac316d60373a6dbbfe9d7c20d17f8206b30e707f9b00480c7d46e5c8c5
Python
4,230
91
import pandas as pd import matplotlib import matplotlib.pyplot as plt import numpy as np from pathlib import Path plt.rcdefaults() from matplotlib.backends.backend_pgf import FigureCanvasPgf matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf) if __name__ == "__main__": data_dir = '/Users/eghbalhosse...
b7a1e0ff9e8f72088d84c9080551e068e1fb9e1b53a3e0832fbeb8cffd051b6e
Python
4,232
84
#! /usr/bin/env python from multiprocessing.util import get_temp_dir from sys import argv, stdout, stderr, exit from subprocess import check_output,call import argparse from os.path import basename, dirname, splitext,realpath,join,normpath,isdir,isfile,exists from os import mkdir,getcwd,rmdir,listdir from copy import d...
c6962d55364402d9ffe0fb454fbd5bd413a9189a4f702be73bb126e775ba1356
Python
4,232
110
# Copyright 2026 Xanadu Quantum Technologies 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 agre...
c0706389616b60a0abee87a9561820b958ffe6feba95dd832709a816533c7b1e
Python
4,233
141
''' A data structure for easy inserts and lookups from a given refseq file For use in quickly determining what genes intersect a large set of genomic regions Author: Rebecca Riley Date 6/7/23 ''' import numpy as np import sys PRESORTED = True # presorted uses linear search, so it's faster get_chrom = l...
f9b2fbe52f89edda48baf2d329b1eba9f005e4dcbff602701a8e58850e446967
Python
4,233
129
from __future__ import annotations from typing import TYPE_CHECKING import weakref from pandas.util._decorators import set_module if TYPE_CHECKING: from pandas.core.generic import NDFrame @set_module("pandas") class Flags: """ Flags that apply to pandas objects. “Flags” differ from “metadata”. Fla...
112d3e8991d60653878939adfc08e668f1316eb9e6ec236af1dbb41fedb8aab7
Python
4,234
106
# emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: """ .. _metas_ibma: ========================= Image-based meta-analysis ========================= Collection of NIDM-Results packs downloaded from Neurovault collection 1425, uploaded by Dr. Cam...
0b199f904e391fb33129e12d4d9cb6aa0debb61a7558a8bee5a4706c5a460c76
Python
4,235
111
"""Tests for Interval-Interval operations, such as overlaps, contains, etc.""" import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.core.arrays import IntervalArray @pytest.fixture(params=[IntervalArray, pd.IntervalIndex]) def constructor(request): """ Fixture for te...
6e8056292babe5a9ddcdf57a39b50e6aa000a4d5fc7c51e31982e10c8b2233e7
Python
4,235
118
from .emulator import APEmulator import numpy as np import torch from torch.utils.data import DataLoader from torch.optim import Adam from tqdm import trange def match_Vm(emulator : APEmulator, t : np.ndarray, traces : np.ndarray, weights=None, x0=None, lambda_x0=10., x_init=None, ...
9539224160da35b948f83f161e38b38145640c9e9a1cf1b82b4de4a5260016f4
Python
4,236
110
import numpy as np from scipy import sparse from umap import UMAP from umap.utils import csr_unique # =================================================== # Spatial Data Test cases # =================================================== # Use force_approximation_algorithm in order to test # the region of the code tha...
8d57a6d5d81f5ca16a64c21a32ed75e029990f7d0c1504c58328e5f1b4821a52
Python
4,241
167
import matplotlib.pyplot as plt import matplotlib from matplotlib.colors import LinearSegmentedColormap import numpy as np import matplotlib.ticker as ticker import pandas as pd import seaborn as sns; sns.set() from statistics import mean, stdev import matplotlib.transforms as transforms import matplotlib.font_manager ...
84caddd892377b74de8b61f1fdf2437de9dc025c2f3bc73a981edcb0605e4f9a
Python
4,242
117
"""Byte pair encoding utilities""" import os import json import regex as re from functools import lru_cache @lru_cache() def bytes_to_unicode(): """ Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # o...
b3332152eb2ade26a48355d0007e645bf6cdf7d934032572113a88735b0e00e9
Python
4,242
119
import torch import numpy import matplotlib.pyplot as plt import bionetwork import pandas from sklearn.decomposition import PCA #from sklearn.manifold import TSNE import umap #Load network networkList, nodeNames, modeOfAction = bionetwork.loadNetwork('data/KEGGnet-Model.tsv') annotation = pandas.read_csv('data/KEGGnet...
ef947fab4160a18ee5a3e8318963aaf2f84036bf438d6b9336354e1b69c68610
Python
4,243
101
# Copyright 2018-2021 Xanadu Quantum Technologies 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...
a85f89e0cea3495b0ef36aad8c84bf08823fd65e03e0401fc4390ebbb4e86680
Python
4,245
111
"""Tests for `multimodal_ad.data.labeling`.""" import polars as pl from multimodal_ad.data.labeling import ( classify_diagnosis, classify_diagnosis_row, label_nearest_visit, smooth_temporal_labels, ) def test_classify_diagnosis_positive_cases() -> None: assert classify_diagnosis("AD dem/Vascular...
fe347375abd0d6f3ec0f028103580764e295bcdca23842acdcf8e5482fa647ce
Python
4,245
129
"""Shared Plotly figure utilities for ``pycaret.plots``. Centralizes the design tokens (color palette, font, layout defaults) so every chart looks consistent in the dashboard. Aligned with the React UI's Tailwind tokens (`ink-*`, `accent-*`, `success-*`, `danger-*`, `warn-*`). """ from __future__ import annotations ...
e78444ef451a8e3ef34b3e3cf4d3014797f8909e07db0cba9b48597c67e72e4d
Python
4,246
123
import numpy as np import pandas as pd import pandas._testing as tm class TestGetLevelValues: def test_get_level_values_box_datetime64(self): dates = pd.date_range("1/1/2000", periods=4) levels = [dates, [0, 1]] codes = [[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]] index =...
be46d37e3166c17e3efae2914e1e5c7e1d24500e0330e546027701dcbb89eb47
Python
4,247
128
import numpy as np import random import os import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.axes_grid1 import make_axes_locatable import time # import sklearn.linear_model # from sklearn.model_selection import train_test_split # from sklearn.linear_model import Perceptron, LogisticRegression ...
55dccfc55a60f61baf4985cc044e7cdc3b918c58e24056c866009500e5c6aa6d
Python
4,248
130
import logging import os import pickle from pathlib import Path import re import click import numpy as np import pandas as pd from dotenv import find_dotenv, load_dotenv def norm_func(x): def std_norm(x): return (x - x.mean()) / x.std() return np.apply_along_axis(std_norm, 1, x) def main_data_filte...
3417af2643824df8e20a68a5c805b0f7ba69ac16408d31d0833531f9288fff5f
Python
4,249
147
"""Conversion between different units.""" from typing import TypeVar import numpy as np import torch __all__ = [ 'GYROMAGNETIC_RATIO_PROTON', 'deg_to_rad', 'lamor_frequency_to_magnetic_field', 'm_to_micrometer', 'm_to_mm', 'magnetic_field_to_lamor_frequency', 'micrometer_to_m', 'mm_to...
c6d4932114d5839fe8b8e8ddd304022535a376f0f91a1345a148969d9d55f7d0
Python
4,249
165
""" 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, Optional import torch import torch.fft def fft2c_new(data: torch.Tensor, norm: str = "ortho") -> torch.Tensor: ...
b95df77128613ca36d89726e06a5d131b5b96333441e30b7fef25607c4a4a3eb
Python
4,252
106
# Copyright 2018-2025 Xanadu Quantum Technologies 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...
261db0035d8c893ac4413a2fade8aac10ae775e167161eb00a2a995de45d82ae
Python
4,253
129
""" Computes the values of the last hidden layer (or the predictions) of the discriminator for regions of real data along the genome. Authors: Rebecca Riley, Sara Mathieson Date: 12/14/22 """ # python imports import math import numpy as np import os import random import sys import tensorflow as tf sys.path.insert(1, ...
a4e87a1fcec94f7fd9d1c69e377f7c0bd6d7f7c406701d16a80dfc48e91fae13
Python
4,253
141
# Copyright 2018-2023 Xanadu Quantum Technologies 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...
b64e556ff452ab749cd83f20026f8d8e171d28137f3d2a1a5c47df4b2d0c5e0e
Python
4,253
121
from onmt.utils.logging import logger from onmt.transforms import register_transform from .transform import Transform, ObservableStats class FilterTooLongStats(ObservableStats): """Runing statistics for FilterTooLongTransform.""" __slots__ = ["filtered"] def __init__(self): self.filtered = 1 ...
c63e52551425997b07ca5e6efc47ba0137606580c67631b0495197134f15d79d
Python
4,253
103
import os, csv, math import scipy.stats as ss import pandas as pd import numpy as np def correct_p_values(pvalues, method = 'BH'): """Corrects p-values for multiple testing using various methods. Arguments --------- pvalues : array List of p values to be corrected. method : str Optional method t...
4f1de2460696c64e1c19cc1dde5df4d7e195e4db6badfea8b00b29e9b41b200e
Python
4,255
72
import numpy as np layers = [ 'X', 'X_Dense', 'X_MaxPool2D', 'X_Conv2D', 'X_BatchNorm', 'g', 'g_Dense', 'g_Conv1D', 'g_BatchNorm', 'M_Concatenate', 'M_Dense', 'M_BatchNorm', 'outputs' ] layer_transitions = [ # X X_Dense X_MaxPool2D X_Conv2D X_BatchNorm g g_Dense g_Conv1D g_Batc...
50b1c795d79b5946ca7f17d1d866230c89b1456895d0a11eee0c2a821f38fc14
Python
4,255
153
import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.initializers import Orthogonal, TruncatedNormal from tensorflow.keras.layers import ( Add, Dense, Dropout, GlobalAveragePooling1D, GlobalMaxPooling1D, Lambda, Layer, LayerNormalization, MultiHeadAttentio...
8a7ec8650ab4c5bc92be34efbac7a2e484498db6f3c9cf00a5337c688a4dd99e
Python
4,255
154
""" Tests nproc>1. N.B. nproc>1 slows things down here because integrand not sufficiently costly. """ import numpy as np import vegas import gvar as gv numpy = np DIM = 3 NPROC = 2 N = 10 NEVAL = 3e3 NITN = 5 NS = 1_000 @vegas.lbatchintegrand def fl(x): ans = 0.0 x0list = np.linspace(0.4, 0.6, N) for x0...
e6472304142af1cf4d8baac2ecd0069650d64ce4765b7b2e7ed85e0b02f349c9
Python
4,255
113
from typing import List, Optional, Any, Dict from multiprocessing import Pool import importlib.util import numpy as np import torch import logging from ..image import Stack def n4_bias_field_correction( stacks: List[Stack], n4_params: Dict[str, Any] ) -> List[Stack]: if importlib.util.find_spec("SimpleITK") i...
6d7f185e3252b7f87111b3fba03db9e1b795ec755da58af0f6e622fbaadaa6f1
Python
4,256
138
""" Functions for writing concatenated sequence alignments Authors: Anna G. Green """ from collections import OrderedDict import numpy as np from evcouplings.align import Alignment, write_fasta, parse_header def write_concatenated_alignment(id_pairing, alignment_1, alignment_2, tar...
17e46ca769fdaf49f33b3087e6c1e56f0dfb6cd9ec7ce5dd20161d2da349732e
Python
4,258
133
import numpy as np import sys import scipy.io as scio import matplotlib.patches as patches import matplotlib.pyplot as plt import os import matplotlib from tqdm import tqdm import math matplotlib.use('agg') class frameLoader(): def __init__(self) -> None: self.frameSet = None se...
023ae5e12007dad7c19f1f27eaeb821dbace3b027e193b6772c6649dfec40110
Python
4,259
113
from queue import Queue, Empty from threading import Thread, Timer class EventManager: """ 事件管理器 """ def __init__(self): """初始化事件管理器""" # 事件对象列表 self.__eventQueue = Queue() # 事件管理器开关 self.__active = False # 事件处理线程 self.__thread =...
9fbfe1833423510099a102a5b682b6b75fe0eff070d8fa95005fc74d215fd7b9
Python
4,260
129
#!/usr/bin/env python def scale_tensor(tensor, tensor_channels, scale, params): ''' Scale a tensor according to the scaling parameter in the params dict. Assumes the tensor has either 5 [batch, channels, x, y, z] or 4 [channels, x, y, z] dimensions. Parameters ---------- tensor : torch.Te...
6cdf77defee6278cebfbe36af4a833109ebd84db97fbd1dfd3df83551d0cf0b6
Python
4,262
160
#small_multiples.py from initialization.config import * from initialization.initialization import * import plotly import plotly.graph_objects as go from plotly.subplots import make_subplots def hist_sm(df, factor='mean_intensity'): ''' Plotly graph object histogram, minimalist: intended for small multip...
7994fc1d1eb52a6f4d2364411d48e18d5f2e7e46edf5f6aafa65cbcb982c5f49
Python
4,264
111
""" =========================================================== Explore SESAME alternative inverse solutions on evoked data =========================================================== In this example we shall show that SESAME is able to provide alternative solutions with non-negligible probabilities and how the user c...
c88966437c21c1a455b9702c41e60bbaad30577381f49090adcf0b4b848b70a1
Python
4,265
108
""" .. _datasets_databases: ========================= Neurosynth and NeuroQuery ========================= Neurosynth and NeuroQuery are the two largest publicly-available coordinate-based databases. NiMARE includes functions for downloading releases of each database and converting the databases to NiMARE Datasets. ...
3bade20a60e9e0954aefe366be48a2fb900c36a5a76c1cc739aa65912a632512
Python
4,269
149
"""Common utilities for Numba operations""" from __future__ import annotations import inspect import types from typing import TYPE_CHECKING import numpy as np from pandas.compat._optional import import_optional_dependency from pandas.errors import NumbaUtilError if TYPE_CHECKING: from collections.abc import Ca...
8fe20c7e41d0d4179ab9d03cf5d131b8d266e256b6ba1f2c652dd811840338ee
Python
4,269
144
# code from https://gitee.com/LynnHg/pytorch-medical-image-segmentation import sys import torch import torch.nn as nn import torch.nn.functional as F activation = nn.ReLU def initialize_weights(*models, a=0): for model in models: for module in model.modules(): if isinstance(module, nn.Conv2d)...
d59ca92a59770b4afa9bb9812aeb8a8d5e266fdbc5722ef8a7aec57d02da55c1
Python
4,272
104
"""Regression coverage for singleton-strand accounting (issues #805 and #757).""" from collections import Counter import pytest from MACS3.Signal.FixWidthTrack import FWTrack @pytest.mark.parametrize("maxnum", [-1, 1, 2]) @pytest.mark.parametrize("reads", [ [], [(b"chr1", 100, 0)], [(b"chr1", 100, 1)],...
373bed207dd3c60b29138fbc914f734f68c98515d6403c6f3d0bd8bf341391ac
Python
4,273
114
""" 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, Optional, Union import torch import torch.distributed as dist from data.mri_data import SliceDataset from torch.uti...
b91d106c8dd2c54682e042a0d2cbb21312be092714190717faf1f34a820dfd3c
Python
4,273
124
"""Utility functions for testing nimare.""" import os.path as op from contextlib import ExitStack as does_not_raise import nibabel as nib import numpy as np import pytest from ..meta.utils import compute_kda_ma # set significance levels used for testing. # duplicated in test_estimator_performance ALPHA = 0.05 def ...
f02dc2f09e78e4f88a2255e899617fd041d9d70ea53ff99d3e6d66365aaf2b82
Python
4,273
173
import numpy as np import collections solute_id = { 'Na' : 0, 'K' : 1, 'Cl' : 2, 'HCO3' : 3, 'H2CO3' : 4, 'CO2' : 5, 'HPO4' : 6, 'H2PO4' : 7, 'urea' : 8, 'NH3' : 9, 'NH4' : 10, 'H' : 11, 'HCO2' : 12, 'H2CO2' : 13, 'glucose' : 14, '...
4d5c59018c009bca97ce8b6afe7b5ea2ba0237a55cffb786572abac25b592e82
Python
4,274
110
# -*- coding: utf-8 -*- """ Created on Thu Dec 16 17:09:27 2021 @author: Daniel Hulsey this script aligns a ccf to an individual session, and extracts dff data for each indicated region. Running it fully requires: 1. saved dff trace for the session being analyzed 2. saved points to align CCF to multim...
6167351f143d0d6b59ee8210d78304771e80e9ef7e636781a791ff9cf6fb2cab
Python
4,274
118
"""Define RNN-based encoders.""" import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pack_padded_sequence as pack from torch.nn.utils.rnn import pad_packed_sequence as unpack from onmt.encoders.encoder import EncoderBase from onmt.utils.rnn_factory import rnn_factory class RNNEncode...
bff0f1a85fda9e553260d5a7648545a98586047c037a4e03ee95f17c2040e826
Python
4,275
112
# Copyright 2018-2025 Xanadu Quantum Technologies 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...
019f2abad00b51efe4a498bfdabe5ed35cb617b693a25e6f6b056e7c9d489771
Python
4,280
143
import numpy as np from pandas import ( DataFrame, HDFStore, Index, date_range, read_hdf, ) from ..pandas_vb_common import BaseIO class HDFStoreDataFrame(BaseIO): def setup(self): N = 25000 index = Index([f"i-{i}" for i in range(N)], dtype=object) self.df = DataFrame(...
3c8eba9497c5d200ecf019a9171c691979c125c39835c99b89a364ea36d15a1a
Python
4,280
119
import math import os import tempfile from typing import Dict, Optional from . import utils from .logging import logger def STAR_genomeGenerate( fasta_path: str, gtf_path: str, index_dir: str, n_threads: int = 8, memory: int = 16 * 1024**3, temp_dir: Optional[str] = None, ) -> Dict[str, str]:...
7dbc3bedf44fba0988dade046fbb2767d534d093ea7e66b222d7f92c740e0101
Python
4,280
129
from __future__ import annotations from datetime import ( date, datetime, time, timedelta, ) from typing import ( TYPE_CHECKING, Any, TypeAlias, ) from pandas.compat._optional import import_optional_dependency from pandas.io.excel._base import BaseExcelReader if TYPE_CHECKING: from p...
804937067a1b4d18e49155de8963ff3b33cc96a9a55ff25748f40123ab1519ef
Python
4,280
138
# Copyright 2021 Xanadu Quantum Technologies 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 agre...
af68f6c297c50e796777a0c7c7ea7c530b30dbb5f59692d05363b1cb4c88f5e9
Python
4,281
156
import os import numpy as np import torch from sklearn.metrics import r2_score from sklearn.model_selection import train_test_split as split from roost.roost.data import CompositionData, collate_batch from roost.roost.model import Roost from roost.utils import results_multitask, train_ensemble torch.manual_seed(0) ...
bca8b35fc5360ce69b31e6083cb12213560397c5511413d43b2c091b31511fde
Python
4,282
140
import numpy as np import pandas as pd class BooleanArray: def setup(self): self.values_bool = np.array([True, False, True, False]) self.values_float = np.array([1.0, 0.0, 1.0, 0.0]) self.values_integer = np.array([1, 0, 1, 0]) self.values_integer_like = [1, 0, 1, 0] self....
d248cbf757e9f55dcc02b1d49a8a4443c078d10e989c151ce4e6ddba95a84b9f
Python
4,283
120
#!/usr/bin/env python __author__ = 'etseng@pacb.com' """ Input: fasta, each sequence is an individual gene given an input transcript sequence --- -> randomly select N positions to have a SNP, N = <length> / 300 -> generate two haplotypes, one is the original, one is mutated (store this in Haplotypes) -> for each hapl...
382f17f7a86e16696749966ee4e27552124a999eba50e907babf01773a359e02
Python
4,284
150
""" Assertion helpers for arithmetic tests. """ import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.core.arrays import ( BooleanArray, NumpyExtensionArray, ) def assert_cannot_add(left, right, msg="cannot add"): """ Helper function to assert that two objects...
e16c1ce7373a7d84da7f3d6f5684d3310d7fae63425b4bf3c3b2e46a81833da8
Python
4,284
99
from esmologs.ESM2_to_3Di import ESM2_to_3Di import argparse import torch from Bio.SeqIO import FastaIO import sys import re from tqdm import tqdm from pathlib import Path torch.set_grad_enabled(False) def convert_batch(model, seqs, device="cpu"): lengths = [len(seq) for seq in seqs] x = model.encode_seqs(seq...
db89554ae33eb430b0c1d6d720d7471f04c0834a98524b9d6b12dd9fe7721057
Python
4,286
113
from typing import Dict, List import torch from ..utils import gaussian_blur from ..transform import RigidTransform, transform_points from ..image import Volume, Slice class PointDataset(object): def __init__(self, slices: List[Slice]) -> None: self.mask_threshold = 1 # args.mask_threshold xyz_a...
2d0889e42942b5cac67e3253508e87c9f5664bee0cde8fa95c68d5fc880c2c8e
Python
4,289
132
# Copyright 2025 Xanadu Quantum Technologies 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 agre...
03436d9134faf5bae845a13b79e64c3cedccce1c82e757f4b7df7a1579e79bbb
Python
4,290
115
import numpy as np import pytest import pandas._config.config as cf import pandas as pd class TestTableSchemaRepr: def test_publishes(self, ip): ipython = ip.instance(config=ip.config) df = pd.DataFrame({"A": [1, 2]}) objects = [df["A"], df] # dataframe / series expected_keys = ...
e526889a5d7aeeae9983e30ad129d8e422188bb8b510e05e4928d139acba806e
Python
4,290
125
import tensorflow as tf from util.loss import gradient_reversal,loss_domain class feature_extracter(tf.keras.layers.Layer): ## 输入的每个sample为二维张量 def __init__(self): super().__init__() self.conv_1_1 = tf.keras.layers.Conv2D(256,kernel_size=(1,5),strides=1,padding='same',activation='relu') ...
511d27f024c0bdb48b2015a99b5a1cb07bf799de2bf43dd159c0fd85dfabe252
Python
4,293
126
# -*- coding: utf-8 -*- """ preprocess of T1w-CE """ import os from app.utils import cast_to_type, end_execution, get_exitcode_stdout_stderr, wrap_string import numpy as np import nrrd from skimage import morphology, filters import logging logger = logging.getLogger(__name__) def mypdf(data): pdf = np.zeros(len(...
01cffd125b06e5a4862d34787afe514718a4e40c064f0417f6f5044fa9a1e058
Python
4,298
110
import importlib.resources import json from pygments import highlight, lexers, formatters from PyQt6 import uic, QtCore, QtWidgets class BasinsPanel(QtWidgets.QWidget): """Tables panel widget Visualizes tables stored in the .rtdc file """ def __init__(self, *args, **kwargs): super(BasinsPan...
33dd870c45646f231ff0f7998b89b8bc31829a90af3c4eafe0ce16d0f3f185ef
Python
4,299
139
import operator import numpy as np import pytest import pandas as pd import pandas._testing as tm @pytest.fixture def data(): """Fixture returning boolean array with valid and missing values.""" return pd.array( [True, False] * 2 + [np.nan] + [True, False] + [np.nan] + [True, False], dtype="...
c6079f8e8cd55dc7fcac11c990f8913a063e89be9e6f2936ee17e5fcf609f7d5
Python
4,301
82
from ..utils import get_phenolist, PheWebError from .. import conf from ..file_utils import VariantFileWriter, write_json, get_generated_path, get_filepath, get_pheno_filepath from .read_input_file import PhenoReader from .load_utils import parallelize_per_pheno, indent, get_phenos_subset import itertools import argp...
cc15b07051237cf02aeb06fa05c526f13e898dbd8b83d6f1172bce42d8ed3ef3
Python
4,301
126
import torch import torch.nn as nn import torch.nn.functional as F from torchvision.models.resnet import ResNet, Bottleneck from torchvision.models.squeezenet import SqueezeNet, Fire num_classes = 2 class ModelParallelSqueezeNet(SqueezeNet): def __init__(self, gpu_number, *args, **kwargs): super(ModelPara...
0f14cd36220d610686c56a82229692b870ffc5ab792ac02d2e3294e9b54aa7dc
Python
4,304
132
"""Interpolation of data tensor.""" from collections.abc import Callable, Sequence from typing import Literal import torch from mrpro.utils.reshape import normalize_indices def interp(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor: """One-dimensional linear interpolation for monotonically...
bab9fdeeb0973028477cb8903f43537b8e1e11d7bf5b932f7c92e418162011c8
Python
4,305
149
# Copyright 2026 Xanadu Quantum Technologies 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 agre...
ac46a17a5f74717e8a9f49c94a4bd8ea801f06657a0c6e981bf2fb2a4269513c
Python
4,306
102
"""Tests for spoiled gradient echo signal model.""" from collections.abc import Sequence import pytest import torch from mrpro.operators.models import SpoiledGRE from mrpro.utils import RandomGenerator from tests import autodiff_test from tests.operators.models.conftest import SHAPE_VARIATIONS_SIGNAL_MODELS def tes...
637d455fe7aea1333a831eaf21955721ab520dcaee3b6aa7ad421467306f6a53
Python
4,308
121
import os import numpy import pandas import skimage.io import tensorflow as tf import matplotlib.pyplot as plt os.environ["KMP_DUPLICATE_LIB_OK"] = "True" exec(open("unet_model.py").read()) # load U-Net model ### functions --------------------------------------------------------- def list_files(catalog, wd = os.getc...
a76f459ca41cdd9424e6d9694d23e366642c32beba6f4b55b2b408b40432c303
Python
4,308
127
"""Test views.""" # ------------------------------------------------------------------------------ # Imports # ------------------------------------------------------------------------------ import numpy as np import pytest from phylib.io.array import _spikes_per_cluster from phylib.io.mock import artificial_features,...
97e85fa4a3bccddec6f61176cc6b1d073a8508eab7272c852fb4dceda2db21ef
Python
4,309
76
import scipy.io as scio import numpy as np from sklearn.preprocessing import MinMaxScaler from scipy import sparse # 封装归一化函数 def Normalize(filename,normalize_file_list): i=0 for per_file in filename: feature=scio.loadmat(per_file)['permission'] scaler = MinMaxScaler() m1 = sc...
98f085d7239746d932857edd8328b914a5aaa7a354fc8cde5f5a3a9fb909eb1c
Python
4,310
115
import sys import os from distutils.spawn import find_executable, spawn import shutil import subprocess from kcsd import sample_data_path if find_executable('nrnivmodl') is not None: for path in ['x86_64', 'i686', 'powerpc']: if os.path.isdir(path): shutil.rmtree(path) spawn([find_executable...
af16bce79c8285c86c71d60e0e3ced10d602f0135b915c77b2726cdb3c926948
Python
4,311
155
""" Module for containing graphql functionality for interacting with the Datasets Service API. """ import os from typing import Any from requests import post GRAPHQL_URL = os.getenv("DATASETS_ENDPOINT_URL", "https://cloud.pennylane.ai/graphql") class GraphQLError(BaseException): """Exception for GraphQL""" d...
1a921220730f71e21e9e8d17af5de797ff49edb5acc21b4deb3a16b7ff60e10a
Python
4,312
134
# # File to train networks built from the hnn.py class. # # This file establishes the clebsch gordan coefficients, sets up an hnn with given parameters, # loads holograms from .npy files, and then tests the network via a function call. # from argparse import ArgumentParser import logging import os import sys import ...