sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
9100f53d264381b7e4146f79b6d563237276a84c5a01849c236d6f58bd1e11bb | Python | 2,798 | 77 | """Smoke tests for native delayed delivery queue binding.
Verifies queue bindings are created correctly for native delayed delivery,
including when some queues in task_queues fail to bind.
See https://github.com/celery/celery/issues/9960
"""
from __future__ import annotations
import pytest
import requests
from pytes... |
e0cf4ba35eae91dc21aa86b851c4924a9b678e26bd7491772940feeec6bd41f2 | Python | 2,798 | 76 | import numpy as np
import math
import re
# read system configuration and energy/force
def Read_data(folderlist,Prop_list,start_table=None):
# to generate the regular expression for various properties
pattern=[]
for prop in Prop_list:
if prop!="Force":
pattern.append(re.compile(r"(?<={}=... |
8dfe898c4fb7d5d533543e2333faa01cac95758b80ddd6c76e162362021d2946 | Python | 2,799 | 95 | 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,
construct_connectivity_matrix,
simulate_to... |
a1bc831c51462f168b5c289badd39097dc5c14fa6d67000913ac3d307b9dee8e | Python | 2,799 | 71 | import numpy as np
import pandas as pd
import pytest
from larvaworld.lib import reg, util
from larvaworld.lib.process.calibration import comp_segmentation, fit_metric_definition
def _make_stride_variability_row(
point_idx: int = 2, use_component: bool = True
) -> pd.DataFrame:
"""Create a minimal stride vari... |
3388e4fd1a334ec56cc707f8298d241a12138d2426ca37e053e12b604cba7664 | Python | 2,800 | 81 | """Runnable save refuses intervention-replaced captures (deephunt F1).
An intervened capture's archived provenance (activations, taken path) reflects
the REPLACED computation, but the sparse runnable descriptor records the
original callables, so a replay would silently recompute the UN-intervened
function. The produce... |
40f418321668a2c9fea10e1da0fbfc7a937d7e65fc6ac873ebf5b86b00fe79c8 | Python | 2,800 | 94 | import numpy as np
from gym import utils
from gym.envs.mujoco import MuJocoPyEnv
from gym.spaces import Box
def mass_center(model, sim):
mass = np.expand_dims(model.body_mass, 1)
xpos = sim.data.xipos
return (np.sum(mass * xpos, 0) / np.sum(mass))[0]
class HumanoidEnv(MuJocoPyEnv, utils.EzPickle):
... |
551b413455a27cbd664b86dba9f0e9142130dc08c4901cca20cd6068e5558b90 | Python | 2,800 | 104 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType
import copy as _copy
class Center(_BaseLayoutHierarchyType):
_parent_path_str = "layout.map"
_path... |
68b92054491783f9efa72e44bb6fc854e392d42497eb065e2c103bc1dc8f8502 | Python | 2,800 | 88 | import numpy as np
import torch
import torch.nn as nn
from modular_splicing.models.motif_models.types import motif_model_types
from modular_splicing.utils.construct import construct
class MotifModelMultipleWidths(nn.Module):
motif_model_dict = True
def __init__(
self,
input_size,
cha... |
81a78654cda4493faef7336189d984d4c683b93c5ca03dd15ad80e7c984054f8 | Python | 2,800 | 82 | """Phase 4 regression tests: save/load schema versioning and the 2.33 floor."""
from __future__ import annotations
import pickle
from pathlib import Path
import pytest
import torch
import torchlens as tl
from torchlens._io import MIN_TLSPEC_VERSION, TLSPEC_VERSION, ArtifactVersionBelowFloorError
def _simple_model... |
9aff83b120c585bdc60bba3b9c3b4679aa5567496a2245e9028a9c542dffd0b5 | Python | 2,800 | 77 | from __future__ import print_function
import numpy as np
import mxnet as mx
import gluoncv as gcv
from gluoncv.model_zoo.model_store import pretrained_model_list
from ..unittests.common import try_gpu
@try_gpu(0)
def test_export_model_zoo():
for model in pretrained_model_list():
print('exporting:', model)... |
b7996fdbb26abe139eae230b7963b647048f2ca22270f4d1c633b972a89ce5b5 | Python | 2,801 | 87 | """
mua_spike_extractor.py
Modules for spike timestamp extractions.
"""
import numpy as np
from numpy import absolute, sqrt, mean
from scipy import signal
###################################################################################################
############################################################... |
e22a39b02c01979ad3530e25a2d50696ebd48f7ff8101afe0b0791ced3e9376e | Python | 2,802 | 81 | from .tmux_launcher import Options, TmuxLauncher
class Launcher(TmuxLauncher):
## List of training commands
def commands(self):
opt = Options()
### common options for all training sessions defined in this launcher
opt.set(dataroot="~/datasets/cityscapes/", # specify --dataroot optio... |
e7d88ad5e5770231a12a1c032480a6542874ad49095f76e40a4b0c25efc12c6e | Python | 2,802 | 62 | import numpy as np
import pyaldata as pyal
rng = np.random.default_rng(np.random.SeedSequence(12345))
raster_example = ('Chewie_CO_FF_2016-10-13.p', 'Mihili_CO_VR_2014-03-03.p')
MAX_HISTORY = 3 #int: no of bins to be added as history
BIN_SIZE = .03 # sec
WINDOW_prep = (-.4, .05) # sec
WINDOW_exec = (-.05, .40) # ... |
202a2958d622711c5652c1e45069f11f9b97b5afcc695ae7ee138e024935be2b | Python | 2,803 | 88 | import torch.nn as nn
from modular_splicing.utils.construct import construct
class ProductSparsityPropagation(nn.Module):
"""
Propagate the influences via multiplication, which mantains sparisty.
"""
def forward(self, influence, to_influence):
return influence * to_influence
class ClearInf... |
8305274001b5adfdbadec6db4a088b0c6eb1d7ddf765833e5c4f0a6ea7cd2a09 | Python | 2,803 | 90 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: sphinx
# format_version: '1.1'
# jupytext_version: 1.5.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
"""
.. _exa-colors:
Colors
======
In general, colors... |
7bb1e596ec8fc1ae6570de43a5f56ae67e6b3edf66cb64f6785361b86f19122e | Python | 2,804 | 81 | """Persistence honesty on REAL models (lane A08; realism rule: toy-only
validation disqualifies).
Reuses the R0 roster's config-built, offline, seeded families (a shrunk
GPT2LMHeadModel and a shrunk BERT with registered buffers) to pin the A-IV
fixes where they shipped broken: real HF architectures, not toy Sequential... |
e56566433e228c45b1dc4d8ee022f664750d6cafb0c2e7226535bb38c13685ca | Python | 2,805 | 60 | import os
import argparse
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('true', 'y', 't'):
return True
elif v.lower() in ('false', 'n', 'f'):
return False
else:
raise argparse.ArgumentTypeError("Boolean value expected.")
def get_parser():
p = a... |
2baf19419e5ed30752b9b6f19b1a4bb1c1bafc77648da2f044d916ee8ec3cf88 | Python | 2,807 | 86 | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (leoxiaobin@gmail.com)
# Modified by Bowen Cheng (bcheng9@illinois.edu)
# ------------------------------------------------------------------------------
fro... |
5fe3d4e1fd391536175a4faceb1f19e4370abc79d2c220932b531fd0c01d5d2d | Python | 2,807 | 77 | # 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... |
98309dba9182486924a54476bc8431f67977f768c86801e0280f99f243446605 | Python | 2,807 | 73 | __author__ = 'quentin'
from ethoscope.tracking.cameras import V4L2Camera
from ethoscope.tracking.cameras import MovieVirtualCamera
# Build ROIs from greyscale image
from ethoscope.tracking.roi_builders import SleepDepROIBuilder
from ethoscope.tracking.roi_builders import SleepMonitorWithTargetROIBuilder
# the ro... |
06f29b08ccdaab97a1c796c6eff2cd6443cbcf2eb275ee959c2b95ab09cd5050 | Python | 2,808 | 71 | #!/usr/bin/env python
"""Create a BED file (using gene names) that describes the
gene's longest transcript as defined by SNVBox.
Transcripts with multiple locations are removed.
"""
import pandas as pd
import argparse
def parse_arguments():
d = 'Returns a file with only one tx per gene and fixes tx name issues.'... |
177ceaf95b7023b02079fce0a389dc7982097d54498d9f35e69c51e7d2605237 | Python | 2,808 | 77 | import torch
from pytorch_lightning import LightningModule
from torch import nn
from pl_bolts.models.gans.pix2pix.components import Generator, PatchGAN
def _weights_init(m):
if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):
torch.nn.init.normal_(m.weight, 0.0, 0.02)
if isinstance(m, nn.BatchNorm2d):... |
31d48b722fef1f234ecc8e20196c39cdad96aacc5993cde2592b2a60e5810946 | Python | 2,808 | 93 | # -*- coding: utf-8 -*-
# @Author: gviejo
# @Date: 2022-01-17 15:50:57
# @Last Modified by: gviejo
# @Last Modified time: 2022-04-11 17:46:22
import numpy as np
import pynapple as nap
from matplotlib.pyplot import *
import pynacollada as pyna
data_directory = '/home/guillaume/pynapple/data/A2929-200711'
data = n... |
98e493e34962785a04724b61d9298a8abf5b9d292ec440eac87c94c9a3aa0c40 | Python | 2,809 | 90 | import copy
from typing import Any
import numpy as np
import pandas as pd
from mirp._images.generic_image import GenericImage
from mirp._imagefilters.generic import GenericFilter
from mirp._images.transformed_image import TransformedImage
from mirp.settings.generic import SettingsClass
class ExponentialTransformedI... |
ce1c86020b4530c67bec4060680e40a4a7da8fa3bc9dea9a307eccf73d29cb31 | Python | 2,809 | 88 | # This example requires the following dependencies to be installed:
# pip install lightly
# 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.
import pytorch_lightning as p... |
d2a9dd869985df3295fe858f831cf4cfbbb2ed8ceb77d91764bd70632a489f39 | Python | 2,809 | 71 | from __future__ import division
import unittest
import numpy as np
from wyrm.types import Data
from wyrm.processing import select_classes
from wyrm.processing import swapaxes
class TestSelectClasses(unittest.TestCase):
def setUp(self):
ones = np.ones((10, 5))
channels = ['ca1', 'ca2', 'cb1', '... |
de7d591a8fa0b9826e3dcb842d5eb069054b0f4519ce6402424632186986a6f6 | Python | 2,809 | 102 | import unittest
from numpy import exp, log, mean
from spitfire.time.methods import *
from spitfire.time.nonlinear import *
from spitfire import odesolve
def direct_solve(fun):
def append_iteration_count_of_one_and_converged(x, *args, **kwargs):
output = fun(x, *args, **kwargs)
return output, 1, Tr... |
58c210a440ac78a9c0ab11082a6408c12d5a2fc49326a1d3a75a02f3f7089fb8 | Python | 2,810 | 93 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Nov 29, 2018
@author: Quentin Lutz <qlutz@enst.fr>
@author: Nathan de Lara <nathan.delara@polytechnique.org>
@author: Thomas Bonald <tbonald@enst.fr>
"""
import numpy as np
from scipy import sparse
import pytest
from sknetwork.utils import directed2undirec... |
902199e98ad2e4b6a72adf6e2d1c82c8f793c337b895f70b969ba5511708d7c9 | Python | 2,811 | 90 | import pandas as pd
def splice_tables_on_common_genes(data_txt_file_paths, common_genes_key):
"""
Produces splice tables for all the given data_txt_file_paths, but only for the
genes that appear in the table indexed by common_genes_key.
Parameters
----------
data_txt_file_paths : dict[key... |
05c988ab2e6cf256ea2e9377b2dd85c4e64d76bc9325f09428cf7daca5eed90c | Python | 2,813 | 68 | from typing import List
from uuid import UUID
from carbonserver.api.errors import NotAllowedError, NotAllowedErrorEnum, UserException
from carbonserver.api.infra.repositories.repository_runs import SqlAlchemyRepository
from carbonserver.api.schemas import Run, RunCreate, User
from carbonserver.api.services.auth_contex... |
71a584f1d7853fee89224d61c30abbcf503aa6b7be202bf4739deef0bdda00bd | Python | 2,813 | 69 | """`BrainModule.module_conf` hands out a copy of its per-mode defaults.
The default dict is built once, in `__init__`, and was previously returned and
updated in place, so any argument a caller omitted kept the value the previous
caller had passed. Two consequences were visible in the shipped registry: every
forager i... |
0a856c110b38ebd1de46c6d243ea7358a0674aa5f7254bd7a853b9f315a88333 | Python | 2,814 | 82 | #!/usr/bin/env python
#=========================================================================
#
# Copyright NumFOCUS
#
# 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://... |
cff5da442a96db5983cd14db6ab4175facc5c7ce948c38e1483d587b4f1730e5 | Python | 2,814 | 77 | import numpy as np
from torch.nn import functional as F
from pl_bolts.utils import _PIL_AVAILABLE
from pl_bolts.utils.warnings import warn_missing_pkg
if _PIL_AVAILABLE:
from PIL import Image
else: # pragma: no cover
warn_missing_pkg("PIL", pypi_name="Pillow")
class RandomTranslateWithReflect:
"""Trans... |
8fd2a5067895b577597e1edd11412378bf4cabc676f9fad74fb8ac4ca848b0ce | Python | 2,815 | 74 | """Calibration capture: a hook the dispatch machinery runs before a forward.
The calibration modes (GPTQ, AWQ) observe the inputs of every layer they
quantize while calibration data flows through a block. Rather than
replacing a layer's `call` for the duration, a capture is registered on
the layer and `Operation._disp... |
a107a843be894e66d8d9238892c2ad4b9a607e3c5adc9af12bce23aafca05399 | Python | 2,815 | 84 | import torch
import torch.nn as nn
import numpy as np
from tqdm.auto import tqdm
from typing import Callable, Dict
from ._utils import _model_to_device
class FeatureExtractor(nn.Module):
"""A module to extract the outputs of a layer in a model
TODO: Comment this
"""
def __init__(self, model: nn.Module... |
b4a1210f6c3b04d378a7fe893cbf6f7f5f21610c40b0803a62e80f8d633b6ee1 | Python | 2,815 | 70 | from ovseg.model.SegmentationModelV2 import SegmentationModelV2
from ovseg.preprocessing.SegmentationPreprocessingV2 import SegmentationPreprocessingV2
from ovseg.model.SegmentationEnsembleV2 import SegmentationEnsembleV2
from ovseg.model.model_parameters_segmentation import get_model_params_3d_UNet
from ovseg.utils.io... |
09df911d89adcf67b3ae65dcee8ff06a79846d0d44d9846b1a706fa7f12254b6 | Python | 2,816 | 112 | import attr
from cached_property import cached_property
from permacache import stable_hash
import numpy as np
def run_length_encoding(inarray):
"""
run length encoding. Partial credit to R rle function.
Multi datatype arrays catered for including non Numpy
returns: tuple (runlengths, startpositions, ... |
5102d25f410a2e2b08476dc3374327fd5016009db61a5d3a2872896bb5f65dde | Python | 2,816 | 110 | import os
import sys
import time
from celery import Celery
os.environ.update(
NOSETPS='yes',
USE_FAST_LOCALS='yes',
)
DEFAULT_ITS = 40000
BROKER_TRANSPORT = os.environ.get('BROKER', 'librabbitmq://')
if hasattr(sys, 'pypy_version_info'):
BROKER_TRANSPORT = 'pyamqp://'
app = Celery('bench_worker')
app.... |
025a3b9934bf10647b349c7a2833961dbedeee1ac9975fdd5ba5b14d5e1a69cd | Python | 2,817 | 96 | import os
import platform
import re
import sys
from setuptools import Extension, setup
# Ensure Cython is installed before we even attempt to install Ripser.py
try:
from Cython.Build import cythonize
from Cython.Distutils import build_ext
except ImportError:
print("You don't seem to have Cython installed.... |
c00ad19fca2f9bc047f68077885860d562c270b1ca1098cb58b752836bccc252 | Python | 2,818 | 96 | #!/usr/bin/python
import argparse
import logging
import os
import shutil
import signal
import subprocess
import sys
import tempfile
def stop_err(logger, msg):
logger.critical(msg)
sys.exit(1)
def restore_sigpipe():
"""
Needed to handle samtools view
"""
signal.signal(signal.SIGPIPE, signal.... |
f5b529741ee2502ead4d6d187c8591181064e4855f996fa2adad7a16bb0e3e2c | Python | 2,818 | 90 | """
Mixins for Taggable model managers and serializers.
"""
# from galaxy import exceptions as galaxy_exceptions
import logging
import re
from galaxy import model
from galaxy.managers.context import ProvidesUserContext
from galaxy.model.tag_filter import build_tag_filter
from galaxy.model.tags import GalaxyTagHandle... |
bca3aba4b0386c9e25cff85ff2821aedb26015ca8286ff9ca7700a74164be15e | Python | 2,819 | 79 | import torch
import torch.nn as nn
from torch.autograd import Function
from bioseq2seq.modules.sparse_activations import _threshold_and_support
from bioseq2seq.utils.misc import aeq
class SparsemaxLossFunction(Function):
@staticmethod
def forward(ctx, input, target):
"""
input (FloatTensor): ... |
d56dfe9db2e2e6b8447fb5ff7a4b67861efc76c1c5a6b73478923526679e910f | Python | 2,819 | 78 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn import manifold
import seaborn as sns
def get_axis(axarr, H, W, i, j):
H, W = H - 1, W - 1
if not (H or W):
ax = axarr
elif not (H and W):
ax = axarr[max(i, j)]
else:
ax = axarr... |
f26f033b305c6871240b964fce247bc03f2d3145d00f388134754c467ce49dd8 | Python | 2,819 | 123 | import math
from fractions import Fraction
import hypothesis.strategies as st
import pandas as pd
import polars as pl
import pytest
import seqpro as sp
from hypothesis import given
from pytest_cases import parametrize_with_cases
def case_bed_even():
return pl.DataFrame(
{
"chrom": ["chr1"],
... |
0f4e1be77e951ae52ec80f10838317e714aa8e64feac86368067af0dce4e954b | Python | 2,820 | 76 | """A synthetic Visium HD sample for the CCI acceptance test.
8 µm bins on a square grid, with sparse log-normalised expression with ~1.2%
non-zero values (about what 8 µm bins have), every ligand and receptor gene of
connectomeDB2020_lit, and cell type proportions. The same arguments always give
the same sample, on an... |
3bb498253c4587c6c502f4339ee1d6170ab83f4a6ee815364a5cfc1e977c2310 | Python | 2,820 | 97 | 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,
construct_connectivity_matrix,
simulate_to... |
854fe01077feee9b24d7bd1a1b2ccdcc89c826ca1c2fd290fe1ebb14267774f0 | Python | 2,820 | 73 | import numpy as np
import pandas as pd
import nibabel as nib
import os
from skimage.restoration import inpaint
import scipy
import skimage
from scipy.ndimage import binary_dilation
#todo:blurring should be done before the preprocesing step
path = 'data/bch_long_pre_test/raw/'
save_to = 'data/bch_long_pre_test/rand_n... |
9a6b4b15bd149c5c96da4d7ec854fa9c4a8ba3f38de9b13c5beb7dccc4bc3e39 | Python | 2,820 | 53 | #!/usr/bin/env python3
"""Пилотная проверка подмены twin (граница провала 3 части 1 черновика A2):
распределение входа 8 у twin против собственной энергии агентов, лаг-1
автокорреляция входа у self / twin / shuffled / constant. Seed'ы 101-103,
2000 тиков после 600 прогрева. Не подтверждающие данные."""
import sys, os, ... |
df7d4cb990761b611ad1bd66a1a9f4cc4f752d064766ebd0988f89bc65204221 | Python | 2,820 | 67 | from prodict import Prodict
from sklearn.metrics import mean_squared_error, r2_score
import numpy as np
import pandas as pd
import random
import sys
import utils
sys.path.append("src")
def perform_bootstrap(cfg: Prodict) -> None:
"""Generates bootstrapped performance metrics between a series of predictions and ... |
75d03f98a87c2ce087b82a45f7ec3bea414239c15894527ee230a08b58024ed7 | Python | 2,821 | 100 | """Test functions for specparam.sim.sim"""
import numpy as np
from numpy import array_equal
from specparam.tests.tdata import default_group_params
from specparam.sim.sim import *
###################################################################################################
#####################################... |
c3f7505f5f6ef2505605b06eb754137597f5f74a0807dd85321e2c23ee4b15d4 | Python | 2,821 | 101 | """Metric object."""
import numpy as np
from specparam.reports.strings import gen_metric_str
###################################################################################################
###################################################################################################
class Metric():
"""... |
0fecfcc76d01fb690dd27662d09363347db79445770deea0b8c2942e993efa44 | Python | 2,822 | 88 | #
# Copyright (c) Lightly AG and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from typing import Any, Callable, Dict, List, Union
import torch
from PIL.Image import Image
from torch import Tensor
from lig... |
627449277e6bd6c306f19c300641d57b2b9193e110379c42ab455ce1d1a990fb | Python | 2,822 | 84 | # 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... |
a8a55cfa5aae201411e0c5ff0e19dae3974979965d8dd610a02d10441780438e | Python | 2,822 | 83 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright The NiPreps Developers <nipreps@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obta... |
f77ad51876e1efd3e274d0a9b4a33d3dcaf7410e2d9a52bb8e2b0910cd2ffdf5 | Python | 2,824 | 107 | """
====================================================================
One-way Manova with time
====================================================================
One-way Manova to compare Left vs Right in time.
"""
from time import time
from mne import Epochs, pick_types, events_from_annotations
from mne.datase... |
17996c5f88f67513be3660c098d4ec8a86c1747b6410894a121b48e54383035f | Python | 2,826 | 90 | import cv2
import numpy as np
import tensorflow as tf
class Saliency:
def __init__(self, parameters):
'''
Initialize the model
'''
self.model = tf.saved_model.load("./saliency_model")
self.model = self.model.signatures["serving_default"]
self.input_tensor = tf.ones((... |
3ee02e4286d209e9c15755144f413fc8db5e9ea01c391f22605f52f41f5aa9c3 | Python | 2,826 | 95 | from matplotlib import pyplot as plt
from PIL import Image
import pandas as pd
import matplotlib
import numpy as np
from typing import Optional, Union, Mapping # Special
from typing import Sequence, Iterable # ABCs
from typing import Tuple # Classes
from anndata import AnnData
import warnings
from stlearn.plottin... |
85e37a55a4e0845de2d909205fe8c37c951e132fc90fa26aec0993c2a59aae1f | Python | 2,826 | 106 | ### Aimed at translation of fastICA (from Octave version)
### So far, not really used anywhere in the rest of the code
import numpy as np
from numpy import dot,argsort,diag,where,dstack,zeros, sqrt,float,real
from numpy import linalg
#from numpy import *
from numpy.linalg import eigh, inv
from numpy.random import rand... |
a77a8db00dda1edcb0dfcf8cbfa07c2e7cfab1d7e27f057721753e845f8ef162 | Python | 2,826 | 114 | # The rest of the methods in this module are specific functions for computing
# atom and bond features. New ones can be easily added though, and these are
# passed directly to the Preprocessor class.
def get_ring_size(obj, max_size=12):
if not obj.IsInRing():
return 0
else:
for i in range(max_... |
fcce80c5ab5e93eb579bfe0ea747c1b7d9ce96b796f9aea5207d5b7f732fe262 | Python | 2,826 | 88 | from options.video_options import VideoOptions
from data import create_dataset
from models import create_model
from itertools import islice
from util import util
import numpy as np
import moviepy.editor
import os
import torch
def get_random_z(opt):
z_samples = np.random.normal(0, 1, (opt.n_samples + 1, opt.nz))
... |
7d8357e8d068135aa18fd660bdb59cf404b3216777f49cc7ba9fb59f4361b4b4 | Python | 2,827 | 75 | from tqdm import tqdm
import unittest
import numpy as np
import mxnet as mx
from mxnet.test_utils import assert_almost_equal
from mxnet.gluon.data.vision import transforms
import gluoncv
from gluoncv.utils.metrics.segmentation import *
from gluoncv.data import ADE20KSegmentation
from .common import try_gpu, with_cpu
... |
3e958ebc4b0e57dc7c91a0c94c304bad644cab37dfc593afb304ae09440534b0 | Python | 2,828 | 82 | import torch.nn as nn
from modular_splicing.models.modules.sparsity_enforcer.sparsity_enforcer import (
sparsity_enforcer_types,
)
from modular_splicing.models.motif_models.types import motif_model_types
from modular_splicing.utils.construct import construct
class AdjustedMotifModel(nn.Module):
"""
Adjus... |
7705f21fa51f69d0bfc098aa7f3d3994110f6da396126db8045aebfb5e6e4e02 | Python | 2,828 | 104 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType
import copy as _copy
class Subtitle(_BaseLayoutHierarchyType):
_parent_path_str = "layout.title"
_... |
789452d1dcea4ccc567da565ee8095a4697d2c5d4881fb8678718ce486486f1a | Python | 2,828 | 90 | from sklearn.cluster import KMeans
from anndata import AnnData
from typing import Optional, Union
import pandas as pd
import numpy as np
from natsort import natsorted
def kmeans(
adata: AnnData,
n_clusters: int = 20,
use_data: str = "X_pca",
init: str = "k-means++",
n_init: int = 10,
max_iter:... |
a406e73f2b16dd9ee5e68e36f4728ea77f63c016bc0ec645b40b9aedc567c3d8 | Python | 2,828 | 97 | from pathlib import Path
from typing import Any, Dict
import pandas as pd
import pytest
from dash import dash_table as dt
from codecarbon.input import DataSource
from codecarbon.viz import data
@pytest.fixture
def emissions_data() -> pd.DataFrame:
tests_path = Path(__file__).parent
return pd.read_csv(tests_... |
bb6f142d72efdc5fc5fe6453f053e4c2c7cca7cc07c6e50b031af254ba24b482 | Python | 2,828 | 91 | """
This module provides an alternative interface for instantiating a linear learning model.
"""
from functools import lru_cache
from pathlib import Path
from typing import Literal
import numpy as np
import hobj.learning_models.linear_learning_model.update_rules as update_rules
from hobj.learning_models import Linea... |
b3a7c92e0ae03df5bc96468711dddc90a84478ebdea120ed7cdba36d8de6082d | Python | 2,829 | 83 | # Written by Seonwoo Min, Seoul National University (mswzeus@gmail.com)
# Some parts of the code were referenced from or inspired by below
# - Tristan Bepler's code (https://github.com/tbepler/protein-sequence-embedding-iclr2019)
""" FASTA file loading functions """
import torch
def load_fasta(cfg, idx, encoder, sa... |
c8baeaab6caf68ff34b6c2de5b164e6801099cc4540d163082242bf5f5dbb06b | Python | 2,829 | 87 | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future__ import d... |
d8563a8b9e51449120534cc2f887d5335e2f5eecd73c7336b21b086b2fb313d7 | Python | 2,829 | 90 | """Example of bulk task producing with eventlet.
This module shows how to submit many tasks concurrently from a single
process without opening a new broker connection for every call to
``apply_async``.
``ProducerPool`` keeps a pool of eventlet greenlets ("producers"),
each of which acquires its own producer/connectio... |
414b7d558530f6a4060dc477024e959e00b37cb0261b1f6e0f90f181cac583cb | Python | 2,830 | 78 | from __future__ import annotations
from typing import Optional, TypeVar
import pandas as pd
def generate_channelwise_ping(
dataframe: pd.DataFrame, required_fields: list[str], optional_fields: Optional[list[str]] = None
):
"""
Transform the dataframe to a generic channelwise ping.
:param required_f... |
6b54ab7020fde6b1db0e8f2ef4783051f195a6d4943098f9a668189f8e1be146 | Python | 2,830 | 99 | import argparse
def get_coordinates(lines):
version = lines[3][34:39]
molecule = []
if version == "V2000":
natom = int(lines[3][:3].strip())
for i in range(1, natom + 1):
temp = []
j = 3 + i
x = float(lines[j][:10].strip())
y = float(lines[j]... |
7060c3904366e8708dcb5421d2e3af336c0ced797304873a32a005fec8dbf673 | Python | 2,830 | 65 | import deeplabcut as dlc
import os
project_name = "DLC_thermography"
username = "jlanden"
#list_videos = ['video1_path', 'video2_path', 'video3_path']
model_num = 1
config_path = 'F:\DLC_thermography-JLanden-2024-07-09\config.yaml'
video_directory = r'F:\DLC_thermography-JLanden-2024-07-09\videos' # Replace with the ... |
8e2b862153c883398acc2ba1644fe525aaab8d2bf2e607d0893f58de6be32660 | Python | 2,830 | 86 | from __future__ import print_function, division, absolute_import
import os
from os.path import expanduser
import hickle as hkl
import torch
import torch.nn.functional as F
from torch.autograd import Variable
__all__ = ['wideresnet50']
model_urls = {
'wideresnet152': 'https://s3.amazonaws.com/pytorch/h5models/wide... |
0a0ebca703d37e1fe6ceb973572b69d7c6a6c38f0fc6c183b89dd81a4647380c | Python | 2,831 | 66 | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/proteolytic_cleavage.ipynb (unless otherwise specified).
__all__ = ['protease_dict', 'get_cleavage_sites']
# Cell
protease_dict = dict()
protease_dict["arg-c"] = "R"
protease_dict["asp-n"] = "\w(?=D)"
protease_dict["bnps-skatole"] = "W"
protease_dict["caspase 1"] = "(?... |
0bf7d4556b4584862c5d905aee4f96adc76a2dfed492a1c90bd7ef655df4cac2 | Python | 2,831 | 97 | """
Tests to make sure the feature attribution interpretation methods work
"""
import torch
import eugene as eu
import numpy as np
import pandas as pd
import pytest
from pathlib import Path
HERE = Path(__file__).parent
@pytest.fixture
def sdata():
"""
sdata
"""
sdata = eu.datasets.random1000()
e... |
3bbd2fab4040bfeacb31cf2dd013ea0294f0a02b2f97ad6aa50f9f559fc8e49b | Python | 2,831 | 86 | from typing import Tuple
import numpy as np
def malinowski_criteria(eigenvalues: np.ndarray, C_tilde_shape: Tuple[int, int]) -> int:
"""
Determines the optimal number of principal components using the Malinowski method.
Args:
eigenvalues (np.ndarray): The sorted eigenvalues of the noise covarian... |
80bc99f1dc799e074b083e8c2b964fdcd6c4ee42d7483fcf47f939ec1351340b | Python | 2,831 | 86 | import os
import shutil
import gym
from gym.wrappers import capped_cubic_video_schedule
def test_record_video_using_default_trigger():
env = gym.make(
"CartPole-v1", render_mode="rgb_array_list", disable_env_checker=True
)
env = gym.wrappers.RecordVideo(env, "videos")
env.reset()
for _ in... |
97e6a6486e2fdf1c8d5797338d51da8f22ed27caa0fd71f51251be403bc3c0a1 | Python | 2,832 | 86 | import torch
from tqdm import tqdm
import numpy as np
from interpretability.utils import (
set_hook_to_get_repr_all_layers,
load_sequences,
load_model_and_vocab,
)
import pickle as pkl
from sklearn.decomposition import NMF
import inspect
from interpretability.create_NMF_projector import get_all_tokens_repr
... |
d0a31f88544e24690355b63fd0e7dde09b936dcec8d25d3962ea2ac8e4c46f04 | Python | 2,832 | 79 | from __future__ import annotations
import time
import pytest
from pytest_celery import CeleryTestSetup
from tenacity import retry, stop_after_delay, wait_fixed
from celery import beat
@pytest.fixture
def beat_pidbox(celery_setup: CeleryTestSetup) -> beat.BeatPidbox:
"""A beat control node bound to the suite's ... |
25d3e0172891466a2894b4d2a296746366ede8d46433a64b403c5d2fddde2e5c | Python | 2,833 | 95 | import attr
import numpy as np
import matplotlib.pyplot as plt
def plot_base_importance(
x,
*importance,
labels=[],
chunk_size=81,
features={},
style={},
headroom=0,
yticks=None,
yticksnames=None,
dpi=400,
feature_text_size=8,
width=14,
):
importance = np.array(imp... |
6c542dbde7e5af66c94947e017e18e5f4efb640392d7af3dc9bcd9a546ccad8c | Python | 2,833 | 95 | import scipy as sp
from scipy import interpolate
'''
Originally written by Nicolo Fusi https://github.com/nfusi/qvalue/pull/3
Modified by Alexis Boukouvalas
'''
def estimate(pv, m=None, verbose=False, lowmem=False, pi0=None):
"""
Estimates q-values from p-values
Args
=====
m: number of t... |
8aa760024234271c968d3f62ff1346a98b55aec80ce184f19ff505fbd579f546 | Python | 2,833 | 110 | """Shared fixtures for train-mode regression tests."""
from __future__ import annotations
import pytest
import torch
from torch import nn
class TwoLayerMlp(nn.Module):
"""Small MLP with a single hidden layer."""
def __init__(self) -> None:
"""Initialize the layers."""
super().__init__()
... |
42f546e8b8c594e98e895530df934f204255b324a6826dc6f493a090cea52999 | Python | 2,834 | 99 | import matplotlib
from anndata import AnnData
from bokeh.io import output_notebook
from bokeh.plotting import show
from stlearn.pl._docs import doc_gene_plot, doc_spatial_base_plot
from stlearn.pl.classes import GenePlot
from stlearn.pl.classes_bokeh import BokehGenePlot
from stlearn.utils import _docs_params
@_docs... |
4c1f1c9b7e9f839b378c72f200b394038108f86a1239d879d4d237c04b00c5a2 | Python | 2,834 | 87 | from typing import TYPE_CHECKING
from sqlalchemy import select
from sqlalchemy.exc import (
MultipleResultsFound,
NoResultFound,
)
from galaxy.exceptions import (
InconsistentDatabase,
InternalServerError,
RequestParameterInvalidException,
)
from galaxy.managers import base
from galaxy.managers.co... |
85e32f98edf8e3d2aa9c3882e89c1cb5f5a64a8b8421efacedf88dafea43450b | Python | 2,834 | 66 | import os
import numpy as np
from .protein_split import ProteinSplit
from sklearn.model_selection import train_test_split
from data import PDBbindMetadataProcessor
from data.chembl_connector import ChEMBLConnector
class KinasesCMGCSplit(ProteinSplit):
def __init__(self,
split_type: str = 'k... |
9ba148d250165af7ba7a4699a63183f28e639b502fe3eea8b6ee25b4bc3bcd04 | Python | 2,834 | 89 | """Contract tests for the trace-free RenderIR renderer boundary."""
from pathlib import Path
import pytest
from torchlens.visualization import _render_nodes
from torchlens.visualization.render_ir import RenderIR, RenderIRDotStatement, RenderIRNode
from torchlens.visualization.renderers import (
GraphvizRenderer,... |
139e260df31bec9bfccff26c8a727c8a2e6e4fdfe1b39b946c20ff11ba963855 | Python | 2,835 | 81 | import torch
import torch.nn as nn
def smoothl1_loss(error, delta=1.0):
"""Smooth L1 loss.
x = error = pred - gt or dist(pred,gt)
0.5 * |x|^2 if |x|<=d
|x| - 0.5 * d if |x|>d
"""
diff = torch.abs(error)
loss = torch.where(diff < delta, 0.5 * diff * diff / delt... |
31e192b95a947c5a3f13a2caca58b95e5a4cabb8b101f354a1f4db0167542494 | Python | 2,835 | 51 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: sphinx
# format_version: '1.1'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
"""
.. _exa-data_split:
.. currentmodule:: eelbrain
... |
46222ed3a62bfb3b16162477384e40f7b19f0b0e7cad9a33a29337dd06e4bb3d | Python | 2,835 | 86 | import numpy as np
from numpy.testing import assert_array_almost_equal
import pytest
from pytest import approx
from pyriemann.geometry.distance import distance
from pyriemann.optimization.grassmann import (
_get_rotation_manifold,
_get_rotation_tangentspace,
_grad,
_loss,
)
pytestmark = pytest.mark.n... |
f1dc0dbaa5056629ee025d2b001158ac7fac3eb2d78e38860c1c17636040c658 | Python | 2,835 | 82 | from collections import defaultdict
from matplotlib import pyplot as plt
from permacache import permacache, stable_hash
import pandas as pd
from modular_splicing.gtex_data.annotation.compute_optimal_sequence import (
compute_optimal_sequences_all,
)
bin_boundaries = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55,... |
076f52997706b051a0df28ba81ada7972d60ea31bf336caaf7b521c02e77916d | Python | 2,837 | 120 | def get_file_paths(control_file):
"""
:param control_file:
:return control_dic:
parses control_file into a dictionary providing the code access to all the paths it needs to run
control file format is @\tkey=path
key is used as a dictionary key and the path is assigned to that key... |
86df2ebaa3d18628c1a08e3e4839535b2ae5a57569f963bf037c0b67ccab7bae | Python | 2,837 | 96 | import pytest
import torch
from PIL import Image as PILImageModule
from PIL.Image import Image as PILImage
from torch.testing import assert_close
from lightly.utils.dependency import torchvision_transforms_v2_available
if not torchvision_transforms_v2_available():
pytest.skip("torchvision.transforms.v2 not availa... |
34d7c16506a36c5f9f3e8c22e4c5c8d3a40376c468354e3745d3e6043738ce2a | Python | 2,838 | 94 | """PaddleDetection DETR: convolutional backbone plus Transformer object queries.
Carion et al. (ECCV 2020), "End-to-End Object Detection with Transformers".
DETR uses image features encoded by a Transformer and a fixed set of learned
object queries decoded into class labels and normalized boxes.
"""
from __future__ i... |
a20d7343dd598a4a7607d7aa8584f3d8bef7d8edf8d8e9bcd185e49ccb6fb697 | Python | 2,838 | 62 | """Блок 0.3: почему пилот 4×5×15000 не укладывался в 18 минут на 8 ядрах.
Гипотеза: в каком-то условии популяция разрастается к max_pop=2000 и тянет
скорость вниз (forward-pass, плотность, поиск соседа — всё растёт с числом
агентов). Проверяем траектории численности и скорость как функцию популяции.
"""
import json
im... |
d34f95c003f058e14fec343d0dc21869307a81e741ab3bc60ce1b0b61eba3760 | Python | 2,838 | 70 | """Tests for spiketools.utils.trials"""
import numpy as np
from spiketools.utils.trials import *
###################################################################################################
###################################################################################################
def test_split_tria... |
34de79dba70e316b037be348fb5303e1e03b46e8b021760cc77e35bb41821418 | Python | 2,839 | 86 | from __future__ import annotations
from pathlib import Path
import panel as pn
import pytest
from larvaworld.lib import reg, util
from larvaworld.lib.reg import config as reg_config
from larvaworld.lib.reg.generators import EnvConf
from larvaworld.portal.config_widgets.conftype_actions import (
ConftypeActionsCo... |
a444cc0fcb9a5df0036619b355a1f8608197e7b4b6bef8735489ce35a0300543 | Python | 2,840 | 92 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on November 12 2019
@author: Quentin Lutz <qlutz@enst.fr>
"""
from math import log
from typing import Union, Optional
import numpy as np
from scipy import sparse
from sknetwork.path.shortest_path import get_distances
from sknetwork.ranking.base import BaseRan... |
d346cf9ffe8d7ab88005d35e4ebf976956f192f8452659a2eaf589f01cdda8fb | Python | 2,841 | 76 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""bn helper."""
import itertools
import torch
@torch.no_grad()
def compute_and_update_bn_stats(model, data_loader, num_batches=200):
"""
Compute and update the batch norm stats to make it more precise. During
... |
f1037e30d196083db4ecb8959458bcad76a17bb942221b0e5679a35c320c96cb | Python | 2,841 | 82 | #!/usr/bin/env python
#=========================================================================
#
# Copyright NumFOCUS
#
# 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://... |
f43dcb1a97ae3e596fb016bfe637940bc9ea809460334cc96c7c4f6dfc988570 | Python | 2,841 | 95 | import torch
import torch.nn as nn
from modular_splicing.utils.construct import construct
from modular_splicing.models.modules.sparsity_enforcer.sparsity_enforcer import (
sparsity_enforcer_types,
)
class MultiMotifParallelSparsityEnforcer(nn.Module):
def __init__(self, *, sparsity_enforcer_spec, count, **... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.