sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
eab1873d684a60e23253374cb0d587f750cfe9bdd60e4c91222963af666d4db4
Python
811
27
from numpy.testing import assert_array_almost_equal def assert_array_almost_equal_up_to_sign(actual, desired, decimal=6, err_msg='', verbose=True): """Like numpy.test.assert_array_almost_equal, but modified to allow objects to have different signs """ msg = '' try: assert_...
4f3c807786ef83b2d5a853f5dae0ad09d25cadd846dda543649124a62a61460f
Python
812
43
import autograd.numpy as _np from autograd.numpy import ( array, eye, zeros, ) atol = 1e-8 rtol = 1e-5 def is_array(x): return type(x) is _np.ndarray def to_ndarray(x, to_ndim, axis=0, dtype=None): x = _np.asarray(x, dtype=dtype) if x.ndim > to_ndim: raise ValueError("The ndim cann...
2036338f4941da50dce3b08563e93d246f15bca303499566bf5f76973a1e6cb0
Python
813
24
from __future__ import absolute_import import numpy as np from numpy.testing import assert_allclose from nose.tools import assert_equal, assert_true, assert_raises, raises import pycircstat def test_clustering(): x = np.asarray([6.10599459, 0.14824723, 3.11272268, 3.45703846, 5.88211171, 3.53760218, ...
8439d06122a12d7256aac8f6081355d308123a5df4cec1a3a4f719c7fed67a5d
Python
813
22
import torch.nn as nn from reinvent.models.transformer.core.network.encode_decode.clones import clones from reinvent.models.transformer.core.network.encode_decode.sublayer_connection import ( SublayerConnection, ) class EncoderLayer(nn.Module): "Encoder is made up of self-attn and feed forward (defined below...
de8df383d97aa12bb0e52b19cd1d734d12e7e18b406dbab3e4491f960b1abc7a
Python
813
28
import pytest from corgie.cli.vote import compute_softmin_temp @pytest.mark.parametrize( "dist, weight, size, result", [ (0, 0.4, 1, 0), (0, 0.6, 1, 0), (8, 0.99, 3, 8./6.), # SEAMLeSS params with MIP0 fields (1, 0.99, 3, 1./6.), # adapting SEAMLeSS params for mipless fields ...
f591b76664e77a902b50fd69818576a901ff7ee1f4b40c850aed375903262991
Python
813
25
import random from geomstats.geometry.poincare_polydisk import PoincarePolydisk from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test_cases.geometry.nfold_manifold import ( NFoldManifoldTestCase, NFoldMetricTestCase, ) from .data.poincare_polydisk import ( PoincarePolydiskMetr...
18602725c1c2080aa819cc0eb0540589f54f454d9e271a581c712123d52a6056
Python
814
29
"""Shared runtime schema types for SanPy detection and analysis results.""" from enum import StrEnum class DetectionParameterCategory(StrEnum): """Categories used to organize detection parameters for presentation.""" PRESETS = "presets" DETECTION = "detection" WINDOWS = "windows" WAVEFORM = "wav...
204e67a67625bedbe3222ab07bbd188ab823700a0b2aa68557a620b18b7a992e
Python
814
31
"""Synthetic accessibility score Synthetic Accessibility Score of Drug-like Molecules from P. Ertl & A. Schuffenhauer, J Cheminformatics 1:8 (2009) Larger SA score = more difficult to synthesize """ from __future__ import annotations __all__ = ["SAScore"] from typing import List import numpy as np from .sascorer ...
7fff038da0ff0a1d9ea687737f5bb4882e82ecd36d287598efd0cbadea62753f
Python
814
23
from PymoNNto.Exploration.StorageManager.StorageManager import * import numpy as np #convenience functions: #add root project folder to import path add_project_root_path() #print numpy arrays with commas for easier copy paste #np.set_string_function(lambda x: repr(x), repr=False) from PymoNNto.NetworkCore.Network i...
a74f363408daa6c156dfcbbfb243d71786ec64086b68fad21b776989a8ae4594
Python
815
24
from PymoNNto import * class CreateWeights(Behavior): def initialize(self, synapses): distribution = self.parameter('distribution', 'uniform(0.0,1.0)') # ones density = self.parameter('density', 1.0) synapses.W = synapses.matrix(distribution, density=density) * synapses.enabled ...
f5c776c54d897b75e20da7c1a8ce311dce80e7139137bcb17b653c23b8124054
Python
815
26
import collections from pathlib import Path, PosixPath, WindowsPath from typing import Any, OrderedDict from ruamel.yaml import YAML, Dumper def get_yaml_io(): """Return yaml loader/dumper configured for snakebids.""" yaml = YAML() # Represent any PathLikes as str. def path2str(dumper: Dumper, data:...
ff6e3364a5d8632fb002d9479f0e9d221dcc7c2837434e2f5460ec95e25363f8
Python
816
23
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. # Separate version utilities to avoid circular imports with __init__.py import importlib.metadata from typing import Optional _ALL_PKGS = importlib.metadata.packages_distributions() def get_version_s...
0d05f119094029b3532224bd4df8d5a2f877e16f7567347fa7124ec1e3a91baa
Python
817
28
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. from .type_mapper import ChemicalSpeciesToAtomTypeMapper from .dataset import DatasetIndexTransform from .neighborlist import ( NeighborListPruneTransform, NeighborListTransform, SortedNeigh...
24bf3a94e7a540830f40375292d9a374eec112306dd00fef43b3977208e9495c
Python
817
29
from video_stream import ImageObserver import numpy as np class HistogramObserver(ImageObserver): """ An observer that calculates the image histogram for each frame and stores it in the observer output. """ default_params = { **ImageObserver.default_params, "bin_count": 255, } ...
b1f0aacdf2fdbcec9debf8aa50a3e3968bafb2c10ad33b9335822585570c3875
Python
817
26
import numpy as np def allclose_sign(a, b): """True is all values are close, up to the same sign for all values.""" return np.allclose(a, b) or np.allclose(a, -b) def allclose_trajs(trajs1, trajs2): """Check that all values of the trajectories are close.""" trajs1 = np.concatenate(trajs1, axis=0) ...
1a06cdf984ddcb36d11d3ac7ab974f24229f8890e7a692d644fcd0902eb34b93
Python
818
33
import torch from .collate import time_aware_collate class DataLoader(torch.utils.data.DataLoader): def __init__( self, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0, collate_fn=time_aware_collate, pin...
921bd2121ba7e66255ddac24eeaecc199fc2c2142bc15c72869325191087fa07
Python
818
20
from reinvent.chemistry.standardization.filter_types_enum import FilterTypesEnum from tests.chemistry.fixtures.test_data import CELECOXIB, BENZENE from tests.chemistry.standardization.base_rdkit_standardizer import BaseRDKitStandardizer class TestRDKitStandardizer(BaseRDKitStandardizer): def setUp(self): ...
d6f3b8c4e81e066ea120d4da92ab23bc0645344772905991bee548f958704a50
Python
818
29
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from torch import nn, Tensor from torch.nn import functional as F from typing import Optional, Tuple from . import register_act_fn @register_act_fn(name="hard_sigmoid") class Hardsigmoid(nn.Hardsigmoid): """ ...
2c2b7e855766414975467f037ad93ccc42b52170e7a276a4d588e9192cd0ce79
Python
819
38
# -*- coding: utf-8 -*- def input_yes_no(default='y'): """ Demand user input y[es] or n[o]. The user is asked repeatedly, until the input is valid. Parameters ---------- default : {``'y'``, ``'n'``}, optional The output if the user enters empty input. Returns ------- inp...
21e8cec2d6a7fad94efc78eac0a0dcdbecf1a2c55dbe25588622dd843904d6b8
Python
820
24
# Generated by Django 4.1.1 on 2022-10-04 10:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('celsus', '0003_remove_author_project'), ] operations = [ migrations.AlterField( model_name='dif...
a4c678938ec1de1573aa4c39d3fff4facb518671b6d0f9a1b753458fdf3c1a4a
Python
820
30
import os from torch.utils import data from torchvision import datasets from torch.utils.data import Dataset import torch import numpy as np def npy_loader(path): sample = torch.from_numpy(np.load(path)) return sample class my_Dataset(Dataset): # Characterizes a dataset for PyTorch def __init__(self, ...
de36da5a1de5b87881311a1ab01028a47803d4e2a851f9858b77642cfbdf4e65
Python
820
27
"""Stacking data objects of one class into a single object.""" def concatenate(data): """Concatenate a list of `BrainData` or `Adjacency` objects. Args: data (list[BrainData] | list[Adjacency]): Objects to concatenate; all must be of the same class. Returns: BrainData | Adjac...
112cdf84abb8a2b43d4eadb1d4910a6582d39971e7b435f7bb6268fe8497c6fb
Python
821
23
import pytest from nltools.data import BrainData from nltools.data.braindata.utils import _check_brain_data def test_check_brain_data_from_list_of_paths(sim_brain_data, tmpdir): """List of file paths is now accepted.""" p1 = str(tmpdir.join("a.nii.gz")) p2 = str(tmpdir.join("b.nii.gz")) sim_brain_dat...
647cc86815bd7066e46b2419dd2a5c7b1810080ef206896a737a903b88bbfe56
Python
821
35
import itertools as it from typing import Iterable, Sequence, TypeVar import more_itertools as itx T = TypeVar("T") def unpack(iterable: Iterable[T], default: Sequence[T]) -> Iterable[T]: """Return default if iterable has no elements Allows safe unpacking of possibly empty iterables Parameters ---...
19e4aed6692edda7a379eea6d51eda5eca1c41a43f514473ef7acc491283d0eb
Python
822
25
from tqdm import tqdm from data.dataset import BratsTest from matplotlib import pyplot as plt from data.utils import plot_img_and_target dataset = BratsTest(None, None, None) dataset.return_name = True image_save_folder = dataset.root.parent / 'plots' image_save_folder.mkdir() fig_handle = plt.figure(figsize=(19.20...
f5d191e4896cc82482b780e5b44e2f94362b37716c9bd014f7f0ede95ce37065
Python
822
37
""" Exponential decay, or exp(-x). For values x < 0, the output is 1.0 ("rectified" of "clamped" exponential decay). """ __all__ = ["ExponentialDecay"] from dataclasses import dataclass import numpy as np from .transform import Transform @dataclass class Parameters: type: str k: float def expdecay(x, k=...
06eb945153a945f34f831af5aee65bc9c583cbde0038f84bab83a69ee348fa02
Python
827
33
# Based on solution at https://gist.github.com/jaradc/eeddf20932c0347928d0da5a09298147 import numpy as np from numpy import unique, multiply from scipy.stats import entropy def getEntropy(series, base = 2, nBits = None): """Obtain Shannon Entropy estimate from a vector values/time series. Args: serie...
540be6f151c62437ec62fc4eefac8ed752e20dffbfd985fabfe4c47bc8bb9554
Python
827
27
# Generated by Django 4.1.1 on 2022-11-10 11:26 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('celsus', '0024_alter_differentialsamplecolumn_column_type'), ] operations = [ migrations.CreateModel( ...
c6ea751d3bd9d370101771ea08c960870a567f96897b54b22caa307850d7527e
Python
827
25
import os import config def seed_from_name(name): return int(name.name.split('_')[0][4:]) root = config.datasets / 'BRATS_stylegan_313subjects_noaugmentation_singlesegmentationchannel' / 'out' all_images = dict() all_seeds = dict() for image_folder in ('T1', 'T1CE', 'T2', 'FLAIR', 'SEG'): modality_folder =...
babaf8c51c897208fe9fac43f214041401947612bc11dbb4d4894242e4ba360c
Python
829
25
# Copyright (c) 2021 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 appli...
964157b136de6efc325088a82bf5141bc31c5d28850b0562bb3e1880823a1ba2
Python
830
35
import unittest import h5py import os from deeprank_gnn.Graph import Graph CWD = os.path.dirname(os.path.realpath(__file__)) class TestGraph(unittest.TestCase): def setUp(self): self.graph = Graph() self.graph.h52nx(f'{CWD}/data/hdf5/1ATN_residue.hdf5', '1ATN_1w') self.graph.pdb = f'{CW...
0df7da65e6b3c3a2397d21b1729596c8992aa2bec63ca8d386d2fee992cc0dfd
Python
832
25
#!/usr/bin/env python3 import unittest import numpy as np import odil class TestIO(unittest.TestCase): def test_raw_xmf(self): name = "foo" xmfpath = "data.xdmf2" nx, ny, nz = 3, 4, 5 lx, ly, lz = 4, 5, 6 for dtype in [np.float32, np.float64]: u_src = np.lins...
3a2b0a74db4f2a74fc91cdfa3c9e03d8cf57f30db7578f85ef9c6335a05a20be
Python
832
25
"""Typed state shared by the SanPy analysis window and interactive plugins.""" from __future__ import annotations from dataclasses import dataclass @dataclass(frozen=True) class WindowState: """Describe the recording, sweep, and spikes selected in one window. Attributes: file_key: Normalized path r...
78a8921c59664dbf8c9dced920a10c17edb1b8a72e5602e823337ad4562d91cd
Python
832
24
import nibabel as nib from nibabel.processing import resample_to_output from skimage.measure import marching_cubes def nifti_to_glb(path, output="prediction.obj"): # load NIFTI into numpy array image = nib.load(path) resampled = resample_to_output(image, [1, 1, 1], order=1) data = resampled.g...
f299ee1c24548604d4ae4c33bab532d3e26958c33aa3dcfd9d580d79e503bd6b
Python
832
25
from dig.threedgraph.evaluation import ThreeDEvaluator import numpy as np import torch import math def test_ThreeDEvaluator(): input_dict = {'y_true':np.array([1.0, -0.5]), 'y_pred':np.array([0.6, 0.0])} evaluator = ThreeDEvaluator() result = evaluator.eval(input_dict) assert len(result) == 1 asse...
4392af7867f19abce449d387522bbcdf0a1d394f37e9cef36417a2e2ce25886a
Python
833
25
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. from .softadapt import SoftAdapt from .loss_coeff_scheduler import ( LossCoefficientScheduler, LinearLossCoefficientScheduler, ) from .loss_coeff_monitor import LossCoefficientMonitor from .writ...
29de7996e1145972b583f804f5eb5f4d75d4ba0f22d6845e1a0047d07dc6aad2
Python
834
30
""" ASGI config for celsusdjango project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ """ import os from channels.auth import AuthMiddlewareStack from channels.routing import Protoc...
07e2ef24da3ad987f464a4d0ad259ce9a9e0d970483c9f28f0abb329cdb7d33f
Python
835
27
from numba import jit from fimpy.roi_extraction.corr_algorithms import _update_labels from split_dataset import Blocks import numpy as np from itertools import product def merge_rois(blocks: Blocks, block_arrays: np.ndarray): """Merges rois extracted from different dataset blocks with padding :param blocks: ...
1e3af90e3df6f43bfae0443d83b5bd1e719dbfa3331ee7e209694a6288e47f05
Python
835
27
import setuptools with open(r'README.md', mode=r'r') as readme_handle: long_description = readme_handle.read() setuptools.setup( name=r'hyper-dti', version=r'1.0.0', author=r'Emma Svensson', author_email=r'svensson@ml.jku.at', url=r'https://github.com/ml-jku/hyper-dti', description=r'Robus...
462db7e6644037b0e182c83caf7c22bfa4bf66e748f5a61754b907bcf00d03e5
Python
836
24
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. from ._base_datamodule import NequIPDataModule from ._ase_datamodule import ASEDataModule from .sgdml_datamodule import sGDML_CCSD_DataModule from ._3bpa_datamodule import NequIP3BPADataModule from .tm2...
f70c7d1b71b8c1cedae4792114e7c58cbe3af5d6d3ab8dcb3bf246eeb1adfd09
Python
837
24
from PymoNNto.NetworkCore.Behavior import * class STDP(Behavior): def initialize(self, neurons): self.stdp_factor = self.parameter('stdp_factor', 0.0015, neurons) self.syn_type = self.parameter('syn_type', 'GLUTAMATE', neurons) neurons.spike_old = neurons.vector() def iteration(self, ...
312d063df7e1af953db108c152626808e602d0bec8e1bc038582822f1705cc3d
Python
839
29
from numpy import corrcoef import dynfc as dyn def cc(series, size, k = 1): """Run cofluctuation analysis for BOLD signal. Args: series (double): BOLD signal array for all parcels/voxels in the format [N, Tmax]. size (int): Size of window. k (int, optional): Standard value k = 1. ...
8b7d58a2ce69d135b84fb77618315df519982a022905e18a7445c3818cf394d5
Python
840
42
from sleepy.gui.builder import Builder from PyQt5.QtWidgets import QWidget from sleepy.processing.parameter import ParameterBase import pdb class Processor: def render(self): self.buildTree = ParameterBase.getBuildTree(self) Builder.setAttributesFromJSON(self.buildTree, self, leve...
6bfe6187df6b53adc33fc2dc1126704f634b743a08cf29248ce165375750974b
Python
841
26
import numpy as np from sklearn.decomposition import PCA if __name__ == '__main__': data_path = 'PROJECT_DIR/results/restfmri/dnn/sFC/' fname = data_path + 'sFC_HCP_Session1.npz' data = np.load(fname) data_features = data['features'] labels = data['labels'] pca = PCA() feature_pcs = pca....
8ad879b1dc6a6835978598c58fafc4c544a740e736f6f5abb47be557e0d860df
Python
841
28
from geomstats.geometry.euclidean import Euclidean, EuclideanMetric from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test_cases.geometry.scalar_product_metric import ( CustomizationTestCase, InstantiationTestCase, WrapperTestCase, ) from .data.scalar_product_metric import ( ...
6dd91dc861e01a34b26825b82947e895af9b3043b332a2e7327be7b12d9cd91b
Python
842
46
#!/usr/bin/env python # Takes a snp file and formats it for WASP, splitting it into one file per scaffold/chromosome # Usage: python3 splitScaffolds.py inFile import os import sys # Read arguments inFile = sys.argv[1] # Create output file outFileSuffix = ".snps.txt" prevChrom = "" outFile = "temp.txt" outFile = ...
0ed29393a4ab8de49d0fa1ec1b44241989c4601080ce5bfa5eb4ec9381460fdd
Python
843
27
import sanpy from sanpy.interface.plugins import basePlotTool from sanpy.sanpyLogger import get_logger logger = get_logger(__name__) class plotTool(basePlotTool): """Plot tool for one bAnalysis. """ myHumanName = "Plot Tool" def __init__(self, **kwargs): super().__init__(**kwargs) ...
d86d90d3586dc88271f45bf0d7d5ba5485796ff0b0c41dc18db11b5ffc6c0b14
Python
843
21
import pytest import unittest from reinvent.models import LinkinventTransformerAdapter, SampledSequencesDTO from tests.models.unit_tests.linkinvent.transformer.fixtures import mocked_linkinvent_model from tests.test_data import ETHANE, HEXANE, PROPANE, BUTANE @pytest.mark.usefixtures("device") class TestLinkInventLi...
1caaa159b4de65279f8f94ffe266e63e7f94c8524ca20015824c8ce38c140bbc
Python
844
28
NAV1P1 = "Nav1.1" KV32 = "Kv3.2" # labels CURRENT_LABEL = "Current (nA)" VOLTAGE_MV_LABEL = "Voltage (mV)" DISTANCE_LABEL = "Distance from soma (μm)" INSTA_FR_LABEL = "Instantaneous firing rate (Hz)" FIRING_RATE_LABEL = "Firing rate (Hz)" MAX_PROP_LABEL = "Max propagation distance (μm)" KVMUT_FRAC_LABEL = f"{KV32} mut...
6b6c60d136dc000c03c886a034fb1b12d1fd6f8df25185026b65d1f5510d7c67
Python
844
24
import torch from dig.sslgraph.method.contrastive.objectives import NCE_loss, JSE_loss def test_nce_more_view(): zs_1 = torch.randn((32, 32)) zs_n_1 = torch.randn((32, 32)) zs_2 = torch.randn((32, 32)) zs_n_2 = torch.randn((32, 32)) zs_3 = torch.randn((32, 32)) zs_n_3 = torch.randn((32, 32)) ...
ac089731e24337619ac2478f36df738f65dcd328a091da173b8a1524b86a404c
Python
845
25
# Copyright (c) 2021 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 appli...
af68f702df9846335ca17e6496dbc5a2f28ba05165d9c9f7e529d3e59b460375
Python
845
37
import NALSM_GEN_SUPPORT as sup import numpy as np import os SAVE_VER_INP = input('VERSION? [int]: ') SAVE_VER = int(SAVE_VER_INP) VER = SAVE_VER main_Path = os.getcwd() data_path = main_Path + '/train_data/ver_' + str(SAVE_VER) net_path = main_Path + '/networks' for file in os.listdir(data_path): ...
07f279cb5136b5332183f9e2b9514608fdb3e3c79299eaebeb9ef4136b7425e8
Python
847
34
import re import pytest from reinvent.scoring.utils import suppress_output, camel_to_snake def test_suppress_output_does_not_raise(): with suppress_output(): print("stdout suppressed") import sys print("stderr suppressed", file=sys.stderr) def test_suppress_output_yields_streams(): ...
c815da6045c9770d0919616e5671a8fb03fef08f5dd7fd3cd3665537ebced339
Python
848
29
import numpy as np from data.dataset import Brats184, Brats313 brats184 = Brats184(None, None, None) brats313 = Brats313(None, None, None) subjects184 = brats184.get_available_subjects() subjects313 = brats313.get_available_subjects() if len(set(subjects184).intersection(set(subjects313))) == len(subjects184): p...
d8faa8d1853915b1aff3e17bff842261432a665501ff77816e2eae1a89fb839d
Python
849
25
from PymoNNto.NetworkCore.Behavior import * import numpy as np from sympy import symbols from sympy.physics.units import * class Clock(Behavior): def initialize(self, neuron_or_network): self.add_tag('Clock') #convert_to(seconds / tau, seconds) neuron_or_network.clock_step_size = float(...
982b2de30aec17c2cd7c351242add5c46831a452215f4935ce53467c5979154c
Python
850
35
# usr/bin/env python # Filter SNP lists for SNps that we want to keep # usage python SNPfilter.py infile keep_list outfile import sys infile, keep, outfile = sys.argv[1:] snp_dict = {} print("Reading SNPs...") with open(infile, 'r') as infile: for line in infile: chrom, pos0, pos1, snp = line.strip().s...
f1ffa3004bdd358c5023b1e0bc3d96b031ddead079eef2840ad3f30d4a408675
Python
852
26
import base64 import os import numpy as np from typing import TYPE_CHECKING DEFAULT_CHROMA_EMBED_URL = "https://embed.trychroma.com" def get_chroma_embed_url() -> str: """Return embed base URL from CHROMA_EMBED_URL or default without trailing slash.""" return (os.environ.get("CHROMA_EMBED_URL") or DEFAULT_CH...
75d663b555aeed9c58bc109d34b5a7ab2d59a8869e61d8e6aa722a971cd5bfe2
Python
853
24
# Generated by Django 4.1.1 on 2022-12-02 11:30 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('celsus', '0036_genenamemap_primary_uniprot_record'), ] operations = [ migratio...
960873acaee6d91158e4d18e95d0ff2bcde8fba261900d5eb4f8718581a1f436
Python
853
36
#!/usr/bin/env python3 """ Visualize LSL stream on the network. The signal is visualizd in real time with spectral filtering, common average filtering option and real-time FFT. Command-line arguments: #1 Stream name Example: python nd_stream_viewer.py python nd_stream_viewer.py StreamPlayer If the scrip...
7cace5e671992cb1442f8d9f3ec3c5d038624ed47098a77e0932b105b2b697cf
Python
854
47
from brian2 import * import time from globparams import * set_device('cpp_standalone') defaultclock.dt = 1*ms prefs.core.default_float_dtype = float32 prefs.codegen.target = 'cython' eqs_neurons = ''' dv/dt = (ge + rand() - v*OM_DECAY) / (1*ms) : 1 dge/dt = -ge / (1*ms) : 1 dspiked/dt = -spiked / (1*ms)...
97b6d609938fd3bc55b0c13910f9c7579ebc34a3aafca38caa0d754c3b0fe807
Python
855
24
import config model_save_folder = config.models model_save_folder = config.models for path_object in model_save_folder.rglob('*'): if path_object.is_file() and path_object.suffix == '.ckpt': experiment_name = path_object.parts[-5] if 'fullrandomsplit' in experiment_name or \ ('Bra...
450e71573259496788aaacb8ee934011db6860b7486ec2bcc27398d16fafff07
Python
856
26
"""The one validation check the nltools estimators share. `_Glm` and `_Ridge` are independent estimators with different input contracts, so they share this small private function instead of a common base class. """ from __future__ import annotations from sklearn.exceptions import NotFittedError def _check_is_fitte...
735165674c402979fb54cd52d016c49eea8e959f93f7a9ce11479c07feda8d07
Python
856
28
""" This code executes preprocessing for all combination of databases, needed to reproduce results of generalization section. """ import logging import subprocess as sp datasets_o = ['DrugBank', 'BIOSNAP', 'BindingDB', 'Davis', 'E', 'GPCR', 'IC', 'NR'] datasets = datasets_o for database1 in datasets_o: for ...
8bcd655fce2fccc91c995cf9b6d8b59c015d9b4ea66dae0169f995f1f448e86a
Python
856
17
""" -------------------------------------------------------------------------------- Date: 05/08/2022 @author: Nikolaos Vardalakis -------------------------------------------------------------------------------- Implementation Notes -------------------------------------------------------------------------------- ...
bad0b132599c7ca38fcdd20b27fa55eef50769eafd2d17c21072245ab14203db
Python
856
38
import numpy as _np import torch as _torch atol = 1e-6 rtol = 1e-5 def from_numpy(x): if _torch.is_tensor(x): return x return _torch.from_numpy(x) def array(val, dtype=None): if _torch.is_tensor(val): if dtype is None or val.dtype == dtype: return val.clone() return...
696f49e32048fe9da2e873aae3bb65f0e07a051e1d9c928aa851199c8839910c
Python
857
37
import sys from navec.vocab import Vocab from ..glove import ( Glove, parse_glove_vocab, format_glove_vocab, trans_glove_vocab ) from ..quantiles import get_quantiles def vocab_count(args): glove = Glove.from_env() glove.vocab(sys.stdin.buffer, sys.stdout.buffer) def vocab_quantile(args):...
100d5f0e333b84fb38368fa440c9601cd6e04ef68ace8ffe504c8f6bcd79d2e4
Python
859
34
"""Config Validation""" from typing import Optional from reinvent.validation import GlobalConfig, Field class SectionParameters(GlobalConfig): model_file: str num_smiles: int smiles_file: Optional[str] = None target_smiles_path: str = "" sample_strategy: Optional[str] = "multinomial" # Mol2Nol ...
8337be428bb920fb8a54b40a16b9ca560dc1a0515ec5c90352f8276a47f0dc95
Python
859
26
"""Segmenting small-scale Chinese language corpora""" import argparse import jieba from tqdm import tqdm def segment_text(input_file, output_file): with open(input_file, 'r', encoding='utf-8') as f: text = f.read() words = jieba.cut(text) segmented_text = ' '.join(words) with open(output_fil...
0021464a2707f55ecfe5dcee85fc4c4a7a422d979086b32b81e8b411ff415631
Python
860
30
""" Merge pandas DataFrames based on the values of selected columns. """ import argparse import pandas as pd from copy import deepcopy CLI = argparse.ArgumentParser() CLI.add_argument("--output", nargs='?', type=str) CLI.add_argument("--data", nargs='+', type=str) CLI.add_argument("--output_img",nargs='?', ty...
068e030a5f3e5c76a53343ca209a4aedc2f4953239563aef55e6d1c2b42e17c9
Python
861
31
"""Global Config Validation""" from typing import Optional from pydantic import BaseModel, ConfigDict, Field class GlobalConfig(BaseModel): model_config = ConfigDict(extra="forbid", protected_namespaces=()) class ReinventConfig(GlobalConfig): run_type: str device: str = "cpu" tb_logdir: Optional[s...
1dd7c089dba5962169b5febfea1a6807f4e445f9b21f4940026dafba228429c2
Python
861
28
""" This code executes preprocessing for all combination of databases, needed to reproduce results of generalization section. """ import logging import subprocess as sp datasets_o = ['DrugBank', 'BIOSNAP', 'BindingDB', 'Davis', 'E', 'GPCR', 'IC', 'NR'] datasets = datasets_o for database1 in datasets_o: for ...
70cd49852ecc2bc00a4d9134d628619f4e084dd4a12993a9dd0ce2fa65d039c5
Python
862
27
"""Shared Matplotlib helpers for SanPy Qt widgets.""" from matplotlib.backends import backend_qtagg from qtpy import QtCore, QtWidgets def _make_navigation_toolbar( canvas: backend_qtagg.FigureCanvasQTAgg, parent: QtWidgets.QWidget, ) -> backend_qtagg.NavigationToolbar2QT: """Create a compact Matplotlib ...
b70717a456871c83d0f4ef6459f2e4ff7500b49e7ad493d3f7bb090f62e5a645
Python
862
30
# Generated by Django 4.1.1 on 2022-10-02 16:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('celsus', '0001_initial'), ] operations = [ migrations.CreateModel( name='ExperimentType', fields=[ (...
2dd6f8de4c2724b422df9e2e16aa9301d7485d0a4aa8da74fb93e5828f153b76
Python
863
24
from dig.oodgraph import GOODCBAS, GOODCMNIST, GOODCora, GOODHIV, GOODMotif, GOODPCBA, GOODZINC, GOODArxiv import pytest import shutil dataset_domain = { 'GOODHIV': ['scaffold', 'size'], 'GOODPCBA': ['scaffold', 'size'], 'GOODZINC': ['scaffold', 'size'], 'GOODCMNIST': ['color'], 'GOODMotif': ['basi...
2e27487409e20118384b937c19fa8f22381d76dd9e35bb009f247fbe61c56e0b
Python
864
27
# Generated by Django 4.1.1 on 2022-10-18 15:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('celsus', '0008_remove_differentialsamplecolumn_comparison_name_and_more'), ] operations = [ migrations.Remo...
ec78acaf242a8ea268e2e6386231f7ed36b33353d9e3ae50c354ac922b2cb715
Python
864
32
import logging from geomstats.geometry.discrete_curves import ElasticMetric, SRVMetric from geomstats.geometry.euclidean import EuclideanMetric from geomstats.metric_geometry.graph_space import GraphSpace from geomstats.metric_geometry.point_set import PointSetMetric ELASTIC_METRICS = (SRVMetric, ElasticMetric) def...
f4f155244a9bf2330a3dff72db3c5e954f19ede8ba4b4638dd524bd61e4a6df2
Python
867
28
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. from .modules import find_first_of_type from .dtype import ( dtype_to_name, dtype_from_name, torch_default_dtype, floating_point_tolerance, ) from .file_utils import download_url, extrac...
0bb9c912bb8fc21f6aca4a0ef068f3ea250306ddf6a28643649aa0e7bc1e2215
Python
868
24
import experiment as exp import video_system as vid class SimpleObserver(exp.Experiment): def setup(self): # assuming an observer exists with id "hist" self.obs = vid.image_observers["hist"] self.obs.start_observing() # start processing image data def run(self): # register on...
3d24cb49b541c99c2f13fb5f2b1a5293d7f9b5576c79f3819fefe9fc1ba71e3a
Python
868
38
"""The documentation functions.""" docdict = dict() # Define docdicts docdict["net"] = """ net : Instance of Network object The Network object. """ docdict["fname"] = """ fname : str | Path object Full path to the output file (.hdf5). """ docdict["overwrite"] = """ overwrite : Boolean True : Overwrite e...
aa98b5608e749d726c14982dc8e9c86f0d5d4dd07991d0169bdfc00e5553aeaa
Python
868
30
""" Merge pandas DataFrames based on the values of selected columns. """ import argparse import pandas as pd from copy import deepcopy CLI = argparse.ArgumentParser() CLI.add_argument("--output", nargs='?', type=str) CLI.add_argument("--data", nargs='+', type=str) CLI.add_argument("--output_img",nargs='?', ty...
f3351d703946772b2076f0585f613ea7a34c2f874cd35564da39c25d14f51f7c
Python
868
26
import math import torch import torch.nn as nn from torch.autograd import Variable class PositionalEncoding(nn.Module): "Implement the PE function." def __init__(self, d_model, dropout, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) # ...
c86f9ec5b770537f42524971c78ee0768459e348a395eb24b9857cfccaed2595
Python
871
32
import os from torch.utils.data import Dataset import nibabel as nib import numpy as np import torch class ImageDatasets(Dataset): def __init__(self, path): self.images = [os.path.join(path, img) for img in os.listdir(path)] print('"End reading dataset..."') def apple_LR(self, i...
dd7f720db3961c379e1db6550b027b903731ee4e471d3f0761864fd01a0793ae
Python
871
37
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="metroem", version="0.0.9", author="Seung Lab", author_email="", description="Metric learning optimization pyramid for EM alignment", long_description=long_description, long_descrip...
087098c1b0d2d5cd4d64cadac883269ae771159202abecafa2a7d1b776189550
Python
873
24
# Copyright (c) 2021 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 appli...
752f6fa3f20182b9fd0abc2bca0a97eabcfd30d7fdf9a31b6d2f915d0b125dc4
Python
873
33
"""Tests for standalone remote NWB transport configuration.""" from pathlib import Path from dandi_transport import FsspecNwbTransport, LindiNwbTransport def test_uses_cache_override(tmp_path: Path) -> None: """Retain an explicitly supplied cache directory. Args: tmp_path: Temporary test directory....
fbac60563e6c56947236ac829b19abedbc34e3cba150082fad0b8ee201eff490
Python
874
38
# Copyright (C) 2020-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from copy import deepcopy import torch import torchvision\ # Download Test datasets mnist_test = torchvision.datasets.MNIST( "./files/", train=False, download=True, transform=torchvision.transforms.Compose( [...
552b1cb24b0f1caaa0c558c2c48173f42ed4d6d459efffa4d34d97039278f7aa
Python
875
27
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages data = pd.read_excel('compare_newTest_tools.xlsx') indicators = ['Accuracy', 'Precision', 'Recall', 'Specificity', 'F1-Score', 'AUC', 'AUPRC'] data_matrix = data.loc[:, indicators].values da...
c50fe801542543d4cf741e4acfb1de500cb7cdb3cce63f62915f3d7190a4217e
Python
875
31
from PymoNNto import * from PymoNNto.Exploration.Evolution.Interface_Functions import * import numpy as np import matplotlib.pyplot as plt class Counter(Behavior): def initialize(self, neurons): self.inc = self.parameter('inc', 1.0) neurons.count = np.zeros(neurons.size)#neurons.vector() pl...
a6c82b7d9c279de51e8547c44429cd65187b3288e4671f787f0c7b9b83a543c8
Python
876
38
"""Transform base class Registers every child class """ __all__ = ["Transform", "get_transform"] from abc import ABC, abstractmethod registry = {} def get_transform(name): clean_name = name.lower().replace("_", "") return registry[clean_name] class Transform(ABC): def __init__(self, params): ...
22d0c76765b0f9108a0e55c255108ca74b6de5e10e1695666a3228a1de52a160
Python
877
45
"""isort:skip_file""" from torch.backends import cudnn from .device import DEVICE from .models import ( IdCNN, IdentifierBase, IdentifierIdCNN, IdentifierContrastive, ResNet18, load_identifier_model, ) from .train import ( evaluate, evaluate_only_acc, StopTraining, train_loop, ...
9aa53e161d0fe5218db7b6b26e68cf812c740927d4c23b88859581c4fb78b5da
Python
877
28
from PymoNNto.NetworkCore.Behavior import * class Homeostasis(Behavior): def initialize(self, neurons): target_act = self.parameter('target_voltage', 0.05, neurons) self.max_ta = self.parameter('max_ta', target_act, neurons) self.min_ta = self.parameter('min_ta', target_act, neurons) ...
dbeceea2d23c1e2b7912d7d11e1481e77d9c0b03a35cebf2c916062e9deb9841
Python
878
39
# Copyright (C) 2020-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from copy import deepcopy import torch import torchvision # Download Test datasets mnist_test = torchvision.datasets.MNIST( "./files/", train=False, download=True, transform=torchvision.transforms.Compose( [ ...
7e239b2d4f89c0db088d61140a3ba9a5f8e7c39a26f6a9b8673d8caad0c0bd3c
Python
879
22
from PymoNNto.NetworkCore.Neuron_Group import * import numpy as np def normalize_synapse_attr_sparse(src_attr, target_attr, target_value, neurons, synapse_type): neurons.temp_weight_sum = neurons.vector() for s in neurons.synapses(afferent, synapse_type): if 'sparse' in s.tags: s.dst.tem...
58214946d5a73a49d5ec0212a901cd750c1461e8cab5b38e3003e98829f4af66
Python
881
35
import torch.nn as nn class Classifier(nn.Module): """ General implementation of simple multi-layer perceptron for single prediction. Author: Emma Svensson """ def __init__(self, hidden_layers): super(Classifier, self).__init__() inplace = False self.layers = nn.ModuleLi...
3244362a704aaa17de2cb0d3011019115c82c843336681cc5d0cb6ed182f040d
Python
883
38
import nibabel as nib import numpy as np def load_ct_to_numpy(data_path): if type(data_path) != str: data_path = data_path.name image = nib.load(data_path) data = image.get_fdata() data = np.rot90(data, k=1, axes=(0, 1)) data[data < -1024] = 1024 data[data > 1024] = 10...
0d35894684abce1a6a1dd2b40e8a65ed39377d911f236f1bb88133b2104b8bfe
Python
885
31
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="pyfizi", version="0.7.1", author="Nicholas Mancuso, Megan Roytman", author_email="nicholas.mancuso@med.usc.edu", description="Impute GWAS summary statistics using reference genotype data",...
24ce3e5cf1b5c5871ee7b85f8f3098f7a306994a8f037e2208f4a5b98096d302
Python
885
26
from common.trials import run_experiments from osa.configuration import get_config_dict_from_yaml def make_config_dict_list(): config_dict_list = list() for name in [ # "WideResNet", # "max-SEResNet20-attention-4", # "BNN-max-SEResNet20-attention-4", # "uniform-smooth-BNN-max-...
42f632c007b98edb22d9ef912f4156e4c7a7be4496c8824dfeae983058f10a8c
Python
886
31
import numpy as np import NALSM_GEN_SUPPORT as sup import os SAVE_VER_INP = input('VERSION? [int]: ') SAVE_VER = int(SAVE_VER_INP) LEN = -1 main_Path = os.getcwd() dataPath_TRAIN = main_Path + '/train_data' netPath = main_Path + '/networks' PATH = dataPath_TRAIN+'/ver_' + str(SAVE_VER) + '/' filen...
94321b2796b2b89f9fe3b73bfe8fe1f841fd044265452782d87d6aa9b3878363
Python
886
31
from dig.xgraph.dataset import BA_LRP import shutil def test_BA_LRP(): root = 'datasets' dataset = BA_LRP(root) gen_data1 = BA_LRP.gen_class1() gen_data2 = BA_LRP.gen_class2() assert len(dataset) == 20000 assert dataset.data.edge_index.size() == (2, 840000) assert dataset.data...
d15ad7d0adaba44d483023de1e122f9088e877065dbe16641c49a3201649d07b
Python
886
31
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="GeneSGAN", version="0.0.1", author="zhijian.yang", author_email="zhijianyang@outlook.com", description="A python implementation of Gene-SGAN for multi-view semi-supervised clustering", ...