sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
6c2ee003aa5eec6ab3d43ccbf7816c725b2025f142a4635d261d674a1077af37
Python
1,682
35
################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is free...
6c9b90a4123a956c0c6e7a0fee9694efcecf53c63808b1684c47cecebd2aec17
Python
1,682
95
from dataclasses import dataclass from pathlib import Path from typing import Any from rdkit import Chem TENSORBOARD_LOG_DIR = Path("tensorboard_logs") """Set of parameters for each atom.""" ALLOWED_ADDUCTS = [ "[M+H]+", "[2M+H]+", "[M+Na]+", "[2M+Na]+", "[M-H]-", "[2M-H]-", "[M+K]+", ...
f25b6e7dac13ee2547f2c900e8d5a27670baa79883c81932dac6fe954591dbfa
Python
1,682
61
#!/usr/bin/env python3.7 """Plot the waveform used for stimulation. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. RUN THI...
1b2b9dc54b7d01648cada062cea32647044d237dc6a96423ff7fedc6de52d8c1
Python
1,684
46
def _get_starfysh_modules(): from ..external.starfysh import AA, _starfysh as sf_model, plot_utils, post_analysis, utils return AA, utils, plot_utils, post_analysis, sf_model class STARFYSH: """ STARFYSH spatial transcriptomics analysis class. A comprehensive tool for analyzing spatial transc...
6bff063892062bb1cfff00f6c483f2faaedb4a698bacbe19dfcea2800b3ff6f4
Python
1,685
39
from torch import nn from .modules import * class MultiModalLayer(nn.Module): def __init__(self, d_model, d_inner, n_head, d_k, d_v): super().__init__() self.peptide_attention_layer = MultiHeadAttention(n_head, d_model, ...
f7695ce945a4115f2285896993c9230e047c3488888e4099538377f42560b292
Python
1,685
45
#!/usr/local/bin/ipython -i from mozaik.experiments import * from mozaik.experiments.vision import * from mozaik.sheets.population_selector import RCRandomPercentage from parameters import ParameterSet def create_experiments(model): return [ # Lets kick the network up into activation # Spontaneo...
883bc96536fa40f9d0df9c6c658d6b2d0c055088e683870aa7596863085b9041
Python
1,686
40
#Test multi_stage from pytorch_lightning import Trainer from src.models import multi_stage from src.data import TreeDataset from src import visualize import numpy as np import glob def test_MultiStage(dm, config): m = multi_stage.MultiStage(train_df=dm.train, test_df=dm.train,crowns=dm.crowns, config=config) ...
e2fa72ca3d2bfa307aa11b2ba391ce4493fe118657f61015b4840da13560ac3a
Python
1,686
46
#!/usr/local/bin/ipython -i from mozaik.experiments import * from mozaik.experiments.vision import * from mozaik.sheets.population_selector import RCRandomPercentage from parameters import ParameterSet def create_experiments(model): return [ # Lets kick the network up into activation # Spontaneo...
53d8e4f925c821a3660c90cb9127765e80a6950cd7060d32f895d6f29b95a679
Python
1,687
75
import pathlib import numpy as np import nose from caiman import mmapping from caiman.paths import caiman_datadir TWO_D_FNAME = ( pathlib.Path(caiman_datadir()) / "testdata/memmap__d1_10_d2_11_d3_1_order_F_frames_12_.mmap" ) THREE_D_FNAME = ( pathlib.Path(caiman_datadir()) / "testdata/memmap__d1_10_...
a41c8a86b1daed60c06de3b7f10bf6c2dd9009aa57bca3c2bfba3b8e77635e3a
Python
1,687
48
"""Shared memory-detection utilities for OmicVerse.""" from __future__ import annotations import os # Fraction of available CPU RAM that a single dense allocation may occupy. # PCA and similar operations need ~2-3x the array size internally, so 0.3 # leaves headroom for temporaries. AUTO_DENSE_CPU_MEM_FRACTION = 0.3...
dad16361688421fd2f2bc4225ad16853d3cf49b2578738b3c629c8813df0409f
Python
1,687
51
import os from pcntoolkit.normative_parallel import execute_nm, collect_nm, delete_nm from pcntoolkit.dataio.fileio import load as ptkload from pcntoolkit.normative import predict, estimate # globals root_dir = '/project_cephfs/3022017.02/projects/hansav/Run8_f/' proc_dir = os.path.join(root_dir) w_dir = os.path.join(...
14e082a8efbc648e21bd6beb8fc32096927804758a0d51ffc1e529ceb3350b74
Python
1,688
50
import torch import torch.nn as nn from ..utils import create_norm class ResMLPEncoder(nn.Module): def __init__(self, num_hidden, num_layers, dropout, norm, covariates_dim=0): super().__init__() self.layers = nn.ModuleList() assert num_layers > 1, 'At least two layer for MLPs.' for ...
180dd116790080adf8125283ab33bfa1a96caae3ee1f20b69a446e167ef446fd
Python
1,688
42
# Import modules import cv2 import pandas as pd import os import shutil import sys image_size = int(sys.argv[1]) base_path = os.getcwd() print(base_path) source_path = f'{base_path}/ultra-mnist' destination_path = f'{base_path}/ultra-mnist_{image_size}' if os.path.exists(destination_path): print("Directory already...
f0b53ab6323e060ec20d7b375fc1b3a2bd5bb7fa549b4ac32eaa33cdfa5f47b5
Python
1,689
51
import os from pcntoolkit.normative_parallel import execute_nm, collect_nm, delete_nm from pcntoolkit.dataio.fileio import load as ptkload from pcntoolkit.normative import predict, estimate # globals root_dir = '/project_cephfs/3022017.02/projects/hansav/Run8_fs/' proc_dir = os.path.join(root_dir) w_dir = os.path.join...
e8f95425d251101daaee62cb37b58d23e660d9bea155f81533f281d1a64b6d54
Python
1,690
68
from pathlib import Path import pandas as pd import numpy as np from collections import defaultdict import random from scipy.stats import multivariate_normal from scipy.stats import wasserstein_distance from scipy.stats import pearsonr import matplotlib import matplotlib.pyplot as plt from matplotlib.font_manager impo...
463d94d4fa1756ec0053cdda6731b0f6d10a52bb09943b0d2b45eaeb17185251
Python
1,691
62
from typing import Tuple import pandas as pd from data_profiling.config import Settings from data_profiling.model.pandas.describe_categorical_pandas import ( length_summary_vc, unicode_summary_vc, word_summary_vc, ) from data_profiling.model.summary_algorithms import ( histogram_compute, series_ha...
fd75512390cf585377a9dcf5784d94fcf4c9d31b01b1447698e35221ab48dbdb
Python
1,691
51
import glob import argparse import concurrent.futures import numpy as np from utils import mri_utils, metadata_utils from config import config parser = argparse.ArgumentParser() parser.add_argument('--dir', type=str, default="/gpfs/data/oermannlab/ObermannNeuro3/dicom/", help=...
5dfb4e2cb7033e33277471d8d201820c5283b864a02b36df6a450e9f0bd8652a
Python
1,692
42
import numpy as np from lib.surface import isotonic_increasing, monotone_free_arcs def test_isotonic_increasing(): y = np.array([0.1, 0.3, 0.2, 0.4, 0.35, 0.36, 0.9]) fit = isotonic_increasing(y) assert np.all(np.diff(fit) >= 0) assert np.isclose(fit.sum(), y.sum()) # pooling keeps the mean asser...
c60b0085bc50b997689f2882b795c7164f88e32108c7e036b572f768383461ba
Python
1,692
50
"""Read BrainVoyager vmr and export nifti.""" import os import nibabel as nb import bvbabel import pprint import subprocess subs = ['sub-08'] ROOT = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives' for sub in subs: folder = f'{ROOT}/rawdata_bv/{sub}/ses-01/anat' inFile = f'{folde...
dbbcf789a9df04a16fa6fb6f49191318e63b8362decb891758092303b79ad00f
Python
1,692
48
# built-in dependencies from typing import Any, List, Union # project dependencies from deepface.commons.onnx_utils import build_session from deepface.models.facial_recognition.onnx.OnnxFacialRecognition import OnnxFacialRecognition from deepface.commons.logger import Logger logger = Logger() # pylint: disable=line-...
0bef0addb3a0abd5e82a90fe60443fb36fd739d3e2ab04a814904c6030a7ad4e
Python
1,693
43
# ------------------------------------------------------------------------------------------------------------------------------------- # Following code curated for Bio-Diffusion (https://github.com/BioinfoMachineLearning/bio-diffusion): # --------------------------------------------------------------------------------...
b8eaf977c4d6563589f7a1c6bcbe581eb1c93c68f3d809d719e9831ee1f6a8f4
Python
1,693
85
#!/usr/bin/env python3 # vim: set ts=4 sw=4 tw=0 : from tempfile import NamedTemporaryFile import numpy as np import cp2k TEST_FILE_CONTENT = """ &FORCE_EVAL METHOD Quickstep &DFT BASIS_SET_FILE_NAME BASIS_SET POTENTIAL_FILE_NAME POTENTIAL LSD &MGRID CUTOFF 140 &END MGRID &QS ...
16094f08f694ab854aef0fe23d5ff24cb895ddc9a75daa31e2f5a848b8de1c64
Python
1,694
56
# flake8: noqa # __begin_deploy_app_with_capacity_queue_router__ import ray from ray import serve from ray.serve.config import DeploymentActorConfig, RequestRouterConfig from ray.serve.context import _get_internal_replica_context from ray.serve.experimental.capacity_queue import ( CapacityQueue, ) @serve.deploy...
34064061adac4393f70e75642e889516e8f7517c24e6c6c5b92acb825b21130b
Python
1,695
58
''' Correcting bias field of MP2RAGE images. ''' import os import glob import subprocess import ants DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti' SUBS = ['sub-08'] for sub in SUBS: # ========================================================================= # Brain extraction...
54f93705e5830958428ec07905da2f16adfd49943f8937b0573b1121518599fa
Python
1,695
55
import copy from ..distances import LpDistance from ..reducers import DoNothingReducer, MeanReducer, MultipleReducers from ..utils.module_with_records import ModuleWithRecords class ModuleWithRecordsAndReducer(ModuleWithRecords): def __init__(self, reducer=None, **kwargs): super().__init__(**kwargs) ...
c48483791d56e9307aa5f821a844d37f479ded093d6d0ec694607902c00300ab
Python
1,695
58
import pdb import numpy as np from data_assimilation.particle_filter.base import BaseObservationOperator class ObservationOperator(BaseObservationOperator): def __init__( self, observation_state_ids: list, observation_space_ids: list, full_space_points: list = None, ...
55157a6146152a2340cd1d9c418136ad42714388bb0abb7ce1551ad2c8f02825
Python
1,696
73
import errno import os import platform import shutil import subprocess def is_nvidia_installed(): installed = True try: subprocess.check_output('nvidia-smi') except Exception: installed = False return installed def is_windows(): return platform.system() == 'Windows' def is_linu...
af6c8ac7cb87081aadc1e83959d2fb7f9e7f1eb9efddf5813df9f4097b0c7bd7
Python
1,696
37
"""Vendored copy of SATURN (Species Alignment Through Unification of Rna and proteiNs). SATURN is a deep-learning method for cross-species single-cell integration. Per species it takes an AnnData of raw counts plus a precomputed protein-embedding dictionary (gene symbol -> ESM2 embedding vector) and trains a "macrogen...
df74a7fda6c8269f1b19619e3c15d3ff549f8f8dd868fd6ae57553c5bf41ff24
Python
1,696
52
#!/usr/bin/env python import platform import setuptools if ( platform.processor() == "arm" or platform.processor() == "i386" ) and platform.system() == "Darwin": tensorflow_os = "tensorflow-macos>=2.10.0,<=2.20.0" else: tensorflow_os = "tensorflow>=2.12.0,<=2.20.0" with open("README.md", "r") as fh: ...
f17cf7611356f7fb9c459205163379556004fae519cd0f5b6f83a12b3753ca16
Python
1,696
49
""" Full assembly of the parts to form the complete network """ import torch.nn.functional as F import torch.nn as nn from .unet_parts import * class UNet_3(nn.Module): def __init__(self, output_c = 1, bilinear=True): super(UNet_3, self).__init__() self.output_c = output_c self.bilinear =...
e9cda066e2861a6621fe7eac9ea351adaa1bb044d114695484bda548e165a2ee
Python
1,697
63
#!/bin/env python3 # usage: python _run-rnapromo-h0.py <rnapromo_out> <test.fa> import sys inf = float("inf") ifname = sys.argv[1] faname = sys.argv[2] def get_correct(): correct = {} with open(faname) as fi: b,e=-1,-1 for l in fi: if l.startswith(">"): l=l[1:].str...
687a21240ec9877a2f2213e6a8fd42ad34c976ea705d2dcdda1b2f86641c6107
Python
1,699
49
import pandas as pd import numpy as np import os.path as osp NAME_COLUMN = 'name' FP_DELIM = '\t' class FPDataset(): """ Dataset class to load fingerprint data. """ def __init__(self, args): self.num_workers = args.num_workers self.data_path = args.data_path self.fp_format = a...
c3a48f90547883adf170939f62fdfb1262a8b2dc1ab8082eeb3ac373b77726d2
Python
1,699
57
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import random import numpy as np import pytest from fairchem.data.oc.core import Bulk, Slab class Te...
5fd2ad87aed661b04129f67feecc0be6e95fb4cdf0d22579749656690c1dbce6
Python
1,700
42
import pandas as pd import os def main(db): old_file = f'./1_output/old_method/{db}_introns.bed' new_file = f'./1_output/{db}_introns.bed' old_df = pd.read_csv(old_file, delimiter='\t', header=None, usecols=range(6), names=['seqid', 'start', 'end', 'name', 'score', 'strand']) new...
b6736a99849bec2f00f7e5e4058fa508be9e889e82ea1b10ad1f5fcaceea752b
Python
1,700
62
#!/usr/bin/env python3 """Extract features with pretrained model from RetCCL: Clustering-guided Contrastive Learning for Whole-slide Image Retrieval https://github.com/Xiyue-Wang/RetCCL use like this: python -m marugoto.extract.xiyue_wang \ --checkpoint-path ~/Downloads/best_ckpt.pth \ --outdir ~/...
4b5bcaa6443e8c6c21f7af803d08d47e26023fce5e2dbca849c1d5f48c6de0cd
Python
1,701
59
from ultralytics import YOLO import os import cv2 import numpy as np import math import tqdm import copy imgs_path = "test_images" out_path = "test_results" crop_image_path = 'cmb_results' os.makedirs(out_path, exist_ok=True) # Load a model model = YOLO("CMB.pt") # load a custom model # Predict ...
5b5ff057cacc19934700ca8e183aaa0aaae23525fc7ddfca86a72ae9e473f8b7
Python
1,701
56
from collections import Counter import pandas as pd from data_profiling.config import Settings from data_profiling.model.table import get_table_stats @get_table_stats.register def pandas_get_table_stats( config: Settings, df: pd.DataFrame, variable_stats: dict ) -> dict: """General statistics for the DataFr...
5c0c9b6398b66e36ef1a56c8fb00d62b86a3797b770f0d0fa89d1ab9c565d299
Python
1,701
48
#!/usr/bin/env python import tflearn import pyaudio import speech_data # Training Step: 544 | total loss: 0.15866 # | Adam | epoch: 034 | loss: 0.15866 - acc: 0.9818 -- iter: 0000/1000 # 98% Accuracy on training set in just a minute # audio = pyaudio.PyAudio() # # format=pyaudio.paFloat32 # format=pyaudio.paInt8 # ...
9ebeea26c00e5622d8ea9fbde03e984bb221cc09ff3a0e4282e8d1398e8f24ff
Python
1,701
48
import numpy as np import matplotlib.pyplot as plt import pandas as pd # Load data for BCI IV-2a df_a = pd.read_excel('length.xlsx', sheet_name='2a') # Load data for BCI IV-2b df_b = pd.read_excel('length.xlsx', sheet_name='2b') # Set token sizes that were experimented with param_values = [12, 13, 15, 17, 2...
6be8487e1e64ee2a94d85544258426f9aff9c225761109de5726bc0bd9602187
Python
1,702
56
from spinnaker2 import snn, hardware def run_model(spikes_per_timestep, timesteps): n_pre = spikes_per_timestep spike_times = dict() all_timesteps = list(range(timesteps)) for i in range(spikes_per_timestep): spike_times[i] = all_timesteps stim = snn.Population( size=...
838a6a8c27a4656392bdffaca03292b116f0b114bf9a4c8e143fe510a8df4f58
Python
1,703
62
import argparse import glob import matplotlib.pyplot as plt def parse_log_line(raw_line): line = raw_line.strip().split(":") for i, v in enumerate(line): if v.startswith("DEBUG"): return line[i], line[i+1], line[i+2:] def main(args): input_logs = glob.glob(args.input) if len(in...
146189bd3736f8b6638f4834c4cee34117801bb7e5a687e09fe20908a86cc4b5
Python
1,704
48
''' Finds the exact times between consecutive triggers from logfiles and computes average TR for SS-SI VASO acquisitions. Takes logfile as input and assumes "Keypress: 5" as trigger in logfile. ''' import re import numpy as np def findTR(logfile): with open(logfile) as f: # Open file f = f.readlines()...
5f8866d98600e1fbb8ae1f239dcf93a63b6208ed94da02af3f96b41b0846ddc1
Python
1,704
46
#!/usr/bin/env python3 """Utility functions for correlation between covariates and PCs""" import logging import numpy as np import pandas as pd def vcorrcoef(X, y): """Vectorized correlation, matrix vs. vector.""" Xm = np.reshape(np.mean(X, axis=1), (X.shape[0], 1)) ym = np.mean(y) r_num = np.sum(np.a...
6b37ff7153abb1d20aaeeea6c045e442987aecf5de118e55dd30f896f66c7944
Python
1,704
44
#!/usr/bin/env python3 import torch from tqdm import tqdm import numpy as np try: import tinycudann as tcnn except: pass # This script stress-tests the GPU memory arena of tiny-cuda-nn with randomly sized allocations and helped # find a bug in its interval arithmetic in the past. class TcnnFCBlock(tcn...
7008a8f63db63b14d1d4a499a13e975715126f7ad975a04a6db63b2f81bfc3e7
Python
1,705
62
# flake8: noqa """ Example Ray Serve LLM application for a multi-host TPU slice. """ # __serve_tpu_multihost_start__ from ray import serve from ray.serve.llm import LLMConfig, LLMServingArgs, build_openai_app llm_config = LLMConfig( model_loading_config=dict( model_id="google/gemma-4-31B-it", mode...
e065aced80d839b128eadf4dadadbdb4c7426bd57cbd619cedb372fdc7cabb25
Python
1,705
48
# built-in dependencies from typing import Any, cast # 3rd party dependencies from numpy.typing import NDArray # project dependencies from deepface.models.Demography import Demography from deepface.commons.onnx_utils import run_session from deepface.commons.logger import Logger logger = Logger() # Notice that facia...
81baf681d70349ef2bf33d7f056e5d18d35fe7b41e1d4cff2ca0e0c51849d5e9
Python
1,706
62
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import random import numpy as np import pytest import torch from ase.build import bulk, molecule from ...
602f5d43eff02f9dadfdcaab6f27a016af8137482d061d68f6ffb93626275cb4
Python
1,707
63
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ """ import argparse import sys import pandas as pd import pysam import svtk.utils as svu def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('vcf') ...
74ca773f2878fcb54dd254c0d1a7cf501face60b367cca8e46c83626251a38bc
Python
1,707
48
from __future__ import annotations import itertools from typing import List, Union import numpy as np import pyarrow as pa import pyarrow.compute as pc def _counts_to_offsets(counts: pa.Array) -> pa.Array: """Convert per-row counts to list offsets via cumulative sum.""" cumsum = pc.cumulative_sum(counts) ...
b748cace6d8dcd52c09a9c929f43be90b3e169d3d6d2cc80ed452ea34f1b3c21
Python
1,707
57
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
d0752b4e47e11fa8f77fea17c1c27902e464a516158415c52be7a3d00dd50483
Python
1,707
56
import torch from torch.autograd import Function class DiceCoeff(Function): """Dice coeff for individual examples""" def forward(self, input, target): self.save_for_backward(input, target) eps = 0.0001 self.inter = torch.dot(input.view(-1), target.view(-1)) self.union = torch....
8f9558e4673944526eda0e36dc9f18eacf63bbc7a1451b66cbe71d61a0603832
Python
1,710
44
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
c8b9987ca2a98d96d524a9324978e7704689cb2ebd32d2f2f5d4bb3fc9367a5f
Python
1,711
51
import pandas as pd from data_profiling.utils.cache import cache_file def test_dataset_schema(): file_name = cache_file("auto2.dta", "http://www.stata-press.com/data/r15/auto2.dta") df = pd.read_stata(file_name) metadata = { "creator": "Firstname Lastname", "author": "Firstnam...
4ccdfed19119b67ed1fba5b07724dda5bf7c70b1e4869e3232ddab3413c7f6c7
Python
1,712
43
import torch import ecg_augmentations as ea FS = 250 ECG, PEAKS = ea.synthetic_ecg(duration=10, fs=FS, n_leads=12, seed=0) NOISE = torch.randn(3, 4000, generator=torch.Generator().manual_seed(0)) def detector(signal, fs): return PEAKS[PEAKS < len(signal)].numpy() TRANSFORMS = { "RandomCrop": lambda: ea.Ra...
4c6e9e6192c08239e72af84af029ebf66d6e040319ee9caa102001f7424f5777
Python
1,714
54
from typing import Any, Dict, Optional, Sequence, Tuple import pyspark.sql.functions as F from pyspark.sql import DataFrame from data_profiling.config import Settings from data_profiling.model.duplicates import get_duplicates @get_duplicates.register def get_duplicates_spark( config: Settings, df: DataFrame, su...
add34a023d186277e354fb63353c2bc70ea0f6dd0faca3223b3165eabf87ea06
Python
1,714
50
from torch import nn from lop.utils.miscellaneous import net_init, fc_body, register_hook, kaiming_init, xavier_init, lecun_init class VF(object): def value(self, x, to_log_features=False): self.to_log_features = to_log_features val = self.v_net(x) self.to_log_features = False retu...
2e757263e1ce12c66f8c3890702ef182d7aef2ef8744d23e1a4cfb1ac0d284a2
Python
1,715
46
from src.commons.process_number import cal_eccentricity from src.display_properties.properties import Properties def get_sub_posi_list_at_given_e(eccentricty, display_posis): """ :param eccentricty: in pixel :param posilist: display position :return: the sub-display positions (within the given eccen...
a69e889a3ac182b485ca8848160d71b692d4cae6e65d05ce6b8e6ab9c74b60ff
Python
1,715
91
#!/usr/bin/env python ''' Brian2 example for lif neuron ''' from brian2 import * import numpy as np defaultclock.dt = 1*ms dt = defaultclock.dt print(dt) n_in = 1 # number of stimuli n_out = 1 # number of output neurons duration = 1*second v_th = 1. alpha_decay = 0.9 tau = dt/(1-alpha_decay) print(f"tau: {tau}") ...
68285bc7032b4df4914a2c817cf6b82451dda56f0d1861036e9f3c12fb5fb3b1
Python
1,718
52
import dataclasses from typing import Iterable def _validate_allowed_keys_exist( dataclass_name: str, data_dict: dict, allowed_keys: set ): keys_not_in_dict = allowed_keys.difference(data_dict) if keys_not_in_dict: raise ValueError( f"Key(s) {sorted(keys_not_in_dict)} are not present i...
c375cce93010687f75fa5eca930dd5eb1540e1015172f5684c7e491a97f18fe7
Python
1,719
54
import struct from spinnaker2.neuron_models.application import BaseApplication from spinnaker2.configuration import PEConfig from spinnaker2.neuron_models.common import add_log_memory_region from spinnaker2.coordinates import ByteAddr, align_addr_to_next_multiple_of_other class SpikeReceiverApplication(BaseApplicati...
d5cc0547481a7dbd15e90a0fd7908a9fa032fe963b020ad1be62251bae89f5fd
Python
1,720
45
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
dab7ceb564cff94edbecb9d89c80a63ded0122983d7fef5e055a231c15c72a14
Python
1,721
49
# 3rd party dependencies import pytest import numpy as np # project dependencies from deepface import DeepFace from deepface.commons.logger import Logger logger = Logger() def test_enabled_enforce_detection_for_non_facial_input(): black_img = np.zeros([224, 224, 3]) with pytest.raises(ValueError): ...
1742af6c598ce636b41ba9058cdf1590d3b28a5d8a7c6b7ecf3dadf963848794
Python
1,722
60
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
499efdcc93c0e771d9e1655920181ab6ba3ca9cb54874d97de03d3b0645bd3d8
Python
1,722
73
from nltk import bleu from rouge import Rouge import jsonlines import json import sys def read_gold_data(path): fi = jsonlines.open(path, 'r') explanations = {line['index']: line['conceptual_explanation'] for line in fi} return explanations def evaluation_bleu(golds, predictions): bleu_socre = 0 ...
bf56be4f746c892469c172d664a7f1848dd7d10dbc33353a8af46a29102403ec
Python
1,722
36
from .trainer import train_vae from .trainer_nogcn import train_vae_nogcn from .trainer_anvi import train_anvi from .trainer_anvi_nogcn import train_anvi_nogcn #from .trainer_atac import train_atac def train(model, adata, epochs = 50, learning_rate = 1e-2, batch_size = 200, grad_clip = 1000, shuffle=True, test=0.1, na...
cbf5038d00768bf2032fa14e7a7079b70db9fa233e98d2e4b89a28d4d5e7357d
Python
1,722
52
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 3 15:48:55 2019 @author: epnevmatikakis """ from caiman.paths import caiman_datadir from caiman.utils.utils import load_graph import os import numpy as np try: os.environ["KERAS_BACKEND"] = "tensorflow" from keras.models import model_from_...
6b54d84f48f95825df9ffb03f577270d18ec9f7266fd122b12c126661757c641
Python
1,723
56
import numpy as np import gzip import pandas as pd import os def gen_GCTA_GRM(M, GRM, outpath): """ Generate the lower triangle indexed GRM text files for GCTA or OSCA reml analysis. Parameters: - info: A dictionary to store relevant information. - M: Number of SNPs/Vertices used for calculati...
bfddd5d4302688e29182cdaf3ce0f521445c062a01301229cc2c1efcdcbb7b54
Python
1,723
69
''' Distributed training related functions. From DeiT. ''' import io import os import time from collections import defaultdict, deque import datetime import torch import torch.distributed as dist def is_dist_avail_and_initialized(): if not dist.is_available(): return False if not dist.is_in...
e20483a090dcd45111559e5eb0690a59fe57626b1394f32c0c75d7d1d52348b5
Python
1,724
64
import numpy import torch import scipy import scipy.sparse as sp import logging from six.moves import xrange from collections import OrderedDict import sys import pdb from sklearn import metrics import torch.nn.functional as F from torch.autograd import Variable from pdb import set_trace as stop def compute_aupr(all...
12b6bd324f4b2c1f3da716b2886dc9f14a4170bdb6b353519bcdcbdbb31cd114
Python
1,725
53
import torch from torch import nn import torch.nn.functional as F class CNN_LSTM(nn.Module): def __init__(self, num_hiddens, num_layers=1, bidirectional=False, **kwargs): super(CNN_LSTM, self).__init__(**kwargs) self.conv = nn.Conv1d(1, 32, kernel_size=20, padding=5, stride=5) self.bn = nn.BatchNorm1d(32) se...
1e12b14a2ddc4dc8dbb7e9fa711e6bcb6ea0b22235b7a1838733ac8a90952c20
Python
1,725
49
#!/usr/bin/env python #!/usr/bin/python import speech_data import layer from layer import * # Training Step: 544 | total loss: 0.15866 # | Adam | epoch: 034 | loss: 0.15866 - acc: 0.9818 -- iter: 0000/1000 # 98% Accuracy on training set in just a minute # audio = pyaudio.PyAudio() # # format=pyaudio.paFloat32 # form...
790a5f0d0f24bbf446a6affa4b6938e450f2874f003d68aa8bf539750706e342
Python
1,727
80
from ray import serve import time import os # __updating_a_deployment_start__ @serve.deployment(name="my_deployment", num_replicas=1) class SimpleDeployment: pass # Creates one initial replica. serve.run(SimpleDeployment.bind()) # Re-deploys, creating an additional replica. # This could be the SAME Python scr...
48bad8512ffbbf81a653222d9402b3f24f7bf3c07e392bf53bb360233eff3d7f
Python
1,728
52
from __future__ import print_function import argparse import glob import numpy as np import os def parse_args(): parser = argparse.ArgumentParser("Summarize VCFEval summaries") parser.add_argument('--input', '-i', dest='input', default=None, required=True, type=str, help='Glob matching s...
9a0a6e8e3a1510322ac20503742ca662df139c58c98025575fc520272f6da381
Python
1,728
67
import os import matplotlib.pyplot as plt import boto3 from neuron_morphology.morphology import Morphology from neuron_morphology.swc_io import (morphology_from_swc, morphology_to_swc) s3 = boto3.client("s3") def collect_morphology(bucket: str, swc_key: str): swc_response = s3.get_objec...
b67f31a4c2d88c0dc044f6ff8eb9445f3b64863779bcbd443ca88cd16528784e
Python
1,728
55
class Params(object): def __init__(self, **kwargs): self.inhibition = None self.n_days = 30 self.record_on_days = [0, 29] self.neuron = { 'N_E': kwargs.get('N_E', 20000), 'N_I': kwargs.get('N_I', 5000), 'c': kwargs.get('c', 0.04), 'g': ...
40fe74c945337a8b5d56c6c9c176ad18ff729819951322fa3c996a26d3bdd86b
Python
1,729
44
from typing import TYPE_CHECKING, Iterator from ray.data._internal.object_extensions.arrow import raise_on_pickle_object_columns from ray.data.block import Block from ray.data.datasource.file_based_datasource import FileBasedDatasource if TYPE_CHECKING: import pyarrow import pyarrow.fs class ORCDatasource(F...
d16dd5dff5e2ef0393e70176cca76b34d0851106e8ec4f8ef523e9415bd8f9ca
Python
1,729
56
import os import swap_errors.figures as swf if __name__ == "__main__": fig_data = {} save_fig_templates = ("fig-{}.svg", "fig-{}.pdf") os.chdir("/burg/home/wjj2109/analysis") fig_key = "pro_lm" fig = swf.ProLMFigure(data=fig_data.get(fig_key)) fig.panel_color_cue() fig_data[fig_key] = fig...
3eede96274fa73c31cf309e82b07d91753fed3f8a3ff0718acf9053d487e3c46
Python
1,730
67
# flake8: noqa # __import_start__ from starlette.requests import Request import ray from ray import serve # __import_end__ # __model_start__ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer @serve.deployment(num_replicas=2, ray_actor_options={"num_cpus": 0.2, "num_gpus": 0}) class Translator: def...
512a832976f842edb0e350258778ef72036f98292c5bb75fe047e429d1e611f5
Python
1,730
53
''' check if we can cluster the scene vectors in particular, can we derive good clustering parameters from the training set and generalize to the validation set this is essential for the clustering based shortcut model to work ''' import os import pickle import numpy as np import pandas as pd import seaborn as sns imp...
5fa9a125a5dbd0663deb03e41d2ba260f5ed24cc9e4bb263d7929fdfa976e9cb
Python
1,730
57
from sklearn.linear_model import LinearRegression import pandas as pd import argparse import os parser = argparse.ArgumentParser() masks = ["true", 'false'] parser.add_argument('-k', '--mask', type=str, choices=masks, required=False, default="false",\ help='whether to use masked dataset. default=f...
8df7accaf224dc4d7cac007c6f8934ab1213190b2b87c273d7565cbf1012191a
Python
1,731
42
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from torch.nn import CrossEntropyLoss as CE import torch from torch.nn import MSELoss as MSE from .losses import FocalLoss, FocalLoss_L2, dice_loss, CE_dice, CE_L1, DecadeCELoss, HuberLoss def criterions(cfg): criterion_type = cfg.crit...
b9dbfd625a3011b545457b5f17cdb30e517955ae17492cb13a218fb7393a17cc
Python
1,731
41
from model import (IntraEncoder, InterEncoder, ProteinInteractionNet, Tester) from uncertaintyAwareDeepLearn import VanillaRFFLayer from utils import ( load_configuration, set_random_seed, get_computation_device, evaluate ) import torch def main(): # --- Pre-Training Setup --- # Load configs. ...
07ea2d76fcce673ba45195b688f28bbe46a09bada5af514afe80e0e8359ed79e
Python
1,732
50
"""FAISS padding is not an identity when the requested gallery is too small.""" from unittest.mock import MagicMock import numpy as np import pytest faiss = pytest.importorskip("faiss") from deepface.modules import datastore @pytest.mark.parametrize("normalized", [False, True]) @pytest.mark.parametrize("similarit...
cd093a00d1266ddf36137d6ab1f313149920909b6c753b9f71a90f64376aebf7
Python
1,733
36
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
1213014aaa74eb8325709f982da6dabc960c04af4e879db1c317497148b3ed84
Python
1,735
62
from pathlib import Path import spectral as sp from siapy.entities import SpectralImage from siapy.entities.images import SpectralLibImage # Set the path to the directory containing the data # !! ADJUST THIS PATH TO YOUR DATA DIRECTORY !! data_dir = "./docs/examples/data" # Find all header and image files in the da...
4218b0cf5f555abd0996dc8f9ab6289d0efc5f9f6201a11ed9899d882b193cfb
Python
1,736
44
import csv import neuron_morphology.constants as constants from neuron_morphology.validation.result import InvalidMarkerFile from neuron_morphology.validation.result import MarkerValidationError class Marker(dict): """ Simple dictionary class for handling reconstruction marker objects. """ def __init__(self,...
9249dd305fa42f4a36d0d534bd14bae07e3b11bf852e63300aabe18c74e7a064
Python
1,736
61
import time import ray from ray.util.metrics import Counter, Gauge, Histogram ray.init(_metrics_export_port=8080) @ray.remote class MyActor: def __init__(self, name): self._curr_count = 0 self.counter = Counter( "num_requests", description="Number of requests processed b...
b3cbe86b0fdf636596aa42098338a4ab33c70f6d967fe9a84bbb98cf859d4c71
Python
1,736
46
import json import logging from datetime import datetime from agent.data.entities.config import ROOT_LOGGER_ID from agent.data.sql.sql_mgmt import get_connection from agent.crawlers.snopes_crawler import crawl as crawl_snopes from agent.crawlers.politifact_crawler import crawl as crawl_politifact from agent.crawlers....
edb61426f2c985d4159964a6c2b7a982a4cd8528e1ec13d09c8591ec7926a1a4
Python
1,736
46
from setuptools import setup short_description = "AP-Net is an atomic-pairwise neural network framework for modeling interaction energies" try: with open("README.md", "r") as fp: long_description = fp.read() except FileNotFoundError: long_description = short_description setup( name="apnet", v...
edbc5bd4dd5000ea61fdcecebdb0d8e13fcddcef7f9ac7c79638be021ba14d5a
Python
1,737
61
""" This script is used to clean up state after running test scripts, including on external services. For instance, this script can be used to remove the runs from WandB that have been saved during unit testing or when running examples. TODO: can we remove this file? """ import sys def clear_wandb_project(): imp...
2989f960613822c29303fd5728805f2566cfb9acc626012b232bc125a8c7d452
Python
1,738
39
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
e3d66f528d65f88a742fee851d455666c050b1ade2ef8d94675206f6768ef76e
Python
1,738
74
import numpy as np import pandas as pd import pdb import matplotlib.pyplot as plt from scipy.interpolate import interp1d def main(): #sensors_locations = [ # '02', '04', '05', '10', '12', '13', '14', '15', '17', '19', '21' #] sensors_locations = [ '04', '10', '13', '14', '15', '17', '19', '...
856f13003dd92cf507d1f81968ea02fa3bc7e57e938fccd05bea4f40ca0370f7
Python
1,739
42
import timeit import argparse from Bio import SeqIO from pyrosetta import * parser = argparse.ArgumentParser(description="Perform FastRelax on predicted protein structure") parser.add_argument("--input", type=str, help="input unrelaxed model") parser.add_argument("--output", type=str, help="output model (.pdb f...
af9d0757ec1c7f09e59db18260cdd0fadba65156ea9c058db04200d3309767c0
Python
1,739
52
import warnings from typing import Union from mmengine.config import ConfigDict from mmengine.dataset import (ClassBalancedDataset, ConcatDataset, DefaultSampler, InfiniteSampler, RepeatDataset) ConfigType = Union[dict, ConfigDict] def process_debug_mode(cfg: ConfigType) -> ConfigType:...
1f5eee80264cf1649e984c4ee5d668243c93c4e2c08dfe19c3ce383b5173eac0
Python
1,740
77
import torch import collections import pdb import csv from kipoi.data import Dataset import math import numpy as np class HMData(Dataset): # Dataset class for loading data def __init__(self, input_file, bin_size=100): self.hm_data = self.loadData(input_file, bin_size) def loadData(self,filename,windows): with...
2bae153b4f3a339038dba0ec630c2ce3bedad3766240efe6c72074e238b93183
Python
1,740
40
"""Read BrainVoyager vmr and export nifti.""" import os import numpy as np import nibabel as nb import bvbabel import pprint FOLDER = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives/rawdata_bv/sub-05/ses-01/anat' # FILE = f"{FOLDER}/sub-05_ses-01_uni_part-mag_run-01_MP2RAGE_denoised_IIHC_p...
3d57a2b18d13399b76258937e4a35567546e75882e8c9adce8b9c272eb64792d
Python
1,741
51
import os from importlib import resources as impresources from pathlib import Path import pandas as pd from ... import bids from ...bids.convert2bids import BidsConverter from ...load_annotations.siena import loadAnnotationsFromEdf BIDS_DIR = impresources.files(bids) DATASET = BIDS_DIR / "siena" def convert(root: ...
f4b84c76302bc6a094d313f001430bedad91e1b8855c79a78f90c0c9da243e4f
Python
1,741
49
import intel_extension_for_pytorch as ipex import torch from PIL import Image from diffusers import StableDiffusionPipeline def image_grid(imgs, rows, cols): assert len(imgs) == rows * cols w, h = imgs[0].size grid = Image.new("RGB", size=(cols * w, rows * h)) grid_w, grid_h = grid.size for i, ...
58479f1ad112e2fa68190cf05b006de2f11ddeb81605d6ebbb2726f58967dcf3
Python
1,742
53
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations from typing import TypeVar import pandas as pd from fairchem.core.components.benchmark import JsonDFR...
e8854b795ea4b38c608ef4b8c46672303bb16e53afd20a2a229cc9eba0b639f6
Python
1,742
47
import os import numpy as np import nibabel as nib import IVIMNET.deep as deep from hyperparams import hyperparams as hp root = '/mnt/d/fc-ivim-estimation' input_root = os.path.join(root, 'data') output_root = os.path.join(root, 'results') subs = os.listdir(input_root) times = [] for sub in subs: input_folder = ...