sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
3ec7b4f64c334f64c12ec9922574bb4ddb35ba8cbb914d9e34e27ba61067aa57
Python
1,058
36
from dig.ggraph.dataset import QM9 import shutil def test_qm9(): root = './dataset/QM9' dataset = QM9(root, prop_name='penalized_logp') assert len(dataset) == 133885 assert dataset.num_features == 4 assert dataset.__repr__() == 'qm9_property(133885)' assert len(dataset.get_split_idx()) == 2 ...
ae969784339191a96841c8d4d47e8334c34d481678f4f061e87f0ad5fdfd645b
Python
1,058
45
from navec.pq import PQ def quantize(matrix, qdim, centroids, sample, iterations): import numpy as np import pqkmeans encoder = pqkmeans.encoder.PQEncoder( iteration=iterations, num_subdim=qdim, Ks=centroids ) matrix = np.array(matrix) vectors, dim = matrix.shape ...
dd199c034e41c6c5d9f0543a006f6d02db911d1b5abbb5d481f76f825118e064
Python
1,059
37
# ------------------------------------------- # Miscellaneous helper functions # ------------------------------------------- def make_flat(old_list): ''' Takes as argument a list of lists and flattens it (i.e. returns a 1D list with all the elements) ''' new_list = [] for elem in old_list : if type...
2ff6022c4b42eeab255386f3c5f5ba40104d4df8917023ed013baa334f777931
Python
1,061
37
"""Define a state-aware base class for DANDI NiceGUI widgets.""" from __future__ import annotations from abc import ABC, abstractmethod from gui.app_state import DandiAppState, DandiAppStateStore class DandiWidget(ABC): """Subscribe a NiceGUI widget to immutable application state changes.""" def __init__(...
453930cb466fd782570605152313f7e3a893ba2ad314255bebc7fd1fd8c4888a
Python
1,061
40
from sleepy.gui.tagging.model.event.point import PointEvent from functools import partial import pdb class UserPointEvent(PointEvent): def __init__(self, point, dataSource, applicationSettings): super().__init__(point, dataSource, applicationSettings) self.artist = None se...
52cdb5b19f022c12c3c5037eaffff7289c34c9ae4f55c2b31875b8806aa03d96
Python
1,061
31
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages data = pd.read_excel('compare_test.xlsx') indicators = ['Accuracy', 'Precision', 'Recall', 'Specificity', 'F1-Score', 'AUC', 'AUPRC'] data_matrix = data.loc[:, indicators].values data.set_in...
ac502a6dea6596848b16573f04c51c24ba84c70f256c31de13c4a17293c70411
Python
1,065
29
import unittest import pytest import torch from reinvent.models import TransformerAdapter, SampledSequencesDTO, Mol2MolModel from reinvent.runmodes.utils.helpers import set_torch_device from tests.test_data import ETHANE, HEXANE, PROPANE, BUTANE @pytest.mark.integration @pytest.mark.usefixtures("device", "json_conf...
eb15beb476240f62c8f660eb544040d1ad771cec6df2bd1016abc93b6631031e
Python
1,066
33
"""Focused tests for the public analysis-directory API.""" from pathlib import Path import shutil import sanpy def test_analysis_dir_discovers_default_loaders(tmp_path: Path) -> None: """Scan a fresh folder without requiring a loader dictionary. Args: tmp_path: Pytest-managed temporary directory. ...
85f82f446c85f21c92bad1755b1f53813d9062fe4232fb28e134deb12ec74f23
Python
1,068
34
import os import numpy as np def test_loss_log_plot(): from mlspm.logging import LossLogPlot loss_log_path = "loss_log.csv" plot_path = "test_plot.png" log_path = "test_log.txt" info_log = open(log_path, 'w') if os.path.exists(loss_log_path): os.remove(loss_log_path) loss_log = ...
a821eacf50abf1e4ad0913f288e26f2b1a5feebfebc7cc0b871cfc311122306d
Python
1,068
33
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages data = pd.read_excel('compare_newTest.xlsx') indicators = ['Accuracy', 'Precision', 'Recall', 'Specificity', 'F1-Score', 'AUC', 'AUPRC'] data_matrix = data.loc[:, indicators].values data.se...
b6f03b4bddac5e4968c23add7589e0f64a13b0396e60a87edb950b4b1dc8b741
Python
1,070
34
import re import subprocess import time import os def _get_gpu_memory_in_use(): success = True try: nvidia_smi_output = subprocess.check_output(["nvidia-smi"]).decode("utf-8") except: success = False return success, [] gpu_memory_in_use = [] for l in nvidia_smi_output.split(...
1dc0c5cb03af6b0c70ff913652d1851026f8150f577ce896df7c4a0e071af02a
Python
1,072
35
from __future__ import annotations import logging from reinvent.runmodes.RL import memories from reinvent.runmodes.RL.validation import SectionDiversityFilter logger = logging.getLogger(__name__) def setup_diversity_filter(config: SectionDiversityFilter, rdkit_smiles_flags: dict): """Setup of the diversity fil...
9822142ac0b2fa2da054252ee4718d771a882b3ea26919bb4e6248f345bf5c8d
Python
1,073
30
import pytest import unittest import torch from reinvent.models import LinkinventAdapter, SampledSequencesDTO from reinvent.runmodes.utils.helpers import set_torch_device from tests.test_data import ETHANE, HEXANE, PROPANE, BUTANE from tests.models.unit_tests.linkinvent.RNN.fixtures import mocked_linkinvent_model @...
5c5f027b82604f48b19f548c6a6e48a451ba093d0251c725f724f1b911148b9c
Python
1,074
39
import geomstats.backend as gs from ._base import BaseEstimatorTestData, TestData class PairwiseDistsTestData(TestData): def dists_among_selves_test_data(self): return self.generate_random_data() def symmetric_test_data(self): return self.generate_random_data(exclude_single=True) def ma...
9c720f57749fd76e024d2c1d2e6be72b83183ff21761bfcc58b3a30affd015e6
Python
1,075
31
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages data = pd.read_excel('compare_test_pseudo.xlsx') indicators = ['Accuracy', 'Precision', 'Recall', 'Specificity', 'F1-Score', 'AUC', 'AUPRC'] data_matrix = data.loc[:, indicators].values data...
eeccd8f05b20bb33430f9797534466263c660315c06026a0efb96fd2959a81d4
Python
1,076
32
from collections import OrderedDict from typing import Any, Callable, Generic, Optional, TypeVar K = TypeVar("K") V = TypeVar("V") class LRUCache(Generic[K, V]): """A simple LRU cache implementation, based on the OrderedDict class, which allows for a callback to be invoked when an item is evicted from the c...
f6317b839a24190810b5667953f690be8b53b249c7d7da6412d31721aa916d5a
Python
1,076
33
#!/usr/bin/env python3 import argparse import matplotlib.pyplot as plt import numpy as np from odil import plotutil plotutil.set_extlist(["png"]) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data", type=str, default="out_poisson/train.csv") parser.add_argument("-...
37a278766c90e80e557087fb9689841ab98ed22f1db34cdd318e812800ea9322
Python
1,077
28
import glob import platform directory_split = "\\" if platform.system() == "Windows" else "/" def generate_training_data(save_location, msd_directory, target_platform): target_split = "\\\\" if target_platform.lower() == "windows" else "/" with open(save_location, 'w+') as f: print(msd_directory) ...
66e1d2117d262aaeb7adf8db7235211f1c274d2c326b8ef591479f6c8b607f69
Python
1,081
32
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages data = pd.read_excel('compare_newTest_pseudo.xlsx') indicators = ['Accuracy', 'Precision', 'Recall', 'Specificity', 'F1-Score', 'AUC', 'AUPRC'] data_matrix = data.loc[:, indicators].values d...
06a17b325eb5f11c2bc233bc6bd882f5fd4282d1fb22a020b15e861677950cdb
Python
1,082
49
import sympy.physics.units as units from sympy.physics.units import convert_to, second, seconds def eq_split(eq): str = eq.replace(" ", "") parts = [] str_buf = "" for s in str: if s in ["*", "/", "+", "-", "%", ":", ";", "=", "!", "(", ")", "[", "]"]: parts.append(str_buf) ...
ad1c35d0f27cb7afdb670b972af1746a36eb0890eb9ad6aa4f15269178ab0fb2
Python
1,082
30
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 """ Utils for transfer learning """ from torch.nn.parameter import Parameter def load_state_dict_to_model(model, state_dict): """Initialize a model with parameters in `state_dict` (inplace) from a pretrained ...
53bfb96dbbfebc12343718f75dfa4608300839329fab7364792edd759e4b10a7
Python
1,083
23
"""Atlas registry, lazy loading, and coordinate labeling. Atlases are hosted at `huggingface.co/datasets/nltools/niftis` under `atlases/` and fetched on first use via `fetch_resource`, then cached locally. The labeling logic was adapted from [atlasreader](https://github.com/miykael/atlasreader) (BSD-3-Clause); please...
a071c64e69cfc6a718d7eefaab6f809c7040c701e501a49154c0305ca0b9b6b3
Python
1,083
47
import json from collections import OrderedDict from .record import Record class Meta(Record): __attributes__ = ['id', 'protocol'] PROTOCOL = 1 def __init__(self, id, protocol=PROTOCOL): self.id = id self.protocol = protocol @property def as_json(self): return OrderedD...
226dba93f6e93849afe34b023b5b08a056c7aefd57e18aa0522bcaa8e0c63927
Python
1,086
35
# Usage: python3 splitScaffolds.py inFile species type_of_variant (indels or snps) type_of_comparison (e.g. huch, hugo, hurh etc. where huch indicates that the MAF was a human chimp alignment) import os import sys import pandas as pd # Read arguments inFile = sys.argv[1] species = sys.argv[2] type_of_variant = sys.ar...
569ba7dc45094fe7975897988cff14dcce0e8a0564b07a0bd72a7f7aa66cee6e
Python
1,086
42
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2023/10/7 16:09 # @Author : lvtongxuan # @File : setup.py # @Software: PyCharm # @Email : lvtongxuan@genomics.cn import setuptools from wheel.bdist_wheel import bdist_wheel __version__ = "1.0.5" class BDistWheel(bdist_wheel): def get_tag(self): ...
772160038b8d2857377e1afe91fc60eb86877229cfee1f80b9d6407845907c75
Python
1,086
36
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html import os import sys sys.path.insert(0, os.path.abspath('../..')) # -- Project information ------------------------...
6cafa3d5a907aa15c2eea2c9ff0e1f04fe09c839bef4048f27e3262e4a43c15e
Python
1,088
39
import nibabel as nb import numpy as np import pytest from pydfc.data_loader import nifti2timeseries @pytest.fixture def simulated_bold_and_label(tmp_path): # Simulated BOLD data bold_data = np.random.rand(10, 10, 10, 100) affine = np.eye(4) bold_img = nb.Nifti1Image(bold_data, affine) bold_file ...
a1893b47028b880ca8ac697ed21b8f2db9fe7f4dd892a5d067b07e75f87432aa
Python
1,089
37
# 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 # # Un...
f78069a3fea481b6db3b4ed46c6c4135d4dfcf94374ebcee9f611c6c45610f1e
Python
1,089
53
import sys sys.path.append('../../') import time t=time.time() from PymoNNto import * from PymoNNto.Exploration.Network_UI.Basic_Tabs import * from NetworkBehavior.EulerEquationModules.VariableInitializer import * from NetworkBehavior.EulerEquationModules.Equation import * from NetworkBehavior.EulerEquationModules.Eu...
3b62f1b912e3d7c8a228ba3d787a3c302fcb9b956ac14eb1861948ec4050d68f
Python
1,090
43
import geomstats.backend as gs from geomstats.test.data import TestData from .base import LevelSetTestData from .riemannian_metric import RiemannianMetricTestData class HyperboloidTestData(LevelSetTestData): tolerances = {"projection_belongs": {"atol": 1e-8}} class Hyperboloid2TestData(TestData): def belon...
9065983127f8a611f17627d44a57304141e6f80f8832598a3c78543e25313769
Python
1,091
38
"""Compatibility API. New code should use Proj2ProjReconstructor.""" import warnings from .proj2proj import Proj2ProjReconstructor class N2SelfReconstructor(Proj2ProjReconstructor): def __init__( self, name, net="skip", lr=0.001, n2self_n_iter=8000, n2self_weights...
bebaebbeedef5814193cd519b748e98201e05f8cb68fb95157b24c99f77c67c0
Python
1,091
49
import pytest from corgie.helpers import BoolFn @pytest.mark.parametrize( "exp, result", [ ( { "inputs": [ {"val": 1}, {"val": 1}, ], "threshold": 2, }, False, ), ...
98ec643ca4cf6843b47fa37d2cf30ae790e11ed71c01c0dd55e22963301f7783
Python
1,092
32
import sys, os def readAndLabelStats(statFileName, label): examples = [] with open(statFileName) as statFile: first = True for line in statFile: if first: header = "classLabel\t"+line first = False else: examples.append(str...
5faddb99d205fcac33e852d0a181c3738a8d7e2f7661d03f8d442fa2d8bcbcc1
Python
1,093
25
# 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 # # Un...
b740713eb16e4bcf10d0dc3769c5078240d11ddcd17691aea7547e41c4d06a28
Python
1,093
40
from geomstats.test.data import TestData class _ManifoldMixinsTestData: def belongs_vec_test_data(self): return self.generate_vec_data() def not_belongs_test_data(self): return self.generate_random_data() def random_point_belongs_test_data(self): return self.generate_random_data(...
1edbe1b4a5c085e2269f964c7a82d81538a307f6fa62950824175b6347ae9b8d
Python
1,095
32
from __future__ import annotations import importlib.metadata as impm import re import jinja2.parser import requests from jinja2.ext import Extension class SnakebidsVersionExtension(Extension): """Retrieve the latest snakebids version from pypi. Stores value in the ``snakebids_version`` global variable. ...
583beae61d8b7ff68664e6f8ac1d45a3f9c8db441abec86dd32251570fae57b0
Python
1,095
37
import pandas as pd import seaborn as sns from matplotlib import pyplot as plt from src.data.files import get_file_path tau_df = pd.read_csv(get_file_path("new_tau", "data", ext="csv")).infer_objects() tau_types = tau_df["tau type"].unique() fig, axs = plt.subplot_mosaic([list(tau_types)], figsize=(8, 4)) # type: i...
c4163f573aaa58d8d9999e97acf693662b64ba804ee0af1fb148953a517df52d
Python
1,095
44
# Author: Youzhi Luo (yzluo@tamu.edu) # Updated by: Anmol Anand (aanand@tamu.edu) BATCH_SIZE = 'batch_size' INITIAL_LR = 'start_lr' GENERATOR_STEPS = 'g_steps' TEST_INTERVAL = 'test_interval' LOSS_INTERVAL = 'loss_interval' FACTOR = 'factor' PATIENCE = 'patience' MIN_LR = 'min_lr' MAX_NUM_EPOCHS = 'max_num_epochs' REW...
60ae275cf7082b27f024122605b8bf402d2b8b1ad67e80dc16676bcbbf11111f
Python
1,097
29
from conftest import TrainingInvarianceBaseTest import pytest import torch from nequip.utils.versions import _TORCH_GE_2_4 @pytest.mark.skipif(not _TORCH_GE_2_4, reason="OpenEquivariance requires torch >= 2.4") @pytest.mark.skipif(not torch.cuda.is_available(), reason="OEQ requires CUDA") class TestOEQTrainingInvaria...
73203c51acda2c10a5ca3772e9620afa9bb7c814cd9c994feb0e0be80746132a
Python
1,097
34
from numpy import zeros, corrcoef, arange def corr_slide(series, size, slide = None): """Run cofluctuation analysis for BOLD signal. Args: series (double): BOLD signal array for all parcels/voxels in the format [N, Tmax]. size (int): Size of sliding window. slide (int, optional): Shift...
739bc922aa19c7c66f119d2e28084f5a2875c9b8588dd588588c82a9bcb625ae
Python
1,097
53
# Parse ALL input files and collect information about how many # entities there are (BCIO, external, etc.) # Relies on there being an ID column with either a BCIO ID or # an external ID to count # Needs specification of the root directory in which to find input files ROOT_DIR = '../inputs/' import os import o...
779929e4e912f7d2196e2771fc42066761b5942ead7b784d9fed56f3e065b0e8
Python
1,102
56
from pathlib import Path from neurodesign import Experiment, Optimisation, report output_dir = Path(__file__).parent / "output" output_dir.mkdir(parents=True, exist_ok=True) exp = Experiment( TR=2, n_trials=100, P=[0.33, 0.33, 0.33], C=[[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, -1, 0], [0, 1, -1]], n_...
319fe64b10b1fccdbcac59ac4132849a3afa0b91b913ee617a414ddd093879c9
Python
1,104
30
# -*- coding: utf-8 -*- # # # PyRates software framework for flexible implementation of neural # network models and simulations. See also: # https://github.com/pyrates-neuroscience/PyRates # # Copyright (C) 2017-2018 the original authors (Richard Gast and # Daniel Rose), the Max-Planck-Institute for Human Cognitive Bra...
d69936c5a033fb65bfe319231e1b7fb6c1f0b526d3cc45667cc67f3987606827
Python
1,105
44
import pytest import reinvent.utils.logmon as logmon from reinvent.utils.logmon import RemoteJSONReporter, get_reporter, setup_reporter @pytest.fixture(autouse=True) def reset_reporter(): """Reset the module-level reporter before and after each test.""" logmon._reporter = None yield logmon._reporter ...
97343890ecd3ed1ff2a37ecb24e83b25d7d24049037c5d13c392dd619fac015e
Python
1,108
32
import numpy as np import os import pdb base_folder = '' # save folder config_folders = [] # configuration subfolders models = ['student'] for config in config_folders: for model in models: load_folder = os.path.join(base_folder, config) metrics = [] roc_auc = [] for fold in range(5): fold_met...
35718978164ad4ec8464c3c3c0b860893bc262d1076ff35da56ff9a744cab197
Python
1,109
36
"""Module that defines common errors.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os def check_valid_range(value, name, valid_range): """Raises a ValueError exception if value not in valid_range""" if value > valid_range[1] or value ...
9edc15c91de8cd0bfa8e61ceb598bea2ad938e1e7fa861b64319b809513bbfa9
Python
1,109
27
import argparse import pandas as pd # Create an argument parser parser = argparse.ArgumentParser(description='Extract columns from a DataFrame based on the content of another file.') parser.add_argument('first_file', type=str, help='Path to the first file') parser.add_argument('second_file', type=str, help='Path to th...
eadec254e25b073df75e8335e9333441f0cd91818d9068fe5efc17698c54a17c
Python
1,109
36
from dig.ggraph.dataset import ZINC250k import shutil def test_zinc250k(): root = './dataset/ZINC250k' dataset = ZINC250k(root, prop_name='penalized_logp') assert len(dataset) == 249455 assert dataset.num_features == 9 assert dataset.__repr__() == 'zinc250k_property(249455)' assert len(da...
d0ee92906e8ef8b608f92aec3d272d53e23c6ced8e55fb4bc3754ebc80fb724f
Python
1,110
35
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html import os import sys import sphinx_rtd_theme sys.path.insert(0, os.path.abspath('../../')) # -- Project information -...
a1e53ffe4bdf1899ec41cd07cc8bb6c7b919b454b8fb1fc9fe9e8968bf9518c6
Python
1,112
32
from geomstats.test_cases.geometry.lie_algebra import MatrixLieAlgebraTestCase class SkewSymmetricMatricesTestCase(MatrixLieAlgebraTestCase): def test_baker_campbell_hausdorff_with_basis(self, atol): # valid for n > 2 if self.space.n < 3: return fb = self.space.basis[0] ...
b134cb9545e60fe31ba34e3af0af7b114bf5990bb51826f8ed86b89510cbf6c6
Python
1,112
46
import PymoNNto as pymonnto from brian2 import * import brian2 from PymoNNto.NetworkCore.Behavior import * class Brian2_embedding(Behavior): def initialize(self, neurons): self.add_tag('Brian2_embedding') brian2.defaultclock.dt = 1 * ms eqs = self.parameter('eqs', '') self.G = ...
f7acc0b49bd7aff1e78365b8e27a6f0c5f5bc344d7a66ac768dc5755770b856c
Python
1,113
35
import os import json input_dir = 'instances/atlas/parcellationEntityVersion/JBA-v2-9' output_dir = 'instances/atlas/parcellationEntity/JBA' def main(): existing_dict = {} def get_existing(pev_filename: str): jba_version, space, areaname, version, hemisphere = pev_filename.split('_') if arean...
4a462b5a79ec53bf07c863f9de2cc3da19b2856b55e4fb32634809e89766f6dd
Python
1,115
43
""" Tests for variance schedules """ import unittest import torch from foldingdiff import beta_schedules class TestLinearVarianceSchedule(unittest.TestCase): def test_strictly_increasing(self): """ Test that betas should be strictly increasing """ betas = beta_schedules.linear_b...
f6905df0605ef7694803a4b7d782ce51ce2d53811083fee979f2d8c9e8a98d80
Python
1,115
28
import numpy as np from reinvent.models.model_factory.sample_batch import SmilesState, SampleBatch def common_report(sampled: SampleBatch, **kwargs): valid_mask = np.where( (sampled.states == SmilesState.VALID) | (sampled.states == SmilesState.DUPLICATE), True, False, ) unique_mas...
ba2855fed6952ee9ef5448b5b2fce6b71d834452452c76137ad34bbfde96f6d3
Python
1,117
62
# Author: Youzhi Luo (yzluo@tamu.edu) # Updated by: Anmol Anand (aanand@tamu.edu) from enum import Enum class FuseType(Enum): ABS_DIFF = 'abs_diff' CONCAT = 'concat' COSINE = 'cosine' ADD = 'add' MULTIPLY = 'multiply' class AugType(Enum): NODE_FM = 'node_fm' NODE_DROP = 'node_drop' ED...
6d72c5c7e2e5e5957cd2145bd87a67acc38ab0f3a889b38deff3937fd35542a6
Python
1,118
32
from ..abstract_dataset import AbstractDataset import os import numpy as np import matplotlib.pyplot as plt import matplotlib.tri as mtri class ElasticBlockDataset(AbstractDataset): parametric = True time_dependent = False description = "elastic block TODO" data_directory = os.path.join(os.path.dirna...
a8467806ccba2a9ab9b84efb813394ba039926ccb96ce972b46fd953c0509dde
Python
1,120
38
"""Send information to a remote server""" from __future__ import annotations __all__ = ["SamplingRemoteReporter"] import collections from typing import TYPE_CHECKING from reinvent.runmodes.samplers.reports.common import common_report if TYPE_CHECKING: from reinvent.models.model_factory.sample_batch import Sampl...
1497922a9a8cfa2227210e9291812e97b671b3b4cc8dea7840d511199e726188
Python
1,121
47
from __future__ import annotations import textwrap import warnings from colorama import Fore, Style WARN_TEMPLATE = f"""\ {Fore.YELLOW}{Style.BRIGHT}[{{category}}]{Style.NORMAL} {{filename}}:{{lineno}} \ {Fore.RESET}{{line}} {{message}} """ def formatwarning( message: Warning | str, category: type[Warning...
33ad5bd1d9848f6ae7a598aec391e79ae234d84c944136186d2199f16d1ae714
Python
1,123
36
import pytest import numpy as np from reinvent_plugins.components.Lilly.comp_medchem_rules import Parameters from reinvent_plugins.components.Lilly.comp_medchem_rules import LillyMedchemRules SMILIES = [ "Cc1ccc(-n2[nH]c(C)c(N=Nc3cccc(-c4cccc(C(=O)O)c4)c3O)c2=O)cc1C", "CC(=O)Oc1ccccc1C(=O)O", "Cc1ccc(-c2...
4da1bea1003552f168c7d4fdf4c295a63f6091c710d829ba7188478d6e7a1a53
Python
1,124
34
# 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...
2d4e768356e190e92a90bd5a8fe35d9f0247ac7e03c5a8430c92c8c0d11a6d0a
Python
1,126
33
# Test if bilateral filtering of batch of images works (visual check required) # GPU OP must be compiled with SPATIAL_DIMS=2 INPUT_CHANNELS=3 REFERENCE_CHANNELS=3 import tensorflow as tf import numpy as np from PIL import Image from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__))...
a65f48932d1140d84725d970e6d2643e4e7b1c04f0a38438bf0095492cc742fa
Python
1,126
42
"""Send information to a remote server""" from __future__ import annotations __all__ = ["TLRemoteReporter"] from collections import Counter import logging from typing import TYPE_CHECKING if TYPE_CHECKING: from reinvent.runmodes.TL.reports import TLReportData logger = logging.getLogger(__name__) class TLRemot...
12e504a5ef23d87ca3bde6235f61f2554c454299f80b502ecde493f88875cace
Python
1,127
32
"""Tests for SanPy text acquisition snapshot extraction.""" from pathlib import Path import numpy as np import sanpy from sanpy.io.zarr_export.sanpy_file_adapter import snapshot_sanpy def test_snapshot_sanpy_preserves_sweep_epochs(sanpy_data_folder: Path) -> None: """Copy every text sweep and its sweep-specifi...
154aa57647aa1501393b64be687e3311bdbb270653436fcf2bbb2a3111e937be
Python
1,130
38
import os import random import gc import time # Borrowed from https://github.com/rogerbinns/apsw/blob/master/apsw/tests.py#L224 # Used to delete sqlite files on Windows, since Windows file locking # behaves differently to other operating systems # This should only be used for test or non-production code, such as in r...
ac04e09a6cc8c5ebb7b8742e4586128c095cbfae25381c71ff60f3c52a3a7a16
Python
1,130
39
import numpy as np from reinvent_plugins.components.comp_custom_alerts import CustomAlerts from reinvent_plugins.components.comp_custom_alerts import Parameters def test_comp_custom_alerts(): endpoint1_smarts = [ "[*;r8]", "[*;r9]", "[*;r10]", "[*;r11]", "[*;r12]", ...
fd3f78d3742b353577f98714b25f8d6cdeb543679387860f8d8fa37f5e50175f
Python
1,131
31
from pynetdicom import AE, evt, AllStoragePresentationContexts, debug_logger, build_context from pynetdicom.sop_class import Verification import os debug_logger() def handle_store(event): """Saving Incoming DICOM series based on Patient ID""" ds = event.dataset root = r"YOUR PATH TO \Dicom_receiver" ...
5ae204ab4e215a33f345d493fb45883abea51813b2571df7d4146f05d8ef845d
Python
1,133
31
from setuptools import setup, find_packages setup( name='Humatch', version='1.0.1', description='Fast, gene-specific joint humanisation of antibody heavy and light chains.', license='BSD 3-clause license', maintainer='Lewis Chinery', long_description_content_type='text/markdown', maintainer...
ad53dd89b545529078b6df0c4b8d1c61ac7c963916ebec1190e073bd42936ced
Python
1,134
38
# import sys # import os # from pathlib import Path # import shutil # install_dir = Path(sys.argv[0]).resolve().parent # user = os.getlogin() # out_lines = [] # with open('sssort.sh', 'r') as fH: # for line in fH.readlines(): # if line.startswith('INSTALL_DIR'): # out_lines.append('INSTALL_DIR...
135aff89e5cc203d7059a8e3a25deace7d64a74b36f3f87c32fb377e7be36a7f
Python
1,135
24
import pandas as pd from uniprotparser.betaparser import UniprotSequence import re df = pd.read_csv(r"C:\Users\Toan Phung\Downloads\supp_RA118.000696_136158_1_supp_105958_p6rjww.txt", sep="\t") pattern = re.compile("r(\d+)") new_df = [] for i, r in df.iterrows(): mods = r["Variable modifications identified by spec...
e9d4fdebc50ebc609aa61608401847be540fecd0fd0364cfaa9c68efc8c7f20a
Python
1,135
44
import pandas as pd import os # List of input files and output files input_files = [ "CD16p_Mono_SNP.txt", "CL_Mono_SNP.txt", "CM_CD8_SNP.txt", "DN_B_SNP.txt", "EM_CD8_SNP.txt", "Fr_I_nTreg_SNP.txt", "Fr_II_eTreg_SNP.txt", "Fr_III_T_SNP.txt", "Int_Mono_SNP.txt", "LDG_SNP.txt", ...
56e13f0ae82805b1b1b2c087d031687efbfc604dcac9103600acc16f6ff1d5ce
Python
1,136
56
import time class Timer: """ Timer class. if autoreset=True, timer is reset after any member function call """ def __init__(self, autoreset=False): self.autoreset = autoreset self.reset() def sec(self): """ Provide the time since reset in seconds. """...
2aed05e7ca26b027cf4c35ee7bbeb49a7b774ff5bfd520a9dbf349620eaa49d1
Python
1,137
33
# SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2020-2026, Christian Gaser. See LICENSE. """Exact TFCE and permutation inference. The core is deliberately framework-free: arrays in, arrays out, numpy and scipy and nothing else. The pieces are * :mod:`tfce.core` -- the exact TFCE transform (max-tree, no ste...
7ed878f340d1c81e58a20df6d3198c34d2d161e40e278945557619e251452bf4
Python
1,138
40
import experiment as exp class MyExperiment(exp.Experiment): default_params = { "color": "blue", } default_blocks = [ {"color": "red"}, {"color": "green"}, {} ] def run_trial(self): if exp.state["video", "record", "is_recording"]: self.log.info(...
dc2401aacb851f580ad7b52a1e77d1ca1e9744656c82e6dcdddcb0fb6049d4fb
Python
1,138
38
from pathlib import Path import pytest from cookiecutter.main import cookiecutter import snakebids from snakebids.app import SnakeBidsApp from snakebids.cli import SnakebidsArgs def test_template_dry_runs_successfully(tmp_path): cookiecutter( str(Path(snakebids.__path__[0]) / "project_template"), ...
2ebee3845235957e3eb4dac95df6e1d338475434bd2c2597ed412ef941898350
Python
1,139
30
import experiment as exp from canvas import Canvas class CanvasSimpleExperiment(exp.Experiment): async def run(self): # Create a new Canvas instance to communicate with a Canvas app with ID "my_canvas" and start listening for incoming messages. self.canvas = Canvas("my_canvas") # Wait unti...
1e41024e67427723c9eddf32899aeaac9f70f57eaad5ca64741f261b16539ba4
Python
1,140
41
import pytest from torch import nn from reinvent.models.transformer.core.network.encode_decode.model import EncoderDecoder from reinvent.models.transformer.core.vocabulary import build_vocabulary from reinvent.models.transformer.pepinvent.pepinvent import PepinventModel from reinvent.models import meta_data from tests...
9760ab5cfe2529f0f42e41c87986cff4414fba6cfb659ad6a8bdf06996e25ce5
Python
1,140
30
from torch.utils.data import Dataset from PIL import Image from torchvision import transforms class MultiModalDataset(Dataset): def __init__(self, face_image_paths, tongue_image_paths, fundus_image_paths, labels, transform=None): self.face_image_paths = face_image_paths self.tongue_image_paths = to...
fca580c82da84d3978502c8dc0612f163024a7b7071dae87537791d8d76c27c7
Python
1,140
37
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """openfl.federated package.""" import os from importlib import util from openfl.federated.data import DataLoader # NOQA from openfl.federated.plan import Plan # NOQA from openfl.federated.task import TaskRunner # NOQA if util.find_sp...
bd756cda36d394583d827108c46379562e8caa9cded57b4a0c2315c78cb4f146
Python
1,142
38
# Usage: python3 splitScaffolds.py inFile species type_of_variant (indels or snps) type_of_comparison (e.g. huch, hugo, hurh etc. where huch indicates that the MAF was a human chimp alignment) import os import sys import pandas as pd # Read arguments inFile = sys.argv[1] species = sys.argv[2] valid_chr = ["chr2A", "...
ecb00655e989d8fa0d284b3d51ed21511bb6d04d879991161a2c0c08f1d0993d
Python
1,142
37
"""Display application information in a NiceGUI side panel.""" from __future__ import annotations from nicegui import ui from gui.app_state import DandiAppState, DandiAppStateStore from gui.widgets.base import DandiWidget class AppInfoWidget(DandiWidget): """Render a small application-information placeholder."...
dc3fe17acaa9cb9efa85cf88b4fe57205a4f11f6326fa55ab62f6119c84aeed7
Python
1,143
34
import unittest from reinvent.models.linkinvent.dataset.paired_dataset import PairedDataset from reinvent.models.linkinvent.model_vocabulary.paired_model_vocabulary import ( PairedModelVocabulary, ) from tests.test_data import ( SCAFFOLD_SUZUKI, ETHANE, HEXANE, PROPANE, BUTANE, ) class TestPa...
f5b4cc5b8e06c1ff2034a37e6d8e3ffe84a23018253dbf7de109d57f28a95cfe
Python
1,143
32
from PymoNNto.Exploration.Network_UI.TabBase import * class sidebar_module_quick_access(TabBase): def __init__(self, module_tags=[]): self.module_tags = module_tags def module_on_off(self, cb, Network_UI): module_tag=cb.module_tag print(module_tag) Network_UI.network.set_behav...
b348b4da26752d0286071b6e016a408bf84a913aa6b7a3efdccd7599fcd20e3d
Python
1,144
28
# -*- coding: utf-8 -*- import unittest import odl from dival.data import DataPairs class TestDataPairs(unittest.TestCase): def test(self): reco_space = odl.uniform_discr([0, 0], [1, 1], (2, 2)) observation_space = odl.uniform_discr([0, 0], [1, 1], (1, 1)) ground_truth = [reco_space.one(),...
4ffbdf399f4ab7dce33c87afbc240033555e002532ea1b519b1e54f37c7a49e9
Python
1,147
41
import numpy as np from split_dataset import Blocks from fimpy.roi_extraction.merging import merge_rois def test_merging_rois(): test_0 = np.array( [ [-1, -1, -1, -1, -1], [-1, 0, 0, 0, -1], [0, 0, 0, -1, 1], [-1, -1, 2, 2, 2], [-1, -1, 2, -1, -1...
5bcc68ba5641c57329c8bfc7e208b68afa86204c255ecebe1220937d5389b5b5
Python
1,147
38
from video_stream import ImageSource import time import numpy as np class NoiseImageSource(ImageSource): default_params = { **ImageSource.default_params, "frame_rate": 30, # add an additional parameter with default value 30. } def _on_start(self): try: self.log.info(f...
82d3b368abcade60e1227f860abe75e68a9441b266dce809ee54878dfef2a34c
Python
1,147
44
from typing import List, Union import numpy as np from scipy.stats import gaussian_kde from reinvent.runmodes.utils.decorators import extra_dependencies @extra_dependencies("matplotlib") def plot_histogram(data: List[Union[int, float]], xlabel: str, bins=50, title=None): import matplotlib matplotlib.use("Agg...
f08d71909b8fa132b7f3938eba1afe22f6195b8c50b6b6a27c5f015de09e8c4f
Python
1,147
30
import os import runCmdAsJob import stdpopsim #just to make sure we are in an env with it baseDir = "" slimScriptDir = baseDir + "slimScripts" rawSlimScriptDir = baseDir + "rawSlimScripts" outDir = baseDir + "slimOutput" logDir = baseDir + "slimLogs" os.system(f"mkdir -p {rawSlimScriptDir} {slimScriptDir} {outDir} {l...
0af2c62b055cbdb719430c98dfc2dadb3a8434d0c6ffcf1cc75f35410cb39db2
Python
1,148
26
"""The published consumer must read the user-selected build without downloading a release.""" import polars as pl import pytest from vdjmatch.db import vdjdb def test_local_build_reference_is_current_and_offline(tmp_path, monkeypatch): def no_download(**kwargs): pytest.fail("a local build must not fetch ...
3794cc713e75ac6354418f17ae79920a48bfb79a284d1bf6067b6e2842ab187e
Python
1,148
39
import logging class CustomFormatter(logging.Formatter): bold = "\033[1m" normal = "\033[22m" lightblue = "\x1b[36;20m" yellow = "\x1b[33;20m" red = "\x1b[31;20m" bold_red = "\x1b[31;1m" reset = "\x1b[0m" format = f"[ %(asctime)s ] [ {bold}%(levelname)s{normal} ][ %(name)s:%(funcName)...
5b4a189026a54028a2d2c4be7b5226c917ba5cdde6bbe56021809671e5258cee
Python
1,151
45
from subprocess import STDOUT, Popen, PIPE def execute(command, cwd=None, shell=False, logger=None): """ Run external program as a subprocess and return its output Args: - command: (str) the command that will be executed. - cwd: Current working directory. cwd argument for subprocess.Popen - s...
3f08044b20cc00c10d72f50b0bc95799e9b4f9ff3efef8330094c6c6ee7bbae1
Python
1,152
32
"""OpenEquivariance backend: e3nn parity. OEQ JIT-compiles CUDA/HIP kernels, so execution requires a GPU (capability gpu); works on NVIDIA and AMD. """ # pylint: disable=wrong-import-position import os os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1" import pytest from mace.cli.convert_e3nn_oeq import run as run...
e6557f1fa8f0d3345277210b8aa9cd850dbfab1d328ce5f3d1c504234e8f8d08
Python
1,153
50
import numpy as np class AlignerTransformException(Exception): """Exception class for AlignerTransforms""" pass def aff_matrix(theta, offs=None): """affine matrix or augmented affine matrix given a rotation angle. Parameters ---------- theta : float rotation angle in radians ...
13af21bbf80ec590131970bee34614cd95f7a3eccede9ebeee0cd72e2fe0c8bb
Python
1,157
33
import pytest import unittest import torch from reinvent.models import LibinventAdapter, SampledSequencesDTO from reinvent.runmodes.utils.helpers import set_torch_device from reinvent.models.libinvent.models.model import DecoratorModel from tests.test_data import ETHANE, HEXANE, PROPANE, BUTANE @pytest.mark.integra...
465986e7339684f4488c9ac3c1d72cadb89523a9ff461bf93ed70b5959b73125
Python
1,157
31
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from torch import nn, Tensor from typing import Union, Tuple class AdaptiveAvgPool2d(nn.AdaptiveAvgPool2d): """ Applies a 2D adaptive average pooling over an input tensor. Args: output_size (O...
77af97de16a54565f3e8f3af0b1ddb5277d953b00f2086a1047dbb81a638a391
Python
1,157
31
from dig.xgraph.dataset import SynGraphDataset import shutil def test_SynGraphDataset(): root = 'datasets' dataset_names = ['ba_shapes', 'ba_community', 'tree_grid', 'tree_cycle', 'ba_2motifs'] dataset_length = [1, 1, 1, 1, 1000] dataset_x_shape = [(700, 10), (1400, 10), (1231, 10), (871, 10), (25000,...
2cac5e10faddeb54a66bd499ae6e97b5108621cb85591f3f763ef90a83033739
Python
1,159
30
import os import numpy as np import h5py from scipy.io import savemat, loadmat from scipy import sparse import glob if __name__ == '__main__': # Set the path of the 'GT Masks' folder, which contains the manual labels in 3D arrays. dir_Masks = '../data/GT Masks' # %% dir_all = glob.glob(os.path.join(d...
964a4585790ce7dce349a339d83bb59dbee1a942dab881f4db002de88a2284ea
Python
1,159
37
from pathlib import Path from SimpleITK import ReadImage, WriteImage from tqdm import tqdm input_path: Path = Path("M:/Dataset/Loki") output_path: Path = Path("S:/data/Loki/ref") label_names: list[str] = ["tumor", "brain", "skin", "ventricles"] patients = [x.resolve() for x in input_path.glob("*") if x.is_dir()] pa...
6ad9ed185d791d8a45e79922ad3cadc4ba9dce97bac9cee7ff779200ab9f8040
Python
1,161
39
from typing import Any, Dict _UNSAFE_KWARG_KEYS = frozenset({"trust_remote_code"}) _LOCAL_MODEL_LOADER_EMBEDDING_FUNCTIONS = frozenset( { "fastembed_sparse", "huggingface_sparse", "sentence_transformer", } ) def _contains_unsafe_kwarg(value: Any) -> bool: if isinstance(value, dic...
7f5749333f1e35727c5b7db439e54da2aa82b2858d55416e07b90cd68653d251
Python
1,161
43
import numpy as np from reinvent_plugins.components.RDKit.comp_tpsa import TPSA, Parameters smilies = ( "Cc1[nH]c(=O)[nH]c(=S)c1C(=O)NC(C)(CO)CO", "CC(c1cccc(F)n1)c1c(CCN(C)C)sc2ccccc12", "N=c1[nH]cnc2c1cnn2CCC(=O)O", ) def test_comp_tpsa(): expected_results = [np.array([118.21, 16.13, 107.65]), np....
231331dbe1c5958bf86c05bf4da0a29400a3d4c753591e86c7eada89ec97ea89
Python
1,162
32
"""Tests for plot-time data-loader key handling.""" import pytest # mace.tools first on purpose: mace.tools.train imports TrainingPlotter, so # importing mace.cli.visualise_train before it hits a partially initialised # module. The cycle predates this test. import mace.tools # noqa: F401 # pylint: disable=unused-im...