sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
1da1917cc1df93bd42f10e87e5d454aab3d006998a107a1922dda5e044a359ec
Python
3,099
119
import os import sys import pandas as pd #sys.path.append('C:/Users/User/Dropbox/PC (2)/Documents/GitHub/BBC') # define starting datafolder #this is the directory import os import platform platform.system() # define starting datafolder if platform.system()=='Darwin': os.chdir('/Volumes/BBC/BBC/WP1/data/EEG...
cd41317345ab1df5b19c55026ff2252a404c20b5a8abf024757c83b1ba477ffa
Python
3,100
75
# fit probablistic representation manifold (PRM) of the grid cell population in different speed bins import numpy as np import matplotlib.pyplot as plt import os import copy import hickle as hkl from grid_cell.speed_partition_processor import Speed_Partition_Processor from grid_cell.manifold_fitter import GP_Fitter fro...
163e20ec90b3afd9b3b8b2c92cc3f49885a8b16e81c6d6e07844f92e20118f83
Python
3,101
76
import numpy as np import pandas as pd from enum import Enum import tensorflow as tf from tensorflow import one_hot from tensorflow.python.keras.layers import Concatenate from utils.constants import GLM_HMM_SIMULUS_VALUES class CognitiveModel(Enum): PRL4 = 1 PRL_foraging_dynamic = 2 HRL2 = 3 GLM_HMM...
645235a338bc6dec8765570fa239393406ee6cd89315b54522a147a0856e8f07
Python
3,101
92
from medperf.exceptions import InvalidArgumentError import pytest from medperf.tests.mocks.dataset import TestDataset from medperf.tests.mocks.training_exp import TestTrainingExp from medperf.commands.dataset.associate_training import AssociateTrainingDataset PATCH_ASSOC = "medperf.commands.dataset.associate_training...
ac84352fb28bc0ea5ab0d441358d1c6d85a49d7f9f737e65178524a6466e41b6
Python
3,101
94
"""Unit tests for FrameSourceRead provider.""" import ase import msgpack import numpy as np import pytest from zndraw.providers.frame_source import FrameSourceRead @pytest.fixture def water(): """Simple water molecule for testing.""" return ase.Atoms("H2O", positions=[[0, 0, 0], [1, 0, 0], [0, 1, 0]]) @py...
cfd374d0917a052f5f52937531b0f1bd04797f0d25536c077ec164913d833920
Python
3,101
93
# Script to fit the maximum correlation between diffraction patterns to solve for strain, tilt_lr, and tilt_ud # This method was developed by Tao Zhou (tzhou@anl.gov) import os import numpy as np from math import * import time from skimage import io # Data folder folder = '/SOME_PATH/NanobeamNN/data' # Load the expe...
f3440ed22ade871052886cd0a692d22318648a9f9fca5877a5c972543e0104f6
Python
3,101
80
#!/usr/bin/env python # Noise2Void - 2D Example for RGB Data" # Using TensorFlow backend from n2v.models import N2VConfig, N2V import numpy as np from csbdeep.utils import plot_history from n2v.utils.n2v_utils import manipulate_val_data from n2v.internals.N2V_DataGenerator import N2V_DataGenerator from matplotlib impor...
5729d20b7d9101bba6e6fb9b5d7d2be27612a2473d09abb2ae79290e866b8129
Python
3,102
87
from collections.abc import Mapping, Sequence from typing import List, Optional, Union import torch.utils.data from torch.utils.data.dataloader import default_collate from .batch import Batch from .data import Data from .dataset import Dataset class Collater: def __init__(self, follow_batch, exclude_keys): ...
86ac8d0ab2db585087d524a61a1cab612b4d2d21b6333e55af48086582e08ae1
Python
3,102
107
# Configuration file for the Sphinx documentation builder. # -- Project information from os.path import dirname, abspath, join from sys import path as syspath # import time # from datetime import datetime from sphinx.application import Sphinx # If extensions (or modules to document with autodoc) are in another direc...
baf19318f473eb25a4c8c9f5a6e18f3098efb77c634d0f1d7cc48a02cdc77bca
Python
3,102
80
#!/usr/bin/env python # Noise2Void - 2D Example for RGB Data" # Using TensorFlow backend from n2v.models import N2VConfig, N2V import numpy as np from csbdeep.utils import plot_history from n2v.utils.n2v_utils import manipulate_val_data from n2v.internals.N2V_DataGenerator import N2V_DataGenerator from matplotlib impor...
52af3086407d5ff135aa1e2f16c89c2e80069569bfa7599c6e41d70cc3e96b82
Python
3,105
73
"""Shared plumbing for serving a pipeline step's result view on the persistent main app. Each step that shows results after its compute job (preprocess, transients, …) opens a browser tab on a dedicated route of the always-running main server. The compute job and the server share the main process, so the per-tab conte...
fa1040cf252426a466033d46d4ebb487cc8c980e65c2ad0d5f6d37f22130c217
Python
3,106
118
import os import re import yaml import time import numpy as np import pandas as pd import pathlib as pl import subprocess as sp from matplotlib import pylab as plt configFilePath = None def changeWorkingNetwork(network='Gazer'): """ """ if network == 'Gazer': global configFilePath configF...
d33ca598aec67659b2bf5991e166fb21de1f7f1af3a32397af1c68030d30655d
Python
3,107
96
# -*- coding: utf-8 -*- """ Created on Wed Sep 25 11:36:10 2024 @author: AC """ import pandas as pd from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, roc_auc_s...
9d79ea1e5c54f83ca0c1e2c0b25d265f6ef532d4943b6042c4ccf9b5e1ec195a
Python
3,109
67
import numpy as np import pandas as pd import pytest from guppy.analysis.group_tables import stack_member_tables, summarize_member_tables @pytest.fixture def member_tables(): """Two members' tonic means over the same two epochs, listed in different orders.""" first = pd.DataFrame( {"mean_zscore": [1....
a479981a2ec7da92ce9035d6f458b5df650be6eef2be487e09647a508c6e0e85
Python
3,109
73
#!/usr/bin/env python3 """ after downloading redcap data, convert it into table for Inclusion Enrollment Report # multiindex # grab rows that have "Consent" in it. " # TODO: insert columns # calculate totals """ import os, sys, glob import itertools import pandas as pd import numpy as np import datetime from pathlib i...
5cc2a154fe5be231e1fcc151db78def17947fc466abed077fc23c9b888b408f7
Python
3,111
69
#!/usr/bin/env python """ extract dvars and fd info from fmriprep_confounds_timeseries calculate mean and append it with BIDS data """ __author__ = "Heejung Jung, Owen Collins" __copyright__ = "Spatial Topology Project" __credits__ = [""] # people who reported bug fixes, made suggestions, etc. but did not actually wri...
9d1061b9b368c9b5aabb47fe3c688205741166abc8fe2c649e5636ce9e0eccfb
Python
3,111
123
import shutil import tempfile from collections.abc import Callable, MutableMapping from io import StringIO from typing import cast import pytest from cwl_utils.types import CWLObjectType, CWLOutputType from cwltool.main import main from cwltool.secrets import SecretStore from .util import get_data, needs_docker, nee...
fb7b6563b8b825c4b33a69554dcd62eb1c6234ccd8eabb3eaa7a2d6521a967f3
Python
3,111
96
import os # os.chdir('../..') import sys sys.path.append(os.path.abspath("/home/harryc/github/CCF_translator/")) import os from brainglobe_atlasapi.bg_atlas import BrainGlobeAtlas import CCF_translator as CCF_translator import nibabel as nib import numpy as np import nrrd import requests import io import tempfile ...
8b49e0d057664422e6710acdb9ae32b6dd6fe7d6eefda25a53a6932c91459a38
Python
3,112
75
#!/bin/env python import pickle import utils file = open('../database.pickle', 'rb') database = pickle.load(file, encoding='latin1') file.close() utils.convert_to_json('../database.pickle', '../database.json') #Put it in a nice table for easy parsing. Use semicolons to separate fields, making sure each individual fi...
cf4d28338c354b8fc5244394dc6ea51b91f0c23acae447d5b29642bbf65a42d1
Python
3,112
78
"""Utilities for preprocessing sequence data. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from keras_preprocessing import sequence from .. import utils pad_sequences = sequence.pad_sequences make_sampling_table = sequence.make_sampling_table skipgra...
54054857fe76a564a4dc7f0401fa8a0203355230af84dde1750809a30debb2ac
Python
3,114
88
from PyQt5 import QtGui, QtWidgets, QtCore import pyqtgraph as pg import numpy as np from copy import deepcopy from util.conf import fs_fft_params from util.functions import movingAverage from features.Feature import Feature class PowerSpectrum(Feature): def __init__(self, data, parent=None, liveplot=None): ...
5a55d441f8f3e63ad9f1b5bdd5e22267e2a512f0b3a623710f98d383cfecc41f
Python
3,114
105
import os import sys import numpy as np import yaml # Parameters to randomly screen num_configs = int(sys.argv[1]) if len(sys.argv) > 1 else 10 mode = sys.argv[2] if len(sys.argv) > 2 else "w" # Default to overwrite mode output_dir = "screen_configs" os.makedirs(output_dir, exist_ok=True) # Initialize RNG for repro...
96c176b0bd70c06933a97a49475945f82314d60b529ee4ec251cf0c7d773e058
Python
3,117
110
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import tensorflow as tf from tensorflow.keras.losses import Loss # ============================================================================= # distance calculations # ============================================================================= de...
9f431a4ec05abdb6ef0f3341efaabcc8644c0949bbf02dba96a4f3ff04a57d19
Python
3,117
99
"""Utilities for the XGBoost Dask interface.""" import logging import warnings from typing import Any, Dict, Optional, Tuple import distributed from ..collective import Config LOGGER = logging.getLogger("[xgboost.dask]") def get_n_threads(local_param: Dict[str, Any], worker: "distributed.Worker") -> int: """G...
1e6ac473b4e918b296b4d9417dc67ec0735896795b9c65d2039ec21a1582cabd
Python
3,118
81
import csv import logging import requests from src.babel_utils import make_local_name from src.util import ensure_parent_dir def readlabels(which): swissname = make_local_name(f"UniProtKB/uniprot_{which}.fasta") swissprot_labels = {} with open(swissname) as inf: for line in inf: if l...
3b76efba132a953033268bcd62a6faca16b8841b61684ba25a0fc90c247bd3a4
Python
3,120
85
import torch import torch.nn as nn from nnunet_mednext.network_architecture.custom_modules.custom_networks.nnFormer.nnFormer_tumor import nnFormer as nnFormer_Orig from nnunet_mednext.training.network_training.nnUNet_variants.architectural_variants.nnUNetTrainerV2_noDeepSupervision import \ nnUNetTrainerV2_noDeepSu...
77fc2b7949cc523a7085902a5cb31ab45b808efdfa2a690193dcf8c30c6c4b00
Python
3,121
88
# -*- coding: utf-8 -*- import urllib, json import http.cookiejar as cj class CatmaidInstance: """ A class giving access to a CATMAID instance. """ def __init__(self, srv, catmaid_usr, catmaid_pwd, http_usr=None, http_pwd=None): # Store server and user information self.server ...
ba2bafe39001818a7d80002ada5b77766d99545d9cce2779704de9df37a52b9e
Python
3,121
108
# SPDX-License-Identifier: Apache-2.0 import cv2 import numpy as np from skimage import transform as trans def parse_lst_line(line): ''' Helper function for line parsing ''' vec = line.strip().split("\t") assert len(vec)>=3 aligned = int(vec[0]) image_path = vec[1] label = int(vec[2]) bbox = None ...
e09081fc552544f4dadcc9f61979486d4bf19e6b66c50add0bf0b49a8357a6e3
Python
3,121
89
# Atlas-related PyQt5 threads from typing import Any, Callable, Optional, Sequence, TYPE_CHECKING from PyQt5 import QtCore from magmap.atlas import ontology from magmap.settings import config if TYPE_CHECKING: from magmap.plot import plot_support _logger = config.logger.getChild(__name__) class RemapLevelThre...
3e1c7bced382f7f471ccf8f1ddd5607c026e2778a4a0e568f63efa3d5d8d1685
Python
3,122
121
# -*- coding: utf-8 -*- # @Author: Theo Lemaire # @Date: 2023-11-10 17:02:12 # @Last Modified by: Theo Lemaire # @Last Modified time: 2023-11-21 15:03:15 import re import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns ''' Reproduction of experimental data from: Owen et al., ...
5d2793b873ce5b9dee48275ee399eb1bc7e7d4d07bf093efc2082c87d8cbe91e
Python
3,122
77
import os from medperf.entities.dataset import Dataset from medperf.utils import sanitize_path, tar, generate_tmp_path import medperf.config as config from medperf.exceptions import ExecutionError, MedperfException import yaml class ExportDataset: @classmethod def run(cls, dataset_id: str, output_path: str): ...
823085b654b38a51edb0653cf7559579f928b824fb98cf592216983269091325
Python
3,123
69
import torch import torch.nn.functional as F from fengshen.models.transfo_xl_paraphrase import TransfoXLModel from fengshen.utils import top_k_logits, get_masks_and_position_ids from transformers import T5Tokenizer def get_batch(context_tokens, mem_length, batch_size=1): tokens = context_tokens tokens = token...
b2c05a69e5214c1c5e5d037b8fab708cb00d8d33e1551ebfc633a5acc30e5a01
Python
3,125
111
"""Checking the gradient steps for pypesto""" import amici import matplotlib as mpl import numpy as np import time import petab import logging import pypesto.optimize as optimize import pypesto.petab import pypesto.profile as profile import pypesto.sample as sample import pypesto.store as store import pypesto.visualiz...
94b70bfd06c164221df8e45abe644a0609dba172d1bd58f0edcab50ae6891a97
Python
3,127
86
import numpy as np import time from . import _eval_protocols as eval_protocols def generate_pred_samples(features, data, pred_len, drop=0): n = data.shape[1] features = features[:, :-pred_len] labels = np.stack([ data[:, i:1+n+i-pred_len] for i in range(pred_len)], axis=2)[:, 1:] features = features[:,...
3bfbffee384ebe42c1caaed422fda18ee18b92ab76d230dd1096d8f73283e0bd
Python
3,129
81
import pyoxigraph from src.babel_utils import parse_rdf_literal, pull_via_urllib from src.categories import MOLECULAR_ACTIVITY from src.prefixes import EC def pull_ec(): pull_via_urllib("https://ftp.expasy.org/databases/enzyme/", "enzyme.rdf", subpath="EC", decompress=False) class ECgraph: """Load the mesh...
49f14f3153c2d1baa579c6c0dc6d0f1193e8c3085332e5e9e936e27bd9d858db
Python
3,129
76
import numpy as np import gpflow import tensorflow as tf from tensorflow_probability import distributions as tfd from grid_cell.gaussian_wishart.src.likelihoods.WishartProcessLikelihood import WishartLikelihood from grid_cell.gaussian_wishart.src.models .SVGP_deprecated import SVGP_deprecated class WishartProcessBase(...
c87f45c9b8d754d1b6bbf5f2804f7e48b6cdb8926c72eedb40bb66972368a48e
Python
3,130
107
import os import pytest from kgx.transformer import Transformer from tests import RESOURCE_DIR, TARGET_DIR from tests.unit import clean_database from kgx.config import get_logger from tests.integration import ( check_neo4j_container, NEO4J_CONTAINER_NAME, DEFAULT_NEO4J_URL, DEFAULT_NEO4J_USERNAME, ...
56e2c99478a249bc9efdc0d0a9cee0d09ac80b774f30b424511e611fd6fa44be
Python
3,134
101
from .ProvenanceObject import ProvenanceObject from .attribute import Attribute from .extractor import Extractor from .set_type import SetType class Set(ProvenanceObject): """ This class defines a dataflow set. Attributes: - tag (:obj:`str`): Set Tag. - type (:obj:`SetType`): Set Type. ...
b44e5c68c41c9fa5f2300cdaf49358b3edf0b87571343b2ee3d02323e3967916
Python
3,134
87
import random import numpy as np import pandas as pd from scipy.cluster.hierarchy import leaves_list, linkage, optimal_leaf_ordering from sklearn.cluster import KMeans def sub2ind(array_shape, rows, cols): ind = rows * array_shape[1] + cols ind[ind < 0] = -1 ind[ind >= array_shape[0] * array_shape[1]] = ...
e386f335d8ca4df835a6cea1aca5e7397f226c167f15a0a994c3ff6084463df7
Python
3,135
97
# tests/test_router_task_claim.py """Tests for task claim endpoint using shared fixtures.""" from conftest import make_room_address from zndraw_joblib.schemas import TaskClaimResponse def test_claim_task_returns_null_when_empty(seeded_client): worker_id = seeded_client.seeded_worker_id response = seeded_cli...
72fe2cfddb1e9638b141c6be77a0486db9869fd824e26c7560d245dbc610d42b
Python
3,136
97
baseFileName = './shellScripts/LIF_TEST' baseSimTag = 'LIF_2_CLASS_' def generateCommand(trial_num=0, num_trials=10, learning_rate=0.001, sim_tag='default', exc_hid_rat=0.5, epochs=30, log_file='example.log', obj_dir='./data/obj', w1_std=-1, w1...
b9afc4219a866fe54bed6c42af74c7028276fc0944ff5dde92032b49ec71a02b
Python
3,136
77
# import cProfile, pstats # pr = cProfile.Profile() # pr.enable() os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # GPU is not needed for this small dataset # test the performance of methods depending on the number of datapoints import numpy as np import matplotlib.pyplot as plt import hickle as hkl import os from grid_cel...
beef04a9976d401613c8c349dbe26e30a38a7f7d796ec8edba22c899c48bc555
Python
3,137
81
from pathlib import Path import pandas as pd import pytest from guppy.orchestration.import_custom_events import build_custom_events_template @pytest.fixture def template(panel_extension, tmp_path): return build_custom_events_template(str(tmp_path)) def _set_row(config, index, name, text): while len(config...
1f726624ed174ffbdd12b0998f77c6505f36203be6a233ca0ec411db9b7265bd
Python
3,138
110
""" Algorithms to extract various features of interest for outlier detection methods. """ from os import makedirs from os.path import exists as pexists, join as pjoin, splitext import numpy as np from visualqc import config as cfg from visualqc.utils import read_image, scale_0to1 def t1_histogram_whole_scan(in_mr...
f0a465323bbbed077ed0e3912a9782929028c0e69405425422581ca5d252d47e
Python
3,138
98
# This file is part of h5py, a Python interface to the HDF5 library. # # http://www.h5py.org # # Copyright 2008-2013 Andrew Collette and contributors # # License: Standard 3-clause BSD; see "license.txt" for full license terms # and contributor agreement. """ Versioning module for h5py. """ from typing ...
c30d1807b775152fa1f0669ba6db36c5c89656bba56ea25c09706c2b1d541a43
Python
3,139
93
import glob import os import shutil import string import subprocess import tarfile import random def generate_random_str(length): return ''.join(random.choice(string.ascii_lowercase) for _ in range(length)) def copy_matching_paths(src_pattern, dst, root_dir=''): if type(src_pattern) is str: matching...
b13d9457b74bd0d5a453f6c807499f7ba63fc8f8b4a9effb95a6cbf4601cc03d
Python
3,140
73
import catmaid.fields from django.conf import settings import django.contrib.postgres.functions from django.db import migrations, models import django.db.models.deletion forward = """ CREATE TABLE catmaid_writable_stack ( id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, user_id int REFERENCES ...
f9e83ad7208cb6f14b454c628c2a3d2eb4db78867d8fa3a4f0dbba5cda33f881
Python
3,140
95
"""Unit tests for the delta-varint codec (encode_intlist / decode_intlist).""" import pytest from eggnogmapper.annotator import encode_intlist, decode_intlist # --------------------------------------------------------------------------- # Roundtrip helpers # ---------------------------------------------------------...
63a8671e9f79545b6a7184d31188a2047c943bd47784766a3c43663c28b2e560
Python
3,143
74
# -*- coding: utf-8 -*- """ Created on Mon Jun 10 16:54:02 2024 @author: mbmad """ from patchanalysis.measures.measuretools import NoResultError, InvalidRecordingError, \ withinEachSweep, withinEachSweepHzXuYuCu from patchanalysis import TimeSpan, FullSpan, NullSpan from scipy.signal import find_peaks import num...
82505ec6f9c97aeb0ef6f90587114817407cb75e2d21b1f5c2265146fc2fe57f
Python
3,144
94
"""Shared bootstrap for the default @internal filesystem provider. Used by both the in-process taskiq worker (``zndraw.database.lifespan``) and the standalone taskiq worker (``zndraw.broker``). Centralizing the construction keeps both call sites in lockstep. """ from __future__ import annotations from pathlib import...
b195d4b84fdeeec683509f6e2cb27cfaeb107ca55ba9ee20b8c9105314d7ddbb
Python
3,145
100
#!/usr/bin/env python """ Trains a model using one or more GPUs. """ from multiprocessing import Process import caffe def train( solver, # solver proto definition snapshot, # solver snapshot to restore gpus, # list of device ids timing=False, # show timing info for compute and com...
64210ca9baa4da400328dc700d629960fd63d4f9bc5e29fe645f203670335e67
Python
3,146
60
import os def create_key(template, outtype=('nii.gz',), annotation_classes=None): if template is None or not template: raise ValueError('Template must be a valid format string') return template, outtype, annotation_classes def infotodict(seqinfo): """Heuristic evaluator for determining which run...
c80743e78d61296beeb38aecdfcf5a85ec03a5e68b0c9d8807db0d7bb9b7aa73
Python
3,146
112
"""Light geometry types for scene illumination. Provides directional, ambient, and hemisphere lights as scene objects. Lights can be attached to the camera to follow view direction. """ from pydantic import BaseModel, ConfigDict, Field Vec3 = tuple[float, float, float] class LightPosition(BaseModel): """Positi...
4d5fb1ebda756c51f7b71716016b75612cccadb91a9e483c7f8587e17618ad88
Python
3,149
75
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import catmaid.fields forward = """ CREATE TYPE volume_origin_source_type AS ENUM ('mesh', 'segmentation'); CREATE TABLE volume_origin ( id int GENERATED BY DEFAULT ...
5a2432807559a267c33f08af49e812fedfb5f52ce0f12bf5a5142dede4f6bf4c
Python
3,149
103
import torch import torch.nn as nn import numpy as np from Bio import SeqIO import matplotlib.pyplot as plt import logomaker import pandas as pd import os class CNN(nn.Module): def __init__(self, channel=7, nb_filter=16, kernel_size=(4, 10), stride=(1, 1), padding=(0, 0)): super(CNN, self).__init__() ...
8d35b16ab69016a07c49de03a153c790c1b455357b04b720226967ca908f3eaa
Python
3,151
91
import torch import numpy as np class BirdParticle: def __init__(self, position, w=1.0, c1=0.8, c2=0.2, minclamp=0.0, maxclamp=1.0, name=None): """ Initializes a particle. Args: position (torch.Tensor): The initial position of the particle. w (float): The inertia we...
d3893326683f6fa02399252994355efacc48496362b0b1da27cc310b61d994c8
Python
3,151
90
from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from .models import EncryptedKey from .serializers import ( EncryptedKeySerializer, CreateEncryptedKeyListSerializer, UpdateEncryptedKeyListSerializer, ) from .permissions impor...
c81c174f52cda7faf7d134c899af5533fa9090999e5d447e060cbbb17645de9a
Python
3,152
69
# %% # load library import os from nilearn import plotting from nilearn import datasets from nilearn import image import matplotlib.pyplot as plt from pathlib import Path import itertools import sys, argparse # help ----- # https://stackoverflow.com/questions/64331987/removing-hiding-empty-subplots-in-matplotlib-when-p...
16a14f8e041b747faea536a2603025ff98d28b6b94de7f49efe1f03fcba53064
Python
3,156
98
import re import subprocess import os import sys import readline from optparse import OptionParser WD = os.path.abspath(os.path.split(__file__)[0]) os.chdir(WD) parser = OptionParser() parser.add_option("--notest", dest="notest", action='store_true') parser.add_option("--simulate", dest="simulate", action='store_true...
6b1d1b23b343a4c62c48cee9b2331d25610ddb2f6a16e3487bf1c79ba0722132
Python
3,156
126
import queue as Queue import threading import torch from torch.utils.data import DataLoader class PrefetchGenerator(threading.Thread): """A general prefetch generator. Ref: https://stackoverflow.com/questions/7323664/python-generator-pre-fetch Args: generator: Python generator. num_p...
e601327a036c5ad6c578212ebb77dcc028e6a094e349f6e0bf553cd16be9d302
Python
3,156
92
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os.path as osp from functools import partial import numpy as np from mmengine.utils import mkdir_or_exist, scandir, track_parallel_progress from PIL import Image from scipy.io import loadmat AUG_LEN = 10582 def convert_mat(mat_file, in_dir, out_...
76f27275adadb1f5e48d7e112f47f349f030f4329e9ddc8107102c37c7c9e381
Python
3,157
101
# this file imports custom routes into the experiment server from flask import Blueprint, render_template, request, jsonify, Response, abort, current_app from jinja2 import TemplateNotFound from functools import wraps from sqlalchemy import or_ from psiturk.psiturk_config import PsiturkConfig from psiturk.experiment_...
28832527f722729c1e6035d78fa38fac596bc4a8bf34f6ea7ff76dff9842f4e7
Python
3,158
88
import logging import os from pyalfe.data_structure import Modality, PipelineDataDir from pyalfe.image_processing import ImageProcessor from pyalfe.inference import InferenceModel from pyalfe.tasks import Task class Skullstripping(Task): """This task performs skullstripping for all the modalities. Attribute...
f6630026d9ff9d222285713ef7b87b002f324a4cd4f0a75c1948a46c8e40c184
Python
3,158
97
from medperf.exceptions import InvalidArgumentError, MedperfException class CompatibilityTestParamsValidator: """Validates the input parameters to the CompatibilityTestExecution class""" def __init__( self, benchmark: int = None, data_prep: str = None, model: str = None, ...
51688573d95f7d8420d82aa5a90dfcd7eed5665d5b03e8fe21d5b647a1d01ac3
Python
3,160
112
from luna.paths import LunaPaths from luna import candidate_info, dataset from luna.ct import Ct from luna.prepcache import LunaPrepCacheApp from torch.utils.data import DataLoader #from Utils.dataloader import * from Utils.models import * from Utils.TrainModelLUNA import * from Utils.config import * from multiprocessi...
eb30efb407b5da9224ad6e92a8ad0d3ad83a85090f141ce43f6ed90e0011f343
Python
3,162
110
from medperf.comms.entity_resources.sources.synapse import SynapseSource import pytest import os from medperf.exceptions import ( CommunicationAuthenticationError, CommunicationRetrievalError, ) from synapseclient.core.exceptions import ( SynapseNoCredentialsError, SynapseHTTPError, SynapseUnmetAcce...
b6e8181fd68bc113f923fd0d3b8f6ef68d561fa45781b6f14d54f75154bcb979
Python
3,163
100
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import numpy as np plt.rcParams.update({'font.size': 20}) # Default is usually 10 # Load the data datapath = "../data_files/" ages = ["P28", "P21", "P14", "P07", "P04"] colours = pd.read_csv(f"{datapath}/points_hierarchies.csv") colour_map = ...
3725e828aa547e8d2124f737fae669356094f09114ee6851ea647ef577fd8404
Python
3,165
114
from rest_framework import status from medperf.tests import MedPerfTest from medperf.testing_utils import mock_mlcube, mock_dataset from parameterized import parameterized class UserTest(MedPerfTest): def generic_setup(self): # setup users user1 = "user1" user2 = "user2" user3 = ...
8dfd08f3969d4fdf34b903dbf7d11f1d862367c4a72c7bd111f4af483181ce96
Python
3,166
118
import logging import os import random import time from logging import Logger import numpy as np import torch import yaml from easydict import EasyDict from tqdm.auto import tqdm class BlackHole(object): def __setattr__(self, name, value): pass def __call__(self, *args, **kwargs): return sel...
e601a5622ba44933df1ac8a53dbb84892a57f8ec31d094385bb0c0e85cefb09d
Python
3,167
78
from pathlib import Path import pandas as pd import pytest from guppy.extractors.csv_recording_extractor import CsvRecordingExtractor from guppy.utils.custom_events import ( is_sorted, parse_pasted_timestamps, write_custom_event_csv, ) class TestParsePastedTimestamps: def test_newline_separated(self...
f47ef1b5ae696798ea4cb4400d8e23c5e6268dbcff3c275ef5dc48b0e1a18639
Python
3,167
59
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://w...
00d02cd96d1b9c8400ebe87ff7bf79ba83ecd62a6bbfcc67c8e928062cc275e2
Python
3,168
101
"""Testing code shared by other tests.""" # pylint: disable=invalid-name import collections import importlib.util import json import os import tempfile from typing import Any, Callable, Dict, Type import numpy as np import xgboost as xgb from xgboost._typing import ArrayLike def validate_leaf_output(leaf: np.ndarr...
90a1cc78e9ce5fbc4178f31d3c9792b5d777c68317a0fd2d118a76dcccb295ae
Python
3,169
86
import torch import torch.nn as nn import torch.nn.functional as F class DynamicLSTM(nn.Module): """ An Attention-based Bidirectional LSTM (Att-BiLSTM). Highly cited in speech and audio processing literature because the attention mechanism allows the model to weigh the importance of different time fra...
7419e7eb817f178c86ebf12431bf7b6702c3f4286519d0b7a92300d4f68a8283
Python
3,170
61
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://w...
a487caf0d54433f2975c74a78324b8b06b6edfbbdd2af79c28405130c5e6b0fe
Python
3,170
97
# -*- coding: utf-8 -*- """ Created on Tue Sep 24 13:46:09 2024 @author: AC """ import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, ...
0a646ba2800d247d755d2ae97ae8e556cefb69efcfdf1a5e34c1b550a11f8287
Python
3,172
89
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://w...
1d4ba22322077a7991ddbd116a39a87e8ad687ab91fb55fc19029af9c92d158d
Python
3,172
97
import pytest from hypothesis import assume, given, note, settings, strategies import xgboost as xgb from xgboost import testing as tm pytestmark = tm.timeout(10) parameter_strategy = strategies.fixed_dictionaries( { "booster": strategies.just("gblinear"), "eta": strategies.floats(0.01, 0.25), ...
fd2661d29b7d29586cddd7a0c11f64ccf7a9d8ff600ff125ef2172e727a998e8
Python
3,172
107
"""Data transformation models for filtering geometry properties. Transformations allow dynamic filtering of geometry data based on frame data. For example, filtering positions to only show atoms that are constrained. Also includes CurveAttachment for referencing Curve geometries with progress. """ from typing import...
d4b285979a2b764c7acb03fa2002c3742ac3184027ad2fb8400f4f4b5f87dde9
Python
3,175
105
from Utils.dataloader_BrainTumorMRI import * from Utils.config import * from Utils.models import * from Utils.TrainModel import * from multiprocessing import Process from codecarbon import EmissionsTracker def task(lr, data_partition:float=None, run_idx:int=None, backbone:str='dense121'): _cuda = 'cuda:0' _im...
3d946b16fb524863fec74ad2b4a1ca1ad5f8b1de105e0a44871125d8e6147a0d
Python
3,176
100
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import glob import os import pandas as pd import shutil from dmriqcpy.io.report import Report from dmriqcpy.io.utils import (add_online_arg, add_overwrite_arg, assert_inputs_exist, assert_outputs_exist) from dmriqcpy.viz.uti...
d03aca6e8c43fd541826be4b97873f883c0f8bc09b71dc486d130e17157f2ccf
Python
3,176
104
"""Xgboost pyspark integration submodule for params.""" from typing import Dict from pyspark.ml.param import TypeConverters from pyspark.ml.param.shared import Param, Params class HasArbitraryParamsDict(Params): """ This is a Params based class that is extended by _SparkXGBParams and holds the variable ...
b01a5b3a6cbbc3e6fedd66465c04176e2ecf2e91972466c4a29d76aaf1ec8f17
Python
3,177
75
# -*- coding: utf-8 -*- """Tsodyks-Markram model Evaluator used to fit data from multiple frequency stimulations. This module contains an evaluator for the Tsodyks-Markram model. @authors: Andras Ecker and Giuseppe Chindemi @remark: Copyright (c) 2017, EPFL/Blue Brain Project This file is part of BluePyOpt <h...
fcaf2bcb30ceba739ba0308964d2774de9883fa792f042faf001ae1cd76e48a8
Python
3,177
89
# An Pytorch implementation of the pafnucy model # The original model was in outdated TensorFlow 1.x. from collections import OrderedDict import torch from torch import nn class PafnucyNetwork(nn.Module): """ Pytorch implementation of the Pafnucy model. Original paper: Stepniewska-Dziubinska, M.M.,...
bfc4cca926ba011bb77fad70ab4bfbe414169d004250bbcdb628b1f5fe242dc9
Python
3,178
99
# Copyright (c) OpenMMLab. All rights reserved. import argparse import glob import math import os import os.path as osp import mmcv import numpy as np from mmengine.utils import ProgressBar def parse_args(): parser = argparse.ArgumentParser( description='Convert levir-cd dataset to mmsegmentation format'...
3172c08d05f452d0a6170ed2debc0a135d927e3314915b20ec0d9e246d07146a
Python
3,179
82
import json from pathlib import Path import h5py import pytest @pytest.mark.parametrize( "step3_fixture_name, expected_recording_site, expected_ttl", [ ( "step3_output_csv", "region", "ttl", ), ( "step3_output_tdt", "dms", ...
a2416d84f14f21dd9534ae7914fa166de59b5c54e4c3013c4e0daa2c0087fa4f
Python
3,179
99
# MLP model import tensorflow.keras as keras import tensorflow as tf import numpy as np import time import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt from utils.utils import save_logs from utils.utils import calculate_metrics class Classifier_MLP: def __init__(self, output_directory, input...
026ac477150191ad4ae3c37a12f06f429201a106f1d9fb7985ede8cfdb5300a9
Python
3,180
112
import subprocess import sys import os import logging from .utils import which lgr = logging.getLogger(__name__) def queue_conversion(queue, iterarg, iterables, queue_args=None): """ Write out conversion arguments to file and submit to a job scheduler. Parses `sys.argv` for heudiconv arguments. Para...
b6d1034f7b01e7fa87215f271f58098f3997226475193f31e79f6d62884ee57c
Python
3,180
106
from medperf.tests.mocks.cube import TestCube import pytest import medperf.commands.compatibility_test.utils as utils import os import medperf.config as config PATCH_UTILS = "medperf.commands.compatibility_test.utils.{}" class TestPrepareCube: @pytest.fixture(autouse=True) def setup(self, mocker, fs): ...
ebf6cc06ccfa42942709d2de3eb9d343e5895c8c5ff0d5e287c87002bb6c030b
Python
3,180
96
# -*- coding: utf-8 -*- """ Created on Wed Sep 25 11:22:25 2024 @author: AC """ import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import AdaBoostClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, roc_...
3061e057e310cab3c4611d2c6339d0876e413def1213508d183cb66c889634af
Python
3,181
105
import os import pytest from rdflib import URIRef, Graph from pprint import pprint from kgx.prefix_manager import PrefixManager from kgx.utils.rdf_utils import infer_category, process_predicate from tests import RESOURCE_DIR @pytest.mark.parametrize( "query", [ (URIRef("http://purl.obolibrary.org/obo...
3c880f25a2694bc3eae11579b2791e4461e173ac636d8866804754e4483e0ea1
Python
3,181
84
# Model for preparing data: Extract features and labels from csv files # This module provides utility functions for mapping emotion labels, # managing emotion lists, and handling device placement for PyTorch tensors. import torch def dict_emotions(): """ Returns an dictionary for the emotions :return: Dict...
6165c6cd7e7776bc894f6796fad4973843eaf3456babeb3807d689a55fd68ec8
Python
3,181
100
# This file is part of h5py, a Python interface to the HDF5 library. # # http://www.h5py.org # # Copyright 2008-2013 Andrew Collette and contributors # # License: Standard 3-clause BSD; see "license.txt" for full license terms # and contributor agreement. """ Tests the h5py.AttributeManager.create() met...
4f745fb0ba0c6d888cb885e82c1283910ec5312d3f61dc3596084462e2ad403e
Python
3,183
117
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 28 10:22:58 2023 @author: george """ from __future__ import division, unicode_literals, print_function # for compatibility with Python 2 and 3 import matplotlib as mpl import matplotlib.pyplot as plt # Optionally, tweak styles. mpl.rc('figure', ...
4be365f4193abb83eb935afd99d7dd04cea59a5150cd65439cc682765d3a6983
Python
3,184
90
# + from src import config as cfg import os #import scipy.io as sio #import h5py import json #from datetime import datetime as dt ################ # data in ################# def readfile(path): print(f'Reading file at {path}') with open(path, 'r') as f: lines = f.read() print(lines) def loadmat...
544190e9c4fe020ed0ae01b2b014bb5b4e3459ef7eacc84810ff5e24ac945cf6
Python
3,184
131
#!/usr/bin/env python import sys, os, subprocess, random from argparse import ArgumentParser, FileType """ """ def reverse_complement(seq): result = "" for nt in seq: base = nt if nt == 'A': base = 'T' elif nt == 'a': base = 't' elif nt == 'C': ...
b05a871de28abddeafe56cce63732f9134d953e8f39ec3fcbc840b1827689e92
Python
3,184
83
from __future__ import annotations import os.path from typing import TYPE_CHECKING from zipfile import ZipFile import pytest from pymatgen.core import Structure from chgnet import ROOT from chgnet.data.dataset import StructureData from chgnet.utils import parse_vasp_dir if TYPE_CHECKING: from pathlib import Pat...
8f449f973198add42d7c45b756c76d95826f86dfbe66a78c757491acd1e4d114
Python
3,186
77
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase import torch from mmengine.structures import InstanceData from mmseg.models.assigners import HungarianAssigner class TestHungarianAssigner(TestCase): def test_init(self): with self.assertRaises(AssertionError): Hu...
afad86bbeed21d520b050f92cc32e7922c9238f38fb8919eb84d19c5cc52edd1
Python
3,187
119
import torch.nn as nn from nnunet_mednext.network_architecture.custom_modules.custom_networks.TransBTS.IntmdSequential import IntermediateSequential class SelfAttention(nn.Module): def __init__( self, dim, heads=8, qkv_bias=False, qk_scale=None, dropout_rate=0.0 ): super().__init__() s...
6efae52d577918ea12193cad0264eb840a76fa2bb0e1717e6335a4ad90c98349
Python
3,188
91
from __future__ import annotations import json from ast import literal_eval from pathlib import Path from typing import Mapping, Optional, Union from xml.etree import ElementTree import cv2 import numpy as np import pandas as pd from numpy.typing import ArrayLike, NDArray from .base import SoccerTrackMixin _pathlik...
6695ee018ce66ab84768d5373256933d3d478e430138acf58167dcb895b5dbdd
Python
3,191
113
""" 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 logging import os import random import numpy as np import pytest import torch from ase.io import read from ocpmodels.common.registry...