sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
eb0f87b1a4d5f45a77b25b25fd963d3312e11999ac5cd319521c3507786b79c9
Python
2,140
61
from PymoNNto.Exploration.Network_UI.TabBase import * class event_tab(TabBase): def __init__(self, title='Events'): super().__init__(title) def initialize(self, Network_UI): self.event_tab = Network_UI.add_tab(title=self.title) self.plot = Network_UI.tab.add_plot(title='Events', x_l...
90d608f4f84fad1b941c14077da873e638cc8ff2fe3ee5879d926551430e94bb
Python
2,142
57
import torch.nn.functional as F import torch class gru(torch.nn.Module): def __init__(self, classes, arch=[41, 3, 6, 23, 0.07643942323789713]): super(gru, self).__init__() self.input_size = 1 self.num_layers = 3 self.bidirectional = True self.arch = arch self.arch =...
a2f8d0c3bbbf521b73cb76e9a28a1aa7dbbed9c559a5b4cf351d519f0e72db34
Python
2,144
48
from PymoNNto.Exploration.Network_UI.TabBase import * class buffer_tab(TabBase): def __init__(self, title='Buffer'): super().__init__(title) def add_recorder_variables(self, neuron_group, Network_UI): return def initialize(self, Network_UI): self.buffer_tab = Network_UI.Next_Tab(...
f8d26c166b6da56a0230cdbc714b684ce36f37bab4cea42e6fabdae9e3c8d731
Python
2,144
74
import sys from PyQt5 import QtWidgets, QtGui import matplotlib import matplotlib.figure from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar class PrettyWidget(QtWidgets.QWidget): def __init__(sel...
0b143735a91b4455ce8139d5fefc512d00e66583bc857a6c73bd40e45e68cc0f
Python
2,146
59
from PymoNNto.Exploration.Evolution.Devices.Evolution_Device import * from multiprocessing import Process, Pipe #import subprocess #import time #import os import numpy as np import sys import traceback def local_thread_worker(slave_file, evo_name, static_genome, conn): #try: # import psutil as psu # ...
97a1a64a9686295c8b78053cef0d44757e57496fa283b7b418e844833e0d047e
Python
2,147
81
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """DataLoader module.""" class DataLoader: """A base class used to represent a Federated Learning Data Loader. This class should be inherited by any data loader class specific to a machine learning framework. Attributes:...
78883acbf74b7dd0fa43368db08f419a1c2bf2d5f030026106612cf3db8be300
Python
2,148
64
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 12 15:25:17 2018 @author: ngritti """ from deeprest.rawDataClass import rawData from deeprest.modelClass import modelRest from deeprest.timeLapseClass import sampleTimeLapse import time, glob, os, shutil from tifffile import imread, imsave from skim...
6acecfbb69590646a8825f4c6a4c6ffa2cbdc780e87ae5b28c4d8da8d3e30857
Python
2,150
61
import numpy as np from SALib.sample import saltelli import numpy as np from SALib.analyze import sobol from matplotlib import pyplot as plt print("Def SA problem") problemDef = { 'num_vars': 5, 'names': ['k_iAno1', 'k_iNSCC', 'k_iCa50', 'k_iSK', 'k_eIP3'], 'bounds': [[0.28873, 0.34498], [0...
aa910abddd82ff3fed63622ac5d0707703d7fa5974fe776d9a0a7215fcf41b8f
Python
2,153
92
from .. import logger class Buffer(): """ Class representing the stream's buffer. This is not a Python Buffer Interface compatible class. Parameters ---------- bufsize : int Buffer's size [samples]. winsize : int To extract the latest winsize samples from the buffer [sampl...
eab8694d578106367d4707de747daa9a6ded7036e41184ffa30c5deb801b07e4
Python
2,155
68
# An implementation of https://en.wikipedia.org/wiki/Rendezvous_hashing from typing import Callable, List, Tuple import mmh3 import heapq Hasher = Callable[[str, str], int] Member = str Members = List[str] Key = str def assign( key: Key, members: Members, hasher: Hasher, replication: int ) -> List[Member]: "...
35f4b83b541005d10a286bb6159a20635986310e2dae168a8f536dad62758518
Python
2,157
62
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
299a855fb58b132876c02b7cefb8975d582e22957ea451f521c41935a4b7efae
Python
2,158
72
from PymoNNto.NetworkCore.Neuron_Group import * from PymoNNto.NetworkCore.Behavior import * import numpy as np class Synaptic_Normalization(Behavior): def initialize(self, neurons): self.syn_type = self.parameter('syn_type', 'GLU', neurons) self.clip_max = self.parameter('clip_max', None, neurons)...
8f63438d58b22b3bb5dd18c6eb54507ff3c904d512eec174ec93f512ef4cbd16
Python
2,158
65
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
9dca013b3873d709ec9685c0a87173c745c3a8198e44270a0ff43c80fdbf221d
Python
2,159
61
from PymoNNto.Exploration.Network_UI.TabBase import * from PymoNNto.NetworkCore.Base_Attachable_Modules import * from PymoNNto.Exploration.StorageManager.StorageManager import * from PymoNNto.Exploration.Network_UI.Basic_Tabs.info_tabs import * from PymoNNto.Exploration.HelperFunctions.Save_Load import * import copy im...
722c38a93b1c88d0503cbee531a32311162fe6329e9eaf6a0e5dfb03db95a0e8
Python
2,160
74
import random import pytest from geomstats.geometry.hyperboloid import Hyperboloid from geomstats.geometry.minkowski import Minkowski from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test_cases.geometry.base import LevelSetTestCase from geomstats.test_cases.geometry.riemannian_metric impo...
fc7b92dbc34963144af91f17d611970686a8be5fabef6eca726285a3cd361241
Python
2,160
66
from PyQt5 import QtCore, QtWidgets from PyQt5.QtCore import QModelIndex from PyQt5.QtGui import QStandardItemModel from PyQt5.QtWidgets import QApplication, QTableView class CheckBoxDelegate(QtWidgets.QItemDelegate): """ A delegate that places a fully functioning QCheckBox cell of the column to which it's app...
e9e36e068d1cd713087fe63cb77ee6fca8663f38fcabc1530a86f856fdf1d2be
Python
2,161
67
from typing import Optional import torch from torch import Tensor class History(torch.nn.Module): r"""A historical embedding storage module.""" def __init__(self, num_embeddings: int, embedding_dim: int, device=None): super().__init__() self.num_embeddings = num_embeddings self.embed...
6f99914679ecc066a92adc581f4b76182e091fd12234597ad70b4d3c9e567e9e
Python
2,162
48
import sys import argparse import torch from hyper_dti.settings.config import get_configs from hyper_dti.trainer import DtiPredictor, CrossValidator if __name__ == "__main__": parser = argparse.ArgumentParser(description='Drug-target interaction prediction') config = get_configs(parser) log = False if ...
ad8290ee41ccbb9f9dfb05da5f696248860c8d18d9ec23957d1e4c23a397e2a4
Python
2,162
68
from PyQt5 import QtCore, QtWidgets from PyQt5.QtCore import QModelIndex from PyQt5.QtGui import QStandardItemModel from PyQt5.QtWidgets import QApplication, QTableView class CheckBoxDelegate(QtWidgets.QItemDelegate): """ A delegate that places a fully functioning QCheckBox cell of the column to which it's app...
a25231c48404a0b054786fac5fa630656932d3ef59c70573084e30e1f30b5743
Python
2,163
77
#!/usr/bin/env python3 from copy import deepcopy import numpy as np import odil cases = ["pack", "arrays"] def test(case, dim): cshape = (1 + np.array(range(dim))) * 2 dimnames = ["x", "y", "z", "w"][:dim] domain = odil.Domain(cshape=cshape, dimnames=dimnames, multigrid=1, mg_convert_all=False) s...
ba064d4cc75ee58b9cb618614a8a57ca4a5414df94fc2f698a5d23ca8241bca4
Python
2,163
85
"""A simple bucket counter Increments the count for a bucket when an item is added. Can test if the bucket is full. """ from __future__ import annotations all = ["BucketCounter"] from collections import Counter from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Hashable class Buck...
dfd3fc3f4febbb9718de69eab88d53cccc372cffe338ee1f7aea0fdf1c24bf9f
Python
2,163
66
import sys sys.path.append('../../../TREN2') sys.path.append('../../../tren2') from PymoNNto.Exploration.StorageManager.StorageManager import * smg = StorageManagerGroup('SORN_Gram_train_time_100k')# SORN_One_layer_all_600 x=[] y=[] for ms_i, sm in enumerate(smg.StorageManagerList): try: network = sm.lo...
1d32bcf233d0dc523e5afa5792edc0014e3fea5356080366228b6bacef891654
Python
2,164
65
import sys import numpy as np import umap import csv from scipy.sparse import coo_array def load_spike_times(spikingFile): """ Load spike times from the file specified by the variable spikingFile """ preEI = list() with open(spikingFile, newline='') as csvfile: spikeTimes = csv.reader(csvfile,...
6d0a1d582588547f461c2ad2875facb60af3be7c1697b3b46b00863ff9b380ef
Python
2,164
68
""" Visualize the wave detection by means of clustering the detected trigger in (time,x,y) space. """ import numpy as np import quantities as pq import argparse from pathlib import Path import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import seaborn as sns import random import warnings from...
18ccbed4c2af339035facbf8ddc477a91383df0b0466345c34cf876d440cf6f4
Python
2,167
69
import geomstats.backend as gs from geomstats.geometry.euclidean import Euclidean from geomstats.geometry.spd_matrices import ( SPDAffineMetric, SPDEuclideanMetric, SPDMatrices, ) from geomstats.learning.geometric_median import GeometricMedian from geomstats.test.data import TestData from ._base import Bas...
592eedf7bf2d0caccc775e35f1d7fd1c82a8f0b9eece17d32051c9cd2eb1e00d
Python
2,167
61
import csv import matplotlib.pyplot as plt import numpy as np def _decode_train_csv(csv_path): epochs = [] train_loss = [] val_loss = [] dice = [] with open(csv_path) as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: epochs.append(row['step'...
b141bd8c40715b05c3b6f994dc4c9ed0cbe3add1ff52452ec6aef77295b6907e
Python
2,167
66
import os import copy import numpy as np from cloudfiles import CloudFiles from corgie import layers from corgie import exceptions from corgie.log import logger as corgie_logger from corgie.data_backends.base import DataBackendBase, BaseLayerBackend, \ register_backend, str_to_backend @register_backend("js...
8f78c3c008818ea529507f1a1c2f4842f74e8bc39898db9b8ec33766c4cb7b5a
Python
2,169
72
import json from pathlib import Path import click import pandas as pd def read_json(file: Path) -> pd.DataFrame: with file.open('r') as f: d: dict = json.load(f) transformed_dict = { "metric": [], "metric_name": [], "class": [], } for k in d.keys(): for c in ...
456cf9739635a1b0340a1578bfda0d7276f8ab0b504a636992c57d051c914f8f
Python
2,170
57
import pytest import geomstats.backend as gs from geomstats.test_cases.geometry.base import VectorSpaceTestCase from geomstats.test_cases.geometry.mixins import GroupExpTestCaseMixins from geomstats.test_cases.geometry.riemannian_metric import RiemannianMetricTestCase class EuclideanTestCase(GroupExpTestCaseMixins, ...
b5bc0f08cdc421264202bfc0b0885fe1ec5637bba92d7f22b6c81b04489522c2
Python
2,170
51
import numpy as np import h5py import networkx as nx import pandas as pd import scipy.sparse as sps import os df_instances = pd.read_csv('instances_list.csv') instances_list = df_instances.instances.tolist() df_classify = df_instances for i in range(len(df_instances)): ins = df_instances.loc[i,'instan...
8172d7df9ff3b8a45c23bdcb7a2a81160a214d8e86a1d5f540a24b46dedc94a7
Python
2,172
63
import argparse import importlib import logging from .start_live2p import start_live2p, DEFAULT_IP, DEFAULT_PORT def make_args(): parser = argparse.ArgumentParser() # add arguments here # turns on all debugging, incl websocket package parser.add_argument('-d', '--debug', d...
2a76190d9f1638c3296051c21c22215314357a14b3a3ce4f138df198202c920b
Python
2,173
71
import os import sys import platform import subprocess import pandas as pd from tqdm import tqdm def get_simulation_time(byte_out): str_out = byte_out.decode("utf-8") result = [ line for line in str_out.split("\n") if line.startswith("simulation time:") ] return result def get_number(line, s...
377531ffbc200b4357fb56b2b357c20e50c129a6fbc40d15b4d439c2d0ce19c8
Python
2,173
62
import math import pytest import geomstats.algebra_utils as utils import geomstats.backend as gs from geomstats.geometry.hypersphere import Hypersphere from geomstats.test.test_case import TestCase class AlgebraUtilsTestCase(TestCase): @pytest.mark.random def test_taylor_functions_even_exp(self, taylor_func...
ad92beed844d72d28f6e69d0cdf6f1882fa33d80d5f9e02713f539d5814968e0
Python
2,173
59
# Copyright 2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from abc import abstractmethod import numpy as np import torch from openfl.federated.data.sources.verifiable_dataset_info import ( VerifiableDatasetInfo, ) class VerifiableMapStyleDataset(torch.utils.data.Dataset): """Base class for d...
b0d22c79bd54df28f7f9eb803af54364855e40a914f123257003bfb911a97702
Python
2,174
70
#------------------------------------------- # Data #------------------------------------------- DATA_PATH = '' EPOCH = [0.5, 3.5] #------------------------------------------- # Trigger #------------------------------------------- TRIGGER_FILE = '' TRIGGER_DEF = ['LEFT_GO', 'RIGHT_GO'] LOAD_EVENTS = {'selected':'Fals...
483c20a02cadc7ce0df5120a0eae686a0f807f81780006b98b5d1556f2df9bfe
Python
2,175
65
from typing import Dict, List, Optional import logging from rdkit.Chem.rdmolfiles import MolToSmiles from reinvent.chemistry import conversions from reinvent.chemistry.standardization.filter_configuration import FilterConfiguration from reinvent.chemistry.standardization.filter_registry import FilterRegistry logger...
b0b34b34cf7c8c18e384571f50cbc1e95439104099b92893daed820ea8511515
Python
2,178
60
"""Module that defines useful metrics to monitor a model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from sleeprnn.common import constants def confusion_matrix(logits, labels, masks=None): """Returns TP, FP and FN""" ...
c8722189d7f12d5928217a8e23886a17fc8e9ea983251381e188fe8b9d6a76e9
Python
2,180
74
from __future__ import absolute_import import numpy as np from numpy.testing import assert_allclose from nose.tools import assert_equal, assert_true, raises import pycircstat as circ test_data_2d = np.array([ [0.58429, 0.88333], [1.14892, 2.22854], [2.87128, 3.06369], [1.07677, 1.49836], [2.9696...
9a3b027e6302507bcc39dda32ca1953125da0cec64347133d648cfc644d3f019
Python
2,184
68
import pytest import geomstats.backend as gs from geomstats.test_cases.learning._base import BaseEstimatorTestCase class TangentPCATestCase(BaseEstimatorTestCase): @pytest.mark.random def test_fit_inverse_transform(self, n_samples, atol): X = expected = self.data_generator.random_point(n_samples) ...
e62d87573ad575218c61bf72dc616d66082cbb1fab102bbacdcf75648c224ae3
Python
2,185
63
""" -------------------------------------------------------------------------------- Date: 09/12/2021 @author: Nikolaos Vardalakis -------------------------------------------------------------------------------- Implementation Notes -------------------------------------------------------------------------------- ...
0d906e4ddd57589e2d013cf985ec0512a6d9c2dd98c9ddc8414ba2a464b5df16
Python
2,186
70
# Copyright 2020-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import pytest import logging import os from tests.end_to_end.utils.tr_common_fixtures import ( fx_federation_tr, ) from tests.end_to_end.utils import federation_helper as fed_helper import json import tests.end_to_end.utils.defaults as...
8c6b345492c59aece901f015325ad8eed6e4b36f2487c0619f6e8b8b251a4a44
Python
2,186
68
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """You may copy this file as the starting point of your own model.""" from openfl.federated import KerasDataLoader from src.mnist_utils import load_mnist_shard class KerasMNISTInMemory(KerasDataLoader): """Data Loader for MNIST Da...
260d56c4cbf5360e80f3f9e533899c8c55586cc5f9d4fb1abda9c6da602bf2fe
Python
2,187
84
from __future__ import annotations __all__ = [ "set_seed", "extract_sections", "write_json_config", "get_tokens_from_vocabulary", ] import os import random import logging import numpy as np import torch from reinvent.utils import config_parse logger = logging.getLogger(__name__) def set_seed(seed:...
74c8e361622294e0963af80e5de788d8a9b43013626ff68ac5f5ccd0ee308cf1
Python
2,187
56
#!/usr/bin/env python import h5py import numpy as np import pickle import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--basis-set", type=str, default="STO-6G") parser.add_argument("--output", type=str, default="", help="Path of output file; defaults to same n...
5efdeb82fed9f2a1a7e4e9a5ec7f166cc0c128a317dbb29d9146d1956a9a32bb
Python
2,188
65
from PymoNNto import * class Basic_Behavior(Behavior): def initialize(self, neurons): neurons.voltage = neurons.vector() self.threshold = 0.5 self.leak_factor = self.parameter('leak_factor', 0.9, neurons) def iteration(self, neurons): neurons.spike = neurons.voltage > self.thr...
f301e118a875b082ec8af8438e308fd74cbc8ba364a2b50684f81996d5a64b9b
Python
2,188
57
"""Every calculator entry point must run the model at the model's dtype. Extensions create tensors mid-forward without an explicit dtype and follow the process-wide default. When that disagrees with the model, the mismatch survives the forward through type promotion and only fails in the backward, as a dtype error out...
08fdaa3f98883904e142b128c08a24e202d0dad0f77f5dad9cc1ae238c8ca39a
Python
2,189
60
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
b70b2403f1fb228fed92a572a67e508f51b8f91004460beb04fc332b34a71324
Python
2,189
53
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Federated averaging module.""" import numpy as np from openfl.interface.aggregation_functions.core import AggregationFunction def weighted_average(tensors, weights): """Compute average.""" return np.average(tensors, weights=w...
b696a2e64af8676f6ee7f080d60d7d572b6eb588ac47267894874cc228bd396b
Python
2,190
75
#!/usr/bin/env python import os import sys import matplotlib.pyplot as plt import nibabel as nib import nilearn.image as nimage import numpy as np import pandas as pd import seaborn as sns import scipy.linalg as la from glob import glob from budapestcode.utils import compute_tsnr from budapestcode.viz import make_mo...
5907369d05f09e87eb70197f42812c860599a5fb75d5aa254a51ddc44041a2b9
Python
2,191
76
from django.contrib import admin from celsus.models import Project, File, Comparison, CellType, Author, Collaborator, ExperimentType, TissueType, \ Keyword, Disease, Instrument, Organism, OrganismPart, Curtain, QuantificationMethod, DifferentialAnalysisData # Register your models here. @admin.register(Project) c...
65018a14b01b2609e894006b4fc13891f3507adde6d4879d813fc289fc6b3b9a
Python
2,191
54
from PymoNNto.Exploration.Network_UI.TabBase import * class afferent_syn_attr_plot_tab(TabBase): def __init__(self, syn_vars, title='Aff Syn',timesteps=500): super().__init__(title) self.syn_vars=syn_vars self.timesteps=timesteps def add_recorder_variables(self, neuron_group, Network...
31428f1724a22e391d6443dd815026952a5b91d67f6835fd830aeda7b5c4253a
Python
2,193
65
import json import pandas as pd import argparse from pathlib import Path def parse_df(df): """Given CSV from neuroglancer export, extract and clean points""" c1 = "Coordinate 1" coord_cols = ["x0", "y0", "z0"] exported = c1 in df.columns if exported: df[["x0", "y0", "z0"]] = ( ...
319a88d3f95fd3a49a4cf7d7a8b2b90d6d587572a36cd718d6454659dfcdf965
Python
2,197
67
from dgl.nn.pytorch import GATConv import torch import torch.nn as nn import torch.nn.functional as F class GATLayer(nn.Module): def __init__(self, g, in_dim, out_dim): super(GATLayer, self).__init__() self.g = g self.fc = nn.Linear(in_dim, out_dim, bias=False) self.attn_fc = nn.Li...
b013cddaf119288f6baf38a98fed5ac003b6c53ce3a91b60dea3b4a89b6b455a
Python
2,197
74
import cv2 import os import fastdeploy as fd def parse_arguments(): import argparse import ast parser = argparse.ArgumentParser() parser.add_argument( "--model_dir", required=True, help="Path of PaddleDetection model.") parser.add_argument( "--image_file", type=str, required=True,...
30a9976b5a244df72a68eadce5df3a90e6597574997df7755fd886fd1e6e0324
Python
2,199
75
from __future__ import annotations from typing import Iterator, List import importlib_resources as impr import more_itertools as itx from typing_extensions import NotRequired, TypeAlias, TypedDict from snakebids.io.yaml import get_yaml_io from snakebids.paths import resources __all__ = ["BidsPathEntitySpec", "BidsP...
5849bcb8b743b04bf32b809b6f5946ef005b7bce8150922550064768d9d9f1ea
Python
2,200
67
"""Convert BIDS events tables into design-matrix regressors.""" from __future__ import annotations from typing import TYPE_CHECKING import numpy as np import polars as pl if TYPE_CHECKING: import pandas as pd def events_to_dm( events: pl.DataFrame | pd.DataFrame, *, run_length: int, sampling_f...
a0da2ca6213f2c36dcaae9e434116751a894b6e1d735d34c0937982b69501e5b
Python
2,201
51
########################################################################################### # Slurm environment setup for distributed training. # This code is refactored from rsarm's contribution at: # https://github.com/Lumi-supercomputer/lumi-reframe-tests/blob/main/checks/apps/deeplearning/pytorch/src/pt_distr_env.p...
e9268bb484b28bff28eda4f32f7decab6548da1799c46241144c10a142532f22
Python
2,201
50
import logging import os import subprocess import jax from jax.lib import xla_bridge def disable_slave_loggers(logger): if jax.process_index() > 0: logger.debug(f"DeepErwin: Disabling logging for process {jax.process_index()}") logging.disable() def configure_hardware( config, ) -> None: ...
c7ca092f11899f1f1d8e4d6bb116d3fd6c79a0e2626176416d08c4736ac3fc9c
Python
2,204
71
import experiment as exp import video_system as vid import numpy as np class ObserverTest(exp.Experiment): """ A simple experiment to test ImageObservers """ default_params = { "obs_ids": None, } def run(self): obs_ids = exp.get_params()["obs_ids"] if obs_ids is None:...
d608210aa5d7bded4be756cf79dc598e6b073ded4a9a44e8d59444ac2f251977
Python
2,205
87
from pathlib import Path import os from utils import ( timing, save_projection_axes, store_features, store_on_off_features ) def parse_args(): import argparse parser = argparse.ArgumentParser( description='...' ) parser.add_argument( '-1', '--data', ...
049ad00a499df4057abf40df19991f660e675bacbaa638dcf94a3374d81ee2dd
Python
2,206
56
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. import lightning from lightning.pytorch.callbacks import Callback from lightning.pytorch.loggers.wandb import WandbLogger from nequip.train import NequIPLightningModule class WandbWatch(Callback): ...
d52b8bab6faf3c781ecc5a3a9ee18ca983ebcbceb04e91d50ed983349dfb9d0d
Python
2,207
57
"""Tests for RL intrinsic penalty functions: Sigmoid, Tanh, Linear, Erf, Step.""" import pytest from reinvent.runmodes.RL.memories.bucket_counter import BucketCounter from reinvent.runmodes.RL.intrinsic_penalty.penalties import ( SigmoidPenalty, TanhPenalty, LinearPenalty, ErfPenalty, StepPenalty,...
a31cfa02ba3c8fe921cb88fe63ac824eefb438cd41a7501b159cab9e690d821d
Python
2,210
58
import json from pathlib import Path import pandas as pd def read_json(files: list[Path]) -> pd.DataFrame: transformed_dict = { "metric": [], "metric_name": [], "center": [], "anatomy": [], "segment_volume": [], "image_volume": [], "time": [], "pt_i...
f1effb8aad27aaf83d7e5dc7f5a84c3f38da2e73d2fb075f8ae4b62eddb335cf
Python
2,212
68
"""Plot the result of a KNN classification on the sphere.""" import logging import os import matplotlib.pyplot as plt import geomstats.backend as gs import geomstats.visualization as visualization from geomstats.geometry.hypersphere import Hypersphere from geomstats.learning.knn import KNearestNeighborsClassifier ...
57bad63592a33f40514a0c163de383336bd83b301c2cb401473c6e4aaf6e3f9b
Python
2,213
89
import gzip import json import os def _convert_ext(filepath, compress): b, e = os.path.splitext(filepath) filepath = b + '.json' if compress: filepath += '.gz' return filepath def _check_ext(filepath): compress = False b, e = os.path.splitext(filepath) if e == '.gz': comp...
82d1a475959f4e747d7494a8f6a013f20bf88817ef8a75c823ee1ee073b67cbe
Python
2,213
70
import pytest from geomstats.information_geometry.beta import BetaDistributions from geomstats.information_geometry.exponential import ExponentialDistributions from geomstats.information_geometry.fisher_rao_metric import FisherRaoMetric from geomstats.information_geometry.gamma import GammaDistributions from geomstats...
519573452d2b814098f3eb0a5700a052258634aeb05743b202014a76b58a556f
Python
2,214
59
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn from fairseq.models import FairseqEncoder from fairseq.models.transformer import Linear class CTCDecoder(...
8dce59e57ca729a88a25d2227a114fd0b95fb2bb705e6bd1780cdaf13eda9636
Python
2,214
102
import analysis_utils as au import torch import seaborn as sns import matplotlib import torch.nn as nn class Layer1(nn.Module): def __init__( self, w_1, w_2, ): super().__init__() self.w_1 = nn.Parameter(torch.tensor([[w_1]])) self.w_2 = nn.Parameter(torch.tensor([[w...
0bb5c85abbdc77dd539024cd98c1bffa01f10b0e6298100e55e0c46cd835ede6
Python
2,216
51
""" Filter between a highpass and a lowpass frequency using a butterworth filter. """ import argparse import quantities as pq import os from elephant.signal_processing import butter from utils.io_utils import load_neo, write_neo from utils.parse import none_or_float CLI = argparse.ArgumentParser() CLI.add_argument("-...
52eac8b8f00633868a68136d2a2c2dd54560d7649f4ca10748deb21f8cedb6a6
Python
2,221
79
from bindsnet.network import Network from bindsnet.pipeline import EnvironmentPipeline from bindsnet.learning import MSTDP from bindsnet.encoding import bernoulli from bindsnet.network.topology import Connection from bindsnet.environment import GymEnvironment from bindsnet.network.nodes import Input, LIFNodes from bind...
5f382be61b3729b40aa4e34b0f7464653d6f44cf16d0b1590a259156b480ca44
Python
2,221
74
"""Code to calculate mel spectrograms.""" import math import librosa import numpy as np import scipy.signal def calculate_mel_spectrogram( audio_path, target_fs=64, fmin=0, fmax=5000, nb_filters=10, hop_length=None, win_length=None, ): """Calculates mel spectrogram of a raw speech file...
d174ee65eb3696ca10aff792c30bbcd0dae2549312ebef9e2383a794d77f40e1
Python
2,221
58
import os from typing import Tuple from Bio.PDB import MMCIFParser from model_angelo.utils.fasta_utils import read_fasta import pandas as pd _search_result_names = ["fasta_chain_id", "db_chain_id", "seq_sim", "chain_len"] def calculate_cif_similarities( pdb_id: str, chain_sims: pd.DataFrame, ...
0bcd7cc932a296c6b6cf66cbb5d0b763783c7dd76abb37af35fe98de1bcf8c3e
Python
2,225
68
import logging import cv2 import numpy as np from idtrackerai import Blob, Session def compute_erosion_disk(blobs_in_video: list[list[Blob]]) -> int: """Estimates the erosion kernel size as the median, over all frames, of the thickness (maximum distance transform) of the thinnest individual blob.""" min...
f8a895e4c91106847c1723b8a708a9647ccfd55d610ad31752ddf1974a5a2fca
Python
2,225
75
import glob import h5py import os import sys import numpy as np def add_target(graph_path, target_name, target_list, sep=' '): """Add a target to all the graphs contains in hdf5 files Args: graph_path (str, list(str)): either a directory containing all the hdf5 files, ...
7609c3c4c2904e98861497d4d2443fd71400b3e5cd302533e6a33a7220d77f7c
Python
2,228
54
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. import importlib import zipfile from typing import List, Final, Set NEQUIP_AOTI_INPUTS_KEY: Final[str] = "nequip_aoti_inputs" NEQUIP_AOTI_OUTPUTS_KEY: Final[str] = "nequip_aoti_outputs" NEQUIP_CUSTOM_O...
76c9c105e3e7b02ee07f9a614f5602abc04d2b807acb254ceabb79675f825b16
Python
2,228
75
"""solves using the python scientific stack""" import time import numpy as np from scipy.sparse.linalg import factorized def solve(A, weights, reg, x0, rhs): """regularized, weighted linear least squares solve Parameters ---------- A : :class:`scipy.sparse.csr_matrix` the matrix...
65c1a1bd703b002bfb224b0f18b119c8d1b591f7c07740a844b88825f29c51a4
Python
2,229
77
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
567806d356797d540af56ef2a361998952fb4b6b242820fbd11d2552813d03ae
Python
2,230
60
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 12 15:25:17 2018 @author: ngritti """ from csbdeep.models import CARE import time, os, glob, tqdm import numpy as np from csbdeep.io import save_tiff_imagej_compatible from skimage.io import imread #%% ''' register images and save them in the Regis...
7ac05addf111ccaa08f33e0903661f0eb2a965adfec083ccdd995f74d235dbcc
Python
2,233
52
""" Filter between a highpass and a lowpass frequency using a butterworth filter. """ import argparse import quantities as pq import os from elephant.signal_processing import butter from utils.io_utils import load_neo, write_neo from utils.parse import none_or_float CLI = argparse.ArgumentParser() CLI.add_argument("-...
db0d0a456e3c8dd7f32bc65b481d8985b56beda613fec932599e2bdee1d91fa1
Python
2,233
56
from sleepy.processing.processor import Algorithm from sleepy.processing.parameter import Parameter import numpy as np class BiLSTM(Algorithm): def __init__(self): self.name = "BiLSTM" def compute(self, signal): if not hasattr(self, 'BiLSTM_model'): # generate ...
ab9fdafd029cc44efaeab8524a96c57bb9421974f7bac69761fe88ac0037847a
Python
2,236
49
def return_colordic(): dict_protfam = {'Enzyme': '#1F77B4', 'Membrane receptor': '#FF7F0E', 'Transporter': '#2CA02C', 'Secreted protein': '#D62728', 'Ion channel': '#9467BD', 'Transcription factor': '#8C564B'...
46b43b65d9e45a3a6bc3494f229584797169f0ef1603c51bb743500cdda185d2
Python
2,238
49
import json import argparse from rdkit import RDLogger from torch_geometric.loader import DenseDataLoader from dig.ggraph.dataset import QM9, ZINC250k, MOSES from dig.ggraph.method import GraphDF from dig.ggraph.evaluation import RandGenEvaluator RDLogger.DisableLog('rdApp.*') parser = argparse.ArgumentParser() parse...
099b9b1a0e6be14649b7a21090966719b3148e5d086464e980859a24c05ee406
Python
2,239
83
import socket, time, os from neurodecode.utils.timer import Timer class GlassControl(): def __init__(self): self.BUFFER_SIZE = 1024 self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.last_dir = 'L' self.timer = Timer() def connect(self, ip, port): self.ip...
1217ad83f3cc0e193297c3d8672b4e0e5ecffe1ca8022564d4b72caa76a84a33
Python
2,240
81
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import importlib import os import argparse from utils import logger from ..base_criteria import BaseCriteria SUPPORTED_CLS_LOSS_FNS = [] CLS_LOSS_FN_REGISTRY = {} def register_classification_loss_fn(name): ...
adbe096c540ffaab9e7a86dc643a30e1613b7beb037bb5d10e1ce1fcaaceafc9
Python
2,240
79
import math, sys from PyQt5.QtCore import Qt, QTimer from PyQt5.QtGui import * from PyQt5.QtWidgets import * class Overlay(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) palette = QPalette(self.palette()) palette.setColor(palette.Background, Qt.transparent...
11996be65ec8bae0d912fdc0b9e3323c9c94c3eda58f7f57d86e28957cc8a7c4
Python
2,241
73
"""Module to validate the tracking data of a session, see :ref:`validator_reference`.""" import sys from argparse import ArgumentParser from multiprocessing import Process from pathlib import Path from qtpy.QtWidgets import QApplication from idtrackerai import Session from idtrackerai.utils import ( LOGGING_QUEU...
e97732b78b018640c9f7c9cf7b02f71735e357b5833b4e181261fecd17189f4d
Python
2,241
54
import numpy as np from scipy import interpolate as interpolate_ def nan_to_zero(im): """ Set all values to zero that are less than zero or nan; return the indices of all elements that are zero after the modification (i.e. those that have been nan or smaller than or equal to zero before calling this funct...
6f5c88333acbdfce781c9cafb605a4fb5fbb84f2a8fcab67007842f2daad8550
Python
2,243
96
import numpy as np def test_add_noise(): from mlspm.preprocessing import add_noise np.random.seed(0) n = 1000 c = 0.1 for _ in range(n): test_input = np.zeros((3, 10)) # The add_noise function scales the noise amplitude by the range of the data so we need at least one element ...
dcce3f83baf21bc684ae982e5971267420cfdebc7478c851b8301036a703e089
Python
2,243
52
""" Filter between a highpass and a lowpass frequency using a butterworth filter. """ import argparse from pathlib import Path import quantities as pq import os from elephant.signal_processing import butter from utils.io_utils import load_neo, write_neo from utils.parse import none_or_float CLI = argparse.ArgumentPar...
428e866f162d4423f5846809670442622d318aa5611fa5ec9ec7047513f08c00
Python
2,244
56
from sleepy.processing.processor import Algorithm from sleepy.processing.parameter import Parameter import numpy as np class BiLSTM(Algorithm): def __init__(self): self.name = "BiLSTM" def compute(self, signal): if not hasattr(self, 'BiLSTM_model'): # generate ...
a58d93992e5c99729db2d28142f1c3b57e768fe76430b10c63514b941f7080b1
Python
2,247
67
"""Plot a geodesic on the Poincare polydisk. Plot a geodesic on the Poincare polydisk, with Poincare Disk visualization. """ import matplotlib.pyplot as plt import geomstats.backend as gs import geomstats.visualization as visualization from geomstats.geometry.poincare_polydisk import PoincarePolydisk def plot_geod...
0de95dc26780b5f1333f5a079a9cfcf57d3fa44b7e933996e17c22cb8c4ef521
Python
2,248
61
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """You may copy this file as the starting point of your own model.""" from openfl.federated import KerasDataLoader from src.brats_utils import load_from_nifti class KerasBratsInMemory(KerasDataLoader): """Keras Data Loader for the...
e71b42410c7ca264ffd62a6c699576816e1b9193e6b8ea2e69f846b85ffd95eb
Python
2,249
79
import random import pytest from geomstats.information_geometry.binomial import ( BinomialDistributions, BinomialDistributionsRandomVariable, BinomialMetric, ) from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test_cases.geometry.riemannian_metric import RiemannianMetricTestCas...
9af96416f33d21d26e29cec5523900a4a61efbf5af9c9561539157bc4b7368ff
Python
2,250
91
''' Example showing software-timed (on demand) analog output pinidaqmxegs.ao.OnDemand Purpose Generates a class that can be used interactively set the voltage of an AO line. If instantiated at the Python command prompt, the user can interact with the object. If run at the system comma...
d91a8c27812e0add5c7ef1448b440ccec6722e4db39dc820108bcc56d69e47fb
Python
2,252
56
import pytest import geomstats.backend as gs from geomstats.test_cases.geometry.riemannian_metric import RiemannianMetricTestCase class ComplexRiemannianMetricTestCase(RiemannianMetricTestCase): @pytest.mark.random def test_inner_product_is_symmetric(self, n_points, atol): """Check that the inner pro...
b6af87d1f8a897666223a64bd82a3baddd292f7d8643794b2937f5526e46e2d6
Python
2,253
65
import jax import jax.numpy as jnp from typing import Tuple def generate_input_parameters( key: jax.random.PRNGKey, cfg ) -> Tuple[jnp.ndarray, float]: """ Generates input parameters for a neural network model. Args: key (jax.random.PRNGKey): Random key for generating random numbers. ...
b79a234ce1cd19331521ef1463a9ca2396f83160452b55908bc204d4afac7792
Python
2,253
67
"""Sampler setup needed for sampling and staged learning""" from __future__ import annotations from typing import TYPE_CHECKING import logging import warnings from reinvent.runmodes import samplers if TYPE_CHECKING: from reinvent.models import ModelAdapter logger = logging.getLogger(__name__) warnings.filterwar...
ecec8ed23e7066bac958c66595c631d12d54c8726df2cde4a57c0032aa0ad59d
Python
2,253
64
from chromadb.utils.rendezvous_hash import assign, murmur3hasher from math import sqrt def test_rendezvous_hash() -> None: # Tests the assign works as expected members = ["a", "b", "c"] key = "key" def mock_hasher(member: str, key: str) -> int: return members.index(member) # Highest index wi...
479a17f9302a451975365fd5d06c658f1190882f8f50f5b2e5388a03f54f4c69
Python
2,254
69
"""Provides custom loss functions for PyTorch.""" import torch import numpy as np from dival.util.constants import MU_MAX def tv_loss(x): """ Anisotropic TV loss similar to the one in [1]_. Parameters ---------- x : :class:`torch.Tensor` Tensor of which to compute the anisotropic TV w.r....
69c8abb379006bbca1b71502888dccba6ae07100dd11368eeaeab33f06d7d13c
Python
2,256
60
"""Test calculation of implied timescales.""" import numpy as np from ivac.linear import _vac_its as vac_its from ivac.linear import _ivac_its as ivac_its def vac_eval(sigmas, lag): return np.exp(-sigmas * lag) def ivac_eval(sigmas, minlag, maxlag, lagstep): assert (maxlag - minlag) % lagstep == 0 lag...