sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
d1f476ab279ff52c562635ba74b33a0e1446b940766f45ab061586bef1564fbf
Python
637
15
"""Tests for pruned model adaptation (timm.models._prune).""" import pytest import torch import timm from timm.models import list_models @pytest.mark.parametrize('model_name', list_models('*pruned*')) def test_pruned_feature_info_matches_forward(model_name): """Pruning rebuilds layers with new widths; feature_in...
933f0f18e7f258f308b6916fbcbd3fbb96f66793d9c3174ed120b3acb5c31b09
Python
639
34
# -*- coding: utf-8 -*- """ Created on Wed Mar 1 10:31:23 2023 @author: yxliao """ import numpy as np from sklearn.metrics import r2_score def Rx(theta): R_x = np.array([ [1, 0, 0], [0, np.cos(theta), -np.sin(theta)], [0, np.sin(theta), np.cos(theta)], ]) return R_x def Ry(thet...
c363b5a5bcf1461f63989f616af47baf7d4fb22dea53effba6aef592bd9d8167
Python
639
20
from .adjacency import segmentation_adjacency from .form_feature_extraction import FormFeatureExtraction from .feature_extraction import extract_features, extract_features_fixed from .form_feature_selection import FormFeatureSelection from .algorithm import (slic, slic_fixed, quickshift, quickshift_fixed, ...
f5d51a803d3fd104fba7ae8fd196369a7d6e005e9fed232586abfa0d088f762d
Python
639
23
import numpy as np from pytorch_grad_cam.base_cam import BaseCAM class GradCAM(BaseCAM): def __init__(self, model, target_layers, use_cuda=False, reshape_transform=None): super( GradCAM, self).__init__( model, target_layers, use_...
e6d939ca6e46a07455ea532a11a1c0bc30ee6d2e0e8611d61b01e6719276aef0
Python
645
39
class TestWorker: def test_enter_thread(self): pass def test_exit_thread(self): pass def test_run(self): pass def test_do_job(self): pass def test_interaction_handler(self): pass def test_cancel_handler(self): pass def test_display_handle...
28b28dc362e3d16c97b363b7754c98c34257b2a738e561a8c4602314913bf570
Python
647
22
import numpy as np import matplotlib.pyplot as plt freq = 5. time = np.arange(0., 1.0, 0.01) sine = np.sin(2 * np.pi * freq * time) fig = plt.figure() fig.set_size_inches(5.5, 2.5) ax = fig.add_subplot(111) ax.plot(time, sine, color="dodgerblue", marker='.', markersize=5, label="sinewave", ls="solid", lw=1.2...
653957af80114156386e9fbc0114ca92654febc3a44ca6744413057d6d8753eb
Python
647
22
from ._image_subscriber import ImageSubscriber class FileImageSubscriber(ImageSubscriber): """A setting that provides image names loaded from files""" def __init__( self, text, value="Do not use", can_be_blank=False, blank_text="Leave blank", *args, **k...
8bd2b5876c0431167f72a879fe53c23979e8d63ec301e60bb143f9e91af516e1
Python
647
21
from __future__ import absolute_import import numpy import scipy.ndimage.filters def kirsch(image): convolution_mask = [5, -3, -3, -3, -3, -3, 5, 5] derivatives = numpy.zeros(image.shape) kernel = numpy.zeros((3, 3), image.dtype) kindex = numpy.array([[0, 1, 2], [7, -1, 3], [6, 5, 4]]) for _ in ...
503dcbbeda98d3a0f77cab4628330b3b10a0201ea9459a816be42a3bfb805659
Python
648
20
class ValidationError(ValueError): """An exception indicating that a setting's value prevents the pipeline from running """ def __init__(self, message, setting): """Initialize with an explanatory message and the setting that caused the problem """ super(ValidationError, self).__init...
407511d4e778ddb897257dccaaeb1109fab83fcfa5e9ef96dea5609b11083d00
Python
649
21
import re from ._filter_predicate import FilterPredicate class RegexpFilterPredicate(FilterPredicate): def __init__(self, display_name, subpredicates): super(self.__class__, self).__init__( "containregexp", display_name, self.regexp_fn, subpredicates, ...
0e9fbdf7c8988224739ac5525e0b4cee74f6c64f752a62078a109c027e17fa27
Python
650
22
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import pandas as pd import tensorflow as tf from .tools.data_processing import * def predict_fitness(AA_sequence, model=None, model_file='/mnt/shared/notebooks/albert/FitPred/Final_model_24K_v1.h5' ...
2943a5472cb2b992318c5dd90bc735fa7cdd51c2ac29af7ba9359e7d67a7c71a
Python
650
12
import pyControl.hardware as _h class Double_poke(): # Two IR beams, single LED and Solenoid. def __init__(self, port, rising_event_A = None, falling_event_A = None, rising_event_B = None, falling_event_B = None, debounce = 5): self.input_A = _h.Digital_input(port.DIO_A, rising_e...
31a4cefe7dcbd74cf72a732cd338a60886466c775275309ef66dcb215ba59604
Python
650
15
from pathlib import Path from imctools.data import Session class TestSession: def test_read_session(self, analysis_ometiff_path: Path): session_file_path = analysis_ometiff_path / '20210305_NE_mockData1' / '20210305_NE_mockData1_session.json' session = Session.load(session_file_path) asse...
d06a40144ae344aeebb4eb1482f5f2ac1be20fd762450ae3cb202d7dbe097b42
Python
650
23
class ImageSetChannelDescriptor: """This class represents the metadata for one image set channel An image set has a collection of channels which are either planar images or objects. The ImageSetChannelDescriptor describes one of these: The channel's name The channel's type - grayscale image /...
235995e2e5ef37d1df4030de8d2e1a39c7183b21027099e0f7327fa7f1cd6140
Python
651
14
from neurodynex3.exponential_integrate_fire import exp_IF from neurodynex3.tools import input_factory import brian2 as b2 def test_simulate_exponential_IF_neuron(): """Test exponential-integrate-and-fire model""" c = input_factory.get_step_current(0, 2, 1 * b2.ms, amplitude=8.5 * b2.namp) m, spike_monitor...
2a6624ff4bfb10b91fc88a8d0443fc74f8b581d19e8936cd6924a5db87b21930
Python
651
14
from neurodynex3.adex_model import AdEx from neurodynex3.tools import input_factory import brian2 as b2 def test_simulate_exponential_IF_neuron(): """Test if simulates simulate_AdEx_neuron generates two spikes""" current = input_factory.get_step_current(0, 0, 1. * b2.ms, 0.5 * b2.nA) state_monitor, spike_...
33c169ee0a0c1e95ef1fa2ae3a9b4477164cfd3e4c9e39efb9598b2b43d8d721
Python
651
22
from ._file_image import FileImage class STKFrameImage(FileImage): """Provide an image by filename:frame from an STK file""" def __init__(self, name, pathname, filename, frame, rescale_range=None): """Initialize the provider name - name of the provider for access from image set pathn...
3813391fba92fc06339b84ac1c3308b3cdde305e3166ecca9cb6e89c43fd92a1
Python
651
23
# Copyright (c) OpenMMLab. All rights reserved. import random import numpy as np import torch def worker_init_fn(worker_id: int, num_workers: int, rank: int, seed: int): """Function to initialize each worker. The seed of each worker equals to ``num_worker * rank + worker_id + user_seed``. Args: ...
2606b3a6393f8eec183e4da327f5b9adeafc485499659777c5816a5f521c5cd7
Python
653
34
import torch from torch import nn import pdb class GAN(nn.Module): """ Wasserstein GAN """ def __init__( self, critic: nn.Module, generator: nn.Module, ): super().__init__() self.critic = critic self.generator = generator self.latent_d...
55f20a57b88201f8cfc06845265af5f18e8cc20eec9f7f0b9c9b11492fd61b5f
Python
654
15
from ._analysis_cancel import AnalysisCancel from ._debug_complete import DebugComplete from ._debug_waiting import DebugWaiting from ._debug_waiting import DebugWaiting from ._display import Display from ._display_post_group import DisplayPostGroup from ._display_post_run import DisplayPostRun from ._exception_report ...
619986b1f9da3fec23c47bc1474280da6ff5015b302857ffe2aa31bb917b5f39
Python
654
13
# 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...
023978e111668c4154ac45bbf7e39f9714c9305e36f8319bbd572f106b54c3eb
Python
658
22
from ._image_subscriber import ImageSubscriber class CropImageSubscriber(ImageSubscriber): """A setting that provides image names that have cropping masks""" def __init__( self, text, value="Do not use", can_be_blank=False, blank_text="Leave blank", *args, ...
4c8b5034df43f83116c96a0eca145777bca015b0bb5a42f50a06e053ad43e351
Python
660
21
class Environment: def __init__(self, pdb_root=None, pssm_root=None, dssp_root=None, conservation_root=None, dbnsfp_path=None, gnomad_path=None, device=None, zero_miss...
842ec361584044cbfed66c3ffdc9b034329b18979ac1f5209dc8803ee071fdda
Python
660
25
from ._file_image import FileImage class FlexFrameImage(FileImage): """Provide an image by filename:frame, loading the file as it is requested """ def __init__(self, name, pathname, filename, series, index, ...
91bec42ffcf55249174c7eb7d9d11b0a153a1f70eb6a3684ce95542aae1dd6f9
Python
660
21
# 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 applicable law or agreed to in writing, software # distributed under the...
4d928842bf0ff614164fc9ddabc258b862e2b1c1f583b676df59e5103ce500a1
Python
661
18
from ._setting import Setting class FigureSubscriber(Setting): """A setting that subscribes to a figure indicator provider """ def __init__(self, text, value="Do not use", *args, **kwargs): super(Setting, self).__init__(text, value, *args, **kwargs) def get_choices(self, pipeline): c...
6054a310efa43021d132d56fde9be638b46821f078e616f1eb885f011cf674b1
Python
662
25
from enum import Enum class DistanceMethod(str, Enum): NONE = "None" CENTROID = "Centroid" MINIMUM = "Minimum" BOTH = "Both" class TemplateMeasurementFormat(str): FF_PARENT = "Parent_%s" FF_CHILDREN_COUNT = "Children_%s_Count" # Centroid distance measurement (FF_DISTANCE % parent) FF_C...
e682790d92172f3e1e2f4c0f00a80b58445a23bdf37b740c7d371fad117092b4
Python
663
22
from ptsa.data.readers import LocReader import os.path as osp import pandas as pd class TestLocReader: @classmethod def setup_class(cls): loc_file = osp.join(osp.dirname(__file__), 'data', 'localization.json') cls.localization = LocReader(filename=loc_file).read() def test_split(...
db140f4623848214abbf21e6a062bc23d62409d5b679b46592aa6062309433ed
Python
665
24
import torch.nn as nn class Interpolate(nn.Module): def __init__(self, interp_kwargs=None): """ Initialize the function. Args: interp_kwargs (list, optional): Keyword arguments for initialization. Defaults to None. """ nn.Module.__init__(self) if interp...
149d568c2536b13647789a6585fed1a5861f041aef40b525a43f0eda8c9818ea
Python
666
23
import numpy as np # define Izhikevich model class Izhikevich: def __init__(self, a, b, c, d, v_init=0.1, u_init=0.2, n_neurons=50): self.a = a self.b = b self.c = c self.d = d self.v = np.full(n_neurons, v_init) self.u = np.full(n_neurons, u_init) def u...
a82fc3e5feaca63533403da4aa979d55256910354b5be24a7e08f208fdc41d4e
Python
666
21
from ._name import Name from ...._validation_error import ValidationError class LabelName(Name): """ A setting that provides an image name """ def __init__(self, text, value="Do not use", *args, **kwargs): super(LabelName, self).__init__(text, "objectgroup", value, *args, **kwargs) def t...
891e6f70355c27946c8e76f4338a5608d519da4d4f7732e5c501669db517212d
Python
667
10
data_param = { 'per_sys' : ["Be","B", "C", "N", "O", "F" , "Ne", "Na", "Mg", "Al", "Si", "P","S", "Cl", "Ar" , "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se" , "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "C...
ab99a7cbcaad1d3a9e5dff57151b5d7a1d8cdc4be50722b5abad1d7e0b61e638
Python
667
16
import datetime from ipyparallel import Client rc = Client(profile="benchmark.") # rc.get_result('77cdf201-5925-4199-bdd8-0eae0d833d2a') # incomplete = rc.db_query({'completed' : None}, keys=['msg_id', 'started']) completed = rc.db_query( {'completed': {'$ne': None}}, keys=['msg_id', 'started', 'completed', ...
8ea60952da4a5990bba6cfa23d9bd2b94453eb35c0909b1059e937fedd9ba91e
Python
670
17
from ._grayscale_image import GrayscaleImage from ._image import Image from ._image_set import ImageSet from ._image_set_list import ImageSetList from ._rgb_image import RGBImage from .abstract_image import AbstractImage from .abstract_image import CallbackImage from .abstract_image import ColorImage from .abstract_ima...
d0f29ff54f6159d67719277751192499f9ef6e99e60fb40fcee9c90bef8d4212
Python
670
25
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Util functions for megsim. """ import IPython def _ipython_setup(enable_reload=False, use_qt5=True, matplotlib_qt=True): """Performs some IPython magic if we are running in IPython""" try: __IPYTHON__ except NameError: return from IPy...
02d4bb22b64aeaec285065e9dd55754c3c2498a95ee9b13c19c257f699d00809
Python
673
22
import keras.backend as K import tensorflow as tf def depth_loss_function(y_true, y_pred, theta=0.1, maxDepthVal=1000.0/10.0): # Point-wise depth l_depth = K.mean(K.abs(y_pred - y_true), axis=-1) # Edges dy_true, dx_true = tf.image.image_gradients(y_true) dy_pred, dx_pred = tf.image.image_gra...
2072a4c80f6776d2fff197967b1139c7606673db4da90402c382b29ebabbb698
Python
673
20
""" @author: Johanna Rahm Research group Heilemann Institute for Physical and Theoretical Chemistry, Goethe University Frankfurt a.M. Save localizations of single frames found by DeepSTORM2D to one csv file. Filter out localizations below a confidence threshold. """ import os def save(dir_path, threshold, locs): ...
0db44a84291cd4d9f684524940c218dba272e779276087129824fa66ac918498
Python
674
34
from cellprofiler_core.constants.measurement import ( C_URL, C_FILE_NAME, C_PATH_NAME, C_OBJECTS_URL, C_OBJECTS_FILE_NAME, C_OBJECTS_PATH_NAME, ) from cellprofiler_core.preferences import ( DEFAULT_INPUT_FOLDER_NAME, DEFAULT_OUTPUT_FOLDER_NAME, NO_FOLDER_NAME, ABSOLUTE_FOLDER_NAM...
9566a6847e71b57c7d6fff1b5b45e22b114ccdff690723f71414755d8f2d1b2b
Python
674
17
# -*- 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...
1be2e513e14182c8d540624d2a0732728de17f4c829b9be3227c0d29e8e32159
Python
675
16
# -*- 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...
d43fa95778c18f37eae966089086e05142475bbd6482ce257128549f2734a8a3
Python
679
26
from ._dependency import Dependency class ImageDependency(Dependency): """A dependency on an image""" def __init__( self, source_module, destination_module, image_name, source_setting=None, destination_setting=None, ): super(type(self), self).__init...
0dfc9661ac5e84b7aefbf985e30cf75a2a0ca10e0213be1b59c23721e0e1f81f
Python
680
22
from pdb2sql import pdb2sql import numpy from deeprank.operate.pdb import get_pdb_path def __compute_feature__(environment, cutoff_distance, featgrp, variant): pdb_path = get_pdb_path(environment.pdb_root, variant.pdb_ac) pdb = pdb2sql(pdb_path) try: chain_ids = sorted(set(pdb.get("chainID")))...
fee403497fb2c3fef136eb26973abfc14f6b3d172faf927301e77655b0008ee1
Python
681
31
# -*- coding: utf-8 -*- """ Created on Fri Aug 9 10:23:56 2019 @author: Xiaoxuan Jia """ import numpy as np from scipy.optimize import curve_fit from scipy.ndimage import gaussian_filter def fit_exp(rsc_time_matrix, color): intr = np.abs(rsc_time_matrix) tmp = np.nanmean(intr, axis=0) n=intr....
3825e074401352e243cbd74eb5050072d8f148c52b4cb89bcb51ebbe8ec2fe94
Python
682
45
class TestFileImage: def test_series(self): pass def test_series(self): pass def test_channel(self): pass def test_channel(self): pass def test_index(self): pass def test_index(self): pass def test_get_name(self): pass def te...
bdae368d06763abcfa8f4210c03944deddd2b9b20c5cc81a5b58666209910781
Python
682
17
# -*- 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...
4e7b091987a09067467c7d57d9bbb0970b9ab1e066892c84edd15d33265d3f26
Python
684
22
import tensorflow as tf import tensorflow.keras.backend as K def depth_loss_function(y_true, y_pred, theta=0.1, maxDepthVal=1000.0/10.0): # Point-wise depth l_depth = K.mean(K.abs(y_pred - y_true), axis=-1) # Edges dy_true, dx_true = tf.image.image_gradients(y_true) dy_pred, dx_pred = tf.imag...
84a2ed2d5f2eb25d3731a9f7db01b2bf99cad6bf8b3882ea3e02c0b552760d14
Python
685
35
import math import numpy as np from scipy.integrate import odeint from scipy.interpolate import interp1d import matplotlib.pyplot as plt def calcW(Y): # This function converts Y (which is after Hale transformation) to W. def dWdY(W,Y): dWdY = np.sqrt(1.65894)*np.exp(1.0/3.0*W**3) return dWdY ...
e8a30525ebd497e88061f3d875924a3f1fb96a1fecedd744b3dfa86a108a0887
Python
686
20
from torch.optim.lr_scheduler import _LRScheduler from torch import optim import numpy as np class CosineWarmupScheduler(optim.lr_scheduler._LRScheduler): def __init__(self, optimizer, warmup, max_iters): self.warmup = warmup self.max_num_iters = max_iters super().__init__(optimizer) ...
d87e3d7db3f13c230d829507b3caab7d9560f25b85f779b2400cafdb40c62d30
Python
687
25
class Atom: def __init__(self, id_, position, chain_id, name, element, residue=None, altloc=None, occupancy=None): self.id = id_ self.name = name self.element = element self.chain_id = chain_id self.position = position self.residue = residue self.altloc = al...
0d9da6f4b794f430eb215bc8144211dc8d52db94687a5234b1525b7c7e7ca18e
Python
689
19
# -*- 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...
aba93b89ba11332d2d604ab9d7f046ed21addb6dd7799040de9911d292328362
Python
689
26
def show_image(image, grayscale = True, ax=None, title=''): if ax is None: plt.figure() plt.axis('off') if len(image.shape) == 2 or grayscale == True: if len(image.shape) == 3: image = np.sum(np.abs(image), axis=2) vmax = np.percentile(image, 99) ...
ac54f3ecd042d3558ea9fa05b8dfeb97fc91adb12d1ef868bcfb344e39f3a7c2
Python
690
24
from ._change_setting_event import ChangeSettingEvent class BeforeChangeSettingEvent(ChangeSettingEvent): """Indicates that a setting is about to change, allows a listener to cancel the change """ def __init__(self, old_value, new_value): ChangeSettingEvent.__init__(self, old_value, new_value) ...
96cd43e8d5db8adfb96732af9ad3e1794224b0ef983e4a71c6458061a13492dc
Python
691
30
from scipy.stats import circmean,circvar from cmath import phase from numpy import array from scipy.stats import circmean,circvar,circstd from numpy import * from cmath import phase from matplotlib.pylab import * def len2(x): if type(x) is not type([]): if type(x) is not type(array([])): return -1 return len(...
a3541d0a2a9a2cff22927cc92b5a95274e8145cc4f4c940fe727e8278e62a4d0
Python
692
21
import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": event_times = np.arange(1, 20, 2.5) event_times += np.random.randn(len(event_times))*0.5 fig = plt.figure() fig.set_size_inches(5.5, 1.25) ax = fig.add_subplot(111) ax.scatter(event_times, np.ones(event_times.shape),...
bb42ff1499509a82958dab1226b5bee78ee327c62589fd51dc447b332e4f84d9
Python
693
24
from enum import Enum class HaralickFeatures(str, Enum): AngularSecondMoment = "AngularSecondMoment", Contrast = "Contrast", Correlation = "Correlation", Variance = "Variance", InverseDifferenceMoment = "InverseDifferenceMoment", SumAverage = "SumAverage", SumVariance = "SumVariance", ...
c5172c59668265047dd8f0024b95b4bf2eef9d89e4d6fcaa7b69a9248350e1d5
Python
693
45
class TestRange: def test_str_to_value(self): pass def test_value_to_str(self): pass def test_get_value(self): pass def test_set_value(self): pass def test_get_min_text(self): pass def test_get_min(self): pass def test_get_max_text(self):...
deafdbc63bfbb06b575851942c38f5001dcdb71ec0dc73dcb64fecafa80be96a
Python
694
32
""" Run pipelines on imagesets to produce measurements. """ import sys use_analysis = True DEBUG = "DEBUG" ANNOUNCE_DONE = "DONE" ############################### # Request, Replies, Events ############################### if sys.platform == "darwin": pass if __name__ == "__main__": # This is an ugly hac...
2d664867d82f742f4fa646968485edd65aedcb3ff6ce136dceaebd99d76d198a
Python
695
21
# 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...
3776c63fcae6ffb3a86695e2f7fa782d7d9100dac227ca820de7c06f7e61758f
Python
696
39
class TestMeasurement: def test_construct_value(self): pass def test_get_measurement_object(self): pass def test_get_category_choices(self): pass def test_get_category(self): pass def test_get_feature_name_choices(self): pass def test_get_feature_name...
986041fcdb6bb65d9fb4309f18ea5fb5fe145090f6512fc6d812f79c2a6ca50e
Python
696
21
from ._directory import Directory from ._filename import Filename from ._text import Text from .alphanumeric import Alphanumeric from .alphanumeric import Character from .alphanumeric import CropImageName from .alphanumeric import ExternalImageName from .alphanumeric import FileImageName from .alphanumeric import GridN...
ab4ac23d8ce25253f5e13cd61b6c627fd2d2e97b8f23f9c9066472284ca92103
Python
697
33
# -*- coding: utf-8 -*- import time from pysteps.decorators import memoize def test_memoize(): @memoize(maxsize=1) def _slow_function(x, **kwargs): time.sleep(1) return x for i in range(2): out = _slow_function(i, hkey=i) assert out == i # cached result t0 = time...
a9498fefcd384f9ab5d17a33193b9abaee7d381f294bb5c17faa73671dc79c06
Python
699
26
from ._dependency import Dependency class ObjectDependency(Dependency): """A dependency on an object labeling""" def __init__( self, source_module, destination_module, object_name, source_setting=None, destination_setting=None, ): super(type(self), ...
17ee4e6564e9a003a8d3987766c1dbfecbbf12c76ff0f9447e33dd757e3c07bf
Python
705
22
# -*- coding: utf-8 -*- """ Script used to install the pysteps data in a test environment and set a pystepsrc configuration file that points to that data. The test data is downloaded in the `PYSTEPS_DATA_PATH` environmental variable. After this script is run, the `PYSTEPSRC` environmental variable should be set to PY...
26805b7578d69ffebf54a4f8df3b2bc8e476f50428b29b9b846eb23ad768cb03
Python
713
32
""" /!\ WARNING - DEPRECATED /!\ utf16encode.py - encode unicode strings as escaped utf16 This is only used for pipeline version < 3 files """ def utf16decode(x): """Decode an escaped utf8-encoded string """ y = "" state = -1 for z in x: if state == -1: if z == "\\": ...
d9bc56681253895d8b8772af5cbba4a0c61b3de82d7f3d3fe14824a16a8411f5
Python
713
19
from .b0_utils import B0Utils from .dimensions import FitBox, FitToBox from .dwi import (AssertDwiDimensions, CheckDuplicatedBvecsInShell, DetermineSHOrder, DisplacementFieldToFieldmap, DwiMetadataUtils, ExtractShells, ...
dd1cc580cea884d3721101a1c5d8dcc2a697b91dcad1e9c5205910399f8ece01
Python
713
20
import numpy as np from scipy.linalg import cho_solve_banded, solve_triangular from ..utils.linalg import unband_matrix def log_det_from_banded_cholesky(banded_cholesky): diag_cholesky = banded_cholesky[0, :] return 2 * np.sum(np.log(diag_cholesky)) def sum_elements_from_inv_banded_cholesky(inv_banded_chol...
6fe526ab242b7a98ec298d1ce6c3687962fbe82084421c65acfc816568ae4b65
Python
714
30
#!/usr/bin/env python2 import sys,os if len(sys.argv)!=3: print '<broadpeak file> <track name>' sys.exit() infile,outfile=sys.argv[1:] # all values on 9th field are -1, exclude them id=1 fout=open(outfile,'w') with open(infile) as fin: for line in fin: lst=line.rstrip().split('\t') fout.write('{0[0]}\t{0[1]...
6ce30f3b0135abf032d1a70f78466889b21b13cc67644864a7b2602c856068d3
Python
715
22
# this program makes sure each protein alignment has more sequences that "min_seqs". import os import sys from shutil import copyfile perc_sims = ["20","40","60","80","100"] #perc_sims = ["40"] min_seqs = 10 min_lines = min_seqs * 2 for perc_sim in perc_sims: input_path = "../../data/PSICOV/aln_" + perc_sim + "/" ...
b7e8f490498c32f39049d244f35c3962baf086a78a1b26b3f55c58335776e396
Python
716
34
from enum import Enum class BrightnessMode(str, Enum): MAX_IMAGE = "Max of image" MAX_POSSIBLE = "Max possible" class LineMode(str, Enum): INNER = "Inner" OUTER = "Outer" THICK = "Thick" class SourceMode(str, Enum): FROM_IMAGES = "Image" FROM_OBJECTS = "Objects" class OutlineMode(str, ...
b4b95e14067ac17340b3b0355ef7d38e02b678696f99e99692e70bf331027eeb
Python
718
16
import pyControl.hardware as _h import pyControl.audio as _a class Audio_poke(): # Single IR beam, LED and Solenoid. Audio amplifier to drive speaker. def __init__(self, port, rising_event = None, falling_event = None, debounce = 5): assert port.DAC is not None, '! Audio poke needs port with DAC...
1085c6c22a1230b4c254c16c10ffd905b07e978e69d7e5bae7f8e7a58324517d
Python
720
20
import pyControl.hardware as _h class Stepper_motor(): def __init__(self, port=None, direction_pin=None, step_pin=None): if port: direction_pin = port.DIO_A step_pin = port.DIO_B self._direction = _h.Digital_output(direction_pin) self._step = _h.Digital_outpu...
aaf1c1cd4872a0d0faf52bb8ad11d6a36e9262842013fe6929daa619b99cb5ac
Python
721
17
from .asymmetric_loss import AsymmetricLossMultiLabel, AsymmetricLossSingleLabel from .binary_cross_entropy import BinaryCrossEntropy from .class_weights import ( CLASS_WEIGHT_METHODS, CLASS_WEIGHT_METHOD_KINDS, compute_class_weights, load_class_stats, load_class_weights, resolve_class_weights, ...
ee98a30ffb5e384a8dee6303eb35e0b76cf0d7f509546ba79b688e5fb36674b9
Python
722
23
import numpy as np import matplotlib.pyplot as plt freq = 5. time = np.arange(0., 1.0, 0.01) times = time[np.sort(np.random.permutation(range(0, len(time)))[:40])] sine = np.sin(2 * np.pi * freq * times) fig = plt.figure() fig.set_size_inches(5.5, 2.5) ax = fig.add_subplot(111) ax.plot(times, sine, color="dodgerblue...
8fb60e35f16e3d0196b49b045c1c06ab96e8a648fc14e6ea33df20b7188ef911
Python
724
24
import click from .subcommands import cli_subcommands from GANDLF.entrypoints import append_copyright_to_help from GANDLF.utils import logger_setup from GANDLF import version @click.group() @click.version_option(version, "--version", "-v", message="GANDLF Version: %(version)s") @click.pass_context # Pass th...
c67c79b0455ebadb1e7900416c5ad3f2b0d2b79da2d9d33e38ec674564e97bbe
Python
725
31
from scipy.stats import circmean,circvar from cmath import phase from numpy import array from scipy.stats import circmean,circvar,circstd from numpy import * from cmath import phase from matplotlib.pylab import * warnings.filterwarnings("ignore") def len2(x): if type(x) is not type([]): if type(x) is not type(arr...
f32a23a0e4eecd049301097e58160b6b2eda0e6ab93f450a619639d36576e1bc
Python
726
19
# -*- 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...
c0227c309d6265400fa52cc735845406ac9d1bcb3bc7221f56fdac25e0054a47
Python
727
21
from ._abstract_image import AbstractImage class CallbackImage(AbstractImage): """An image provider proxy that calls the indicated callback functions (presumably in your module) to implement the methods """ def __init__(self, name, image_provider_fn): """Constructor name - na...
139fc3319481c2f624bf5e961db4a8683be5c1f0fbb7a81c580afb5e500d3356
Python
731
17
# 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...
2bebb8f07d2033b025b3780b6bb3570d533661677501df682919c4ceca64344b
Python
732
27
from .._setting import Setting class DoSomething(Setting): """Do something in response to a button press """ save_to_pipeline = False def __init__(self, text, label, callback, *args, **kwargs): super(DoSomething, self).__init__(text, "n/a", **kwargs) self.__label = label self...
5850f5ea0e1db3fa7dc0e0dce98ffe0ab7fc38b7ab59b61daf6a7aafe007ca07
Python
733
22
import numpy as np class ThetaNeuron: def __init__(self, tau, v_reset, v_th, v_init=0.0): self.tau = tau self.v_reset = v_reset self.v_th = v_th self.v = v_init self.theta = np.random.uniform(low=0, high=2 * np.pi) self.weights = np.random.normal(loc=0.0, scale=1.0) ...
ef9534cf4607b9e086503e73c559905325e4302b4ec2fad0aaa3dd6bba5f2fb3
Python
733
31
#!/usr/bin/env python2 import sys,os if len(sys.argv)!=3: print '<narrowpeak file> <track name>' sys.exit() infile,outfile=sys.argv[1:] id=1 fout=open(outfile,'w') with open(infile) as fin: for line in fin: lst=line.rstrip().split('\t') fout.write('{0[0]}\t{0[1]}\t{0[2]}\tscorelst:[{0[6]},{0[7]},{0[8]}],id:{...
5dbfdd801607791d7168556ccba0f040cbcea0e30dc6ad1a7b5ec19be127366b
Python
735
29
from typing import Any, Dict, Iterable, Union, Protocol, Type try: from typing import TypeAlias except ImportError: from typing_extensions import TypeAlias try: from typing import TypeVar except ImportError: from typing_extensions import TypeVar import torch import torch.optim try: from torch.opti...
771bbb0240dc732a2db8b7efbdbcc7ef3ab783f19ac6a773592df99b877d1372
Python
735
23
#First run cliprunlistopt.py to get to do list import numpy as np folder = './Inputs/SDC20220929_invivoCA1pyrs5/' inputsToDO = folder+'inputsToDO.csv' ypossdefault = list(np.arange(0,2000,200)) # check simulation.gridFieldStimulation splittype = 'ysplit' delimiter = ',' with open(inputsToDO,'r') as f: inputsToDO...
a900ecf83ac786d968e6b276bf259c366556c1fa38999512d0d9c1e0b3b5d18f
Python
735
21
class TargetTransform(object): def __call__(self, target): raise NotImplementedError() def __repr__(self): return str(self.__class__.__name__) class DefaultTargetTransform(TargetTransform): def __init__(self, class_augmentations): super(DefaultTargetTransform, self).__init__() ...
f156a111db8a944d448dbe9768bd2ac8954557919d93ce9f8cff804ed081b8f2
Python
735
31
import torch import torch.nn as nn from torch import sin, cos def rot_z(gamma): return torch.tensor([[cos(gamma), -sin(gamma), 0], [sin(gamma), cos(gamma), 0], [0, 0, 1]], dtype=gamma.dtype) def rot_y(beta): return torch.tensor([[cos(beta), 0, sin(beta)], [0, 1, 0], [-sin(beta), 0, cos(beta)]], dtype=beta.d...
1007ffefd49c5bb263e0edb03a8345ac6bbb9c719b64fe2698dfdec40fbda453
Python
739
28
import os import sys import numpy as np import networkx as nx import itertools as it import random as rd import umap import pickle as pk import pandas as pd ppi = pd.read_csv("input/ppi_symbol_lcc.csv"delimiter= ',', skipinitialspace=True) G_ppi = nx.from_pandas_edgelist(ppi, 'symbol1', 'symbol2') G_ppi...
c4e0997680a21ceb8f0bc0d409cc57cb976c9466e655225584292659665de842
Python
740
17
import pandas as pd filename = r"D:/merged.csv" df = pd.read_csv(filename) counts_gold = df.groupby(['gold', 'split'])['split'].size().unstack(fill_value=0).add_prefix('count_') with pd.option_context('display.max_rows', None, 'display.max_columns', None): print(counts_gold) counts_gold = df.groupby(['CT_Visual_...
a7deeb91b81b47f3a8a271289ba0052ef538034df2d28577a7efe194b4eeb382
Python
741
21
# -*- coding: utf-8 -*- import pytest from datetime import datetime from pysteps.io.archive import _generate_path test_argvalues = [ ("20190130_1200", "%Y/foo/%m", "./2019/foo/01"), ("20190225_1200", "%Y/foo/%m", "./2019/foo/02"), ("20190122_2222", "%Y/foo/%m", "./2019/foo/01"), ("20190130_1200", "%Y...
1d25b335dab94bc3a6d66ee7ac71188fdb191b70927a156e361aa5811597751e
Python
745
23
import numpy as np # define QIF model class QIF: def __init__(self, tau, v_reset, v_th, v_init=0.0, beta=0.5): self.tau = tau self.v_reset = v_reset self.v_th = v_th self.v = v_init self.beta = beta self.num_ops = 0 def update(self, I, dt): dvdt ...
a4bc23c2492d2e8efc168b0e3c546e6d76f8b3b44860501dcf39108f0a649a70
Python
745
39
_args_template = """ POSITIONAL=() while [ $# -gt 0 ] do key=\"$1\" case $key in {} *) POSITIONAL+=(\"$1\") shift ;; esac done """ _named_template = """ {}) {}=\"$2\" shift shift ;; """ def build...
20fe5109f0e857152b1ec8a5a2e56e9fb574d7cf396fe9c32e142a1a66846759
Python
746
25
import numpy as np # define AdEx model class AdEX: def __init__(self, tau_m, v_rheo, v_spike, delta_T, v_reset, v_init=0.0): self.tau_m = tau_m self.v_rheo = v_rheo self.v_spike = v_spike self.delta_T = delta_T self.v_reset = v_reset self.v = v_init self.num_...
859ed59ab4b1c2790943dd82b0d8f478b0a069362474280796a1aab81f20af69
Python
748
22
# -*- coding: utf-8 -*- import numpy as np import pytest from numpy.testing import assert_array_equal from pysteps.utils import arrays # compute_centred_coord_array test_data = [ (2, 2, [np.array([[-1, 0]]).T, np.array([[-1, 0]])]), (3, 3, [np.array([[-1, 0, 1]]).T, np.array([[-1, 0, 1]])]), (3, 2, [np.a...
5fb5cd11f615438fd5b837dcf7caa9c16619390c70a27f73ac95b05063021664
Python
751
18
import numpy as np class AdEX: def __init__(self, tau_m, v_rheo, v_spike, delta_T, v_reset, v_init=0.0, n_neurons=1000): self.tau_m = tau_m self.v_rheo = v_rheo self.v_spike = v_spike self.delta_T = delta_T self.v_reset = v_reset self.v = np.full(n_neurons, v_init) ...
9a75960c0028b022121366a11236134f7139907fc204bee32f5b2f79508e1d24
Python
752
34
#!/usr/bin/env python import time import sys from rgbmatrix import RGBMatrix, RGBMatrixOptions from PIL import Image if len(sys.argv) < 2: sys.exit("Require an image argument") else: image_file = sys.argv[1] image = Image.open(image_file) # Configuration for the matrix options = RGBMatrixOptions() options.r...
75341d05ec02a541e1abafec87ea568bc076889aefeff326b94d05de1d590167
Python
753
19
import torch.nn as nn from torchmeta.modules.module import MetaModule from torchmeta.modules.utils import get_subdict class MetaSequential(nn.Sequential, MetaModule): __doc__ = nn.Sequential.__doc__ def forward(self, input, params=None): for name, module in self._modules.items(): if isins...
8cefb26c83f12f0db73960ef15d4ee91b7edd1933c50ea1f1a7a0bd82e42129b
Python
754
21
from typing import Optional, Union from .config_manager import ConfigManager def parseConfig( config_file_path: Union[str, dict], version_check_flag: Optional[bool] = True ) -> None: """ This function parses the configuration file and returns a dictionary of parameters. Args: config_file_path...
a4a9520558d2b824b8d5c6b526d7fa5dc98ce4cb48393b919a48455eb137d1cc
Python
757
29
from ...utilities.zmq.communicable.request import AnalysisRequest class ExceptionReport(AnalysisRequest): def __init__( self, analysis_id, image_set_number, module_name, exc_type, exc_message, exc_traceback, filename, line_number, ): ...
ab925cbc37f9861f768b89ead589bf6fda67430004658c92151798b589d06c1e
Python
759
38
# -*- coding: utf-8 -*- # # main.py # """ Features selection and classifications """ __author__ = "Ahmed Albuni" __email__ = "ahmed.albuni@gmail.com" import argparse import json import imskaper.experiment.experiment as ex import imskaper.validations.validate_config as validate parser = argparse.ArgumentParser( ...
02d7c3088426438b1d7c42cf5aa5677b2f5b3763d4deb3f07fa6b3b2ab2265f3
Python
761
33
import numpy.testing import skimage.restoration import cellprofiler.modules.reducenoise instance = cellprofiler.modules.reducenoise.ReduceNoise() def test_run(image, module, image_set, workspace): module.x_name.value = "example" module.y_name.value = "ReduceNoise" module.size.value = 7 module.dis...
d06b3c0db3a1c67b9eaac854bed9bb9097612295ed4e49f03c177b71a27af2dc
Python
761
18
# -*- 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...