sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
e5b03f8dbe73f3a58dcbbe4a47b3990227fa09cdd704586607d2bc7abbc49c3f | Python | 1,304 | 38 | import os.path as osp
from PIL import Image
from torch.utils.data import Dataset
class Dataset(Dataset):
'''
Class to load the dataset
'''
def __init__(self, data_dir, dataset, transform=None):
'''
:param data_dir: directory where the dataset is kept
:param transform: Type of t... |
5d15a1cd8db080f484eef10bae564c1ddc31dc5cb58e2363856d2410394cb083 | Python | 1,305 | 39 | # Now just import from pytorch, add custom operation if need
from torchvision.transforms import (Compose, CenterCrop, ColorJitter, Normalize, Pad,
RandomCrop, RandomGrayscale, RandomResizedCrop,
RandomHorizontalFlip, RandomVerticalFlip, Resize, ToTensor)
from .simclr... |
ba02077caeef3b2167e12813e025b6521c24d7a00bd1d60f24c56b664c86ac31 | Python | 1,305 | 35 | # -*- coding: utf-8 -*-
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from pygenometracks.utilities import MyBasePairFormatter
from tempfile import NamedTemporaryFile
import pytest
mpl.use('agg')
outfile = NamedTemporaryFile(suffix='.png', prefix='pyGenomeTracks_test_',
... |
5fac24dc43567226bf40676024f35cf30083c6fb6ce8f985065d116829d35882 | Python | 1,309 | 49 | import os
import subprocess
import sys
import pytest
from xgboost import testing as tm
PYTHON = sys.executable
DEMO_DIR = tm.demo_dir(__file__)
PYTHON_DEMO_DIR = os.path.join(DEMO_DIR, "guide-python")
@pytest.mark.skipif(**tm.no_cupy())
def test_data_iterator() -> None:
script = os.path.join(PYTHON_DEMO_DIR, ... |
95c941fe6e3cb6fcbb0d8752c8cfe93aae131e7c68c5033414dcc29746ff9a5f | Python | 1,309 | 18 | from devices._poke import _Poke
class Five_poke():
# 5 IR beams, each with LED.
def __init__(self, ports, rising_event_1='poke_1', falling_event_1='poke_1_out',
rising_event_2='poke_2', falling_event_2='poke_2_out',
rising_event_3='poke_3', fal... |
f1df1dfc600f3086168d03bf5455684b063fd791fcb7de999e3036e6953bf4fa | Python | 1,310 | 50 | import os, pathlib, pytest
from click.testing import CliRunner
from pytest import fixture
from .test_full import (
prerequisites_hook_download_data,
prerequisites_constructTrainingCSV,
)
def pytest_addoption(parser):
parser.addoption(
"--device", action="store", default="cpu", help="device optio... |
17cde94fbc9436058a68e9453377d04feadf8cea83b3bb4942cf1d2b1721224f | Python | 1,311 | 37 | import wx
from cellprofiler_core import pipeline
from cellprofiler_core.pipeline.io._v6 import dump
from cellprofiler_core.pipeline import PipelineLoadCancelledException
class Pipeline(pipeline.Pipeline):
def create_progress_dialog(self, message, pipeline, title):
return wx.ProgressDialog(
tit... |
6defcb65e5c007b88e9c31e55710c789fcb1694e3ab0e587f144088a2623bad5 | Python | 1,314 | 48 | import torch.nn as nn
import torch.nn.functional as F
class IncUpsamplingModule(nn.Module):
def __init__(
self,
input_channels,
output_channels,
ConvTranspose,
Dropout,
InstanceNorm,
dropout_p=0.3,
leakiness=1e-2,
conv_bias=True,
inst... |
c8c5e60aefbf9caa609fffc5682745d7e1cef4c7c02d4bf91fcbb6aef64a3447 | Python | 1,314 | 40 | """aihwkit example 19: Analog summary on LeNet.
Extracts analog information in the form of a printed table.
The information can also be accessed via the returned AnalogInfo object.
"""
# pylint: disable=invalid-name
# Imports from PyTorch.
from torch import nn
# Imports from aihwkit.
from aihwkit.nn.conversion impor... |
67f7eca8c987941ff4076ca813929b6c4b1dbb78bf6a773405c2f2d3f841cd4f | Python | 1,316 | 44 | import pdb
import torch
from torch import nn
from DT_for_WDN_leak_localization.inference.observation import ObservationModel
from DT_for_WDN_leak_localization.inference.noise import ObservationNoise
import matplotlib.pyplot as plt
class Likelihood():
def __init__(
self,
observation_model: Observa... |
022126a87f11eb04a30eccb11fbdb675376baf9a5eb533a6de0107cbc734b1c4 | Python | 1,318 | 37 | import sys
from ptsa.extensions import morlet
from scipy.stats import describe
import numpy as np
def fixme():
num_freqs = 8
min_frequency = 3.0
max_frequency = 60.0
morlet_transform = morlet.MorletWaveletTransform(5, np.logspace(np.log10(min_frequency), np.log10(max_frequency), num_freqs), 1000, 40... |
0efa8e4e986e318546bf23a5112f71c042a3f4b5cc000fcc7b981dd9f0812869 | Python | 1,318 | 37 | from cellprofiler_core.preferences import get_default_colormap
from ._workspace_view_row import WorkspaceViewRow
from ..artist import MODE_HIDE
from ..artist import MODE_LINES
from ..artist import ObjectsData
from ..utilities.workspace_view import bind_data_class
class WorkspaceViewObjectsRow(WorkspaceViewRow):
... |
8ccc759a1efa89208fa0b83b0338763154af348ae258a3edd3b7f94c8e49c0c0 | Python | 1,321 | 58 | """
Demo for using feature weight to change column sampling
=======================================================
.. versionadded:: 1.3.0
"""
import argparse
import numpy as np
from matplotlib import pyplot as plt
import xgboost
def main(args: argparse.Namespace) -> None:
rng = np.random.RandomState(199... |
6747b4df31229683a7b03062dc2f6a6b4d2199e8c5e7c34e2bd2e1ad4e1ff1d3 | Python | 1,324 | 30 | from src.models.tabular.widedeep.base import WDBaseModel
from pytorch_widedeep.models import TabMlp
class WDTabMLPModel(WDBaseModel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def build_network(self):
self.model = TabMlp(
column_idx=self.hparams.column_idx,
... |
94ce67fd4b9e707c2f7dccc8c735f285adac827e4d0ac8bb418b2901481f62fc | Python | 1,324 | 44 | import sys
import torch
class Net(torch.nn.Module):
def __init__(self, args, inputsize, taskcla, labsize, nhid, nlayers=1):
super(Net, self).__init__()
ncha, size, size2 = inputsize
self.taskcla = taskcla
self.args = args
self.nlayers = nlayers
self.a... |
6d2661f5b580c006d40dc5398c01ae637a6cf4553191b2a4ac514006e239d3a1 | Python | 1,329 | 28 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: joaosds
"""
import numpy as np
path = '/scratch/c7051184/'
data_dict = {}
n2 = 12 + 1 # number of files + 1
n1 = 11
data_dict = {'data_'+str(i) : np.load(path + 'station{0}/temptestmap{0}.npz'.format(i)) for i in range(n1,n2)}
## Merge arrays
# DataX -> [si... |
9f1b060ce50d8e107d862d32402d557f4ffbec3b6d00bb81c935d91ba94ba766 | Python | 1,329 | 35 |
"""
MIT License
Copyright (c) 2022 Pawan Goyal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, ... |
0b39efaa9812f1208d4ce9e8f2deefe7d00834f08560179b0f5b0a7a87af9e89 | Python | 1,331 | 35 | from .mnist import MNIST
from .cifar_10 import Cifar10
from .pascal_voc import PascalVOC
from .queue import PreprocessQueue
from .m2nist import M2NIST
from .vessel12 import VESSEL12
from .svessel import SVESSEL
from .isles2018 import ISLES2018
try:
from .transforms import Crop, CropVessel12
except ImportError as e:... |
42b8f6cc97e1f2cbd5d33e2a727f3226b39a2f789f9b35f2d69947496b616530 | Python | 1,333 | 67 | import torch
from torch import nn
import pdb
class SupervisedWassersteinAE(nn.Module):
"""
Wasserstein Autoencoder
"""
def __init__(
self,
encoder: nn.Module,
decoder: nn.Module,
):
super().__init__()
self.encoder = encoder
self.decoder = decod... |
d4d016410ef8e73bbd3a4256c25954e3ee41028e18a9cd6b868d47b565178c33 | Python | 1,334 | 37 | import re
from ._setting import Setting
from ._validation_error import ValidationError
class RegexpText(Setting):
"""A setting with a regexp button on the side
"""
GUESS_FILE = "file"
GUESS_FOLDER = "folder"
def __init__(self, text, value, *args, **kwargs):
"""initialize the setting
... |
018e108df1baebfd5f79704248bab7f8faee37ada15aa2a4c7155687b2fec9d8 | Python | 1,337 | 39 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Plot some examples of sensor configurations from an optimization run. Read the
run data from the folder given as a parameter. If the output folder given as
a second parameter, also save the images there.
"""
import sys
from mayavi import mlab
from megsimutils.viz impo... |
8068b3f13f16003bfd9c49b86a8038b44989f5b6b82701b86e4c86a867cd60f5 | Python | 1,338 | 38 | # -*- coding: utf-8 -*-
from . GenomeTrack import GenomeTrack
import numpy as np
class TextTrack(GenomeTrack):
SUPPORTED_ENDINGS = ['.txt'] # this is used by make_tracks_file to guess the type of track based on file name
TRACK_TYPE = 'text'
OPTIONS_TXT = """
height = 3
title =
text =
# x position of text... |
30e7d20e770518919bf8440ff6c1469f4cae2a95f4d742288b628dc2db5a7b1f | Python | 1,339 | 40 | import SimpleITK as sitk
def convert_to_nifti(input_dicom_directory: str, output_file: str) -> None:
"""
This function performs NIfTI conversion of a DICOM image series.
Args:
input_dicom_directory (str): The path to a DICOM series.
output_file (str): The output NIfTI file.
"""
pr... |
f9e954dddae1dca7883b829f910c4ed44c6d5e753f9bff230ac5c15ed7935254 | Python | 1,339 | 35 | import torch
import torch.nn as nn
class GradientLayer(nn.Module):
def __init__(self, model):
super(GradientLayer, self).__init__()
self.model = model
def forward(self, x):
x.requires_grad_(True)
c = self.model(x)
# dc_dt, dc_dx, dc_dy = torch.autograd.grad(c, x, grad... |
f047b1c084dc426da68283e58b105205e7db5b82bc0e4ed4b7be08758fbc8e6b | Python | 1,340 | 42 | import nibabel as nib
import numpy as np
from dipy.core.gradients import gradient_table
from dipy.io.streamline import load_tractogram
from dipy.tracking.life import FiberModel
from traitlets import Bool, Float, List
from mrHARDI.base.application import (mrHARDIBaseApplication,
... |
6c0cb357f1c03eeb0644f72d7bd71ae1dd8222fad7c03e14d0c84e5e68282084 | Python | 1,345 | 42 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023 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.
#
# Any... |
abe1e293c9f6c6e3900351bbdd9ecaf91e9636b8e65509340459a84b8980bd53 | Python | 1,349 | 38 | """
Plot an example of a scalp array. If the output folder given as
a parameter, also save the image there.
"""
import sys
from mayavi import mlab
from megsimutils.arrays import BarbuteArrayScalp, BarbuteArraySL
from megsimutils.viz import _plot_anatomy
R_ENCL = 0.3 # m, radius of an invisible sphere to plot to force... |
9555b500d5db48279a558eb326dfabd453ed7f14c33f4a75e50f68e95668b568 | Python | 1,351 | 49 | """
Example code for processing data and performing the infrerence of GLMs.
@author: JingyiGF
"""
from .optitracking_lib import *
from .ratemap_lib import *
from .model_selection import *
from .process_data import *
from .calc_backwards_scores import *
# load the data
a_file = open('/.../clean_data_johnjohn_210520_s... |
2974fac6977fe5b142e01269fa715be0f493704a9c2aae18cfe35ebc5ca58603 | Python | 1,353 | 33 | """
Generate predictors for word-level variables
See the `explore_word_predictors.py` notebook for more background
"""
from pathlib import Path
import os
import eelbrain
language = 'French'
DATA_ROOT = Path(os.path.dirname(os.path.abspath(__file__))).expanduser()
STIMULUS_DIR = DATA_ROOT / 'stimuli' / language
PRED... |
eced479b5d67aba0435bbdc14203df30befe087376d3d4caad322d1d20288635 | Python | 1,356 | 39 | import os
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2"
import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
import numpy as np
import cv2
import resnet
import config
def load(saver, sess, ckpt_path):
saver.restore(sess, ckpt_path)
print('Restored model par... |
3ff187e88dc7cbae0764277e92b38527b977091dd28dc48409675578878254b1 | Python | 1,363 | 38 | """
Author: Mingjian He <mh1@stanford.edu>
Testing function for importing numpy and torch libraries
"""
import torch
import numpy as np
def test_import_numpy_torch(dim=2):
"""
Due to a strange dependency on sys lib5.dll between numpy and torch in
macOS(osx-arm64), one must import torch first then numpy t... |
e4aec914551d648bd3189b8667c7747429c5625d8fcde4c6206a32bbeaded219 | Python | 1,363 | 45 | from sklearn import svm
from loadDataSet import getDataset
from saveClassifiers import saveSVMClassifier
X_train, X_test, y_train, y_test = getDataset()
#I used 7 parameters
clfs = [svm.SVC(kernel='linear', C=5000), svm.SVC(kernel='poly', C=5000), svm.SVC(kernel='rbf', C=5000),
svm.SVC(kernel='sigmoid')]
for ... |
7e7f8b076860bb0930bb398081b42b2944512fe316313a95e78f7f75c77a57cc | Python | 1,365 | 28 | # rvt.default quick TEST
import rvt.default
if __name__ == "__main__":
# class with default values for all visualization functions
default = rvt.default.DefaultValues()
default.save_default_to_file()
default.read_default_from_file(r"settings\default_settings.json")
dem_path = r"test_data\TM1_564_1... |
2ff255ed34c298a89a65066fdf5b9c82e9a218bdca8478636f5eace481fbe76f | Python | 1,366 | 62 | # -*- coding: utf-8 -*-
#
# validate_config.py
#
"""
Validate the configuration json file
"""
__author__ = "Ahmed Albuni"
__email__ = "ahmed.albuni@gmail.com"
import json
import os.path
from jsonschema import validate
from jsonschema.exceptions import ValidationError
import pkg_resources
# path = os.path.join(os... |
7ff5921aa63a257b98afcbc51f5ffa503a2df58f2608d1d6a12d538a44fd2211 | Python | 1,367 | 48 | import numpy as np
import torch
class UnilateralMse(torch.nn.Module):
"""
扩展单边的MSE损失, 用于控制输出层的期望fire-rate 高于 thresh
:param thresh: 输出层的期望输出频率
"""
def __init__(self, thresh=1.):
super(UnilateralMse, self).__init__()
self.thresh = thresh
self.loss = torch.nn.MSELoss()
de... |
1b6289fb59aa2d9612a4f648a464e11e44cfa796ecd80ad4d5a1d99dcda7e68a | Python | 1,368 | 36 | from ..segmentation import segmentation_adjacency
from ..graph import coarsen_adj, perm_features
def preprocess_pipeline(image,
segmentation_algorithm,
feature_extraction_algorithm,
levels,
connectivity=4,
... |
802b9b6120154f9a2f3339f3285d11cbaf4c12a57e70deef1789ad6f9ae8e492 | Python | 1,368 | 53 | import torch
from rdkit.Chem import AllChem
import pandas as pd
from rdkit import Chem
import numpy as np
from rdkit import DataStructs
import torch.nn as nn
import torch
def to_fp_ECFP(smi):
mol = Chem.MolFromSmiles(smi)
return AllChem.GetHashedMorganFingerprint(mol,2,2048)
def toarray(fp):
array = np.z... |
136d38b2644fb87ec5bf8ac13e48d55e6c4c3c1fd3cddda54c0755c69da13616 | Python | 1,370 | 56 | #!usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import click
from deprecated import deprecated
from GANDLF.entrypoints import append_copyright_to_help
from GANDLF.utils import logger_setup
def _verify_install():
try:
import GANDLF as gf
print("GaNDLF installed version:", gf.__versi... |
23401142dda4c758eee1aa9dc0e0bf388371ce4417e5af7a0702e95b33255339 | Python | 1,371 | 30 | from biopandas.pdb import PandasPdb
from src.utils.protein_utils import rigid_transform_Kabsch_3D
import numpy as np
import os
## Align receptor files for HDOCK or ATTRACT.
input_dir = '/path/to/hdock_or_attract/pdb_files/'
method = 'HDOCK'
file = 'aq_4aqa.pdb1_0.dill_'
ligand_filename = os.path.join(input_dir, fil... |
92e6de8c3c28d97d2ba121d814acbd3d94d9baa915fd8379d7158576d1cb7bba | Python | 1,372 | 41 | import csv
def csv_to_dict(filename, delimeter, has_header=False, key_col=0, item_col=1):
"""
CSV file has two columns
"""
values = {}
with open(filename, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=delimeter)
header_skipped = False
for row in csvreade... |
6fd540a87b6fca700aa20f99cbb5fca9aa6aa92689cd6b9440c8a2355b73af16 | Python | 1,376 | 49 | """
DilateImage
===========
**DilateImage** expands bright shapes in an image. See `this tutorial <https://scikit-image.org/docs/dev/auto_examples/applications/plot_morphology.html#dilation>`__ for more information.
|
============ ============ ===============
Supports 2D? Supports 3D? Respects masks?
============ ==... |
9671ac2672d79a60f45489e5346e1636574376971d40a33d7c4767062546f3cf | Python | 1,381 | 48 | import os
import shutil
import yaml
from click.testing import CliRunner
from ..cli import main
CSV_FILE_NAME = "redcap_hbn_sample.csv"
YAML_FILE_NAME = "redcap2rs.yaml"
CSV_TEST_FILE = os.path.join(
os.path.dirname(__file__), "test_redcap2rs_data", CSV_FILE_NAME
)
YAML_TEST_FILE = os.path.join(
os.path.dirna... |
e2e95d2ac1e12eb85944fbb1ccaef724009b8d23c1cc654247857a3ac7a50f9e | Python | 1,385 | 46 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
plt.rcParams.update({'font.size': 13})
x = list(range(1,21))
figpath = '../results/MLP_delta/top 1/'
datasets = ['lipo', 'freesolv', 'delaney']
def get_shot_result(dataset):
path = '../results/MLP_delta/top 1/' + dataset +'/tables/'
df = pd... |
a519955d3385f86586335b5ea20dc42645d15e071b79c6432e9e5809d67fb38e | Python | 1,387 | 46 | from ._setting import Setting
class BinaryMatrix(Setting):
"""A setting that allows editing of a 2D matrix of binary values
"""
def __init__(
self, text, default_value=True, default_width=5, default_height=5, **kwargs
):
initial_value_text = self.to_value(
[[default_value]... |
eaf25ca1fafc0f22358cdf79999bf1f25828dda1754db08c34fa809198731a29 | Python | 1,387 | 34 | """Build the quickstart data by subsampling the tutorial toy data.
The reference is a random subset of the spots in
tutorial/data/MousePosteriorToy.h5ad and the query a random subset of the
cells in tutorial/data/MouseSCToy.h5ad. Genes that do not vary within either
subset are dropped, because get_zscore cannot standa... |
4213d9393b81c261a0e0f487ce8102cefbe8cfd4ffd08fbe247b90406df829a8 | Python | 1,389 | 27 | from cli.experiment import *
# A simple example showing the minimal set of arguments needed to define an experiment.
simple_exp = Experiment(
name = 'simple_experiment',
start_date = '2016-12-01',
subjects = {1: 'm001',
2: 'm002'},
task = 'rand... |
df3f44a483ae099067edf7232a60e8585fa5e51e897bdfafb6580acbcb4ded65 | Python | 1,389 | 51 | """Morlet wavelet transform extension.
The compiled module is ``_morlet`` (built from ``wrap.cpp`` via pybind11);
its public symbols are re-exported here so that code using the historical
``from ptsa.extensions import morlet; morlet.MorletWaveletTransform`` (or
``from ptsa.extensions.morlet import POWER``) keeps worki... |
acaaa5e64f27550808281ed45bd1dd1adf73cf15f5baf8b75ee527d3b5917fc8 | Python | 1,390 | 31 | """ ZLPR (zero-bounded log-sum-exp & pairwise rank-based) Loss
Paper: `ZLPR: A Novel Loss for Multi-label Classification` - https://arxiv.org/abs/2208.02955
"""
import torch
import torch.nn as nn
class ZlprLoss(nn.Module):
"""ZLPR loss, the multi-label extension of softmax cross-entropy.
Per sample, log(1 +... |
eb1420f60c50dfaae5adfa5bd2a3420673faa4806b22ba2e8a7c4099495dfef6 | Python | 1,394 | 62 | import tensorflow as tf
class GradientLayer(tf.keras.layers.Layer):
def __init__(self, model, **kwargs):
self.model = model
super().__init__(**kwargs)
def call(self, x):
with tf.GradientTape(persistent=True) as g:
g.watch(x)
with tf.GradientTape(persistent=... |
4a9e18dd2ed04f1c98e9be5b498911d37146e4378ab04675b9177a4959c70647 | Python | 1,397 | 43 | from __future__ import absolute_import
import logging
logger = logging.getLogger(__name__)
import numpy as np
from centriole.mode import mode
import unittest
class TestMode(unittest.TestCase):
def test_00_00_empty(self):
self.assertEqual(len(mode(np.zeros(0))), 0)
def test_01_01_single_mode(self):
... |
65cc11c15604d8c1c7d6a821679748d8e7b0b6f6cdc86e86973c02e133a6f476 | Python | 1,399 | 34 | import rvt.vis
import rvt.default
import numpy as np
import time
rast_path = r"D:\RVT_py\test\manhattan\Manhattan_DSM_1m_max.tif"
dict_rast = rvt.default.get_raster_arr(rast_path)
arr = dict_rast["array"]
nodata = dict_rast["no_data"]
arr[arr == nodata] = np.nan
# idw
start_time = time.time()
arr_out = rvt.vis.fill_w... |
c02edd81fb0b68cbcdfef5a529b2da808ed0c379f9d29b8ce9e3fd420c5fabdc | Python | 1,399 | 46 | import numpy as np
import numpy_groupies as npg
import scipy.sparse as sp
def segmentation_adjacency(segmentation, connectivity=4):
"""Generate an adjacency matrix out of a given segmentation."""
assert connectivity == 4 or connectivity == 8
# Get centroids.
idx = np.indices(segmentation.shape)
... |
f5da49e22aaef81f944d35549d467b7d3554ea1ecf9d1c718fa0f19ea7bce128 | Python | 1,400 | 47 | import torch
class BinaryCrossEntropy:
def __init__(self):
super(BinaryCrossEntropy, self).__init__()
self.eps = 1e-6
def __call__(self, y, y_hat, mask=None, smoothness=0.65):
# y : N1DHW
# y_hat: N1DHW
assert (y.size() == y_hat.size())
# y_hat_sm = F.sigmoid(... |
0b386b59e0340452ffb089c8f46aa1676c69c12ccb724e1541cb75b97452db96 | Python | 1,401 | 51 | import csv
import os
from pathlib import Path
from shutil import copytree, rmtree
import pytest
from click.testing import CliRunner
from ..cli import main
def test_reproschemaui2redcap(tmpdir):
runner = CliRunner()
with runner.isolated_filesystem():
# Copy necessary test data into the isolated file... |
0b9a69c0b038a738145372bf3dc1576d0f66bd940bc86653c981848f1756ab90 | Python | 1,402 | 60 | """
@author: Nikolai M Chapochnikov
Created in 2021
Testing the subspc_overlap functions
ALL TESTS PASS
"""
import functions.general as FG
import numpy as np
import scipy.linalg as LA
import pytest
NS = [(200, 20, 10), (200, 1, 1), (124, 1, 10), (70, 7, 7)]
@pytest.fixture(scope='module', params=NS)
def get_ab(r... |
1863ba123800ffa034a63aec013c5c7ecd5afd0999d6b4b92de73b2a46f6d61c | Python | 1,402 | 51 | # coding=utf-8
"""
ErodeImage
==========
**ErodeImage** shrinks bright shapes in an image. See `this tutorial <https://scikit-image.org/docs/stable/auto_examples/applications/plot_morphology.html#erosion>`__ for more information.
|
============ ============ ===============
Supports 2D? Supports 3D? Respects masks?
... |
19c76d8e3997ebec2dd9749564980b2d15acf14f183827888c2e46107d3f5aec | Python | 1,402 | 47 | import warnings
import numpy as np
from pdb2sql import StructureSimilarity
from deeprank.targets import rmsd_fnat
def __compute_target__(decoy, targrp):
"""Calculate CAPRI class.
CAPRI class name and ID:
- 'high': 0
- 'medium': 1
- 'accepetable': 2
- 'inc... |
51bc8082df19d41be547d96eea37b4e957f8d8aae905abff784c2b30464cf43e | Python | 1,407 | 51 | #!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
import sys
import getopt
import researchdata1258
from scipy import signal
subj = 20
startsec = 60
p300daqlatency = 100 # ms
helptext = 'usage: {} -p participant -s startsec -f file -h'.format(sys.argv[0])
try:
# Gather the arguments
all_ar... |
cfae26dcc26c518c699f376ba510c8b93047a6728424dcef256cf9002867d0da | Python | 1,407 | 42 | # import Bio import
import freesasa
import get_freeSASA_scores
import os
import sys
import csv
# solvent_accessibility using freeSASA
aaCodes = {'ALA':'A', 'ARG':'R', 'ASN':'N', 'ASP':'D', 'CYS':'C', 'GLN':'Q', 'GLU':'E', 'GLY':'G', 'HIS':'H', 'ILE':'I', 'LEU':'L', 'LYS':'K', 'MET':'M', 'PHE':'F', 'PRO':'P', 'SER':'S... |
34063f7302c9bd59b1130ee65edba79b45673635c6f32a107e0fda4df77c25ad | Python | 1,410 | 46 | """FastEMD - python wrapper of the FastEMD algorithm
CellProfiler is distributed under the GNU General Public License,
but this file is licensed under the more permissive BSD license.
See the accompanying file LICENSE for details.
Copyright (c) 2003-2009 Massachusetts Institute of Technology
Copyright (c) 2009-2015 B... |
38b0c2a6feccdd700445fd8ab734fa28feee45fc300abfbc9451996e843d8607 | Python | 1,411 | 64 | import time
import torch
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq... |
170ed4e5866bfcc40970b8594d6b6b4579564135913598dd4a8341454e28a116 | Python | 1,413 | 34 | # rvt.blend.gray_scale_to_color_ramp quick TEST
import rasterio as rio
from rasterio.enums import ColorInterp
import rvt.vis
import rvt.blend
import numpy as np
# Computed slope for example and saved as custom color scheme
input_dem_path = r"test_data\TM1_564_146.tif"
output_path = r"test_data\TM1_564_146_test_slp_... |
cad0afab63879e7662e03500b06d8b66513a1cbb296936504e3b54120595ca82 | Python | 1,414 | 35 | import sys
sys.path.append("../")
from api.music_engine_api import EngineAPI
import os
if __name__=="__main__":
#----------------------------------Init------------------------------#
musicEngine = EngineAPI()
musicEngine.cortexInit()
#----------------------------Learning process-----------------------... |
862b8d1618e2e924ba38696e519933312b9f9042a338960a09e773b121c069e0 | Python | 1,417 | 47 | # coding=utf-8
import os
import sys
import webbrowser
from urllib.request import pathname2url
import wx.html
import cellprofiler.icons
from cellprofiler.gui.html import utils
MEMORY_SCHEME = "memory:"
class HtmlClickableWindow(wx.html.HtmlWindow):
def __init__(self, *args, **kwargs):
wx.html.HtmlWindo... |
95d9ba58f20f8434556ad1ebe2fcc785c962a2da714257d5babd1cb915dca3fc | Python | 1,417 | 47 | # This file is part of pyunicorn.
# Copyright (C) 2008--2026 Jonathan F. Donges and pyunicorn authors
# URL: <https://www.pik-potsdam.de/members/donges/software-2/software>
# License: BSD (3-clause)
#
# Please acknowledge and cite the use of this software and its authors
# when results are used in publications or publi... |
eedc61a2a637549c8c213b2b0de7e1772637fe0ecff83eb4bfe03e9733891840 | Python | 1,417 | 38 | """Load shared language-neutral conformance cases for Python tests."""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
from typing import Any, cast
CORPUS = Path(__file__).resolve().parents[3] / "tests" / "conformance"
CASES = json.loads((CORPUS / "cases.json").read_bytes())["c... |
238b3af07018ed952ff056313c0a3c301025f967787ac0286b5474769079db12 | Python | 1,418 | 46 | from argparse import ArgumentParser
from nidm.experiment.Utils import read_nidm
def main():
parser = ArgumentParser()
# parse command line arguments
parser.add_argument(
"-nidm", dest="nidm_file", required=True, help="NIDM-Exp RDF File to import"
)
parser.add_argument("-out", dest="outfile... |
dce790d998a53ef5cc2526228f0f299354a139110098e42d5478ce854bd5a051 | Python | 1,418 | 47 | import numpy as np
import matplotlib.pyplot as plt
# Define parameters
dt = 0.1 # time step
t = np.arange(0, 100, dt) # time vector
tau = 10 # membrane time constant
Rm = 1 # membrane resistance
Vth = 1 # spike threshold
Vreset = 0 # reset potential
V0 = 0.5 # initial potential
g_leak = 0.1 # leak conductance
... |
a9bb2007387a4b50402440edf2260cbfd9d3ba3fe6b457d09521ebb93609fcfc | Python | 1,420 | 55 | import wx
from cellprofiler.icons import get_builtin_image
COLOR_NAMES = ["Red", "Green", "Blue", "Yellow", "Cyan", "Magenta", "White"]
COLOR_VALS = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[1, 1, 0],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1],
]
CPLDM_ALPHA = "alpha"
CPLDM_LINES = "lines"
CPLDM_NONE = "no... |
bc6c0aa7c41305dc9f1aab8cf462a4d25fdd4ea204d72a4e1f7856dee1f3c972 | Python | 1,420 | 76 | #!/usr/bin/env python2
import sys
if len(sys.argv)!=3:
print '<input coordinate file> <basename of output file>'
sys.exit()
infile,outn=sys.argv[1:]
aliencoord=0
alienchrid=1
id1=1
id2=1
fn1=outn+'_native'
fn2=outn+'_alien'
fout1=open(fn1,'w')
fout2=open(fn2,'w')
chrname='scaffold_'
with open(infile) as fin:
f... |
49cc7dc3c9b81cd0ba811c10dd5e5ca6d143d72d2119ce5ddc8dc386fa8a2cad | Python | 1,424 | 48 | import numpy as np
from skimage import color, segmentation
def slic(image, num_segments, compactness=10, max_iterations=10, sigma=0):
image = _preprocess(image)
return segmentation.slic(image, num_segments, compactness, max_iterations,
sigma)
def slic_fixed(num_segments, compact... |
8f01f69892c280cb5fbe3dbb65844eb4af79c3f8ac389c39b5b67af78beb696e | Python | 1,425 | 44 | import json
import os
import sys
if __name__ == '__main__':
import Functions.setup as stp
from simulation import *
try:
filepath = sys.argv[1]
if ',' in filepath:
fps = filepath.split(',')
filepath = fps[0]
for i, val in enumerate(fps):
... |
9ce822d6bad2bca73b01d7fbcf76d636685efeb3d625855e0abce94520e99498 | Python | 1,425 | 43 | import wx
import wx.lib.colourselect
from ..artist import ColorMixin
def show_workspace_viewer(parent, workspace):
global __the_workspace_viewer
if __the_workspace_viewer is None:
from cellprofiler.gui.workspace_view import WorkspaceView
__the_workspace_viewer = WorkspaceView(parent, workspa... |
423aa02921d3414e9c41e857d208300ca7b630228d973df4126066f56d11b5b5 | Python | 1,431 | 54 | import numpy
import numpy.testing
import skimage.morphology
import cellprofiler.modules.opening
instance = cellprofiler.modules.opening.Opening()
def test_run(image, module, image_set, workspace):
module.x_name.value = "example"
module.y_name.value = "opening"
if image.dimensions == 3 or image.multich... |
6f41666b7715cb7641c7c3754cddd5107d940150bf40e8fd078dd1c3d252fcf6 | Python | 1,431 | 35 | from tempfile import NamedTemporaryFile
import os.path
import filecmp
import pygenometracks.makeTracksFile
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"test_data")
# the relative path is needed to compare the two .ini files correctly.
# Otherwise the paths will differ.
relative_... |
8e7e5cfc3a139ab6a3c2ef07ae15980f6668fbaec96c0ab59bc4da7fe2616dfe | Python | 1,431 | 54 | import numpy
import numpy.testing
import skimage.morphology
import cellprofiler.modules.closing
instance = cellprofiler.modules.closing.Closing()
def test_run(image, module, image_set, workspace):
module.x_name.value = "example"
module.y_name.value = "closing"
if image.dimensions == 3 or image.multich... |
8982477135cdd437b3451e0e1a0c06e5cd06683a992420030d8d317c4cae6e64 | Python | 1,432 | 38 | # Print iterations progress
import sys
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total it... |
8db6122212d4ff92e80831fcbf1a8f1108c44bd36a806f050f784f9814b4f822 | Python | 1,432 | 54 |
import os
import json
import tensorflow as tf
import numpy as np
def load_json(file_path):
with open(file_path, 'r') as f:
return json.load(f)
def save_json(data, target_file):
with open(target_file, 'w') as f:
json.dump(data, f, indent=2, sort_keys=True)
def random_crop(img, crop_dims):
... |
a76bced62bf09e87dce3bcc881b24b2d1f76930c89c3584409935fb0d6a5deb0 | Python | 1,432 | 58 | """Configuration classes for flask/heroku."""
import os
from dataclasses import dataclass
from dotenv import load_dotenv
load_dotenv()
@dataclass
class Config:
"""Configuration class
This class contains all of the global configuration variables needed for
the AFIDs validator. Ideally, variables such a... |
e07fd39485e37e71dee67cd5dd878c45a2554d79c2b35dca4736b1a860f9c497 | Python | 1,436 | 37 | """Execute every ``.. code-block:: python`` block in ``docs/*.rst`` as a
pytest case.
Goal: any drift between PTSA's runtime API and the user-facing
documentation breaks CI immediately, instead of silently rotting on
the published GH-Pages site.
The actual ``pytest_collect_file`` hook lives in
``tests/conftest.py`` (... |
4b37ee5be71bf7df4d85ed9fa2d59b291ae18bbd7912b9a73dddfc3b57e753ef | Python | 1,437 | 43 | def get_unique_distances(matrix):
return list(sorted(set([j for row in matrix for j in row])))
def get_number_of_components(matrix, min_distance):
v = len(matrix[0])
group = 0
seen = set()
for i in range(v):
if i not in seen:
visited = [False for _ in range(v)]
star... |
bf2a1f1aba4f994ace686566c6ec0b7448bb41aa071d6539649794b03d15e04f | Python | 1,437 | 46 | #!/usr/bin/python3
pkgname="normalisr"
pkgnamefull="Normalisr Offers Robust Modelling of Associations Linearly In Single-cell RNA-seq"
version=[1,0,0]
license="BSD-3-Clause"
url="https://github.com/lingfeiwang/"+pkgname
author="Lingfei Wang"
author_email="Lingfei.Wang.github@outlook.com"
def pkg_setup():
from set... |
a8b5360d240edd2260fba512916de29749fa41b2f690694d6849ef2f521db70d | Python | 1,438 | 51 | import pytest
import sys
from pathlib import Path
from .entrypoints import CliCase, run_test_case
parent = str(Path(__file__).parent.parent.absolute())
sys.path.append(parent)
from update_version import main
# This function is a place where a real logic is executed.
# For tests, we replace it with mock up... |
2252acdec7dce706a33b1b82550c89653f9ce2a836bfdbd6ffe0ea02d88f9141 | Python | 1,439 | 45 | import os
import glob
import argparse
import matplotlib
# Keras / TensorFlow
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '5'
from keras.models import load_model
from layers import BilinearUpSampling2D
from tensorflow.keras.layers import Layer, InputSpec
from utils import predict, load_images, display_images
from matplotlib i... |
e6e95877edf943b8378611bff2b14726703b126135d78515ee204ca57945c379 | Python | 1,440 | 54 | import numpy
import numpy.testing
import skimage.morphology
import cellprofiler.modules.erodeimage
instance = cellprofiler.modules.erodeimage.ErodeImage()
def test_run(image, module, image_set, workspace):
module.x_name.value = "example"
module.y_name.value = "erosion"
if image.dimensions == 3 or imag... |
f60a901e43dd2396cc5d8289fcadf2124e613abaf75da514464f35a39f9765b8 | Python | 1,440 | 55 | """
ClinicalASL - Clinical Arterial Spin Labeling processing pipeline
Main pipeline script for processing ASL MRI data.
Repository: https://github.com/JSIERO/ClinicalASL
Author: Jeroen Siero
Institution: UMC Utrecht (University Medical Center Utrecht), The Netherlands
Contact: j.c.w.siero@umcutrecht.nl
Description:
... |
b4d31e4dce1817f613d2625a91a51f1ecfc6915d1c9c171f1e3a3c99819ac1b9 | Python | 1,442 | 50 | from easydict import EasyDict as edict
import yaml
"""
Config from yaml file
"""
def _edict2dict(dest_dict, src_edict):
if isinstance(dest_dict, dict) and isinstance(src_edict, dict):
for k, v in src_edict.items():
if not isinstance(v, edict):
dest_dict[k] = v
else:... |
b6838fc96665e9ab049bb106ecaf1b676cd06b9ee149f5e9aee3ffca26cfdb93 | Python | 1,444 | 55 | import warnings
import numpy as np
from deeprank.config import logger
from deeprank.targets import rmsd_fnat
def __compute_target__(decoy, targrp):
"""Calculate binary class ID using IRMSD.
Args:
decoy(bytes): pdb data of the decoy
targrp(h5 file hadnle): HDF5 'targets' group
Examples:... |
2f00497b541ba29ada66441d6a39e8c5889f9460c289246a8671cb084debae4e | Python | 1,445 | 54 | """
@author: Johanna Rahm
Research group Heilemann
Institute for Physical and Theoretical Chemistry, Goethe University Frankfurt a.M.
Handle data loading for DeepSTORM2DAddOns Jupyter Notebook.
"""
from skimage import io
import pandas as pd
# Split movie & localization file
class DataSplit():
def __init__(self)... |
38d6e92432510ff2c97e7b7b50de5a9c058bfae86de9f2cb043e8ddcd7fb643a | Python | 1,449 | 39 | from torch.utils.data import Dataset, DataLoader, SequentialSampler
from HiSiNet.HiCDatasetClass import HiCDataset, HiCDatasetDec, SiameseHiCDataset, PairOfDatasets
from HiSiNet.reference_dictionaries import reference_genomes
from HiSiNet import models
import numpy as np
import sys
import pandas as pd
import torch
impo... |
50c203451be8c6aa584ce5af289d206e053dab7a259ebad058a453b149e83595 | Python | 1,449 | 43 | from ._setting import Setting
class Binary(Setting):
"""A setting that is represented as either true or false
The underlying value stored in the settings slot is "Yes" or "No"
for historical reasons.
"""
def __init__(self, text, value, callback=None, *args, **kwargs):
"""Initialize the bi... |
e28d857a0eeb6f1df3414f45190071675b9fb09aac8f57a99349173af03d6335 | Python | 1,450 | 54 | import numpy
import numpy.testing
import skimage.morphology
import cellprofiler.modules.dilateimage
instance = cellprofiler.modules.dilateimage.DilateImage()
def test_run(image, module, image_set, workspace):
module.x_name.value = "example"
module.y_name.value = "dilation"
if image.dimensions == 3 or ... |
8142d8837cab1805f5523bbe61eddd18f3fc4c0b4b0b62f83be1267bba483c45 | Python | 1,452 | 39 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed May 9 13:42:34 2018
@author: saskiad
"""
import numpy as np
import pandas as pd
import os
import core
from allensdk.core.brain_observatory_cache import BrainObservatoryCache
save_path_head = core.get_save_path()
save_path = os.path.join(save_path_hea... |
61ffc20d7d81d7bad2da98a5c8312437dbc9d2d9e02ca1d4136c394ba13825a0 | Python | 1,454 | 36 | # Copyright 2015 The TensorFlow 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 applica... |
3f32b29526eb0364903d1149964626f776f90eca80422d91123d58ebe52c2fa2 | Python | 1,461 | 33 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="rvt_py",
version="2.2.3",
author="ZRC SAZU and University of Ljubljana (UL FGG)",
author_email="ziga.kokalj@zrc-sazu.si",
description="Relief Visualization Toolbox Python... |
9b11e6e431825b8e3e3eda9478a6571af34df9751437adf714f1eccc88365954 | Python | 1,461 | 56 | """
MorphologicalSkeleton
=====================
**MorphologicalSkeleton** thins an image into a single-pixel wide skeleton. See `this tutorial <https://scikit-image.org/docs/0.14.x/auto_examples/xx_applications/plot_morphology.html#skeletonize>`__ for more information.
|
============ ============ ===============
Sup... |
f4f2aad8ac9485f01af7eadb6ccfb295caff3a93dab135eccfaa4a6f463e82c0 | Python | 1,461 | 30 | #https://www.programcreek.com/python/example/112291/faiss.GpuIndexFlatL2
def _retrieve_knn_faiss_gpu_euclidean(query_embeddings, db_embeddings, k, gpu_id=0):
"""
Retrieve k nearest neighbor based on inner product
Args:
query_embeddings: numpy array of size [NUM_QUERY_IMAGES x ... |
4f9da2ffb0da4bddc38eec3fc84a8254eddf99e83a0b1365a230ed1aec75c2ac | Python | 1,462 | 53 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023 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.
#
# Any... |
c5c31ddf569758c8bbe5753e7914031b1201ad0f65d706ccea252440052a3c6c | Python | 1,462 | 50 | """
batch processing for participants
"""
import os, argparse, subprocess
def run_cmd(args):
# input
cmd = args.cmd
projectdir = args.projectdir
# subject
if args.subject:
subjects = args.subject
else:
subjects = [sub.replace("sub-", "") for sub in os.listdir(os.path.join... |
f645f94d7293ede86916b1636ea91a28f41510913f737f239c73eb41c82bdb5e | Python | 1,464 | 39 | import os, sys, argparse, time, random, math
import ot
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.model_selection import KFold, StratifiedKFold, train_test_split
from sklearn.cluster import KMeans, AgglomerativeClustering
import scipy.cluster.hierarchy as sch
from scipy ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.