sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
18ca46e8c9f59de3372775730d838886c9351eb2aae9d23e81c75106b90bb8e2
Python
5,485
134
""" Tests for independence_tests.py. """ from __future__ import print_function from collections import OrderedDict import numpy as np import pytest import sys import tigramite.data_processing as pp from tigramite.toymodels import structural_causal_processes as toys # Pylint settings # pylint: disable=redefined-outer-...
7589434717486dca50d0eab69e55f4e24597b1102e310aa111973df2b0853068
Python
5,486
191
# amplifier.py # Copyright (C) 2013 Bastian Venthur # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program ...
f65c0e3282e20a4fca6b5f9f939266df61450bc47d353d65cf8a2d7d39c2f9a3
Python
5,486
135
import numpy as np import pytest from hypothesis import given, settings from hypothesis import strategies as st import seqpro as sp from seqpro import AA # standard AminoAlphabet from seqpro.rag import Ragged def _bio_like_translate(seq_str: str) -> str: """Reference using AA.codon_to_aa directly (independent o...
914a2c9508577b51d33c665bce8ef8e130717835856fe4d6955a1cdc9725f706
Python
5,487
135
"""Belief propagation to compute the marginal probabilities of a spot being occupied by a cell. """ from typing import Optional import cv2 import numpy as np from ..configuration import config from . import utils def create_neighbor_offsets(neighborhood: np.ndarray) -> np.ndarray: """Helper function to convert ...
e89e66339e65d8bde7b6d30a68323958531c09ef89a6a030dbe1432a3c3e83af
Python
5,487
126
"""Implementation of a space that represents finite-length sequences.""" from collections.abc import Sequence as CollectionSequence from typing import Any, List, Optional, Tuple, Union import numpy as np import gym from gym.spaces.space import Space class Sequence(Space[Tuple]): r"""This space represent sets of...
1381b7cadca2887fb0834a7b8138599005ddd537350341f9b44e3fd036870e65
Python
5,488
139
import itertools import json import os import re from json import JSONDecodeError from typing import Iterable import matplotlib import matplotlib.pyplot as plt import numpy as np from matplotlib.axes import Axes from angorapy.common.const import PATH_TO_EXPERIMENTS, BASE_SAVE_PATH, QUALITATIVE_COLOR_PALETTE matplotl...
1b5ec3d722747e2ff8645a2465493f6a6d1803c16bafc24d7cc70add8325fc63
Python
5,488
155
# Copyright 2022 Deepfold Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
7021cf1c696b173d4cf1e24242c239412234639c254e10521c9cf02ef453a92e
Python
5,488
139
"""MSCOCO Semantic Segmentation pretraining for VOC.""" import os import pickle from tqdm import trange from PIL import Image import numpy as np from .utils import try_import_pycocotools from ..segbase import SegmentationDataset class COCOSegmentation(SegmentationDataset): """COCO Semantic Segmentation Dataset fo...
23a37f098e8be7e3293c35b8189a19600b07701ddee866a33b0495a91466c3f9
Python
5,491
141
#!/usr/bin/env python3 """ Test script for the new unified backup status endpoint. This script tests the modified backup status API that combines information from both MySQL backup daemon (port 8090) and rsync backup daemon (port 8093). """ import json import urllib.error import urllib.request def test_individual_s...
545e77ad9a3be2603bbbab18bfb6d450760fe2d4767a98173d3f850d79476ff4
Python
5,491
163
"""Compatibility checks for tensors saved into portable bundles. This module codifies which tensor layouts and dtypes the portable bundle path accepts in this sprint. Save code calls these helpers to decide whether a tensor should be written, skipped under ``strict=False``, or rejected with a hard ``TorchLensIOError``...
c408a0699c9ea668f4dcf1eef27174cd840f8918ed7761946d39aa447e5772f6
Python
5,491
161
# Mossy layer at 45, 90, 135 degrees from os.path import join import numpy as np import os import pandas as pd from library.comput_utils import cal_hd_np from library.utils import save_pickle from library.simulation import simulate_SNN # # ================================= Network Parameters ========================...
0adbdc0e0fe98c9d991d63e7613240e971555f9abc442d010d12308ffb38feed
Python
5,492
162
import pytest import numpy as np from BM3D.src.support_function import * # The test function takes in a function to test and the expected output def test_initialization(): Img = np.random.rand(10, 10) BlockSize = 3 Kaiser_Window_beta = 2.0 # Invoke the function being tested init_img, init_weights,...
36c57db5fb8acc90ed99db28bd9010bda527871ad91205ccf8d039a7e5cd3775
Python
5,492
118
from ovseg.model.SegmentationEnsemble import SegmentationEnsemble from ovseg.model.SegmentationModelV2 import SegmentationModelV2 from ovseg.data.Dataset import raw_Dataset from os.path import join, exists from os import environ import torch import numpy as np class SegmentationEnsembleV2(SegmentationEnsemble): ...
61d3d35f01f62c083fd9eee538fd5c1ef655da5648bc050999a115666f77deb3
Python
5,494
124
# Written by Seonwoo Min, Seoul National University (mswzeus@gmail.com) """ Utility functions """ import os import sys import math import random import numpy as np from datetime import datetime from sklearn.metrics import auc, roc_auc_score from scipy.stats import pearsonr, spearmanr, t import torch import torch.nn ...
8a295992cf30dda5624cee883c64e38b40548bd123bb06a65edf44105bf3cb71
Python
5,494
149
"""B11 (cone preflight, exact-membership oracle) + B12 (generated cache key). B11's oracle is EXACT (memo D-12 / composition row "preflight x lane"): predicted replay membership EQUALS the engine's actual recomputed cone. B12 pins the generated-universe property the warm-cache key now has: every capture option is in t...
973d74c9cfe09b92b12670e9b923110e4fb6652f9c6caa82b11de52feac2c0d8
Python
5,495
166
#!/usr/bin/env python # # Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list...
bfea54394e1a1401a1dddfb31c134d772c337801080a3e417a55c675e169f557
Python
5,495
160
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import numpy as np from spitfire.chemistry.flamelet import Flamelet from spitfire.chemistry.mechanism import ChemicalMechanismSpec m = ChemicalMechanismSpec(cantera_xml='heptane-liu-hewson-che...
4870a73b8cf7639afca85c05215af65265df0247da3fd08b0ee204b8192d0505
Python
5,497
153
import os import pandas import pandas as pd import torch from hydra import initialize, compose from matplotlib import pyplot as plt from torchmetrics.utilities.compute import auc from data.loader import get_kfold_dataloader3d from initial_setting import get_instance from utils.calculate import margin_of_error def i...
833af9e9502657c2239b5860ceb5bc01826659011036dde9d6514fd657c71662
Python
5,498
168
# 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 app...
8dd7481d9efd3ebe4a7d58e24be6bf73c33db4df5a29cda518e9bed1f154345e
Python
5,498
144
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Pramod Bharadwaj Chandrashekar @email: pchandrashe3@wisc.edu """ import math import torch from torch import nn import torch.nn.functional as F class FNN(nn.Module): """ Class for Feed Forward Network""" def __init__(self, input_dim, hidden_dim_array,...
46734f82943943ade2a667972a3c94e77147cdea7624e86fc1688913940ed1ee
Python
5,500
129
"""r-b4 R29-2: input alias validation pre-filters pairs with an interval sweep. ``_record_unpreserved_tensor_aliases`` ran the exact ``touched_bytes_relation`` ladder on EVERY pair -- O(T^2) in tensor-leaf count (measured 0.72 s at 4k disjoint leaves). The sweep (``_alias_candidate_pairs``) drops only pairs the ladder...
c6f00ba1a4c6d4e0cc5ad582b689a0451ee259272e0d60492264a46bfd9c6798
Python
5,501
146
import pytest import torch import torch.nn as nn from pytest_mock import MockerFixture from torch import Tensor from torch import distributed as dist from torch.nn import Module from lightly.loss.barlow_twins_loss import BarlowTwinsLoss from tests.ddp_helpers import NUM_PROCESSES, USE_PYTEST_POOL class BarlowTwinsLo...
0764063b5e426878d2fb38b7011998cd90ee25edd04ee737a929f624f0e5cd9f
Python
5,502
133
import torch import torch.nn as nn from torch.autograd import Variable from collections import OrderedDict import numpy as np def summary(model, input_size, batch_size=-1, device="cuda"): def register_hook(module): def hook(module, input, output): class_name = str(module.__class__).split("....
76dca60ba87a712719151a465016e210e397eeab67ad014368cdf9a067fd1c37
Python
5,502
175
from __future__ import annotations from abc import ABC, abstractmethod from typing import Iterable, TypeVar, Generic import warnings import torch.nn as nn _T = TypeVar("_T") class Domain(nn.Module, ABC, Generic[_T]): """Base class for stimulus domain. This class is used to convert data between each domain...
c7b7fd630b47158e3faae7eb442f9bfb7a1d09caba46a32dd9b7112e93fadc70
Python
5,503
147
# This example requires the following dependencies to be installed: # pip install "lightly[timm]" # Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU: fewer clusters, a shal...
b66489b17f1e574ba1895025078a6aaf516778faf8d9139c3b4794a0dbd7135b
Python
5,504
209
from typing import cast import numpy as np from numpy.typing import NDArray from ._utils import SeqType, cast_seqs, check_axes from .alphabets._alphabets import NucleotideAlphabet def length(seqs: SeqType, length_axis: int | None = None) -> NDArray[np.integer]: """Calculate the length of each sequence. Par...
f5a76ac1ca28ab438bfd0ddcf3e93e114bc1c72d8ed0c94ed075707bdea25263
Python
5,504
188
from collections.abc import Mapping from enum import Enum from textwrap import dedent import networkx as nx import numpy as np from anndata import AnnData from matplotlib import axes from matplotlib.axes import Axes class Empty(Enum): token = 0 _empty = Empty.token class _AxesSubplot(Axes, axes.SubplotBase):...
8e58d40a29332b2d74ae9b91ad5335c5a74dbcf7967c017fe53a787a0beaa38c
Python
5,506
156
import os import numpy as np import rclpy from rclpy.node import Node from rclpy.parameter import Parameter from std_msgs.msg import Bool, String, Int32, Float32MultiArray, MultiArrayDimension from camera_code import Camera class CameraROS2Node(Node): def __init__(self): ''' Initialize the CameraR...
e8d28d6ff1979274c3cd4547fb1ccfcd11cc70c7341499c2ae05a5cde7e3e2c0
Python
5,506
182
""" helper_fcts.py This script contains helper functions for paper analysis plotting. Authors: Colleen Gillon Date: January, 2021 Note: this code uses python 3.7. """ from pathlib import Path from util import file_util, logger_util TAB = " " logger = logger_util.get_module_logger(name=__name__) ##########...
f5fe8e1bb8865248054c4b6401b188d981f567f717f4335e59c27f7ace8b1fe9
Python
5,508
182
import pytorch_lightning as pl import torch from survival_plus_x.models.mae import MAE class MAELightning(pl.LightningModule): def __init__(self, vit, learning_rate, masking_ratio, decoder_dim, decoder_depth, ...
c4fa810b52cd389efe2149ff2677c8ac27c84b95597258cdf6c69a665758a2a0
Python
5,509
143
from typing import Optional import numpy as np from anndata import AnnData from ..._compat import Literal import scipy.spatial as spatial from tqdm import tqdm _SIMILARITY_MATRIX = Literal["cosine", "euclidean", "pearson", "spearman"] def adjust( adata: AnnData, use_data: str = "X_pca", radius: float = 5...
122bb5ea90b6d374403fe75478991eb45de0399c89d7478302d4c7414dcf6b49
Python
5,510
164
"""This module controls the pynapple configurations. ## Backend configuration By default, pynapple core functions are compiled with [Numba](https://numba.pydata.org/). It is possible to change the backend to [Jax](https://jax.readthedocs.io/en/latest/index.html) through the [pynajax package](https://github.com/pynapp...
921a967d960504b29cccf807c5b6a062b84d7081e19fe6b9fb7c24fbbc6987e4
Python
5,510
149
# SOURCE: vendored from autonlab/auton-survival @ 5dde465f7223601717abddc1d075e837707c403b # https://raw.githubusercontent.com/autonlab/auton-survival/5dde465f7223601717abddc1d075e837707c403b/auton_survival/models/dcm/dcm_torch.py # https://raw.githubusercontent.com/autonlab/auton-survival/5dde465f7223601717abddc1d075e...
eb0dfc5047883f75afbb53871dc3d054edce30b821b2920db9f49b7d4ef9b5f8
Python
5,510
164
import pre_process import os import data_prep import numpy as np import scipy from scipy.stats import pearsonr, spearmanr import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import pandas as pd import tensorflow.keras.backend as K from sklearn.model_selection import train_test_split from sklearn ...
2360b1d697a4def3f8111707bfcc31c091efee4d578785b103a037794415104a
Python
5,511
181
import sqlite3 import pandas as pd import json def get_queries(): CONFIGPATH = './configs/visualization.sql.json' with open(CONFIGPATH, 'r') as f: queries = json.load(f) return queries def get_generic_query_result(db_uri, queryid, return_csv=True): queries = get_queries() query = querie...
3e6bbfacc46d453f3d75cca2d55f7bf961ae5ff21c64120c9f8cecef62d60c04
Python
5,511
163
"""Mask transformation functions.""" import copy import numpy as np from PIL import Image from ..mscoco.utils import try_import_pycocotools __all__ = ['flip', 'resize', 'to_mask', 'fill'] def flip(polys, size, flip_x=False, flip_y=False): """Flip polygons according to image flipping directions. Parameters...
0b6efcf9678aad11b0db790415567a3cc72c9f89d8084a8d52822e865c92e07c
Python
5,512
137
""" BASIL GUI for Oxford ASL - Structural data options Copyright (C) 2020 University of Oxford """ import wx import wx.grid from .widgets import TabPage class StructureTab(TabPage): """ Tab page containing options for structural space transformation """ EXISTING_FSLANAT = 0 NEW_FSLANAT = 1 I...
c39e0f78c23c84454d25b85485d74422d1051e26373b4325eb6138456f5d2629
Python
5,513
125
""" Check the first value of every ABF to ensure it matches what we expect. """ import sys from numpy.testing import assert_almost_equal import pytest import datetime import inspect import numpy as np import glob try: # this ensures pyABF is imported from this specific path sys.path.insert(0, "src") impor...
f8d63bf488f4548793fa0fda9b9c37b70c37199bd76e7d5653a0230b3b8b436a
Python
5,513
180
import numpy as np from numpy.random import default_rng import pathlib from mpi4py import MPI from causal_optoconnectics.tools import conditional_probability, joint_probability, roll_pad from causal_optoconnectics.generator import ( construct_connectivity_filters, simulate, construct_input_filters, gen...
ff82d81b454b4b3972e611793f330694de247f2386122ae251288f5ba42f268b
Python
5,514
142
# -*- coding: utf-8 -*- """ To explore the time fluctuation of the network clean the data preprocessed from frmriprep extract the data using yeo7 network calculate the correlations between each session with average seesion By M.-Y. Wang 10-Jul-2023 """ import os from nilearn import datasets from nile...
13af813e241323f6f690f9b1d2effa1ed44ae24ebce37dd80f67000427084a0b
Python
5,517
125
""" BASIL GUI for Oxford ASL - Calibration options Copyright (C) 2020 University of Oxford """ from .widgets import TabPage # T1 and T2 defaults for different reference tissue types REF_TISSUE_DEFAULTS = { "csf" : (4.3, 750), "wm" : (1.0, 50), "gm" : (1.3, 100), } class CalibTab(TabPage): """ Ta...
2528962205737319054434337d224976a6b8389a5852eba60942bc95bc9aab5d
Python
5,517
178
from typing import List, Tuple, Dict, Union, Optional from pathlib import Path import pandas as pd import torch from torch_geometric.loader import DataLoader import torch_geometric.transforms as T from coeffnet.dataset.reaction import ReactionDataset from utils import ( get_train_data_path, get_validation_...
a8c84f8d69f0f6a2c4817d51737b02b155a48eeba7d07cc2b9e8dac5c5f49f22
Python
5,518
132
""" This script shows the training pipeline for k-fold training, without logging it via wandb. """ import tensorflow as tf import tensorflow.keras as keras import tensorflow_addons as tfa from sklearn.model_selection import StratifiedKFold from tf_spiking.helper import TrainingHistory from tf_spiking import DenseLIF, ...
c569f25b0681a2d99c7c5248bcea351b83bcd2ea2f43b64f5eefc89294de1bc9
Python
5,518
169
import argparse from . import gaussian_diffusion as gd from .respace import SpacedDiffusion, space_timesteps from .unet import UNetModel def create_model_and_diffusion(cfg): model = create_model( image_size=cfg.TRAIN.IMG_SIZE, num_classes=cfg.TRAIN.NUM_CLASSES, num_channels=cfg.TRAIN.NUM_...
f1c171e0dca8e6d9630ef357099088d2ab46fd813a39ca4fa233591fb53e4fee
Python
5,519
155
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
72819eb9bd02a2a7ad4dea25aa748baf96b973febe99230e579e38f8222389f0
Python
5,523
149
import os import random import re import tempfile import unittest import hydra import torchvision import yaml from hydra.experimental import compose try: from hydra import initialize except ImportError: from hydra.experimental import initialize import lightly from lightly.data import LightlyDataset from ligh...
90c60216e357c417cd7855deb693138c0fb5f37485d4d18b500a835dc69bcfb3
Python
5,525
189
"""TensorFlow payload codec and portable ``.tlspec`` round-trip tests.""" from __future__ import annotations import json from pathlib import Path from typing import Any import numpy as np import pytest import safetensors # noqa: F401 from conftest import tensorflow_backend_modules tf, keras, _TF_BACKEND_SKIP_REASO...
f0228e5a7b46a4d1d8a6324068f71ba433ce9de1b97c4d4fc5a73d4890a381fc
Python
5,525
141
"""SQLAlchemy session.""" import time from kombu.utils.compat import register_after_fork from sqlalchemy import create_engine, inspect, text from sqlalchemy.exc import DatabaseError from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool from celery.utils.log import get_logger from celery.utils.t...
7ec8748a462641e2291eb1c5f408b70fa2e65a42410298cbbf0144cef19a19ab
Python
5,526
155
# 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 app...
894f0ca9f9caef3841494a0bce2ab63b584df333054328c4d02c98b5e355e8c6
Python
5,526
141
"""Tests for the xcp_d.utils.write_save module.""" import os import numpy as np import pytest from xcp_d.utils import write_save def test_read_ndata(ds001419_data): """Test write_save.read_ndata.""" # Try to load a gifti gifti_file = ds001419_data['gifti_file'] with pytest.raises(ValueError, match=...
8b45e202eb4d6a5f489801aa32d48b544abf422a99a06025016c25486acd63c4
Python
5,526
153
#!/usr/bin/env python3 # coding: utf-8 """ Created in April 2022 @author: Simon Delarue <sdelarue@enst.fr> """ from typing import Optional, Union import numpy as np from scipy import sparse from sknetwork.gnn.activation import BaseActivation from sknetwork.gnn.loss import BaseLoss from sknetwork.gnn.base_layer import...
22ef9a0063f203798482262abbdeff15def815858184a0379f90c32a9b056c34
Python
5,528
184
from unittest.mock import Mock, patch import pytest from celery import chord, group from celery.app import builtins from celery.contrib.testing.mocks import ContextMock from celery.utils.functional import pass1 class BuiltinsCase: def setup_method(self): @self.app.task(shared=False) def xsum(x)...
b2dc276cd9c2893323838f9910eebed5717d5e9bb32485c9537216ce42cf72e7
Python
5,530
160
"""Scheduler for Python functions. .. note:: This is used for the thread-based worker only, not for amqp/redis/sqs/qpid where :mod:`kombu.asynchronous.timer` is used. """ import os import sys import threading from itertools import count from threading import TIMEOUT_MAX as THREAD_TIMEOUT_MAX from time import s...
a9bc4fd3b055b08e8c2b87ff36021588919127d50e9cf59df8162b124e8e648b
Python
5,532
173
""" sess_file_util.py This module contains functions for loading and reading from data files generated by the Allen Institute OpenScope experiments for the Credit Assignment Project. Authors: Colleen Gillon, Blake Richards Date: August, 2018 Note: this code uses python 3.7. """ import glob from pathlib import P...
1ce7ff52176524cf9bdc11ecff9732de236dfe1e3e197eb25d382e3509328712
Python
5,533
166
# This example requires the following dependencies to be installed: # pip install lightly # pip install "scikit-learn>=1.7.1" # Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single...
0603c7acfb570cd6ec172317e40cd3c06d8c186eee64a7a576d2b34522c604f4
Python
5,534
174
# %% import pandas as pd import matplotlib.pyplot as plt from globals import path, sessions, subjects, folder_spots_noboth, colours_types import os from plotting import prettifySpinesTicks, removeSpines lwD = 7 widthtick = 10 lenD = 20 ss = 50 transparency = 0.9 mc = "black" plt.rcParams.update( { "font.s...
8d6bf870e6e6042a398d13543f40468913ce008e35d44399a838f16ae6008cdd
Python
5,534
149
#!/usr/bin/env python """ Using a pre-trained model, and given the preprocessed signal arrays, annotate the state for each sample in the signal array, and save out a 1) a hypnogram, and 2) the likelihood of the predicted state for each sample. The latter can then be used to manually refine annotation. """ import nump...
f2660d4395141c7671559300b5c6216f367dbe9e0002afd6f1e35fd47923dd69
Python
5,534
148
"""Semantic identity goldens for the RenderIR-backed rank renderer. Regenerate deliberately with ``TORCHLENS_UPDATE_RANK_RENDER_IR=1`` (the update run reports SKIP, never green; re-run without the flag to verify). Governance adjudication (b10 R78 round-3): this family is ENVIRONMENT- SENSITIVE — the semantic record i...
87b872e1f26e87a880c0c42e35cbc32d1cd4e49123265f7435e8879317c3993f
Python
5,537
155
# 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 app...
7a9e0a0359a529f29e4531b51d5d44eda9ee01634d6e6a575a67bc6fff527ebf
Python
5,538
165
#!/usr/bin/env python import sys import tarfile import unicodedata import wave from glob import glob from os import makedirs, path, remove, rmdir import pandas from sox import Transformer from tensorflow.python.platform import gfile from deepspeech_training.util.downloader import maybe_download from deepspeech_traini...
7ced5965cdc21bc513cd394edf50bf0414aef8df49ff83d0210da736048c4a86
Python
5,538
179
"""Smoke tests for garbage-collected results on the Redis result backend. Regression coverage for #10326: the garbage collector can run ``AsyncResult.__del__`` -> ``cancel_for`` while the same thread is in the middle of a pubsub SUBSCRIBE, UNSUBSCRIBE or ``get_message()``. The nested UNSUBSCRIBE deadlocked on redis-p...
ff5fc2de58486fb9d0f944585ff2ae3a1234ba1f0689ccb84d14d17964ab9799
Python
5,539
150
"""Calculate Intersection-Over-Union(IOU) of two bounding boxes.""" from __future__ import division import numpy as np def bbox_iou(bbox_a, bbox_b, offset=0): """Calculate Intersection-Over-Union(IOU) of two bounding boxes. Parameters ---------- bbox_a : numpy.ndarray An ndarray with shape :...
8d47fae7b594cb94f450ca77bd8374be0027db3384a3bedd4a815e7b5a44d22d
Python
5,540
154
from typing import Callable, Dict, Hashable, Optional import networkx as nx import numpy as np from nfp.frameworks import tf from nfp.preprocessing import features from nfp.preprocessing.preprocessor import Preprocessor from nfp.preprocessing.tokenizer import Tokenizer try: import rdkit.Chem except ImportError: ...
9fae56aa56abcf0f780297af8af77af2bfe82c0f6c4c52d6fbc9f8582e6bd8c3
Python
5,540
125
import copy import os import warnings from typing import Any from xml.etree import ElementTree as ElemTree from mirp.settings.utilities import str2list, str2type, read_node def import_data_settings( path: str, is_mask: bool ) -> list[dict[str, Any]]: if not os.path.exists(path): raise ValueError(...
4f8aa4518fd602c40f5cff2a1a7f60423e1774e7d5db1602f50f52f0d91659b6
Python
5,543
229
import array import pytest import struct import sys import rpy2.rinterface as ri try: import numpy has_numpy = True except ImportError: has_numpy = False ri.initr() def test_init_from_iter(): seq = range(3) v = ri.IntSexpVector(seq) assert len(v) == 3 for x, y in zip(seq, v): ass...
94b7d92b748d24c23ff32860768549dd4962e0697da951eb89098edc827f46f6
Python
5,543
162
"""TensorFlow static FuncGraph fallback tests.""" from __future__ import annotations from pathlib import Path from typing import Any import numpy as np import pytest from conftest import tensorflow_backend_modules import torchlens as tl from torchlens.backends.tf import TFBackend tf, keras, _TF_BACKEND_SKIP_REASON...
fef371a3921bde31779642895681859f7d73353b94be79b475f21b12746dadf6
Python
5,543
166
"""Medians of SPD/HPD matrices.""" import warnings import numpy as np from .base import sqrtm, invsqrtm, logm, expm from .distance import distance from .mean import mean_euclid from .utils import check_weights def median_euclid(X, *, tol=10e-6, maxiter=50, init=None, weights=None): r"""Euclidean geometric media...
dcba5cf90b6fd53f59abda2dfd854c785cca42464c4fe027dae205d39d6cb14d
Python
5,544
121
import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import Dataset, DataLoader from torch.autograd import Variable from torch.nn import Linear, ReLU, CrossEntropyLoss, Sequential, Conv...
e28a0434cd4e633e9b9596e926501030185bd862702342b9e9bef9b336cf1dbd
Python
5,544
171
"""Shared application unit-test support for job runners.""" import datetime import os import tempfile import time from galaxy import model from galaxy.jobs.job_destination import JobDestination from galaxy.util import bunch class MockJobWrapper: """A runner-facing ``MinimalJobWrapper`` test double with real wor...
0caab340533e119a65db5acceca2d01687828005f819da4744cc114c098b4ba0
Python
5,545
142
from typing import Optional, Tuple, Union import torch from pytorch_lightning import Callback, LightningModule, Trainer from pytorch_lightning.accelerators import Accelerator from torch import Tensor from torch.nn import functional as F class KNNOnlineEvaluator(Callback): """Weighted KNN online evaluator for sel...
1b0dc600a6cee976fae83f718c60a3384c9b34fdfa5b77369bd0a7556acf03c7
Python
5,545
194
"""Set of Error classes for gym.""" import warnings class Error(Exception): """Error superclass.""" # Local errors class Unregistered(Error): """Raised when the user requests an item from the registry that does not actually exist.""" class UnregisteredEnv(Unregistered): """Raised when the user reque...
d1b4f3a3d4efb98329cfe96b2cd4853da1b259f1ae062d7ddd346fc7147ff5c8
Python
5,545
171
import numpy as np import skimage.io from scipy.ndimage import zoom from skimage.transform import resize from caffe.proto import caffe_pb2 def load_image(filename, color=True): """ Load an image converting from grayscale or alpha as needed. Take filename: string color: flag for color format. Tru...
f7b7c7775fffe2863af8d894bfc46069b63b74c942e28bacb6990ef0e05f3227
Python
5,545
117
from nose import tools as nt from nose.tools import assert_dict_equal import neurom from neurom import load_neurons import numpy as np from numpy.testing import assert_array_almost_equal, assert_array_equal, assert_equal, assert_raises from tns import extract_input import os import json from tns import TNSError import...
0b7eb1c5201508cc81df74d315eee5fe8d37f6c7f6142bb81871606d7b3324a1
Python
5,547
144
#!/usr/bin/env python3 """Cross-paper consistency check. Run one canonical synthetic subject through every paper's *canonical* compute path and assert byte-identical 5D output. Catches the kind of cross-paper drift the May 2026 audit found (paper 5 / paper 6 / paper 7 had different generations of `compute_phi_5d` scat...
cfd2cde87a2d6b5081d199b4301412296901489019d7aaa191779844e8200a2b
Python
5,547
111
import torch class _input: """ Algorithm input. """ def __init__(self): self.dat = None self.dim = None self.ct = None self.mat = None self.mu = 1.0 self.po = None self.sd = 1.0 self.tau = 1.0 self.file = None self.fname = No...
b0cfb99c3a278d4dc3d5615bc79a50a4c1bbb87e39d17a1e6799501b880f07b0
Python
5,548
165
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import argparse from sklearn.model_selection import LeaveOneOut from sklearn.model_selection import train_test_split from models import GraphConv, AE, LP from utils import * parser = argparse.ArgumentParser() parser.add_argument('--n...
d2c94ddcd9bc1be00b4247ae396a5b32326647011d3be700f2d5725469328e0d
Python
5,548
158
#!/usr/bin/env python3 """ File: save_ieqtl_fdr_matrix.py Created: 2022/07/05 Last Changed: Author: M.Vochteloo Copyright (C) 2020 University Medical Center Groningen. A copy of the BSD 3-Clause "New" or "Revised" License can be found in the LICENSE file in the root directory of this source tree. ...
ed9715dfe3443dd09e10055055d57fe69fd644e2a36fe1c7640fc298feab93c5
Python
5,548
149
import numpy as np from numpy.testing import assert_array_equal import pytest from pyriemann.datasets import sample_gaussian, RandomOverSampler from pyriemann.geometry.distance import distance_riemann from pyriemann.geometry.test import ( is_herm_pos_def as is_hpd, is_real, ) pytestmark = pytest.mark.numpy_on...
ed0e1a73890422f97bca08dee32982a700e51454b5b9ed4708ebc02ccf79cc6f
Python
5,549
156
""" Code to fine-tune hugging-face implementation of GPT2 model. https://huggingface.co/ """ import warnings warnings.simplefilter(action="ignore") import os import gc import glob import logging import argparse import pandas as pd from transformers import GPT2LMHeadModel, GPT2Tokenizer from irnlm.models.tokenizer i...
fc6120dd76a8eefae73cd6a0ae846459305171b7faf1c5c3941ae3170d0b0bc7
Python
5,549
129
import numpy as np import math import random from collections import defaultdict def tokenize_pet_mlm_txt(tokenizer, config, txt1, txt2, txt3, txt_trim, mask_idx=None): ''' Tokenizes the text by trimming the appropriate txt :param tokenizer: param config: :param txt1: :param txt2: :param ...
7f72a640ad0edc4403b3d3f2cb21d12c4ea1a9a9c003f064cd028f85c5efba07
Python
5,550
172
#!/usr/bin/env python """ NAME : LDC TIMIT Dataset URL : https://catalog.ldc.upenn.edu/ldc93s1 HOURS : 5 TYPE : Read - English AUTHORS : Garofolo, John, et al. TYPE : LDC Membership LICENCE : LDC User Agreement """ import errno import fnmatch import os import subprocess impo...
ae3d4c2abc3433346fe5c207157fc7dbe83ea9eadd42fb8e446e035767f35632
Python
5,551
168
import json import numpy as np import seaborn as sns import torch from matplotlib import pyplot as plt from sklearn.metrics import roc_curve, roc_auc_score, precision_recall_curve, auc sns.set_theme() def extract_best_model(directory, metric='val_loss'): """ Extract best model from a directory with checkpoin...
5ec82ee18367a6acbe327d39df3b4e74ba428bc6de5980464e5fde9f844c06b2
Python
5,552
168
import shutil import os import json import sys import pathlib import copy import hashlib import collections from tools.hash_value.make_hash import * from tools.hash_value.parameters import * def save_parameter_set(parameter_set, destination): """ :param parameter_set: :param destination: :return: ...
66371a017252aa2e8606ba13dbc6c76307088d69159a5f46970138a9412846c5
Python
5,552
111
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from ultralytics.engine.results import Results from ultralytics.models.yolo.detect.predict import DetectionPredictor from ultralytics.utils import DEFAULT_CFG, ops class SegmentationPredictor(DetectionPredictor): ...
923aa814403653dc9ab9e21efdb61a4f0e92fe51cdf1982817937e3a01634b94
Python
5,552
143
"""Provider-specific behavior for interactive file-source template forms. The template manager owns the generic lifecycle; capabilities own remote-service lookups and validation that are meaningful only for one file-source type. """ from collections.abc import Callable from dataclasses import ( dataclass, fie...
7c148dd0dcbd9d0d2429a255d2b9bfc1757e66939ee5786be60dba7cd695c0a9
Python
5,554
77
"""Протокол B2 (ЧЕРНОВИК, 13 октября 2026): конфигурация для следующей версии эксперимента «Когда выгодно учиться». Не заморожен, прогонов по нему не было. Что здесь уже решено (ИДЕИ_2026-10-13.md §2.5, §5.6, §5.7; REPORT_B.md §10): * нейтральный маркерный ген marker_gene=True во всех условиях: второй мультиплик...
aab59e40b19f976097573eb682b533da15e4046275f1820db5fdd5e2d9af4f92
Python
5,554
139
#!/usr/bin/env python3 """ Dx BM — State-geometry feature sensitivity check ================================================= Reviewer concern: 4 of the 15 features (I_A, org, I_M, I_R) are defined in self-deposited Howie 2026a-d Zenodo preprints whose construct validity has not been independently established. rel_alp...
4e35016a0fbed4b29b9edf2cc086563344f69a25c3756d3c34b0e409276078b0
Python
5,555
149
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import build_norm_layer, ConvModule from mmcv.runner import BaseModule from .fpn import FPN from ..builder import NECKS @NECKS.register_module() class FPNonLinearNeck(BaseModule): """The feature pyramid non-linear neck. Stru...
a722e861f4de45fb35150b4f9755b3307c6401fe73ff108df86ebdbf127878a1
Python
5,555
183
"""Tests for access-time theoretical roofline properties.""" from __future__ import annotations import json import pickle from pathlib import Path from typing import Any import pytest import torch from torch import nn import torchlens as tl from torchlens import constants from torchlens.quantities import Bytes cl...
f6355c79ba968a7c7a0c758bf96bbc9117726ae2f243264fd466a10380ca9dd7
Python
5,555
136
import argparse import os import random import time from tqdm import tqdm import numpy as np import pandas as pd import torch from torch_geometric.data import DataLoader, DataListLoader,Batch from torch_geometric.nn import DataParallel from sklearn import metrics import torch.nn.functional as F from torch.o...
0b82359614ed1fde57a1eb4d84e78e16cb13fdbc310ae4b3b9608d3c15c62162
Python
5,556
137
import unittest from numpy import ones, hstack from cantera import Solution, one_atm import numpy as np from spitfire import ChemicalMechanismSpec from os.path import join, abspath from subprocess import getoutput test_mech_directory = abspath(join('tests', 'test_mechanisms', 'old_xmls')) mechs = [x.replace('.yaml', '...
3ee1159f30e3b85adb49bf985d2fb1bf8f48cee284d8eb9dff5513b95b68677f
Python
5,558
126
import torch import numpy as np def pad_patient_3D(patient, shape_must_be_divisible_by=16, min_size=None): if not (isinstance(shape_must_be_divisible_by, list) or isinstance(shape_must_be_divisible_by, tuple)): shape_must_be_divisible_by = [shape_must_be_divisible_by] * 3 shp = patient.shape new_s...
94088855c5fc9e12537f717e8355def58d5cfe12d650fa7351741668eabdc69a
Python
5,558
159
import re import numpy as np import pandas as pd from tqdm import tqdm import benepar from spacy.symbols import ORTH import torch from irnlm.data.utils import set_nlp_pipeline, get_ids_syntax from irnlm.data.extract_syntactic_features import integral2syntactic from irnlm.models.gpt2.extract_features_gpt2_integral im...
1f2ce97b472ce5a15eaf9077fa23ad0750a30cc8280dac6251c54ce4b2d7dbfd
Python
5,559
182
# %% import sys sys.path.append("/home/rzhu/Documents/edamame/") # %% import numpy as np import matplotlib.pyplot as plt import pandas as pd import nptdms from edamame import * from edamame.analysis.InfoTheory import * import mkl from fig8_online_seq import * from sklearn import preprocessing # %% from tqdm import ...
1fa64df5bc9fec69765ac612573434c0e4f44dccb8c43f20726772e5bed0119b
Python
5,561
223
import math import numpy as np class Point(np.ndarray): def __new__(cls, x, y=0, dtype=float): obj = super(Point, cls).__new__(cls, shape=(2,), dtype=dtype, buffer=None, offset=0, strides=None, order=None) if type(x) ...
77138a042ed4cde3fc3d2b364e8d290f15f3d0d5f2863a4a5978d89aba34a349
Python
5,561
162
import copy from typing import Any from mirp._data_import.dicom_multi_frame import ImageDicomMultiFrameStack, ImageDicomMultiFrameIndividual from mirp._data_import.dicom_file_mr import ImageDicomFileMR from mirp._data_import.utilities import get_pydicom_meta_tag class ImageDicomFileMRADC(ImageDicomFileMR): def _...
a2cfe3c9a7fa27f96384054f747bdf059c9e1bebdeea2fbecb6804444b3995e7
Python
5,561
221
#!/usr/bin/python3 # # script to learn multi-output regression neural network to predict protein secondary structure # # (C) Yuri V. Milchevskiy, Yuri V. Kravatsky # email: milch@eimb.ru # # Dependencies: # 1. python 3 (tested with python 3.8.10) # 2. numpy (tested with 1.22.3) # 3. PyTorch (tested with 1.12.1) # ##...
c8f9f399c881f4a6f5b411893e3d7cf835698e4bb247786f770ade9079e75e76
Python
5,561
134
"""B8-18: a captured conditional must not leak an absolute source path on save. ``Trace.conditional_records`` holds ``ConditionalEvent`` objects whose ``source_file`` is the ABSOLUTE path of the user's ``forward``-defining module. Those dataclasses had no ``PORTABLE_STATE_SPEC``, so the scrubber returned them verbatim...
fcf2b1c2b913a74af2e61bebf428eb628efe17c42bca7dfcbd3392ec66bc299f
Python
5,561
150
import argparse import os import numpy as np import math import torchvision.transforms as transforms from torchvision.utils import save_image from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import ...
09479e231cbdf3869382112c261e7d8c1185819cb2963a03aaba6e5045e447e1
Python
5,564
164
# Copyright 2023 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...