sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
1322446a4241e23f3b49e1ba0f1173f6555e19748c6f776fafe53a4ec5595755
Python
1,131
42
import matplotlib.pyplot as plt import pickle from pathlib import Path import pandas as pd from multiprocessing import Pool from itertools import repeat from tqdm import tqdm plot_folder = Path('../../data/case1/plot') def main(args): trace, frames = args out_path = plot_folder / f"{trace[0][1]}.png" x ...
422d75713666f5afeac9c837c6af9939d8e22762aacd01d8f4fab026fa18a6b3
Python
1,131
40
''' Created on 2015.5.27 @author: Liang Qian ''' class Thalamus(): ''' This class defines the basic functions and properties of thalamus ''' def __init__(self): ''' Constructor ''' self.neuronsNumber = 0 self.synapsesNumber = 0 self.neurons = [] ...
6743d1649d606c58e59cc05ac54ef1a17672b46c355b300704b4f1802c17b3aa
Python
1,131
27
# License: GNU Affero General Public License v3 or later # A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt. # for test files, silence irrelevant and noisy pylint warnings # pylint: disable=no-self-use,protected-access,missing-docstring from unittest.mock import patch from anti...
a8aae16b36005542628db7c299e65a911dc08d96c74d2072346a6b94baf28fcc
Python
1,131
32
import sys sys.path.append('.') sys.path.append('..') from plotting.utils import load_results, set_plotting_defaults, efcolor, pvscolor, ecscolor,occolor, dpi import matplotlib.pyplot as plt set_plotting_defaults() if __name__ == '__main__': sim_name = sys.argv[1] mesh_name = sys.argv[2] results = loa...
d38824a27fc5a77f91495352468d98a67fab23f47ea9a5ad565ccf423794c1a4
Python
1,133
31
import setuptools import urllib.request, sys with open("README.md", "r") as fh: long_description = fh.read() install_requires = ['numpy', 'setuptools', 'scipy'] setuptools.setup( name="lang2vec", version="1.1.6", author="Patrick Littell, David Mortensen, Antonis Anastasopoul...
783d1b66efc659fa02abefb05aa10a45ff85da1e40c284f23ba18c03dc093ebe
Python
1,135
44
# This test is ported from numpy.distutils from numpy.f2py._src_pyf import process_str from numpy.testing import assert_equal pyf_src = """ python module foo <_rd=real,double precision> interface subroutine <s,d>foosub(tol) <_rd>, intent(in,out) :: tol end subroutine <s,d>foosub ...
f0afbb43199fa17086d0dc11d1b84880236b0e31a5ad3cd69eb475b11f1bb605
Python
1,135
35
import subprocess from pathlib import Path import pytest # PyInstaller has been very unproactive about replacing 'imp' with 'importlib'. @pytest.mark.filterwarnings('ignore::DeprecationWarning') # It also leaks io.BytesIO()s. @pytest.mark.filterwarnings('ignore::ResourceWarning') @pytest.mark.parametrize("mode", ["-...
b5198cc667f624c647fc5f23d94604847190db65338025185a00053f3c8f1f72
Python
1,136
43
#!/usr/bin/env python3.7 # isort: skip_file """Defines imports for the src.core module. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-du...
494db5b9dc1ad19b44b32aef5befc32cf18793e437ccb3b9d3af4583467fb29e
Python
1,138
39
from os import path import yass from yass import preprocess from yass import detect from yass import cluster from yass import templates from util import ReferenceTesting def test_templates_returns_expected_results(path_to_config, path_to_output_reference, ...
94b563d2cca454e7815ce46f557c4ae554f4c671d166ee05386d720fa1918c4c
Python
1,138
44
from __future__ import absolute_import from __future__ import division from __future__ import print_function from smac.env import StarCraft2Env import numpy as np def main(): env = StarCraft2Env(map_name="8m") env_info = env.get_env_info() n_actions = env_info["n_actions"] n_agents = env_info["n_age...
f4a1e250f51dcebf9ad1076cb0c4c751c118cd607c2f69e2abd25a4661dc0fb3
Python
1,138
44
from PIL import Image import sys infilename = sys.argv[1] numlines = int(sys.argv[2]) vae = sys.argv[3] outfilename = sys.argv[4] infile = open(infilename, "r") data = infile.readlines() infile.close() data = data[30:]#remove seeds, and maybe a little bit more (oh well) newinputs = [] count = 0 for line in data: i...
a24ede1e1be0932edb12727b7de3392580bb77948c47cde76eb64e6ba4bc2de6
Python
1,139
43
from __future__ import annotations import re from ..utils._typed_cache import typed_cache from ..utils.constants import RE_NONCONTRACTION_APOSTROPHE @typed_cache def remove_punctuation( text: str, rm_apostrophe: bool, ) -> str: """Get a copy of the text with punctuation removed. If the parameter `r...
d680efe6987815d053287bde5b19f1af893825a797a8ed5fca9ebc59fd500ea1
Python
1,139
32
""" User-defined Python extensions that can be called from the menu. """ import spells # class to create a submenu of Extensions class Extension(object): """ A Python extension that can be added as a submenu in the Extensions menu of Stimfit. """ def __init__(self, menuEntryString, pyFunc, descri...
1ac3536b5ef880262194a42f0d7034fb225fff3fd38c98cdc542531ee7f7593d
Python
1,140
44
''' Following timm implementation ''' import sys import re import fnmatch from collections import defaultdict from copy import deepcopy __all__ = ['model_entrypoint'] _module_to_models = defaultdict(set) # dict of sets to check membership of model in module _model_to_module = {} # mapping of model names to m...
5f9118b313862ed0caa0a781a919df8f9c98faf114064d66febbcdd2f30e7ca7
Python
1,141
38
from setuptools import setup from os.path import join, dirname try: # obtain long description from README readme_path = join(dirname(__file__), "README.rst") with open(readme_path, encoding="utf-8") as f: README = f.read() # remove raw html not supported by PyPI README = "\n".join(R...
1ab7a4ae478e9bdcf7d46762e28aab66cf66724d9060f33714c1d5b1026b06d7
Python
1,143
29
import numpy as np from sklearn.neighbors import KDTree import yaml from pathlib import Path import nrrd import pandas as pd from CrystalTracer3D.io import CrystalReader from skimage.measure import regionprops if __name__ == '__main__': with open('config.yml', 'r') as ymlfile: cfg = yaml.safe_load(ymlfile...
e8d905946155739fc1c16c30bd4d9cbdfbf8291ff46981d0cf4eb61cb6db698e
Python
1,143
33
import torch import torch.nn as nn from ..functional import cutoff_function """ computes radial basis functions with exponential Gaussians """ class GaussianRadialBasisFunctions(nn.Module): def __init__(self, num_basis_functions, cutoff): super(GaussianRadialBasisFunctions, self).__init__() self...
ea22fe787310686debc674b912072fac2a84966f5a28bd3b0a3af51592525e5b
Python
1,143
32
"""A crude *bit of everything* smoke test to verify PyInstaller compatibility. PyInstaller typically goes wrong by forgetting to package modules, extension modules or shared libraries. This script should aim to touch as many of those as possible in an attempt to trip a ModuleNotFoundError or a DLL load failure due to ...
5e22d9d9dfed98213cb86e55014e4e2b6ce5cd06b205f798e25f0514496d6e28
Python
1,144
31
from distutils.command.build_py import build_py as old_build_py from numpy.distutils.misc_util import is_string class build_py(old_build_py): def run(self): build_src = self.get_finalized_command('build_src') if build_src.py_modules_dict and self.packages is None: self.packages = list(...
2b75d2376b16aa13200d930a67abee3b286ea01b57faf6b39cb4f7d3040a8612
Python
1,146
34
import sys sys.path.append('.') from plotting.utils import load_results, set_plotting_defaults, efcolor, pvscolor, ecscolor, dpi import matplotlib.pyplot as plt import seaborn as sns import numpy as np set_plotting_defaults() if __name__ == '__main__': sim_name = sys.argv[1] mesh_name = sys.argv[2] results ...
5acd447905827fbbf3f06fd5b054c8654548fa180a5d41006ed429be8063047a
Python
1,147
35
import pytest import random from numpy._core._multiarray_tests import identityhash_tester @pytest.mark.parametrize("key_length", [1, 3, 6]) @pytest.mark.parametrize("length", [1, 16, 2000]) def test_identity_hashtable(key_length, length): # use a 30 object pool for everything (duplicates will happen) pool = ...
a417fb7a14e653b42557e83bedc40a51ed8f4173534d79054f9772200ca946be
Python
1,147
30
import sys sys.path.append('.') from plotting.utils import load_results, mesh_name, sim_name, set_plotting_defaults, efcolor, pvscolor, ecscolor, occolor,dpi import matplotlib.pyplot as plt if __name__ == '__main__': sim_name = sys.argv[1] mesh_name = sys.argv[2] results = load_results(mesh_name, sim_name)...
1d02502d2f7e453edd7ba9c11ecc39d25068e1aac199711566154cb788ae1f28
Python
1,148
44
import pytest from pandas import ( IntervalIndex, MultiIndex, RangeIndex, ) import pandas._testing as tm @pytest.fixture def range_index(): return RangeIndex(3, name="range_index") @pytest.fixture def interval_index(): return IntervalIndex.from_tuples( [(0.0, 1.0), (1.0, 2.0), (1.5, 2.5...
3dc3f1f8f2a5a8b87d48b37bcb2e44f57eb85c00068604cd943fc3abdc170765
Python
1,149
46
from yass import util def add(a, b, c): return a + b + c class Object(object): def add(self, a, b, c): return a + b + c obj = Object() expected = dict(a=0, b=1, c=2) # TODO: test this case # util.map_parameters_in_fn_call([0, 1], dict(b=1), add) def test_all_kwargs_function(): assert util....
54729711ec1586e0c855719c8ca5e6727b02c0e3a50c2b21babe0e1c525f54b0
Python
1,150
38
from re import L import numpy as np import os from scipy.linalg import svd from numpy_groupies import aggregate from skimage.util.shape import view_as_windows def vectorize(image, mask): """ - If the input is 1D or 2D: unpatch it to 3D or 4D using a mask. - If the input is 3D or 4D: vectorize to 2D using ...
66ced438884e1f709aad7b13f1059003f99071dad6b6dae7ddc848d2d6db8b93
Python
1,150
41
# Copyright 2024 RADar-AZDelta # SPDX-License-Identifier: gpl3+ from abc import ABC, abstractmethod from .etl_base import EtlBase class CreateOmopDb(EtlBase, ABC): """ Class that creates the CDM folder structure that holds the raw queries, Usagi CSV's and custom concept CSV's. """ def __init__( ...
a0ec8ee2d717b07888fcf46c20ea06ca52dae7e291cd0f6bbf5be77887334e51
Python
1,151
30
import numpy as np import pyvista as pv import sys import yaml def compute_lumen_centerline(mesh, lumen): surf = mesh.extract_surface() surf.compute_normals(non_manifold_traversal=False, inplace=True) b = np.array(lumen.bounds).reshape(3,2) xrng = np.linspace(*b[0], 100) yrng = np.linspace(*b[1], 1...
ff3784a5a70ec14bf7290eb96536a6b3327027b1241d99c197e8e03b486acded
Python
1,151
28
# License: GNU Affero General Public License v3 or later # A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt. """ The base Pairing class and all default promoter ranges for CASSIS """ class Pairing: """ A common component throughout CASSIS is a range given by number of ...
d5152559530f8845b0c7f10e80dded576ed870e75e6785e24aae651c31845695
Python
1,152
43
import asap # The below code is to be used for exporting predictions from a trained model using the ASAP library. # It includes data paths, model parameters, and the creation of datasets for prediction. def main(): # Data paths signal_file = "../data/TCGA-A6-A567/TCGA-A6-A567.nodup.no_chrM_MT.tn5.pval.signal...
b00f001d06fe67afcff5908e79998ad1e17bcdc5a8bda41ecc83775482b0f6b5
Python
1,153
40
from __future__ import annotations import os from tempfile import NamedTemporaryFile from typing import TYPE_CHECKING from .utils.logs import logger if TYPE_CHECKING: import pytest lsl_cfg = NamedTemporaryFile("w", prefix="lsl", suffix=".cfg", delete=False) if "LSLAPICFG" not in os.environ: with lsl_cfg as...
0ac125645e0de537fb7ebdbb4c9b9dbb7243fc929beb74ae6d45cf6239792e58
Python
1,154
44
import pytest import numpy as np from . import util class TestSizeSumExample(util.F2PyTest): sources = [util.getpath("tests", "src", "size", "foo.f90")] @pytest.mark.slow def test_all(self): r = self.module.foo([[]]) assert r == [0] r = self.module.foo([[1, 2]]) assert r...
e87fe8e01a17a99133c9348b41bcd83161f6cfc7bbe8ddbc318c2764735b5156
Python
1,154
46
""" Creates numpy array from a CSV file containing axial currents Author: Drew B. Headley """ import numpy as np import pandas as pd def load_axcurrent_csv(fpath, dend_pairs, apic_pair): """ Loads a CSV file that contains axial currents from dendritic segments entering the soma. Parameters ---...
37f057ecd6d4f0f9638b3d9ba2e58cceb3f6db187feb0ffca4778f101db2715c
Python
1,157
47
import numpy as np import pytest import pandas as pd from pandas.core.arrays.floating import ( Float32Dtype, Float64Dtype, ) def test_dtypes(dtype): # smoke tests on auto dtype construction np.dtype(dtype.type).kind == "f" assert dtype.name is not None @pytest.mark.parametrize( "dtype, exp...
883ff1f46a1ca58ca4639926cbb233b031af259f95967696450150d2ea800612
Python
1,158
25
from torch.nn import TransformerEncoderLayer from torch import Tensor from typing import Optional import torch.nn.functional as F class InterpretableTransformerEncoder(TransformerEncoderLayer): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation=F.relu, layer_norm_eps...
31f1b0927996dc9246fd801a399b01c2308afcce072cea602155a852a53fc5f3
Python
1,159
27
from setuptools import find_packages from setuptools import setup with open("./requirements.txt", "r", encoding="utf-8") as fh: install_requires = fh.read() with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setup( install_requires=install_requires, packages=find_packages...
47721da6bf57219f02f37b32f0dbd64ac87d9272b18b8d9300e375dc7a4646ad
Python
1,159
37
import sys from importlib.util import LazyLoader, find_spec, module_from_spec import pytest # Warning raised by _reload_guard() in numpy/__init__.py @pytest.mark.filterwarnings("ignore:The NumPy module was reloaded") def test_lazy_load(): # gh-22045. lazyload doesn't import submodule names into the namespace ...
c2b3738687cf0c566c55dd541bb504d101514b4b73035ea82d574477ca2f293e
Python
1,159
55
"""Functions for loading, saving, and displaying images, and for creating masks.""" from ._core import collage, load_image, load_mask, save_image, export_image, save_mask, show_image, smooth_gaussian from ._edit import normalize, crop, flip_left_right, flip_up_down, pad, resize, rotate_left, rotate_right from ._mask i...
5c1c654164bbff0279aad29ec03b9bff3d6ff4c70dbc7dd62f8b2746959bab50
Python
1,160
32
from crystal_tracer.visual.draw import draw_contour import numpy as np import cv2 from pathlib import Path from crystal_tracer.utils import load_czi_slice, get_czi_shape import platform font = cv2.FONT_HERSHEY_PLAIN color = (255, 255, 255) # white color font_scale = 1 position = (2, 2 + int(font_scale * 10)) # posit...
cd1ee9f33da806f314d71d1e21548bd5e2b8067036071248f00775ad2ff8284b
Python
1,160
29
# License: GNU Affero General Public License v3 or later # A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt. # for test files, silence irrelevant and noisy pylint warnings # pylint: disable=no-self-use,protected-access,missing-docstring import unittest from antismash.common.sec...
3e400e774a03bde3c1b572fe37432798418298330fdff0f0f98c29c6035f97e9
Python
1,161
48
import numpy as np import pytest import pandas as pd from pandas.core.arrays.floating import ( Float32Dtype, Float64Dtype, ) @pytest.fixture(params=[Float32Dtype, Float64Dtype]) def dtype(request): """Parametrized fixture returning a float 'dtype'""" return request.param() @pytest.fixture def data(...
5a76476bb3bd4aa4c016c23b9851b9c710597f2cc4c538527da80b333de3236e
Python
1,163
51
import datetime import viz # UNIQUE names!!! class myTimer(): def __init__(self,dateFormat = '%d.%m.%Y', timeFormat = '%H%M%S'): self.dateFormat = dateFormat self.timeFormat = timeFormat self.started = False # timer methods to calculate time differences def start(self): self.startTick = viz.tick()...
7d731e74fa81e8323a8925bbc49b58975aa4f407f253572bb3dc8ae4eab0892f
Python
1,163
34
from typing import Tuple import torch class CropBoundingBox(torch.nn.Module): def __init__(self): super().__init__() def forward(self, img: Tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor: img, bounding_box = img width = bounding_box[2] - bounding_box[0] height = bounding...
4da5f4a4d92e9d276e62426e92bf53b47c049f08f7e3cd1f2ad9b7c069cc7276
Python
1,164
64
""" Created on Apr 9, 2025 @author: mning """ from src.pipelines.calc_Classification_Entropy_Bands_Ratio import ( calc_Classification_Entropy_Bands_Ratio, ) calc_Classification_Entropy_Bands_Ratio( op_Training="V1CV", band_name="broadband", op_NumClass=2, dist_Medn=0, op_Num_Epoch=0, op_Pe...
babe6bb2fbccbb2ed11e114291b0d84878817892ee6248641a6ec9294270f4a1
Python
1,164
45
""" topological fingerprint """ import numpy as np from rdkit.Chem.rdmolops import RDKFingerprint from rdkit.Chem import DataStructs _type = 'topological-based' def GetRDkitFPs(mol, nBits = 2048, return_bitInfo = False): """ ################################################################# Calculate...
5dd3549138b43b5747e2d3e836b72d615ae73c74773b2cc960399fb4a2465a93
Python
1,165
35
from pySOT.surrogate import RBFInterpolant, CubicKernel, TPSKernel, LinearTail, ConstantTail class RBF: """ Radial Basis Function """ def __init__(self, kernel='cubic', tail='linear'): self.kernel = kernel self.tail = tail self.name = 'rbf' self.model = None def fit(self,...
7e68fae32608e024031d44b31b3fe39806e7e77967bbfac45e60c4314c6087a2
Python
1,165
27
from brainiak.searchlight.searchlight import Searchlight from nilearn.image import new_img_like import numpy as np from .fear_rsa_core import calculate_similarity_matrix, get_item_stability, get_cue_generalization def run_fear_searchlight(anat_mask, beta_data, metadata, radius=5): """ [cite_start]Runs whole-br...
44990867758849332798d9af7846f3734bdb07224cb8800a2925fa53ba574ab0
Python
1,166
31
# -*- coding: utf-8 -*- import os import csv import dirfiles def trial_order(order_directory): """ Reads a specific trial order for n blocks from n csv files and returns n lists to be used by the object block_list.order_trials() of Expyriment library """ # Define the pathway of the inputs dir...
fb6c51ad6eb8c6673295e54b8023ba2ced6f44c49737faf78dfdea506324a668
Python
1,167
42
import matplotlib.pyplot as plt import pickle from pathlib import Path import pandas as pd from multiprocessing import Pool from itertools import repeat from tqdm import tqdm plot_folder = Path('../../data/case2/plot') def main(args): trace, frames = args out_path = plot_folder / f"{trace[0][1]}.png" x ...
07c69d9fa3baf820b3d5d7ab52baf3ed5ac351a407e21310db29bab1630440d1
Python
1,168
43
import pytest import pandas import sbmlcore def test_stride(): a = sbmlcore.Stride('tests/3pl1.pdb') assert len(a.results) == 185 # check that all the -180 < phi <= 180 (and also for psi) assert all((a.results.phi > -180) & (a.results.phi <= 180)) assert (a.results.n_hbond_acceptors>=0).sum(...
457c9c26bb6309368ace8ba5c7fc3f3ff2d1b1eb9530ec2e149ec841e9b50c89
Python
1,169
41
import torch import numpy as np class Cutout(object): """Randomly mask out one or more patches from an image. Args: n_holes (int): Number of patches to cut out of each image. length (int): The length (in pixels) of each square patch. """ def __init__(self, n_holes, length): self...
b6453db3656da285990dd327ef8e3b499e9098d8a5aa8580d831c51a8814eff5
Python
1,171
45
""" Test script for an upload """ import os import argparse import requests from requests.auth import HTTPBasicAuth def test_upload(local_file_path, upload_url, username, password): if not os.path.exists(local_file_path): print(f"File does not exist: {local_file_path}") return filename = os....
833459e4303d857b49cf00cb0109f954b56afdc3fa9401bc439551b4f74d4080
Python
1,172
38
"""Generate a heatmap of activation thresholds. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. Note: if more than one heatm...
c8cba4830fb84b29cbc087d4f4c87d6a7b170ab88c046c4b559f01575bc4a86b
Python
1,174
33
from pathlib import Path import typer from .._qt.components.tilt_series_browser import TiltSeriesBrowserWidget from .._metadata_models.relion.tilt_series_set import RlnTiltSeriesSet from ..view._cli import cli COMMAND_NAME = 'tilt-series' @cli.command(name=COMMAND_NAME, no_args_is_help=True) def view_tilt_series( ...
d018e7380448efd36e6c5168a855b5de8821be8b2ab44dab959a9de49a2df805
Python
1,174
36
"""Configure file paths and parameters for project """ import os pjoin = os.path.join class Config(object): # project directories config_path = os.path.dirname(os.path.abspath(__file__)) resources = pjoin(config_path, '../resources') fmriprep_dir = '/Raid6/raw/VMR-Learning-Complete/derivatives/2020/...
6e608ba7da8c860c603074b348515c2ca20e258d076739094a1e62c838d65488
Python
1,179
29
import numpy as np from .io import get_bw_from_file def get_coverage(bw, chrom, start, end): chroms_in_bw = bw.chroms() use_chr = any(c.startswith("chr") for c in chroms_in_bw) chrom_query = f'chr{chrom}' if use_chr else f'{chrom}' return bw.values(chrom_query, start, end, numpy=True).astype('float16'...
3f416d24e82a8060a8614b6a6d31e04efe9aa317369fcae700f736430370147c
Python
1,180
42
""" matrix product: a new twist rewrite matrix product in a vmap style """ from functools import partial import numpy as np import tensorcircuit as tc for bk in ["jax", "tensorflow"]: with tc.runtime_backend(bk) as K: print("~~~~~~~~~~~~~~~~~~~~~") print(f"using {K.name} backend") @parti...
bcb8ba124bc018c2ae75171bc5ca2cc4757bcffaba19b92766e61d122b078f2e
Python
1,181
43
from io import BytesIO import pytest from pandas import read_csv def test_streaming_s3_objects(): # GH17135 # botocore gained iteration support in 1.10.47, can now be used in read_* pytest.importorskip("botocore", minversion="1.10.47") from botocore.response import StreamingBody data = [b"foo,b...
321ba044d95a2a1bf9b8c53074cc88d4f72100b9d708f0fa4ddaea3332f2f70f
Python
1,182
34
import numpy as np import torch import torch.nn as nn from .electron_configurations import * """ Embedding layer which takes scalar nuclear charges Z and transforms them to vectors of size num_features """ class Embedding(nn.Module): def __init__(self, num_features, Zmax=87): super(Embedding, self).__i...
3f1ae0a073cd6b0d8fc36a8d8e31c33c2f80cbf21a0db0aa3f777fe4df9c8f60
Python
1,182
40
import distutils.command.bdist_rpm as orig import warnings from setuptools import SetuptoolsDeprecationWarning class bdist_rpm(orig.bdist_rpm): """ Override the default bdist_rpm behavior to do the following: 1. Run egg_info to ensure the name and version are properly calculated. 2. Always run 'inst...
84e9891be0f89b3236c02f15430a4b38fc0f17a04a3c3fa382d22d5d73964ebc
Python
1,184
44
"""Tests the trace module. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent """ import numpy as np import pytest from src.core...
8552cd734651f932bb9ea03ed62ac298f375867d3ff4c4e532f8e06c005be4e2
Python
1,185
51
# type: ignore import sys if sys.version_info[:2] >= (3, 8): # TODO: Import directly (no need for conditional) when `python_requires = >= 3.8` from importlib.metadata import PackageNotFoundError, version # pragma: no cover else: from importlib_metadata import PackageNotFoundError, version # pragma: no c...
c4812f4bde856d8c80b867e4ee19c7cd8044aad469287862f6f2b42044733b5e
Python
1,185
45
"""Tests the trace module. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent """ import numpy as np import pytest from src.cor...
e1d4b46822cca7d91eac32a3553cf85ceb7e65b6b9d21026a14382c1f7fa2b22
Python
1,185
37
"""Compare thresholds across models using a boxplot. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. For more controls over ...
205c3c0db7f4c29e2cee1af0dbcd4229a2321a6416c587b2630d8c6b74feb33f
Python
1,186
38
"""Compare thresholds across models using a boxplot. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. For more controls over ...
76e7416e6412ae00d0fe75e72b52dc43d5699410653c71ace6225726f86a1a0a
Python
1,186
25
"""estimate_r: one shared initial GLM for the r grid, per-r wall time, sane JIC.""" import numpy as np import pandas as pd from causarray import estimate_r def test_estimate_r_returns_time_and_finite_jic(): rng = np.random.default_rng(0) n, p, a, r_true = 400, 150, 3, 2 U = rng.normal(0, 0.6, (n, r_true)...
a337317d32a9d20c32259fad7beba3427380f6b1b59cd8fe752b7d6e2c14ff0b
Python
1,186
45
from __future__ import division import viz import vizact import vizmat import vizshape import os import random import itertools import sys import math import cPickle ## user librarys sys.path.insert(0,os.path.realpath('..\py')) sys.path.insert(0,os.path.realpath('..\objects')) # File I/O from csv_io import write_to_c...
18a6fdf94685b334f4e39bd4815ba43ecd67f7b8b2ca3a9a86b58ac4b38a358a
Python
1,187
46
from __future__ import annotations from abc import ABC, abstractmethod class Backend(ABC): def __init__( self, modulename, sources, extra_objects, build_dir, include_dirs, library_dirs, libraries, define_macros, undef_macros, ...
66cc9c9bea8dcef9d037b0c2f9f7af58f47e7e6971b010e8bfb4ff224ec2e299
Python
1,187
36
# License: GNU Affero General Public License v3 or later # A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt. # for test files, silence irrelevant and noisy pylint warnings # pylint: disable=no-self-use,protected-access,missing-docstring,too-many-public-methods import os from tem...
b55efc1109e60ce7893d620f356d9296e91de13f06c64530ac13010f0c4b4d76
Python
1,187
44
import hashlib REGISTRIES = { "LIGHTNING_REGISTRY": {}, "DATASET_REGISTRY": {}, "MODEL_REGISTRY": {}, "LOSS_REGISTRY": {}, "METRIC_REGISTRY": {}, "OPTIMIZER_REGISTRY": {}, "SCHEDULER_REGISTRY": {}, "SEARCHER_REGISTRY": {}, "CALLBACK_REGISTRY": {}, "INPUT_LOADER_REGISTRY": {}, ...
daa82a6870d210a60ed61c04f4c68f4c52619789bbade8c7cae39cae6bea6818
Python
1,187
39
import numpy as np import pytest from pandas import DataFrame import pandas._testing as tm class TestDataFrameReindexLike: def test_reindex_like(self, float_frame): other = float_frame.reindex(index=float_frame.index[:10], columns=["C", "B"]) tm.assert_frame_equal(other, float_frame.reindex_like...
0a9f79c2d70c4a21a63093607586c32750364703fa7d25e0682f1ca0bebbc8fe
Python
1,188
33
from mpe.MPE_Env import MPEEnv class MPE: def __init__(self, args): self.env = MPEEnv(args) # TODO args name and random seed # scenario_name=args.scenario_name, benchmark=args.benchmark, num_agents=args.num_agents, # num_adversaries, num_landmarks, episode_length self.env.seed(ar...
af0c74939eba4226483a614e3b48c3742af887499e9b6e84449fc7b7128d809e
Python
1,188
36
# Add this after your other imports import zmq import pickle ZMQ_CONTROL_PUB_SOCKET = "tcp://127.0.0.1:5521" def initialize_control_socket(): # Create command publisher (add this in main or as global) context = zmq.Context.instance() command_push_socket = context.socket(zmq.PUSH) command_push_socket.c...
ea112ba9036f2c7f73b792edb99db95b8d8afb0fc78d17cdf17cb55de243c89b
Python
1,188
37
"""Compare thresholds across models using a barchart. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. For more controls over...
85f40c16b6f71099dfec1260d0b656c8db40050161aa9ec74d1435d6bdf68bad
Python
1,189
38
"""Compare thresholds across models using a barchart. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. For more controls over...
ea9c5264a99d7b9287a0dde210c291780147acc95d026dd9650c1587f910f54c
Python
1,189
45
import pytest import warnings import numpy as np @pytest.mark.filterwarnings("error") def test_getattr_warning(): # issue gh-14735: make sure we clear only getattr errors, and let warnings # through class Wrapper: def __init__(self, array): self.array = array def __len__(self)...
f9cb29960b31cf76ac1650994f580b6841eceac5b35e06dec033edf86e25f3e8
Python
1,189
45
import os import tempfile import pytest import numpy as np from yass.batch import BatchProcessor @pytest.fixture def path_to_data(request): temp = tempfile.NamedTemporaryFile(delete=False) path = temp.name def delete_file(): os.unlink(path) request.addfinalizer(delete_file) array = (np....
10a60468cea084d32cfbff870c470a205556b42d844170faabb014bd04a9500f
Python
1,192
42
# Copyright (C) 2013,2015 Bernd Feige # This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING). """ Delphi table storage format - serialized into lines, row-fastest, with empty row separator lines. """ class delphi_table(list): def read_file(self,filename): with open(filename,"rb") as infile:...
11d7873ee962490897468817b69710e249bf16ca0daafa65f874dfd191daffc8
Python
1,193
37
"""Compare thresholds across models using a boxplot. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. For more controls over ...
a4fecd7c79d0ec9721acf11ed1777d2cfa4900bceec44b6970cab11bb7e98c77
Python
1,193
32
import uuid import os import utils if __name__ == "__main__": _uuid = str(uuid.uuid4()) nwires, nlayer, nitrs, timeLimit, isgpu, minus, path = utils.arg() if isgpu == 0: os.environ["CUDA_VISIBLE_DEVICES"] = "-1" else: import tensorflow as tf gpu = tf.config.list_physical_devic...
34d0a456b36a30ac548be6d41030a5f6d0ced6420977619cc03fc4f501ee896b
Python
1,194
38
"""Compare thresholds across models using a boxplot. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. For more controls over ...
ab9cbb0bb49d6d037eaaa44eedcbdd1a9126929dba0761254bd994b1ccebe089
Python
1,195
41
import logging from pathlib import Path from typing import Tuple from omegaconf import DictConfig def get_formatter() -> logging.Formatter: return logging.Formatter('[%(asctime)s][%(filename)s][L%(lineno)d][%(levelname)s] %(message)s') def initialize_logger() -> logging.Logger: logger = logging.getLogger() ...
19e21ffeb36c9881299af38f43b6d9a7ca45f4e3f2eb6f3b5636de8079514748
Python
1,198
40
# Resume all interrupted trainings in yolov5/ dir including DDP trainings # Usage: $ python utils/aws/resume.py import os import sys from pathlib import Path import torch import yaml FILE = Path(__file__).resolve() ROOT = FILE.parents[2] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(...
5c781b2244e7ec610da933d3a6ff4bed4d5c1f5603119b6ed64cd58257b5fb4b
Python
1,198
36
import torch.nn as nn import torch.nn.functional as F import torch class BCE_plus_DICE_Loss_function(nn.Module): """Combined Binary Cross-Entropy and DICE Loss""" def __init__(self, smooth=1, alpha=0.5): super(BCE_plus_DICE_Loss_function, self).__init__() self.smooth = smooth sel...
cc0bc70a751ad9e27ca77093f5fba88b67d05ca3b9f603ce96711deb8adb9dfe
Python
1,198
44
import polars as pl from tqdm import tqdm import numpy as np import pickle from Functions import * import argparse parser = argparse.ArgumentParser() parser.add_argument('--config_path', type=str, default="configs/pairwise.yaml") args = parser.parse_args() np.random.seed(0) config = load_config_from_yaml(args.confi...
ebd46932354b23a751e6c5f5ab2555f8f3202ef544e3d8fa6625959946761fab
Python
1,199
30
import numpy as np from nilearn.glm import non_parametric_inference from nilearn.image import concat_imgs def run_group_inference(map_paths, mask_img, phase_name, n_perm=10000): """ Runs group-level non-parametric permutation testing with phase-specific alpha thresholding[cite: 335, 372, 374]. """ ...
689b31e2e9f1e0e337a442ba49b8b4cec1566d6a82eeb1ad00dbeabbc112f543
Python
1,200
49
""" Created on Jun 13, 2024 @author: mning Compute AUC of curve. Likely will re-use this many times, so worth creating even a short function """ import numpy as np from numpy.typing import ArrayLike from numpy.typing import NDArray from scipy.integrate import simpson def calc_AUC(X: ArrayLike, T: ArrayLike, param...
81250a1873240e5e860b21a7fdba5b37f36dde19f0d27c24c1525936f2a938e1
Python
1,203
30
#!/usr/bin/env python3 from pathlib import Path import pandas as pd import numpy as np def cont(s): s = pd.to_numeric(s, errors="coerce") return f"{s.mean():.2f} ({s.std(ddof=1):.2f})" def cat(s): c = s.value_counts(dropna=False) n = len(s) return " | ".join([f"{k}: {int(v)} ({v/n*100:.1f}%)" for ...
bceabd7eea8fa52036fb24a61617ac281e4e9a632dfa398b3acee70955c6e599
Python
1,204
41
import setuptools import nnap setuptools.setup( name="aggreprot-predictor", version=nnap.__version__, maintainer="Simeon Borko", maintainer_email="simeon.borko@recetox.muni.cz", description="NNAP: Neural Network based Amyloid Predictor", long_description=None, long_description_content_type=...
03349740acc2b63d1be23bd87a583e6cdb2f72e1a2b2b8d453a43feb2a30cc45
Python
1,205
47
# timeout_tests_working.py import time import multiprocessing as mp # --- top-level worker (must NOT be nested) --- def _wrap_fn(q, fn, a): try: q.put(("ok", fn(a))) except Exception as e: q.put(("err", repr(e))) def run_with_timeout(fn, arg, timeout_s=5): ctx = mp.get_context("spawn") #...
bb35ce84297d3782cf57d855d88aa0fec92090a31b04f045d065cf53d10c7ae1
Python
1,205
64
"""Typing tests for `numpy._core._ufunc_config`.""" import numpy as np def func1(a: str, b: int) -> None: return None def func2(a: str, b: int, c: float = 1.0) -> None: return None def func3(a: str, b: int) -> int: return 0 class Write1: def write(self, a: str) -> None: return None cl...
e6a0bb596dc7526523336b9adad5b44a792dac29dcb69d9026e51f29b353a34a
Python
1,205
33
#!/usr/bin/env python3 from setuptools import setup import os import sys setup(name='stereoscope', version='0.3.1', description='Integration of ST and SC data', author='Alma Andersson', author_email='alma.andersson@scilifelab.se', url='http://github.com/alma...
218540412c09bbe45209d2911ee9d8494d706ead8ff2d39098e204da7efb2019
Python
1,207
37
import logging from functools import wraps class Trace: """ Decorator for tracing function calls. If you add the trace decorator to a function, it logs the start and end of every function call to the provided logger. Helps debugging the program flow, especially once we deploy the program to our collab...
a808d284dbd1464f728f8709e38e2bcf9c6aeb19d919dfa2cff9527fb06a48ca
Python
1,207
34
import pickle import h5py def save_pkl(filename, save_object): writer = open(filename,'wb') pickle.dump(save_object, writer) writer.close() def load_pkl(filename): loader = open(filename,'rb') file = pickle.load(loader) loader.close() return file def save_hdf5(output_path, asset_dict, attr_dict= None, mode='...
8d4afc76693fe8542c4cd8c3918b1acd69e2a078ace1c2e2f789e8cb8b711b9e
Python
1,212
39
import pytest import pandas as pd import pandas._testing as tm from pandas.tests.arrays.masked_shared import ( ComparisonOps, NumericOps, ) class TestComparisonOps(NumericOps, ComparisonOps): @pytest.mark.parametrize("other", [True, False, pd.NA, -1, 0, 1]) def test_scalar(self, other, comparison_op,...
a6c5375914f09f36eaecffe571d4f4a7297aac8e43c11ebf00bc7f1023c0263f
Python
1,213
41
import sys from pathlib import Path import wandb FILE = Path(__file__).resolve() ROOT = FILE.parents[3] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH from train import parse_opt, train from utils.callbacks import Callbacks from utils.general import incremen...
f832138c900773291c941db1b0d7eac9a4a5b37eae29a1ba430956dfa9184e17
Python
1,218
45
from ..base_loss import * from .tensor_models import logsigmoid class HingeLoss(BaseHingeLoss): def __init__(self, margin): assert False, 'HingeLoss is not implemented' def __call__(self, score, label): pass class LogisticLoss(BaseLogisticLoss): def __init__(self): assert False, '...
6bcbd462fd77d023cdf1c04ec3a949ce7829a0c1c605b1bc3185410117d96daf
Python
1,219
36
import numpy as np from shap.links import identity, logit class LinkSuite: params = ([1, 2], [1, 100, 10_000]) param_names = ["ndim", "element_count"] def setup(self, ndim, element_count): if ndim == 1: shape = (element_count,) else: side_length = int(np.sqrt(elem...
c22d514719a801d71b17394ff4e425cb510366efc50ab7f9419a64318bba06ca
Python
1,219
34
import os import sys sys.path.append(r'D:\ASCENT\fresh') os.chdir(r'D:\ASCENT\fresh') import pickle import shutil new_nsim = 1 dest_samples, dest_model, dest_sim = [3070, 3150, 3230], 0, 3000 source_sample, source_model, source_sim = 3000, 0, 3000 for dest_sample in dest_samples: with open(fr'samples\{dest_sample...
e165143d80053d093fc72e1ab1d9e21b3f8114bb6b18adf5c6c29063ef21cb79
Python
1,220
54
""" """ import sys, time, logging, warnings import numpy as np import matplotlib as mpl warnings.filterwarnings("ignore") mpl.use('Qt5Agg') # ignore qtapp warning... import matplotlib.pyplot as plt def DrawFigure(num): mpl.rcParams['toolbar'] = 'None' figure = plt.figure(num) ax = plt.axes([0,0,1,1], frameon=Fa...
03c91d0876845ae9af23989d8f316d832ecdf046d057ca7c13feb397d26160c8
Python
1,225
33
from setuptools import setup, find_packages from io import open setup( name="textstat", packages=find_packages(), version="0.7.12", description="Calculate statistical features from text", author="Shivam Bansal, Chaitanya Aggarwal", author_email="shivam5992@gmail.com", url="https://github.co...