sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
13744e903b5e8284bfcd265d9d926ce70370d5c7860d92ca7e941900bec1726c
Python
2,996
73
# Copyright 2024 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
186ed1258767506cd941bb856dc49f3cf7adb98fd562dfaa486bf7de0ce6a8f8
Python
2,996
81
import os import sys import re import types import itertools from cgatReport.Tracker import * from cgatReport.odict import OrderedDict as odict from cpgReport import * ########################################################################## class MappingSummary(cpgTracker, SingleTableTrackerRows): table = "ba...
bf1f4d802ef91d903ce01acff5ba5b04e4c57258695569c4dc2efbc5256d148a
Python
2,997
77
""" adopted from SHINE/utils/attention.py https://github.com/luoyuanlab/SHINE/blob/main/utils/attention.py """ import torch import numpy as np from torch import nn class Attention(nn.Module): def __init__(self, encoder_dim: int, decoder_dim: int): super().__init__() self.encoder_dim = encoder_dim...
ffb2d0ad1dc3588b69ef2ac26e8ebb9a5b5b41671d2a951c8db9ba4bb9a1054c
Python
2,997
81
import numpy as np from .get_atom_kdtree import getAtomKDTree def getAngle(v1, v2): cp = np.cross(v1, v2, axis=-1) dp = (v1*v2).sum(axis=-1) return np.arctan2(np.linalg.norm(cp, axis=-1), dp) def getEffectiveInteractions(X, Y, omega): atoms = np.array(Y) X = X.coord Y = np.array([y.coord ...
72f37de1a7c1be6a2b0aca1bf6d0b11fd527f2a5468c50ebd9e216157816236b
Python
2,998
92
import torch import numpy as np import matplotlib.pyplot as plt from data import generate_recog_data, recog_chance from net_utils import binary_thres_classifier_accuracy #%% m=350 #filter size (m=350 <=> 350 KCs projectng to MBON_alpha'3) r=6 #sampling rate random projection (r=6 <=> each KC gets input from ~6...
293b128aa1b407154aae2e1a8c77c16d6957161c1a65a4396d3d91f6f35a4b3f
Python
2,999
84
import torch def drop_path(x, drop_prob: float = 0., training: bool = False): if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, de...
907dc45b793227db4489e3a10c7797cb8be3357e0c7b24cf02d5c910804f59db
Python
2,999
106
import pickle import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import figure_config mpl.rcParams.update(figure_config.mpl_style) LOG = True def plot_weights(ax, w, *, ylabel): ax.set_ylabel(ylabel, fontsize=figure_config.fontsize_xsmall) ax.set_xlim(plot_params["xlim"]) ax.s...
24350f41c33da385180935f07315e929e445018e3d6c688e9603379a23d12128
Python
3,001
98
import numpy as np import struct def readmda(fname): f = open(fname, "rb") try: code=struct.unpack('i', f.read(4))[0] except: raise IOError("Problem reading file: %s" % (fname)) if code > 0: num_dims = code code = -1 else: f.read(4) num_dims = struct....
1b3e0d0bccd9b75f08fe925324e5dac04ed1689b526163c7625c3a9bdcecb753
Python
3,002
112
#%% # import pandas as pd import numpy as np import time import pandas as pd linux = False import os #%% Import scripts #from xgboost import XGBRegressor directory = os.getcwd() if directory[0] == "/": linux = True else: linux = False #%% Import scripts import sys if linux == True: directory_functions =...
e29e52feff7e7c3b0e14c615c0d4fbeeff262b00ca6dcf655c2266ef3703302d
Python
3,003
96
from typing import Dict, Tuple, List import numpy as np import scipy.stats as stats from scipy.signal import welch from scipy.spatial import ConvexHull from modules.utils import naive_diff def get_all_features(x: np.ndarray, name: str, dt: float, abs: bool = False) -> Tuple[List, List]: features, names = [], []...
45589ad7bb7f85814e1995ce7cd256d33a7f2f0a328f995a6f823aeca947417a
Python
3,004
92
import sys sys.path.append('../classes') import class_model import class_stimuli import numpy as np import pickle import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt ### MAIN SCRIPT stimulus_tasks = ['varyposition', 'varysize', 'varyrotation'] stimulus_folder = '../stimuli/simple_seqs/' save...
f591180fd9647d0a068947ba63b5087c9cd69c635f955e16210c27e815f1bcb9
Python
3,005
84
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for detai...
fa438e0e69ffd2c76fccac17092667f3009779b64992f891722482e512f94a70
Python
3,005
77
import numpy as np import scipy def get_bins(max_bin, num_bins): # generates bins for discretizing network activations return np.linspace(0, max_bin, num_bins) def get_IQR_bins(layer, num_bins): IQR = scipy.stats.iqr(layer) maximum = np.quantile(layer, 0.75) + 1.5*IQR minimum = np.quantile(layer, ...
ea59890ae90641d852b45d4dd4232f436253891530701b399ccd93b795caa5c0
Python
3,007
97
from typing import Any from langchain_core.callbacks.manager import CallbackManagerForLLMRun from langchain_core.language_models.chat_models import BaseChatModel from langchain_core.messages import AIMessage, BaseMessage from langchain_core.outputs import ChatGeneration, ChatResult from pytest_mock import MockerFixtur...
8d3219cef94faca2b745640d739b81676031fed29cf7f064a18654cdb7a4ca1f
Python
3,009
65
import os import argparse import torch from runner import Runner from dataset import MatDataset from torch_geometric.data import DataLoader from utils import smact_validity, compute_elem_type_num_wdist, get_structure, compute_density_wdist, structure_validity parser = argparse.ArgumentParser() parser.add_argument('--m...
7470d287ffebd1d581f68d18fe31e5d25d627bffef6e5a025f4fd5cf10be9cff
Python
3,013
89
"""Question-answering with sources over a vector database.""" import warnings from typing import Any from langchain_core.callbacks import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain_core.documents import Document from langchain_core.vectorstores import VectorStore from pyda...
95486824ba98158dd48ba5f1fbaa73d57d7021744d20cabfd14d59574b75df52
Python
3,013
91
import sys, os, gzip from collections import defaultdict from rdkit import Chem sys.path.append('..') def read_rd_mols_from_sdf_file(sdf_file, removeHs=False, sanitize=False): if sdf_file.endswith('.gz'): with gzip.open(sdf_file) as f: suppl = Chem.ForwardSDMolSupplier(f, removeHs=removeHs, ...
f1eeb048adafbd7cf3d07e433fb0f9dfe365eb9b388f7100569bc8d0c24b7bfe
Python
3,016
85
# language=rst """ This code is directly pulled from the pytorch version found at: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py Modifications exist to have [time, batch, n_0, ... n_k] instead of batch in dimension 0. """ import collections import torch from torch.utils.data._uti...
33b2d6bfa53d5e20e4c837efb7268e0d311e7c97e05f75ff2a7b1e27ab10467a
Python
3,018
81
import scanpy as sc, anndata as ad import numpy as np import pandas as pd if __name__ == "__main__": path_rawdata_mouse = "./brain_human_mouse/mouse_brain_region_67_sparse.h5ad" adata = sc.read_h5ad(path_rawdata_mouse) sc.settings.verbosity = 3 #sc.settings.set_figure_params(dpi=80) ...
ac7b87226c1fc24eb3b7a045183fa811c8a469b5b9902047524f33c20ddb7292
Python
3,018
105
""" Write TIP5P parameters into a SMIRNOFF force field. Based on https://docs.lammps.org/Howto_tip5p.html """ from pathlib import Path from openff.toolkit.typing.engines.smirnoff.forcefield import ForceField from openff.toolkit.typing.engines.smirnoff.parameters import ( ConstraintHandler, ElectrostaticsHandl...
86bc847b070d01de13a6010208e7bf104f790e8d2c4da7bbf7dd4a8365c5c469
Python
3,020
77
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
180f99872f668b40c0bcf33fa42051868cd5e45489f87b3a403e27cd10451b71
Python
3,022
78
#!/usr/bin/env python3 import os import pandas as pd import numpy as np import joblib import pysam import math import tempfile import multiprocessing import gzip def count_reads_in_regions(bam_file, regions): """Count the number of reads in a BAM file for a list of regions using pysam.""" bam = pysam.Alignmen...
659fe4824af91dda7a5be17df9155be86a49667265864262a3d2bc90f0658429
Python
3,022
82
import math from itertools import combinations import pandas as pd from tqdm import tqdm from pgmpy.base import DAG from pgmpy.ci_tests import get_ci_test from pgmpy.global_vars import config from pgmpy.metrics import BaseUnsupervisedMetric class ImpliedCIs(BaseUnsupervisedMetric): """ Tests the implied Con...
d706b2101131a759ad5629a849c005ccb382fbd251dfae5d1fba9bdab841a006
Python
3,024
99
import torch.nn as nn import torch.nn.functional as F from inspect import getmembers, isfunction from . import channels from ..utils import utils from ..utils.utils import * class ZephOD(nn.Module): def __init__(self, n_channels_in=6, n_channels_out=1, init_nod...
872977185457504dd78ee04ec4d370bf8508ba569a40ddf75384a3f090f4bdb4
Python
3,025
76
# Differentiable Augmentation for Data-Efficient GAN Training # Shengyu Zhao, Zhijian Liu, Ji Lin, Jun-Yan Zhu, and Song Han # https://arxiv.org/pdf/2006.10738 import torch import torch.nn.functional as F def DiffAugment(x, policy='', channels_first=True): if policy: if not channels_first: x ...
a38f17457b3610971a08e58f2d5ffc913728564f3800b0f1a4ba62e27018ba52
Python
3,027
77
"""A server behind a full OAuth 2.1 flow, with no client credentials up front. This one process plays two roles that are normally separate: - Resource Server: serves `/mcp` and rejects unauthenticated calls with a 401 pointing at its protected-resource metadata. - Authorization Server: serves discovery, `/register`...
9c49b3cffb2577ebc2e8b46dacbaf3355daa38c49d60110d95cdde37a659c136
Python
3,028
54
import numpy as np import matplotlib.pyplot as plt # Plot behavioral response from 10 seconds before addition of stimulus to 60 seconds after addition with the curve # fit to the data. Takes a dataframe with the behavior data (proportion of 2 week old and 2 month old ants # outside the nest at timepoints -60 to 60), a...
92045bf63fcbc6fa99eb3c0bc92cabe1396f886c2eebc2b345fd9d77133cd246
Python
3,029
80
import pandas as pd import sys from mantis_ml.modules.pre_processing.data_compilation.process_generic_features import ProcessGenericFeatures from mantis_ml.config_class import Config class ProcessCardiovascularSpecificFeatures(ProcessGenericFeatures): def __init__(self, cfg): ProcessGenericFeatures.__in...
d0b87655ce1ba50f666dfa1a3d316dbda5c506bead04194888b034a5f03ef407
Python
3,031
101
"""A prompt is the input to the model. Prompt is often constructed from multiple components and prompt values. Prompt classes and functions make constructing and working with prompts easy. """ from typing import TYPE_CHECKING from langchain_core._import_utils import import_attr if TYPE_CHECKING: from langchain_...
0ae0cbb877b87d113e29d0f000185b84d0dadbc31cb260ef03ad556b7eadff31
Python
3,032
82
#### This script compares GENCODE version 25 with version 41. import session_info import polars as pl import seaborn as sns from pyhere import here import matplotlib.pyplot as plt from scipy.stats import spearmanr def load_annotation(fn, region, sex): return pl.read_csv(fn, separator="\t")\ .filter((...
7b3975183b29458d60f30573d8574357d0a12f6f2256f74d0a92d3f525210cf2
Python
3,032
74
import pandas as pd ''' #step 1 读取CSV文件 input_file1 = "F:/BIDE/statement/ABIDEI.csv" input_file2 = "F:/BIDE/statement/ABIDEII.csv" output_file1 = "F:/BIDE/statement/out1.csv" output_file2 = "F:/BIDE/statement/out2.csv" # 读取CSV文件并指定第一行为列名 df = pd.read_csv(input_file2, header=0) # 筛选数据:SRS_RAW_TOTAL和SRS_AWAR...
c3fd3a91fb81307f103fdd0f4475d0240e8594c375fff6f8022a43d99fe38a8d
Python
3,032
98
import argparse from joblib import Parallel, delayed import pandas as pd import mne from mne_bids import BIDSPath import autoreject from utils import prepare_dataset DATASETS = ['chbp', 'lemon', 'tuab', 'camcan'] parser = argparse.ArgumentParser(description='Compute autoreject.') parser.add_argument( '-d', '--da...
84f7adb0458da0c347af929ab5ba5a02fb839abb90744cf60da8e641a17a8541
Python
3,034
85
import scanpy as sc, anndata as ad import numpy as np import pandas as pd if __name__ == "__main__": path_rawdata_human = "./brain_human_mouse/human_brain_region_88_sparse.h5ad" adata = sc.read_h5ad(path_rawdata_human) sc.settings.verbosity = 3 #sc.settings.set_figure_params(dpi=80) ...
72789b6a2139d971d3b307a2fc009ee06bb9a99e5b020c215f47eb8761c237c3
Python
3,035
104
"""Test string utilities.""" from langchain_core.utils.strings import ( comma_list, sanitize_for_postgres, stringify_dict, stringify_value, ) def test_sanitize_for_postgres() -> None: """Test sanitizing text for PostgreSQL compatibility.""" # Test with NUL bytes text_with_nul = "Hello\x00...
29e28d8a061660acef6b9e10dfb121ff9ce7bc5e1e1530edf70e374466a271bc
Python
3,036
79
""" This module generates videos comparing intact and antennaless flies behavioural respones Author: jonas.braun@epfl.ch """ import os import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.backends.backend_pdf import PdfPages import pickle from tqdm ...
1595664d37b574bc497b08ea7e42b262b3ed8151a939c7e05749563e61f0caf1
Python
3,038
84
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
5914b48429de10b5df1cc067c9942c54ca2fc7264a3094dcf256b10c2e0ad39c
Python
3,038
118
# -*- coding: utf-8 -*- """ Created on Fri Feb 26 18:13:27 2021 Module for miscellaneous utility functions @author: Bruno Caneco """ import shutil import os from distutils.util import strtobool import requests from tqdm import tqdm # ------------------------------------------------------------------------------ d...
a9bff059c67e41c69b26b4d0dab9cb9141fbf30e26e9cef9fdf18891121c14a9
Python
3,039
74
#!/usr/bin/env python # Imports import unittest import os import sys import tempfile import filecmp import shutil path_to_script = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'bin', 'enrichm') path_to_data = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') sys.path = [os.path.join(...
e5393f87c17bdda6f5424929403f9853edae2ca333afb5f6262554553e7c9de9
Python
3,039
92
""" Use the Acquisition class with Napari as an image viewer. This is tested in an IDE. In other python environments (i.e. notebook), the relevant calls to napari might be different """ from pycromanager import start_headless from pycromanager import JavaBackendAcquisition, multi_d_acquisition_events from napari.qt.thr...
8065614ee46f95c25bb03f725fc7dfbedef617471766958c0b2f41f345bcb9cc
Python
3,041
69
import pytest from imagingplus.workflows.AllOptical import AllOpticalTrial from imagingplus._archive.TwoPhotonImagingMain import TwoPhotonImagingTrial from imagingplus._archive.ExperimentMain import Experiment from imagingplus.plotting.plotting import makeSuite2pPlots, plot_flu_trace, plotMeanFovFluTrace, \ plo...
bf48cf2606050a5a101786f10c38df7a8fa43b00cd84949637395ffaafa27008
Python
3,041
73
import os import socket import sys from configs.configs import get_config_dict from helpers.hcp import get_human_connectome_project_subjects from helpers.slurm import save_slurm_job_to_file, send_slurm_job_to_queue if __name__ == "__main__": hostname = socket.gethostname() assert hostname == 'hivemind' ...
ca7e991873318bb323aa88d20644f6b02c58469a3beb300805c2a74d1689d8f7
Python
3,041
111
"""Utility functions for LangChain. These functions do not depend on any other LangChain module. """ from typing import TYPE_CHECKING from langchain_core._import_utils import import_attr if TYPE_CHECKING: # for type checking and IDE support, we include the imports here # but we don't want to eagerly import ...
d4917708eab9af9165e0813c9b4bf655ebb54102dca1fe63fc06a8bb4c18479f
Python
3,041
92
# Copyright (c) 2008-2019 the MRtrix3 contributors. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Covered Software is provided under this License on an "as is" ...
e8c4432ab78146d38e3cebb72bdf0b94f0048435b92c6f40678740320ed711ae
Python
3,045
118
# -*- coding: utf-8 -*- """ Created on Wed Feb 20 19:50:28 2019 @author: Vinícius Rezende Carvalho Test script for Variational Mode Decomposition (Dragomiretskiy and Zosso, 2014) Original paper: Dragomiretskiy, K. and Zosso, D. (2014) ‘Variational Mode Decomposition’, IEEE Transactions on Signal Processing,...
fbef7f0e10bc96895aaf5ed0b0102f8198a8608eabb498fece0d8ea33b3821eb
Python
3,047
105
import torch import torch.nn as nn import torch.nn.functional as F from models.resnet import conv3x3x3, conv1x1x1, get_inplanes, ResNet class PreActivationBasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super().__init__() self.bn1 = nn.B...
965eb5df5e502feb85301dc55eda5a3e987ec935da223bddd6c0faea92595c9d
Python
3,049
112
import numpy as np import pandas as pd import pytest from skbase.lookup import all_objects from pgmpy.ci_tests import BaseCITest, ChiSquare, FisherZ, IndependenceMatch, Pearsonr, get_ci_test def test_ci_registry(): all_tests = [ ci_test.get_class_tag("name") for ci_test in all_objects( ...
2ef4776244ea908fd9ce96985c9b7f7abf5ec6b3fc5c3539dac6afff7d9286f0
Python
3,051
104
import os import matplotlib matplotlib.use('Agg') import torch import matplotlib.pyplot as plt def create_folders(args): try: os.makedirs(args.outf) except OSError: pass try: os.makedirs(args.outf + '/' + args.exp_name) except OSError: pass try: os.makedirs...
7d66124629cbb9b317bb42f514d9745392a57b7bb5f5053bd389a1c7ea872894
Python
3,051
81
"""Gate destructive MCP tools behind human approval. An MCP server can flag a tool as destructive (`destructiveHint=True`). The adapter surfaces that on the LangChain tool as `metadata["mcp"]["tool"]["annotations"]["destructive_hint"]`, so a client can decide how to treat it without hardcoding tool names. Here we rea...
37b69f3b15c087c9886b9516a933cddba6fb6b0db541a920543d93a33206d1cd
Python
3,052
96
import sys import os import os.path ##################This script is for calculate the Jaccard-index of SV breakpoints between samples# mismatch=int(sys.argv[1]) binsizes=5000#################acceptable mismatch bins for loop anchor######## rootdir='.' f=open(f'./SVPairwise_'+'mis'+str(sys.argv[1])+'_withoutS_...
360b2c67483b4cfb004378adcd9fe7667da7ab81f9d02ad23d7a1d9cf697eb43
Python
3,056
102
from matplotlib import pyplot as plt import pickle as pkl import matplotlib.ticker as ticker import numpy as np import scipy from scipy import special from pathlib import Path from joblib import Memory import time import plots_utils as util import itertools import pandas as pd from scipy.signal import ricker import se...
afbb1e80287a51eec96f54b53b45f8c3bf079f78b36e7f685ab7c362af976973
Python
3,056
79
import sys import os import time import warnings from sklearn.exceptions import ConvergenceWarning import gc import psutil import numpy as np warnings.simplefilter(action='ignore', category=ConvergenceWarning) warnings.simplefilter(action='ignore', category=RuntimeWarning) warnings.simplefilter(action='error', cate...
7cb2be5ed65c4841689c4801089491e0d8ea90511454fdaa3c2ec1736ac5aa1e
Python
3,058
101
import string from typing import Any from typing_extensions import override from langchain_classic.evaluation.schema import StringEvaluator class ExactMatchStringEvaluator(StringEvaluator): """Compute an exact match between the prediction and the reference. Examples: ---------- >>> evaluator = Exac...
f8672aac9906415be802a72020589372396c83a64cf021f7aa82c3e6ad2befbd
Python
3,058
83
"""Read in a list of structures/chain ids and find, in a given directory, which assembly files contain the given chain(s). If the same chain is found in multiple assemblies, then the user should manually decide which assembly they want to use. input: list in form '<pdb id>_<chain id>\n' output: list in form '<pdb_id...
d9dff14b8301c2c4e04fe39292fcda8542a275842f1a3a546cfa55de44141149
Python
3,059
95
# Copyright 2022 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
ae62549f1ff139871c6822d6a41f6cf981660d7c586f5bdf32cc5c26e79df217
Python
3,060
106
import numpy import torch from utils import load_data, set_params, evaluate from module import HeCo import warnings import datetime import pickle as pkl import os import random warnings.filterwarnings('ignore') os.environ['CUDA_VISIBLE_DEVICES'] = '1,2' args = set_params() if torch.cuda.is_available(): device ...
681ef3fb73ba564eec843bc8f3d86c2dd7f51d0d0ad3b0004a1fa6441ff4c55b
Python
3,062
99
import os import unittest from typing import Literal import numpy as np from dataloader import ( ParcellationDataBinary, filter_rid, read_csv, read_csv_ext, ) def _test_individual_fold(rids, fold, stage, ds_) -> None: txt = _read_txt(fold, stage, ds_) return np.array_equal(np.asarray(rids), ...
8207060546247932a826bc45d47c3ec663c371cb318fea5d38787e062c9ae2b8
Python
3,062
65
""" Import data OmicScope allows user to import data from several Omics Software. To date, OmicScope is designed to run with output from Progenesis, PatternLab V, and a generic data. Since outputs can largely vary among software, user must specify from what software the data came from. """ class Input(): def...
17af2a3e029d7d367e5f14f2f82efd3ad314285006c4882d5121516146bc0e91
Python
3,063
94
import warnings from abc import ABC, abstractmethod from collections import OrderedDict from torch import nn class Core(ABC): """ Base class for the core models, taking 2d inputs and computing nonlinear features. """ def initialize(self): """ Initialization applied on the core. ...
8c99309487745c4d0533b4f65aff7001473f704cb1f8c26dc6b07713032b97c3
Python
3,063
80
"""Utilities for formatting strings.""" from collections.abc import Mapping, Sequence from string import Formatter from typing import Any class StrictFormatter(Formatter): """A string formatter that enforces keyword-only argument substitution. This formatter extends Python's built-in `string.Formatter` to p...
cfd54ad80237c10aa32f353f7ea50d45891f5de1e04be81de9b6891faf37efb7
Python
3,063
93
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import os import subprocess import sys from os.path import abspath from os.path import dirname from os.path import exists from os.path import join from os.p...
d9a9d95a5d9de62d0c2fcf36f372d2dad1b9cd17f82df197086022ba3ff65ce7
Python
3,063
77
import pandas as pd import numpy as np import argparse from pandas.api.types import is_string_dtype def get_ratio(data,nc,n=0): feature = list(data.index) data_NC = data.loc[feature,nc] ratio = pd.DataFrame(columns=['feature', 'ratio_all', 'ratio']) ratio_all = [] ratio_NC = [] j = 0 # n = ...
1139fd7bbda6fd7595f609dc74ca7a5d5a858a974fdd65a9a8b9ba83301e71df
Python
3,068
102
#!/usr/bin/env python # -*- encoding: utf-8 -*- import io import re from glob import glob from os.path import basename from os.path import dirname from os.path import join from os.path import splitext from setuptools import find_packages from setuptools import setup def read(*names, **kwargs): with io.open(join...
a6a1eb5e695ad3f068c3b2698223fea546d433ae8e7c3717a08fe423f02b9f24
Python
3,069
73
from dival import TaskTable from dival.measure import PSNR, SSIM from dliplib.utils import Params from dliplib.utils.data.datasets import CachedDataset from dliplib.utils.helper import select_hyper_best_parameters, load_standard_dataset from dliplib.utils.reports import save_results_table from dliplib.utils.weights im...
2e78e083af3b6479a6755f2c80359eb097e98e1ac9ae281bdf48bc306f4d6b94
Python
3,070
113
import matplotlib.pyplot as plt import numpy as np plt.style.use('seaborn-white') plt.rcParams.update({'font.size':15}) plt.rc('xtick', labelsize=36) plt.rc('ytick', labelsize=36) #plt.rc('xtick', labelsize=26) #plt.rc('ytick', labelsize=26) logfile='../../logs/Xgboost/xgboost.log' save_path='../../logs/Xgboost/sa...
71b96772168ebd24be8f6a70496ba5462b3fed7b2090c5d5910fd2c850919e26
Python
3,070
127
from langchain_classic import tools EXPECTED_ALL = [ "AINAppOps", "AINOwnerOps", "AINRuleOps", "AINTransfer", "AINValueOps", "AIPluginTool", "APIOperation", "ArxivQueryRun", "AzureCogsFormRecognizerTool", "AzureCogsImageAnalysisTool", "AzureCogsSpeech2TextTool", "AzureCo...
744526a8ffeadca48208d97251624b3b977854940b9e871a232a9ae66aab2bdc
Python
3,072
84
import argparse import numpy as np from oset.ecg.peak_detection.peak_det_simple import peak_det_simple def peak_det_amp_threshold(x, ff, th, *args): """ peak_det_amp_threshold - R-peak detector based on max search and level thresholding Syntax: peaks, peak_indexes = peak_det_amp_threshold(x, ff, th, *ar...
d4871349d63e837e8d45f53996bf15fda8a2a83e2121c71ec1c04be4544734e7
Python
3,073
87
import pandas as pd import pathlib import gzip import shutil import tqdm.auto as tqdm import multiprocessing as mp def _remove_prefix(string): if string.startswith('"'): string = string[1:] if string.endswith('"'): string = string[:-1] return string def parse_series_matrix(file): res...
13104715b58d0f33c80102e4b4c27532c19528e6644ff1a4890aeb3e8061d80a
Python
3,075
85
import torch import torch.nn as nn import torchvision.models as models class CEEffNet(nn.Module): """encoder + classifier""" def __init__(self, num_classes=2, model_name='effb0', dropout=0.4): super(CEEffNet, self).__init__() self.encoder = choose_model(model_name=model_name) dim_in = ...
dc7fc80999b63f3317ccba54825537674a6c1d4ea8c5e63a9d153040888c8d1e
Python
3,075
66
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
fc56657b11c6cbe8a0029d24e5037238c8a39504a588867d10546bcf9011b754
Python
3,075
75
from pyjavaz.wrappers import JavaObject from ndstorage.ndstorage_base import NDStorageBase class NDRAMDatasetJava(NDStorageBase): """ A python class that wraps a Java-backend RAM data storage. This class maintains an index of which images have been saved, but otherwise routes all calls to the Java imp...
39e6549ee71599f289660afaa591fff8d5483fcf81441c44c36ba4b1ead58d5a
Python
3,076
69
# R-peak detector python implementation. # It is based on the Pan-Tompkins R-peak detector; the "pure" P-T procedure is returing the variable "peaks". An extra step is added in order to fine tune the positions, by searching in an interval around the peaks the argmax. The "fine-tuned" positons are returned in the varia...
b197ed9653adac1f327d5c386c7f3261918bf8ec97af8f453ed795f20693f600
Python
3,076
75
## Imports import numpy as np from chromograph.pipeline import config from chromograph.preprocessing.utils import * from cytograph.visualization.scatter import * from cytograph.visualization.colors import Colorizer import torch from torch import nn from twobitreader import TwoBitFile from deeplift.dinuc_shuffle impor...
304befb1caa807704183664be093c47112684ce078e10689c5a91d2ff90a5b08
Python
3,077
111
import types import numpy as np import matplotlib.pyplot as plt from fastweights_numpy import FastWeights, FeedforwardNet from dt_utils import Timer from data_utils import generate_recognition_data, chance from neural_net_utils import plot_W, plot_B, plot_W_seq, plot_h_seq, plot_train_perf def make_fwRan...
2e35e5bd6584a6af8e7597b9cc324243654f41887b8969f32f4a080dc863fef8
Python
3,079
93
import yarp import pyicub from pyicub.iCubHelper import iCub, iCubRequest, iCubTask, ICUB_PARTS, JointAction pyicub.controllers.PositionController.MIN_JOINTS_DIST = 20 TIMEOUT_LOOKAT = 0.4 TIMEOUT_LANDMARKS = 0.5 TIMEOUT_EYELIDS = 0.5 import time class iCubHelper: def __init__(self): self.icub = iCub(co...
ba3bc83fe53ad65ac8139e29b3e8c60499fcc12907fcde8473ac77ed16e37322
Python
3,080
87
import argparse import gcsfs import pandas as pd from tqdm import tqdm # This script generates replicate to sample mapping file to interpret the qc report. It # was developed as an alternative to extract_rep_names_from_encode.sh which might not # work if the pipeline run_dir had outputs for a specific condition in m...
973dd0bbe2bc886057df1e5610a91a665b62d28b483111b29dada401ace7eadc
Python
3,082
79
# Copyright (c) MONAI Consortium # 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 writing, so...
e4f40455b9459a8e44c800a3abb2cc37d09d1729a882bebee48996b95a9488e1
Python
3,083
84
""" Adapted from: https://github.com/karpathy/nanoGPT/blob/eba36e84649f3c6d840a93092cb779a260544d08/sample.py """ import sys sys.path.append(".") import os from dataclasses import dataclass from contextlib import nullcontext from omegaconf import OmegaConf import torch from crystallm import ( parse_config, CI...
57c85c4b0a8a9a6cd22d2df7d63e1ca3de0b9d4bc7072b2a613f4916f575b12a
Python
3,085
87
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 8 23:16:55 2023 @author: weihan """ import pandas as pd from torch.utils.data.dataset import Dataset from sklearn import preprocessing class MakePygFormat(Dataset): """ The PygLinkPrediction object can convert graph for pyg using. ...
ce42d996af5499f696a063f01894ac298eee4d15c2f449da525a47be7ca9fb02
Python
3,087
73
from torch.utils.data import Dataset import numpy as np from torchvision import transforms import torch from .PredictionDataset import max_to_1, min_max_norm import torch import json if torch.cuda.is_available() is True: try: import cupy as cu from cucim.skimage.morphology import dilation, ball ...
8509f34671d030b043622f3fdc456479db5796194b2bef215b465563a5e0d6da
Python
3,088
97
from tqdm import tqdm class Engine: def __init__(self): hook_names = ['on_start', 'on_start_epoch', 'on_sample', 'on_forward', 'on_backward', 'on_end_epoch', 'on_update', 'on_end'] self.hooks = {} for hook_name in hook_names: self.hooks[hook_nam...
bd2b268047d0ee137cccfa9169be042c5f09cdf144825fd7ff775cf290d83967
Python
3,089
93
import torch import networks as nets from data import generate_recog_data, generate_recog_data_batch from plotting import plot_generalization, get_recog_positive_rates import numpy as np torch.manual_seed(0) # choose parameters netType = 'HebbNet' # HebbFF or LSTM d = 100 # input dim N = 120 # hidden dim force = 'A...
95e0d0552bf283585d70b3f648c2d3054bb1468ad0f85d0c403c8b69f8b954b9
Python
3,091
91
import torch from torch import nn from utils import RBFExpansion from transformer import ComformerConv, ComformerConvEqui, Gradient_block, Piezo_block, Elastic_block from torch_scatter import scatter def bond_cosine(r1, r2): bond_cosine = torch.sum(r1 * r2, dim=-1) / ( torch.norm(r1, dim=-1) * torch.norm...
c8f57b5ad78e755a21f79c449127370f727fb6cdb472d87c1e3e556ecf37143d
Python
3,094
96
""" Test cwas.core.configuration.create """ import cwas.core.configuration.create as create import pytest import yaml @pytest.fixture(scope="module", autouse=True) def setup(cwas_workspace): cwas_workspace.mkdir() @pytest.fixture(scope="module", autouse=True) def teardown(cwas_workspace): yield remove_w...
10f840ebd641b025e50bbc01201124d3e3da21e454b448d8aa20f9083747e3ba
Python
3,096
83
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for d...
24539b5f08be2e9bfb1e7020c23c948eba46102d1e12da623d86da3ed46e0323
Python
3,097
84
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 24 00:57:18 2023 @author: weihan """ import time import torch import argparse import pandas as pd from model.DeepNeuralNetworks import DeepNeuralNetworks def set_args(): parser = argparse.ArgumentParser(description='Graph construct by genome a...
515a73c8eaa0e5d1d3fbefc541223631a661a284919a287c9e0c438cb94542e9
Python
3,097
83
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for detai...
c93fd73735d4d863ca06e31457dafc10db8657c99729a5d431b6a1ec38744dd1
Python
3,098
78
# -*- coding: utf-8 -*- """ Created on Fri Apr 24 12:26:12 2020 @author: gritti """ import tqdm, os, glob, sys from morgana.GUIs.manualmask import makeManualMask from morgana.DatasetTools import io import PyQt5.QtWidgets ############################################################################### # select folder c...
30e85b3d76bfb7eaf2a1a067525bf3de5e9a83160ccfe7bbe3474d8e582e7b40
Python
3,099
87
#!/usr/bin/env python # coding:utf8 import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable torch.manual_seed(123456) class BLSTM(nn.Module): """ Implementation of BLSTM Concatenation for sentiment classification task """ def __init__(self, embeddi...
2de3b2803b86eb1c08360bb5454bd35f8c19456e9e0fca4b8e2812390877c7b2
Python
3,104
82
from __future__ import annotations import numpy as np from libs.common.graph import Graph from libs.function.function import NormalizeAxis from libs.function.utils import aline_spatial as als from libs.function.utils import euclidean_distance def set_distance(position: np.ndarray) -> np.ndarray: dim = position....
451fba9d824ec52620986093083c65c8594d24b6b9f27fae798b33feec97e178
Python
3,104
110
import torch.nn as nn try: from inplace_abn import InPlaceABN except ImportError: InPlaceABN = None class Conv2dReLU(nn.Sequential): def __init__( self, in_channels, out_channels, kernel_size, padding=0, stride=1, use_bat...
effef0afe3db139ebcac3f48bba4fe69791053fd8b0856e1c8f079dfec745dd9
Python
3,104
71
"""Co-quantification control for the antisense-lncRNA finding (the feasible substitute for a literal strand-aware re-quant, which is impossible: SMART-seq2 is unstranded and the raw reads are ~7.5 TB). The worry: a sense-antisense correlation could be an artefact of reads from overlapping loci being counted for both g...
85435a3fce58c14cfdc58c1799d17d607fad4b1dc0d1f7db69d67997468294b6
Python
3,105
79
import os import numpy as np import pandas as pd import random from sklearn.preprocessing import StandardScaler from imblearn.over_sampling import SMOTE from sklearn.model_selection import StratifiedKFold def _load_data(path): X_train = np.array(pd.read_csv(os.path.join(path, 'X_train.csv'), header=None)) y_tr...
b67c1f3c98c27f78b5e3341cd4f773f1215aec4094e14574745522feffdaca0c
Python
3,106
97
from __future__ import annotations import array import random from pathlib import Path import numpy as np from libs.function.function import Normalize from libs.function.utils import aline_spatial # image -> view def image2view(image: np.ndarray, size: int, view: int) -> list[np.ndarray]: data = [] for x i...
028496b355711d6842c63d5472b282d606c8646661d4cbf81e284ab76cf99946
Python
3,107
86
from dival import TaskTable from dival.measure import PSNR, SSIM from dliplib.utils import Params from dliplib.utils.data.datasets import CachedDataset from dliplib.utils.helper import select_hyper_best_parameters, load_standard_dataset from dliplib.utils.reports import save_results_table from dliplib.utils.weights im...
454f10192203e2540d4eaab67503c4d63248e972e7da46f13b4f3f342765d1de
Python
3,107
126
from SMdRQA.RQA_functions import * import ast import memory_profiler from scipy.interpolate import pchip_interpolate from functools import partial from p_tqdm import p_map from scipy.stats import skew import random import pickle import os from tqdm import tqdm import csv from collections import defaultdict from os.path...
9f47fbe15ab80cfa67dc6d489e8e67d578b7acd8b9239452331bb50b938ad656
Python
3,107
110
from abc import abstractproperty import tensorflow as tf from tensorflow.keras.layers import Conv2D, Conv3D from typing import Callable, Tuple from .layer import StandardLRPLayer class ConvLRP(StandardLRPLayer): @abstractproperty def convolve(self) -> Callable: pass @abstractproperty def co...
1196235a031e14c4b464c97edd771b175de0a03be0b7383ec2319fc6ad144305
Python
3,108
90
import pytest from packaging import version from langchain_core.prompts.string import ( check_valid_template, get_template_variables, mustache_schema, ) from langchain_core.utils.formatting import formatter from langchain_core.utils.pydantic import PYDANTIC_VERSION PYDANTIC_VERSION_AT_LEAST_29 = version.p...
5a204f714c316c6edf251d338beaf0aefd23b1199c69352047c66467fe983e7f
Python
3,108
70
# Author: Raktim Mitra (timkartar7879@gmail.com, raktimmi@usc.edu) # Contributions by Jared Sagendorf # third-party modules import torch from torch import nn from torch_geometric.nn import MessagePassing class ContinuousCRF(MessagePassing): def __init__(self, alpha=None, beta=None, niter=4, eps=1e-8, gij=None): ...
c07b8a859c84dcaa8f8c425aba7ae5a76481309ad32f2cdf1ffd1876886da60d
Python
3,108
111
# builtin modules import os import re import subprocess import logging # pnabind modules from pnabind.utils import Interpolator def runAPBS(pqr, command="apbs", prefix="tmp", basedir='.', quiet=True, clean=True, space=0.5, cfac=1.7, fadd=20, gmemceil=400, keep_dx=False): """ run APBS and return potential """ ...
23e9d7c269c7a6c8111820c73322d139fe62312f1094dc4798609490674bdcf8
Python
3,109
121
import logging import tempfile from pathlib import Path from protocol import ACRONYMS_IMAGING_PARAMETERS #: Parameters that are supported by MRdataset VALID_PARAMETERS = sorted(list(ACRONYMS_IMAGING_PARAMETERS.keys())) MRDS_EXT = '.mrds.pkl' VALID_DATASET_FORMATS = [ 'dicom', 'bids', ] VALID_BIDS_EXTENSIONS...