sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
e1b8e53a876933b84e6863e9f287bc57180961114ca9db8d2eb456ce1dc30024
Python
4,602
135
import mne from scipy.signal import detrend import sys, os from tqdm import tqdm from glob import glob import numpy as np import itertools import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import re from sklearn.metrics import accuracy_score, balanced_accuracy_score from sklearn.model_selection...
2236303689bf094f5ae577290651fb8b3f7af2b331c5ab68ef110bb8cdcfaecd
Python
4,603
118
import os import matplotlib.pyplot as plt import matplotlib.patches as mplpatches import numpy as np import pysam from bisect import bisect_left from tqdm import tqdm from scipy import stats def getReadQual(bam): readToQual = {} samfile = pysam.AlignmentFile(bam, "rb") for s in samfile: if s.is_map...
107204c1298c94819c6613d706b51fbb42f4744a71525108c03300f4df8bdb8c
Python
4,604
134
import glob import os import json import argparse import pandas as pd def get_parser(): parser = argparse.ArgumentParser(description='Check if AcquisitionDuration, RepetitionTime, VolumeTiming, ' 'SliceTiming are available in the JSON metadata for *_T2star.json ') ...
4e14622103ab02d7b5894c9bd47cbd5bafaca8c3613a61d9ef2ba20f572cace0
Python
4,606
136
"""Progress reporting channel for pipeline steps. Modelled on :mod:`logging`: deep pipeline code emits progress by calling the module-level functions here, with no reporter threaded through its signature, and the top level decides where those emissions go. Emitting when nothing is bound is a no-op, so the workers can ...
0d2b6f197dead74933fa35016417cae3add862ae0fa9f92afa0104eee81ea327
Python
4,607
72
import os import numpy as np import matplotlib.pyplot as plt import hickle as hkl from grid_cell.ploter import error_bar_plot from grid_cell.toy_locf import LOCFExperiment, run_experiments from global_setting import * n_boot = 5 # base_params = {'n_neuron': 5, 'n_data': 5000, 'std_frac': 0.2, 'dl': 0.1, 'box_size': [0...
3861ac0e63fa84b1b4cb95101904f208a2242f7ab51687012eb7da120fa800ef
Python
4,608
105
# Module for neural network models # This module defines the neural network architectures used for facial emotion recognition, # including a recurrent neural network with an attention mechanism. import torch from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from torch import nn class Attention...
0611fa49cbdd40b53396efe2148903b94851d241accf924a13390fabad82abd5
Python
4,609
148
"""Tests for Presets accessor class. Tests the Presets(MutableMapping[str, Preset]) accessor by mocking APIManager to verify mapping interface and convenience methods. """ import json import tempfile from pathlib import Path from unittest.mock import MagicMock import pytest from zndraw.accessors import Presets from...
a83e2e02b63dc6e969ce629207968a7fb7344ae390b2c299b439c1a26007bd97
Python
4,611
130
import random import torch from pathlib import Path from torch.utils import data as data from basicsr.data.transforms import augment, paired_random_crop from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor class Vimeo90KDataset(data.Dataset): """Vimeo90K dataset for training. The k...
33cd4aa57bc9b293ad18f629fa70c5fdf9cc4c8f303943a683280d12da48321f
Python
4,613
172
import itertools import logging import math from contextlib import contextmanager from typing import Callable, Optional, TypedDict, Union import torch import torch.nn as nn class _Stats(TypedDict): variance_in: float variance_out: float n_samples: int IndexFn = Callable[[], None] def _check_consisten...
04411168ce59fd7b876adb36429115869084ffd6dc6758d01fc09f51fcc7d85e
Python
4,615
132
from medperf.exceptions import CleanExit, InvalidArgumentError import pytest from unittest.mock import ANY from medperf.tests.mocks.execution import TestExecution from medperf.tests.mocks.dataset import TestDataset from medperf.tests.mocks.benchmark import TestBenchmark from medperf.commands.dataset.associate import A...
ddd37f597cb42923a49c23aeae11cec680ec8f1b1359af1aeae1d68bd8aa27dd
Python
4,616
132
''' Date: 2022-11-21 15:53:39 LastEditors: yuhhong LastEditTime: 2022-11-22 23:35:52 ''' import os import argparse import pprint import pandas as pd from rdkit import Chem # suppress rdkit warning from rdkit import RDLogger RDLogger.DisableLog('rdApp.*') from utils import ATOM_LIST, convert2cls ''' preprocess: 1....
1f6ea3d68fe865ae01cfb5d05b608cb5e2080222d7f07f7bce794eddc0bc19e2
Python
4,619
141
_base_ = [ '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] norm_cfg = dict(type='SyncBN', requires_grad=True) crop_size = (512, 512) data_preprocessor = dict( type='SegDataPreProcessor', size=crop_size, mean=[123.675, 116.28, 103.53], std=...
800720ea448ea6b110f8f18a3e5ec181c76ad2424327500f67e323366abf244d
Python
4,620
126
import json from tqdm import tqdm import os from sklearn.utils import shuffle import re import argparse def cut_sent(para): para = re.sub('([。,,!?\?])([^”’])', r"\1\n\2", para) # 单字符断句符 para = re.sub('(\.{6})([^”’])', r"\1\n\2", para) # 英文省略号 para = re.sub('(\…{2})([^”’])', r"\1\n\2", para) # 中文省略号 ...
e8b49498e2d615ac5c8b44290abdfe6e00c5dad92072b84d9cd8a9c30b42d2db
Python
4,624
126
import importlib import numpy as np import random import torch import torch.utils.data from functools import partial from os import path as osp from basicsr.data.prefetch_dataloader import PrefetchDataLoader from basicsr.utils import get_root_logger, scandir from basicsr.utils.dist_util import get_dist_info __all__ =...
0fdf24db2a3bea224bd52f763052f6bb8d69f8f1299fbfe9ea3a8d1c9c6ed2f7
Python
4,628
90
from PyQt5 import QtWidgets, QtCore, QtGui class DeleteMultipleDialog(QtWidgets.QDialog): def __init__(self, parent, data_manager): QtWidgets.QDialog.__init__(self, parent, flags = QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint) self.data_manager = data_manager se...
2956d225effee72990548d04ca5440b9501920d412bfb11446ba7351c177c33f
Python
4,631
88
import argparse import torch import scanpy as sc from vgae import agent import joblib def str2bool(v): if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False ...
f9783f51b964a92d23688363ef0f5f527e5dcd7017b39bccd852f06b1fc9d8af
Python
4,631
159
""" 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 io import logging import os import random import numpy as np import pytest import requests import torch from ase.io import read from...
03230d0ce679a45ba3205df42a59e16688323ecc278168ef6f4c3da02fcf5c08
Python
4,634
133
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import sys import json import parser from pathlib import Path import numpy as np import util def select_examples_TQA(data...
83dc2c05c884b41d4650804c64ec82e429f94bc14f7c49fd9df5916850e1f4f5
Python
4,640
153
import logging from abc import ABC, abstractmethod from typing import Optional, Union from .files import InputFiles from .utils import Progress from .modifiers import ( SingleEndModifier, PairedEndModifier, PairedEndModifierWrapper, ModificationInfo, ) from .steps import SingleEndStep logger = logging...
0d3846a79dbcb57bd5ca7e2a9456f548d9812124703dca3917777ce861b7b7a3
Python
4,641
129
#!/usr/bin/env python3 """ The purpose of this script is to convert redcap data (ethnicity, gender, race) into a table for Inclusion Enrollment Report Parameters ------------ csv_fname: str the REDcap downloaded file, which contains ethnicity, gender, race information Return ------------ df_tally: pand...
2984f14b72764fd7a7040b2affe8cf2c7374467ef7b1e5deb55cae3bca29a89d
Python
4,642
161
#!/usr/bin/env python # coding=utf-8 # Copyright 2023 Statistics and Machine Learning Research Group at HKUST. All rights reserved. """A simple shell chatbot implemented with lmflow APIs. """ import logging import json import os import sys sys.path.remove(os.path.abspath(os.path.dirname(sys.argv[0]))) import warnings ...
2efffadaf0e8c84291afc7ff9cce7c0b99826e86ee60ea2b1fa92d63415ab648
Python
4,642
113
import numpy as np import matplotlib.pyplot as plt import os from sklearn.decomposition import PCA from sklearn.model_selection import train_test_split from grid_cell.sphere_manifold import Circle_Manifold, get_circle_mesh, plot_cov_ellipse from grid_cell.gpr_covnet import GPR_CovNet from grid_cell.manifold_fitter impo...
154666117a0d881bea8a6ad6824e1d43c9bb7ef042f7a48355e67921260fc649
Python
4,643
91
"""Pipeline tests for the GARD_label concord, run against a real built concord. Skipped by default unless pytest is run with --pipeline. Run with: uv run pytest tests/pipeline/test_gard_label.py --pipeline --no-cov -v GARD_label is the only concord in this pipeline derived from labels rather than an asserted map...
2b060d09c875a4154f367a891d664a718032cec4a80e25f9f580111825ea1ca1
Python
4,643
151
"""Long-signal speedup benchmark: Python vs Rust multitaper. Runs `multitaper_spectrogram` on increasingly long signals at Fs=200 Hz and reports median wall-clock time over 3 trials (one warm-up run is discarded) for both the pure-Python and Rust backends. Usage: python test_rust_speedup.py Prints a compact mark...
6ae3210a625f9d5d8ef10429e522932affe6a8ef0eb1e21a3d1e30c1d7b1276e
Python
4,650
132
import argparse import pathlib import ase import ase.io as aio import numpy as np import torch from mace.calculators import mace_off from rdkit import Chem from simgen.calculators import MaceSimilarityCalculator from torch_scatter import scatter_logsumexp def rdkit_mol_2_ase(mol): if mol is None: return ...
057eeb63fae654d726507b649f2e3e62f9b589ecae3f7b1be34ef4006edbc0b1
Python
4,651
148
#!/usr/bin/env python """ MeteWIBELE: finalize prioritization module Copyright (c) 2019 Harvard School of Public Health Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, inclu...
ae2205ac5d2d820acee98910ebad4c989881bafa2b2aaea39779fbe9c871f392
Python
4,651
108
from __future__ import annotations from typing import Optional from heudiconv.utils import SeqInfo def create_key( template: Optional[str], outtype: tuple[str, ...] = ("nii.gz", "dicom"), annotation_classes: None = None, ) -> tuple[str, tuple[str, ...], None]: if template is None or not template: ...
6782c7d36f1e7510fdd787a19f481bdb46b5b1f6d7305f8f38d9fb6879a32820
Python
4,653
142
# Copyright (c) 2021, EleutherAI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
ae365ef1597b14c7d94d3622a09893e7cd333b26094349b34d1d3c9336503fa9
Python
4,659
144
""" 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 argparse from pathlib import Path class Flags: def __init__(self) -> None: self.parser = argparse.ArgumentParser( ...
8d8c800744bbb1fa12d4440d83bea0d30b7e105618bbb4dd49f0df175e8391f0
Python
4,660
138
from typing import Union import numpy as np from abc import ABC, abstractmethod NEURAL_METADATA_REGISTRY = {} def register_metadata(name: str): """ Decorator to register a neural dataset class. Args: name (str): name of the dataset to be used. Returns: function: returns the...
e7171b5119634d4683749dae68a0b64fc58fa7d930ef471f5cd9982a47834f07
Python
4,660
98
# sys.path.append("/home/plent/Documenten/Gitlab/NeuralODEs/jax_neural_odes") from jaxkineticmodel.load_sbml.sbml_load_utils import separate_params from jaxkineticmodel.load_sbml.sbml_load_utils import construct_param_point_dictionary, separate_params_jac import numpy as np import jax.numpy as jnp import jax class J...
bb89d7321622452fa51119b1795ebb58fc0ae7aab489bc321352db8505862a1f
Python
4,661
129
import requests import os from .ProvenanceObject import ProvenanceObject from .dependency import Dependency from .task_status import TaskStatus from .dataset import DataSet from .performance import Performance from datetime import datetime dfa_url = os.environ.get('DFA_URL',"http://localhost:22000/") class Task(Pro...
2428608314fce5d46bca8bd6e54383ff901a3900274da1f1755fb37e48768bfd
Python
4,667
133
import os from kgx.graph.nx_graph import NxGraph from kgx.sink import SqlSink from kgx.transformer import Transformer from tests import TARGET_DIR from kgx.utils.kgx_utils import create_connection, drop_existing_tables NAMED_THING = "biolink:NamedThing" SUBCLASS_OF = "biolink:sub_class_of" def test_write_sqlite(): ...
09ee4a0c6106ceb3c0a5ee7787467c8ad857cebd6ebae24e6856ce3b13241671
Python
4,668
154
# ############################# # # Copyright (C) 2018 # Jennifer Dreiling (dreiling@gfz-potsdam.de) # # # ############################# import numpy as np from BayHunter import rfmini class RFminiModRF(object): """Forward modeling of receiver functions based on SeisPy (Joachim Saul). """ def __init__(...
91a8da730f67702b004c51f39b301758aaa7ccfca4abc49c08aaf153aa9a26ee
Python
4,670
154
"""CircleCurve geometry for ZnDraw.""" import math import typing as t import numpy as np from pydantic import Field, field_validator from .base import BaseGeometry, InteractionSettings, Vec3 class CircleCurve(BaseGeometry): """A circular/elliptical curve for camera orbit paths. The curve lies in the XY pl...
9a56c52418979aee43851237eef3005d766ba6cdb7c4a3a4997a2864c7c56d3d
Python
4,670
128
import copy from typing import cast from cwl_utils.types import CWLObjectType from ruamel.yaml.comments import CommentedMap from schema_salad.exceptions import ValidationException from schema_salad.sourceline import indent from .context import LoadingContext, RuntimeContext from .errors import WorkflowException from ...
8d08486a5894a8e34dae033333b4632151ce0116049f2dbf54ca634031d55736
Python
4,672
117
import os import gensim from Utils.dataloader_RSNA_BONE import * from Utils.models import * from Utils.TrainModelRSNA import * from Utils.config import * from multiprocessing import Process # OPTIONAL: Load the "autoreload" extension so that code can change #%load_ext autoreload # OPTIONAL: always reload modules so t...
6c550fe86931db80a4817e0c7e0f61b3572fd638147b8547072d41f6188f2f93
Python
4,673
190
import argparse import dataclasses import glob import json import os import re from typing import List import matplotlib.pyplot as plt import numpy as np import pandas as pd fig_width = 2.5 fig_height = 2.1 plt.rcParams.update({"font.size": 6}) colors = [ "#1f77b4", # muted blue "#d62728", # brick red ...
781ac3bd67238fbde89103b9f94a6a9e83bd01c4283af3acf210c202dba577d7
Python
4,673
179
"""Recording classes""" """ Copyright (c) 2016-2020, EPFL/Blue Brain Project This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3.0 as published by the Fre...
b25f33097bad303ea98e9bce4809dfe079d754890ad2e58df71d0e4221f352e4
Python
4,673
156
import os from sys import stderr from kgx.utils.kgx_utils import get_toolkit from kgx.validator import Validator from kgx.graph.nx_graph import NxGraph from kgx.transformer import Transformer from tests import RESOURCE_DIR from bmt import Toolkit toolkit = Toolkit() def test_validator_bad(): """ A fake test ...
e10976ddf12394e8586d1aaa95f40f43e8588ff238189bfa15240c30c2132dea
Python
4,673
123
"""Regression: a failing taskiq dispatch must release the inflight lock.""" from __future__ import annotations import asyncio import contextlib import uuid async def _seed_internal_provider(async_session_factory): """Create an @internal provider in the DB and return its full_name.""" from zndraw_auth import...
f04a25b92f799e9faf6a2bbe57fb80d6f8b05f4c5c07634007af157d0eb0f34a
Python
4,674
133
# -*- coding: utf-8 -*- import django.core.validators from django.db import migrations, models import django.db.models.deletion forward = """ CREATE OR REPLACE FUNCTION refresh_skeleton_summary_table() RETURNS void LANGUAGE plpgsql AS $$ BEGIN -- Remove all entries TRUNCATE catmaid_ske...
c7d2129d9aa1cda9d72c86690ec16c58c9040462d3dbf16c9a468a9541a91d76
Python
4,676
133
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmseg.models.backbones import TIMMBackbone from .utils import check_norm_state def test_timm_backbone(): with pytest.raises(TypeError): # pretrained must be a string path model = TIMMBackbone() model.init_weig...
d2fd95c35b2a941a35a577ebd6bf9033a0036831af065c1fd8ac45f5a77151e3
Python
4,680
106
""" Copyright (c) 2022 EPFL-BBP, All rights reserved. THIS SOFTWARE IS PROVIDED BY THE BLUE BRAIN PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE BLUE BRAIN PROJE...
bd48a9f00165a84d500737d2b427b6f710135e0605b8be149132e8ad66236418
Python
4,681
185
import torch from torch import nn, einsum from torch.nn import Module, ModuleList import torch.nn.functional as F from einops import rearrange, repeat class GEGLU(Module): def forward(self, x): return x * F.gelu(x) def FeedForward(dim, mult = 4, dropout = 0.): return nn.Sequential( ...
f1682030e7875b536638f9a3e0d3946ae6adda6f11e97eb5ac403cb2ba022b7f
Python
4,681
136
"""IBEA selector""" """ Copyright (c) 2016-2022, EPFL/Blue Brain Project This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3.0 as published by the Free So...
020e25df1931c4b9e88ab278801aa4bf8d8c4a95acda60fd69024efdf518405f
Python
4,683
123
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os.path as osp import mmengine import numpy as np import torch def vit_jax_to_torch(jax_weights, num_layer=12): torch_weights = dict() # patch embedding conv_filters = jax_weights['embedding/kernel'] conv_filters = conv_filters.p...
18e8b8afbaf399ef0ff483eef193edecce4388a2642a6246c5492a506bda2be1
Python
4,684
140
''' Date: 2022-11-23 11:29:36 LastEditors: yuhhong LastEditTime: 2022-12-12 12:57:28 ''' import os import argparse import numpy as np from tqdm import tqdm import yaml import pandas as pd import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import DataLoa...
928649e0d65e607954e2856e34a1390e1c2ac3e147ba353e0edd669bd87b622e
Python
4,692
138
# -*- coding: utf-8 -*- """ Created on Tue Sep 24 18:54:47 2024 @author: AC """ import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, c...
16050fe591aaa4b1c7990d3db9a707118640901448ebe9f3ce66cf78fd1089ed
Python
4,695
114
import logging from dataclasses import dataclass import torch from mace.data import AtomicData from simgen.manifolds import PriorManifold from simgen.utils import get_system_torch_device_str # if get_system_torch_device_str() == "mps": # torch.set_default_dtype(torch.float32) # else: # torch.set_default_dtyp...
5373590c93ff3b39cc99ca63f4719afad90336869288ff470313002d5e83082f
Python
4,695
103
# pytest unit tests for isct_antsRegistration import os import numpy as np import nibabel as nib from spinalcordtoolbox.utils.sys import run_proc, printv from spinalcordtoolbox.utils.fs import tmp_create, rmtree from spinalcordtoolbox.scripts import sct_dice_coefficient def test_ants_registration(): """ T...
ee40ec0a72833ba8ed1fa511c0ca30ef4a11eb97590af0f96e630491875cd2ab
Python
4,698
128
import shutil from pathlib import Path import pandas as pd import pytest from guppy.testing.api import ( group_analysis, label_groups, locate_run_folder, step1, step2, step3, step4, ) from guppy_test_data import STUBBED_TESTING_DATA @pytest.mark.filterwarnings("ignore::UserWarning") def ...
4241bb24d10e73b88b49ec57b9655561bb441e296caa2c167fad905ff4d9f94b
Python
4,702
123
""" Command-line entry point for GuPPy (Guided Photometry Analysis in Python). Keep this module cheap to import. The pipeline steps run their multiprocessing pools under the "spawn" start method, and a spawned worker is a fresh interpreter that must materialize ``__main__`` before it can unpickle its task. Here ``__ma...
7919ca40f9e617d3ebf56d19171721442d81a998ad9097e9aafedf3582cc290f
Python
4,702
130
""" Function to compare two mRS probability distributions and find the difference in utility across the full distributions. e.g. when both probability distributions have mRS=0, the difference in utility is 0. When one has mRS=0 and the other mRS=1, the difference is 0.97 - 0.88 = 0.09. """ import numpy as np def f...
8a1ab1ce2557774e4939d9b3bc0d28c0485199ce3f712bfc2d8f2bd1c864115b
Python
4,710
105
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone forward = """ CREATE TABLE data_source ( id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, user_id int REFERENCES auth_user(id) NOT NULL, project_id in...
1dab4b4077f74ffecb3e57eaf22f0d3a4da9252edce1ee733d5aa18b99c7c799
Python
4,711
139
""" GBMPurity.py This script performs inference using the GBMPurity model on given input data. The input data path is specified via command line arguments. """ import argparse import torch import pandas as pd import numpy as np from typing import Tuple, List, Optional import sys sys.path.insert(1, './src/modelling') ...
4aec46dc3db16b890606e7f0d9f03555369354f964d5a70be6cb1623df637ebc
Python
4,714
173
import numpy as np from myphdlib.general.toolkit import psth2 from sklearn.decomposition import PCA from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.impute import SimpleImputer from sklearn.cluster import AgglomerativeClustering from sklearn.metrics import silhouette_samples, silhouette_score...
b358aa761c16870df9aa80247eff29fd11ed81a8afdb5cc4ba6621d19bd125a0
Python
4,715
122
import pandas as pd import numpy as np from scipy.integrate import solve_ivp def calc_bold_signal(neurons, results_coherent, results_incoherent, results_nonadap, T, dts, dts_bold = 100, t0 = 0, t0adap = 6000): """ Calculates the blood-oxygen-level-dependent (BOLD) signal generated by the simulated neuronal activ...
d9ae7c69a47dfbecbf9a86632032a45f66e63e0c447ef77625fc1383cf21773e
Python
4,715
131
""" 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 os import numpy as np import pytest from ase.io import read from ase.neighborlist import NeighborList, NewPrimitiveNeighborList from...
a39a5e6d34b64a1a3710029d01e127cc59609d32d4b5a319ed01792ed257dc24
Python
4,719
152
""" trainGBMPurity.py This script trains GBMPurity using single-cell RNA-sequencing data from GBMap resource (Ruiz-Moreno et al., 2022). It includes data preprocessing, model definition, and training with early stopping. Author: Morgan Thomas <scmpht@leeds.ac.uk> Date: 2024-07-08 """ import anndata as ad im...
5072af77f87b2a9ce270f337c09f1ca280e0945c835e04ddac4ad180cb24dd68
Python
4,722
170
# SPDX-License-Identifier: Apache-2.0 # coding: utf-8 # YuanYang import math import cv2 import numpy as np def nms(boxes, overlap_threshold, mode='Union'): """ non max suppression Parameters: ---------- box: numpy array n x 5 input bbox array overlap_threshold: float ...
63aeeef1e3f1586a55a208e2cf7a0a38bd527d7439dd033dc8355dbd4401fbdd
Python
4,727
98
"""Pipeline tests for the NCBIGene data handler. Downloads the full gene_info.gz (>1 GB compressed) and runs pull_ncbigene_labels_synonyms_and_taxa over every row, so these tests are marked both `pipeline` and `slow` and are skipped by default. Run with: uv run pytest tests/pipeline/test_ncbigene.py --pipeline --...
5412597d5dce4eeb12799778fc44de5a0860e06b9c5a937417383cf101605381
Python
4,730
121
""" Main.py - main entry point to start DL experiments """ import os.path import yaml import logging import argparse import wandb from datetime import datetime import sys sys.path.insert(0, '../iml-dl') from dl_utils.config_utils import * import warnings class Main(object): def __init__(self, config_file): ...
4e62fd16f55e46dbe13acbd242fc17019528b7c4451d3a82f9aaf9ff54fafd2e
Python
4,735
105
# import cProfile, pstats # pr = cProfile.Profile() # pr.enable() # 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_cell.sphere_manifold import Circle_Manifold, get_circle_mesh from grid_cell.ori_tuning_ma...
5260c5a5aeb79bcd025283ca445c209498f1e24df9c95325097e4ad01bcbce7b
Python
4,740
160
import contextlib import os import sys import h5py import numpy as np import pytraj as pt import nearl.features import nearl.featurizer import nearl.io from nearl.io import Trajectory class MisatoTraj(Trajectory): def __init__(self, pdbcode, misatodir, **kwarg): # Locate the topology and trajectory file...
d35c197f197c99a9f213ba3a577e9ddc9b0a93e0feab420044b19dc0ceb44cd2
Python
4,744
127
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import silhouette_score from sklearn.cluster import AgglomerativeClustering def fit_and_predict(X, n_clusters): model = AgglomerativeClustering(n_clusters=n_clusters, linkage='ward') labels = model.fit_predi...
2684dd9e6fbee099cd95bab83ff09d8ba87fbb1bd35ffbf6c4fdd7a844b24220
Python
4,745
127
"""Tonic / basal fluorescence analysis. Pharmacological experiments care about slow shifts in the overall fluorescence level after a drug injection rather than event-triggered transients. This module averages the already-preprocessed z-score and dF/F traces over user-defined absolute-time epoch windows, producing one ...
93ab80ca84f4e8e927eed98e9c11a0cca338a00c1ad210eb4c9c1c2eea4269b7
Python
4,749
106
"""Live streaming contract tests for DandiNwbRecordingExtractor. These tests hit the real DANDI Archive and are intended for **local use only**. They are deselected in CI (see ``.github/workflows/run-tests.yml``) because streaming from DANDI is subject to network flakiness and upstream availability. Run locally with:...
54940d7f1e26adf75bfe3289995bc3f386e74dcc0ddce0dc522cc484da193b5f
Python
4,754
106
# 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...
60a06b3bed5d35728ec2780d1c8befb024df0a19699a1c2c31bf30d93a1f9cf0
Python
4,754
142
import numpy as np import math def calculate_XYZ_pad_old(alignment, bounds): """ alignment is a quicknii alignment bounds is the shape of the volume minus 1 """ Ox, Oy, Oz, Ux, Uy, Uz, Vx, Vy, Vz = alignment #bounds = np.array(volume.shape) - 1 X_size = np.sqrt(np.sum(np.square((Ux, Uy, Uz...
98b411285581e9dab702e637591a1cb46e1c9f34f754a6da733cbdc800ab0690
Python
4,754
144
"""Existence-hiding invariants for the namespaced POST /v1/rooms.""" from __future__ import annotations from typing import TYPE_CHECKING from uuid import uuid4 import pytest if TYPE_CHECKING: from httpx import AsyncClient async def _register_and_login( client: AsyncClient, email: str, password: st...
c808be4ca7b86a22334ce03e4d2ba71c9ef954f5dca58565e8672d095168ace0
Python
4,754
113
import numpy as np def check_shapes_same(output, target): if output.shape != target.shape: raise ValueError('Shapes of output {} and target {} do not match.'.format(output.shape, target.shape)) def check_classes_enumerated_along_correct_axis(array, axis, num_classes): if array.shape[axis] != num_clas...
344c26439376cb25e4ba58ac7a03796e614a37ed4f28647878733209119968a5
Python
4,755
136
"""Taskiq-side executor for @internal providers. Resolves the filesystem handler from configured settings, invokes ``Provider.read(handler)``, and POSTs the result to the server via the same ``/v1/joblib/providers/{id}/results`` endpoint that remote providers use. """ from __future__ import annotations import asynci...
eaa9ea57684f188fe3e33a81ec0610befb63bba45839f47fa864c4af21b1585c
Python
4,755
134
# -*- coding: utf-8 -*- import django.core.validators from django.db import migrations, models import django.db.models.deletion forward = """ CREATE OR REPLACE FUNCTION refresh_skeleton_summary_table() RETURNS void LANGUAGE plpgsql AS $$ BEGIN -- Remove all entries TRUNCATE catmaid_ske...
54f4e4763f06f246e67cfd11cfc112a9ee82c297931315000023f7d1a163cbcc
Python
4,758
183
from pathlib import Path import time import pickle import gzip import torch import torch.nn.functional as F import contextlib from functools import wraps, lru_cache from filelock import FileLock from equiformer_pytorch.version import __version__ from einops import rearrange # helper functions def exists(val): ...
858b30d87634dc9ca6bb9334b9c4574f526d6bede4a81a0395b476b1a6308bc4
Python
4,760
130
#!/usr/bin/env python3 """ The purpose of this script is to convert redcap data (ethnicity, gender, race) into a table for Inclusion Enrollment Report Parameters ------------ csv_fname: str the REDcap downloaded file, which contains ethnicity, gender, race information Return ------------ df_tally: pand...
5a2582abb7a6f3a48501ebdf4d3075b94bee45892494bbd4b34a0772288c03ce
Python
4,766
147
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 16 05:37:22 2020 @author: takeiyuuichi """ import mne from mne.preprocessing import create_ecg_epochs import os from mne.io import Raw import mne import matplotlib.pyplot as plt from mne.preprocessing import create_...
f89f6d119d188326dc6bcb13034c22c43b0b2e45d42d49ea39b8f1da463c9a5d
Python
4,766
129
import keras import numpy as np import pytest from dante.neural_surrogate import AckleySurrogateModel from dante.obj_functions import Ackley, ObjectiveFunction from dante.tree_exploration import OptTask, TreeExploration from dante.utils import generate_initial_samples @pytest.fixture def ackley_function(): retur...
2e87d983a33ddec4cb12b964b72c20306b868f60fd6367c0b04d5387e5e16f07
Python
4,772
150
#!/usr/bin/env python # # Resample data using nibabel # # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # License: see the file LICENSE # TODO: add possiblity to resample to destination image import sys from typing import Sequence import textwrap from spinalcordtoolbox.utils.sys import init_sct, s...
f0caedb507b0025fd418fada49ed1dde4b7eb55e6fe1620eb0576afe1b9f6330
Python
4,772
168
#!/usr/bin/python # -*- coding: utf-8 -*- # This script fetches treenodes from the database and renders them to # stack-sized PNGs from math import pi as M_PI # used by many snippets import sys import psycopg2 import os import numpy as np import yaml import cairo if not (cairo.HAS_IMAGE_SURFACE and cairo.HAS_PNG_FU...
c319abb44ca8ece379000d69a025d2651cd22ce9845025b70c366727ea9bedf3
Python
4,774
132
from django.db import migrations forward = """ CREATE OR REPLACE VIEW catmaid_table_info AS SELECT pc.oid AS rel_oid, pc.relname AS rel_name, pn.nspname AS rel_schema, c.column_name AS column_name, c.ordinal_position AS pos FROM information_schema.columns c, pg_class pc...
70c123214842187d8c8b96f8f6215bbb237a89d9c146aead124c232eee95929b
Python
4,776
140
"""IBEA selector""" from __future__ import division from past.builtins import xrange # pylint: disable=W0622 """ Copyright (c) 2016-2022, EPFL/Blue Brain Project This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt> This library is free software; you can redistribute it and/or modify it under ...
96efbc844bf1614482741191ba2009c4ed00daaffd13436c86402cbd32694ad1
Python
4,780
126
import sys import os import argparse import pathlib from tqdm import tqdm import json import torch import torch.nn as nn # https://github.com/PyTorchLightning/pytorch-lightning/issues/11663 import sentencepiece; import pytorch_lightning as pl; import clip from transfer_experiments.train import LinearClassifier from ...
9dd318443ca5660f81664c69f560d8ec0b86051c2903bb8c789c006df43c392b
Python
4,780
130
"""Mock recording extractor for unit testing.""" from pathlib import Path from typing import ClassVar import numpy as np from guppy.extractors.base_recording_extractor import BaseRecordingExtractor from guppy.utils._hdf5_io import write_hdf5 _MOCK_EVENTS = ["mock_signal", "mock_control", "mock_ttl"] _MOCK_SAMPLING_...
f12faca6ef77a54956903fb8e4f6fb90e8ef81c901fe0f17568612ba6b8bd423
Python
4,784
116
import torch import pandas as pd import numpy as np import os import argparse from tqdm import tqdm from params import datapath, num_workers from data import read_config, get_datasets # from main import setup_pretraining import models from training import Trainer from proc_4_decodability import feature_decodability, f...
5ec0894526016117edbad5315ebde5b38d2f7847ef9b2a50b7540795a2109983
Python
4,792
124
import numpy as np import pandas as pd import random import copy from scipy import special def simulate_4prl(parameters, num_trials, pval, minswitch, num_action, agent_id): """ #### Inputs #### parameters : model parameter values (list) num_trials : number of trials we want to simulate for an age...
53f96311946a9411e0087c7a75b50667d45553f1d82e3a1e1f0a9ce7554e34f8
Python
4,794
187
from medperf.exceptions import InvalidArgumentError import pytest from medperf.commands.benchmark.update_associations_poilcy import ( UpdateAssociationsPolicy, ) @pytest.mark.parametrize("mode", ["", "allow", "false"]) def test_invalid_model_modes(mocker, mode): # Arrange obj = UpdateAssociationsPolicy(1...
70aad2c4160fa5be8c4a734596b069cb40d2f078fbe53ebb382b702f59ca735b
Python
4,795
116
#!/usr/bin/env python2.7 import sys, os import argparse from multiprocessing import Lock, Value, Pool from collections import Counter import chisel src = os.path.dirname(chisel.__file__) from ..Utils import * from chisel import Plotter def parse_args(): description = "CHISEL command to generate a BED file for...
1c0dee259792a8d688dab36950f7349aac576ff89e98cebe96eb1c8426fc1be8
Python
4,799
117
# Copyright (c) 2021, EleutherAI # This file is based on code by the authors denoted below and has been modified from its original version. # # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complian...
17aabeb2c0063bcf1ef4a616e35ca23c29f707137f92244fd2f10d44f3eea14d
Python
4,802
143
import os from importlib import import_module import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class Loss(nn.modules.loss._Loss): def __init__(self, args, ckp): super(Loss, self)._...
7eeff0a68d963b87c03c9c89fd4f67a22e663dbefd771cb9457a50c7b5d8e573
Python
4,803
136
import torch import torch.nn as nn import torch.nn.functional as F class SE_block(nn.Module): def __init__(self, inchannels, reduction = 16 ): super(SE_block,self).__init__() self.GAP = nn.AdaptiveAvgPool3d((1,1,1)) self.FC1 = nn.Linear(inchannels,inchannels//reduction) sel...
aeb3b34d123fabf04781772589e45e416d0e9f5341f89f5161f6509f3676f938
Python
4,803
118
# Copyright (c) OpenMMLab. All rights reserved. """MMSegmentation provides 21 registry nodes to support using modules across projects. Each node is a child of the root registry in MMEngine. More details can be found at https://mmengine.readthedocs.io/en/latest/advanced_tutorials/registry.html. """ from mmengine.regis...
2891ad04f75e77f6992f4f98291f6bd2dbc44dcdb703d3938aeb939d2c42a3a2
Python
4,804
185
# Based on: https://github.com/HazyResearch/flash-attention/blob/4a6eaa9f27df6fff7ffb2c24e894938a687dd870/flash_attn/flash_attn_interface.py import torch import torch.nn as nn import torch.nn.functional as F import flash_attn_cuda def _flash_attn_forward( q, k, v, out, cu_seqlens_q, cu_seqle...
875c210d52b5f048adfcffcf977c7b366f0abbf13ef7d225cc63ce629ab83750
Python
4,807
129
"""Step-5 dashboard tab for whole-session time-binned metrics. Reads the ``binned_metrics_<site>.h5`` tables Step 4 wrote and plots the selected metric as bars under the trace it was reduced from. Sessions analysed without the binned metrics parameter have no such tables, so the tab renders a short note instead and ca...
04d18ff2eac20c5c034b16c5d267f3f2ef005b488259b39b1f23d8e03120d863
Python
4,808
138
import textwrap import cv2 import numpy as np from PyQt5.QtCore import QThread, pyqtSignal from PyQt5.QtWidgets import QMessageBox from numpy import ndarray def turn_function_into_thread(inputfunction, emit_prog_signal=False, *arg, **kwargs): class ThreadedFunction(QThread): if emit_prog_signal: ...
a12c048b0e909e4c42e704d6cdb1ed995c977c227b73dea29005aa78df920b08
Python
4,809
148
########################################################################################### # Script for evaluating configurations contained in an xyz file with a trained model # Authors: Ilyes Batatia, Gregor Simm # This program is distributed under the MIT License (see MIT.md) ########################################...
f5fdcc31bd5d78a100964988b48809ddae9e0a44cf17a894fd1238dbd15bff7c
Python
4,810
148
#!/usr/bin/env python """ MetaWIBELE: extract_cluster_CD-hit module Extract the cluster information from CD-hit results Copyright (c) 2019 Harvard School of Public Health Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),...
01355c974bcdd33eaf215474233374a2cd1b13023bed97d3cf8096258a68732e
Python
4,811
93
import pandas as pd import numpy as np import jsonlines from unsloth import FastLanguageModel import transformers import argparse def randomized_choice_options(num_choices): choice_options = list(map(chr, range(65, 91))) return np.random.choice(choice_options, num_choices, replace=False) if __name__ == '__mai...
3f17fa7eefdedc411f1bcf1f7a1c4bd7acf73b41476891acf9f19b07fe4d052d
Python
4,811
128
## ## CPCantalapiedra 2019 import os import sys import time from ..common import get_call_info from ..emapperException import EmapperException ## # Generator of hits from filename def parse_seeds(filename): for lineno, raw in enumerate(open(filename, 'r'), 1): if raw.startswith('#') or not raw.strip(): ...
453298dab4d5b753031419b5039ebd9c52a2a38c39cd2b389cd6f98a6a5be798
Python
4,812
143
import numpy as np import pandas as pd import os import sys from glob import glob from tqdm import tqdm import mne import matplotlib.pyplot as plt import seaborn as sns import scipy.stats as stats files = sorted(glob(f"/ptmp/kroma/m4d/models/leakage/eegnet/N170/*/eegnet_leakage.csv")) df = pd.concat([pd.read_csv(f...