sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
b3feaffcd8796daa426504aec74944c827011afab539fe593e9511b9e49b0714
Python
1,806
47
# Copyright 2019 Novartis Institutes for BioMedical Research Inc. 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...
b91f48ed17d2a0b91c4280f405c8ac2752867529d993a7ad33108477be1e7b1d
Python
1,806
51
"""myapp.py This is a simple example of how to use the stamping feature. It uses a custom stamping visitor to stamp a workflow with a unique monitoring id stamp (per task), and a different visitor to stamp the last task in the workflow. The last task is stamped with a consistent stamp, which is used to revoke the task...
43e7fd511b4acbebbf922a06b5dd0821fd2f38284f92b70a611310ecc424a29a
Python
1,807
57
from __future__ import division import unittest import numpy as np from wyrm.types import Data, BlockBuffer from wyrm.processing import append_cnt from functools import reduce class TestBlockBuffer(unittest.TestCase): def setUp(self): self.empty_dat = Data(np.array([]), [], [], []) self.dat_1 ...
474910e5ccdf2feac85fce3cba34e655416c6b820aee28b429d43fd1153796b2
Python
1,807
66
import os import subprocess import pysam try: import cyvcf2 except ImportError: pass def build_filter_from_vcf_with_samtoolsshell(fn): retval = os.popen( "bcftools filter -e \"N_ALT != 1 || QUAL < 20 || maf[0]>0.05\" {} | grep -cv ^# ".format(fn)).read() return int(retval.strip()) def build...
642aa4d859cc3dc4ded1d60b0014fd09ef2de297a6a1a5c7a18cb8c6e161dee9
Python
1,807
57
import h5py import numpy as np import tqdm.auto as tqdm from permacache import permacache from modular_splicing.dataset.dataset_aligner import DatasetAligner from modular_splicing.data_for_experiments.standardized_sample import ( standardized_sample, ) @permacache("dataset/dataset_by_gene_length/dataset_by_gene_...
eb092c6ec1046308bdfc87400bc99e3196f45732c278def3fd0f2d8eb1a449ab
Python
1,808
50
from model import * from utils import * import numpy as np import torch import os import warnings warnings.filterwarnings("ignore") TEST_BATCH_SIZE =256 model_name = 'ratio_0.9bach128LR_1e-4random_0_onehot.pt' dataset = ['tmp','BindingDB_reg','JAK','AR','CYP_reg'][int(sys.argv[1])] cuda_name = ['cuda:0','cuda:1','c...
bc41518b1f0cb62c70b4c499af7a97ce5a60c06c1845aadb2a40eacb79e31887
Python
1,810
51
# Copyright (c) 2022 PaddlePaddle Authors. 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 app...
7efd710ac26f0d89f422869ed9b27a39535092257433771c460f6f5665ed1ff1
Python
1,811
47
""" The previous code generated ABF1 files which display properly in ClampFit but not in MiniAnalysis. To assess why, the ABF converter was used to convert this "unknown binary" format to an ABF with a header MiniAnalysis is comfortable with. By inspecting that header we can see what needs to be changed to support Mi...
820fe475bcc9b64b96fc5d4fbf64a3cae76353816d9a622ccf79b7e3038c5c3d
Python
1,811
52
import os from setuptools import setup from setuptools import find_packages import sys if sys.version_info[:2] < (3, 8): raise RuntimeError("Python version >= 3.8 required.") # load the description PATH_HERE = os.path.abspath(os.path.dirname(__file__)) with open(os.path.abspath(PATH_HERE+"/README.rst")) as f: ...
cc79beea28eb17167acfb7b1d15d14073a66eb4f682245d8de77e5300ea4da79
Python
1,811
69
from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import IterableDataset from modular_splicing.utils.construct import construct from modular_splicing.utils.io import load_model from .motif_selector import ( MotifIncrementalAdder, MotifIncrementalDropper, ) def train( *, ...
e2455dfaad46857789caaa039907be595a4a3ed896fd809f87c68e27e75dada1
Python
1,811
57
import sys from robustness import datasets from robustness.attacker import AttackerModel from robustness.model_utils import make_and_restore_model from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH def build_net(ds_kwargs={}, return_metamer_layers=False): # We need to build the datase...
4acf54c69435629744e2ca1dde2e405f2ce5b5120a944ea18b255c5623264bdc
Python
1,812
47
from unittest import TestCase from drug_interactions.reader.dal import Drug, DrugBank class DrugTestCase(TestCase): def setUp(self): self.drug1 = Drug(**{'id_': '1', 'interactions': [('3', 'bar')]}) self.drug2 = Drug(**{'id_': '2', 'interactions': [('3', 'baz')]}) self.drug3 = Drug(**{'id...
6e51a021b5767d1fcfed4402ed781fcc56bf1f5a92f7a20c7bd4d941995ab9ed
Python
1,812
43
from typing import Tuple, Union import numpy as np def estimate_basic_bootstrap_CI( alpha: float, point_estimate: Union[np.ndarray, np.generic, float, int], # [*] bootstrapped_point_estimates: np.ndarray, # [n_bootstraps, *] ) -> Tuple[float, float]: """ Estimates the basic confidence interval ...
cf436f2154cf58e488b298628d08196eb4de2f233c5da75cba8667ddf1c04392
Python
1,812
60
import numpy as np import scipy.io # Code adapted from Mineault et al. 2021 def load_mat_as_dict(the_path: str): """Loads a mat file as a dictionary. Arguments: the_path: a string containing the path of a mat file. Returns: The mat file, formatted as a dict instead of a weir...
f6a9eb22424b69af7f2612ef606145ac690867e86890d5abf0cbbb7f45879295
Python
1,812
52
import argparse from pathlib import Path import jupytext import nbformat from nbformat import NotebookNode def add_installation_cell(nb: NotebookNode, script_path: Path) -> NotebookNode: # Find installation snippet with open(script_path, "r") as f: for line in f: line = line.strip() ...
073352b2d2376393785416293a5ab339590034ace427c96afe9addc2bf4f7bd0
Python
1,813
38
from pathlib import Path from pydantic_settings import BaseSettings, SettingsConfigDict # The root of the repository ROOT_DIR = Path(__file__).parent.parent.parent PKG_DIR = ROOT_DIR / "neurogym" CONFIG_DIR = PKG_DIR / "config" # Set LOCAL_DIR to the current working directory. This path is dynamic and depends on # wh...
20f5dde58f983bd770fc12a4070f2169b32f42b8a8de764af69412995fb9add1
Python
1,813
61
#!/usr/bin/env python from distutils.core import setup, Extension from distutils.command.build_ext import build_ext import git class CustomBuildExtCommand(build_ext): """build_ext command for use when numpy headers are needed.""" def run(self): # Import numpy here, only when headers are needed ...
374cc9a12dfb1937505098099b208c01ccbc9adc93f945ec40712f191e0244cf
Python
1,813
62
from __future__ import annotations import os import pytest from pytest_celery import CeleryTestWorker, defaults from pytest_docker_tools import build, container, fxtr from celery import Celery from t.smoke.workers.dev import SmokeWorkerContainer class OtherSmokeWorkerContainer(SmokeWorkerContainer): """Alterna...
41e7842c65164b04d3fea0d0a4518c205748caa426ad5312c5892fa23fc32e30
Python
1,813
60
from abc import abstractmethod from modular_splicing.motif_names import get_motif_names from .trainer import AutoMinimizingTrainer from modular_splicing.utils.construct import construct class MotifSelector(AutoMinimizingTrainer): def __init__(self, *args, names_spec, **kwargs): super().__init__(*args, **...
69fd8178375c70027a9fee6803a553f175201da0e0121a7e4e3fad5b147afa40
Python
1,813
77
from __future__ import annotations from pathlib import Path import polars as pl def scan(path: str | Path) -> pl.LazyFrame: """Scan a GFF or GTF file. Parameters ---------- path The path to the GTF file. Returns ------- pl.LazyFrame A lazy frame with columns: seqname, s...
0678f9a333c0eb003fe9d2e95553a670e180849278e19f9e2711f09eaacd2848
Python
1,814
53
from __future__ import annotations from typing import TYPE_CHECKING import numpy as np from gymnasium import Wrapper from neurogym.utils import spaces if TYPE_CHECKING: from neurogym.core import TrialEnv class PassAction(Wrapper): """Modifies observation by adding the previous action.""" metadata: di...
6b1e76727660661e1d990a6dd18ce93d130d1034d242308f59b125325a50ddef
Python
1,814
46
import os import tempfile from ethoscope.core.monitor import Monitor from ethoscope.drawers.drawers import DefaultDrawer from ethoscope.hardware.input.cameras import MovieVirtualCamera from ethoscope.hardware.interfaces.interfaces import HardwareConnection from ethoscope.io import ResultWriter, SQLiteResultWriter from...
ecbc93e230c194a0c4980b017757c5eb4c312b55c9e1c60f7185d0e1d8c3341d
Python
1,814
56
""" Norm Layer Factory Create norm modules by string (to mirror create_act and creat_norm-act fns) Copyright 2022 Ross Wightman """ import types import functools import torch.nn as nn from .norm import GroupNorm, GroupNorm1, LayerNorm, LayerNorm2d _NORM_MAP = dict( batchnorm=nn.BatchNorm2d, batchnorm2d=nn....
f175907f7570b62ff804520b2602afa9c8c4d35d3fa6d95a160f1af3bf296e83
Python
1,814
58
import http.server import json import socketserver import logging from src import config from src import sba_api from legacy.rpc_interface import RpcInterface logger = logging.getLogger(__name__) # Simple configuration PORT = config.PORT # State sba_interface = None neuriteLengthDistribution = None mySomaLocations =...
662f14465d5e5f528e5a4551d57ffb7465f6e5bfefde6b707eb061a75ad19d51
Python
1,815
40
from src.mesoscale_extractor import NeuronPopulation from src.utils import * # import src.convertAllenSpace as CAS data_repository = 'atlas_files' ## Initialize the NeuronPopulation class with the requested source and target areas from which the statistics will be derived neuropop_cls = NeuronPopulation(data_path = d...
c08b7f8cd18c77ff216ac9f088c8cfe2dc90310fc92208f65596fd57f0a3f097
Python
1,815
57
# coding=utf-8 # Copyright 2025 The Google Research Authors. # # 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 applicab...
f8625d4ec08a2e05833dafa63f621d00701cc2fef514f4c94cf0f41ec8b99080
Python
1,815
54
import os from mirp._images.generic_image import GenericImage from mirp._images.mr_dce_image import MRDCEImage from mirp.extract_features_and_images import extract_features_and_images, extract_images CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) def test_basic_dce_mr_feature_extraction(): # Separate ...
27785ce7a5996b5d515633ef96df9b1259cd53e7bd4c45b5fa51f7a44a170d74
Python
1,816
62
#!/usr/bin/env python # Created on: December 13, 2013 __author__ = "Sven Kreiss, Kyle Cranmer" __version__ = "0.1" import optparse parser = optparse.OptionParser(version=__version__) parser.add_option("-i", "--input", dest="input", default=None, help="Input folder.") parser.add_option("-f", "--inputFull", dest="in...
6e009a2ea95e4347104b0a9e2bc509699adac741090dd2745988b2f894cd29f2
Python
1,816
56
import subprocess def remove_docker_image(image_name): # Remove containers using the image try: container_rm_command = [ "docker", "rm", "-f", "$(docker ps -a -q --filter ancestor=" + image_name + ")", ] subprocess.run(container_rm_comman...
76770df7d2ce164bc5471a6a154cd6a7fd8baa546e8cbb69862a1ed11c05fc72
Python
1,816
37
"""Prepare cycle gan datasets""" import os import argparse import zipfile from gluoncv.utils import download, makedirs def parse_args(): parser = argparse.ArgumentParser( description='Initialize Cycle Gan dataset.', epilog='Example: python download_dataset.py --download-dir ./', formatter_c...
9a788288734e30594e51fa23ad5e0e2eaf8a03176c7fe44c991b825e078a56cc
Python
1,816
57
"""Add Notification System tables Revision ID: 2d749563e1fe Revises: b855b714e8b8 Create Date: 2023-03-02 15:16:36.737075 """ import sqlalchemy as sa from galaxy.model.custom_types import JSONType from galaxy.model.migrations.util import ( create_table, drop_table, transaction, ) # revision identifiers...
a3a0cf73d715526cbbb784196b84e514e989e2fcdcd1d57e86b5c9933d779c0f
Python
1,817
72
"""First five minutes with TorchLens interventions. What this demonstrates ---------------------- Capture a tiny model, discover the ReLU site, fork the log, zero-ablate that site, and replay the saved DAG. How to run ---------- ``python examples/intervention/01_first_five_minutes.py`` Runnable by default. No extern...
0ec1435938491abd3770dfb425177f28dc5c21bf72ddf401968ac29f4ebfb156
Python
1,818
59
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.architecture["motif_model_spec"] = dict( type="AdjustedMotifModel", model_to_adjust_spec=dict( ...
0f17bf8cf616f899133c4df1587c7b170671874a0ff2c6d054c5014ada6c8bd7
Python
1,818
72
"""Ordering contract tests for :func:`torchlens.extract_dataset`.""" from __future__ import annotations from pathlib import Path import torch from torch import nn import torchlens as tl class _OrderRevealingModel(nn.Module): """Return a deterministic affine transform that preserves row identity.""" def _...
69768fa5ff5583a4285c6a6810551d0f70b377b0ca2d9971c9c7f061087aa36a
Python
1,818
46
import os import shutil from src.AcquisitionParameters import AcquisitionParameters from src.InstrumentController import InstrumentController class AcquisitionControl: # controller: InstrumentController def __init__(self): self.controller = InstrumentController() def runAcquisition...
7db558836b3c0d741d8981d436e56314cb44260e2877555e8f6e668078460eed
Python
1,818
50
# -*- coding: utf-8 -*- # tests for metrics.py """"tests for clustering metrics""" import unittest import numpy as np from sknetwork.clustering import get_modularity, Louvain from sknetwork.data import star_wars, karate_club from sknetwork.data.test_graphs import test_graph class TestClusteringMetrics(unittest.Test...
fc1ca5ff0d1d0c4254ae56b6f1d8118460fa3f5edc8613215af057c87ae9dc35
Python
1,818
50
# LICENSE # # _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._ # # BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License"); # # - you may not use this software except in compl...
0d912fac7c1e90d57e855da4dee73fba3a1f31863fc05def69ea28f5c55f47d5
Python
1,819
47
import torch import torch.nn as nn import torch.nn.functional as F class MLP(nn.Module): def __init__(self, num_layers, input_dim, hidden_dim, output_dim): ''' num_layers: number of layers in the neural networks (EXCLUDING the input layer). If num_layers=1, this reduces to linear model. ...
08a7603ec8c95e0321aa3a29dcd11af95e3be548f470245be5d0108513b1791d
Python
1,820
49
# LICENSE # # _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._ # # BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License"); # # - you may not use this software except in compl...
27df50d19eb1547ff438db2905e8098b01894a99f75f69aa6ceb1db3471994c9
Python
1,820
53
#!/usr/bin/env python """ Adds Manually created builds and chrom info to Galaxy's info tables Usage: python add_manual_builds.py input_file builds.txt chrom_length_dir """ import os import sys def add_manual_builds(input_file, build_file, chr_dir): # determine existing builds, so as to not overwrite existi...
819085043854679cb041bfedd8e6ac53195a0dc4f4b2bdb9fb6765dfbd43d640
Python
1,821
33
from setuptools import setup, find_packages setup( name = "bio-past", version = "1.6.3", keywords = ["pip", "past"], description = "PAST: latent feature extraction with a Prior-based self-Attention framework for Spatial Transcriptomics", long_description = "PAST software is build on a variational g...
848ac77c6fff8658fb214fcbf43c535a908f2466d180c2804546c220aed69f80
Python
1,821
41
#Hopfield Networks created as described by: # Wulfram Gerstner, Werner M. Kistler, Richard Naud, and Liam Paninski. # Neuronal Dynamics: From Single Neurons to Networks and Models of Cognition. # Cambridge University Press, 2014. #Run for simulation of CRFS in: #Identification of Pattern Completion Neurons in N...
9eaf8344002c5941e012b960884160158e75d353d0629a334939a573527033b9
Python
1,821
62
from dotenv import load_dotenv import torch from omop_learn.omop import OMOPDataset from omop_learn.torch.models import VisitClassifier, VisitTransformer load_dotenv() config = Config({ "path": os.getenv("DATABASE_PATH"), "cdm_schema": os.getenv("CDM_SCHEMA"), "aux_cdm_schema": os.getenv("AUX_CDM_SCHEMA...
b414b693f199d981d7bca1b24912f83cc3cf393ddf6911a019d1eb2aacaa7810
Python
1,821
65
"""Parameter definition for Modes.""" from specparam.reports.strings import gen_params_str ################################################################################################### ################################################################################################### class ParamDefinition(): ...
ef2ee8525e4f0b7161442433f0040565f157dff8be041f3339acd452105bf76a
Python
1,821
62
import pandas as pd import matplotlib.pyplot as plt import numpy as np import re import spacy import pickle import time from collections import defaultdict import pmi_tfidf_classifier as ptic path = "../data/" np.random.seed(250) #spacy.prefer_gpu() #nlp = spacy.load("en_core_sci_sm", disable=['ner', 'parser']) data_...
8312fa563855552df566b4de3fe27daf649c1f49afe8d67fc35a32de38fd5a42
Python
1,822
57
import sys from robustness import datasets from robustness.attacker import AttackerModel from robustness.model_utils import make_and_restore_model from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH def build_net(ds_kwargs={}, return_metamer_layers=False): # We need to build the datase...
c4e13fe76d821a6a65942ef66b1fc4a08f172746acf87242194f9ebefb51ef89
Python
1,822
68
# Author: aqeelanwar # Created: 2 May,2020, 2:49 AM # Email: aqeel.anwar@gatech.edu from tkinter import filedialog from tkinter import * import cv2, os mouse_pts = [] def get_mouse_points(event, x, y, flags, param): global mouseX, mouseY, mouse_pts if event == cv2.EVENT_LBUTTONDOWN: mouseX, mouseY =...
42e82bc280dc82bef549a6071ae5d43bc69f3909e7c264674cf91b1ec959d16e
Python
1,823
53
__author__ = 'quentin' import cv2 import numpy as np from ethoscope.roi_builders.target_roi_builder import TargetGridROIBuilder from ethoscope.roi_builders.target_roi_builder import TargetGridROIBuilder import itertools class HD12TubesRoiBuilder(TargetGridROIBuilder): _description = {"overview": "The default sle...
a6fba570853af01d506576c5406392237a87e35f4517bd4ad5fd27737e56e2ad
Python
1,824
40
""" Generate predictors for word-level variables See the `explore_word_predictors.py` notebook for more background """ from pathlib import Path import eelbrain # Define paths to source data, and destination for predictors DATA_ROOT = Path("~").expanduser() / 'Data' / 'Alice' STIMULUS_DIR = DATA_ROOT / 'stimuli' PRE...
ff15773b3f8acfea07d41096026df3db9c6fa7c9ce52269aff367cd4c07525f2
Python
1,824
63
import numpy as np import scanpy as sc from scipy.optimize import linear_sum_assignment from scipy.stats import pearsonr from sklearn import metrics from sklearn.cluster import KMeans from sklearn.metrics.pairwise import cosine_similarity def pearsonr_error(y, h): res = [] if len(y.shape) < 2: y = y.r...
d47bb2cb2c1f15a275a4e172f5ff817c5f5eb47cacfc79d417ae211bb440d6e2
Python
1,825
50
# coding=utf-8 # Copyright 2026 The Google Research Authors. # # 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 applicab...
8100a23d815f833e6827f64ebd10df0c1571cf04c2a3a36462cb9cbeb9ccd976
Python
1,826
38
import unittest import pysam import os from svim.SVIM_COLLECT import retrieve_other_alignments class TestSAExtraction(unittest.TestCase): def setUp(self): TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'chimeric_read.sam') self.samfile = pysam.AlignmentFile(TESTDATA_FILENAME, "r") ...
8d586742cb69bfc5146b10ceb5d3386008e1c05c613819500af4cde202765a76
Python
1,826
64
"""Thread execution pool.""" from __future__ import annotations from concurrent.futures import Future, ThreadPoolExecutor, wait from typing import TYPE_CHECKING, Any, Callable from .base import BasePool, apply_target __all__ = ('TaskPool',) if TYPE_CHECKING: from typing import TypedDict PoolInfo = TypedDic...
a4b8a0f1a6ca113f5dc74f9695b0063804a9d99d14d54564a119ed50d2681016
Python
1,826
56
from tqdm import tqdm import pandas as pd def get_atoms(atoms, mp_params, width_coeff=1): columns = ['iteration', 'modulus', 'amplitude', 'width', 'frequency', 'phase', 'struct_len', 'absolute_position', 'offset', 'ch_id', 'ch_name'] dtypes = {'iteration': int, 'modulus': float, 'amplitude': fl...
d89453d947e0b34258d8b0e3b3bc58dd23a785d25da77b1f9e4cea51ba461b24
Python
1,826
53
import os import simplekml from tqdm.auto import tqdm from .geotif import get_geoms def preds_to_kml(df, data_folder, kml=None): """ Creates a simplekml kml object with polygons of given files. Polygons are green if correctly predicted and red if falsely predicted. :param files: list of files of wh...
05075695db2066f3581b1a7a1eba821539584dc21ddc92e753ef3031e1037e59
Python
1,827
53
import torch import torchmetrics METRIC_REGISTRY = { "r2score": torchmetrics.R2Score, "pearson": torchmetrics.PearsonCorrCoef, "spearman": torchmetrics.SpearmanCorrCoef, "explainedvariance": torchmetrics.ExplainedVariance, "auroc": torchmetrics.AUROC, # can be binary, multiclass, or multilabel, ca...
14d71d33c3cb75520600d583cf432031b7672053d5274984835721f74bfffa81
Python
1,827
55
""" A small collection of clustering algorithms. Some algorithms are in a naive implementation. More mature implementations can be found in `scikit-learn`. """ import numpy as np from numba import jit from .conv_squares_ import csq_find_rois, csq_plot_rois from .dbscan_ import dbscan from . import metrics #from . imp...
23bbbe32bc831f9e4d8f56959684c200807486fb856cb9d190fa466374e0ccd9
Python
1,827
40
import unittest from unittest import mock from codecarbon.core.slurm import warn_on_multi_rank_double_counting from codecarbon.emissions_tracker import OfflineEmissionsTracker class TestMultiRankWarning(unittest.TestCase): def _warnings(self, tracking_mode="machine", **env): with mock.patch.dict("os.envi...
a3d20ebd8b4543542df5ed9a117ab28e254e26f47e7027498cf6e1f47dbdf158
Python
1,827
47
import sys # setting path sys.path.append('../TM2_segmentation') import os import numpy as np import nibabel as nib import itk import pandas as pd import tarfile from scripts.preprocess_utils import find_file_in_path, register_to_template # load metadata file input_annotation_file = 'data/csv_files/aomic.tsv' ...
bdb247afd6ccd8413e63dc978cea98c863df28c7a62496c1a47c5dce1e2f4f7a
Python
1,827
62
""" Author: Derek van Tilborg -- TU/e -- 23-05-2022 Basic Multi-Layer Perceptron """ import torch import torch.nn.functional as F from torch.nn import Linear, Dropout from MoleculeACE.models.utils import NN import os class MLP(NN): def __init__(self, feat_in: int = 1024, n_layers: int = 3, hidden: int = 512, d...
5333b730077eccc20c2eb4f3f2dae58e8dcb377dad3230afb0539400fb52a77f
Python
1,829
68
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["motif_model_spec"] = dict( type="AdjustedMotifModel", model_to_adjust_spec=dict( type="PSAMMotifModel", motif_spec=dict(type="rbns"), e...
6582d2962fe1af6f22546a91be6d4b751793a2c584c3c806fe0a3bceddc2f098
Python
1,830
50
#!/usr/bin/env python # coding: utf-8 """ Plot sensor-level RDMs ---------------------- This example demonstrates how to visualize representational dissimilarity matrices (RDMs) computed from EEG data. We will compute them using a spatial searchlight and plot the RDM computed for each searchlight-patch. | Authors: |...
6c172fafb7ba4b49c560f669f5918024b94fb2a63b21965e7df85e90b74ef36e
Python
1,830
56
import tensorflow as tf from tensorflow.keras.layers import Dropout, Dense, GRU, Bidirectional class CharSmilesConfig(): def __init__(self, gru_layers: int=2, gru_units: int=32, gru_dropout_rate: float=0.2, dropout_rate: float=0.2, num_classes: int=1, **kwargs): self.gru_layer...
a583027ec99786251c1d08e92f9984b6f3c2e98e3bdbef54468ee4a80234960d
Python
1,830
55
"""`ParamRegistry.compute` on a parameter that has not been realized yet. `kdict` is filled lazily: a key is instantiated the first time something asks for it. `get` calls `update_kdict` before indexing, but `compute` indexed `kdict` directly, so computing a parameter nobody had touched raised a bare `KeyError`. The c...
399f2316713521e3fe04a3605199ea59f0d07dc9e2439149acef86f8807c9140
Python
1,832
58
import csv import copy #Функция, определяющая взаимодействие по главной/вспомогательной субъединице. X — цепь рецептора, Y — лиганда. def site(X,Y): if (X, Y) in (('A', 'D'), ('B','E'), ('C','F')): return '+' if (X, Y) in (('C', 'D'), ('A','E'), ('B','F')): return '–' Data="{}.csv" Types=['HB','PHO...
2412c996e214f5e699f140cf696c2d959039dd0f30cf577c3ee31553325f04d4
Python
1,833
56
""" This module create TransformerClassifPerProt """ # pylint: disable=W0223 import torch.nn as nn import torch class TransformerClassifPerProtApriori(nn.Module): """ This class define a Transformer model that classify an entire protein to ONE classe """ def __init__(self, transformer_embedder, num_c...
2a53e0880e43a06048b284f7cc46be77760bf62ce917a429114631c35514a94a
Python
1,833
71
""" ca_plots.py Modules for calcium imaging plots. """ import matplotlib.pyplot as plt from matplotlib.pyplot import style from scipy import signal from ..utils import (save_fig) ############################################################################### ########################################################...
b4ecb369cc3fdbb0e5cc84ac9910a80bcf72ab09b1dcba005ec9d664889e73d8
Python
1,833
64
"""Microbench: flat-buffer to_padded vs the awkward rpad/pad_none idiom.""" import time import tracemalloc import awkward.operations.str as ak_str import numpy as np from seqpro.rag import Ragged, to_padded def _naive_pad_bytes(rag, pad_value, length): return Ragged(ak_str.rpad(rag, length, pad_value)).to_nump...
c206a5a17a1b69dc5751663225fb21b2cfbff015c0a3df61f92d4affc531ffa8
Python
1,833
57
import sys from robustness import datasets from robustness.attacker import AttackerModel from robustness.model_utils import make_and_restore_model from model_analysis_folders.all_model_info import IMAGENET_PATH def build_net(ds_kwargs={}, return_metamer_layers=False): # We need to build the dataset so that the num...
0bb0b86abcdc6a1c93101acf311de0149c28bd9dd580a3b7eeddb6b170d2cb3f
Python
1,834
62
import numpy as np import pytest import gym from gym.wrappers import TransformReward @pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1"]) def test_transform_reward(env_id): # use case #1: scale scales = [0.1, 200] for scale in scales: env = gym.make(env_id, disable_env_checker=True)...
2f81f1f955a1ad7ec28ec30fe9da7e6ac2a86118849aef33152842fd8637ab01
Python
1,835
37
"""Per-epoch primitive extraction for the redesigned data layer (Phase 1, 2026-06-16). THIN WRAPPER over the single extraction authority `ingest.extract_subject_features` (called with return_per_epoch=True). It owns NO pipeline orchestration of its own — the select → CAR → resample → epoch → compute_phi_5d sequence li...
592fbc29d2ea10171fd3805e56f186e9a1f9b929a2b0f314e4c9e467c9690d7c
Python
1,835
51
import sys from importlib import import_module from celery.app.defaults import (_OLD_DEFAULTS, _OLD_SETTING_KEYS, _TO_NEW_KEY, _TO_OLD_KEY, DEFAULTS, NAMESPACES, SETTING_KEYS) class test_defaults: def setup_method(self): self._prev = sys.modules.pop('celery.app.defaults'...
21af32ace200cce1cd06dc6398520491b8dc1d68b77eef0f75a2c061639591c2
Python
1,836
50
import tensorflow as tf import tensorflow.keras as keras import tensorflow_addons as tfa import numpy as np from sklearn.model_selection import StratifiedKFold brightness_offset = 22 #43 # THIS OFFSET IS ADDED def load_mnist_with_brightness_offset(num_folds=5): # load and split the dataset into train and test s...
a9d20ec0472a16a41052584d3b68d526d71ecbf220f23b64378317fa159fab6b
Python
1,836
61
import unittest import pandas as pd from sqlalchemy import create_engine import os import codes3d import snps import create_test_data as test class VariantTest(unittest.TestCase): def setUp(self): self.output_dir = test.output_dir self.snp_list = test.snp_list self.snp_rsid_df = test.snp_r...
bc45a3adbd3e2f4ea6e2c3a7c9206c081da170ebba62c51b2886dc3aaef5d417
Python
1,836
60
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 7 18:08:10 2023 This script average the signal across voxels in each ROI, zscore the result per session, and save. @author: Florent Meyniel """ import re import os import glob import pickle import numpy as np SUBJECTS = [23, 24, 25, 26, 27, 28, ...
707cdec1a52da70f98086cbf044de15b5c5a2192287346fe87cdfbe2540e7d0b
Python
1,837
72
import itertools import time import pytest from billiard.einfo import ExceptionInfo pytest.importorskip('multiprocessing') def do_something(i): return i * i def long_something(): time.sleep(1) def raise_something(i): try: raise KeyError('FOO EXCEPTION') except KeyError: return Ex...
9790aa1eaee3e79d6fe1e17ea535e46de99630b98655979e059fa8a04e96e3ab
Python
1,837
58
# Author: Francois Aguet import numpy as np import rpy2 from rpy2.robjects.packages import importr from collections import Iterable from contextlib import contextmanager @contextmanager def suppress_stdout(): with open(os.devnull, "w") as devnull: old_stdout = sys.stdout sys.stdout = devnull ...
39af057cfeb36250e99586fed718802f4afc7cd888531720c3cde3d4022b866b
Python
1,839
38
# Import all the modules necessary for the Tool import streamlit as st st.set_page_config(page_title = "NOCICEPTRA",layout="wide") # set the tab name #draw interactive visualization using holoviews def main(): """ Landing Page of the Nociceptra Trajectory Tool """ #set the logo st.sidebar.info...
c7fdab6abc944eed8426a4f65e151310d3af78988b364bec0d89169fc6ac83fe
Python
1,839
67
"""Tests for specparam.io.files. Note: load tests load files created from save functions, so failures may reflect saving issues. """ import os from specparam.tests.tsettings import TEST_DATA_PATH from specparam.io.files import * ######################################################################################...
d237646e59d44caf5f983084a40f1544bd50d7ae7eb6f40ff1562109776ebaa2
Python
1,839
56
try: from fs_basespace import BASESPACEFS except ImportError: BASESPACEFS = None from galaxy.files.models import ( BaseFileSourceConfiguration, BaseFileSourceTemplateConfiguration, FilesSourceRuntimeContext, ) from galaxy.util.config_templates import TemplateExpansion from ._pyfilesystem2 import P...
dfb1680dd97dcf1968f9ade69c6e6c28eeabc5b1f50cd3ac7a478c1530b6fb20
Python
1,839
38
"""Convolutional Motif Kernel Network This package implements convolutional motif kernel networks (CMKNs) as well as functions that help interpret trained CMKN models. References: model: This module contains a basic network that utilizes the convolutional motif kernel. layers: This module contains different l...
524a72ecc0a85a974d956fa5e9f509292eccf153145da16df09e7d42a2500015
Python
1,840
60
""" Base UI for plugin popup. SimplyFire - Customizable analysis of electrophysiology data Copyright (C) 2022 Megumi Mori This program comes with ABSOLUTELY NO WARRANTY This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free So...
5c610bf170e22554b472593716edb30f00c1300c8707204d4b635d3bb95bf6cc
Python
1,840
61
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.architecture["motif_model_spec"] = dict( type="AdjustedMotifModel", model_to_adjust_spec=dict( ...
87b8a4f0f5d19e6f187255524016db0a1b3f61d5b244fdd04dd4c0a783d27ae2
Python
1,840
48
from keras.src import ops from keras.src import random from keras.src import testing from keras.src.backend.common import keras_tensor from keras.src.ops.einops import rearrange class RearrangeTest(testing.TestCase): def test_basic_rearrangement_symbolic(self): x = keras_tensor.KerasTensor((2, 3, 4)) ...
a38f370a0742909686be1111f9b11077c6076b8fb0cd5af840abbf3e43fdf060
Python
1,840
64
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class HalfCheetahEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 20, }...
df9f4509914a36488c1c5c49912ff4925e91e3fe257b6f744f02b949c083d831
Python
1,840
48
# Copyright (c) 2022 PaddlePaddle Authors. 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 app...
05632cc516c6637d24faa2c0a852f8edd149f5252f9ae3a6cf6c3b5ee63ad66d
Python
1,841
59
import os import random import h5py import numpy as np import scanpy as sc import tensorflow as tf from dca.api import dca from scbig.utils import louvain, calculate_metric def seed(SEED): os.environ['PYTHONHASHSEED'] = str(SEED) random.seed(SEED) np.random.seed(SEED) tf.random.set_seed(SEED) for d...
15e74f5bec8d1dcb127197339d87659f531978dc7c4d71eefd1215692e069731
Python
1,841
56
# first 2 lines to run in the console import os sys.path.append(os.path.join(os.getcwd(), 'brian_models/ripples_2populations_v2')) from external_input_utils import generate_ext_input, plot_ext_input, generate_multiple_spw import pickle ### Generate 100ms input with dt=0.1 duration = 100 N_e = 12000 n_excited = 1580 e...
26c3f466469b26b213f9ae58b4b54967a8b6242671859cc2906c76d60db44952
Python
1,841
55
import pickle def run(): from spitfire.time.integrator import odesolve from spitfire.time.stepcontrol import PIController from spitfire.time.methods import CashKarpS6P5Q4 import numpy as np def right_hand_side(q, fluid_density, drag_coeff, gravity, surface_area, mass): vel_x = q[0] ...
deb657cb99a2406829c149dcb764387fb0e9ff28e0c5dbf9d1a77ddb13ff96ce
Python
1,841
60
import sys,os,re from scipy.stats import pearsonr,spearmanr import pandas as pd def parse_entry(entry): if any([c == ' ' for c in entry]): return None else: return entry[0], float(entry[1]) def build_codon_table(filename): raw_frequencies = {} search_string = re.search('(.*)/(.*)_...
984ef01809b387ded93eb0dd99d668de55c1490a763be4eebf5e418cd0109e06
Python
1,842
61
from typing import Dict, List, Tuple, Union from PIL.Image import Image from torch import Tensor from lightly.transforms.torchvision_v2_compatibility import torchvision_transforms as T from lightly.transforms.utils import IMAGENET_NORMALIZE class IJEPATransform: """Implements the augmentations for I-JEPA [0, 1]...
d11a9fc9cd6996961147dd297558df5be0409be721678191f96f84af6b24ca17
Python
1,842
57
# inference test import unittest from unittest import TestCase import logging import pickle import glob logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) import os os.environ['CUDA_VISIBLE_DEVICES'] = '2' import jax import jax.numpy as jnp import jax.random as jrand from deepfold.model.con...
1314d9a80313de3a1853545243efddd588a9cac82790b29e3deed91ee3281de6
Python
1,843
41
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """tests for gnn utils""" import unittest from sknetwork.gnn.utils import * class TestUtils(unittest.TestCase): def test_check_norm(self): with self.assertRaises(ValueError): check_normalizations('foo') with self.assertRaises(ValueError...
966ad49a68589cb8d67e427331c638aaf16cb7ead7b64d03c2d7b68a44683a45
Python
1,843
45
"""Run with compute-sanitizer --tool synccheck to check cross-role TMEM barriers.""" import math import pytest import torch from flash_attn.cute import flash_attn_func pytestmark = pytest.mark.skipif( not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] not in (10, 11), reason="SM100/S...
a36bc8b555e8e46352c1039183271ebe316296ccc2c594995a8dc46657fb1f95
Python
1,843
56
from mirp._image_processing.utilities import standard_image_process_checks from mirp._images.generic_image import GenericImage from mirp._images.mask_image import MaskImage from mirp._data_import.utilities import flatten_list from mirp._masks.base_mask import BaseMask def randomise_mask( image: GenericImage, ...
235c88b104eaca92dc1e44b22a145061ebc0b00c7d503ea9df8df87d3faf0367
Python
1,844
66
#!/usr/bin/env python3 f_1 = open("files.txt", "r", encoding = "utf-8") filename = [] All = [] i = 1 for file_1 in f_1: line_1 = file_1.strip().split('\t') #改行コートをはがしてタブ区切 filename.append(line_1[0]) f_1.close j = 0 for file in filename: samplename = file.split('.')[0] All.append([samplename]) f...
40822b9408188bfb407f1797c08042a781fc51f9aa4906117236b96d96210bca
Python
1,844
60
'''Tests for distcomp''' import unittest import os import tempfile from bdpy.distcomp import DistComp class TestDistComp(unittest.TestCase): def test_distcomp_file(self): with tempfile.TemporaryDirectory() as lockdir: comp_id = 'test-distcomp-fs' # init distcomp = D...
2a9763314d18c08b72662fef5a9e4df946c623b8dadfb7100d2a7b726ff9157a
Python
1,845
73
import http.server import socketserver import threading import tempfile import os import asyncio import websockets import sys import json os.chdir('/Users/xenios/bisweb/src/build/web'); httpd=0; connections={}; # Temporary Directory # ------------------- def createTemp(): tmp=tempfile.TemporaryDirectory(dir='/Us...
5fcfea83864d09d31f91e7aced29621a9163bee62730b13ed4bf059898dd739f
Python
1,845
53
# import packages import numpy as np import dicom2nifti from volume import Volume import nibabel as nib import os import shutil def copytree(src, dst, symlinks=False, ignore=None): for item in os.listdir(src): if "Vinci" in item: continue s = os.path.join(src, item) d = os.path...
75ad33c826694549f9b23a1e6c58d9c937a5401d933d637c21188902a0e4e64e
Python
1,845
56
import numpy as np import tensorflow as tf import nibabel as nib import matplotlib.pyplot as plt class DataGenerator(tf.keras.utils.Sequence): def __init__(self, list_ids, labels, batch_size=5, dim=(128, 128, 70), n_channels=1, n_classes=2, shuffle=True): """Initialization""" self.dim = dim ...