sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
2ba40add5b3325d60bc63f6e82330c4615aa14df9da0b4fc4209e244ab890b14
Python
1,833
55
"""Customed activations.""" from typing import Any, Union import torch from spikingjelly.activation_based import surrogate from spikingjelly.activation_based.neuron import LIFNode surrogate_dict = { 'sigmoid': surrogate.Sigmoid, 'atan': surrogate.ATan, 'leaky_relu': surrogate.LeakyKReLU, } class LIF(LIF...
b249a224f7c3eb35511f30b6113a0fb5c21b3d6177c84379e5d7300c1bafe13a
Python
1,833
73
import argparse import base64 import os import requests def upload_weights_to_github(filename: str, token: str, user: str, repo: str): with open(filename, 'rb') as f: bytes = f.read() bytes = base64.b64encode(bytes).decode() if os.path.isfile(token): with open(token, 'r') as f: ...
efa08eadfbea5af29ce1e94e162bb1970b8e04e3d29b694af6b44ff23041bccb
Python
1,833
50
#this script with assistance from ChatGPT3.5 20231204 # the function is to create a mean of all the normalized images: # python nii2meanT1.py import os import nibabel as nib import numpy as np import fnmatch def create_mean_image(folder_path, output_path): # Ensure the output folder exists os.makedirs(os.pat...
d8c53627b8cbde8714fa54c3538ab933b79926d5a6a0d22e027dd4db704d5981
Python
1,834
60
from abc import abstractmethod import tensorflow as tf class Backbone(tf.keras.Model): """ Interface class for backbones. """ def __init__( self, image_size: tuple, num_channel_initial: int, out_kernel_initializer: str, out_activation: str, out_channel...
0d18905e5704e180d75358a374b4eb5bb0d85e194bd1f87ce92c3b6db5d5cc1a
Python
1,835
60
#!/usr/bin/python # ## @file # # Coherent CUBE 445 laser control. # # Hazen 7/10 # import cube ## Cube445 # # Controls a Coherent Cube 445 laser. This is sub-class of cube.Cube. # class Cube445(cube.Cube): ## __init__ # # Initiate RS-232 communication, verify that the laser is respondi...
c3d380549b1421e1cbb72b8495fb492c84ca0163b23a4b3a5135bd139cf90ca7
Python
1,835
55
################################################################### ### Script to merge data from multiple files into a single file ### ################################################################### ### Copyright 2020-2021 Jannik Luboeinski ### licensed under Apache-2.0 (http://www.apache.org/licenses/LICENSE-2.0...
d08c498c693c6a1e061db24e90b4f8995bf9873cea03fec0e54e55b6a2d392e3
Python
1,836
67
#!/usr/bin/env python """ Reads a list of intervals and a set of indexed mafs. For each interval print the amount covered by each species other than the reference. usage: %prog maf_files [options] < interval_file -s, --src=s: Use this src for all intervals -p, --prefix=p: Prepend this to each src before...
f0c4d6ae474fe3c6fe7a687663de1420fe0bd70a21e31c7a2c7a1b0e251651df
Python
1,836
48
#!/usr/bin/env python # Copyright (c) 2015 Tobias Neumann, Philipp Rescheneder. # # This file is part of Slamdunk. # # Slamdunk is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the ...
26e0d044e0d63648dbc1e5a2f9ea51b7729bc5bef770643cd4605190cf585f81
Python
1,837
58
# -*- coding: utf-8 -*- import sys sys.path.append('..') def test_get_entity(): from seqeval.metrics.sequence_labeling import get_entities seq = ['B-PER', 'I-PER', 'I-PER', 'O', 'B-LOC', 'I-LOC', 'O', 'O'] r = get_entities(seq, suffix=False) print(r) # [('PER', 0, 2), ('LOC', 4, 5)] assert r...
b6d137a07034f9d61300c232fab110899ef4c1ecbe0f21d1264aed2cb4e3764c
Python
1,837
58
#!/usr/bin/env python # coding: utf-8 # In[3]: import scvelo as scv import numpy as np import torch import matplotlib.pyplot as plt import pyrovelocity as pv from pyrovelocity.tasks.data import download_dataset from pyrovelocity.tasks.preprocess import preprocess_dataset from pyrovelocity.tasks.train import train_d...
171b0d453df19ce8fc2e55a179e1fb0595832b898d715e16dbcf3979854a97db
Python
1,838
85
import argparse import uvicorn from fastapi import FastAPI from eir.serve_modules.serve_api import create_info_endpoint, create_predict_endpoint from eir.serve_modules.serve_experiment_io import ( ServeExperiment, load_experiment_for_serve, ) from eir.utils.logging import get_logger logger = get_logger(name=...
2a6e900f1c46aec7511fb3e29e09edf1917e920d526f834f2e808fcc9b11e9b2
Python
1,838
44
import torch import torch.nn as nn from models import * class Net2(nn.Module): def __init__(self, my_pretrained_classifier, context_dim, feature_dim=512): super(Net2, self).__init__() self.pretrained_clf = my_pretrained_classifier self.clf_fc1 = nn.Sequential(nn.Linear(feature_dim, ...
3ed7f71dd12b08b4f0f942984e037c6dbb7a8cf6184add39008293b1f1552f3b
Python
1,838
79
# %% from data_loading import load_dataset_gino import torch from deepcardio import Trainer from deepcardio.losses import LpLoss, H1Loss dltrain, dltest, data_processor = load_dataset_gino( folder_path='./data', train_batch_sizes=[10], test_batch_sizes=[10], query_res=[32, 32]) device = 'cuda' if torch.cuda...
a8ece44c94479cae776440ecf9d3a635adcc36ca97ff79fde4f101b026cce90d
Python
1,838
60
import os import numpy as np import pytest from deepreg.warp import main, shape_sanity_check image_path = "./data/test/nifti/unit_test/moving_image.nii.gz" ddf_path = "./data/test/nifti/unit_test/ddf.nii.gz" @pytest.mark.parametrize( ("out_path", "expected_path"), [ ("logs/test_warp/out.nii.gz", "l...
c7a4a8b224ba201fc3495c6b906f7e9e2cc293e1f790f164269b8c636f6db137
Python
1,838
52
import scipy as s import scipy.special as special from .basic_distributions import Distribution from mofapy2.core.utils import * class Beta(Distribution): """ Class to define Beta distributions Equations: p(x|a,b) = GammaF(a+b)/(GammaF(a)*GammaF(b)) * x**(a-1) * (1-x)**(b-1) log p(x|a,b) = log[Ga...
c8b6170b200b3aa7a8348a8a31c16c259fdecff05ee06f5652580461c9849866
Python
1,839
46
import os import sys import argparse def check_and_link_symbolic_file(source_file, symbolic_file, link_mode): """Check the input, manage directories, and handle links based on mode.""" # Check if input file exists if not os.path.isfile(source_file): print(f"Error: The input file {source_file} ...
0a9fbd2d13cf71ac065c3fdda38bd3bcc77a7e3597a74a32f162ab648ac704f0
Python
1,840
73
import os import random import torch import numpy as np def set_seed(seed=42): """ Set random seeds for reproducibility. Parameters: - seed: Random seed """ random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_s...
0b00812c17a2841d3a3e99ff9e1e79e75c8ced3508da03c91e567aa8cf576d92
Python
1,840
67
#!/usr/bin/env python """ Reads a list of intervals and an axt. Produces a new axt containing the portions of the original that overlapped the intervals usage: %prog interval_file refindex [options] < axt_file -m, --mincols=10: Minimum length (columns) required for alignment to be output """ import sys import bx...
67702d20282c52ded525ac5701d76d74a5a974f0c9aa1bce9dfbfc5f20a7d7b4
Python
1,841
47
"""Split each echo to prepare for registration. NOTE: This script is unnnecessary if the scanner exports each echo separately. """ import os import subprocess import numpy as np import nibabel as nb # ============================================================================= NII_NAMES = [ "/home/faruk/DATA-P...
89b386d521494b8ac131fe48bd528c3c8fe7af4c9f50439a599de7dda57be83a
Python
1,841
52
""" Load an LSM stack into Lasagna """ import os import tifffile from lasagna.plugins.io.io_plugin_base import IoBasePlugin from lasagna.utils import preferences class loaderClass(IoBasePlugin): def __init__(self, lasagna_serving): self.objectName = 'LSM_reader' self.kind = 'imagestack' ...
beb13ba8c6190fb7013ce664d62a931e44ab2b7ac4c8305c996bd09ccb21a975
Python
1,841
67
#!/usr/bin/env python3 import argparse import numpy as np import nibabel as nib def extend_mask_x( mask_nii: str, out_nii: str, extend_part_nii: str, n_vox: int = 3, direction: str = "plus", ) -> None: img = nib.load(mask_nii) data = img.get_fdata() > 0 out = data.copy() extend_pa...
79ed4ae0d2745edbf945298f1daed1af8d94ef26f1370165348f11f7a12a27d8
Python
1,842
53
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import numpy as np import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['processing.zip']) t...
902cff04040a2df8c7fd51525b8537411273d4664628dba20148fd52e908e0e0
Python
1,842
70
# -*- coding: utf-8 -*- # python standard library inputs import os # external inputs import numpy as np import nibabel as nb # local inputs from ..io.get_filename import get_filename def get_tsnr(file_in, tsnr_max=200, write_output=False, path_output=""): """Get tSNR. This function computes the tsnr o...
f7651c6793cabbec6636be5544940817cb4f719928b68c8341f8ff0c7fb508f4
Python
1,842
56
import os import matplotlib.pyplot as plt import torch def visualize_segmentation(test_loader, model, device): model.eval() batch = next(iter((test_loader))) inputs = batch['image'] labels = batch['label'] print("############################") print(inputs) inputs = inputs.to(dtype=torch....
2f3acd5ddee80b6c78f7ba36fd8223a6defab812b70f39f2bc20ae39ce7dcb79
Python
1,843
66
import os import sys import time from unittest.mock import patch import pytest from magicgui._util import debounce, user_cache_dir from magicgui.widgets import FunctionGui def test_user_cache_dir(): ucd = user_cache_dir() import sys from pathlib import Path home = Path.home().resolve() if sys.p...
31711d187a1be4170e56187d3d9f69e07c5a2835e65cb6b8b90c0b7caccd3482
Python
1,843
52
import sys from pathlib import Path p_dir = str(Path(__file__).absolute().parents[2]) if p_dir not in sys.path: sys.path.insert(0, p_dir) import os from os.path import join import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from libs.pytorch_utils import AdaptiveConcatPool2...
53fa995114c6baf9ae71693d67aa10dea19cf15826a899a785fec97abab81a2d
Python
1,843
57
"""Example code for plotting connectivity maps using the coherence from state/mode spectra. The spectra can be calculate with a multitaper (in the case of a state time course) or regression (in the case of a mode time course). See examples/spectra/hmm_multitaper.py for how to calculate a multitaper """ import numpy ...
707adcb362d0d7a67430a97c656a164e25274bc21848acc0da2cebeeb7344958
Python
1,843
51
import torch from distances import LpDistance from utils import common_functions as c_f from utils import loss_and_miner_utils as lmu from losses.base_metric_loss_function import BaseMetricLossFunction class NCALoss(BaseMetricLossFunction): def __init__(self, softmax_scale=1, **kwargs): super().__init__(...
b4f711b129ef15d9ea5f3a2d6c0efbff8f1a6598d05c430a3714072682e14388
Python
1,843
49
"""Guard: chat clients are constructed only in the protocol builders. After PR 2, no module under ``chemgraph/models`` or ``chemgraph/agent`` may construct ``ChatOpenAI``, ``ChatAnthropic``, or ``ChatGoogleGenerativeAI`` except the corresponding ``protocols/*`` builder. The agent layer now routes all model loading thr...
1ec2202f26a23e2a2f99645b055ef89f703eb782cefe8e2acf9cf0f763d39738
Python
1,844
69
# Figure 3 import numpy as np from scipy.constants import epsilon_0 as e0 import impedancefitter as ifit from impedancefitter.single_shell_wall import eps_cell_single_shell_wall from impedancefitter.suspensionmodels import bhcubic_eps_model, eps_sus_MW Cm = 0.01 dm = 7e-9 em = Cm * dm / e0 print("Membrane permittivi...
997d514bf2aad4147476ff42466a74d294d19b0af075311b15885de81fae8348
Python
1,844
57
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 25 16:03:07 2023 @author: rl05 """ import os import os.path as op import shutil import mne import config data_dir = op.join(config.project_repo, 'data') subjects_dir = op.join(data_dir, 'mri') os.environ['SUBJECTS_DIR'] = subjects_dir subject =...
ac50a5708135d2918e9174ebaa45eaa5fb7e526057f20dd31717c0e146f2e5ee
Python
1,844
51
import numpy as np def color_log_remap(ori_cmap, lo_lev, up_lev): """ colorLogRemap: Lookup of the original color map table according to a "log-like" curve. The log-like curve contains a linear part and a logarithmic part; the size of the parts depends on the range (lo_lev, up_lev). Arguments: ...
2aea2cf199ef1d80df119128b3e087315d7d95485862674fe0b0250fef217836
Python
1,845
47
import numpy as np from dipy.reconst.shm import anisotropic_power __all__ = ["anisotropic_index", "anisotropic_power"] def anisotropic_index(shm): """ Calculates anisotropic index based on spherical harmonics coefficients. Code from Dmipy --------------- The MIT License (MIT) Copyright (c) ...
6c0341342e38d3f524ae35980306041d8a1ebc5c92c2b5fb62065877d1ddd74f
Python
1,846
61
""" Import helper methods Gregory Way 2018 Usage: from utils import apply_classifier from utils import shuffle_columns """ def apply_classifier(coef_df, rnaseq_df): """ Apply the logistic regression classifier coefficients to the input gene expression matrix. The function will perform the gene s...
8d0068ab89f756ac94cc3baf26ab9e64f523ed3010d9a7c6cf5370ec88695314
Python
1,846
47
#!/usr/bin/python """ GamepadF310 HAL module. Hazen 04/18 Jeff 06/21 """ import storm_control.sc_hardware.baseClasses.joystickModule as joystickModule import storm_control.sc_hardware.logitech.gamepadF310 as gamepadF310 class GamepadF310Module(joystickModule.JoystickModule): def __init__(self, **kwds): ...
b86f8c23beb3b6f5f87c2194d40ca261fd83d29a34803f1c6861a98551aa100c
Python
1,846
50
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['others.zip']) tmp_dir = tempfile.Tempo...
1433c3ac998ffa971d8575637f3fe2adf2ee45c362ad9d34b80eda31c3aea853
Python
1,847
66
"""Groq endpoint (own-client protocol). Groq keeps its existing client (``load_groq_model``), which owns ``groq:`` prefix stripping, ``GROQ_API_KEY`` handling, and retry-on-auth. This spec routes ``groq:`` models to that loader via the ``groq`` protocol builder. """ from __future__ import annotations from chemgraph....
9e5677d4cac51d77f3a8a751c68c8474383de1484961db229c65e67c29eb2fbb
Python
1,847
45
import logging import sys import xnat class XNATConnectionProvider: """Provides the Connection to the XNAT-server with the given alias, secret and address.""" def __init__(self, xnat_alias: str, xnat_secret: str, xnat_web_addr: str): self._xnat_alias = xnat_alias self._xnat_secret = xnat_sec...
c3013462bd74eccb016365f8db19bfb90896450a4299a793640d68d3819ec17c
Python
1,847
57
import glob, os, re, shutil, subprocess, pgzip, time, traceback, tifffile, numpy as np, numba as nb, \ scipy.stats, joblib as jl from itertools import chain from skimage.measure import label, regionprops import skimage.filters from tqdm import tqdm def findTransformix(): try: v = subproc...
d52a3fe2710d34fed97f20935fc3948ed9d4b88c4d51feb62c774edfcac2b45a
Python
1,847
34
import json import pandas as pd import os import yaml def aggregate(directory): maps = pd.DataFrame(columns=["train", "human breast cancer", "canine lung cancer", "canine lymphoma", "canine cutaneous mast cell tumor", "human neuroendocrine tumor", ...
235f5eda20090d15fada36377b7ce0413481ce26f8b8b5725e7553183aa34ce5
Python
1,848
53
#!/usr/bin/env python3 """ filter_frags.py Ro3 fragment-like filter: MW 120¨C250, cLogP ¨C1~2.5, HBD¡Ü3, HBA¡Ü4, Rot¡Ü3, rings¡Ü2 + salt removal + neutralization + PAINS removal """ import sys from rdkit import Chem from rdkit.Chem import Descriptors, rdMolDescriptors, Crippen, Lipinski from rdkit.Chem.Filte...
b45d940a1a5592a1f5be733966df6de611e78c92a5189e9b0822bef8cef795ac
Python
1,848
52
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['tractometry.zip']) tmp_dir = tempfile....
ed42ec8575c7ce83b9ee59b12d6048f73640e9f344596ee89dcf6ec963a85dad
Python
1,848
54
import sys import getopt import json import pandas as pd import numpy as np def affine_gem_usage(): print(""" Usage : affine_gem.py -i <input.gem> \\ -o <output> \\ -B [backward (reverse) affine matrix] -F [forward affine matrix]...
b631dc0c1c0639a539eddc7e11b42b7cf1b3765e7009dd083543686c288b71aa
Python
1,849
68
#-*- coding : utf-8-*- import csv import pandas as pd import time def caculate_feature(df ,length, bias): data = df.loc[bias:bias+length-1] characters = sum(list(data["characters"])) hashtags = sum(list(data["hashtags"])) words = sum(list(data["words"])) mentions = sum(list(data["mentions"]))...
641ffcbd135f51232494a1f678c41ffe24a88c404114ea2c7a0c41dea2f61bb4
Python
1,850
49
import os import re import click def rename_files(directory): for filename in os.listdir(directory): if 'complete_optimized' in filename: print(f"Skipping: {filename}") continue if filename.endswith('.pkl'): match = re.match(r'(.*?)_(\d{5})_(\d{3})_complete(.*)\...
ba8e754b83fec8bf0ed75051b7abcc07dbd51b290ad08cea49f745c3c320b212
Python
1,850
50
import numpy as np from scipy import stats import matplotlib.pyplot as plt def getplot_corrmat_clusters(enrmat,corrfnstr='pearsonr',**kwargs): '''enrmat is enrichment-mat like in nregs x nclust''' corrfn = getattr(stats,corrfnstr) nregs,ncl = enrmat.shape corrmat,pmat = np.zeros((ncl,ncl))*np.nan,np.z...
dda5e5a6c43ac538091e09a39b82616698ac22e0edd9e831bd89f799f57ecf54
Python
1,850
62
######################################################################## ### Routine to compute the frequency spectrum of spike raster data ### ### from multiple data files ### ######################################################################## ### Copyright 2019-202...
5bb20e60a4ed4b2575c9779f5d7c5f18732aa69d519f435d21ee5775a2e5ebaf
Python
1,851
48
import torch import torch.nn as nn from .modules import CausalCNN, Softplus class CausalCNNVDecoder(torch.nn.Module): """ Variational decoder. """ def __init__(self, k, width, in_channels, channels, depth, out_channels, kernel_size, gaussian_out, softplus_eps, dropout): super(C...
5c4eb92447fd345dab06e841b89331f58a1289e870b16a55cc97306fb55dfca9
Python
1,851
57
import jellyfish import unittest import sys import os from collections import Counter class TestMerFile(unittest.TestCase): def setUp(self): self.mf = jellyfish.ReadMerFile(os.path.join(data, "swig_python.jf")) def test_histo(self): histo = Counter() while self.mf.next_mer(): ...
7826936b277fc6888b7d05b32e0c2bafe8a4648ae362c5ef3d03d1ad3004a2c3
Python
1,851
75
#!/usr/bin/python3 # from functools import reduce from uac.edge import Edge class Element: num = 0 def __init__(self, t, n, reg=0): self.type = t self.index = Element.num self.n = list(map(int, n)) self.nset = frozenset(self.n) self.isolated = False self.region...
8990cbd2c5339aaa520e561f0d2b279eec34c8a504df92cd52fd9a8cf4aa6cce
Python
1,851
68
#-*- coding : utf-8-*- import csv import pandas as pd import time def caculate_feature(df ,length, bias): data = df.loc[bias:bias+length-1] characters = sum(list(data["characters"])) hashtags = sum(list(data["hashtags"])) words = sum(list(data["words"])) mentions = sum(list(data["mentions"]))...
d579d0bd167146e8a07378c92f3f52ca4f77e26fa5f4f2263b52b6a1ae5da89d
Python
1,851
24
from brainscore_vision import benchmark_registry from .benchmark import Allen2022fmri, Allen2022fmriRSA # Default: 8 subjects, 515 images benchmark_registry['Allen2022_fmri.V1-ridge'] = lambda: Allen2022fmri('V1', 'ridge') benchmark_registry['Allen2022_fmri.V2-ridge'] = lambda: Allen2022fmri('V2', 'ridge') benchmark_r...
e26576c94147c891132a311c5f4c9d457167d114d22501d06451d4502e7f796f
Python
1,851
51
"""A minimal Thalamus Task Controller task. This is the smallest useful behavioral task: it draws a square, waits for it to be touched, logs the trial, and reports success. It is meant to be loaded by the Task Controller (it is not a standalone script) -- either drop it into ``thalamus/task_controller/`` and register...
0439664c024f6df08813bb4a632dc5b181581a6122eef600be6ad1e4f4f5fff3
Python
1,852
79
"""Train an HMM on time-delay embedded/PCA data. """ from sys import argv if len(argv) != 3: print("Please pass the number of states and run id, e.g. python 1_train_hmm.py 8 1") exit() n_states = int(argv[1]) run = int(argv[2]) #%% Import packages print("Importing packages") import pickle from glob import...
519d9784d8a6f25acbdb63328c3ae19a40d5a85918b3b889530db5217b9de31b
Python
1,852
64
"""Post-hoc analysis. """ import os from sys import argv if len(argv) != 2: print("Please pass the number of states and run id, e.g. python 5_calc_post_hoc.py 8") exit() n_states = int(argv[1]) output_dir = f"results/inf_params/{n_states:02d}_states" import pickle import numpy as np from glob import glob ...
465a063536655f019926d0c2cf0dc130ba4ddf5e46d3011709e4a25f365e970d
Python
1,853
69
import re """ Module to infer data type from string or convert a string to a data type. """ def data_type_from_string(input_string): """ Returns the data type which string appears to be: int, float, or str """ # if all integers return int if re.match('^[0-9]+$', input_string) is not None: ...
c399faa0d20eb6e12e354736a875f3cbb3cd13eef02dead75be3de59efb41b2c
Python
1,853
61
from python.segmentation.train import ManagedList class TestManagedList(): # Initialize ManagedList with values and verify they are stored correctly def test_initialize_with_values(self): # Given initial_values = [1, 2, 3, 4, 5] max_size = 10 # When managed_list = ...
c70ece9db5285aa20dd2c89ee41b4eea9b9dc244f441507469538e97d50721f0
Python
1,853
60
"""Contains global variables for use in the ADMET-AI website.""" import time import pandas as pd from admet_ai.web.app import app USER_TO_PREDS: dict[str, pd.DataFrame] = {} USER_TO_LAST_ACTIVITY: dict[str, float] = {} def get_user_preds(user_id: str) -> pd.DataFrame: """Gets the user's predictions. :par...
29d6d22eee727a0c8d12129a0c243a8f04b3a4fe0a2d087b2abe99bba6773b5f
Python
1,854
62
######################################################################## ### Routine to compute the frequency spectrum of spike raster data ### ### from multiple data files ### ######################################################################## ### Copyright 2019-202...
3a02f06818cd5c2ed640424e3b8d6c40c16bc325eca7dca9be1f4a8cc47d1360
Python
1,854
69
"""Post-hoc calculation of mode-spectra using a GLM regression. """ from sys import argv if len(argv) != 3: print("Please pass the number of modes and run id, e.g. python 4_calc_regression_spectra.py 6 1") exit() n_modes = int(argv[1]) run = int(argv[2]) #%% Import packages print("Importing packages") impo...
9f19dee056433bb735eda060c55441a007f4fc9120a03989e7a6499a895a5676
Python
1,854
58
#!/usr/bin/env python # coding: utf-8 # In[3]: import scvelo as scv import numpy as np import torch import matplotlib.pyplot as plt import pyrovelocity as pv from pyrovelocity.tasks.data import download_dataset from pyrovelocity.tasks.preprocess import preprocess_dataset from pyrovelocity.tasks.train import train_d...
a53667bf840948deb8f31edad8e0a1a51a0c28235a3ad725b28818967ccae4d1
Python
1,854
54
import os import numpy as np from scipy.spatial.distance import pdist from scipy.stats import spearmanr from mapdata.nsd_datalocation import nsd_datalocation from meadows.meadows import (get_matask, get_dragrate, load_json_data, mead...
fefb52d3a4fc5ac3820365ebc03ba612994576432d9731cbb6d6f850e57fc002
Python
1,854
48
# Copyright (c) DP Technology. # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.optim from . import UnicoreOptimizer, register_optimizer @register_optimizer("adadelta") class ...
0ced11557bda88c09f8b324ba6eabc8d060b03f1d98d71547af540c38da07e8b
Python
1,855
61
from dynamont.segmentation.train import ManagedList class TestManagedList(): # Initialize ManagedList with values and verify they are stored correctly def test_initialize_with_values(self): # Given initial_values = [1, 2, 3, 4, 5] max_size = 10 # When managed_list ...
17465cc9edae9595a404402bf090f02c5018d5a7956cc9dfa2f560c54dba3c26
Python
1,855
66
#!/usr/bin/env python import click as ck import numpy as np import pandas as pd import time import math from utils import Ontology, NAMESPACES import gzip from extract_esm import extract_esm from pathlib import Path import torch as th from Bio import SeqIO @ck.command() @ck.option( '--data-root', '-dr', default='...
3bf9a63c2c8e10158469f3b1a6fb3d2a6b40c049e4a4fc4e68310589dcd38d9a
Python
1,855
56
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license __version__ = "8.4.171" import importlib import os import sys from typing import TYPE_CHECKING # Set ENV variables (place before imports) if not os.environ.get("OMP_NUM_THREADS"): os.environ["OMP_NUM_THREADS"] = "1" # default for reduced CPU ut...
877ad405af808964cbc750346cd09efd8f1d1ce558af1fad40bd1f76fe90e980
Python
1,856
61
import numpy as np import pandas as pd import logging def set_log(lgr, verbose): if verbose==True: lgr.setLevel(logging.INFO) return True elif verbose==False: lgr.setLevel(logging.CRITICAL) return False else: lgr.setLevel(verbose) return True def remove...
af5b03451da4b7aba2b1efad5d87d34d98de8b40fa177e22eb5eca07c976c3b5
Python
1,856
51
# -*- coding: utf-8 -*- """ Created on Mon Aug 21 11:01:06 2023 @author: Guido Meijer """ import json from os import mkdir from os.path import join, dirname, realpath, isdir, isfile from datetime import date # Get data folder path with open(join(dirname(realpath(__file__)), 'settings.json'), 'r') as openfile: se...
d82bace8233c6e1885a38c3debecbe0a7d380758b783b943a783a296fc82403f
Python
1,856
47
import torch import torch.nn.functional as F from typing import List def consistency_regularization_loss( img_logits: torch.Tensor, # shape: [B, 1, H, W] ins_logits_list: List[torch.Tensor] # list of B tensors, each of shape [Nᵢ, 1] ) -> torch.Tensor: """Compute the consistency regulariza...
dcd98ac4a9952ea28559952bc18454fc879cefb4785c739902b25bd766cbc807
Python
1,856
44
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['atlas.zip']) tmp_dir = tempfile.Tempor...
38b13ff93d64a42d8d13c08272e89d0e3face805e3444d459a15348dd2540f5a
Python
1,857
70
import numpy as np from scipy.constants import epsilon_0 as e0 import impedancefitter as ifit from impedancefitter.single_shell_wall import eps_cell_single_shell_wall from impedancefitter.suspensionmodels import bhcubic_eps_model, eps_sus_MW em = 5.0 Rc = 5e-6 dm = 7e-9 km = 0.0 kcp = 0.1 ecp = 60 kmed = 0.1 emed = 8...
4a22552314e284aac203f40d9b90d5f0a5a93b700860e5c13d94b9c09bd82720
Python
1,857
61
#!/usr/bin/env python # coding: utf-8 # In[3]: import scvelo as scv import numpy as np import torch import matplotlib.pyplot as plt import pyrovelocity as pv from pyrovelocity.tasks.data import download_dataset from pyrovelocity.tasks.preprocess import preprocess_dataset from pyrovelocity.tasks.train import train_d...
e185534777c9b8fa15597e0737961e9008b151c32a85eeae0a9749513d63cbe0
Python
1,857
59
import os import torch from torch import autograd from torchdrug import utils path = os.path.dirname(__file__) if torch.cuda.is_available(): spmm_ext = utils.load_extension( "generalized_spmm", [os.path.join(path, "generalized_spmm.cpp"), os.path.join(path, "generalized_spmm.cu")], ext...
12f8552edac987fac2d5e7d1561167814f351c6604a3f62404e86b608c8ec749
Python
1,858
35
"""Running one analysis across several computers through a shared folder. Most of a run is per-recording work that nothing else depends on — spike detection, thresholding, the null models — and most people have more than one computer. A *shared run* splits the recordings between the machines you have, lets each work t...
c005f4f695467bb9a959f6b36045f184cad978580141059ede31d67f9aaad1ec
Python
1,858
48
import numpy as np from tqdm import tqdm from argclz import AbstractParser from neuralib.io import csv_header from rscvp.spatial.util import prepare_si_data from rscvp.util.cli import SelectionOptions, PositionShuffleOptions, DataOutput, NeuronID __all__ = ['SparsityOptions'] class SparsityOptions(AbstractParser, P...
cc10190041d1ebf0bcc239671a8fc015b01fe56638daa6d4111bc1aa6ddb1683
Python
1,858
37
""" The purpose of this file is to provide benchmarks based on publicly accessible data that can be run on candidate models without restrictions. As opposed to the private benchmarks hosted on www.Brain-Score.org, models can be evaluated without having to submit them to the online platform. This allows for quick local ...
69080e8817ca00a9f9ca32cd34bfd2f4576f017c38dbd26a0dbaf0b54ab0807d
Python
1,859
56
from __future__ import annotations from pathlib import Path from labelme import _config def test_load_retired_release_keys(*, tmp_path: Path) -> None: config_file = tmp_path / "labelmerc" config_file.write_text("""\ instance_label_auto_increment: true auto_save: false shortcuts: edit_line_color: Ctrl+L ...
dd7de3f794d2fa45bf5e84d6c196ac89f313a5dbcdb1e1476a7a0d921479a393
Python
1,859
38
import os from nipype.interfaces.base import CommandLine, CommandLineInputSpec, Directory, File, TraitedSpec, traits from cvdproc.config.paths import get_package_path recon_all_external_mask_script = get_package_path("pipelines", "bash", "freesurfer", "freesurfer_reconall_external_mask.sh") class ReconAllExternal...
a771a0b3c470286a169197309843cc2ac56ecbc3d6281eedca27dc53dfbf0e05
Python
1,860
69
from re import L import numpy as np import networkx as nx from gensim.models import Word2Vec #load features dataset='Twibot-22' #nlp features nlp= np.load('Twibot-22/nlp_22.npy') id_include=np.load('Twibot-22/id_include.npy',allow_pickle=True) id_include=list(id_include.item()) #profile features nlp=nlp p=np.load('Tw...
b79860b4ecc9e572b143c7e39de32f63e82655d3202b8c707d870964f051e5f9
Python
1,860
73
#!/usr/bin/env python """ Base class / functionality for a filter wheel. Hazen 06/17 """ from PyQt5 import QtCore import storm_control.hal4000.halLib.halMessage as halMessage import storm_control.sc_hardware.baseClasses.hardwareModule as hardwareModule class FilterWheelWorker(hardwareModule.HardwareWorker): pa...
87f61658f8de5f8a795bbd3ade1410ff3714d2988ff3e1c1974965c00dfa5b05
Python
1,862
50
import pandas as pd import pytest from eir.setup.input_setup_modules import setup_omics @pytest.mark.parametrize( "indices_to_subset,expected", [ ([0, 10, 20, 30, 40, 50, 60, 70], [0, 10, 20, 30, 40, 50, 60, 70]), ([0, 10, 20, 30, 40, 50, 60, 70, 120, 999], [0, 10, 20, 30, 40, 50, 60, 70]), ...
b96180a048a5404e3e827ba19c5ec9f598f7f3dbb8a2699f4bba6fdd68abb8ad
Python
1,862
66
""" Step Scheduler Basic step LR schedule with warmup, noise. Hacked together by / Copyright 2020 Ross Wightman """ import math import torch from typing import List from .scheduler import Scheduler class StepLRScheduler(Scheduler): """ """ def __init__( self, optimizer: torch....
170cee120f7c5472c96ff9d80e9d8783d997a98840e5303523f9de6a0085b5b1
Python
1,863
47
from argclz import AbstractParser from neuralib.io import csv_header from neuralib.registration import CellularCoordinates from neuralib.suite2p import get_s2p_coords from neuralib.util.verbose import publish_annotation from rscvp.util.cli import StimpyOptions from rscvp.util.cli.cli_sbx import SBXOptions from rscvp.ut...
7f8bc206c282b5954261151ee4d59289ae4ae1a19ff749bfafe845d3bf4ae427
Python
1,863
50
from brainscore_vision.model_helpers.check_submission import check_models import functools import os from urllib.request import urlretrieve import torchvision.models from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.activations.pytorch import load_prepro...
b936d231d25b1399c4ea8da977b5413e1969b507daa991c211281f1d8ae110ba
Python
1,863
49
import os import nibabel as nib import numpy as np from nipype.interfaces.base import ( TraitedSpec, BaseInterfaceInputSpec, BaseInterface, File, traits, Str ) class FlipBTableInputSpec(BaseInterfaceInputSpec): in_bvec = File(exists=True, mandatory=True, desc='Input bvec file to be flipped') out_bvec =...
35079b2c6c73065c4272bdbf53a299c835848226e3e5ef6a8566d904a978c560
Python
1,864
65
from collections import OrderedDict import numpy as np from brainscore_vision.model_helpers.activations.core import ActivationsExtractorHelper try: from .descriptor import GaborEntropyConfig, GaborFilterEntropyExtractor except ImportError: from descriptor import GaborEntropyConfig, GaborFilterEntropyExtrac...
a5d1c0074fad7665e20491f4ce9881b26154787169fd4a828922897ca7e516e0
Python
1,864
57
import os import numpy as np # generate batch-iterbale dataloader class BatchLoader: def __init__(self, data, batch_size: int = 32, apply_noise: bool = False): self.data = data self.batch_size = batch_size self.apply_noise = apply_noise self._label_in = "low" self....
067684ae83a8368822655af2f8558bfedd5bd86d902cbb4f4594298f1cf24ac6
Python
1,865
54
# SPDX-FileCopyrightText: Copyright © Timo Koch # SPDX-License-Identifier: GPL-3.0-or-later import numpy as np import nibabel as nib import matplotlib.pyplot as plt import click from pathlib import Path def overlay_images(overlay_data: np.ndarray, background_data: np.ndarray, ax, slicer_op, min_val=None, max_val=Non...
08dc86551075dbf1eef387f3098a4e481d75ff68d36371f61c825e0db0ac222e
Python
1,865
60
""" Created on Aug 30 2022 Script to demonstrate usage of standalone DWI functions: Generate_ADC Generate_IVIMmaps @authors: s.zijlema, p.vhoudt, k.baas, e.kooreman Group: Uulke van der Heide - NKI """ import numpy as np from DWI_functions_standalone import generate_ADC_standalone, generate_IVIMmaps_standalone impo...
33038261c31bfce391b6573d17bdc5aa0c654733c17b6145c4040506e70b0afc
Python
1,865
48
from torch_scatter import scatter_softmax, scatter_sum import torch import torch.nn as nn from .activation import get_activation class AttentionPooling(nn.Module): """Attention-based pooling layer supporting batched graphs.""" def __init__(self, input_dim: int, dropout: float = 0.2, activation: str = 'gelu'):...
5faaf87018cd4758449f2bf9811b24579f70fdf2b6246ae579d9c4f9b5be6b00
Python
1,865
47
import matplotlib import numpy as np import matplotlib.pyplot as plt angle_list = np.linspace(0, 350, 1000) fold3 = np.cos(3*np.linspace(-np.pi/3, np.pi/3, len(angle_list), endpoint=False)) fold6 = np.cos(6*np.linspace(-np.pi/3, np.pi/3, len(angle_list), endpoint=False)) fold3 = (fold3-np.min(fold3))/(np.max(fold3) -...
d71c7a795a6f04500b75befac0975c1ae89aa9707965bb234911d47dd73c3e1e
Python
1,865
57
#!/usr/bin/env python # coding: utf-8 # In[3]: import scvelo as scv import numpy as np import torch import matplotlib.pyplot as plt import pyrovelocity as pv from pyrovelocity.tasks.data import download_dataset from pyrovelocity.tasks.preprocess import preprocess_dataset from pyrovelocity.tasks.train import train_d...
34462ba9eff9440f53b74363ad6f85398ffe638056cfd11e0c1bce19d961dddc
Python
1,866
47
import socket from psychopy import visual, monitors, core from VideoCallStimYale import activeblock, restblock, runtask # Initialise psychopy, parameters of monitor from psychopy monitor tool win = visual.Window([1280, 720], screen=0, monitor="Main_Monitor", units="deg") #initial_screen = visual.TextBox(window=w...
ba3fa1de680ad60c68b98e321f4349235f17a26379e078b83c4ba5903fb20270
Python
1,866
57
import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, matthews_corrcoef, auc, roc_curve from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.mo...
e6d9c2903af265be7adb9fd384caafdaad5ce7790cc70c3a9a15e0c3f45bb4d1
Python
1,866
69
# -*- coding: utf-8 -*- """Python package for the analysis of high-resolution fMRI data.""" import os import subprocess import sys # meta infos __author__ = "Daniel Haenelt" __license__ = "GPL v3" __version__ = "2.0.0-alpha" __status__ = "Development" __all__ = ["SoftwareName", "check_installation", "execute_command...
0939e729b0f06f5dcf59c6818bcdcf3dc29e5f82870e9b1f12eb2b49166df72d
Python
1,867
65
# -*- coding: utf-8 -*- """Python package for for analysis of high-resolution fMRI data.""" import os class MatlabCommand: """Class for running Matlab commands. Parameters ---------- fname : str Name of the Matlab script to run. *args Variable length argument list to pass to the ...
a4cb4ab78174fd9ca86b0c87639a798805038ca8a2db2215d03df36d1dbda391
Python
1,867
55
""" This module contains utility functions for the MSI project. """ import os import torch import json # Load the trained model from a checkpoint def load_checkpoint(model, checkpoint_path): model.load_state_dict(torch.load(checkpoint_path, weights_only=True)) model.eval() def extract_paths(path_dir, type=...
c320dbe5f0726a6dbace737e9bfec856eafcde4fcfa2ac0cdd6ffa6dbd60beac
Python
1,867
55
import json import base64 import io from PIL import Image import yaml from model_loader import ModelLoader def init_context(context): context.logger.info("Init context... 0%") model_path = "/opt/nuclio/faster_rcnn/frozen_inference_graph.pb" model_handler = ModelLoader(model_path) context.user_data.mo...
28cbc1ed2370529de068533bc857013d42a74776040940d1131937018a68cbf0
Python
1,868
48
import chromatics import json import os import pandas as pd def add_enhancer_distance_to_promoter(df, bin_count = None, bins = None): df['window_start'] = df[['promoter_end', 'enhancer_end']].min(axis = 1) + 1 df['window_end'] = df[['promoter_start', 'enhancer_start']].max(axis = 1) - 1 df['enhancer_distan...
ac1381e533754f56781c68ca87f45f600aa3b0089eb2562f11c9590a36e4792d
Python
1,868
59
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved import os import numpy as np import pytest import torch from PIL import Image from sam3.perflib.masks_ops import masks_to_boxes class TestMasksToBoxes: def test_masks_box(self): def masks_box_check(masks, expected, atol=1e-4): ...