sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
c4f50bd624369a3054c65f8e327107bb6d2d7359cec52db917a7cfd8c18d9dde
Python
1,763
50
__author__ = "quentin" from ethoscope.hardware.interfaces.lynx_motion import LynxMotionInterface class SleepDepriverInterface(LynxMotionInterface): def send(self, channel, dt=350, margin=10): """ Sleep deprive an animal by rotating its tube. :param channel: The channel to use (i.e. the nu...
eaf33d4a1d279a1f68aa971b3c1823fb8a27e0dd7f2ad3d2ad2f4854ed0ab157
Python
1,763
54
from setuptools import setup, find_packages from pathlib import Path this_directory = Path(__file__).parent long_description = (this_directory / "README.md").read_text() setup( name="tomopari", version="0.2.16", description="A plugin for accelerated tomographic reconstruction.", long_description=long...
6e680c87839d65f29da6e3f5c9f94c94181a538c19e67c0664d59c07ab44b1e5
Python
1,764
36
from pyrosm.data_manager import get_osm_data from pyrosm.frames import prepare_geodataframe import warnings def get_network_data(node_coordinates, way_records, tags_as_columns, network_filter, bounding_box, slice_to_segments): # Tags to keep as separate columns tags_as_columns += ["id", "...
e0c6118881f3b21505bcefeb582659b806f0069083e84b014be997305b83bcdd
Python
1,764
56
import os import json """ Meta.json is the core for each model. It contains the combination of morphologies and parameter sets. """ def write_meta(directory, selected=False): """ meta.json contains the combinations of morphologies and parameter sets and additional parameters f...
65b079c8da165ff48772bb1b16e5fed0006dddb17fd7f8efa75d13e00187b618
Python
1,765
57
"""Common type definitions. The annotation files in BDD100K format has additional annotations ('other person', 'other vehicle' and 'trail') besides the considered categories ('car', 'pedestrian', 'truck', etc.) to indicate the uncertain regions. Given the different handlings of these additional classes, we provide thr...
8ede87ef554d9bcfe00f96607041e51adfe1f21685534549de2ff2c2b4c1975f
Python
1,765
59
"""This module runs continuous updates for R, such as redrawing graphs when the plot window is resized. Use the start() and stop() functions to turn updates on and off. """ from rpy2.rinterface import process_revents import time import warnings import threading class _EventProcessorThread(threading.Thread): """ ...
12839978cfef4d8b8300b996bb31650425118a1de44678ffa0ed3044e5351273
Python
1,766
66
"""Classic clean-versus-corrupted out patching. What this demonstrates ---------------------- Capture a clean run and a corrupted run, then patch the corrupted ReLU out with the clean out. How to run ---------- ``python examples/intervention/03_out_patching_paired_prompt.py`` Runnable by default. The "prompts" are s...
56b0915adbaa8582fb3c54a164c6581124aa0b7725f12441f2dda378beb75e2f
Python
1,766
70
""" Custom parameters and parameterized classes extending those existing in the `param` package. Previous versions eagerly re-exported everything with star-imports. We now lazy load these to avoid heavy import chains and potential cycles while preserving the public API surface. """ from __future__ import annotations ...
f7acda30b4fd501430b26e2e8b9c3226efe4677eb27272afa39bfc2246c70f61
Python
1,766
55
import os from setuptools import find_packages, setup def read_requirements(path): with open(path, "r") as f: return [line.strip() for line in f if line.strip() and not line.lstrip().startswith("#")] with open("README.md", "r", encoding="UTF-8") as fh: long_description = fh.read() setup( name=...
e8ff764977f10e6b4495916dc98d8b0a831fcc24e98a7a259b6f37fe117d7e4b
Python
1,767
55
from __future__ import division import unittest import numpy as np from wyrm.processing import calculate_whitening_matrix, apply_spatial_filter from wyrm.types import Data SAMPLES = 1000 CHANS = 3 class TestCalculateWhitentingMatrix(unittest.TestCase): def setUp(self): data = np.random.randn(SAMPLES...
faf7b76fc3b13d1911def628f2eb7e6baefff670de1692f0573973faec2a46be
Python
1,767
43
"""Drop whole-text annotation indexes. Revision ID: a4c3f2e1b790 Revises: e96dd6fd5863 Create Date: 2026-09-17 """ from galaxy.model.migrations.util import ( create_index, drop_index, index_names_on_columns, ) revision = "a4c3f2e1b790" down_revision = "e96dd6fd5863" branch_labels = None depends_on = None...
f261c0a6ad58b3e3bc3b7c04833df3c9051ac952c87f6842fd9dc3ccac3b3326
Python
1,768
58
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.architecture["motif_model_spec"]["motif_width"] = 13 msp.architecture["motif_model_spec"]["motif_feature...
4f3115c18642066f59fffe208b6860a42813691a7c339a66551d931b02d11b87
Python
1,769
51
import json import pandas as pd from tqdm import tqdm tqdm.pandas() def main(): type_ = 'old' test = pd.read_csv(f'./data/csvs/data/test_new_{type_}.csv') old_new = pd.read_csv(f'./data/csvs/data/test_new_old.csv') old_new = old_new[['Drug2_ID', 'Drug2_SMILES']] with open('./data/jsons/tf_...
96fff76f9a32177e572bb3a317ba4b2a08695542d52f914ceb8473a4c1a2c55e
Python
1,769
39
import tensorflow as tf from tensorflow.keras.layers import (Dense, Dropout, Embedding, Layer, LayerNormalization, MultiHeadAttention) from tensorflow.keras.models import Sequential class TransformerBlock(Layer): def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1): ...
a81b87733ccb0c6d359e9c1c61ba1554304c7be8d1a0ee9fb442a860f5e8ce1b
Python
1,769
77
""" spike_features.py Basic modules for spike feature extractions. """ import numpy as np ########################################################################## ########################################################################## def return_mfr(spiketimes, time_window): """ Returns mean firing ra...
ef0993d5b220ff6fc8a8ff62e6b8eb3b85f122debda3d65c747b9bab387e4cd8
Python
1,769
54
import os import argparse import logging import autogluon.core as ag from gluoncv.auto.tasks import ObjectDetection from gluoncv.auto.estimators import YOLOv3Estimator from d8.object_detection import Dataset os.environ['MXNET_ENABLE_GPU_P2P'] = '0' if __name__ == '__main__': # user defined arguments parser ...
16b74aafa625905d5b083867f6aa40bd2a4495d4defc74fa7dc33b6208fa8efc
Python
1,770
60
#!/usr/bin/env python import numpy as np import argparse parser = argparse.ArgumentParser(description='Plot weight histogram.') parser.add_argument('--freq', type=float, default=1.0, help='repetitation freq') parser.add_argument('--pairings', type=int, default=100, help='nb pairings') parser.add_argument('--interval'...
22ea40259e80f449b6c59de201c65b6229aafe29669894dbac07bf63813c953e
Python
1,770
64
"""Publish an intervention recipe with ``.tlspec``. What this demonstrates ---------------------- Save a portable intervention spec, load it back, and check that it still targets a fresh compatible capture. How to run ---------- ``python examples/intervention/15_publishing_for_reproducibility.py`` Runnable by defaul...
67488e864bf04ad512c90cf21d5323b61dbc3167047e2f5a5fc539659753001d
Python
1,770
56
import os from options.test_options import TestOptions from data import create_dataset from models import create_model from util.visualizer import save_images from itertools import islice from util import html import time start_time = time.time() # options opt = TestOptions().parse() opt.num_threads = 1 # test code...
ffdf2c3017637fb071facc0c34a4119384e6fe37f9e579d4d06764d01d3a529e
Python
1,770
47
import torch import torch.nn.functional as F from torch import nn class SPADE(nn.Module): def __init__(self, kernel_size, norm_nc, label_nc, param_free_norm_type='batch'): super().__init__() if param_free_norm_type == 'instance': self.param_free_norm = nn.InstanceNorm2d(norm_nc, affine...
54c8e63302e006f58e7c9b752a4be9a32adca2e91de878d009d15763adcab9b0
Python
1,771
69
''' Copyright 2023 Douglas Feitosa Tomé 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 3 of the License, or (at your option) any later version. This program is distributed in the hop...
0769bf7c9786a8e381a53ab30288b2cb075c5818358e52117fd124e7e4e793c3
Python
1,772
52
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ Test objects and function in the module ``tfep.potentials.base``. """ # ======================================...
4bc43b559e3c868a6c26e0701f37a4120f0dcb43980240716db011ebf4f9872c
Python
1,772
46
import pytest import torch from lightly.loss.ibot_loss import IBOTPatchLoss class TestIBOTPatchLoss: @pytest.mark.parametrize("device", ["cpu", "cuda"]) def test_forward(self, device: str) -> None: if not torch.cuda.is_available() and device == "cuda": pytest.skip("CUDA not available") ...
4fa4a70ef82de3dd172f6ff8f55bf85bc489813436ff69da515be4065321c966
Python
1,773
75
""" Widget for editing the borders placed in an environment. """ from __future__ import annotations import param from .widget_base import ( classdict_editor, collapsible_family_box, family_box, parameterized_editor, ) __all__ = ["build_border_widget"] def _ordered_names(instance: param.Parameteriz...
0db70258f211758ec5183e87e8811fc85f45a8cf38e062c03ba5436c8bd613bf
Python
1,774
102
""" Location of protocols used in datatypes """ from typing import Any from typing_extensions import ( Protocol, runtime_checkable, ) from galaxy.objectstore import ObjectStoreAuth class HasClearAssociatedFiles(Protocol): def clear_associated_files(self, metadata_safe: bool = False, purge: bool = False...
256e8b082b777388915c88d3d2e80e0f040fbefeff9cbf5ab43f2fa0fbc163f2
Python
1,774
44
from __future__ import division import argparse import numpy as np import mxnet as mx from mxnet import gluon, nd, image import matplotlib.pyplot as plt import gluoncv as gcv gcv.utils.check_version('0.6.0') from gluoncv import data from gluoncv.model_zoo import get_model from gluoncv.data.transforms.pose import det...
41d9c308ef8502c11a32d25ae51e3c789ea0981cd830cb35552df080b398c3c5
Python
1,774
45
import unittest from os.path import join, abspath import os from numpy.testing import assert_allclose from tests.tabulation.adiabatic_equilibrium.rebless import run from spitfire.chemistry.library import Library import spitfire.chemistry.analysis as sca from spitfire.chemistry.ctversion import check as cantera_versio...
731ff1302f7e372ce406d42e9fb7d5eaa7476d1149ef07e9559414aaa5611d3b
Python
1,774
73
"""Set of functions for logging messages.""" import sys import warnings from typing import Optional, Type from gym.utils import colorize DEBUG = 10 INFO = 20 WARN = 30 ERROR = 40 DISABLED = 50 min_level = 30 # Ensure DeprecationWarning to be displayed (#2685, #3059) warnings.filterwarnings("once", "", DeprecationW...
8de21629e22da1c8222eed54537aec980a61ab8b64e4e446f122e80b8b0185e7
Python
1,774
55
from __future__ import annotations import pytest from pytest_celery import RESULT_TIMEOUT, CeleryTestSetup, CeleryTestWorker, CeleryWorkerCluster from celery import Celery from t.smoke.conftest import SuiteOperations, WorkerKill from t.smoke.tasks import long_running_task @pytest.fixture def celery_worker_cluster( ...
d79c3cb616a022a1a9243c84631f835110f6489f3f6c58f07a747e943a186162
Python
1,774
54
import sys from robustness import datasets from robustness.attacker import AttackerModel from robustness.model_utils import make_and_restore_model from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH def build_net(ds_kwargs={}, return_metamer_layers=False): # We need to build the datase...
66fd82350f5c0ba84118ba6bbd65d5f732a6109d190f257e670899a9a9b06ad1
Python
1,775
54
import numpy as np import torch from scipy.optimize import linear_sum_assignment from sklearn import metrics from torch import nn class ZINBLoss(nn.Module): def __init__(self): super().__init__() def forward(self, mean, disp, pi, x=None, eps=1e-10): if x is None: zero_nb = torch.p...
0c8a006c7cf5a53ca400deaa96eda7d4d18817f6b72aaa949130adca30fbb60c
Python
1,776
44
"""Stop-early surface tests (A06 rewrite: ``stop_after`` is WIRED). Historical note: these tests originally pinned the pre-wiring defect -- ``pluck`` accepted-and-ignored ``stop_after`` while ``trace`` raised ``NotImplementedError``. A06 wired the option through the halt engine with brainpipe's inclusive spelling; the...
2a504ee4a58deb26879c2c0f65c46d3922ba5316f27fcc044960704479ca283e
Python
1,777
57
from os.path import dirname, join import numpy as np from sklearn.datasets.base import Bunch def load_housing(): from pandas import read_csv """Load and return the Copenhagen housing survey dataset (ordinal classification). ============== ============== Samples total 1681 ...
3e9501333e7bdd61c56b9e18ba1230c073c8b93a059f3804e1f8e4c94090a531
Python
1,777
63
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ Base conditioner classes for autoregressive flows. """ # =====================================================...
8d261417f43ef704419a743285f538a274c560064f947e8f1e154a7f7f63aabf
Python
1,777
65
"""Module for handling image loading in torchvision-compatible format. This module provides image loading functionality similar to torchvision's implementation (see https://pytorch.org/vision/main/generated/torchvision.datasets.ImageFolder.html) """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Re...
9a1f7552bf91f6e530b6efa911b03801ad08e228c30cdcbe52c0145fdfe2ddca
Python
1,777
46
from distutils.core import setup, Extension from distutils.command.build_ext import build_ext import os import git class CustomBuildExtCommand(build_ext): """build_ext command for use when numpy headers are needed.""" def run(self): # Import numpy here, only when headers are needed import num...
b69a850d610fafc963a4bcb4825094d2e0210c0d9aae90b64e1f8afb8132d863
Python
1,777
55
import functools import os from .data_directory import DATA_DIRECTORY from .rbns import read_rbns_motif_from_file, read_rbns_motifs RBNS_V2_EXTRAS_DIRECTORY = os.path.join(DATA_DIRECTORY, "motifs_rbns_v2_extras") PASSED_QC = ( "CIRBP ELAVL1 ENOX1 ESRP1 EXOSC2 EXOSC4 EXOSC8 IGF2BP3 LIN28B NSUN2" " PABPC3 PPP1R...
1febd0fb03e2035a94141be13708b65137ad83dce2999ee5d74c77dd88fe7557
Python
1,778
53
# pylint: disable=line-too-long """Encode/Decode helper function for compressed quantized models""" import zlib import base64 def encode_json(json_file, is_print=False): r""" Encode json string to compressed base64 string. Parameters ---------- json_file : str String value represents the path ...
24dc72b9503c6bbc30ca0f8d84b0f1d5fd9d2d72012c5dcc9caeb5b0ac725ac8
Python
1,778
65
import subprocess import requests COMMITS = "https://api.github.com/repos/jsbroks/coco-annotator/commits/{}" COMPARE = "https://api.github.com/repos/jsbroks/coco-annotator/compare/{}...{}" CURRENT_VERSION = "" LATEST_VERSION = "" def get_tag(): result = subprocess.run(["git", "describe", "--abbrev=0", "--tags"...
4e68fb70f684f5ce7f4282e427d2ebcb3ee0219955cab0b2d030306d131cabc4
Python
1,778
50
import pytest from ome_zarr.data import create_zarr from ome_zarr.io import parse_url from ome_zarr.reader import OMERO, Label, Labels, Multiscales, Node, Spec class TestStartingPoints: """Creates a small but complete OME-Zarr file and tests that readers will detect the correct type when starting at all the ...
d2f8d9dac3e25bba227da060532db9617bf48d7e5e6c0b749727d167c8f18145
Python
1,780
68
from modular_splicing.models_for_testing.models_for_testing import ( EndToEndModelsForTesting, STANDARD_DENSITY, ) am_ad_sparse = EndToEndModelsForTesting( name="AM + adjusted donor", path_prefix="model/msp-311a1", seeds=(1, 2, 3), density=STANDARD_DENSITY, ) am_ad_nonsparse = EndToEndModelsFo...
dd55fb03da861573b35e48dc2ede781bcedc6b6aad02f670e4d1e4bfa824fd98
Python
1,780
51
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """Wrapper to train and test a video classification model.""" from slowfast.config.defaults import assert_and_infer_cfg from slowfast.utils.misc import launch_job from slowfast.utils.parser import load_config, parse_args fr...
e0dbc741feba7052b2e74d2403af08055bfffbfa5fef91ea75bab6a1d84932be
Python
1,780
43
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """tests for optimizer""" import unittest import numpy as np from sknetwork.data.test_graphs import test_graph from sknetwork.gnn.gnn_classifier import GNNClassifier from sknetwork.gnn.optimizer import get_optimizer class TestOptimizer(unittest.TestCase): def set...
a401b71879c2b0a976516fbaad13063262ad5324ed35f6d703dbdece128bbb5e
Python
1,781
56
import os import warnings import h5py import numpy as np import scanpy as sc from scbig import run_scbig, preprocess, setup_seed warnings.filterwarnings('ignore') import time from memory_profiler import profile @profile def run(adata): adata = run_scbig(adata) from memory_profiler import memory_usage m...
10277310d6e91e0dd7b89546ce03ca5d3ad26e251b79b825527e2e71bc983d7b
Python
1,782
49
# LICENSE # # _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._ # # BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License"); # # - you may not use this software except in compl...
3b390e0578f2a685963aa979ae4c4b449714b4ec80e6db4306dbe98cc7a39c05
Python
1,782
52
from __future__ import annotations import pytest from kombu import Producer, Queue from pytest_celery import CeleryBrokerCluster, RabbitMQTestBroker from celery import Celery, uuid from celery.app.amqp import Queues @pytest.fixture def celery_broker_cluster(celery_rabbitmq_broker: RabbitMQTestBroker) -> CeleryBroke...
4228c968f1ffade6d54dd94797e24830ee355c5a418502b046a7cf59bafcb802
Python
1,782
53
import logging import secrets import threading from typing import Optional import httpx LOGGER = logging.getLogger(__name__) class MatomoTracker: """Send events to Matomo's HTTP Tracking API for things the browser cannot see, such as the account being created on the API side. Events carry a category, a...
423e01fa6fc92351668885e334a505201ff34fe2735eee3479e92e22dda77929
Python
1,783
44
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # ------------------------------------------------------------------------------ from __future__ import absolute_import from __future__ import d...
c9b5a587b6ef4cf86b87f125d4769aac8287f17c74c4ed6aa0c2488ccdebdd87
Python
1,783
59
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 2 14:07:48 2022 @author: Audrey Mazancieux This script rename physio files from the Prisma 3T scanner. """ import os import glob from sys import exit import math # ============================================================================= #...
fdc59893104cab79a7e9890a3f847dace14d4f42ae8972005382aec49fe913b6
Python
1,783
44
from imodelsx import submit_utils from os.path import dirname import os.path repo_dir = dirname(dirname(os.path.abspath(__file__))) # python /home/chansingh/llm-tree/experiments/01_train_model.py --use_cache 0 --subsample_frac 1 --model_name llm_tree --max_depth 3 --use_llm_refine 1 # python /home/chansingh/llm-tree/...
71a7239f857f00b32936330ba64cdbcc25549e464acc08923e2c326438538609
Python
1,784
63
from gymnasium.spaces import Box as GymBox from gymnasium.spaces import Dict, MultiBinary, MultiDiscrete, Space, Tuple from gymnasium.spaces import Discrete as GymDiscrete from gymnasium.spaces.utils import flatdim, flatten, unflatten class Box(GymBox): """Thin wrapper of gymnasium.spaces.Box. Allow the user...
8c93d7655043f366cbc469db3e2a21d9f9213c933896184dce2a28aceaadb2b3
Python
1,784
56
import json import pandas as pd from tqdm import tqdm def LCSubStr(X, Y): # Create a table to store lengths of # longest common suffixes of substrings. # Note that LCSuff[i][j] contains the # length of longest common suffix of # X[0...i-1] and Y[0...j-1]. The first # row and first column entries have no # log...
06a0127713bb9c2432b16206a0b31fa2ff556d77bdc2a781ed0f95886600b3bd
Python
1,785
50
#!/usr/bin/env python # Variants of this code exists in 2 places, this file which has no # user facing options which is called for implicit data conversion, # lib/galaxy/datatypes/converters/fasta_to_tabular_converter.py # and the user-facing Galaxy tool of the same name which has many # options. That version is now on...
0e9ef4bae4197e6d4e90e807d94d51885334d77fd614fa95269fdd735f7025ac
Python
1,785
50
import os import random import numpy as np import torch from PIL import Image from torch.utils.data import Dataset class DiffusionDataset(Dataset): def __init__(self, image_dir, img_transform=None, label_transform=None, device=torch.device('cpu')): self.image_dir = image_dir self.image_path = os...
d41b6bd067918e162d2079c8d5b0c9803cd41753ef7697fdaecc9674863ef150
Python
1,785
55
import sys from robustness import datasets from robustness.attacker import AttackerModel from robustness.model_utils import make_and_restore_model import torch from model_analysis_folders.all_model_info import IMAGENET_PATH torch.backends.cudnn.benchmark = True def build_net(ds_kwargs={}, return_metamer_layers=False):...
240e89641a6b372b9f8082857a0690d02add4fe2bfcb36c515a8c0777ed3477c
Python
1,786
45
import pytest import gym from gym.envs.classic_control import CartPoleEnv from gym.error import ResetNeeded from gym.wrappers import OrderEnforcing from tests.envs.utils import all_testing_env_specs from tests.wrappers.utils import has_wrapper @pytest.mark.parametrize( "spec", all_testing_env_specs, ids=[spec.id...
ee087c6c92b6f80a117642d223704b19d72213bb472fd71c4ba9e46eda849c2a
Python
1,786
61
from mirp._images.generic_image import GenericImage class RTDoseImage(GenericImage): def __init__(self, **kwargs): super().__init__(**kwargs) self.calibrated_units = True @staticmethod def get_default_lowest_intensity(): return 0.0 @staticmethod def get_default_ivh_disc...
f0f9c666cf4677328fd6e71eee218af9bfac2418aa788cebd1f03cfe85c45892
Python
1,787
48
#!/usr/bin/env python3 import argparse import functools import pandas from deepspeech_training.util.helpers import secs_to_hours from pathlib import Path def read_csvs(csv_files): # Relative paths are relative to CSV location def absolutify(csv, path): path = Path(path) if path.is_absolute():...
402c3492eec3ebf2427c9d7698f43312b5ef8b3fc1b4eec4854693089b6c2b83
Python
1,788
39
from torch.utils.data.dataset import random_split from pl_bolts.datasets.sr_celeba_dataset import SRCelebA from pl_bolts.datasets.sr_mnist_dataset import SRMNIST from pl_bolts.datasets.sr_stl10_dataset import SRSTL10 def prepare_sr_datasets(dataset: str, scale_factor: int, data_dir: str): """Creates train, val, ...
64d6f6349b36c804c73fcc517a16c14dc0789988362b964d78fcb9412aed42b0
Python
1,788
52
"""Standalone: re-run the getitem hot-path bench vs the design gates. Run: pixi run -e dev python tests/bench_ragged_getitem.py Gates: slice within ~1.2x of a bare numpy view-slice baseline; to_numpy(validate=False) within ~1.2x of a bare reshape; from_offsets within ~1.1x of a bare dataclass wrap.""" im...
07e3af533cff8ce296dad07772304e85fc8bac956947de790d167a0b57af0480
Python
1,789
56
"""Tests for the xcp_d.interfaces.plotting module.""" import os import numpy as np import pandas as pd from xcp_d.interfaces.plotting import CensoringPlot def test_censoring_plot_marks_censor_between(tmp_path_factory): """The censoring plot draws a separate legend entry for censor-between volumes.""" impor...
3a92946c75fe8a8cb1fcd536b65e4cac2ad5aacecc2465cbd7af4dc73e00903d
Python
1,789
47
import sys # setting path sys.path.append('../TM2_segmentation') import os import numpy as np import nibabel as nib import itk import pandas as pd import tarfile from scripts.preprocess_utils import find_file_in_path, register_to_template # load metadata file input_annotation_file = 'data/csv_files/PediatricMRI_D...
54b7a816508718162e0641d205844ea8328f5e6227d1bec2416817cee138fb2f
Python
1,790
64
# -*- coding: utf-8 -*- import os #%% function to write to a sbatch file def get_default_conda_env(conda_env_sh): conda_lines = f'''## activate the virtual environment source {conda_env_sh} conda_init > /dev/null 2>&1 conda deactivate > /dev/null 2>&1 conda activate fastai > /dev/null 2>&1 ''...
6ea4e9b99e265abcaddeb236c837c223d83d4934c07a54b8752eccd25889dfab
Python
1,790
54
import os import pandas as pd import numpy as np from sklearn.ensemble import BaggingRegressor from sklearn.ensemble import BaggingClassifier from sklearn import linear_model import sklearn import pickle def load_model(in_model_fp): if not os.path.exists(in_model_fp): print("Error: Can not find ensemble m...
8f2ef1803a33e59eba84d6b6cc04c0d048257c0f585fbb5d5986a304ddea01b0
Python
1,790
43
import tempfile import os from ethoscope.core.monitor import Monitor from ethoscope.hardware.input.cameras import MovieVirtualCamera from ethoscope.utils.io import SQLiteResultWriter, ResultWriter from ethoscope.trackers.adaptive_bg_tracker import AdaptiveBGModel from ethoscope.drawers.drawers import DefaultDrawer from...
e0f4ac2a63fcf69c80867477675d545f637ac052bd1c7d21b7ed9531a83d8076
Python
1,790
37
'''Components of the package: - The Brains class is used to represent the coordinates of multiple instances of the same brain, like you have in a whole-brain imaging recording. Because the number of detected neurons in each volume can fluctuate, the class uses the irregular array (irrarray) from the mistofrutt...
146c486b0a0dd2830a7885a94b61edff8be8a43b7ee588dab48891c88b799822
Python
1,791
57
#!/usr/bin/env python import unittest import os import json import struct import numpy as np from wyrm.io import load_mushu_data class TestLoadMushuData(unittest.TestCase): def setUp(self): with open('foo.meta', 'w') as fh: json.dump({'Sampling Frequency' : 1, 'Chan...
28fdc1b2865ca4bf0e64dd34e9d89c65e9ad0c53a028c2e6858f772c9bd1d587
Python
1,791
58
import torch from keras.src import ops from keras.src import optimizers from keras.src.backend.torch.optimizers import torch_parallel_optimizer class Adadelta( torch_parallel_optimizer.TorchParallelOptimizer, optimizers.Adadelta ): def _parallel_update_step( self, grads, variables, ...
c1e3a9e30c6df9a3584ae39ec33cee8fc4b5ae6dfc13365f5dc6229ed6abfca6
Python
1,791
65
import logging import yaml import argparse from pymatgen.core import Molecule from atomate.qchem.fireworks.core import SinglePointFW from atomate.common.powerups import add_tags from fireworks import LaunchPad, Workflow from instance_mongodb import instance_mongodb_sei from fireworks.user_objects.dupefinders.dupef...
05f9f460517ae5048fc39d234a63acc85c515f207897b65aae6eb7932493b9f2
Python
1,792
67
from cvnn.layers import ComplexUnPooling2D, complex_input, ComplexMaxPooling2DWithArgmax, \ ComplexUpSampling2D, ComplexMaxPooling2D import tensorflow as tf import numpy as np from pdb import set_trace def get_img(): img_r = np.array([[ [0, 1, 2], [0, 2, 2], [0, 5, 7] ], [ ...
e6ef57229016d86938a5b042ff653cd3f80f13c6a71d7c57fde29669e4a54c5a
Python
1,792
66
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["motif_model_spec"]["motif_width"] = 13 msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = dict( type="ResidualStack", depth=3, ) msp.archi...
4874ef7d3c2d54b9905dc09683d2d101b2a7a03b33aa52828d16e16edfa9026a
Python
1,793
69
from os import link from .bulletin import Bulletin from bs4 import BeautifulSoup import re class TamilNadu(Bulletin): def __init__(self, basedir): statename = 'TN' super().__init__(basedir, statename) self.bulletin_url = 'https://stopcorona.tn.gov.in/daily-bulletin/' self.archi...
8ab9b2331fb90220a1afffeb36e017f12ff2484e3bab1fe57e0fec70493d34cf
Python
1,793
57
import os import h5py import numpy as np import scanpy as sc from ica import ica1 from scbig.utils import setup_seed, louvain, calculate_metric def preprocess(adata, scale=True): sc.pp.filter_genes(adata, min_cells=3) sc.pp.filter_cells(adata, min_genes=200) sc.pp.normalize_total(adata, target_sum=1e4) ...
9d6427467a59accd5e05fe1c802e31d7b6a828a31195ba545e18a648d78ae2f0
Python
1,793
48
import os import random from abc import ABC from .data_split import DataSplit class ProteinSplit(DataSplit, ABC) : def __init__(self, split_type: str, split_i: int, cel_name: str = 'pdb_conf_ensembles', root: str = '/home/bb596/hdd/pdbbi...
01a9a1651bd4c5347a77bc7335a4bbcba678fcc6a33a9f44830ecea35d7b326f
Python
1,794
51
from __future__ import annotations from typing import TYPE_CHECKING import numpy as np from gymnasium import Wrapper from neurogym.utils import spaces if TYPE_CHECKING: from neurogym.core import TrialEnv class PassReward(Wrapper): metadata: dict[str, str | None] = { # noqa: RUF012 "description": ...
241df0b29b51b049741b362dcb31e3c2ae39ac6c39c7ef7377f43f0769c8ad03
Python
1,794
54
from typing import List, Sequence, Union from PIL.Image import Image from torch import Tensor from lightly.transforms.torchvision_v2_compatibility import torchvision_transforms as T class ImageGridTransform: """Transforms an image into multiple views and grids. Used for VICRegL. Attributes: tr...
43bc45ed9a14628284b7c82b9116e42f723d3a061f20a3ec9b754835b7d45c68
Python
1,794
66
import logging import os from typing import Optional def set_logger_format(custom_preamble: Optional[str] = ""): logger = logging.getLogger("codecarbon") format = "[%(name)s %(levelname)s @ %(asctime)s]" if custom_preamble: format += f"[{custom_preamble}]" format += " %(message)s" formatte...
554b0343d1318734d12c781312448d55b77466ab23c68c314ddde44cf5eae95f
Python
1,794
53
import os import argparse import torch from src import util # Build em response tensors def build_unit_activity_tensor(dataset): unit_activity_list = [] for i, (_, y) in enumerate(dataset): if i % 10000 == 0: print(f"i={i}/{len(dataset)}") unit_activity_list.append(y) retur...
7636e3941da5216980f4d5764eec2e77310016e95cadb5cc1037d084c200f983
Python
1,795
52
"""Single-sourcing gate for the lookback payload policy vocabulary. The canonical authority is the ``LookbackPayloadPolicy`` literal in ``torchlens/fastlog/options.py``; the runtime tuple is derived from it with ``typing.get_args``, so validation and the type can never drift apart. These tests pin that derivation and ...
e13ba150d913299a2d0e9fe18830ad3baa0580ce12e22581d93b7e3e7ab7985d
Python
1,795
51
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Rewrite an OpenCC config JSON so that its dictionary references point at # a different dictionary format (text or ocd) instead of ocd2. Used to build # the OPENCC_DICT_FORMAT=text/ocd CMake outputs, mirroring the ocd2<->text # config conversion already used by the Bazel...
398cda978e95a567c1bc33d9d306c18c861fe27f31b4cfeb1c3def992d2a0857
Python
1,796
50
import numpy as np from modular_splicing.dataset.additional_data import ( AdditionalData, DatafileReferencingAdditionalData, ) from modular_splicing.utils.genome_statistics import gene_at_richness class GeneATRichnessAdditionalData(DatafileReferencingAdditionalData): def __init__(self, *args, cl_max, **...
adc8468f7e251f993cbd2f2b1e809ee5ba95854f466435724c3ab2648f3a5dc0
Python
1,796
43
""" Use this code to evaluate all models from the different variants of experiment 2 (defined by the length of the pre-cue delay interval) or experiment 4 (defined by the cue validity). Uncomment the relevant code section to run. @author: emilia """ import importlib from main import run_experiment def run_all_varia...
b04bf3cd349b0ea8f107b3af85aa836524eda2bb24d2e6869f4a7f4f5976873f
Python
1,796
59
""" Widget for editing a spatial distribution of agents or sources. """ from __future__ import annotations import param from .widget_base import family_box, numeric_tuple_param_control, param_control __all__ = ["build_distribution_widget"] def build_distribution_widget( distribution: param.Parameterized, ...
49d82b112f5afd4ee3957eef5307e059c0514a01f4b7923200f852b2698009de
Python
1,797
60
from __future__ import annotations from abc import ABC, abstractmethod from typing import Iterable, Any, TypeVar, Generic from bdpy.task.callback import CallbackHandler, BaseCallback _CallbackType = TypeVar("_CallbackType", bound=BaseCallback) class BaseTask(ABC, Generic[_CallbackType]): """Base class for ta...
e253b573c0831919f7b640b1cc77a7dbf213e45075e23c1a3a6e44aa401f2b06
Python
1,797
48
# -*- coding: utf-8 -*- from model import CGAN from utils import input_setup import numpy as np import tensorflow as tf import pprint import os flags = tf.app.flags flags.DEFINE_integer("epoch", 10, "Number of epoch [10]") flags.DEFINE_integer("batch_size", 32, "The size of batch images [128]") flags.DEFINE_integer(...
70619f4351c7beb6553f07d587840590a07970a0d962082f7d8006bde800e55b
Python
1,799
50
#!/usr/bin/env python3 '''Glob through files in current directory looking for */*_ligand.sdf and */*.gninatypes (assuming PDBbind layout). Calculate the distance between centers. If types files are passed, create versions with this information, optionally filtering. ''' import sys,glob,argparse,os import numpy as n...
724b3500b32484ee32b1e8aea86afdf2db910513a1913e58a6e66733f3faf3dc
Python
1,799
77
import numpy as np import torch as th # __func is original, func is GPU optimized def __random_aug(graph, x, feat_drop_rate, edge_mask_rate): import dgl n_node = graph.number_of_nodes() edge_mask = mask_edge(graph, edge_mask_rate) feat = drop_feature(x, feat_drop_rate) ng = dgl.graph([]) ng...
75b9b29d35406fb8888fc3ad25b4bd8bb09700de8f99bd2d9ff4f8b94244ec2f
Python
1,799
62
import numpy as np from .hsmm_model import HSMM def substring_hsmm(hsmm, new_initial, ell): return HSMM( initial=new_initial, distance_distributions=substring_p(hsmm, ell), transition_distributions=substring_a(hsmm, ell), ) def substring_a(hsmm, ell): states = hsmm.states al...
092f06aec5bd12f0108bb81d4a114aa2424807121ffcd6b9cd6e01993d3ebce7
Python
1,800
54
"""Consumer Broker Connection Bootstep.""" from kombu.common import ignore_errors from kombu.utils.url import maybe_sanitize_url from celery import bootsteps from celery.utils.log import get_logger __all__ = ('Connection',) logger = get_logger(__name__) info = logger.info class Connection(bootsteps.StartStopStep):...
0ce417f4460c8d9ca73939e3082dfa886c674d965c7c531d3be4ec553d17583d
Python
1,800
55
import os import paddle def print_metrics(loss, f_max, auprc): print(f"loss: {loss:.4f}, f_max: {f_max:.4f}, auprc: {auprc:.4f}") def get_model_params_state(model, args, epoch, f_max, auprc): return { "model": model.state_dict(), "epoch": epoch, "n_h_dim": args.n_h_dim, "s_...
c5c8a6dd1feeb5354834dc5d7ae93811c80af1e46a0ef2bd701389ce05c78eef
Python
1,800
57
import csv import copy #Функция, определяющая взаимодействие по главной/вспомогательной субъединице. X — цепь рецептора, Y — лиганда. def site(X,Y): if (X, Y) == ('B', 'D'): return '+' if (X, Y) == ('C', 'D'): return '–' Data="{}.csv" Types=['HB','PHOB','PI','SB','STK'] D={} #Dictionary for data...
697e7d20554bf43f291597780fb73693506fe3a7369fb64bd1b5f979ab63806d
Python
1,803
47
from __future__ import division import unittest import numpy as np from wyrm.types import Data from wyrm.processing import select_channels from wyrm.processing import swapaxes class TestSelectChannels(unittest.TestCase): def setUp(self): raw = np.arange(20).reshape(4, 5) channels = ['ca1', 'ca2...
83be96e73ba2729fd932ba5ccdd2f06207b4c4651f50f035c29a3dc97f925328
Python
1,803
51
# 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...
a5cbc2b759ae29aaea21608309185b2f503b31f47edbd8cc12d2660ced4cac9d
Python
1,803
33
#!/usr/bin/env python3 import argparse import os import warnings from predict import predict_itmt from settings import CUDA_VISIBLE_DEVICES if __name__ == '__main__': parser = argparse.ArgumentParser(description = 'Input T1.nii.gz to predict iTMT(temporalis muscle thickness)') parser.add_argument('--age', '-...
f337d205126fb957979695d44347b078ac4f94193a8e9a59905e690ae4556e3d
Python
1,804
52
"""A wrapper that adds render collection mode to an environment.""" import gym class RenderCollection(gym.Wrapper): """Save collection of render frames.""" def __init__(self, env: gym.Env, pop_frames: bool = True, reset_clean: bool = True): """Initialize a :class:`RenderCollection` instance. ...
5b9e68174411a4257476b40ed7cb711d554730fb15f847645447c6c467ef6a78
Python
1,805
66
import torch from pathlib import Path import nibabel as nib from DeepDenoise.src.res_unet import CESTResUNet from DeepDenoise.src.unet import CESTUnet import pytest def test_unet(): # Initialize the model model = CESTUnet(input_shape=(42, 128, 128)) # Generate a random input tensor x = torch.randn((1...
62cccf4d905ef68349654f39adc3f4304e6ce56161c5c8cbd043cfeabe0cb411
Python
1,805
48
import torch from torch.nn import functional as F def sigmoid_focal_loss(inputs: torch.Tensor, targets: torch.Tensor, alpha: float = -1, gamma: float = 2, reduction: str = "none") -> torch.Tensor: """ Loss used in Reti...
7088f899a5929361c11bacfa3f718875f9f45a63571c6c68eefa84250c8b0803
Python
1,805
69
import numpy as np from .coords import locations def mask_percent_threshold(mat, thresh): minv = np.min(mat) maxv = np.max(mat) val = (maxv-minv) * thresh/100.0 return mat > val def mask_threshold(mat, thresh, func=lambda a,b: a>b): return mat > thresh def mask_num_std(mat, n, func=lambda a,b: a>...
bfd2407bdaa7766ea2dd5388b77868177df1800c9cbeede0dd20e689e2f80cee
Python
1,805
60
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["sparse_spec"] = dict( type="ParallelSpatiallySparse", sparse_specs=[ dict(type="SpatiallySparseAcrossChannels"), dict(type="SpatiallySparseAcros...
e3710a7ad3d6466e926cd2557bdc07be89c7df27fc88f731cd9ce7bca8917aac
Python
1,805
61
#!/bin/python3 import torch import numpy as np import matplotlib.pyplot as plt from torch.utils.data import DataLoader from torch import nn from torch import optim from NNucleate.dataset import GNNTrajectory from NNucleate.models import initialise_weights, GNNCV from NNucleate.training import evaluate_model_gnn, early...