sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
8e84a2fd1a3c8a3c25907dd511840d2c0d3d910ccd6e31531db6bd96d6ab8afd
Python
1,419
38
"""Test application utils""" import unittest import pandas as pd from lefshift import constants from lefshift.application_utils import validate_column, validate_training_input class ApplicationUtilsTests(unittest.TestCase): """Test application utils""" def test_validate_input(self): """Test input v...
0b78ce25fc5e5d6ff372aef0921bb3cf3939b6d9b768f5b82258f3644402a1e0
Python
1,420
49
import os import json import pandas as pd from IPython.display import display, HTML from .io import RESULTS_DIR, load_params, load_meta def make_index(directory=RESULTS_DIR): '''Creates an index of runs and parameters. Arguments --------- * directory (string): directory to look for runs in `directory`...
c8ebd629e280904a489cee644e2a5947519887cabf47da77d4161109f9475b0f
Python
1,420
53
import re import numpy as np import pandas as pd from lib.surface import compute_edge_lengths, read_surface_from_gifti density_list = [] rows = [] for surf_gii in snakemake.input.surf_giis: # get the resample value from the filename resample = re.search(r"_resample-(\d+)_", surf_gii).group(1) hemi = re...
24884de4b2c6bf8383110033c76827dc2595d3d8cacb9daee7a115a75f06fad7
Python
1,421
52
""" Test for more than 5 input spikes per time step """ import os from spinnaker2 import hardware, snn def test_many_input_spikes(): n_stim = 12 spike_times = {} time_offset = 0 for i in range(n_stim): spike_times[i] = range(time_offset + i, time_offset + n_stim) stim = snn.Population(n_s...
2eef65674d7dbd4fa247e03ccf08200cd458231ae972b4d38519a3d6f7b471c6
Python
1,423
49
import logging import aiohttp.web import ray.dashboard.modules.tests.test_consts as test_consts import ray.dashboard.modules.tests.test_utils as test_utils import ray.dashboard.optional_utils as dashboard_optional_utils import ray.dashboard.utils as dashboard_utils from ray._private.ray_constants import env_bool log...
c874b29068f076c09d62747319844e74045e5ba774a0cfe3af9b579529462c58
Python
1,423
35
from siapy.entities import SpectralImage from siapy.entities.shapes import Shape from siapy.utils.images import ( calculate_correction_factor_from_panel, convert_radiance_image_to_reflectance, spy_save_image, ) # Load radiance image radiance_img = SpectralImage.spy_open(header_path="radiance_data.hdr") # ...
3d168557572d6adf0996f0e107b09aa34bfb220732e59d5f12ea1a08ce776dbe
Python
1,424
66
import argparse import os import shutil import numpy as np import torch import torch.nn as nn import torch.optim as optim from PIL import Image from torch.autograd import Variable from torchvision import transforms import cv2 import time import argparse from scipy.io import loadmat from torch.nn import functional as F ...
856018ba3c57833edf1d621240709e385d7204e1ab2cc4a401c29a0e1df1d168
Python
1,425
34
import numpy as np from kneed import DataGenerator, KneeLocator from .dp_related import dp_bucketized import torch import matplotlib.pyplot as plt def plot_ll_curve(gaston_model, A, S, max_domain_num=8, start_from=2): ll_list=get_ll_list(gaston_model, A, S, num_buckets=150, kmax=max_domain_num) kneedle=Kn...
c5a902f54939544f46bc1fa2e61cf5c59d9946ef6e8e4f6a82247ccd9efc32dd
Python
1,425
52
#!/usr/bin/env python3 """ Example script demonstrating how to use CEBRA DCL with the sklearn API. This reproduces the functionality of dcl_example.py using the sklearn wrapper. """ import sklearn.decomposition import cebra import cebra.datasets if __name__ == "__main__": device = "mps" input_data = cebra.d...
3a05fba5ba32ba0eeafddafda00394fa363f0bc4696a32dedd302bdadcb91509
Python
1,427
44
# This file is part of the INTREPPPID programme. # Copyright (c) 2023 Joseph Szymborski. # # This programme is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, version 3. # # This programme is distributed i...
429d14c49bf9c11acb6c8a9ad67957eb7a2b8d4d5a5705b59ec726da2efb5faf
Python
1,427
45
import os import sys list_name_video = ['blood_vessel_10Hz','PFC4_15Hz','bma22_epm','CaMKII_120_TMT Exposure_5fps'] for name_video in list_name_video: ID_part = ['_part11', '_part12', '_part21', '_part22'] list_Exp_ID = [name_video+x for x in ID_part] folder = os.path.join('E:\\data_CNMFE', name_video, 'DeepWonder_...
9b2c25042a4752ee5da910726bdcac99f841db2e344d2380b65237221af20f1c
Python
1,427
51
from typing import Tuple import pyspark.sql.functions as F from numpy import array from pyspark.sql import DataFrame from data_profiling.config import Settings def date_stats_spark(df: DataFrame, summary: dict) -> dict: column = df.columns[0] expr = [ F.min(F.col(column)).alias("min"), F.ma...
f451c8587e48e5bb8dc498e90cf4f7953f48fb7faff8e29dcb1bd56fa6b31bde
Python
1,427
53
import os import subprocess import json from spinnaker2.configuration import PEConfig, ExperimentConfig, MemoryRegion from spinnaker2.coordinates import ByteAddr, WordAddr, PE """ Simple example that takes an input value, sends it to a PE, where it is multiplied by a constant depending on the PE-ID. The result is re...
62a4999772e47a8a7d9a5685646b0652c6eecc20a5b14df85e34fb07a71a51e2
Python
1,428
42
# -*- coding: utf-8 -*- ### ------------------------------ IMPORTS ------------------------------- ### import os import numpy as np import pandas as pd from functools import reduce ### ---------------------------------------------------------------------- ### def get_best(csv_dir='train', common_n=10, best_n=100, sa...
6d0bd7d49db6e027f92125056366dcb32bd949105c0c5c6a1baa2389de29cb29
Python
1,428
43
from typing import TYPE_CHECKING, Iterator, List, Union from ray.data._internal.output_buffer import BlockOutputBuffer, OutputBlockSizeOption from ray.data._internal.util import _check_import from ray.data.block import Block from ray.data.context import DataContext from ray.data.datasource.file_based_datasource import...
f188172259d06d8466562cf24fd59af9c212ab3986bb3a62a86bb9fc69d927c3
Python
1,428
46
import moabbpatch import config import pandas as pd import scipy.stats import swifter datasetname = config.DATASET_NAME outpath = config.CSP_RESEARCH_OUT_PATH in_file = outpath / f"00_{datasetname}_all_combs.hdf5" comb_file = outpath / "00_combinations.txt" out_file = outpath / f"01_{datasetname}_selected_combs.txt" ...
695e34c3d6cb6bf92524c5c0c509a97fe254bae0c956233adfdd11617c1f49b9
Python
1,429
41
import torch def copy_param(target_link, source_link): """Copy parameters of a link to another link.""" target_link.load_state_dict(source_link.state_dict()) def soft_copy_param(target_link, source_link, tau): """Soft-copy parameters of a link to another link.""" target_dict = target_link.state_dict...
68bbd878b1a32141c6ca30278dce8e3cc942f93a6b7e0229fa825517190af644
Python
1,430
39
"""Make sure tests will be run by CI. """ import glob import subprocess import xml.etree.ElementTree as ET if __name__ == "__main__": # Make sure python unit tests have corresponding bazel targets that will run them. xml_string = subprocess.run( ["bazel", "query", 'kind("py_test", //...)', "--output=x...
b2d0e41f2640575c11f7c0f01281981e14dae21eb87bd96641ea13f7aa309cbe
Python
1,431
46
import argparse from matplotlib import cm, pyplot import numpy import tifffile from pysted import base, utils parser = argparse.ArgumentParser(description="Simulate the acquisition of a single 10nm particule.") parser.add_argument("pixelsize", type=float, help="pixelsize (in m) of the acquired ...
3dfcaabfbf9a2d0ea6c095884304eff8f6a93b7a038103e9444b48a8fb52d789
Python
1,432
45
from .transformer import TransformerEncoder from .mlp import ResMLPEncoder, MLPEncoder from torch import nn def setup_encoder(model_type, num_hidden, num_layers, dropout, activation, norm, nhead, covariates_dim=0) -> nn.Module: if model_type in ["performer", "cosformer", "transformer", "flowformer"]: mod =...
80ae3dafe8c1f43d55103fbdab784c9eca893ae9dc4183dbfdc4f59b35cd9159
Python
1,433
21
from neuron_morphology.validation.result import NodeValidationError from neuron_morphology.validation.result import MarkerValidationError import unittest class ValidationTestCase(unittest.TestCase): def assertNodeErrors(self, validation_errors, expected_message_fragment, expected_invalid_node_ids): matchi...
f2d383560b8bea45346edfacc00ec6bf227733346e4be564bc6deaef6563cd27
Python
1,433
49
#Ori Zaff - 7/29/22 from psychopy import visual, core, event win = visual.Window([800,600], monitor="testMonitor", units="deg") button_box = visual.ImageStim(win, image = './buttons.jpg',size=(20), pos=[0,0]) index = visual.ImageStim(win, image = './index.jpg',size=(20), pos=[0,0]) middle = visual.ImageStim(win, imag...
0dc90bdd8747bc11cee3dfd17b47c241e29f5f822eb74d6904d29ebe4a80bf09
Python
1,434
35
# # CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables # © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) # Source code: # https://github.com/AdaptiveMotorControlLab/CEBRA # # Please see LICENSE.md for the full license document: # https://github.com/AdaptiveMotorControlLab/CEBRA/bl...
af068ee8c83a88a907f26c489018e1c831f74237f53920514d98671473447413
Python
1,434
51
import requests import starlette from typing import Dict from ray import serve from ray.serve.handle import DeploymentHandle # 1. Define the models in our composition graph and an ingress that calls them. @serve.deployment class Adder: def __init__(self, increment: int): self.increment = increment de...
0a46f870fe5354b92e512514b62a41e65fe40e88e06560fe9aa322c1fdb70bd6
Python
1,435
45
import pandas as pd import pyranges as pr def bins_to_genes_intersection(bins, genes, genes_cols=['seq_id', 'start', 'end']): """ bins :: pandas.DataFrame : columns: Chromosome: `chr1`, Start: `10000` End: `20000` genes :: pandas.DataFrame : columns i...
9de2d6c0af691d0fce4a017c2f6b048396410c3e408bcc8fb766e77ef88fc52f
Python
1,436
48
# utils.py # Copyright (c) 2010 Jes Frellsen # # This file is part of Muninn. # # Muninn is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # Muninn is distributed in the hope that it will be useful, ...
05cec819bb2a3cc045c86a7991659545bb2223c96a911462c30872eb9da29398
Python
1,437
32
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
1af5078c3092129e7619484823d656ccf084fe0b1e1dfb4b31d8a378916b7f2c
Python
1,439
56
from __future__ import annotations from dataclasses import dataclass from typing import Any, Awaitable, Callable, Optional, Protocol from ..agent_bridge import AgentRunResult, AgentBridge ProgressCallback = Callable[[str], Awaitable[None]] ChunkCallback = Callable[[str], Awaitable[None]] @dataclass class Executio...
e92a465e947ec1c4b66fc595bbc8b550d85ce681dde4c653cb8249dd4a39694d
Python
1,439
40
import os import sys sys.path.append('.') import cv2 import math import torch import argparse import numpy as np from torch.nn import functional as F from model.pytorch_msssim import ssim_matlab from model.RIFE import Model device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = Model() model.loa...
f8528e407771f068c45caeb83a5599c9cd4621de05151a6d567b7cd232c195cb
Python
1,439
51
from typing import List, Tuple, Union import numpy as np from torch import nn ArrayLike = Union[np.ndarray, List, Tuple] class Crop2d(nn.Module): """Crop input image by.""" def __init__( self, cropping: ArrayLike = ((0, 0), (0, 0)), ): """Crop input to the the rectangle dimensio...
0b05cdc275b084a61a026833020360a6a820491f4ae39845a97b30296c8afe0b
Python
1,440
38
from distutils.core import setup import setuptools from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name = 'nested_cv', packages = ['nested_cv'], version = '0.916', ...
a801005deee3158f27113eaa63d23b46cc3e4cfae9a066c0085904bd4ab90bed
Python
1,441
50
import multiprocessing as mp import os import signal import sys import unittest import warnings from pfrl.utils import async_ class TestAsync(unittest.TestCase): def test_run_async(self): counter = mp.Value("l", 0) def run_func(process_idx): for _ in range(1000): with...
bf349ce809284ed1c7cb7f8e0ae7ade5d130f14c4b1c526bd6252b5941b0da84
Python
1,442
46
import hashlib import os from pathlib import Path from filelock import FileLock import ray RAY_LOCKFILE_DIR = "_ray_lockfiles" class TempFileLock: """FileLock wrapper that uses temporary file locks. The temporary directory that these locks are saved to can be configured via the `RAY_TMPDIR` environmen...
d12976eaf570a2a1be853405ee701fa60899683cb8fe4bc1001243042913d1de
Python
1,442
38
import warnings import torch def find_peaks(y, threshold, min_dist): # y: (batch, length) if min_dist % 2 == 0: warnings.warn('min_dist must be odd, but got {}'.format(min_dist)) min_dist += 1 batch = y.shape[0] local_maxima_mask = torch.cat([torch.zeros(batch, 1, dtype=torch...
c59f3d9b4fe5ce28595726e64dafd887f8318d48f61e16a43ae7ca029fef0274
Python
1,443
61
import sys if len(sys.argv) == 1: # A small number for CI test. sys.argv.append("5") # __program_start__ import sys import ray # fmt: off # __large_values_start__ import numpy as np @ray.remote def large_values(num_returns): return [ np.random.randint(np.iinfo(np.int8).max, size=(100_000_000, 1...
5c8d5dc7fc7e8c16433deb99c76faf4636359aab2a8c366e6ef239dfe04a566d
Python
1,445
49
from typing import Dict, TypeVar K = TypeVar("K") def collapse_transitive_map(d: Dict[K, K]) -> Dict[K, K]: """Collapse transitive mappings in a dictionary. Given a mapping like {a: b, b: c, c: d}, returns {a: d}, removing intermediate b -> c, c -> d. Only keeps mappings where the key is NOT a value in ...
e18d7f6e3783549f3de8f3991356278e3b5cc7e07bda8e96ed9b92f0734a1a59
Python
1,445
42
from typing import List, Dict import numpy as np from tensorflow.keras.models import load_model, Model from preprocess_ecg import process_ecg, LEADS def get_model(model_name = 'pclr') -> Model: """Get PCLR embedding model""" if model_name == 'pclr': return load_model("./PCLR.h5") elif model_name...
3031bcdddf02d581864a718dc22f6c1ba737dff14468c192dc15469daa9626a4
Python
1,446
35
# Copyright 2023 The HuggingFace Team. All rights reserved. # # 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 applicabl...
3ece29e2474ab863cf09f3c48166fbf6e239b2c91215011b2fe50518651ab00a
Python
1,446
59
"""Dataset cache utility functions""" import zipfile from pathlib import Path from requests import get as get_file from data_profiling.utils.paths import get_data_path def cache_file(file_name: str, url: str) -> Path: """Check if file_name already is in the data path, otherwise download it from url. Args: ...
7f144efb11ab42a83f09991bb619379bf0f5d3d32bf83b210c63c26fba10f01e
Python
1,446
75
# flake8: noqa # __starting_ray_start__ import ray ray.init() # __starting_ray_end__ # fmt: off # __running_task_start__ # Define the square task. @ray.remote def square(x): return x * x # Launch four parallel square tasks. futures = [square.remote(i) for i in range(4)] # Retrieve results. print(ray.get(future...
123dd54bcb60117f472e39286766cbf4ff9a88c35f8c992924eb2d4996a2f885
Python
1,448
52
#!/bin/python #------------------- Description & Notes --------------------# #------------------- Dependencies ---------------------------# # Standard imports import functools # Third-party imports import pyspark.sql.functions as F import pyspark.sql.types as T # Internal imports from ..schema import * from .. imp...
4327bc86e1416855f94bdefe67e5e167c82382a21715f8a8ec0efba04cc1ccd8
Python
1,448
36
import argparse import pandas as pd def parse_argument(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', help='Input expression matrix file.', required=True) parser.add_argument('--target-genes', help='List of target gene IDs to train.', required=True) parser.add_argument('--id...
ab3ebbd3c4e2653ce98ce40e93149bed1930a248c911d4440dee5b863fed5c1a
Python
1,448
23
import pandas as pd def citation_analysis(df_publications: pd.DataFrame, df_authors: pd.DataFrame, config: dict): df_temp = df_publications[~df_publications["iCite_is_research_article"].isna()] df_temp = df_temp[df_temp["iCite_is_research_article"].apply(lambda x: True if x.lower()=="yes" else False)] ci...
bf941dfc66f542fcb6d95f5c8eb4075d29aa04db2badd17edaab4f4147fadb6b
Python
1,449
43
"""Install script for setuptools.""" from setuptools import find_packages from setuptools import setup setup( name="unimol_tools", version="0.1.0.post1", description=("unimol_tools is a Python package for property prediciton with Uni-Mol in molecule, materials and protein."), author="DP Technology", ...
6685178bfc121360736e0cf287527f8bd2c292deeaf73759f20ba2a1f30ef27e
Python
1,451
44
import os import pandas as pd import numpy as np import tensorflow as tf from utils import oneHot from tensorflow.keras.layers import * if __name__ == '__main__': path = '../Data' num_shuffles = 10 predictions_ala = [] predictions_no_ala = [] WTaa = 'SINSVHT' aaList = 'ACDEFGHIKLMNPQRSTVWY' ...
15896598c5a19d3534c27796dbcd74ebc9f491c0e476f86799dc82f4f2eb1ed1
Python
1,452
34
import argparse from scripts.pdbbind_pipeline import construct_pdbbind_core_data, construct_pdbbind_data, load_config, parse_params if __name__ == "__main__": parser = argparse.ArgumentParser( description="Parsing of PDB Bind dataset", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) pars...
21dafb4896a1e9e539f400605baf9f805047ab8f8c3622b25cb161b6ecd1dcb3
Python
1,452
46
# Copyright 2026 Google LLC. # # 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 writing, ...
f9d21b8a8577d40bad6e64250f97100d6a5222705913c6887e1ad25d7b9449b7
Python
1,453
61
#!/usr/bin/env python """ Collect genotyping cutoff metrics. Writes stats to stdout. Metric format: gt_cutoffs_<COPY_STATE>_<MEAN/SD/CUTOFF> """ import argparse import sys import pandas as pd KEY_PREFIX = "gt_cutoffs_" MEAN_COL = 'mean' SD_COL = 'sd' CUTOFFS_COL = 'cutoffs' def main(argv): parser = argparse...
e7d7d565632ce4b6930404c4fd0560da42a472123b35e27b51df900709a5564a
Python
1,455
36
#!/usr/bin/env python # import from __future__ import print_function ## batteries import os import sys import pytest # data dir test_dir = os.path.join(os.path.dirname(__file__)) data_dir = os.path.join(test_dir, 'data') # tests def test_help(script_runner): ret = script_runner.run('ncbi-gtdb_map.py', '-h') ...
ea4f4fef81d735b8aea25be9724a41a1f1212498010a695a41f8093b54856249
Python
1,455
42
from typing import Callable, Iterable, Literal import optuna from pydantic import BaseModel, ConfigDict from siapy.optimizers.parameters import TrialParameters from siapy.optimizers.scorers import Scorer __all__ = [ "CreateStudyConfig", "OptimizeStudyConfig", "TabularOptimizerConfig", ] class CreateStu...
da7e71e911145bf1e921133d7dfc3b580451070128db7b0aa14fd2fbcaad8f29
Python
1,456
44
import torch import glob import numpy as np import os from tqdm import tqdm import json from .points_utils import get_ini_position from einops import rearrange import collections from .base import BaseDataset import imageio class HeartDataset(BaseDataset): def __init__(self, root_dir, split='train', **kwargs): ...
66809cc5cb1dd77b2b7f8ba97427785918cfba7459ac714a4c8a7160339b2640
Python
1,458
60
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ """ import argparse import pandas as pd def take_highest_effect(s): if 'LOF' in s.values: return 'LOF' if 'COPY_GAIN' in s.values: return 'COPY_GAIN' if 'DUP_PARTIAL' in s.values: return 'DUP_PARTIAL' if 'INV_SPAN' in s.val...
39b0e1167a36edc2fab8c84cc798405bc9f5adfdcac81d9064b21468ff3fd6db
Python
1,459
37
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import scipy as sp from pathlib import Path import numpy as np base_dir = '/Volumes/diedrichsen_data$/data/Cerebellum/Language' if not Path(base_dir).exists(): base_dir = '/srv/diedrichsen/data/Cerebellum/Language' if not Path(base_dir).exis...
3d68be1824a2bea6009b0e8437193559315e6d636b3eeb5effcd805dcd4a04cf
Python
1,459
50
""" Functions for preprocessing of single cell RNA-seq counts """ import numpy as np import anndata from scipy.sparse import issparse def filter_counts_data(data, cell_min_molecules=1000, genes_min_cells=10): """Remove low molecule count cells and low detection genes :param data: Counts matrix: Cells x Gene...
dd0105b0c7f2ffc3bfac2b8a64b04e8597239b8c44fa3e636365f831081b016f
Python
1,459
51
import torch def _find_repeats(data): temp = data.detach().clone() temp = temp.sort()[0] change = torch.cat([torch.tensor([True], device=temp.device), temp[1:] != temp[:-1]]) unique = temp[change] change_idx = torch.cat([torch.nonzero(change), torch.tensor([[temp.numel()]], device=temp.device)])...
f2061833072404cfd644d95712e88b07e8025932acf6552075778fe2cddc40f4
Python
1,461
44
import pathlib path = pathlib.Path.cwd() if path.stem == 'tmb_survival': cwd = path else: cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')] import sys sys.path.append(str(cwd)) from matplotlib import pyplot as plt from lifelines import KaplanMeierFitter from figures.sim_tools import * from lifeli...
9eaabf477e8588e097ff682e3c6943128dbd0b6491e99463ad4f21545f355a7d
Python
1,462
56
import functools from typing import Union import click def bool_cast(string: str) -> Union[bool, str]: """Cast a string to a boolean if possible, otherwise return the string.""" if string.lower() == "true" or string == "1": return True elif string.lower() == "false" or string == "0": retu...
f4fda3314c7606a3cf876055613a195933e5ef28a22126aa62ab90897ae9163f
Python
1,464
50
from typing import Any, Callable, Optional, Sequence from data_profiling.report.presentation.core.renderable import Renderable class Container(Renderable): def __init__( self, items: Sequence[Renderable], sequence_type: str, nested: bool = False, name: Optional[str] = None...
fbcd69df6ebbbb8b8548d78d635a62f57231b60b992a458a03ed8a16ed3b243a
Python
1,464
50
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations from typing import TYPE_CHECKING from torchtnt.framework.evaluate import evaluate from fairchem.core....
05f422a3a72a2b60597926af4900a9247423e4108245d766a32fd4193809b0cb
Python
1,465
45
import torch from structured_kernels import vand_log_mult_sym_fwd, vand_log_mult_sym_bwd def log_vandermonde_cuda(v, z, L): """ Wrap the cuda method to deal with shapes """ v, z = torch.broadcast_tensors(v, z) shape = v.shape v = v.contiguous() z = z.contiguous() N = v.size(-1) assert z....
6dda685159eca8ef7a38d250483d76812f59bee1ecfeeb0e35bc7a2d9a4626f9
Python
1,465
56
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Exceptions related to the cloud client.""" from urllib.parse import urlparse from requests import Response from aihwkit.exceptions import CloudError clas...
46311421c2f380c3bfbdb077d6ab5331b6b5d8b7770427b4bdd013361f7a06d0
Python
1,466
52
import logging from math import pi as PI import torch from torch import nn logger = logging.getLogger(__name__) class GaussianEmbedding(torch.nn.Module): def __init__( self, out_dim=50, dist_resoln=None, min_x=0.0, max_x=5.0, cos_dump=False ): super().__init__() num_div = None ...
c8a8281465aae65bd56883b1d854f3596ca2509531d505396e84d3ab03fbbadc
Python
1,466
45
import torch from torch import nn import torch.nn.functional as F class LSTM(nn.Module): def __init__(self, input_size, num_hiddens, num_layers=1, bidirectional=False, **kwargs): super(LSTM, self).__init__(**kwargs) self.lstm = nn.LSTM(input_size=input_size, hidden_size=num_hiddens, num_layers=num_layers, bias=...
f8adb0459cadc7b2bb66843fa1ef531c21b9fc0bb84f530f5dc8ad1879b5299b
Python
1,466
35
from data_profiling.report.structure.variables.render_boolean import render_boolean from data_profiling.report.structure.variables.render_categorical import ( render_categorical, ) from data_profiling.report.structure.variables.render_common import render_common from data_profiling.report.structure.variables.render...
34ce39582671fb07fe12bdc3a81407bcd6b05c39eabfb50349efa5a4e9bb8074
Python
1,468
40
from imports import * from ngs_mapper import compat class Base(common.BaseBaseCaller): modulepath = 'ngs_mapper.vcf_diff' def setUp( self ): super(Base,self).setUp() fixpath = join(fixtures.THIS,'fixtures') # Bam built from scratch that has multiple refs self.test_vcf ...
78ff763991a8e6a87284431eedeb8866bcc371c6e2f515da5279b0c381afd574
Python
1,468
66
from unittest import mock import pytest import pfrl @pytest.mark.parametrize( "render_kwargs", [ {}, {"mode": "human"}, {"mode": "rgb_array"}, ], ) def test_render(render_kwargs): orig_env = mock.Mock() # Reaches the terminal state after five actions orig_env.reset.si...
7aea13afd810b2afeb85cacd5b3cb88342b7b8840bef2c2eff98084aa76650ed
Python
1,468
59
import cv2 # noqa: F401 — preload libtiff before HIPT/torchvision shadows it (omicverse vendored patch) import sys import numpy as np from utils import save_image, load_pickle from cluster import cluster from connected_components import relabel_small_connected from image import crop_image def remove_margins(embs, ...
b36fde61e27d1c548512b752e4259d332ab1f498970c3f5e71c848c1577a4d1b
Python
1,468
143
atom_names = [ "C", "CA", "CB", "N", "O", "OXT", "OT1", "OT2", # ARG "CB", "CG", "CD", "NE", "CZ", "NH1", "NH2", # ASN "CB", "CG", "OD1", "ND2", # ASP "CB", "CG", "OD1", "OD2", # CYS "CB", "SG", # GLN...
a1a644883b7e3939cc6cdd8d7c59b78e6952171564f7eca803ac98bf22339ca9
Python
1,469
46
import sys import pytest from ray.core.generated import gcs_pb2 from ray.core.generated.common_pb2 import TaskStatus, TaskType from ray.dashboard.modules.task_events.gc_policy import FinishedTaskActorTaskGcPolicy def _finished_event() -> gcs_pb2.TaskEvents: event = gcs_pb2.TaskEvents() event.state_updates.s...
b57269a0343ae8fdb9df7502227ae715d435b9ffd9045f3960610c677351c6a6
Python
1,469
39
from sklearn.base import BaseEstimator from sklearn.pipeline import Pipeline from siapy.utils.general import dict_zip def assert_estimators_parameters_equal(estimator1: BaseEstimator, estimator2: BaseEstimator) -> bool: if len(estimator1.get_params()) != len(estimator2.get_params()): return False fo...
9c0421883881e74377cc933f2180e2a887a6dbe1429832dc2854b9926c161519
Python
1,470
34
#Test data module from src import data import pandas as pd import copy def test_TreeData_setup(config, ROOT): #One site's worth of data local_config = copy.deepcopy(config) local_config["use_data_commit"] = None csv_file = "{}/tests/data/sample_neon.csv".format(ROOT) dm = data.T...
4e2bb41cf2fe82cad15cb3e87f818522723dc0157067d35f631c5624075269fd
Python
1,471
44
import os import numpy as np import torch import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable matplotlib.use('Agg') os.makedirs('images', exist_ok=True) test_traj = torch.load('ckpts/test_traj.pt') test_traj = test_traj - test_traj.mean(dim=(1, 2), keep...
8e279b3db8d7e6ed7f7f01275a16346eef759007581a91b2afbc9f6906794d14
Python
1,471
41
import cProfile import pstats from sklearn.datasets import make_blobs from sklearn.model_selection import train_test_split from sklearn.cluster import KMeans, AgglomerativeClustering from hdbscan import HDBSCAN from sklearn.neighbors import KNeighborsClassifier from reval.best_nclust_cv import FindBestClustCV s = KNei...
27d656700a670d865fc07691c9d65b3b52903c2a7bba4e046496078dce610dc1
Python
1,472
36
# Copyright 2021 Division of Medical Image Computing, German Cancer Research Center (DKFZ) # and Applied Computer Vision Lab, Helmholtz Imaging Platform # # 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 L...
e597f9ab280104754dcca864a6b038aab5028d7cbcdf2c9cdc0dd5cbd77c82c2
Python
1,472
37
import os import sys import glob def get_conda_bin_dir(): if os.path.basename(sys.executable) in ['python', 'python2', 'python3']: # note: the case where the current script is run # with the full path to the Conda Python executable return os.path.dirname(sys.executable) else: r...
d0dd125b3539533e871359ee284e3690ba561288d99fff4538a2fedd27083871
Python
1,473
47
# ------------------------------------------------------------------------------------------------------------------------------------- # Following code adapted from GCPNet (https://github.com/BioinfoMachineLearning/GCPNet): # ---------------------------------------------------------------------------------------------...
daedaa08b95430b2ef0908864321a64e8187853808ce1c09c1b8f6ba6e526ff3
Python
1,474
58
import torch import pickle import torchvision import torchvision.transforms as transforms def mnist(): batch_size = 60000 transform = transforms.Compose( [transforms.ToTensor()]) train_dataset = torchvision.datasets.MNIST( root="data", train=True, transform=transform, download=True ) ...
9aba86c636032e55d51350389a96778907f9d470758b6bb17759f93ef9028ef0
Python
1,476
56
from functools import wraps, partial import time from typing import Callable, Optional import numpy as np __all__ = ["cal_fdr", "timer"] def cal_fdr(p_vals: np.ndarray) -> np.ndarray: """Benjamini-Hochberg FDR adjustment for an array of p-values. Parameters ---------- p_vals Raw p-values. ...
76eb2b4874b5c037196be44c762acb5f9be532c777154a206bd0630a73d8b9ab
Python
1,477
63
from utility import * # check utility.py for functions documentation from component import * import numpy as np class DefaultComponent(Component): def initialize(self): #print(sys.path) log_error(self.this(), sys.path[0]) log_error(self.this(), sys.path[1]) log_error(self...
c1c8593b24cdbea846a535d043500791b09516730477a4b4450f2ac6554aaf35
Python
1,477
48
def test_stat3D_mask(): import samri.plotting.maps as maps stat_map = '/usr/share/mouse-brain-templates/dsurqec_200micron_roi-dr.nii' template = '/usr/share/mouse-brain-templates/dsurqec_40micron_masked.nii' maps.stat3D(stat_map, template=template, save_as="_stat3D_mask.png", show_plot=False, threshold=0....
45adde171454ce5ca70d1abb9b277909cd7b81a775ab477db167cd34d7785fab
Python
1,478
57
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ Drop records with no non-reference genotypes from an input VCF Alternative to VCFTools, which rounds GQ to a max of 99 """ import argparse import sys import pysam from svtk.utils import is_biallelic def drop_nonref_gts(vcf, fout): NULL_GT = [(0, 0), (None, Non...
7c7e6bb5a8f56a99f0d5368143244289778756ae7d7ed1c4046f2cae725118b4
Python
1,478
48
from __future__ import division, print_function from nose.tools import with_setup, assert_raises, assert_equal import numpy as np from lavaburst import utils def test_compress_restore_path(): # simple example, no special cases data = np.fromiter('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', dtype...
cd4f5d1a0dc38a6fe064194e0a1e63bd0f3684a484355a8a1bda82e2cedfbac9
Python
1,478
41
# Train Dead import comet_ml from pytorch_lightning import Trainer from pytorch_lightning.loggers import CometLogger from src.models import dead from src.data import read_config import numpy as np import torch from sklearn.metrics import precision_recall_curve, PrecisionRecallDisplay config = read_config("config.yml"...
680a25d62e5f1794e11c2e5f502420dceccc163ef4c02c8e85c3ee3add7a86a6
Python
1,479
50
from pathlib import Path import matplotlib.pyplot as plt from siapy.entities import Pixels, SpectralImage # Set the path to the directory containing the data # !! ADJUST THIS PATH TO YOUR DATA DIRECTORY !! data_dir = "./docs/examples/data" # Get first image header_path_img0 = sorted(Path(data_dir).rglob("*.hdr"))[1...
86cb51bee08cd85effc9faa9057637c706aeca25038cccab9a71fe0150527ee5
Python
1,479
43
import os import argparse import numpy as np """Compute the SVM test accuracy obtained by K-fold cross validation""" def kfold_get_score(path): # Count the number of folds kfold_dir_runs = [] for item in os.listdir(path): full_path = os.path.join(path, item) if os.path.isdir(full_path): k...
a13fd4d611d3e558081a17fe9f37664a79e620ee3daeec674fc3258c539bb112
Python
1,479
61
#!/usr/local/bin/python from __future__ import print_function import wave import numpy import pyaudio from dateutil import parser audio = pyaudio.PyAudio() waveFile = wave.open('qanda_2012_ep99_climate.wav', 'r') subtitles = "qanda_2012_ep99_climate.srt" # csvfile = open('qanda/qanda_2012_ep99_climate.csv') # , n...
a9d78f2a378b204377dfc9cc67ec528970545b62349200950fd01c523e1b02ea
Python
1,480
66
import math import pytest import torch from aisegcell.models.unet import LitUnet, UNet_rec def test_Unet_rec(): """ Tests expected output size of an image by the Unet model """ image = torch.rand((2, 1, 512, 512)) unet = UNet_rec(bilinear=True, base_filters=32, receptive_field=128) image...
e73578df3e0e29e5bb702aaa0574a0c0f3102525fcf74533b5eca33a912fc94b
Python
1,480
84
import string import os import pathlib import vamb PARENTDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATADIR = os.path.join(PARENTDIR, "test", "data") BAM_FILES = sorted( [ pathlib.Path(DATADIR).joinpath("bam").joinpath(i) for i in os.listdir(os.path.join(DATADIR, "bam")) ...
2a2db6c750472314f2ea5012251f80d9fc092933b012adcc9a154a98bb82e18a
Python
1,481
41
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns def main(): # with open("/Users/chaokuan-hao/Documents/Projects/PR_SpliceNN/results/800bp/SRR1352129/OUTPUT/SpliceAI_6_RB_p_n_nn_n1_TB_all_samples_thr_100_splitByChrom_L64_C16_L800_v31/BAM/SRR1352129.discard.pup", "r") as f: # lines...
5e609ad0db5f5a6f43f18bd87df102c53637aecc5c41840fb2eb12052c4d63cd
Python
1,481
50
from contextlib import contextmanager from typing import List, Union import torch from ray._private.accelerators.hpu import HPU_PACKAGE_AVAILABLE from ray.air._internal.device_manager.torch_device_manager import TorchDeviceManager if HPU_PACKAGE_AVAILABLE: import habana_frameworks.torch.hpu as torch_hpu class ...
21c8eb5bea4e956052a73ba96fe8ff49ea4117e01bf4782140c22bef0e3bd357
Python
1,482
40
import os from importlib import resources as impresources from pathlib import Path from ... import bids from ...bids.convert2bids import BidsConverter from ...load_annotations.seizeit import loadAnnotationsFromEdf BIDS_DIR = impresources.files(bids) DATASET = BIDS_DIR / "seizeit" def convert(root: Path, outDir: Pat...
ceec201103a4e755445822ff96e0f72dca1e7bd74e280f841d452ca5c5e62b6e
Python
1,482
34
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # 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...
17fd832bbe4f984e6daae8d4d29a9b884f1aeb229ea70786696f48580edd2201
Python
1,484
43
import torch from Config import class_number SEED = 1234 torch.manual_seed(SEED) torch.backends.cudnn.deterministic = True import DataSet import torch.nn as nn import torch.nn.functional as F class TextCNN(nn.Module): def __init__(self): super(TextCNN, self).__init__() Vocab = len(DataSet.getTEXT...
391bdb19ad6b28602c889a5450b72ffc671cc587f2d79b08163e58bb83f18e84
Python
1,484
37
import time import sklearn import sklearn.ensemble import sklearn.metrics from sklearn.datasets import fetch_20newsgroups from sklearn.pipeline import make_pipeline from lime.lime_text import LimeTextExplainer def interpret_data(X, y, func, class_names): explainer = LimeTextExplainer(class_names=class_names) ...
c41640dbd10707e4c05e23b44d2acd70a0c58bea743c0875b6cbec814d4d4282
Python
1,484
44
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from fairchem.core.datasets.atomic_data import ...
e0b5759cb49067bd1e40df206ed046996e471c1f6a7c32e9ddd916af7e2a18fe
Python
1,484
58
import argparse import sys import time import ray # This prefix is used to identify the output log line that contains the runtime env. RUNTIME_ENV_LOG_LINE_PREFIX = "ray_job_test_runtime_env_output:" if __name__ == "__main__": parser = argparse.ArgumentParser(description="Dashboard agent.") parser.add_argume...
796f8b295d21068ba668f047aa0b9df07d57c11136c0e62bc4e9e29d2af3f219
Python
1,485
51
#!/usr/bin/env python # coding: utf-8 import torch import torch.nn as nn from Actor1 import init_weights class Critic(nn.Module): def __init__(self, OBS_DIM, ACTION_DIM, TARGET_DIM, RNN_SIZE, FC_SIZE, RNN): super().__init__() self.OBS_DIM = OBS_DIM self.ACTION_DIM = ACTION_DIM RN...
b584076058ea981fd523654bb9c042ba0f927d8a764ec12f9cb5a02820d835e3
Python
1,485
42
import numba from numba import jit, prange, f8, f4, u1 import math @jit("void(f8[:,:],f8[:],f8[:])",nopython=True,parallel=True,cache=True,fastmath=True) def fastCOMdistance(a,b,d): '''Calculate the COM distances between a point "b" and a series of points "a" Inputs: a(numpy.ndarray of float64, shap...
3ea5df0974d60c485a0dd3c1c5f0449b3b9831091a639e9edfca6636fbf9f6f6
Python
1,486
42
import os import sys sys.path.append('.') import cv2 import math import torch import argparse import numpy as np from torch.nn import functional as F from model.pytorch_msssim import ssim_matlab from model.RIFE import Model device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = Model() model.loa...
615080eaf01c0f9b676dcce035d2f10a25f3e05f5fc7c587463afaaa07cba48d
Python
1,486
46
import sys from parameters import ParameterSet from mozaik.models import Model from mozaik.connectors.meta_connectors import GaborConnector from mozaik.connectors.modular import ( ModularSamplingProbabilisticConnector, ModularSamplingProbabilisticConnectorAnnotationSamplesCount, ) from mozaik import load_compon...