sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
5bbea1ea8f511afd6f37d856b62a4ca9299d4f1eaf663b946d2d39486652685e | Python | 2,536 | 75 | """
Modified from the History class from
https://github.com/rusty1s/pyg_autoscale/blob/master/torch_geometric_autoscale/history.py
"""
import torch
from torch import nn, Tensor
from typing import Optional
class FeatureMomentum(nn.Module):
def __init__(self,
num_embeddings: int,
em... |
b44cdb9d1a3544badc4f8a0d9004b7e0efff9806e2328861cc9fb762cafd0980 | Python | 2,536 | 84 | import os
import sys
import numpy as np
project_root = ".."
sys.path.append(project_root)
DATASETS_PATH = os.path.join(project_root, "resources", "datasets", "nsrr")
if __name__ == "__main__":
dataset_name_list = ["shhs1", "mros1", "chat1", "sof", "cfs", "ccshs"]
# Keys in dataset:
# 'dataset'
... |
faa40d1ebe1b7bbc65fa816801aee7acff336e5c3a092d7a2141aebe4ca981c1 | Python | 2,538 | 74 | """
Calculate the period between two consecutive waves for each wave.
"""
from pathlib import Path
import neo
import numpy as np
import quantities as pq
import matplotlib.pyplot as plt
import seaborn as sns
import os
import argparse
import scipy
import pandas as pd
from utils.io_utils import load_neo, save_plot
from u... |
ef5585738054290cf05136bc99c859f2fcabd72148ac0de106dce9e94e8fb3e6 | Python | 2,540 | 71 | from geomstats.metric_geometry.trees import generate_splits
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test.test_case import TestCase
from .data.trees import BaseTopologyTestData, GenerateSplitsTestData, SplitTestData
class TestGenerateSplits(TestCase, metaclass=DataBasedParametriz... |
5e48c496a62208f4e07ec2d1e425deeed60973524bc98aa8b676e6f71788cfe5 | Python | 2,542 | 42 | #*----------------------------------------------------------------------------*
#* Copyright (C) 2024 ETH Zurich, Switzerland *
#* SPDX-License-Identifier: Apache-2.0 *
#* *
... |
6c868ae5768228a83b4f29fd101da77a0a9ab1279fd272795f87915237e71dd3 | Python | 2,542 | 71 | """Tests for schema-backed MkDocs table generation."""
from __future__ import annotations
from datetime import date
import importlib.util
from pathlib import Path
from types import ModuleType
from sanpy.bAnalysisResults import (
get_analysis_result_definitions,
get_plot_result_definitions,
)
from sanpy.bDete... |
09716ca0c029eeba0cab33d8ee0f256d6f9874019250a3b52a7c877635afd9aa | Python | 2,543 | 102 | from globparams import *
from ANNarchy import *
import numpy as np
import time
import os
setup(dt=1.0, paradigm="cuda", precision="float", num_threads=os.cpu_count())
# Definition of the neuron
Izhikevich = Neuron(
parameters=f"""
a = {A}
b = {B}
c = {C}
d = {D}
... |
8d159de862c9835863311a65786ca84ad6768417d8b04111cc515d8986d1a2c1 | Python | 2,544 | 107 | import unittest
from reinvent.models.libinvent.models.vocabulary import SMILESTokenizer
class TestSmilesTokenizer(unittest.TestCase):
def setUp(self):
self.tokenizer = SMILESTokenizer()
def test_tokenize(self):
self.assertListEqual(
self.tokenizer.tokenize("CC(C)Cc1ccc(cc1)[C@@H]... |
a0b830a15a2320a5a6ba998b7f193c087d490b8e5481768c7fb4a1898ed513d8 | Python | 2,545 | 102 | from globparams import *
from ANNarchy import *
import numpy as np
import time
import os
setup(dt=1.0, paradigm="openmp", precision="float", num_threads=os.cpu_count())
# Definition of the neuron
Izhikevich = Neuron(
parameters=f"""
a = {A}
b = {B}
c = {C}
d = {D}
... |
2d530ab50efa66df26694dd1250385ddeda2da74e0611b464bddadc64448da63 | Python | 2,546 | 67 | """Align All and Compute for Graph Space.
Lead author: Anna Calissano.
"""
from geomstats.errors import check_parameter_accepted_values
from geomstats.learning.frechet_mean import AACFrechetMean
from geomstats.learning.pca import AACGGPCA
from geomstats.learning.regression import AACRegression
class AAC:
r"""Cl... |
916155c7843c40c830dc220a365d3d9aee93878fb54bf64ce3192ecc176af2b2 | Python | 2,546 | 63 | from neuron import h
class Synapse_py3:
def __init__(self,source,target,section,weight = 1):
self.input = h.NetStim(0.5)
self.input.start = -10
self.input.number = 1
self.input.interval = 1e9
self.weight = weight
self.postsyns = {}
if (type(source) == t... |
9617e85b861bdfb600cf036a2fcaf20f46c52b77f38f7db295bd5c74fbaf2038 | Python | 2,547 | 85 | from pathlib import Path
import click
import SimpleITK as sitk
def _process_patient(input_file: Path, output_file: Path, axis: str = "z"):
image = sitk.ReadImage(input_file)
# Find the Otsu Threshold
# We use the multiple threshold function here because keyword arguments
# work better than the singl... |
dd1807a8a343f7a6b9d99be341247796092665fb4a661761e9b063480fbf28ce | Python | 2,547 | 72 | __all__ = ["PairGenerator"]
from abc import ABC, abstractmethod
from collections import defaultdict
import numpy as np
import pandas as pd
class PairGenerator(ABC):
def __init__(
self, min_cardinality: int = 0, max_cardinality: int = np.inf, *args, **kwargs
) -> None:
"""__init__.
:p... |
0706cbb9ee12842dddbffb2d9b02a0b55d3b96be0570693314684c5a12d740a5 | Python | 2,548 | 108 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# -*- coding: utf-8 -*-
import os
import argparse
import logging
import random
import glob
import numpy as np
from scipy.spatial.distance import pdist, squareform
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
... |
4df1e51a106861fc5f7c2187f101285664772f9079685cc1a0309b3ded14d804 | Python | 2,549 | 66 | from concurrent.futures import ProcessPoolExecutor
from typing import Callable
import multiprocessing as mp
import os
import numpy as np
def parallel(n_cpus: int, shared_kwargs: dict, func: Callable, *args, **kwargs) -> list:
"""Wrapper to parallelize a function.
Data in *args and **kwargs is assumed to be ... |
5b2a7801bbbfb1c883dc2c6311d7d62ed09ebc8e8e1acb70c38c6d322c6ddbd8 | Python | 2,549 | 42 | #*----------------------------------------------------------------------------*
#* Copyright (C) 2024 ETH Zurich, Switzerland *
#* SPDX-License-Identifier: Apache-2.0 *
#* *
... |
7b4cff318cbad1da73da7fdccd9be61b0efe9a6b61f38b1862d0318c278f80d0 | Python | 2,549 | 63 | """
Create a plot of the channel-wise and average power spectrum density.
"""
import numpy as np
import quantities as pq
import argparse
import matplotlib.pyplot as plt
import seaborn as sns
from elephant.spectral import welch_psd
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_float
CL... |
473e9897673621a6f620c6330ecd6aac94f1e8ac825e4955cd5fc8ee109f6a68 | Python | 2,551 | 80 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 24 14:00:53 2022
@author: Tom
"""
import tensorflow as tf
from tensorflow import keras as k
tf.config.list_physical_devices()
import os
os.environ['CONDA_DLL_SEARCH_MODIFICATION_ENABLE'] = '1'
import shutil
import numpy as np
from scipy.stats import mode
import config
f... |
1beea2d541f28dadf4136bcd69b4eac6cb039fe00b702ac4fe541d9fb0a39f3d | Python | 2,553 | 83 | """
Tests the worker by using the offline pipeline on all planes. Runs start to end.
"""
import logging
from glob import glob
import sys
from live2p.utils import ptoc, tic, get_true_mm3d_range
from live2p.offline import run_plane_offline
# logging setup
# change for more or less information...
caiman_loglevel = logg... |
2db32b71df8f25e67e5f7cb60f402c72796b78ec672e00a1e4d21e86e7a91d62 | Python | 2,553 | 62 | # To add new commands, create a file in this folder implementing a command,
# import the command here and add it to the list:
from corgie.cli.downsample import downsample
from corgie.cli.upsample import upsample
from corgie.cli.compute_field import compute_field
from corgie.cli.compute_stats import compute_stats
from c... |
5c9781180534d4a97b22277fb03501297fb48f51e38b477939fa16407fcde452 | Python | 2,554 | 64 | """
Create a plot of the channel-wise and average power spectrum density.
"""
import numpy as np
import quantities as pq
import argparse
from pathlib import Path
import matplotlib.pyplot as plt
import seaborn as sns
from elephant.spectral import welch_psd
from utils.io_utils import load_neo, save_plot
from utils.parse... |
5cb428c17047f5e181ee3e6f9c8ef3755250578b0a02b1b08cfcf61ed223159a | Python | 2,554 | 57 | import torch
from torch.utils.data import random_split, Subset
from torch_geometric.data import DataLoader
from dig.xgraph.dataset import MoleculeDataset, SynGraphDataset, SentiGraphDataset, BA_LRP
from torch import default_generator
def get_dataset(dataset_root, dataset_name):
if dataset_name.lower() in list(Mol... |
11a8bafea740ac61ca95f6e68b516cf143767e1271a7007d31b7f691a0047b54 | Python | 2,556 | 78 | from pymonntorch import *
import torch
import time
from matplotlib import pyplot as plt
from globparams import *
settings = {'dtype': torch.float64, 'synapse_mode': "DxS", 'device': 'cpu'}
class LeakyIntegrateAndFire(Behavior):
def initialize(self, neurons):
neurons.spikes = neurons.vector(dtype=torch.bo... |
bcf8f1886921c6341e9a7b5af94d842945829452501513b9b65d068a7036c72e | Python | 2,556 | 78 | from pymonntorch import *
import torch
import time
from matplotlib import pyplot as plt
from globparams import *
settings = {'dtype': torch.float32, 'synapse_mode': "DxS", 'device': 'cpu'}
class LeakyIntegrateAndFire(Behavior):
def initialize(self, neurons):
neurons.spikes = neurons.vector(dtype=torch.bo... |
1824666ba00889a174f4422b6ba315c94a747cc129e1795bbf5f3f43bb9c3bd5 | Python | 2,558 | 82 | """DDP smoke test: 2-process CPU training (gloo backend).
First CI coverage of mace/tools/distributed_tools.py: an actual multi-process
run of run_train --distributed --launcher torchrun. The two ranks are spawned
directly with a static rendezvous on 127.0.0.1 (instead of the torchrun
launcher) so the test does not de... |
e5c9b2d0f2eab552aa87a9cb1d8ad1303c52da3592e312eb13ef1ac5966946ee | Python | 2,558 | 68 | import pytest
import unittest
import numpy as np
import numpy.testing as npt
import torch
import torch.utils.data as tud
from reinvent.models import Mol2MolAdapter
from reinvent.models.transformer.core.dataset.dataset import Dataset
from reinvent.models.transformer.core.enums.sampling_mode_enum import SamplingModesEn... |
edfb3044d5af0a66fb337a276c2679dd0982fd9afe6e2e36808252d72c8e4859 | Python | 2,558 | 63 | import unittest
import numpy as np
import numpy.testing as npt
import pytest
import torch
import torch.utils.data as tud
from reinvent.models import TransformerAdapter, Mol2MolModel
from reinvent.models.reinvent.models.vocabulary import SMILESTokenizer
from reinvent.models.transformer.core.dataset.dataset import Data... |
eaceb5579e7cdeeea12b3ed483ca3b798d20875ab91310eabc4aaa8a5e3e03e5 | Python | 2,559 | 78 | from PymoNNto import *
import time
from globparams import *
settings = {'dtype': float64, 'synapse_mode': SxD}
class LeakyIntegrateAndFire(Behavior):
def initialize(self, neurons):
neurons.spikes = neurons.vector('bool')
neurons.spikesOld = neurons.vector('bool')
neurons.voltag... |
f885816c848214dd10aaca9e9778ab9ac9655d1190d8d87a07e95ae3a498385e | Python | 2,559 | 78 | from PymoNNto import *
import time
from globparams import *
settings = {'dtype': float32, 'synapse_mode': SxD}
class LeakyIntegrateAndFire(Behavior):
def initialize(self, neurons):
neurons.spikes = neurons.vector('bool')
neurons.spikesOld = neurons.vector('bool')
neurons.voltag... |
99b7c66cc3d1c1c9686b4b339a6afbea348add0235e8432a3550c454df57e695 | Python | 2,560 | 96 | import pandas as pd
import numpy as np
import scipy.stats as stats
import pyfizi
class TausSeries(pd.Series):
@property
def _constructor(self):
return pyfizi.TausSeries
@property
def _constructor_expanddim(self):
return pyfizi.Taus
class Taus(pd.DataFrame):
"""
Thin wrapper... |
dff51332911665e0638cdccfbcf7c7208f442d3d53197f1e1462b84f19c76a84 | Python | 2,560 | 84 | import numpy as np
import pandas as pd
from sanpy.fileloaders.fileLoader_base import fileLoader_base, recordingModes
from sanpy.sanpyLogger import get_logger
logger = get_logger(__name__)
class fileLoader_text(fileLoader_base):
loadFileType = "sanpy"
# @property
# def loadFileType(self):
# ret... |
3187d19638937c7e6846c3f933bf0b683416b9723c2f82b59ebb0ff2284263d3 | Python | 2,562 | 75 | import sys
import os
import pandas as pd
f1 = sys.argv[1]
f2 = sys.argv[2]
f3 = sys.argv[3]
f4 = sys.argv[4]
r = sys.argv[5]
list_of_files = [f1, f2, f3, f4]
d_p = {}
out = open("All_Peaks_Merged_" + r + "_Fast.bed", 'w')
for f in list_of_files:
o = open(f)
d = {}
for line in o:
l = line.replace("\... |
714d21a565081e20a3f7f90b5b8dcfd3fe487412912bbf8018309e283c3e447e | Python | 2,563 | 117 | import random
import geomstats.backend as gs
from geomstats.test.data import TestData
def _sum_squares(x):
return gs.sum(x**2)
def _jacobian_sum_squares(x):
return 2 * x
def _sum_squares_val_and_grad(x):
return _sum_squares(x), _jacobian_sum_squares(x)
def _hessian_sum_squares(x):
return 2 * gs... |
84bbcf4831a3d02e03c7da80e37b15d1866af435b566a9ec522645de95f1e81f | Python | 2,565 | 81 | import pytest
import geomstats.backend as gs
from geomstats.test.random import RandomDataGenerator
from geomstats.test_cases.learning._base import BaseEstimatorTestCase
class WrappedGaussianProcessRandomDataGenerator(RandomDataGenerator):
def __init__(self, space, prior):
super().__init__(space)
... |
618c40068d586753b579489c17511c00958c976735c3e370e35146ac3dca67bd | Python | 2,566 | 79 | from pydantic import BaseModel, Field
from typing import Any, Dict, List, Optional
from chromadb.api.types import (
CollectionMetadata,
Include,
IncludeMetadataDocuments,
IncludeMetadataDocumentsDistances,
)
class AddEmbedding(BaseModel):
# Pydantic doesn't handle Union types cleanly like Embeddin... |
f64ffe6e9f60539c7203651479aca3676524e8d9e0e8912e4ee82b2d826ad374 | Python | 2,567 | 82 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import json
import logging
import os
import time
from tensorboardX import SummaryWriter
from openfl.callbacks.callback import Callback
logger = logging.getLogger(__name__)
class MetricWriter(Callback):
"""Log scalar metrics at the en... |
2d6dbceadd1b4728d4717d4b6c87c31acfdad199bb447070cb8e309165fe78e1 | Python | 2,569 | 78 | from pymonntorch import *
import torch
import time
from matplotlib import pyplot as plt
from globparams import *
settings = {'dtype': torch.float32, 'synapse_mode': "DxS", 'device': 'cuda'}
class LeakyIntegrateAndFire(Behavior):
def initialize(self, neurons):
neurons.spikes = neurons.vector(dtype=torch.b... |
6a13ac786b15b2f6c948a59e90684d18c68fe2b174ae2b4a715fbb9971f58ad3 | Python | 2,569 | 78 | from pymonntorch import *
import torch
import time
from matplotlib import pyplot as plt
from globparams import *
settings = {'dtype': torch.float64, 'synapse_mode': "DxS", 'device': 'cuda'}
class LeakyIntegrateAndFire(Behavior):
def initialize(self, neurons):
neurons.spikes = neurons.vector(dtype=torch.b... |
456f6444db1f70bb1f0435d6a70c103986d0c1c20e2f1b3c26f4fefcc4c7228b | Python | 2,570 | 68 | from typing import Optional, Set
import grpc
from tenacity import retry, stop_after_attempt, wait_exponential_jitter, retry_if_result
from opentelemetry.trace import Span
class RetryOnRpcErrorClientInterceptor(
grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor
):
"""
A gRPC client interc... |
42db345c8e3df1b2dbff6e618e82ea4ff8a12c4e9970687fc3afebdde4ba6eef | Python | 2,572 | 78 | """Pure URL-normalization tests for the foundation-model downloaders.
No network access: downloads are monkeypatched.
Split out of tests/test_calculator.py."""
from pathlib import Path
import pytest
import mace.calculators.foundations_models as foundations_models
from mace.calculators import mace_off
@pytest.mark... |
69b0c0517adb25929d583754c6913bc9a50f8b84ac40bb2ae1e2a65320561bc0 | Python | 2,573 | 70 | # Copyright (C) 2020-2023 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Data Splitters tests module."""
import numpy as np
import pytest
from openfl.utilities.data_splitters import DirichletNumPyDataSplitter
from openfl.utilities.data_splitters import EqualNumPyDataSplitter
from openfl.utilities.data_spli... |
3b461d9b1f3b1413164d1cca11f93993baa45c5237e281bdec0eda04ef019aae | Python | 2,574 | 75 | # 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.
"""
Train a network across multiple GPUs.
"""
from fairseq.dataclass.configs import FairseqConfig
from fairseq.distributed import utils as di... |
a02679533a4af9fe62addc33ca40bde355b932a5af0fd761af04541699348d35 | Python | 2,574 | 77 | # Copyright (C) 2020-2023 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Assigner tests module."""
from unittest import mock, TestCase
import pytest
from openfl.component.assigner import Assigner
@pytest.fixture()
def assigner():
"""Initialize the assigner."""
assigner = Assigner
assigner.d... |
000c0d0c7659f316b270b81acaa54be15590dd2b299ddbbbc59ae345b83cdb71 | Python | 2,575 | 80 | from PymoNNto import *
import time
from globparams import *
settings = {'dtype': float64, 'synapse_mode': DxS}
class LeakyIntegrateAndFire(Behavior):
def initialize(self, neurons):
neurons.spikes = neurons.vector('bool')
neurons.spikesOld = neurons.vector('bool')
neurons.voltag... |
78cc918a8ede3eac8b0b8f189a8fca93f01e3f13d2abef8f26d4d1a4c4f814bd | Python | 2,575 | 80 | from PymoNNto import *
import time
from globparams import *
settings = {'dtype': float32, 'synapse_mode': DxS}
class LeakyIntegrateAndFire(Behavior):
def initialize(self, neurons):
neurons.spikes = neurons.vector('bool')
neurons.spikesOld = neurons.vector('bool')
neurons.voltag... |
c857b066fea352cf0b1e9c884a662af997a002c555cefd538b8da43ec4d49d95 | Python | 2,575 | 86 | # 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... |
e3ad567fe99bb8792996945cf5f779a04ac977f62c50408a5a1afad1374a1ca8 | Python | 2,576 | 70 | import unittest
import pytest
import torch
import torch.utils.data as tud
from reinvent.models.transformer.core.dataset.dataset import Dataset
from reinvent.models.transformer.core.enums.sampling_mode_enum import SamplingModesEnum
from reinvent.models.transformer.core.vocabulary import SMILESTokenizer
from reinvent.m... |
37578aba0d8eca657a7d3fd0bf3346ceb625fec4488a14c1d37bb23db786885a | Python | 2,577 | 78 | #!/usr/bin/env python
import json
from typing import List
import nibabel as nib
import numpy as np
from numpy import ndarray
def compute_iou(
tissue_prob_vol: ndarray,
tissue_k_seg: ndarray,
sim_prior: ndarray,
thresh: float,
) -> None:
s1 = tissue_prob_vol > thresh
s2 = tissue_k_seg > thresh... |
e1344d987ba4620deb246512b6a5e9198f8ec3a7905703cafae92472571367eb | Python | 2,577 | 88 | import numpy as np
# import matplotlib.pyplot as plt
import torch
import h5py
import torch.nn as nn
from torch.utils import data
import itertools
import json
import sys
from os import path
# We define our custom Sequence DataSet, which provides the
# the one-hot encoding on the fly.
class SequenceDataSet(torch.util... |
89bef8007a204875a8a98b059706bf87fcc21b15dcbb131f913bbd2a884fbb92 | Python | 2,578 | 42 | #*----------------------------------------------------------------------------*
#* Copyright (C) 2024 ETH Zurich, Switzerland *
#* SPDX-License-Identifier: Apache-2.0 *
#* *
... |
8e9691cab8adc17a9a1255d544b947c8d7dc17a0d09513d044dadb5009eb32d9 | Python | 2,578 | 71 | from typing import Any, Dict, Optional
import torch
from torch import nn
class GenericJointEmbedding(nn.Module):
"""
Simple concat‐fusion of any set of node‐ or graph‐level features
with a base embedding. All features are embedded (via Embedding or small MLP),
then concatenated onto `species_emb`, p... |
bc26fa829d5abb4473aa82e780fbfce23e2fcaac3bbd7b675fcc114e190d08f0 | Python | 2,578 | 64 | '''
get_zdFF.py calculates standardized dF/F signal based on calcium-idependent
and calcium-dependent signals commonly recorded using fiber photometry calcium imaging
Ocober 2019 Ekaterina Martianova ekaterina.martianova.1@ulaval.ca
Reference:
(1) Martianova, E., Aronson, S., Proulx, C.D. Multi-Fiber Photometry
... |
ecece7639bbadd6b77a658c713fb5bb455f876312874e894cda52a8c3b171fd7 | Python | 2,581 | 86 | import random
class TestData:
"""Class for TestData objects."""
fail_for_autodiff_exceptions = True
fail_for_not_implemented_errors = True
trials = 3
skip_vec = False
# TODO: remove after refactoring stratified
skip_all = False
xfails = ()
skips = ()
tolerances = {}
N_VE... |
04bc7e118b919c8be3a6057cba1e6b630e55c69b6abce76c4da69a1dc57b7b9d | Python | 2,582 | 84 | from PymoNNto.Exploration.StorageManager.StorageManager import *
from PyQt5.QtWidgets import *
import sys
from PyQt5.QtGui import *
import PymoNNto
from PyQt5 import QtCore
class SM_D_S_Dialog(QDialog):
def __init__(self, parent=None):
super(SM_D_S_Dialog, self).__init__(parent)
layout = QVBoxLay... |
6fb2efcc73a0fff4b12a3c5157fa791d0dd3bce3b09249f9413f6167e5f83c53 | Python | 2,584 | 84 | import random
import pytest
from geomstats.geometry.hypersphere import Hypersphere
from geomstats.information_geometry.multinomial import (
MultinomialDistributions,
SimplexToPositiveHypersphere,
)
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test.random import DiffeoBasedRand... |
4b30758ecbee03762bcf2762b1073605819dda65cfa64b40e2b69fb603fec331 | Python | 2,585 | 83 | import httpx
import pytest
import chromadb.errors as errors
from chromadb.api.base_http_client import BaseHTTPClient
def _error_response(body: object) -> httpx.Response:
return httpx.Response(
status_code=400,
json=body,
request=httpx.Request("GET", "http://localhost/api/v2/test"),
)
... |
30587b1f072ef36b35618fb5a1c2b7060860de2516ecfa5710b56aa0d31cecaa | Python | 2,586 | 80 | from PymoNNto import *
import time
from globparams import *
settings = {'dtype': float64, 'synapse_mode': SxD}
class LeakyIntegrateAndFire(Behavior):
def initialize(self, neurons):
neurons.spikes = neurons.vector('bool')
neurons.spikesOld = neurons.vector('bool')
neurons.voltag... |
46d830f098046dce1cc8f1f68e5922fa67211a1c29dde899fb492c8e8a2ab931 | Python | 2,587 | 70 | # script to sample from ESM-IF for certain numbers of mutated positions in GFP across temperatures
import esm
import pickle
import numpy as np
import importlib
import pandas as pd
import time
import sys
import torch
import random
random.seed=3
models_dir = "models"
device = "cuda" if torch.cuda.is_available() else ... |
5ec9fb164f3804d6205a84bf0733e44ff7cff1e702796dd5fdea41f4ba0cf542 | Python | 2,588 | 56 | import numpy as np
import pytest
from reinvent_plugins.components.RDKit.comp_physchem import Qed
from reinvent_plugins.components.RDKit.comp_physchem import MolecularWeight
from reinvent_plugins.components.RDKit.comp_physchem import GraphLength
from reinvent_plugins.components.RDKit.comp_physchem import NumAtomStereoC... |
90bb67f988602598676222f253ba3fa803f4e4d130d20fcd8f64452e123fcb83 | Python | 2,588 | 86 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Cryptography participant utilities."""
from typing import Tuple
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitive... |
f5a426dc02a6d3ac2dc6fc25f146fee38e33f7fbff4f337b1d9d7a42d9461bae | Python | 2,588 | 84 | import io
import os
import pickle
import pytest
from chromadb.segment.impl.vector.local_persistent_hnsw import (
PersistentData,
SafeUnpickler,
)
def test_safe_unpickler_blocks_exploit():
"""Malicious pickle payload must be rejected (CWE-502)"""
class Exploit:
def __reduce__(self):
... |
121181a3ee6a15560ce0afcd4dd6bc42c2c0a44f1dde627495ab296355033711 | Python | 2,589 | 72 | # 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... |
c9b483e6cecce94819d0f0397186e3e20bc97055c3694f7c1cbb916616097648 | Python | 2,590 | 85 | import json
import os
from typing import Dict, Any, cast
import jsonschema
from jsonschema import ValidationError
# Path to the schemas directory
SCHEMAS_DIR = os.path.join(
os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
),
"schemas",
"embedding_fu... |
bb87fd784ddd923ff0bc2d082080f809ae10bfd37509ab9170c5f86caa9fa991 | Python | 2,592 | 84 | # SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2020-2026, Christian Gaser. See LICENSE.
"""
Build the exact TFCE max-tree as a Python extension.
The C core is shared with the MATLAB toolbox and lives at the repository root.
There is exactly one implementation of TFCE in this repository and both bindings
sit o... |
e82ca32d270616c4205383b655932d8bc5b93badfe91afa842fdc4c70ab667ce | Python | 2,593 | 91 |
from unittest.mock import MagicMock
from sleepy.gui.tagging.model import Navigator
from sleepy.gui.tagging.model.event import PointEvent
from sleepy.gui.tagging.model import DataSource
from sleepy.processing.dataset import Dataset
import numpy as np
class TestBase:
"""Provides a set of constructors for d... |
ec2bad0a336cd14eb3e83b4acee42651d516af015081d172acee136b8e711371 | Python | 2,593 | 75 | import random
import pytest
import geomstats.backend as gs
from geomstats.test_cases.learning._base import BaseEstimatorTestCase
def make_labels(n_samples):
samples = gs.zeros(n_samples, dtype=int)
indices = range(n_samples)
samples[random.sample(indices, n_samples // 2)] = 1
return samples
class... |
918f10fb1172521d9bfcaa0e4df1d547c2bfa87b570725475572b2888913eb77 | Python | 2,595 | 64 | import pytest
import geomstats.backend as gs
from geomstats.test.test_case import TestCase
from geomstats.test_cases.learning._base import BaseEstimatorTestCase
class RiemannianEMTestCase(BaseEstimatorTestCase):
@pytest.mark.random
def test_estimate_belongs(self, n_samples, atol):
X = self.data_gener... |
3eb1b3a23b17d0f01f32dfad046905527ffccb60498c9e612e997445b7fe04e2 | Python | 2,597 | 63 | """
fasta='step2/prot_sequences.fasta' # peptide_sequences.fasta
outpath='step2/ss/prot_ssp'
scratchtool="/home/ec2-user/SageMaker/efs/data/CAMP/tools/SCRATCH-1D_2.0/bin/run_scratch1d_predictors.sh --input_fasta $fasta --output_prefix $outpath "
fasta='step2/peptide_sequences.fasta' # peptide_sequences.fasta
outpath='... |
0f8bef7dc48199489e8238773931aa91d501e665256779502178ece487bc0784 | Python | 2,598 | 87 | """Tests for the untested branches in datapipeline/filters/regex.py.
The existing test_unwanted_tokens.py covers the reject-all path (charged/halogen
tokens) and verifies that plain aspirin passes. These tests target the
isotope/stereo branches and multi-molecule behaviour.
"""
import pytest
from types import Simple... |
3cdab4ffc07e2439c332558d7c2f054395b7c19fea33743e774f6e134d3da899 | Python | 2,598 | 87 | # -*- coding: utf-8 -*-
"""
Created on Wed March 20 2024
@author: mte
"""
import argparse
import json
import os
import traceback
import warnings
import numpy as np
from tvb.simulator.lab import *
from pydfc import simul_utils
warnings.simplefilter("ignore")
os.environ["MKL_NUM_THREADS"] = "16"
os.environ["NUMEXPR_... |
6235f46b9ec5ff6d17a452de0f826a02256ff426763123819cc6228f1e43a341 | Python | 2,598 | 58 | """Shared helpers for the permutation tests: sign flips, z-from-p, the stability epsilon and progress bars."""
import numpy as np
from ...utils import _NullProgressBar, _make_progress_bar, _maybe_tqdm # noqa: F401
from .random import _generate_sign_flips as _generate_sign_flips # noqa: F401
# =====================... |
49ad01ae5619abb913f08921304f32dc7ce4f9cf0286f5e52e58a65bfa2b2981 | Python | 2,599 | 47 | # =====================================================================================
# FIGURE 8 panel (d) - D-Fine, built from the SAVED confusion_matrix.csv (NO D-Fine env).
# Notebook 2 already saved this during D-Fine's Phase-1 run. Just read + restyle it.
# Run in ANY session (CPU is fine). Only needs Drive moun... |
4dc00979a1731dfc17f54883a734b102979163a6bb64e3c7e003a38256f11935 | Python | 2,604 | 85 | import pdb
import time
from torch.cuda.amp import autocast
import torch.autograd.profiler as profiler
# functions
divider = '---------------------------------------'
def time_function(fun, include_gradients, iterations, *args, **kwargs):
res = fun(*args, **kwargs)
grad_tensor = torch.ones_like(res)
torch... |
5e0d7b0574d7faf9cca1035a75379f2977d3b5bebb194534b3297dd0d3f1a4af | Python | 2,605 | 81 | """Config Validation"""
from typing import List, Optional
from pydantic import Field
from reinvent.validation import GlobalConfig
class SectionParameters(GlobalConfig):
prior_file: str
agent_file: str
summary_csv_prefix: str = "summary"
use_checkpoint: bool = False
purge_memories: bool = True
... |
77d9f3aaaa2f5fab154b68e1c7cd09430f361ed64bc3bc1442bad40a50ff6342 | Python | 2,605 | 90 | '''
Utilities to extract datasets of N images divided in M classes
from a whole dataset.
'''
import os
import shutil
from xml.dom import minidom
def select_indeces(valid_classes, max_imgs, xmlfolder):
'''
Function that selects the indexes of the images of a
specific class contained in the source datase... |
aadc36939d7b89d9d92b715b4d1cbe8aea9b11617dc3170a1c662a403ba20f42 | Python | 2,608 | 78 | from PymoNNto import *
from Examples_Paper.STDP_Hom_Norm.Normalization import *
from Examples_Paper.STDP_Hom_Norm.STDP import *
from Examples_Paper.STDP_Hom_Norm.Homeostasis import *
class Basic_Behavior(Behavior):
def initialize(self, neurons):
neurons.voltage = neurons.vector('uniform')
self.lea... |
580e99cf7b89b94978aedf56947618b816640b03cb5eb530bfaeeb2ac33291a3 | Python | 2,609 | 81 | import numpy as np
import os
epochs = 200
num_fold = 5
result_dirs = ['Trained on augmented data/Results record', 'Trained on original data/Results record']
i = 0
for result_dir in result_dirs:
cm_all = np.zeros((epochs, 2, 2))
bac_all = np.zeros(epochs)
auc_all = np.zeros(epochs)
acc_all = ... |
5b8cbc998bd6169fc299fdc6c4685484fb9cb4b9f6aab63cf6f5f22c6396fda2 | Python | 2,609 | 78 | # 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... |
c76ad19f12f8bbdcf05fbfeb1350f05964ab24556a12f79ba9da59447f8c690f | Python | 2,609 | 86 | import pytest
import geomstats.backend as gs
from geomstats.geometry.spd_matrices import SPDAffineMetric, SPDEuclideanMetric
from geomstats.metric_geometry.trees import ForestTopology, Split
from geomstats.metric_geometry.wald_space import (
_AMBIENT_METRIC_TO_SQUARED_DIST_GRAD,
Wald,
)
from geomstats.test.dat... |
23fe9e4cb75c37050ab698e6c78947eb64f089209fc8d34085bb61b0147797be | Python | 2,610 | 71 | import numpy.testing as npt
from unittest.mock import mock_open, patch
from reinvent_plugins.components.database_precedence.comp_ringprecedence import (
RingPrecedence,
Parameters,
)
def test_comp_ringprecedence():
inputs = [
"c1ccccc1Cc1ccccc1",
"Brc1ccncc1",
"BrC1C=CC=C1",
... |
95ef9a9b55ace05ffff0a75e465453a4670dd81d3d30f9665edd49101f5694fb | Python | 2,610 | 77 | import numpy as np
import os
from mpi4py import MPI
def output(path):
"""
Simulate some random spike train input
:param path: the file for the configurations of the connection
:return:
"""
# Start communication channels
path_to_files = path
# For NEST
# Init connection
print("O... |
c928225b85c8f6291d84021e4ff2c7c2f02433fcd27a484c2b7d60cdea902fba | Python | 2,610 | 59 | import json
data = {}
data['ngpu'] = 1
data['lr'] = 0.001
data['batchSize'] = 128
data['modelRoot'] = 'best_models'
data['dataRoot'] = "../../data/new-lba/"
data['labelFile'] = "labels113683228-0.1-10.0-0.01.in"
data['matFile'] = "sequences113683228-0.1-10.0-0.01.in"
data['nTrainSamples'] = 9500
data['nTestSamples'] ... |
aaa65bbdfc01e671c052e64cbec339c07a6b6824c0aaa0c9936e57b35e44059a | Python | 2,611 | 82 | import importlib
import os
from abc import ABC, abstractmethod
from typing import Dict, Optional
class AudioFeatureTransform(ABC):
@classmethod
@abstractmethod
def from_config_dict(cls, config: Optional[Dict] = None):
pass
AUDIO_FEATURE_TRANSFORM_REGISTRY = {}
AUDIO_FEATURE_TRANSFORM_CLASS_NAMES... |
c792f1a28b4e357b9ca3ea8a76fd6e384a31ff2e0ab16c03d916f3b99465f694 | Python | 2,611 | 92 | from __future__ import absolute_import
import numpy as np
import pandas as pd
import os
from sklearn.model_selection import train_test_split
try:
CURRENT_FOLDER = os.path.dirname(os.path.realpath(__file__)) + '/'
except:
CURRENT_FOLDER = os.path.dirname(os.path.realpath('__file__')) + '/'
class Dataset(object):
... |
647aa4295614a778845ff1b70510975f5d509758ce28b125001cf4ad6ba1f412 | Python | 2,613 | 93 | """Estimate statistics from long trajectories."""
import numpy as np
from dgamem.stop import backward_stop, forward_stop
__all__ = ["forecast", "aftcast"]
def forecast(in_domain, function, guess):
"""
Estimate a forecast.
Parameters
----------
in_domain : Sequence[NDArray[bool]], shape=(n_traj... |
395964f6f965d41fe79f717a8af94729fa52e38b9202fdec63c76b4572400d7f | Python | 2,614 | 81 | from pymonntorch import *
import time
import torch
from matplotlib import pyplot as plt
import numpy as np
from globparams import *
settings = {'dtype': torch.float32, 'synapse_mode': "SxD", 'device': 'cuda'}
class LeakyIntegrateAndFire(Behavior):
def initialize(self, neurons):
neurons.spikes... |
42fb2f07df8752abba677aad4af1dacd88da8cd5089b94b8d1203a583667a0d2 | Python | 2,614 | 72 | """Example of principal geodesic analyis in hyperbolic space."""
import matplotlib.pyplot as plt
import geomstats.backend as gs
from geomstats.geometry.hyperbolic import Hyperbolic
from geomstats.learning.pca import PGA
def plot_principal_geodesics(points, coords_type):
"""Compute and plot principal geodesics."... |
23792000e57b1169c0bc375c541f70aceb29b6d4dc0d095d34682cc662e28ee4 | Python | 2,618 | 94 | """259 descriptors from LillyMol's iwdescr
NOTE: iwdescr will terminate on the first invalid SMILES
"""
__all__ = ["LillyDescriptors"]
import os
import csv
import shlex
from io import StringIO
import operator
from dataclasses import dataclass
from typing import List
import logging
import numpy as np
from reinvent_p... |
5a2df100a4f3b58c809d77b79af0c0782e42003c78317907b5a4a8e1dcb2a0c6 | Python | 2,623 | 49 | import numpy as np
import pandas as pd
unique_classes = ['little spiderhunter', 'bushy-crested hornbill', 'banded bay cuckoo', 'grey-headed babbler', 'chestnut-backed scimitar-babbler', 'brown fulvetta', 'blue-eared barbet', 'rhinoceros hornbill', 'rufous-tailed shama', 'rufous-tailed tailorbird', 'black-naped monarch... |
2b20877555d1693aeef32dd4096633e71f7924826518de01131bca392179bb99 | Python | 2,624 | 91 | import torch
from model_angelo.utils.affine_utils import init_random_affine_from_translation
class GNNIO:
def __init__(self, result_dict = None):
self.result_dict = result_dict
def update(self, **kwargs):
for key, value in kwargs.items():
if key in self.result_dict:
... |
cbd2753ef5ce8badb62bc04f544e3c5b9f25c8f51ddac81652818b528be7a185 | Python | 2,626 | 96 | import pytest
import numpy as np
import pandas as pd
from sklearn.metrics import pairwise_distances
from nltools.simulator import Simulator
from nltools.data import Brain_Data, Adjacency, Groupby, Design_Matrix
from nltools.mask import create_sphere
@pytest.fixture(scope="module", params=["2mm"])
def sim_brain_data()... |
f0768434a9075d837b70aafee7dafee13e563fca57fe6d29040eaa4bb39a193a | Python | 2,626 | 77 | # Copyright (C) 2024 Intel Corporation
# Licensed subject to the terms of the separately executed evaluation license agreement between
# Intel Corporation and you.
"""You may copy this file as the starting point of your own model."""
import numpy as np
import xgboost as xgb
from openfl.federated import XGBoostTaskRun... |
61fb0a88d0fcf86458132a47b7f4b4d708e84496f110342fe0b181168e196f87 | Python | 2,628 | 71 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Aggregation function interface module."""
from abc import abstractmethod
from typing import Iterator, List, Tuple
import numpy as np
import pandas as pd
from openfl.utilities import LocalTensor, SingletonABCMeta
class AggregationFun... |
aa76dbeda2dc293cec4c16ac7f603ac32ba01d11ecff20c2fa1206ccc275725b | Python | 2,628 | 94 | import argparse
import logging
import os
import torch
from mace.modules.wrapper_ops import OEQConfig
from mace.tools import deprecation
from mace.tools.scripts_utils import extract_config_mace_model
from mace.tools.torch_tools import restores_default_dtype
@restores_default_dtype
def run(
input_model,
outpu... |
66e9e3336d5e8b8e46f47b748531683daef2b8f21e5a568e3fb02b1300d26784 | Python | 2,629 | 88 | import random
import pytest
from geomstats.geometry.special_orthogonal import (
SpecialOrthogonal,
_SpecialOrthogonalMatrices,
)
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test_cases.geometry.special_orthogonal import (
SpecialOrthogonal3VectorsTestCase,
SpecialOrtho... |
6dbbfa8e10b3977c635faf37ce441960b59c426112b3a28f4b56a164b6690c8d | Python | 2,629 | 90 | from abc import ABC, abstractmethod
import torch
class AbstractReward(ABC):
# language=rst
"""
Abstract base class for reward computation.
"""
@abstractmethod
def compute(self, **kwargs) -> None:
# language=rst
"""
Computes/modifies reward.
"""
pass
... |
e9ac388ff0620a99b0c66864e20e2d6def07c1b345745e1fc1a5fd85d1a843a1 | Python | 2,629 | 77 |
from typing import Optional, Tuple
import config
import pandas as pd
from matplotlib import pyplot as plt
def decode_model_name(model_name: str) -> Tuple[bool, Optional[bool], Optional[int]]:
if 'BratsDiff' not in model_name:
return False, None, None
n_subjects = int(model_name.replace('_', '-').sp... |
9fd98be7055c089af0ea6a685f2b7b10a0f8630e133f71cc47051e3f60b5adbe | Python | 2,633 | 76 | """Tests for reinvent/models/meta_data.py — hash generation and verification."""
import copy
import pytest
import torch
from reinvent.models import meta_data
from reinvent.models.meta_data import (
ModelMetaData,
update_model_data,
check_valid_hash,
HASH_FORMAT,
)
from reinvent.models.reinvent.models.... |
28ccd500182b00cd16c3386c67414c507030f73fe6a18dba974aaf18ed5a8593 | Python | 2,634 | 76 | # Copyright (c) 2022 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... |
372bf956ec84a328971c0c8a50612db464f177b28b6495966b2ed0860b517986 | Python | 2,634 | 64 | from pathlib import Path
import nibabel as nib
import numpy as np
from data.dataset import BratsTest, label_mapping
from learning.metrics import pixelwise_evaluation_metrics
from learning.utils import plot_compare_image, write_results_to_xlsx
from matplotlib import pyplot as plt
import config
nnunet_model_path = Pat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.