sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
a88ada240a4ee1c8c1172afc1b91b9a6dc6f5a3550fc3291645044a052de7de1
Python
1,031
30
import torch from rdkit import Chem import pandas as pd from serenityff.charge import Trainer, ChargeCorrectedNodeWiseAttentiveFP print("imports done") sdf_file = "../test146_combine/combined_multi.sdf" trainer = Trainer(device="cpu") trainer.model = ChargeCorrectedNodeWiseAttentiveFP() trainer.optimizer = torch.optim...
cb564ad794ba7fbe1e33f80d1f43af3d63fdb53d1621f7354665be0dd5ce5a09
Python
1,032
36
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 6 14:37:58 2021 @author: baris """ grid_seed = 1 output_path = ( f"{grid_seed}_{trajectories}_{poisson_seeds[0]}-{poisson_seeds[-1]}_{dur_ms}" ) storage_old = shelve.open( "/home/baris/results/poisson_seeds_seperate/grid-seed_trajectory_p...
368de47f51820abb1f9c090e8016075b17af97b0ceadbd248a0d68263a03acca
Python
1,033
33
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> import warnings as _warnings from sbi.inference.trainers.nre.bnre import BNRE from sbi.inference.trainers.nre.nre_a import NRE_A from sbi.inference.train...
17596da5188a5b20a41ec2868d2195ac1537b7d27725980a089a49ad78d6b394
Python
1,038
34
from setuptools import setup, find_packages setup( name="deepfastvision", version="1.0.2.3", description="A Python library for rapid prototyping of deep transfer learning vision models", author="Fabi Prezja", author_email="faprezja@fairn.fi", url="https://github.com/fabprezja/deep-fast-vision",...
134f05fd76ac5c00b5386cea9064df8f9a65b75faf5abd44a2d3a6f52bcb4560
Python
1,041
40
var.verboseRead = 0 read('t.nex') t = var.trees[0] read('d.nex') var.alignments[0].setCharPartition('cp1') t.data = Data() # Model for Part 0 pNum = 0 t.newComp(partNum=pNum, free=1, spec='empirical') t.newRMatrix(partNum=pNum, free=1, spec='ones') t.setPInvar(partNum=pNum, free=1, val=0.1) t.setNGammaCat(partNum=pNum...
f48207e19791de0b315183000f70a3c2c4fba7e374a2397d87ae7bac07e1605a
Python
1,042
29
from keras.preprocessing.text import Tokenizer from keras.preprocessing import sequence import logging from keras.utils import pad_sequences class KerasTokenizer(): def __init__(self, mode, vocab_size , pad_length): self.mode = mode self.vocab_size = vocab_size self.pad_length = pad_length ...
33c03fe6e1e364824dd1ed249132e86a140ecbb738912a33e29482af447e8b24
Python
1,046
27
### Functions for downloading from Google Drive ### ### Adapted from https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url import requests def download_file_from_google_drive(id, destination): URL = "https://docs.google.com/uc?export=download" session = requests.Sessio...
b3969afc63b7cb3374f10d4aca8f21eaedcf76aa97300056fbff8dde47409192
Python
1,049
37
#!/usr/bin/env python3 from flystim.stim_server import launch_stim_server from flystim.screen import Screen from flystim.trajectory import Trajectory import numpy as np from time import sleep def main(): manager = launch_stim_server(Screen(fullscreen=False, server_number=0, id=0, vsync=False)) manager.load_...
27007a53dc516e9ab6ffe046b52f06273c2aa6b222c94cc94389ebfa5e9186bb
Python
1,052
34
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 1 14:27:20 2022 @author: baris """ import os import shelve #variables to change shuffling = "non-shuffled" network_type = "no-feedback" # netowrk type for the filename path = "/home/baris/results/olli_data/" folder = "no-feedback_adjusted" # fol...
badcfe0950a6c1b8d55b568b7d1cefd4adc346ef0433cc0f078818d4c9b56421
Python
1,055
39
""" Class for holding information about the experiment to be performed. Includes trial type (0 or 1), experiment type (String), list of models to evaluate, nr of epochs to train the classifiers, percentage of data to use for validation and percentage of data to use for testing. """ class Experiment(object)...
9e16aab78b8007f7deac6ba3a062e29f180b9222cb0e13cc54da6ddf64a6a26a
Python
1,056
32
import json import numpy as np import torch from torch.utils.data import DataLoader from torch.utils.data import ConcatDataset from FOD.Trainer import Trainer from FOD.dataset import AutoFocusDataset with open('config.json', 'r') as f: config = json.load(f) np.random.seed(config['General']['seed']) list_data = ...
ad1fecbaf37dd48c43eda345761c721fec430d15a5f76d19fa8b486d5b4e0c61
Python
1,058
38
from abc import ABC, abstractmethod class ModelTrainer(ABC): """Abstract base class for federated learning trainer. 1. The goal of this abstract class is to be compatible to any deep learning frameworks such as PyTorch, TensorFlow, Keras, MXNET, etc. 2. This class can be used in both server a...
12ba213a97c73a724d0f3234bc5aa38dc30d8dd0e65d46907f00ba432c60f6ca
Python
1,062
34
#!usr/bin/env python #coding:utf-8 """ @author: Haidong Zhang @contact: haidong_zhang14@yahoo.com @time: 2021/1/17 16:02 @project: MalariaDetection @description: """ import numpy as np from sklearn.metrics import normalized_mutual_info_score, adjusted_rand_score from scipy.optimize import linear_sum_assignm...
dd78130081c81b1e81fc371c6f2a529399f308712eeaf04657921fd2e52baddc
Python
1,065
26
"""exsclaim_gui URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-...
4524422a103671204ab793a10d0f78d442598dc2935513e234c2f6806324b0f5
Python
1,066
32
import torch import torch.testing as testing from selbstaufsicht.models.self_supervised.msa import diversity_maximization as dm def test_distance_matrix(): msa = torch.tensor([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [1, 2, 3, 2, 1]]) distance_mat = dm.distance_matri...
d315f3a77970da91eafd4e6771ee4c80d9b4983fb7858856946a60f89debc9bf
Python
1,067
29
import torchvision.transforms.functional as F class Normalize(object): """Normalize a tensor volume given the mean and standard deviation. :param mean: mean value. :param std: standard deviation value. """ def __init__(self, mean, std, training=True): if isinstance(mean, list): ...
1919481fd6c7071fd9da4e3c90fe0c7ca86d3b970842aca221310bf9f9c8e3b7
Python
1,068
42
# Copyright (c) OpenMMLab. All rights reserved. from abc import ABCMeta, abstractmethod class TemporalFilter(metaclass=ABCMeta): """Base class of temporal filter. A subclass should implement the method __call__(). Parameters: window_size (int): the size of the sliding window. """ # If t...
a9dfd117510957c9a00fed8868c640e0ff2ffd17eee6f6454466e8df9b1dcd1b
Python
1,068
55
# Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org # Distributed under the MIT License. # (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT) from .ace import Ace, AceHF from .ani import ANI1, ANI1CCX, ANI1X, ANI2X from .comp6 import ( ANIMD, DrugBank, ...
e85f94e898192a38999bdbd4708465e89cae28a2fc265b7eab7aefda9a58db15
Python
1,071
31
def setUp(self): import os import shutil ov_binany_path=os.environ['OV_BINARY_PATH'] self.terminal = App.open("xterm -e " + ov_binany_path +"/designer --no-session-management --play-fast Test_ROCCurve.xml") # NOSONAR while not self.terminal.window(): wait(1) # NOSONAR #def takepict...
1416c15509028d005f4c64c2219be7ae475f8e0eb04ab8cc69a63f7617a66269
Python
1,072
32
from __future__ import annotations from typing import Optional class ToCEntryError(Exception): """Generic Exception for errors related to the table of contents and streams""" ... class ToCStreamError(Exception): """Exception related to ToC streams""" ... class ToCNoSuchChildError(ToCEntryError): ...
cd915145f5afea1db54f8da2fcbf06528c877859936e7a2b8d0aa90b51423d8e
Python
1,072
43
# -*- coding: utf-8 -*- """ Extract ======= Main extraction routine. Run from the command line to start extraction. author: Damian Wilary email: dmw51@cam.ac.uk """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals i...
9626d2f67e67aa37b8ab21b592e5797f3caa0d6eb46ab13cd0c278df4a763e30
Python
1,074
26
import numpy as np import dgl import torch ## https://blog.csdn.net/znsoft/article/details/114515868 def x_message_func(edges): # 0.8 msg = (edges.dst['nodegrid'] - edges.src['nodegrid']) - (edges.dst['nodereg'] - edges.src['nodegrid']) ## h*norm 更新边权重 源头点的h*源头点的正则化参数 msg = np.clip(msg, -2, 2) ## ...
cfb6bdd5cc6d291dc6e696a8ffb99b8933b5e5aa6218aa6b19cf98acf921f939
Python
1,074
34
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import DETECTORS from .panoptic_two_stage_segmentor import TwoStagePanopticSegmentor @DETECTORS.register_module() class PanopticFPN(TwoStagePanopticSegmentor): r"""Implementation of `Panoptic feature pyramid networks <https://arxiv.org/pdf/1901.02...
cffef3607195367f808af7fcb9b878a3355ae14f042b4a001ce07c7f37d9b24c
Python
1,074
35
import torch class ToTensorScale: def __init__(self, mask_type="long", maxv_im=None, maxv_lb=None, training=True): """ Convert numpy array to Torch.Tensor """ self.training = training self.mask_type = mask_type self.maxv_im = maxv_im self.maxv_lb = maxv_lb ...
20977c98de680ac52836724bb49e36ae603f2ac18b37a6cbec873673b6cd6070
Python
1,076
42
import matplotlib.pyplot as plt def remove_keymap_conflicts(new_keys_set): for prop in plt.rcParams: if prop.startswith('keymap.'): keys = plt.rcParams[prop] remove_list = set(keys) & new_keys_set for key in remove_list: keys.remove(key) def multi_slic...
0d0e5e8d98e2c6fc302c0787299b8ec373d174b2ba953be2f0d3be9f5cd245b9
Python
1,078
35
from os import path from setuptools import setup here = path.abspath(path.dirname(__file__)) with open(path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() CLASSIFIERS = [ "Operating System :: OS Independent", "Intended Audience :: Science/Research", "Programming Language...
0315bed8339e0ff48e15bbeb59cc2df18fdea231181ca829cd418a29b72d897c
Python
1,083
31
from data.updated_labels.data_reader import UpdatedLabels # data = ManualLabels(outcome = 'any_cancer', text='IMPRESS') data =[{'id':'any_cancer_IMPRESS','type': 'updated_label' , 'params': {'outcome': 'response', 'text': 'NARR+IMPRESS', 'training_split':0 , 'cloud':True}}] # data = ManualLabels(outcome = 'any_cancer...
a05d2be14bdac9690135a2e93b61e655869182ea4183776d37b0cf9595354fcf
Python
1,083
31
""" This module provides different evaluation strategies for oligonucleotides and their sets based on various scoring criteria. """ from ._oligo_scoring import OligoScoring from ._scorer_base import BaseScorer from ._scorer_region_property import IsoformConsensusScorer, OverlapTargetedExonsScorer, OverlapUTRScorer fro...
c9878fc1c5a62d0f7679614437cece3b96f111bd7d9ce98568c32d20d03bc3fd
Python
1,084
32
import numpy as np from importlib import reload import sys sys.path.insert(2,'support') import functions reload(functions) import functions as f import parameters reload(parameters) import parameters as p direc = sys.argv[0].split('script')[0]+'data/' noise_type = f.poisson_noise tuning_curve = f.vonmises_tuning_curv...
78a9e3c2ffc45e6b2b202f0e2d2bdd1b257c3ee6543b8f82a7da58a28c54dc86
Python
1,085
29
import torchvision.transforms.functional as F class Normalize(object): """Normalize a tensor volume given the mean and standard deviation. :param mean: mean value. :param std: standard deviation value. """ def __init__(self, mean, std, training=True): if isinstance(mean, list): ...
b8fbf6dbdd63a569755feaf5e2a537c45a1b7c482ec465242192cbf191912222
Python
1,086
30
import pytest import eagerpy as ep import foolbox as fbn def test_plot(dummy: ep.Tensor) -> None: # just tests that the calls don't throw any errors images = ep.zeros(dummy, (10, 3, 32, 32)) fbn.plot.images(images) fbn.plot.images(images, n=3) fbn.plot.images(images, n=3, data_format="channels_fir...
e75cd1b11df119db003aa13357279003f8e36bfacdf8b9200f763035303bdf0f
Python
1,086
26
from torchvision import transforms from base import BaseDataLoader from dataset.mnist_split_dataset import MnistSplitDataset from dataset.mnist_synthetic_dataset import MnistSyntheticDataset class MnistDataLoader(BaseDataLoader): """ MNIST data loading demo using BaseDataLoader """ def __init__(self...
2145371313e4d8827b75d10b40b0c18117e128c698e41f115fd40c7c42509ca1
Python
1,090
36
#!/usr/bin/env python # Copyright [1999-2017] EMBL-European Bioinformatics Institute # # 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 # # Unl...
a61b3ed912e5145dbc7f4fb3334cde53fcc673f50e15857136dc488edb837cbe
Python
1,093
39
from typing import List, Tuple import pytest import foolbox as fbn import foolbox.attacks as fa from conftest import ModeAndDataAndDescription def get_attack_id(x: fbn.Attack) -> str: return repr(x) # attack attacks: List[Tuple[fbn.Attack, bool]] = [ (fa.SpatialAttack(), False), (fa.SpatialAttack(grid_...
8c3a909262c63221c1633bcaf0f2c63579b2204f4ef193c651d1f133c86a29ba
Python
1,095
28
#!/usr/bin/env python # Convert calls from Canvas, cn.MOPS, CNVnator, ERDS, Genome STRiP, or RDXplorer to a common format # Usage example: # convert_CNV_calls_to_common_format.py input_filename name_of_caller # name_of_caller must be one of "Canvas", "cn.MOPS", "CNVnator", "ERDS", "Genome_STRiP" (note underscore), or ...
0d26f9b3dc59e8292fa6f65604c5171bec3fc6e4988b187316c1b565eb6c7dff
Python
1,096
40
var.verboseRead = 0 var.warnReadNoFile = 0 read('d.nex') d = Data() d.compoSummary() read('simTree.nex') t = var.trees[0] t.data = d c1 = t.newComp(free=1, spec='empirical') c2 = t.newComp(free=1, spec='empirical') # Put the c1 comp on all the nodes of the tree. Then put c2 on the # root, over-riding c1 that is alre...
8816255e39a6bdc16c36519d737bb83390fcc0277246b55d787654f9e8e1944d
Python
1,096
48
import pandas as pd import requests df = pd.read_excel('EMPIAR.xlsx') df.head() df['Authors'] = df['Authors'].fillna('N/A') df['Size'] = df['Size'].fillna('N/A') df['Resolution'] = df['Resolution'].fillna('N/A') df1 =df.dropna(axis=0) df1 = df1.reset_index() df1 = df1.drop(columns=['index']) df1.to_excel('Processed_EM...
5a583c349648a3a0b1e6101f3c8bf7e5cfb3ab98df5f9f7e50a179842dabff65
Python
1,098
37
import numpy as np import pandas as pd import requests from ftplib import * import ftplib import wget import os import time #running for individual empiar_id = '11139' print(empiar_id) data_download_path = f'/home/ad256/Ashwin/Projects/cryoEM/repo/data_downloads/444_data/{empiar_id}' if not os.path.exists(data_downl...
763972b9e5411f620fd73cd7ac5a9e136ceefdc52802e0cdaa60e2b045e46f1d
Python
1,098
38
import metric.surface_distance.metrics as metrics # import torch import numpy as np def hd95_and_sd_all(output, target, misc): channel_num = output.shape[1] pred = np.argmax(output, axis=1) sds = [] hds = [] for i in range(1, channel_num): hd, sd = h95_and_sd_calc(pred, target, misc, i) ...
3cb8ae568705ff0665dbcfdbf6f83a33baee2fe7ca9582bac093816349139ce0
Python
1,100
31
import numpy as np import struct import os import sys data_name = sys.argv[-2] with np.load(data_name, allow_pickle=True) as f: x_train, y_train = f['x_train'] / 255, f['y_train'] x_test, y_test = f['x_test'] / 255, f['y_test'] dest_dir = sys.argv[-1] interval_train, interval_test = 5 / (x_train.flatten() +...
73ea8d611b4b7987b90e8a6718a040eff7d547c8ccff6661e2c7d2eb35d6d7cf
Python
1,100
49
''' Convert ERDS output to a common format ''' import myvcf import SV import os class ERDS: @staticmethod def doparse ( erds_data ): E=erds_data #if type (erds_data) is str: E = erds_data.rstrip('\n').split('\t') chrom=myvcf.vcf.get_chrom (E) start=myvcf.vcf.get_pos (E) length=abs(int(myvcf.vcf.get...
9effd709c54c650e1f45dcabb0716a394df31456701a2243ad6e9f6e5493bb1e
Python
1,100
35
# Imports from Classes.Survey import SurveyBase from kivy.app import App import pathlib import json # Survey Protocol Class class SurveyProtocol(SurveyBase): """ A demographic survey protocol for collecting participant information. """ def __init__(self, **kwargs): super().__init__(**kwargs)...
af375c1ddc0c10ae643478e5cedf00d7ed6d1c839b0051aa850edcf570fcdcfa
Python
1,100
26
from pydapsys.neo_converters.helper import DapsysToNeoHelper from pydapsys.neo_converters.interface import INeoConverter from pydapsys.neo_converters.ni_pulse_stim import NIPulseStimRecordingConverter class ExtraDependencyNotFoundError(Exception): package_name = "PyDapsys" def __init__(self, missing_name: str...
cf5ea2fc3df52242ba8d0cad06429f6364e1474393d5b9e81aeac0805fbf0091
Python
1,100
33
# Simulate data with more than one data partition. nTax = 5 taxNames = list(string.ascii_uppercase[:nTax]) dnaAlign = func.newEmptyAlignment(dataType='dna', taxNames=taxNames, length=300) read(r"#nexus begin sets; charpartition p1 = first:1-100, second:101-.; end;") dnaAlign.setCharPartition('p1') d = Data([dnaAlign])...
8700c41506313f3bf44f22e466c0fa92fa47ffa20441e72ca2c9c5ea608c936e
Python
1,102
28
#Model import tensorflow as tf from tensorflow import keras from tensorflow.keras import datasets, layers, models def top_k_categorical_accuracy(y_true, y_pred): return tf.keras.metrics.top_k_categorical_accuracy(y_true, y_pred, k=2) #Build model def model_build(num): # num = number of categories input_f = l...
a6e4db956891d1015c085e0c6f756bdeca41b5ebcdd5118e372881ef12ce1e85
Python
1,102
25
from base import BaseDataLoader from data_loader import my_transforms from dataset.brats_dataset import BratsDataset class BratsDataLoader(BaseDataLoader): def __init__(self, h5_filepath, batch_size, shuffle=True, validation_split=0.0, num_workers=1, training=True, img_size=224): if train...
b41222b803dc2920b7187b504710874e4407a77ed2caacf8042527d9198826cd
Python
1,103
36
import tensorflow as tf import numpy as np class ConvUnit(keras.layers.Layer): def __init__( self, filters, activation, normalization, convolution, kernel=3, name="conv3d", **kwargs ): super(ConvUnit, self...
69c87c2c5d21bcb16d05a613045af2a3e8b1f3ae664c360be0c1d9aed4f42504
Python
1,104
41
import matplotlib.pyplot as plt import json import numpy as np root = "/home/wangbowen/PycharmProjects/mmpose/work_dirs/hrnet_w32_coco_tiny_256x192/None.log.json" df = [json.loads(line) for line in open(root, 'r', encoding='utf-8')] loss_epoch = [] epoch_record = [] for i in range(len(df)): current_dict = df[i]...
1fdc29670c979c541aec99c9b9ab025e2d0a1b39e71dee1da1f35c891bfd6e93
Python
1,105
33
import metric.surface_distance.metrics as metrics import torch import numpy as np def surface_distance_avg(output, target, misc): channel_num = output.shape[1] sds = [] for i in range(1, channel_num): sd = surface_distance_calc(output, target, misc, i) sds.append(sd) return np.average...
327f4174b102600d344c61b3ee7df2d68175e5d4dddcda682a30c24d718eeeeb
Python
1,105
47
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression n = 36 start_end = 0.1 peak = 0.2 center = (n - 1) / 2 # 17.5 x = np.arange(n) a = (start_end - peak) / (center ** 2) y = a * (x - center) ** ...
49625d679ee47517963af3fba21c15aceff4f880823d4607652fa047f9a9c948
Python
1,105
41
import json import numpy as np class NumpyEncoder(json.JSONEncoder): """ JSON encoder that handles numpy types. Converts numpy arrays to lists and formats numpy floats with 4 decimal places for compact, readable output. """ def default(self, obj): if isinstance(obj, (np.ndarray,)): ...
25cf5f5f346896e0fd3ae51df4eecc8cd0b85651c9bcb31da66af186b7dc7576
Python
1,108
26
import numpy as np import torch class ToMask(object): """ Convert a 3 channel RGB image into a 1 channel segmentation mask """ def __init__(self, palette_dictionnary): self.nb_classes = len(palette_dictionnary) # sort the dictionary of the classes by the sum of rgb value -> to have ...
959b3194539750cb8f85fba692fe57e25665aef0b38db5d4c944aec9a8afc4c9
Python
1,114
39
def hook(self, theTree): """Write stuff during the MCMC. You get the stuff from the Mcmc (which is self) or from the current tree. Write whatever you like, however you like it. You will need to know how to get it, tho ... In this demo, I write out the gen number+1, the composition, and the ...
2a0c25a1eaf5438fd0d6ae8340ce7b8ceeec70afe9791e86c9c14c81eee8c1e3
Python
1,115
40
from os.path import join as _join from os.path import dirname as _dirname with open(_join(_dirname(__file__), "VERSION")) as _f: __version__ = _f.read().strip() # internal modules # ---------------- from . import devutils # noqa: F401 from . import tensorboard # noqa: F401 from . import types # noqa: F401 # ...
cdfa685c3d2691161c920a42b36bc9622f7fb32cad8ea87553b14ce2f1bcad1b
Python
1,115
39
from tqdm import tqdm import requests import grequests import urllib.parse import datetime import os SERVER_URL = os.environ.get("SERVER_URL", "http://dorresteintesthub.ucsd.edu:6541") def test(): request_url = "{}/classify?smiles={}".format(SERVER_URL, "CC1C(O)CC2C1C(OC1OC(COC(C)=O)C(O)C(O)C1O)OC=C2C(O)=O") ...
77c183e64f99e5256869b6fffad244fd3c6d0bae5151e9c75fc24237bb9ef3cd
Python
1,117
29
# -*- coding: utf-8 -*- # # This file is part of the taxopy package, available at: # https://github.com/apcamargo/taxopy # # Taxopy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of...
9756683cfc2592a5998bbe7bc5ce58b9f8cef2a4aabaf6a703e9dc0eee200962
Python
1,117
46
#!/usr/bin/env python3 # Copyright 2021 Tomoki Hayashi # MIT License (https://opensource.org/licenses/MIT) """Test code for Mel-spectrogram loss modules.""" import numpy as np import torch from parallel_wavegan.bin.preprocess import logmelfilterbank from parallel_wavegan.losses import MelSpectrogram def test_me...
d8f3c1b11df45ba67ff8e5563b8a808ddbed658e8c565af5653bafdd7e2a523f
Python
1,119
34
""" Software to support scientific reproducibility, attribution, and collaboration on the QIIME 2 platform. Core commands: - replay_supplement - replay_provenance - replay_citations These take a payload including QIIME 2 provenance information, and write replay documentation to disk. Core objects: - ProvDAG: A direc...
4cac105a6f08951ab7e40d3b81a501e67357548d5064aafe5f3491e036328ee0
Python
1,120
31
import torch import torchvision.transforms.functional as F from data_loader.my_transforms.normalize3d import normalize_common class NormalizeLabel3d(object): """Normalize a label rather than the image volume given the mean and standard deviation. :param mean: mean value. :param std: standard deviation val...
e00bd0ab2a3ca09c3672df2c23b99405caedcd2363276ed64aa9e02783ec0906
Python
1,121
32
# from model.builders.builders import build_full_network import os filename = os.path.basename(__file__) from copy import copy, deepcopy vocab_size = 20000 data_base ={'id':'progression','type': 'updated_label' , 'params': {'outcome': 'progression', 'text': 'NARR+IMPRESS', 'training_split':0, 'split_path':'splits_new...
1d8386882bb1d84f7334aa0f2a605fd2015cb629955b1400360c1f2509f5507e
Python
1,123
32
import logging class BaseCentralWorker(object): def __init__(self, client_num, args): self.client_num = client_num self.args = args self.client_local_result_list = dict() self.flag_client_model_uploaded_dict = dict() for idx in range(self.client_num): self.fla...
06f50c93b5683dec390eed41f591aec838b4ae0a8f9ba471d22e3450a344c220
Python
1,124
46
#!/usr/bin/env python import argparse import CNVworkflowlib #################################### ### Parse command-line arguments ### parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("samtools_depth_filename", type=str, nargs="?", default="-") args = parser....
3efba740ad1853ef4eee7705f32073fee9df8592d8437752a74c0403aeec9c77
Python
1,124
40
from concept_mapping import UMLSAPI import utils _umls_api_key = '148475b7-ad37-4e15-95a0-ff4d4060c132' def do_compute_subconcept(c, umls, container): try: subconcepts = umls.get_narrower_concepts(c) container.append((c, subconcepts)) except ValueError: print 'no subconcepts found for...
508148d6f83f4584d5fbe4b0e5cc999a7d593b5ee2f9db88128a932344fbfd82
Python
1,124
52
import pickle import os def saveVar(var, filePath): """ saveVar saves a var to a specified filePath INPUT: var: the variable to be saved filePath: the filepath you want to save the var, for example data/.../var.pckl. If the path does not exist, it creates it """ directory = os.path.dirnam...
cfeab4baede85e703d1ba8c587a030ee060e0f25b798f3bd71c562fb6a72774d
Python
1,125
30
import dftd4 from dftd4 import interface import numpy as np import pandas as pd from rdkit import Chem import matplotlib.pyplot as plt from tqdm import tqdm print("start dftd4 calculation", flush=True) mol_sup = Chem.SDMolSupplier("combined_multi.sdf", removeHs=False) sd_writer = Chem.SDWriter("mols_comb_dftd4.sdf") ...
433e2ca0be595c3cb34a3c0d8122f2ad6dd310c60ab234cca17464efd4ff7336
Python
1,128
39
import pytest from pathlib import Path from clipkit.clipkit import execute from clipkit.modes import TrimmingMode from clipkit.settings import DEFAULT_NT_GAP_CHARS here = Path(__file__) @pytest.mark.integration class TestBlockGappyMode(object): def test_simple_alignment(self): input_file = f"{here.paren...
926a000065fff3a9ea7719a8181023f8b0fd88062c7d8e4c3aacb2c22eea677d
Python
1,129
40
import glob import torch import numpy as np from torch.utils.data import Dataset import torch # Ignore warnings import warnings warnings.filterwarnings("ignore") def curvature(pulse): curves = [] for line in pulse: diff1 = np.array(np.gradient(-line * 100)) diff2 = np.gradient(diff1) ...
6434bf266c9560238b1953a19ed219fad424c6c8b6f216a2fc9bc67779f1f28d
Python
1,135
39
import numpy as np import pandas as pd import requests from ftplib import * import ftplib import wget import os import time #running for individual empiar_id = '10970' print(empiar_id) data_download_path = f'/home/ad256/Ashwin/Projects/cryoEM/repo/data_downloads/444_data/{empiar_id}' if not os.path.exists(data_down...
9adfa906e521e16c583959c51d840631493b420e5be2eaa0e2bc63ac4b1bda4d
Python
1,136
41
from typing import Union, Any, Optional import eagerpy as ep from ..criteria import Criterion from ..models import Model from .base import FlexibleDistanceMinimizationAttack from .base import T from .base import raise_if_kwargs from .base import verify_input_bounds class InversionAttack(FlexibleDistanceMinimizatio...
b3783661742e30cd7bb5c1123fa34ee3160cf72c1b40d415b57b26ed0e68e0f1
Python
1,136
54
from setuptools import find_packages, setup # Package meta-data. NAME = "consbi" DESCRIPTION = "simulation-based inference for computational connectomics" URL = "https://github.com/mackelab/synaptic-rule-inference" AUTHOR = "Jan Bölts, Philipp Harth" REQUIRES_PYTHON = ">=3.6.0" REQUIRED = [ "matplotlib", "num...
ae05f24675d95c80b3d070a7a042834db396a08d0a3d75bf725410eb8fc3a67e
Python
1,137
27
from nipype.pipeline.engine import Node, Workflow from shivai.interfaces.datasource import Direct_File_Provider def graft_swomed_infiles(workflow: Workflow): ''' Changes the datagrabber from a processing workflow to and identity interface that gets the file paths directly givent to the pipeline in SWOMed ...
d641abd14f22d17c6399a127777ec8aa5329a5746e6742493ba5a3ae77886ac4
Python
1,137
38
#!/usr/bin/env python # Copyright [1999-2017] EMBL-European Bioinformatics Institute # # 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 # # Unl...
bd346a5aae2f6bdcba88a3409ba00085c03b22b484c9e88175b349301d752ac7
Python
1,139
32
import os import json from torch.utils.data import Dataset from torchvision.datasets.utils import download_url from PIL import Image class nocaps_eval(Dataset): def __init__(self, transform, image_root, ann_root, split): urls = {'val':'https://storage.googleapis.com/sfr-vision-language-research/datase...
c31fb8de9c9897ca780138e6e9d151e755b89b0186395a15f02fffc00e578600
Python
1,139
33
# construct 3D matrices as nodextsfeaturesxsubj import h5py import numpy as np import time import glob datapath = '/path/to/hctsaMEGoutputs/'; # MEG files tsID = np.loadtxt(datapath + 'HCP_MEG_outputs/Schaefer100/sharedIDall_segments_pca_Schaefer100_fullSet_80.txt') tsID = np.array(tsID).astype(int)...
25ed1ed880f1925375bc8f50ff7649c00b624545d4dce9043eaac3179c343c1b
Python
1,140
44
from setuptools import setup, find_packages setup( name='PytorchTemplate', version='0.5.0', description='Annotation tool for Medical Image', author='Qi Chang', author_email='tommy.qichang@gmail.com', license='GPL', home_page='', packages=find_packages(), include_package_data=True, ...
b388cee0fc8922714e90f4303ee50f329401e7964617a4d8b6f4c514fcd1a91d
Python
1,141
50
''' Author: ---- Date: 2022-04-06 10:57:29 LastEditors: GhMa LastEditTime: 2022-10-02 19:24:00 ''' import torch import torch.nn as nn import numpy as np import math class Seq2ANN(nn.Module): r""" Forked from spikingjelly """ def __init__(self, *args): super().__init__() if len(args) ==...
c011d7801c700da33a90c02ad9778b2e0a71406790991bcf1924a6961fd3b038
Python
1,144
27
from distutils.core import setup from distutils.extension import Extension import glob mySources = glob.glob('*.cpp') toRemove = [ 'main.cpp', 'testMatrix.cpp', 'testQDist.cpp' ] for fN in toRemove: mySources.remove(fN) setup(name="PackageName", ext_modules=[ Extension("scqdist", ...
0633d574b50909859adb6c1d3a412e53846e84c5862ed250aed68446a3bd102c
Python
1,146
15
# Copyright (c) 2023 IBM Research. All Rights Reserved. # # Code accompanying a manuscript entitled: # "On the visual analytic intelligence of neural networks" NUM_IMAGES = 6 MAX_COLOR_INTENSITY = 60 NUM_RIDDLES = 45 RIDDLE_IDS = ['color', 'orientation', 'straight_line', 'curve_line', 'alignment_point_on_line'...
8231da8e9b9101adf7d94ae33f8c1b8735445fbff8edeb9288bae146587ad268
Python
1,147
39
from mpi4py import MPI from .central_manager import BaseCentralManager from .central_worker import BaseCentralWorker from .client_manager import BaseClientManager from .client_worker import BaseClientWorker def FedML_init(): comm = MPI.COMM_WORLD process_id = comm.Get_rank() worker_number = comm.Get_size...
3a03cab0efa38ea406b8cd8421fef0e21f0b53e1ef440868c94425a38dcfea89
Python
1,148
38
import sys import os sys.path.append(os.path.abspath("tqDist-1.0.2/tqDist")) import pytqdist if 1: # This does not need p4 # spaces in the string are not allowed. # eg taStr = "(A, B, (C, (D, E)));" taStr = "(A:0.1,B:0.3,(C:0.1,(D:0.1,E:0.1)thisName:0.1,F:0.1):0.1)theRoot;" tbStr = "(B:0.2,A:0.55,(...
aa3404642b4449c076aa06990701187c4708969aaa34f9ed4f96807c601b2719
Python
1,150
34
#!/usr/bin/env python """ Test Measures Script """ import logging import pandas pandas.set_option("display.max_rows", None) logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO, format="%(message)s") def _summarize(summary_df, measures_df, column, threshold): measures_df = measures_df....
a75c21c56e944d16e68de883271deffb719655fbf6ea7f3f2f683ad69ecb7ad2
Python
1,151
34
import numpy as np from .common_func import cropImage2DAt class CropPadding: def __init__(self, load_size, training=True): """ Padding the image: C x H x W, if H or W less than load_size, and will keep the overflow side. """ # TODO: Not just support static filling of the padding, ...
7e3a79cedaaa1d4bccc44ea8eca2ce947ab11e8e6f51727af0df00d3d4117ba8
Python
1,152
27
class SelectChannel: def __init__(self, img_ch=[0], label_ch=[0]): """ Just select image channel(s) and label channel(s) by given img_ch and label_ch array. leave the array empty if don't want select the channel """ assert isinstance(img_ch, list), "Image channels should be a...
fced695efb46c9c5a1ba56bddd8c0090df58a118a929e66b36af6090fa197095
Python
1,154
39
import pytest from pathlib import Path from clipkit.clipkit import execute from clipkit.modes import TrimmingMode from clipkit.settings import DEFAULT_NT_GAP_CHARS here = Path(__file__) @pytest.mark.integration class TestGappyoutMode(object): def test_simple_alignment(self): input_file = f"{here.parent}...
06ed97ab57ab96bd465d893711c70b9543cff5734183ac3ce260e773d349c397
Python
1,155
29
import logging class DecentralizedWorker(object): def __init__(self, worker_index, topology_manager): self.worker_index = worker_index self.in_neighbor_idx_list = topology_manager.get_in_neighbor_idx_list(self.worker_index) logging.info(self.in_neighbor_idx_list) self.worker_resul...
d5db6cdc214dd71384fe6e00c3a4b66a141cb5e392d92df61bc659de9cff3946
Python
1,156
36
import numpy as np import random class RandomSwitchxy: def __init__(self, training=True): self.training = training def __call__(self, sample): """ Randomly switch X-Y axis of the numpy image Args: sample: {'image':..., 'mask':...} image size: [c, h, w] ...
1644bb2919b477bdc371c67153eb18e9ed08c724abd7a890dbed738eb3b17aaa
Python
1,157
40
# Copyright (C) 2024-2025 ETH Zurich, Niels Maeder and other DASH contributors. """Pytest configuration file.""" from collections.abc import Sequence import pytest def pytest_addoption(parser: pytest.Parser) -> None: """Add cli option to include slow tests. Args: parser (pytest.Parser): pytest par...
785c0546df81a79f415e8505810887d8d33951deee028bdc8e803613a15537c2
Python
1,157
35
# Author: Fabi Prezja <faprezja@fairn.fi> # Copyright (C) 2023 Fabi Prezja # License: MIT License (see LICENSE.txt for details) import os import sys sys.path.insert(0, os.path.abspath('../../')) # Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the d...
e1009084a1aaa8d32c6d4dc4289d92dc944a0b145d8bad892591410204d9f1cf
Python
1,158
29
import logging class TA_DecentralizedWorker(object): def __init__(self, worker_index, topology_manager): self.worker_index = worker_index self.in_neighbor_idx_list = topology_manager.get_in_neighbor_idx_list(self.worker_index) logging.info(self.in_neighbor_idx_list) self.worker_re...
daa94542a43a8df8d96113b92104ddcd925a43f6e45465f67a78f3d7361088f5
Python
1,159
45
from typing import cast, Any import eagerpy as ep from ..types import BoundsInput, Preprocessing from .base import ModelWithPreprocessing def get_device(device: Any) -> Any: import tensorflow as tf if device is None: device = tf.device("/GPU:0" if tf.test.is_gpu_available() else "/CPU:0") if is...
52df9822110882e8cbfb1a52342552f2ae12ebd90f28d2b3bbb48bfa7f6a809c
Python
1,163
38
import unittest import pandas as pd import numpy as np from weibull_mlp import datas, make_imaging_sheet_full class WeibullTest(unittest.TestCase): def test_datagen(self) -> None: df2 = pd.read_csv("./metadata/data_processed/weibull_model_adni.csv").set_index( "RID", drop=True ) ...
7d57694620b9baa9fd012b9d57817066086c8b594a479c38d44f8cf5482e66e1
Python
1,166
39
import pytest from pathlib import Path from clipkit.clipkit import execute from clipkit.modes import TrimmingMode from clipkit.settings import DEFAULT_NT_GAP_CHARS here = Path(__file__) @pytest.mark.integration class TestHeterotachyMode(object): def test_simple_alignment(self): input_file = f"{here.pare...
b8c198dfd6ccb17c4030af47574368abb47b1924ca761f9e3ec4ca3d278018b9
Python
1,166
40
#!/usr/bin/env python3 """ Pushes a 4-channel sinusoidal signal to LSL for testing the LabStreamingLayer acquisition-server driver. Requires pylsl: pip install pylsl """ import math import time from pylsl import StreamInfo, StreamOutlet CHANNEL_COUNT = 4 SAMPLING_RATE = 250.0 CHANNEL_NAMES = [f"Sin {i + 1}" for i in...
19a88f2194aff71fa56568ab6b8a375eff01123262693627bc62350a4d2ad362
Python
1,168
28
import numpy as np from skimage.transform import resize class MoveAxis: def __init__(self,from_axis, to_axis, move_label=False, training=True): """ Resize the image: C x H x W to the C x load_size[0] x load_size[1] order will apply to image and mask separately. 0: nearest-neighbor, 1: bi-l...
a30558f47722539cb66f95c710c1c89388babd48e315cf77adb3149204ba585b
Python
1,170
57
import SV import os import re class cnMOPS: seqnames=0 start=1 end=2 width=3 strand=4 sampleName=5 median=6 mean=7 CN=8 @staticmethod def parse_CN (CN): i=re.sub ('CN', '', CN) if int(i) > 2: return 'DUP' else: return 'DEL' @staticmethod def doparse ( input_line ): E=input_line.rstrip('\n')....
f3e9dcbceffe91a9575881543af88a60225e9911e5e920b4867f7c7e6ee3dbb1
Python
1,173
32
from sklearn.mixture import GaussianMixture from sklearn.cluster import KMeans, AgglomerativeClustering import numpy as np def cluster_gmm(A, B, num_clusters): """Gaussian Mixture clustering""" estimator = GaussianMixture(n_components=num_clusters, covariance_type='tied', # c...
9cc8c012748ea0095bceed7949df9bbca6fdd2c75e0e981a997f14c0422f01f3
Python
1,181
42
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch from mmdet.utils.util_random import ensure_rng def random_boxes(num=1, scale=1, rng=None): """Simple version of ``kwimage.Boxes.random`` Returns: Tensor: shape (n, 4) in x1, y1, x2, y2 format. References: ht...
8de2ef3b978c4b43d688ed860ee9bcdf7549b0df3eb083f97e4b126e7e39131b
Python
1,184
59
''' Author: ---- Date: 2022-04-08 11:09:07 LastEditors: GhMa LastEditTime: 2022-10-02 19:25:10 ''' import torch import torch.nn as nn from .snn_modules import tdLayer, BN class ToyNet(nn.Module): r""" """ def __init__( self, num_classes = 10, hidden = 64, norm_layer = Non...
30a68fadba4602779538494d3c077fff8a53af0813eb14757ce4b160abb51e8a
Python
1,185
44
#!/usr/bin/env python3 from flystim.stim_server import launch_stim_server from flystim.screen import Screen from flystim.trajectory import Trajectory import numpy as np from flystim.draw import draw_screens import os from time import sleep def main(): """.""" save_dir = '/home/mhturner/CurrentData/' scre...
8d2244c327dd1e953d4e7b880fbf89c2052505cd6322490637c1c7304786a130
Python
1,185
39
import pytest from pathlib import Path from clipkit.clipkit import execute from clipkit.modes import TrimmingMode from clipkit.settings import DEFAULT_NT_GAP_CHARS here = Path(__file__) @pytest.mark.integration class TestCompositionBiasMode(object): def test_simple_alignment(self): input_file = f"{here....