sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
3817f8e566723de2868a2c207fb9e1205eae36606904c8c21822c08979a0a1fe
Python
2,221
58
from os import path from setuptools import find_packages, setup _dir = path.dirname(__file__) with open(path.join(_dir, "stardist_napari", "_version.py"), encoding="utf-8") as f: exec(f.read()) with open(path.join(_dir, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="sta...
702338a6dbec3874424672797e3dc8cd74c1db6cc2d0b6c7a2a7e65a85e6eaab
Python
2,221
60
# 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...
28e72a2632e168715b5918ec6884ed9dc32a0693b77c76ed31d54118fb692818
Python
2,222
65
import os from tqdm import tqdm import json import logging from os.path import join from dict_hash import sha256 """Handles utilities for saving/caching. This file probably does not need to be edited. """ def save_json(args={}, save_dir='results', fname='params.json', r={}): os.makedirs(save_dir, exist_ok=True) ...
591f46352691b54b89ea07e0ba20472be6fad6c95bb75225f44af811eb7224ec
Python
2,222
77
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Marker(_BaseTraceHierarchyType): _parent_path_str = "choroplethmap.selected" ...
10fa1d2411d889c5ee9e67b5fe0540487a94d583d396ddb8ae01f924a4560697
Python
2,223
91
import pandas as pd from anndata import AnnData def stack_3d_plot( adata: AnnData, slides, height, width, cmap="viridis", slide_col="sample_id", use_label=None, gene_symbol=None, ) -> None: """\ Clustering plot for spatial transcriptomics data. Also, it has a function to di...
a8ecdc0992daf08ed3f27cfb9ea62b049189bde03cf6de9aecbeaa4523420ae0
Python
2,223
77
""" Launchers of the diverse available simulation modes """ from __future__ import annotations from typing import Any __displayname__ = "Simulation" __all__: list[str] = [ "ABModel", "BaseRun", "ReplayRun", "ExpRun", "Exec", "BatchRun", "OptimizationOps", "GAlauncher", "EvalRun",...
2e0bf66690107422718d692b08763aeb2c7b91ad4fb8be46f4a5f6de3c536245
Python
2,224
88
# %% [markdown] # # Write labels # (basic:labels)= # # Storing labels data alongside image data is a key application and feature of the ome-zarr file standard. # First, let's create some image data: # %% import numpy as np from skimage.data import binary_blobs from ome_zarr import OMEZarrImage, OMEZarrLabels, OMEZarr...
5dbcefd55eaadaf0f16cd60fdf9218d6cd074f3c998831676f227bda39be8d89
Python
2,226
67
"""Python Buffer Protocol for R arrays.""" import typing from rpy2.rinterface_lib import openrlib def getrank(cdata) -> int: """Get the rank (number of dimensions) of an R array. The R NULL will return a rank of 1. :param cdata: C data from cffi :return: The rank""" dim_cdata = openrlib.rlib.Rf_g...
7feeb42c06bdf8422643f463514a949b1b29dc908c5c0e3df2425e55755206c3
Python
2,226
87
import numpy as np import torch def all_seqs(n, *, amount=4): """ Generates all sequences of length n, with the given amount of nucleotides. """ if n == 0: yield [] return for s in all_seqs(n - 1, amount=amount): for i in np.eye(amount): yield [i] + s def pack...
2ee38b8ae985fbd286069754c46c1e14a830ca35401578e6ceeacdd272a85362
Python
2,227
62
""" This module define loss logger """ import numpy as np import logging class LossLogger: """ This class keep track of the loss during the training process We have two function in order to add train loss, the first one is add_train_loss_tmp() that is executed at each epoch and calc_mean_train_loss() ...
3d09c17983ab1254916cb93b9410d10d523a01c25b412503694a3b9811d8893a
Python
2,227
55
import sys from tqdm import tqdm # Define file names from command line arguments gtf_file = sys.argv[1] # GTF file hits_file = sys.argv[2] # Hits file annotation_table_file = sys.argv[3] # Transcriptome annotation table file output_file = sys.argv[4] # Output GTF file with annotations # Function to append blastx ...
37a9ba7e1cc92b02ee527a924575f5962e820b773fd6f322cea53a0edb75c380
Python
2,228
80
''' Load K-folding models from groups and evaluate performance author : obanmarcos ''' import os, sys from config import * sys.path.append(where_am_i()) import lightning as pl import argparse import numpy as np import matplotlib.pyplot as plt import pandas as pd from utilities import dataloading_utilities as dlutil...
8f70b1de776f8268c0fb3751a16e2504f74df59ca9ef11890d575f897c8ce5b9
Python
2,229
69
from typing import Dict import torch @torch.jit.script def sample_hiddens( chains : Dict[str, torch.Tensor], params : Dict[str, torch.Tensor], beta : float=1. ) -> Dict[str, torch.Tensor]: """Samples the hidden layer conditioned on the state of the visible layer. Args: chains (Dict[s...
c37ee95c8513402f4b6315113c0287266b4a7fbe0dc5ff04320bb51a9b00feb0
Python
2,229
55
from typing import List, Optional, Tuple import numpy as np from anndata import AnnData from ...logging import logger_manager as lm def get_X_Y_grid( adata: Optional[AnnData] = None, genes: Optional[List] = None, X: Optional[np.ndarray] = None, Y: Optional[np.ndarray] = None, grid_num: List = [5...
cbd708367c44ff8a8d12daceb7ad4e18fa88f79d706304a58cc665f3faf34423
Python
2,229
66
"""Helper functions for dealing with logging By default, mne's logger has a highly verbose stream handler logging to the screen. Here this screen handler is set to a higher level (WARNING), but only if Eelbrain is the primary import (i.e., it is imported before mne) and if the user has not stored another configuration...
85cd94d3b25f22c4c55303aca094111a81eadb01a684256cd3e1d3e6132c5901
Python
2,230
72
"""Save, load, and execute a sparse runnable ``.tlspec`` artifact.""" from __future__ import annotations import tempfile from pathlib import Path import torch from torch import nn import torchlens as tl from torchlens.options import CaptureOptions class TinyClassifier(nn.Module): """Small deterministic model ...
ecb5542c89620318b72a4fd067cae17751d3cdb742bb1b6d37a558bc3a4030e7
Python
2,231
55
#!/usr/bin/env python # # Copyright 2019 Google LLC. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list o...
34afbdff16c58c5502a5ea9d6537178842a61bcc5267b0fc02fd5fa9aca6ba87
Python
2,232
70
from keras.src import backend from keras.src.api_export import keras_export from keras.src.layers.merging.base_merge import Merge @keras_export("keras.layers.Average") class Average(Merge): """Averages a list of inputs element-wise.. It takes as input a list of tensors, all of the same shape, and returns...
ca5ceb6fb5149b03b33559d4e79a3e9e90d7f008e69c8d7f661d4441d7aa4184
Python
2,232
55
'''Power ROI functions''' import numpy as np ours2orig = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 254, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, ...
9da3b7875ccecd5e745c287c77e6033eda1b0ccc20fec657ab2e9c621eed3477
Python
2,233
54
import torch import torch.nn as nn import numpy as np import torch.distributed as dist def Optimize(Epoch,print_epoch,ema_nbatch,weight_scheduler,scheduler,print_info,data_train,data_val,get_loss,swa_model,optim): rank=dist.get_rank() lr=optim.param_groups[0]["lr"] intime_weight=weight_scheduler(lr) ...
7da384d1e7b3fcddee99cac522927ffa599dd7a81ca36ccc507cc350803119f8
Python
2,234
93
from dataclasses import dataclass from enum import Enum from fastapi import HTTPException class EmptyResultException(Exception): """ The request return an empty result. """ class AuthenticationError(HTTPException): """ Raised when a session cookie or bearer token cannot be verified (bad/abs...
c90887e68aaa07653386becaca41162bd9437754bc74446f10680bf1359e8ee4
Python
2,234
61
from copy import deepcopy import numpy as np from sklearn.metrics import accuracy_score from sklearn.utils import resample from tqdm import tqdm class BaggingEstimatorText: def __init__(self, estimator, n_estimators=10, max_samples=1.0, bootstrap=True, random_state=None): """Use this class because skl...
ce7a0195e87917c85fc7c04dd3eca6e6ebb5f3b9290049c26a55b4679d4f89d9
Python
2,234
82
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Fit peptides for degradation constant and half-life. Project: SILAM Step #2 Goals: (1) Filter for peptides with R^2 passed the threshold; (2) Scale the value for each peptide from 0 to 1 based on the max value. Input data: (1) Peptide mass spec readout, normalized...
36c9af185868c693aaecc95b41d5ab5626a8904bee509bbf959cfa90adb6ccea
Python
2,235
76
# # MarkovModels setuptools script # import os from setuptools import find_packages, setup # Load text for description with open('README.md') as f: readme = f.read() # Load version number #with open(os.path.join('MarkovModels', 'version.txt'), 'r') as f: # version = f.read() version = "0" # Go! setup( ...
9aae1ea8fdf29dc3b7fb11a07478a0be90f20b27783f84054447995cc3b903f5
Python
2,236
61
"""Regression tests for r18bauto. Item 2 (landed): ``tl.record`` must enforce the same unsupported-tensor-variant guard that ``tl.trace`` enforces (meta / sparse / symbolic-shape inputs). Before this fix ``record`` skipped the guard and crashed deep in the capture pipeline with an opaque torch error instead of raising...
35eb40bd8352fad47ea61e3e66e523a969e6e6538f6df6c9f3f7c7ae5f5e48ea
Python
2,237
61
""" Create PCA images. """ import argparse import os.path import pathlib import numpy import numpy.random from sklearn import decomposition import skimage.io def parseargs(): """ Parses arguments. """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-i', ...
ab0c7ee31da81cfffda09aea239ac6c4b184fb28e09eb0b89446b04ca0673f0f
Python
2,237
83
"""Tests for specparam.plts.templates.""" import numpy as np from specparam.modutils.dependencies import safe_import from specparam.tests.tutils import plot_test from specparam.plts.templates import * mpl = safe_import('matplotlib') #################################################################################...
c70a158dca63ed22421b96c890eae55f4afb86ad1bf3ca3ffe99e86a68a0a973
Python
2,237
54
"""R23-3: ParamRef construction pairs each RAW parent-param with ITS barcode. ``_param_barcodes`` is the DEDUPED key list of ``parent_param_ops`` (a dict) while ``parent_params`` is the raw occurrence list, so the old ``zip(barcodes, params)`` misaligned every pairing after a repeated param (weight-tied einsum / hyper...
cf9985674153fb8965765563328e58b0df5641418b7f1a82d250218de82e9c7b
Python
2,237
65
# 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...
4915ad227f882c333b185e4db73dd9cd899335788c6918574b1f8832dbfc1f89
Python
2,238
72
# coding=utf-8 # Copyright 2024 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...
1a91256e56db3456d95829e190c9194babb2c4c0f48aa11930e16189484ead2e
Python
2,239
78
"""Prepare Cityscapes dataset. ======================== `Cityscapes <http://sceneparsing.csail.mit.edu/>`_ focuses on semantic understanding of urban street scenes. This tutorial help you to download Cityscapes and set it up for later experiments. .. image:: https://www.cityscapes-dataset.com/wordpress/wp-content/up...
c338943926cb792a566a20a488f5db0a0a9fd880f306840e1e3852ed90520245
Python
2,239
85
#!/usr/bin/python # USAGE: ./manhattan_filt.py <filedir> import sys import os #import json import pandas as pd import numpy as np import math import re filedir = sys.argv[1] if re.match(".+\/$", filedir) is None: filedir += '/' GWAS = pd.read_csv(filedir+"input.snps", delim_whitespace=True, usecols=["chr", "bp", "p...
f6ded044e31e3f8de5f394a186511757aec174a8c6af31f7d1487d7edcf52c0d
Python
2,239
80
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Diagonal(_BaseTraceHierarchyType): _parent_path_str = "splom" _path_str =...
51f2de71b48598a0f46f019ca65be0788cea828003a8b4c71be77af614b3721e
Python
2,240
78
from pathlib import Path from typing import Annotated import typer def main( n_seqs: int, seq_length: int, output: Path, max_memory: Annotated[int, typer.Argument(help="Max memory in mebibytes.")], ): import logging import sys from time import perf_counter import numcodecs as ncds ...
fb2785d33ef8aca1de8551650c52ce95d44d9411d6cc21cd5ad0dbdd26e5e15c
Python
2,240
82
''' compile_test.py - check pyximport functionality with pysam ========================================================== test script for checking if compilation against pysam and tabix works. ''' # clean up previous compilation import os import platform import pytest import pysam from TestUtils import make_data_file...
04ebd9f4bf97ee4c949d0827f8486c330ef00c96bd81f14e535c2878ab8e335b
Python
2,241
62
# content of conftest.py import pytest import torch.multiprocessing as mp # Distributed (DDP) test pool, see #1982. The flag and gloo setup live in # tests/ddp_helpers.py so they can be typed and shared with the test modules; # the session hooks below only start/stop the pool. from tests.ddp_helpers import NUM_PROCES...
29f0c7d65e54f988aa957635a3a15e20c6c912c80df0d54ffe22830a93156c89
Python
2,241
69
# Deprecated # Now we use sa2.merge.rmdlt.py to get a complete bmat snap file. # then do subset on it directly. import os import sys import traceback from pathlib import Path import logging from typing import Dict, List import shutil from numba.core.errors import NumbaDeprecationWarning from numba.core.errors import...
92aeab5a52f8288fc64c8dab84bf969160c966bc31410d49f62da43bc092b7f3
Python
2,241
83
from flask_login import current_user from mongoengine import * import imantics as im class CategoryModel(DynamicDocument): COCO_PROPERTIES = ["id", "name", "supercategory", "color", "metadata",\ "keypoint_edges", "keypoint_labels", "keypoint_colors"] id = SequenceField(primary_key=T...
d07038c616f5cef2773b18262d16ae55dc04f02134286e0c4b4941b253fd3fb2
Python
2,241
67
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 import os def build_net(ds_kwargs={}, return_metamer_layers=False): # We need to build...
0fed94350966e46e36a1f89b98c1f73228316ffa463db378e81444422d211a5a
Python
2,242
50
"""The CPU Float8 allocation guard, importable from an unambiguous dotted path. ``tests/conftest.py`` and ``tests/backends/conftest.py`` are two DIFFERENT files that both resolve to the bare top-level module name ``conftest`` under pytest's default ``prepend`` import mode (neither ``tests/`` nor ``tests/backends/`` is...
a8a4ddf453038d04f3ce157d168f3020ff0ab96e5b2ce3928166a1dd83645082
Python
2,242
62
""" Backs up and restores a settings file to Dropbox. This is an example app for API v2. """ import sys import os import dropbox from dropbox.files import WriteMode from dropbox.exceptions import ApiError, AuthError # Add OAuth2 access token here. # You can generate one for yourself in the App Console. # See <https:/...
c43d89eb95a77290e4fae3accc1b67c454ceed32cdbbbe1fa3cad4950592fec4
Python
2,242
79
""" Collection of standalone methods, custom classes and other tools, all of them independent of the larvaworld registry. This file used to eagerly star-import many submodules, which made importing `larvaworld` heavier and obscured the public surface. We now lazily import the same symbols on first access to preserve b...
641dc5d543d4e9220c6621728beb4ab917e53856a516457af8b819fffee8693e
Python
2,243
76
import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule from mmcv.runner import BaseModule from ..builder import NECKS @NECKS.register_module() class FPN(BaseModule): def __init__(self, in_channels, out_channels, conv_cfg=None, ...
e561debf4f9de674ce83a004cc86720a659289e4cedd834b34eda407a4536161
Python
2,243
62
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """tests for pagerank.py""" import unittest import numpy as np from sknetwork.data.models import cyclic_digraph from sknetwork.data.test_graphs import test_graph, test_digraph, test_bigraph from sknetwork.ranking.pagerank import PageRank class TestPageRank(unittest.Te...
337a283cd580e0ad59e7deec83aecd3e618373c7f0072670ad6ee103991b64d4
Python
2,244
72
# -*- coding: utf-8 -*- # @Author: gviejo # @Date: 2022-11-30 09:29:21 # @Last Modified by: gviejo # @Last Modified time: 2024-02-26 13:14:41 """Tests of time units for `pynapple` package.""" # from pynapple.core.time_units import format_timestamps, return_timestamps, sort_timestamps # from pynapple.core.time_inde...
4c92b1da02ee18b16b4487281f53ba78f531d6a3f86be519164f3cd8267086a6
Python
2,245
64
import os import h5py import numpy as np import scanpy as sc from ica import ica1 from scbig.utils import read_data, setup_seed, louvain, calculate_metric def preprocess(adata, scale=True): sc.pp.filter_genes(adata, min_cells=3) sc.pp.filter_cells(adata, min_genes=200) sc.pp.normalize_total(adata, targe...
c52bf3fc86f13677a2f08ac4cac20e8bc6295ff6ba79dc55138d60fe54b1d669
Python
2,245
63
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for format.py""" import unittest from sknetwork.data.test_graphs import * from sknetwork.utils.format import * class TestFormats(unittest.TestCase): def setUp(self): """Basic biadjacency for tests.""" self.biadjacency = test_bigraph() ...
2643a1933a10e6daa40a7d84adb6c29db1e54740f6d0d7a7ab42fd622064e9af
Python
2,246
70
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: bream/experiment_estimated_end.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflect...
2b5e19bd2507ae0e0df704b94826ede34b39f7c585678f615b9b5cd5edf593e1
Python
2,246
67
#!/usr/bin/env python # coding: utf-8 # In[1]: import tensorflow as tf import tensorflow.keras as keras from tensorflow.keras.layers import Reshape, Input, Flatten, concatenate, Dense, BatchNormalization ,Conv1D,Conv2D,Conv3D,MaxPool1D, MaxPool2D,MaxPool3D, GlobalMaxPool2D, Dropout from tensorflow.keras.optimizers i...
82ff045b06126152a650981ded61536bce73f6ada6e6f280d7ef1361209cdf6b
Python
2,246
60
from typing import Tuple import torch from torch import Tensor from torch.distributions import Uniform from torch.distributions.bernoulli import Bernoulli class PhaseShiftTransform: """Implementation of phase shifting transformation. Applies a random phase shift `theta` (positive or negative) t...
9df4b2524885c55ce90efb09c504b532cdc2e5f0918bb013c5897566c340f9b9
Python
2,247
73
# %% ''' Downsamples fmriprep cifti data into parcellation Assumes you have access to connectome workbench command line ''' import numpy as np import subprocess import sys sys.path.append("..") from functions.data_helpers import get_computer # paths computer, _ = get_computer() if computer == 'lucky2': prefix = '...
b5f88a356ab4735c310b06ceddf950313216516b4f8586e4b64f76cd6bfd9a2f
Python
2,247
81
''' Load K-folding models from groups and evaluate performance author : obanmarcos ''' import os, sys from config import * sys.path.append(where_am_i()) import pytorch_lightning as pl import argparse import numpy as np import matplotlib.pyplot as plt import pandas as pd from utilities import dataloading_utilities a...
6397727f16d72f01454705d1ead4493b0861526250c2949e3a43c8cf1b9e53f4
Python
2,248
63
from __future__ import annotations import panel as pn import pytest from larvaworld.lib.reg.generators import ExpConf from larvaworld.portal.config_widgets import build_sim_ops_widget from larvaworld.portal.simulation.parameter_resolution import ( resolve_base_experiment_parameters, ) def _find_widget_any( ...
2f96e971151725a64796ba619e5bdd988879c22988ae0c31a84504ff3242fcde
Python
2,249
55
import numpy as np from scipy.interpolate import PchipInterpolator, Akima1DInterpolator from numba import jit from typing import Tuple # @jit(nopython=True) # Define a function to generate a 2D Gaussian kernel using the shape and sigma as inputs def matlab_style_gauss2D( shape: Tuple[int, int], sigma: float = 1.0...
be337feb715bf83579badfba8a0d8e5b4e4317c17a5afca5bfefcaf5fec83b83
Python
2,250
56
electronic_states = { "H": "1s1", "He": "1s2", "Li": "1s2 2s1", "Be": "1s2 2s2", "B": "1s2 2s2 2p1", "C": "1s2 2s2 2p2", "N": "1s2 2s2 2p3", "O": "1s2 2s2 2p4", "F": "1s2 2s2 2p5", "Ne": "1s2 2s2 2p6", "Na": "1s2 2s2 2p6 3s1", "Mg": "1s2 2s2 2p6 3s2", "Al": "1s2 2s2 2...
090033855c7d5623eda8b354bc07aa9ca8f98967c511ca8cc794656568c9df47
Python
2,251
79
""" Package containing all pip commands """ from __future__ import absolute_import from pip._internal.commands.completion import CompletionCommand from pip._internal.commands.configuration import ConfigurationCommand from pip._internal.commands.download import DownloadCommand from pip._internal.commands.freeze import ...
878ffd47b52f9e67d82157ba8e22abc4de5fc53414d600df432982862fddd572
Python
2,251
62
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ A script to convert AMBER's NetCDF trajectories to dcd format that CHARMM can read. The script assumes that the ...
daccbd241a3cee7f70f10685064934eb6f272d95a75f3ced5780d4b6d5000eb4
Python
2,252
96
import pathlib import numpy as np from impose.structure import ( StructureComposite, StructureCompositeStack, StructureLayer) from impose.geometry import shapes data_path = pathlib.Path(__file__).parent / "data" def make_sc(seed=42): np.random.seed(seed) sl1 = StructureLayer( label="test layer"...
45148097c83fbded3288b0ccc3333dd3bca51bb74c4000df2fb33fa090863842
Python
2,253
70
import pytest import tensorflow as tf from psychrnn.backend.rnn import RNN from pytest_mock import mocker import sys if sys.version_info[0] == 2: from mock import patch else: from unittest.mock import patch # clears tf graph after each test. @pytest.fixture() def tf_graph(): yield tf.compat.v1.reset...
7be0a3c404456f0484ab517a448b657de53a2d6c77f07d5219e8e0017497d0c6
Python
2,253
72
import numpy as np import torch import tqdm.auto as tqdm from permacache import permacache, stable_hash, drop_if_equal from modular_splicing.evaluation.predict_splicing import predict_splicepoints_cached from modular_splicing.models_for_testing.load_model_for_testing import ( achieved_target_acc, ) from modular_s...
ef1397afea52bae3aee77ce8739e346cf6ad25c8d4b981a57313a815b7ef6195
Python
2,253
44
import tensorflow as tf from tensorflow.keras.layers import MultiHeadAttention, LayerNormalization, Dropout, Layer from tensorflow.keras.layers import Dense, Embedding from tensorflow.keras.models import Sequential class TransformerBlock(Layer): def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1): ...
00883a5f4b7b1d00f00c800818ff392d7a9637cc12b6450035c934d4a0af2b0a
Python
2,254
57
import torch from torchvision import datasets, transforms import numpy as np def rand_match_on_idx(l1, idx1, l2, idx2, max_d, dm): """ l*: sorted labels idx*: indices of sorted labels in original list """ _idx1, _idx2 = [], [] for l in np.unique(l1): # assuming both have same idxs l_i...
0692cc03d90a98a927e9ab4880367c34a77d01e57b3a2d345463e0e6de4d8ca7
Python
2,254
66
import numpy as np from mudcod.community_detection import MuDCoD, StaticSpectralCoD from mudcod.network_simulations import MuSDynamicDCBM from sklearn.metrics.cluster import adjusted_rand_score T = 4 S = 8 # Multi-subject Dynamic DCBM model_dcbm = MuSDynamicDCBM( n=200, # Total number of vertices model_order...
b933a8c05796d832a3df5cdb3488ab30d76c27f69b640b2998c5188668a9beb2
Python
2,254
55
# 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...
c9c1d768aaf36d9bf972b615c47f70b7e15f1fc566eb53ffa18d95555b644f00
Python
2,254
51
from PCA.src.denoise import * from PCA.src.utils import * from Transform.src.noise import Noiser from test_support_function.src.CEST import generate_Z_3D # Function to generate synthetic CEST data with specified image shape, dynamic range, and noise level def gen_data(img_shape: tuple, dyn: int, sigma: float): # ...
e78e469ebab9f6edec3f26a4e42138f60e83d1627a247cd0b522cbb7b2905e85
Python
2,254
70
############################################################# # Plot Figure 3F of the manuscript ############################################################# import numpy as np import pandas as pd import matplotlib.pyplot as plt coordFilename = '../SlideSeq2/spa.csv' expFilename = '../SlideSeq2/count.csv' coord=pd....
ec8b095045708e21257811094e8405aaec129569f8dfebe56499e627c775d8cd
Python
2,254
70
############################################################# # Plot Figure 3G of the manuscript ############################################################# import numpy as np import pandas as pd import matplotlib.pyplot as plt coordFilename = '../SlideSeq2/spa.csv' expFilename = '../SlideSeq2/count.csv' coord=pd....
742d6c7d1b9aab31f0d3e41319d9a1c5aa929f5bd7ee97f294812e7f5717b072
Python
2,255
54
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/healthy_adults...
ef3e04b35e3f55760b13aa5149b1c2334b7b7cb87c41ee183cd02275a3da778b
Python
2,255
76
import numpy as np from bct import distance_wei_floyd, retrieve_shortest_path from tqdm import tqdm import itertools def path_transitivity(W, transform = None): """ Computes the path transitivity, or density of one-step detours (triangles) available along the shortest path between all pairs of nodes. ...
0504898f40dc8a2b2d2d30cd15ac79a6b68f1f2cce9165b6dc276ba7935ca9e4
Python
2,256
74
"""Subprocess entry point for isolated capture-oracle characterization.""" from __future__ import annotations import argparse import json import os from collections.abc import Sequence # Pin the CPU kernel paths BEFORE torch loads (ATen reads its capability and # MKL its reproducibility branch at first use). The gol...
2026073a2fc2e386a288914e4e2a27900b00115da880d96a72334dc46f5f11ed
Python
2,256
62
from enum import Enum from pydantic import Field from galaxy.managers.context import ProvidesUserContext from galaxy.model.tags import GalaxyTagHandlerSession from galaxy.schema.fields import DecodedDatabaseIdField from galaxy.schema.schema import ( Model, TagCollection, ) class TaggableItemClass(Enum): ...
a815bfb46f935f7d1740282677820052e597e6bc508215aa6db75cd4fcf2900a
Python
2,256
67
from __future__ import annotations from typing import Optional import numpy as np import torch from scipy.stats import spearmanr def pearson_r(y_true: torch.Tensor, y_pred: torch.Tensor, dim: int = 0, eps: float = 1e-12) -> torch.Tensor: x = y_true y = y_pred xm = x - torch.nanmean(x, dim=dim, keepdim=T...
1e4a784479e6011937db70099eeea219eb0a7d13d2f770e5b45cad0764212254
Python
2,257
73
from typing import Optional from anndata import AnnData import numpy as np from scipy.sparse import csr_matrix import pandas as pd from ._weighting_matrix import ( calculate_weight_matrix, impute_neighbour, _WEIGHTING_MATRIX, _PLATFORM, ) def SME_normalize( adata: AnnData, use_data: str = "raw...
592f72b4ee143ba346860d3e0f0f50ea836b774f6a6ee1d979db3a0760e7ed48
Python
2,257
71
from sklearn.base import ClassifierMixin, ClusterMixin, TransformerMixin class SpdTransfMixin(TransformerMixin): """TransformerMixin for SPD matrices""" def fit_transform(self, X, y=None, sample_weight=None): """Fit and transform in a single function. Parameters ---------- X ...
675c57c302253ae8c67204be2b7bd930539c20960f949f6b444dca6f3a874817
Python
2,257
89
# a/b will always return float import numpy as np from .constants import * _maxshape=100e6 def memsafe_arr(shape, dtype=_dtype_): import tempfile as tmpf shape = tuple(shape) N = np.prod(shape) if N < _maxshape_: return np.zeros(shape, dtype=dtype) else: print("Using memory-mapp...
7e1ba4a242257ce907c6247a11be16050ed75bfd2919c613ccfbafd69347b6ee
Python
2,257
70
import numpy as np from pylsl import StreamInlet, resolve_stream, local_clock import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import ipdb plot_duration = 2.0 # first resolve an EEG stream on the lab network print("looking for an EEG stream...") streams = resolve_stream('type', 'EEG') ipdb.set_trace() ...
85dfdded5c5514f4d827148993fbc5acd5c279247adbf48c936f87e84753cbb8
Python
2,257
65
import pandas as pd import tqdm from tqdm import tqdm from src.grid_search import * from sklearn.linear_model import LogisticRegression from statistics import mean, stdev import pickle def assign_target(input_df): input_df = pd.read_csv(input_df, index_col=0) input_df['animal'] = input_df.index.str[-1] in...
fe634fad75727af5b6a48b4ef63a13c855052cf0e9b6a6d85f5c0fdfebd229a7
Python
2,257
63
from galaxy.files.sources.gitlab import ( GitLabFileSourceConfiguration, GitLabFileSourceTemplateConfiguration, GitLabFilesSource, ) try: from arcfs.fs import GitLabARCFileSystem except ImportError: GitLabARCFileSystem = None # type: ignore[assignment, misc, unused-ignore] class ARCFileSourceTem...
4fa999bc32e1ffe92fc5af6fec991c6e2bf98e6f8f805f98711495afa25d0799
Python
2,258
76
#!/usr/bin/env python import argparse import sys import readfile txt_output = ["cids", "aids", "sids", "synonyms"] csv_output = ["assaysummary", "property"] check_for_id_type = ["cids", "aids", "sids"] def main(args): url = "http://pubchem.ncbi.nlm.nih.gov/rest/pug/" + args.type + "/" if args.type == "assa...
7b8ce356412ceac1a0e81c760d37bd628eb4aff5b1bcae017b06ed172f2e74b0
Python
2,259
76
"""``run(inputs=)`` on a fork carrying value-edits discloses their inertness. D1 (2026-08-19): ``fork.do(sel, edit)`` then ``fork.run(inputs=new_x)`` is COHERENT -- a do() edit rewrites saved values (path 1), while a new-input run is a fresh execution (path 2) -- but the un-edited VERIFIED result tripped a real user f...
835f819f709d8ad5a4358b1a263c42404278d7c4b210ee9c1b77bb488d879fb5
Python
2,259
59
""" 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...
a0bd9e069e22ba0d95cc80259092df679712739c4b47c106ef82fb2207702f9c
Python
2,259
104
import numpy as np from neuron import gui, h from neuron.units import ms def simulate(): nseg = 100 s0 = h.Section() s0.nseg = nseg s0.L = 300000 s0.insert("hodhux") ic = h.IClamp(s0(0.001)) ic.delay = 0 ic.dur = 1e9 ic.amp = 1000 s1 = h.Section() s1.nseg = nseg s1.L...
c5617c6895ec64b5ee5d60b4241ab13c5b20f9972f13d93f4b39af131ad2701b
Python
2,259
66
from pl_bolts.utils import _PIL_AVAILABLE, _TORCHVISION_AVAILABLE, _TORCHVISION_LESS_THAN_0_9_1 from pl_bolts.utils.warnings import warn_missing_pkg if _TORCHVISION_AVAILABLE: from torchvision.datasets import MNIST else: # pragma: no cover warn_missing_pkg("torchvision") MNIST = object if _PIL_AVAILABLE:...
229007eba0381237c7c698efcb4556a68e1402cb624891e715b674345176e03a
Python
2,260
69
#!/usr/bin/env python3 import argparse import pandas as pd from rdkit import Chem def sdf_to_tab(vars): mols = Chem.SDMolSupplier(vars.inp, sanitize=False) df = pd.DataFrame() # for output for n in range(len(mols)): if mols[n]: d = mols[n].GetPropsAsDict() # filter dict ...
5f4535935b8d2337ef529a25fa5a346fddcc9fb337e1f9869ca439e089bef2e3
Python
2,260
79
from colorsys import hsv_to_rgb import numpy as np import matplotlib.pyplot as plt def plot_text(x, ys, text, align, name): for i in range(ys.shape[0]): plt.text(x, ys[i], text[i], ha=align, va="center") plt.text(x, 1 + ys.shape[0], name, ha=align, va="center") def color(name, names): names = s...
61498698bc31402df6ee9f4d133b0c7092314dca21ff20d444a1c01d8226d8b1
Python
2,261
65
"""Code around assigning implicit list identifiers for collections.""" import os.path from urllib.parse import urlparse from pydantic import BaseModel class FillIdentifiers(BaseModel): fill_inner_list_identifiers: bool = False deduplication_pattern: str = "_{#}" deduplication_index_from: int = 1 def f...
4c1f433194ba2d907e822f6c21fc604381a16153afb32444ccebf2ed744c124c
Python
2,263
64
import pytest import torch from pytest_mock import MockerFixture from torch import distributed as dist from lightly.loss.tico_loss import TiCoLoss class TestTiCoLoss: def test__gather_distributed(self, mocker: MockerFixture) -> None: mock_is_available = mocker.patch.object(dist, "is_available", return_va...
bc255f09b47ff3f3ab815265597e036fd64fa290e325582fd66794e8a66499b4
Python
2,263
83
from typing import ( Any, Dict, Hashable, Iterable, Literal, List, Mapping, MutableMapping, Optional, Tuple, Union, cast, ) import pandas as pd import xarray as xr def concat_sdatas( sdatas: Iterable[xr.Dataset], keys: Optional[List] = None, ) -> xr.Dataset: ...
663ecb624000e09ba43c5b53ebf1cde037f7111753f106e95b398755e9511657
Python
2,264
60
import numpy as np import scipy.interpolate as ip def locextr(v, x=None, refine = True, output='full', sort_values = True, **kwargs): "Finds local extrema " if x is None: x = np.arange(len(v)) tck = ip.splrep(x,v, **kwargs) # spline representation if refine: ...
809ebbb7f60c6d61af25ade459aaa15b5e56c33a4c374de5be562557fa835ab1
Python
2,267
79
import unittest from numpy import log, mean from spitfire.time.methods import * from spitfire.time.nonlinear import * from spitfire import odesolve def direct_solve(fun): def append_iteration_count_of_one_and_converged(x, *args, **kwargs): output = fun(x, *args, **kwargs) return output, 1, True ...
8bbed619b84eda6279decbe317c4e6c7da79a1e91ab637fd02917f04a1a69edf
Python
2,267
83
"""Tests for the public ``tl.sweep`` convenience constructor.""" from __future__ import annotations import torch from torch import nn import torchlens as tl class _ReluModel(nn.Module): """Small model with a sweepable ReLU site.""" def forward(self, x: torch.Tensor) -> torch.Tensor: """Run a simpl...
06cc2e1cf99ad310b1af881592b91f3dd31a216ea0c3aca509de4c4ec7a8eedc
Python
2,268
66
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """tests for values.py""" import unittest import numpy as np from sknetwork.utils.values import get_values, stack_values, values2prob class TestValues(unittest.TestCase): def test_get_values(self): n = 10 labels_array = -np.ones(n) labels_...
7458d783778b07c1bb1cbb91cc52baaa9aeaec12428b8945211149cc03e8a6f3
Python
2,268
77
import pytest import rpy2.rinterface as rinterface try: import numpy has_numpy = True except ImportError: has_numpy = False rinterface.initr() def floatEqual(x, y, epsilon=0.00000001): return abs(x - y) < epsilon @pytest.mark.skipif(not has_numpy, reason='Package numpy is not installed.') def test...
0bed617ea9cca24d9d1bc1b88f1bd5652d4e56806b0d29403df2eafb6cfe8614
Python
2,269
59
from unittest.mock import Mock, patch from celery.apps.beat import Beat class test_Beat_remote_control: """The remote-control knobs must survive the trip to the scheduler. ``Beat.__init__`` swallows unknown keyword arguments, so a flag that isn't threaded through explicitly is silently dropped rather th...
eeeaf5aa7f39ac49c5dbe7f9943e5dfd80ac7a866416fd527d1015633cbdc26d
Python
2,269
57
"""Regression guard: a default-outpath draw() call must never write into the repo root. xdist race (nightly fast tier, 2026-10-03): ``Trace.draw(vis_save_only=True)`` with no explicit ``vis_outpath=`` resolves the literal default basename (``"modelgraph"``) against the process's current working directory. Several xdis...
4e5c399367f5df26a9e3bb71b4583d8c07977bcea9abbfcc7dd5c1ef77e01742
Python
2,270
76
"""Neutral machine identity for recorded benchmark artifacts. Benchmark records are committed to a public repository, so they name the machine with a neutral label instead of its hostname. Comparisons that need hardware context read ``cpu_model`` and ``cpu_count``, which the writers record separately. Absolute checkou...
5bc55f8558d656253d5027814d0a079d031153ef69cdce28574e4d184fc4c7f8
Python
2,270
52
#! /usr/bin/env python import argparse import sys import os import pandas as pd #import subprocess def create_sample_participant_lookup(data_dir): sampleDS_fp = os.path.join(data_dir, 'GTEx_Analysis_v8_Annotations_SampleAttributesDS.txt') subjectDS_fp = os.path.join(data_dir, ...
6e0097e5c254ed228edd9717a01b6971d3f5dfe1e603b4ab80ae5dec3983b9ef
Python
2,270
66
from __future__ import annotations from pathlib import Path import pytest from larvaworld.portal import notebook_workspace from larvaworld.portal.workspace import ( WorkspaceError, initialize_workspace, set_active_workspace_path, ) @pytest.fixture(autouse=True) def workspace_config_dir(tmp_path: Path, ...
9d80e1262cedfea5d072677a471587fd5d4c2e74b7b3241866fe1ce7fb9c7bd2
Python
2,270
81
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["splicepoint_model_spec"] = dict( type="BothLSSIModels", acceptor="model/splicepoint-model-acceptor-1", donor="model/splicepoint-model-donor-1", ) msp.architecture["motif_model_spec"]["motif_...
dadbe38b767a8f442ac7acdabf8f37b4774c43301b12d62aebf6e862d96729a5
Python
2,270
86
import os import sys os.environ["STARDIST_NAPARI_DEBUG"] = "1" import napari import numpy as np from csbdeep.utils import normalize from stardist.data import test_image_nuclei_2d, test_image_nuclei_3d from stardist.models import StarDist2D, StarDist3D from stardist_napari._dock_widget import surface_from_polys def...