sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
88ad40d97ee8963dbfc83c2e89a09fc5415d9013e6eb0e2d448becdb39936dab
Python
1,243
45
import json import torch import pandas as pd from monai.data import Dataset, DataLoader from monai.utils import set_determinism from lightning import Trainer from classifier import NPhaseClassifier from preprocess import get_preprocess_infer def main(): set_determinism(42) with open("datalist.json", "r") a...
1aba3f29449a69bc82db9e47b58f258c4e3d35db3fa10c25cab3983810cdec6e
Python
1,244
28
from brainscore_vision import model_registry from brainscore_vision.model_helpers.brain_transformation import ModelCommitment try: from .model import get_bibtex, get_layers, get_model, get_model_list except ImportError: import importlib.util from pathlib import Path _MODEL_PATH = Path(__file__).resolv...
39292914124ddcc2be4a008d5784429d772915885dd7eca195ae3680e203f734
Python
1,244
70
#-*- coding:utf-8 -*- #Import urlparse in Python 2 or urllib.parse in Python 3 try: import urlparse except ImportError: import urllib.parse as urlparse from docutils import nodes from docutils.parsers import rst class youtube(nodes.General, nodes.Element): pass def is_url(s): if s.startswith(...
4ad719c06d84f1e5f96121a03ae61b1a252f3fce986a6a4e1c0f308843c765be
Python
1,244
43
''' dynamic import model ''' import importlib def import_model(model_path): # 获取模块路径和类名 module_path, class_name = model_path.rsplit('.', maxsplit=1) # 1 利用字符串导入模块 module = importlib.import_module(module_path) # 2 利用反射获取类名 cls = getattr(module, class_name) # 3 生成类的对象 # obj = cls() r...
562886a6a8ffd0a27ba589be31511bcf13e0a2322d21a794330d87b27a65f652
Python
1,244
28
from brainscore_vision import model_registry from brainscore_vision.model_helpers.brain_transformation import ModelCommitment try: from .model import get_bibtex, get_layers, get_model, get_model_list except ImportError: import importlib.util from pathlib import Path _MODEL_PATH = Path(__file__).resolv...
328b32cb81473c2d8a08b5a0f63c10b36687bb3817ec7debc0cb0e7c894a387a
Python
1,245
40
import numpy as np def remove_duplicate_voxels_from_paths(paths): """Remove duplicate consecutive voxels from the paths Duplicate consecutive voxels are identified and removed - the list of voxels is then shifted to fill in the gaps left by the duplicates, so the format is consistent with the origina...
66cfebcec1449b2c47fc6490f49fa88b77597960322ad2ca7dd715d503cc40dd
Python
1,245
42
# -*- coding: utf-8 -*- """TODO""" import numpy as np import core.core_global as core from core.core_definitions import simulation_timestep from core.monitor import Monitor class WeightMatrixMonitor(Monitor): """TODO""" def __init__(self, source, filename, interval=1.0): """TODO""" super()....
b0365660ee9b2ed7cae0421634cecc7792385c0a42df264eff5cbbe1884d8e6f
Python
1,245
46
""" Download the demo data """ import os import shutil import zipfile from tensorflow.keras.utils import get_file PROJECT_DIR = "demos/unpaired_us_prostate_cv" os.chdir(PROJECT_DIR) DATA_PATH = "dataset" DATA_REPO = "dataset_trus3d-master" ZIP_PATH = "master.zip" ORIGIN = "https://github.com/ucl-candi/dataset_trus3d...
c79cf28d737c886ebf3c34d3b62ed8c1ed663437a31dabca72264a7b0ea51e73
Python
1,246
47
# import sys import os import math #from keras.utils import FeatureSpace import tensorflow as tf import pandas as pd import keras from keras import layers from tensorflow import data as tf_data import random import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.metrics import classification_r...
5b5cc3e746beeb182bfabf561a865f389005be2bc05548124f32290d70169b5c
Python
1,247
42
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 28 17:45:23 2024 @author: brainmappers """ def roi(subjects_dir,subject,hemi,surface,mesh,number): import os import numpy as np import math if mesh=='164k': m=163842 #read csv file and save as lists in...
af929345be03a1f4a7d39f22449c129e579497ca7afa7725068eaaaa095d64f8
Python
1,247
37
# -*- coding: utf-8 -*- """ Percent signal change conversion This scripts converts timeseries data into percent signal change. """ # external inputs import nibabel as nb # local inputs from fmri_tools.io.get_filename import get_filename from fmri_tools.preprocessing.timeseries import ScaleTimeseries # input file_i...
d1036ccec6b42e5b80067191f57afdb168c99ef5aa33db5056895de011e05d01
Python
1,247
29
# Copyright (c) 2026 Rohit Jena. All rights reserved. # # This file is part of FireANTs, distributed under the terms of # the FireANTs License version 1.0. A copy of the license can be found # in the LICENSE file at the root of this repository. # # IMPORTANT: This code is part of FireANTs and its use, reproduction, or...
d7bcbcf1ae7acaed474db806a642ec7d585f3f819c6751bb3f8374f8f1c812a4
Python
1,247
42
import numpy as np from nems import Model from nems.layers.base import Parameter, Phi, Layer from nems.distributions import Normal from nems.tools.json import nems_to_json, nems_from_json def test_save_load(): shape1 = (2,3) shape2 = (1,) d1 = Normal( mean=np.full(shape=shape1, fill_value=0.2), ...
ee407adbc0a153f57440d359046806f810c66b1085dba2b9e9258a40951e72d5
Python
1,247
35
#!/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=['processing.zip']) tmp_dir = tempfile.T...
f513c8c9526da491676e510081cb52061e54cbc64818b268d991aba4bd61f289
Python
1,247
41
import functools import os from rich.console import Console CITATION_LINK = "https://github.com/BrainLesion/preprocessing#citation" def citation_reminder(func): """ Decorator to remind users to cite brainles-preprocessing. The reminder is shown when the environment variable `BRAINLES_PREPROCESSING_...
4c1bc2172da554639da6ff28ea0555332ea34b7edca8a6754118e0547d8bc470
Python
1,248
40
from typing import TypeVar from torch import nn T = TypeVar('T', bound='Module') class BatchEvalModule(nn.Module): def __init__(self, *args, **kwargs): super(BatchEvalModule, self).__init__(*args, **kwargs) self.batch_evaluation = False def batch_eval(self): def set_batch_eval(mod...
7e590a2730047ad528643070c13729d9c2e5ccee91c492cdb9e24cb053e96ce0
Python
1,248
41
# -*- coding: utf-8 -*- # # test_spikes.py import unittest import arbor as A from arbor import units as U from .. import fixtures """ all tests for the simulator wrapper """ class TestSpikes(unittest.TestCase): # test that all spikes are sorted by time then by gid @fixtures.single_context() def test_spi...
de62b0c274a352f63533eccba2dd06239b7ceafb2d9feaf015d44904f4c09e24
Python
1,248
33
import argparse import train import src.config def loso_cv(config, dataset_path=None): '''Starts a leave-one-out cross validation''' config.FOLDS = 0 # Enable loo split # In case sequence length and frame shift lead to cutting of # last part of the signal, shall the last part stay cutted or not #...
37a98b95d14dc0ef47a76f751d397be137d72191b3a3cd960cd530195d4419ca
Python
1,249
41
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...
3bd835ec3b800868e38893cfa6157744d79feefb6eab76e29641cc5fbbe4836b
Python
1,249
42
import sys import numpy as np import matplotlib.pyplot as plt def read_ecg_readings (input_file): data = np.genfromtxt(input_file) nlin, ncol = np.shape(data) timesteps = data[:,0] currents = data[:,1:] num_leads = ncol-1 return timesteps, currents, num_leads def plot_ecg_readings (t, currents, nleads): for...
4144de60d92689bc45bb4f009591b30273077c4a01a7692df68eb9934c267e65
Python
1,249
64
r"""Testing package. This package provides helper methods and decorators to ease testing. """ from .decorators import ( is_full_test, onlyFullTest, is_distributed_test, onlyDistributedTest, onlyLinux, noWindows, noMac, minPython, onlyCUDA, onlyXPU, onlyOnline, onlyGraph...
4b2066926b0a97f6a565c26e88c3d934302f2d1bc1642d568c8e4fd18760efc4
Python
1,249
34
import os import json import torch os.environ['CUDA_VISIBLE_DEVICE'] = '5' import pandas as pd import numpy as np from tqdm import tqdm from pathlib import Path from transformers import * pretrained_weights = 't5-small' tokenizer = T5Tokenizer.from_pretrained(pretrained_weights) model = T5EncoderModel.from_pretrained(...
09972bcbe0045f00608789dace00b16d8f9cc3a01723f157b53bc82e44acb46a
Python
1,250
57
#!/usr/bin/env python """ Application to convert LAV file to AXT file. Reads a LAV file from standard input and writes a AXT file to standard out; some statistics are written to standard error. usage: lav_to_axt [--silent] [path=replacement] < lav_file > axt_file """ __author__ = "Bob Harris (rsharris@bx.psu.edu)" ...
2f41efba4b6e98f230e00a69eb2b12be883b995f602f69255e38461f88162b2e
Python
1,250
48
import pytest from napari_dmc_brainmap.visualization.vis_utils.visualization_utils import ( deduplicate_preserve_order, get_descendants, normalize_seaborn_style, ) @pytest.mark.parametrize( ("style", "expected"), [ ("white", "white"), ("dark", "dark"), ("whitegrid", "white...
38de4872aee93ad850f1db8ef41e4f56a50b9690489dcfa3356e0e6098fae3da
Python
1,250
27
# Copyright (C) 2020-2022 Intel Corporation # # SPDX-License-Identifier: MIT from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter(trailing_slash=False) # https://github.com/encode/django-rest-framework/issues/6645 # I want to "call" my functions....
865cabf5c4241b9630d41cb3db5b5cc96b44d7b6f469ffe76fe13ce036392231
Python
1,250
41
import pytest from impedancefitter.utils import draw_scheme # those were used for testing the code # they do not work with LMFIT!!! # they were just there to check that everything is alright working = [ "RC + R + parallel(R, C) + parallel(R, C)", "parallel(R + R, C + C)", "parallel(R, C)", "parallel(...
4b61aabe54755df19ce3afedcf6a484d1cf7f88cd3d626974bfdf59c37a2cd6e
Python
1,251
45
import sys import yaml import os import h5py import pandas as pd from scipy.stats import scoreatpercentile as sap import numpy as np from glob import glob pathpath = 'PATHS/filepaths_IBL.yml' with open(pathpath, 'r') as myfile: pathdict = yaml.safe_load(myfile) sys.path.append(pathdict['code']['workspace']) from pfc...
e0afd7a0ea9084c66883a90134b08584638cfcd0250285725d8efbac3e245f47
Python
1,251
35
"""Utility and helper functions. Modules ------- - :py:mod:`~osl_dynamics.utils.array_ops` — Array operations (covariance ↔ correlation conversions, matrix decompositions, etc.). - :py:mod:`~osl_dynamics.utils.filenames` — :py:class:`OSLFilenames` for managing pipeline file paths. - :py:mod:`~osl_dynamics.utils.lo...
61c057c07968f8cdf7aad68216a103d4d16e25d21995d4c6f7b240706abfccfc
Python
1,252
46
import logging import anndata import numpy as np import scipy.sparse import unittest import batchglm.api as glm import diffxpy.api as de glm.setup_logging(verbosity="WARNING", stream="STDOUT") logger = logging.getLogger(__name__) class TestAccuracyGlmNb( unittest.TestCase ): """ Test whether optimizers ...
fedd05dfc2d34e09a0e4b8ad9ef96e97ee197920d378437d4d98965a88636dbe
Python
1,252
44
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...
55e9b5a3f44e2203cd904eae34cd826e7ae0b23503743d7bcee21256e0b15234
Python
1,253
48
""" Helper functions for data visualization. """ import math import pandas as pd import numpy as np import plotnine as p9 def shade_plot(X: np.array, Y: np.array, sigma: np.array, x_label: str, y_label: str, width: int = 5, height: int = 3): """_summary_ Parameters ---------- X : np.a...
89dd62062ccca73ad7a9474fb6a0114176f7bb3737e562c2ff3551ba5bc2ca0c
Python
1,253
40
# -*- coding: utf-8 -*- """ Function for extracting rotational component from an affine matrix and writing out in affine form """ import numpy as np from numpy.linalg import svd import argparse # pass arguments parser=argparse.ArgumentParser( description=''' Function for extracting rotational component from an a...
b36b505b752db9428b294a4e83d93bf07713cdcd764ef51f89cb54f4a9532e24
Python
1,254
44
# ----------------------------------------------------------------------------- # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Provides QtWebEngineCore cla...
50972550a2de82e22255ea7f6e6d1eb71f032fae2dbaddf48c858c7dc029303a
Python
1,255
35
""" The task of this file is to split the provided sequences file into training, validation and test data. """ import numpy as np if __name__ == '__main__': filename = "ngs_sequences.txt" split = [0.7, 0.15, 0.15] with open(filename, "r") as file: sequences = file.readlines() sequences = [se...
61336932d091fdaf40968b664f5bcd5caa751a5169d34c5a8b46190b17b37340
Python
1,255
46
import subprocess import tempfile from pathlib import Path from re import subn from typing import Optional from dti.utils import create_mask from gmri2fem.utils import with_suffix def dtifit( dti_eddy_corrected: Path, bvals: Path, output: Path, tmppath: Optional[Path] = None, ): if tmppath is Non...
4e4bac04a503ec46ba451050fd501adfa06d7db325d2b905eb7a6ee5853b29e8
Python
1,257
33
#!/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=['connectivity.zip']) tmp_dir = tempfile...
2083be876d94d9aa94cf7d07df15cd2c9b26abff54c6acf54267940b6f2d3f26
Python
1,258
64
import re # user_to_post.csv»ñÈ¡tweetÁбí # node.json»ñÈ¡postÍÆÎÄ # postÊǸö×Öµä # maybe item = item.replace('\n',' ') def count_characters(text): text = text.replace('\n',' ') return len(text) def count_hashtags(text): hashtags = re.findall(r'#\w', text) return len(hashtags) def count_words(text): ...
2edb7e19961f1a4210c07cad2803cfdada467fe8ce517eca82df35712e42ced1
Python
1,258
41
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from typing import Any from django.apps.registry import Apps from django.db import migrations from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.db.models import Q _RETIRED_EVENT_KEY = "delete:organization" def _remov...
fa451f7c378188b1060036b329a45264217e9364d1712faa709afdb863fb9366
Python
1,258
36
#!/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=['tracking.zip']) tmp_dir = tempfile.Tem...
5b1df47cd88ec9ff92c1710031597b76dba8e3c0bd4bc20016335057b8a2237a
Python
1,259
43
import pytest from scilpy.tests.arrays import fodf_3x3_order8_descoteaux07, \ fodf_3x3_order8_descoteaux07_filtered_unified @pytest.mark.ml def test_get_data_order_6_28coeffs(): """ fODF should keep the same number of coeffs.""" # Imported here so as not to trigger an import error with pytorch from ...
d18333c3f2623997bb07f8f490141c9d06666b02e8549109a09413cef53f465a
Python
1,259
37
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile import nibabel as nib 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=['tractograms.zip...
08912c1af66f94b39668a53a858a37beabdf3948077897f53f57ed999e6d9f2a
Python
1,260
53
""" Load TPC wedges """ from itertools import product from pathlib import Path import numpy as np import torch from .utils import get_data_root def __to_list(arg, default): if arg is None: return default if isinstance(arg, int): return [arg] elif isinstance(arg, [list, tuple]): ...
258c8d4680145c4d5734f97f05da99ff93379251ad906187d7ecdda95b47107b
Python
1,260
43
import numpy as np from scipy.ndimage import binary_fill_holes # Hello! crop_to_nonzero is the function you are looking for. Ignore the rest. from acvl_utils.cropping_and_padding.bounding_boxes import get_bbox_from_mask, bounding_box_to_slice def create_nonzero_mask(data): """ :param data: :return: the ...
d0ee9e4fdf3fb738ae3bd4dec8a17728903a1af58eb17dd340238b387632ec72
Python
1,260
51
""" This script is used to compare the beta values of two orthogonalized regressions """ import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import numpy as np import pandas as pd from scipy import stats def compare_slopes_odr(file_1, file_2): # Read beta and s...
660ea5666b1815a8511ce6ee806d5200ddbf94e8c22f26005c2cf8056039b46d
Python
1,261
55
#!/usr/bin/env python3 import arbor as A from arbor import units as U from util import plot_spikes # global parameters # cell count N = 5 # total runtime [ms] T = 1000 # numerical time step [ms] dt = 0.1 class unconnected(A.recipe): def __init__(self, N) -> None: super().__init__() self.N = N ...
94d6aedbd6d637f4bd76989758cdc18bb78d9c8c0f3adc62baea28cfcc6345a7
Python
1,261
54
import torch from inspect import isfunction import contextlib import tempfile import time from typing import Optional import shutil import logging # from .ss_utils import * def exists(val): return val is not None def default(val, d): if exists(val): return val return d() if isfunction(d) else d ...
fde3f36db89bf8cbc36967047bd1c2bcbc7622ce3865d7dc85e9a71621271821
Python
1,261
28
import numpy as np from ccf_streamlines.angle import vector_to_3d_affine_matrix, find_closest_streamline, determine_angle_between_streamline_and_plane def slice_angle_tilt(pin_df, specimen_id, closest_surface_voxel_file, surface_paths_file): """ Estimate angle of slice from CCF pinning information Parameters...
812ddeaa469d1c1ed60fd3a0b13e3495d284b3421e83531f59b2abff2f0dca91
Python
1,262
45
import numpy as np import cv2 def _clahe(image): #-----Reading the image----------------------------------------------------- if not isinstance(image, np.ndarray): image = cv2.imread(image, 1) #-----Converting image to LAB Color model----------------------------------- lab = cv2.cvtColor(im...
d1ff7c44597731f3f79e08d908567ab8ebe9545912ebde9e8ca3861df0e3be0d
Python
1,263
37
# by Shaoxuan Yuan at 2024/04/22 from PIL import Image, ImageDraw import json def fill_polygon(json_file_path, output_file_path): # 读取JSON文件中的标注信息 with open(json_file_path, 'r') as json_file: json_data = json.load(json_file) # 获取图片的宽度和高度 width = json_data['imageWidth'] height =...
e3bdb0ab9b42610b16ce93deaf407d230a2c560848b53acb94dd81ebdda63c99
Python
1,263
33
import torch from batchgeneratorsv2.transforms.base.basic_transform import ImageOnlyTransform from batchgeneratorsv2.helpers.scalar_type import RandomScalar class MissingModalityTransform_perImage_full(ImageOnlyTransform): def __init__(self, probability: RandomScalar = 0.2, num_channels: int = 4): """ ...
6c974dc57a349776a73d53f33f344a78d16ce521cc82af1da545cf2ee0d206d1
Python
1,265
40
from unittest.mock import MagicMock import numpy as np import pytest from PIL import Image from eir.data_load.data_preparation_modules import prepare_image from eir.setup.input_setup_modules.setup_image import ( ImageNormalizationStats, get_image_transforms, ) @pytest.mark.parametrize("resize_approach", ["r...
ec48c97101703a8429f548ae7da4e31272aa141cc632e8643d81932531c1f331
Python
1,265
37
import os import scanpy as sc import pandas as pd import anndata as ad import numpy as np os.chdir("/data/wuqinhua/phase/covid19/datasets") adata = ad.read_h5ad('./pre_data/6_Liu_2021/sce.h5ad') adata = ad.AnnData(X=adata.raw.X, var=adata.raw.var, obs=adata.obs) submatrix_block = adata.X[:15, :25].toarray() submatri...
f4543d0e00b843f39db8034831e289b1def17d20a9832838236744860e51bae5
Python
1,265
37
# Copyright (C) 2021-2022 Intel Corporation # Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import shutil from datumaro.components.dataset import Dataset from cvat.apps.dataset_manager.bindings import ( GetCVATDataExtractor, detect_dataset, import_dm_annotations, ) from cvat.apps.dat...
41b54d099736d378e6f10117f4a18ff8d71e25d853e99266d16f08af4658b655
Python
1,266
43
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the PyMVPA package for the # copyright and license terms. # ### ### ### ### ###...
9470644370d21486d0274dc7ebf2afbd0c84d1a77a6c30c265d3667a49b917c1
Python
1,266
36
# 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. """isort:skip_file""" from .unicore_dataset import UnicoreDataset from .base_wrapper_dataset import BaseWrapp...
7adc2cb46f44b9cb034633ff633ad7f4069aeb9728135cf86517fe9433cc8a3a
Python
1,267
36
#!/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=['processing.zip']) tmp_dir = tempfile.T...
cc22495390f0e0163820ab5fbb5f1aeeea88de0c3e7a9ce61bd4afbabdaa72ec
Python
1,267
34
import os import glob from .session import BIDSSession class BIDSSubject: def __init__(self, subject_id, bids_dir): self.subject_id = subject_id self.bids_dir = os.path.abspath(bids_dir) self.subject_dir = os.path.join(self.bids_dir, f"sub-{subject_id}") if not os.path.exists(self....
4757e885dd7efa7ab2de88060216e5697403884a665d2f4df0f9833943caf1ce
Python
1,268
36
import pytest from impedancefitter.utils import draw_scheme # those were used for testing the code # they do not work with LMFIT!!! # they were just there to check that everything is alright working = ["RC + R + parallel(R, C) + parallel(R, C)", "parallel(R + R, C + C)", "parallel(R, C)", ...
6acaecbe795abb425801fda31d1b626eaeb87c5812b0cc6d782afe13dfc62fd2
Python
1,268
35
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images import ssl import functools import antialiased_cnns from brainscore_vision.model_helpers.check_submission import check_models ssl._create_default_https_c...
ca8fa71ceba7b878e2256080a8f654a791be0d43da5b9d60ffe9e5814b2ed69b
Python
1,268
43
# Generated by Django 3.2.18 on 2023-06-08 19:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("engine", "0068_auto_20230418_0901"), ] operations = [ migrations.AlterField( model_name="labeledimage", name="sourc...
d9cacfac0f74281f5dc02bffbaf77c2dcfe3762b596ac8636df96f23365ead3f
Python
1,268
39
import numpy as np from argparse import ArgumentParser import json from tqdm import tqdm parser = ArgumentParser() parser.add_argument('--dataset', type=str) args = parser.parse_args() dataset_name = args.dataset assert dataset_name in ['Twibot-22', 'Twibot-20', 'cresci-2015'] n_hidden = 128 if __name__ == '__main...
fad1a57d8e8773da82a9ec323835a97195834b352f58129a638422a64ddcbdf7
Python
1,268
29
import os import subprocess import shutil import nibabel as nib import numpy as np import pandas as pd from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec, TraitedSpec, File, Directory, traits, CommandLineInputSpec, File, TraitedSpec, CommandLine, Directory from nipype.interfaces.utility import Ide...
aa6b79fd570b84d608dc29249fc23b09812c01012ba5ef1940cd78645b1a0f4f
Python
1,269
37
import numpy as np def harm_probas(agesA, agesB, bins): """ Computes a sampling probability given ages from two datasets and consecutive age ranges. ---- PARAMETERS: agesA: list of ages in the first dataset agesB: list of ages in the second dataset bins: list of ages correspondi...
195c09f0bf022377feefb69ab61df34089771be43e7f566155a9d7b7c3e8a93c
Python
1,270
35
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from pathlib import Path from typing import Any from django.dispatch import receiver from rq.job import Job as RQJob from cvat.apps.dataset_manager.cron import InstanceTmpDirectoriesCleaner, TmpDirectoryCleaner from cvat.apps.engine import backgrou...
47e578cce00f3959a53c890d68c676f6e490a3a0fb505495033bda3b4e291b1e
Python
1,270
33
""" Predicted concentration vs estimated concentrations for the Look Locker and Mixed sequences with a given SNR """ import matplotlib.pyplot as plt import click from plot_noise_look_locker import plot_estimated_versus_actual as plot_look_locker from plot_noise_mixed import plot_estimated_versus_actual as plot_mixed ...
7c21cd088e8c4a369deb21ed15c2343009dc50f6111e8c4c092d50dc5588fdb6
Python
1,270
20
from testsetclass import TestsetClass class ALKBDE10(TestsetClass): def __init__(self): self.weak = 1.0 self.molecules = ['cao', 'be', 'lio', 'mg', 'na', 'lif', 'ca', 'nao', 's', 'f', 'o', 'h', 'mgo', 'mgs', 'hf', 'kf', 'beo', 'bef', 'li', 'k'] self.exp_values = {'0': 138.7, '1': 106.6, '2...
0057b04298cbcbb918fab5ccdb3a055880cf8f45c10cd934ce7593520cac7c95
Python
1,271
47
# -*- coding: utf-8 -*- from time import time def get_duration(start_time, decimal=2): """ Convert a duration in seconds """ return round(time() - start_time, decimal) def is_float(value): """Returns True if the argument can be casted to a float.""" try: float(value) return True ...
5923880dfc99918058517058dff3579435b50ef7bed4981e55ffab8c51be9e77
Python
1,271
36
############################################################################# # Copyright (C) 2020-2026 MEmilio # # Authors: Henrik Zunker # # Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
71d04c60fcc7394dc2b9972de2c6219c579c929709cdc298662977a12a085740
Python
1,271
35
#!/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=['processing.zip']) tmp_dir = tempfile.T...
384c68ab8cca69d1f8b23b1ec1b2d503e05da8055d54ec43685ce717102237f0
Python
1,273
41
# ----------------------------------------------------------------------------- # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Provides QtSql classes and f...
b7006240f63d952e6087d6b94be0404b828d6857a199541e824b6cb7efa6abd0
Python
1,274
27
"""A collection of miscellaneous utility functions. TODO: Anything that used to be in nems.utils.py should go in this directory, with functions of similar purpose grouped in modules. Even if there's just one function that belongs in a solo group, it should *not* just be dumped in 'misc' or 'etc' or a...
29cd9b84c8a8677113fd14a61ed5820c918dc6a2be8dd19d8e6756b3162a6490
Python
1,276
39
import pytest from qtpy import PYQT5, PYQT_VERSION, QtXml def test_qtxml(): """Test the qtpy.QtXml namespace""" assert QtXml.QDomAttr is not None assert QtXml.QDomCDATASection is not None assert QtXml.QDomCharacterData is not None assert QtXml.QDomComment is not None assert QtXml.QDomDocument...
8bf48dc821e4a30dd55e9d0ba584c843b2c1683f77050fb5e941c21c6b82261b
Python
1,276
54
from typing import Literal, ClassVar from matplotlib import pyplot as plt from argclz import argument __all__ = [ 'PlotOptions', 'FIG_MODE', ] FIG_MODE = Literal['simplified', 'presentation'] class PlotOptions: """Plot options (i.e., figure style, dark theme, ...)""" GROUP_PLOT: ClassVar = 'Plot ...
b69722cdafc6406cf060e8ebc3b0d808e7658c6a0c477f4cd03f6cd412a5b894
Python
1,276
34
import torch from batchgeneratorsv2.transforms.base.basic_transform import ImageOnlyTransform from batchgeneratorsv2.helpers.scalar_type import RandomScalar class MissingModalityTransform(ImageOnlyTransform): def __init__(self, probability: RandomScalar = 0.2): """ Custom transform to randomly set...
3beaa32759a93a8484d58bed33a276acac1b2aa60907affcf6b12f2132e3575f
Python
1,277
53
from typing import List, Union import numpy as np import tensorflow as tf from deepreg.constant import EPS def is_equal_np( x: Union[np.ndarray, List], y: Union[np.ndarray, List], atol: float = EPS ) -> bool: """ Check if two numpy arrays are identical within a tolerance. :param x: :param y: ...
052bffaba7970ddfe0e92f196cafb7297045d45cfdded8fa1493618866aa6cb2
Python
1,278
37
#!/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...
92ced681731dba7a1d041c057e3d579b4a829b6dc04f3b7cb1eb4785f9b2429e
Python
1,278
38
from typing import Set from zigzag.classes.hardware.architecture.core import Core from zigzag.classes.hardware.architecture.memory_instance import MemoryInstance class Accelerator: """ The Accelerator class houses a set of Cores with an additional Global Buffer. This Global Buffer sits above the cores, an...
99755e1d74e2207652f4b70ab4c6ead857821ef7cc45cc9ad985c2403e2a2292
Python
1,278
43
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ from os import listdir import pandas as pd tallyfile=pd.DataFrame() filedirectory='filtered' files=listdir('filtered') z=0 for file in files: if file.endswith('.summary'): unclassified=0 total=0 ...
adacb6652c1c524e5891f5e1de108d4c53046cf92f6de7f4fa8620b8d292ed6c
Python
1,279
34
import torch.nn as nn from Model.resnet import resnet18, resnet34, resnet50 from Model.vgg import vgg16_bn, vgg19 from efficientnet_pytorch import EfficientNet from Model.DenseNet import densenet121 import pretrainedmodels def create_model(model, pretrain): if model == 'vgg16_bn': Model = vgg16_bn(pretrai...
ae76257dac17c3aaf4f0302d8e780d57ef53d681dc0ea04a967b2e20af3721b0
Python
1,279
28
# Copyright (c) OpenMMLab. All rights reserved. def make_divisible(value, divisor, min_value=None, min_ratio=0.9): """Make divisible function. This function rounds the channel number to the nearest value that can be divisible by the divisor. It is taken from the original tf repo. It ensures that all la...
a4bb3ce86724f8a1c266d539ac37ea9710ce3fb58f480236efdd98c3ba0a8abb
Python
1,280
39
"""Filter CSV files in a directory to keep only rows with valid RDKit SMILES.""" from pathlib import Path import pandas as pd from rdkit import Chem from tap import tapify from tqdm import tqdm def filter_valid_smiles( data_dir: Path, smiles_column: str = "smiles", ) -> None: """For each CSV in the dire...
a9ec826454798b48e12c662a1c4d976097b335352ffd0112e5794312ea349235
Python
1,280
49
# -*- coding: utf-8 -*- # python standard library inputs import os import sys # external inputs from nipype.interfaces.freesurfer import Curvature def get_curvature(file_in, path_output, a=10): """Get curvature. This function calculates a curvature file for an input surface mesh using freesurf...
db2feb7ff5d4dfa6d60daf1b2929f83cf834eff046e276d5a18101c139d91834
Python
1,280
28
"""TensorFlow layers, callbacks, and utilities used by the models. This subpackage contains the building blocks that the model classes in :py:mod:`osl_dynamics.models` use internally. Most users will not need to interact with this subpackage directly. Modules ------- - :py:mod:`~osl_dynamics.inference.layers` — Custo...
0d6e3378c7936c75693ca0f32014e35b3e8666414075c4f9e03bd5cdebe7bc4d
Python
1,281
46
# fmt: off # flake8: noqa import csv import os from collections import OrderedDict def validate_metrics_list(metrics_list): """Get names of metric class and ensures they are unique, further checks that the fields within each metric class do not have overlapping names. """ metric_names = [metric.get_n...
94ca2320a60584679b75699e31fccbd1a5463fd6a6f12cac2017ca29776daaae
Python
1,281
39
# ============================================================================= # MODULES AND ENVIRONMENT VARIABLES # ============================================================================= # Python built-in import os import sys import time import logging import json import pickle import re import math import im...
995698624b10052e7b219dec0f3c6f40891129807b2d29ec2e25681f83d414a1
Python
1,282
51
# -*- coding: utf-8 -*- # python standard library inputs import os # external inputs from nibabel.freesurfer.io import read_morph_data, write_morph_data, \ read_geometry from scipy.interpolate import griddata def morph2dense(source_sphere, target_sphere, input_morph, path_output): """Morph to dense. ...
a7e49889fce39ef8f72310fd40016e865965f5842cb065c4a10f757811809e68
Python
1,282
44
import numpy as np from pyment.metrics.r_squared import R2 def test_result_is_one_for_perfect_predictions(): metric = R2() metric.update_state([1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0, 4.0]) assert np.isclose(metric.result().numpy(), 1.0), ( 'Expected R2 to return 1.0 for perfect predictions' ) ...
b75b942e3ca5fd10a5407dfdf7cfe38d95ab8246ea625da99cd66bf567307a15
Python
1,282
24
from typing import Union, List, Tuple import torch from batchgeneratorsv2.transforms.base.basic_transform import SegOnlyTransform class ConvertSegmentationToRegionsTransform(SegOnlyTransform): def __init__(self, regions: Union[List, Tuple], channel_in_seg: int = 0): super().__init__() self.region...
0f041496047b1e6ff8425ad7a5d7c68b2491cff0ede2ac54e7559274480b7e1d
Python
1,283
44
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html import os import sys sys.path.insert(0, os.path.abspath("../../")) # -- Project information -----------------------...
6d44fcd443b0a7df4340baae4807d47f6f2362933c38413aaea0d2081d55ab52
Python
1,283
42
from __future__ import annotations import pytest from PySide6.QtCore import QPointF from pytestqt.qtbot import QtBot import labelme._utils from labelme._app import MainWindow from labelme._widgets._brightness_contrast_dialog import BrightnessContrastDialog from ..conftest import close_or_pause @pytest.mark.gui def...
7a90362e8f74aea28aa928232ccdb529215908050a3dc5edc6f4a3fed767b3c6
Python
1,285
53
import dataclasses from collections.abc import Callable import torch from torch import nn from eir.models.fusion.fusion_default import al_features, default_fuse_features al_identity_features = Callable[[dict[str, torch.Tensor]], dict[str, torch.Tensor]] @dataclasses.dataclass class IdentityConfig: pass def p...
03ea0fb1f0339c33cf27391c3bac56160ba8ea52a6aed7320be97ab12b550bf0
Python
1,286
47
from ..qt import * from ..observable_item_models import TreeObservableCollectionModel from ..config import ObservableDict import logging LOGGER = logging.getLogger(__name__) class PersistenceWidget(QWidget): def __init__(self, config: ObservableDict): super().__init__() LOGGER.debug('%s', config) if '...
341c8fd97aae6e46edf642a6e7ce4cec3ac563d5ec0d7187f10b883df2f53c9b
Python
1,286
60
import numpy as np from impedancefitter.double_shell import double_shell_model from impedancefitter.single_shell import single_shell_model omega = 2.0 * np.pi * np.logspace(0, 12, num=30) # for cole_cole_model c0 = 1.0 em = 10.0 km = 1e-6 kcp = 0.5 ecp = 60 kmed = 0.1 emed = 80 p = 0.1 dm = 5e-9 Rc = 5e-6 # fo...
c235a54e0dd0eba0bd9d7882fd949b7668340721ef9d15b298681c840f9498fe
Python
1,286
38
import os import json import torch import pandas as pd import numpy as np from tqdm import tqdm from pathlib import Path path1 = Path('datasets/Twibot-20/node.json') with open(path1, 'r') as f: nodes = json.loads(f.read()) nodes = pd.DataFrame(nodes) users = nodes[nodes.id.str.contains('^u')] tweets = ...
2dfa7f74abf81c867d0ca08140c378f44eb17361e2d9581ec67f49024e0b4b81
Python
1,287
45
# -*- coding: utf-8 -*- """ Created on Fri Oct 21 12:26:17 2022 @author: tianj """ import torch.nn as nn import torch # Discriminator model class definition class Discriminator(nn.Module): def __init__(self, patch_size: int): super(Discriminator, self).__init__() ...
4e34815e2f95541243cbc154717cb4e46a0ec8142feed0da29770e9f2a18aaf8
Python
1,287
41
from typing import TYPE_CHECKING from eir.models.output.sequence.sequence_output_modules import SequenceOutputModule from eir.setup.output_setup_modules.sequence_output_setup import ( ComputedSequenceOutputInfo, ) al_sequence_module_classes = type[SequenceOutputModule] if TYPE_CHECKING: from eir.models.model...
e75745c52c6df825c0f83d7d512476a0212b8caf8f82f1b9bb1fa710bf9c614f
Python
1,287
38
class TestSegment(): # Parse command line arguments with all required parameters def test_parse_with_all_required_parameters(self): # Given import sys from argparse import Namespace from python.segmentation.segment import parse # Save original sys.argv origi...
0e320e7ea6289ec1ce533110b6d77dcb16f85b28bd1672c18651f2f4ad33889a
Python
1,288
37
# -*- coding: utf-8 -*- """ Created on Tue Dec 3 17:19:44 2019 @author: Yoshi """ import numpy as np from statistics import mean def data_reader(image_stack,cell_arrays,background_arrays): # Creates empty array to store data in image_total = image_stack.shape[0] cell_total = len(cell_arrays) ...
5e4530ba6023958fd74eba52d8923c37f9b1bdf830beab03e7b19c916b07af00
Python
1,288
46
"""Pydantic configuration for FastSurfer dataset loading.""" import os from typing import Any, Callable from numpy.typing import ArrayLike from pydantic import BaseModel from ..data.fastsurfer_dataset import FastSurferDataset class FastSurferDatasetConfiguration(BaseModel): """Configuration for a FastSurfer da...
afe340d67e953dff530e6b4327590a234b06009a5f9ecc948bb32aa1be157595
Python
1,288
50
#!/usr/bin/env python """ Complement the regions of a bed file. Requires a file that maps source names to sizes. This should be in the simple LEN file format (each line contains a source name followed by a size, separated by whitespace). usage: %prog bed_file chrom_length_file """ from bx.bitset_builders import binn...