sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
65874818eea8e5f23cdc946de72b607ac53c19c22a4ff5ff46175ac872eb3da5 | Python | 347 | 15 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import annotations
import pytest
@pytest.fixture(scope="session")
def max_num_elements(dummy_element_refs):
return l... |
972d69470cf32bf328fc08392e8a716f07c92c60a75db0aef05720d792a0bdf7 | Python | 347 | 11 | from ray.data._internal.execution.callbacks.insert_issue_detectors import (
IssueDetectionExecutionCallback,
)
from ray.data._internal.execution.callbacks.resource_allocator_prometheus_callback import (
ResourceAllocatorPrometheusCallback,
)
__all__ = [
"IssueDetectionExecutionCallback",
"ResourceAlloc... |
d7da4c43407f361ec28a87c1047b34e06b8e25467904e25a3de8adefef5b7e0e | Python | 347 | 10 | from telemanom.detector import Detector
import argparse
parser = argparse.ArgumentParser(description='Parse path to anomaly labels if provided.')
parser.add_argument('-l', '--labels_path', default=None, required=False)
args = parser.parse_args()
if __name__ == '__main__':
detector = Detector(labels_path=args.labe... |
5a872d70236317779cb51ce0d40cec747054e6e0cba7a11421ed4075aabb004a | Python | 348 | 14 | import torch
from pfrl.nn.lmbda import Lambda
def concat_obs_and_action(obs_and_action):
"""Concat observation and action to feed the critic."""
assert len(obs_and_action) == 2
return torch.cat(obs_and_action, dim=-1)
class ConcatObsAndAction(Lambda):
def __init__(self):
return super().__in... |
69233204baaeb6428c277a3462cbeafcefc4569607a9fb9ebfd77e60a35a7a32 | Python | 348 | 15 | #!/usr/bin/python
# -----------------
# Load datasets:
# Updated: 06/28/21
# -----------------
from pathlib import Path
import pandas as pd
HERE = Path(__file__).parent
def snap_colors():
"""Load a list of 88 categorical colors for plotting."""
filename = HERE / "snap_colors.tsv"
return pd.read_csv(filen... |
40a6010e9c21d2a27097ae67dbff7ed7d0cc7674d2c2a9465592be27c32fd92f | Python | 349 | 8 | from moabb.datasets import Weibo2014
from pathlib import Path
CSP_RESEARCH_OUT_PATH = Path("..") / "results"
DATASET = Weibo2014
DATASET_NAME = ("Yi2014" if DATASET.__name__ == "Weibo2014" else DATASET.__name__).lower()
SELECTED_CHANNELS = ["Fz", "FC3", "FC1", "FCz", "FC2", "FC4", "C3", "C1", "Cz", "C2", "C4", "CP3", ... |
4c22c98ae944ffb2fe782d571c2a5e2c381a80ef3dfb3005f4bb2fc53ae4ca6d | Python | 349 | 12 | import sys
from mozaik.meta_workflow.parameter_search import parameter_search_run_script_distributed_slurm_UK
assert len(sys.argv) == 2
directory = sys.argv[1]
parameter_search_run_script_distributed_slurm_UK(
"SelfSustainedPushPull",
directory,
'run_analysis.py',
16,
"/home/antolikjan/virt_env/moz... |
1917809225f36f1b0ba6440d469d6f9bd5ddbd20ff160209647d54429a80022a | Python | 350 | 22 | """
A dummy ray driver script that executes in subprocess. Prints runtime_env
from ray's runtime context for job submission API testing.
"""
import ray
def run():
ray.init()
@ray.remote
def foo():
return "bar"
ray.get(foo.remote())
print(ray.get_runtime_context().runtime_env)
if __na... |
491ddcc1a37f6cbb72e361007ed36163a12d6b8003ba3360ebaec2431f4d8fe3 | Python | 350 | 16 | from typing import Any, Union
import torch
def check_scalar(x: Union[Any, float, int]) -> bool:
"""
Provide interface to check for scalars
Args:
x: object to check for scalar
Returns:
bool" True if input is scalar
"""
return isinstance(x, (int, float)) or (isinstance(x, torc... |
995a44d3cf8133096831e0681175416907402bcc0e444c83e320400375d8cfbe | Python | 350 | 12 | from absplice import SpliceOutlier, SpliceOutlierDataloader
import snakemake
dl = SpliceOutlierDataloader(
snakemake.input["fasta"],
snakemake.input["vcf"],
splicemap5=list(snakemake.input["splicemap_5"]),
splicemap3=list(snakemake.input["splicemap_3"]),
)
model = SpliceOutlier()
model.predict_save(dl... |
5ad24da670cd1747aadb9e1142fc86d85b3a911984e7f6d63c807a279996bf18 | Python | 351 | 12 | import logging
from mol2ccs.constants import TENSORBOARD_LOG_DIR
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.info("mol2ccs package is being imported.")
# create tensorboard log directory
TENSORBOARD_LOG_DIR.mkdir(exist_ok=True, parents=True)
logger.info(f"Tensorboard log directory: {TE... |
6e67f364ef0ec88fb2924c774e8fd35908a73808a5dcf0b5d98abbc1b7de21bb | Python | 351 | 12 | __author__ = "Marko van Treeck"
__copyright__ = "Copyright 2022, Kather Lab"
__license__ = "MIT"
__version__ = "0.3.0"
__maintainer__ = "Marko van Treeck"
__email__ = "mvantreeck@ukaachen.de"
__changelog__ = {
"0.2.0": "Add extractor information to tiles.",
"0.3.0": "Factor out imagenet extractor.",
"0.4.0... |
d224de81104a084afac1dea18e3ba44f19edd972905f578225fa009ed3acec79 | Python | 352 | 7 | import numpy as np
def filter_genes(counts_mat, gene_labels, umi_threshold=500, exclude_prefix=['MT-', 'RPL', 'RPS']):
idx_kept=np.where(np.sum(counts_mat,0) > umi_threshold)[0]
idx_kept=np.array( [i for i in idx_kept if gene_labels[i][:3] not in exclude_prefix] )
gene_labels_idx=gene_labels[idx_kept]
... |
27957a0112e8d6005b29b4ac83c003cf4ba01c8ce52548d14011165205293a9b | Python | 353 | 12 | from ipywidgets import widgets
from data_profiling.report.presentation.core import Variable
class WidgetVariable(Variable):
def render(self) -> widgets.VBox:
items = [self.content["top"].render()]
if self.content["bottom"] is not None:
items.append(self.content["bottom"].render())
... |
76afc15aea740baa76795cd3cc8d454325d82ad20daaea7a4dc794c0ce34c095 | Python | 353 | 18 | #!/usr/bin/env python
# import
from __future__ import print_function
## batteries
import os
import sys
import pytest
# data dir
test_dir = os.path.join(os.path.dirname(__file__))
data_dir = os.path.join(test_dir, 'data')
# tests
def test_help(script_runner):
ret = script_runner.run('lineage2taxid.py', '-h')
... |
6e0351616944ed79ae798a62b5949326eb3d24a82b94ab9b0b614963cb5c6458 | Python | 354 | 14 | #!/usr/bin/env python
import numpy.testing as npt
import numpy as np
from caiman.source_extraction import cnmf as cnmf
def test_axcov():
data = np.random.randn(1000)
maxlag = 5
C = cnmf.pre_processing.axcov(data, maxlag)
print(C)
npt.assert_allclose(C, np.concatenate((np.zeros(maxlag), np.array(... |
ffa1b4f5493b2568110fe4fd71d5b29fafeabca627c4791c8af12749de118519 | Python | 354 | 17 | from abc import ABCMeta, abstractmethod
from logging import getLogger
logger = getLogger(__name__)
class Policy(object, metaclass=ABCMeta):
"""Abstract policy."""
@abstractmethod
def __call__(self, state):
"""Evaluate a policy.
Returns:
Distribution of actions
"""
... |
2f81fc4478e278322ba1590beb8a7fdd46b585379a5c842068a45528f34899bc | Python | 355 | 18 | #!/usr/bin/env python
# import
from __future__ import print_function
## batteries
import os
import sys
import pytest
# data dir
test_dir = os.path.join(os.path.dirname(__file__))
data_dir = os.path.join(test_dir, 'data')
# tests
def test_help(script_runner):
ret = script_runner.run('gtdb_to_diamond.py', '-h')
... |
42967ff20fa933728b1f66a2f518bc94a6f7219cc543086f3177bf16ebe3a904 | Python | 355 | 12 | from pathlib import Path
from siapy.entities import SpectralImageSet
# Load multiple images
header_paths = list(Path("data_dir").glob("*.hdr"))
image_paths = list(Path("data_dir").glob("*.img"))
image_set = SpectralImageSet.spy_open(header_paths=header_paths, image_paths=image_paths)
# Iterate over the images
for im... |
4fa6b550a60ba6800cef089eebeae4704339e9cd192213250c0c4d6885f091ee | Python | 355 | 9 | from absplice import SplicingOutlierResult
import snakemake
splicing_result = SplicingOutlierResult(
df_mmsplice=snakemake.input["mmsplice_splicemap"],
df_spliceai=snakemake.input["spliceai"],
)
splicing_result.predict_absplice_dna(extra_info=snakemake.params["extra_info"])
splicing_result._absplice_dna.to_csv... |
8390988b719703415bd53046aaa6cf66e9c7116c0fb751c99566b5589053e18d | Python | 357 | 18 | import cv2
import fire
from imwatermark import WatermarkDecoder
def testit(img_path):
bgr = cv2.imread(img_path)
decoder = WatermarkDecoder('bytes', 136)
watermark = decoder.decode(bgr, 'dwtDct')
try:
dec = watermark.decode('utf-8')
except:
dec = "null"
print(dec)
if __name__... |
59b89b137557c1e65466d1b78e3697cec6a2a0fa326dba289f06e0d8ff552044 | Python | 358 | 16 | import argparse
import torch
from pathlib import Path
from train import SequenceLightningModule
parser = argparse.ArgumentParser()
parser.add_argument("ckpt_path", type=str)
args = parser.parse_args()
ckpt = torch.load(args.ckpt_path, map_location='cuda')
state_dict = ckpt['state_dict']
torch.save(state_dict, Pat... |
e6edbb5cf49bafa6de551f5486070d8254c8ec1fa51cf41b529172f36f015aeb | Python | 358 | 14 | """Research coordination utilities.
This package provides primitives for breaking down research briefs into
subtopics and running specialised agents to gather findings."""
from .agent import ResearchAgent, Finding, SourceCitation
from .supervisor import Supervisor
__all__ = [
"ResearchAgent",
"Finding",
... |
b27912c6c2795fe3e461fe5334d0acdba1df718efdb234229841c7cbc4921704 | Python | 360 | 12 | import subprocess
# script list to run
scripts_to_run = ["update_pyprj_toml.py",
"update_meta_yaml.py",
"create_archive.py",
"run_pypi_build.py",
"run_conda_build.py",
"create_git_tag_version.py"]
for script in scripts_to_run... |
1a56bd73c05a06f7da369215d8b2be554da853f9678f474d99e4bcad8b0c385d | Python | 361 | 12 | # -*- coding: utf-8 -*-
import torch
import numpy as np
def sparse_mx_to_torch_edge_list(sparse_mx):
sparse_mx = sparse_mx.tocoo().astype(np.float32)
edge_list = torch.from_numpy(
np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
return edge_list
def corruption(x, edge_index):
return... |
24b8f66ba592f10de0b93c318a8c221d346ee5e70a3990d9e308ad435718cb73 | Python | 361 | 13 | from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(name='routines',
ext_modules=cythonize(
Extension(
"routines",
sources=["routines.pyx", "lif_transfer_function.cpp"],
extra_compile_args=["-std=c++11"],
extra_link_args=[],... |
67e2a5467fce26ac9dc6b491b59a691b9e9dc9cfdf37a3dc9c2ed4dc1e2e3709 | Python | 361 | 14 | """Minimal CellCharter backend used by omicverse spatial clustering."""
from ._aggr import aggregate_neighbors
from ._autok import ClusterAutoK, plot_autok_stability
from ._gmm import Cluster
from ._graph import remove_long_links
__all__ = [
"aggregate_neighbors",
"Cluster",
"ClusterAutoK",
"plot_auto... |
c6819aa8ef74e64a9d6eb541f6b3718ddc3601b11bb574dc3bb6a4ba40360f83 | Python | 361 | 14 | from typing import Any
from data_profiling.report.presentation.core.item_renderer import ItemRenderer
class HTML(ItemRenderer):
def __init__(self, content: str, **kwargs):
super().__init__("html", {"html": content}, **kwargs)
def __repr__(self) -> str:
return "HTML"
def render(self) -> ... |
7337cf1f563d9af8765b5f17709a83207d8ecb500bda355257c144b523e161a8 | Python | 362 | 11 | """Re-export retrievers from `omicverse.llm.dr`.
Provides a stable import path: `omicverse.llm.domain_research.retrievers`.
"""
from __future__ import annotations
from ...dr.retrievers.web_store import WebRetrieverStore # noqa: F401
from ...dr.retrievers.embed_web import EmbedWebRetriever # noqa: F401
__all__ = [... |
646da7084b95fa5553c58b692be2bac39daf0e480587fcee1c9ced8bb4547de6 | Python | 363 | 9 | import os
import sys
# train RMBG model
os.system('python train_RMBG_model.py --datasets_folder train_RMBG1 \
--n_epochs 2 --GPU 0 --batch_size 1 \
--fmap 32 --lr 0.0001 \
--img_h 128 --img_w 128 --img_s 128 \
... |
e470166c7c899db4733bb2b287726eb4ca7bdcfad8357fbc663bdeee7242041f | Python | 363 | 11 | import unittest
import pfrl
class TestIsReturnCodeZero(unittest.TestCase):
def test(self):
# Assume ls command exists
self.assertTrue(pfrl.utils.is_return_code_zero(["ls"]))
self.assertFalse(pfrl.utils.is_return_code_zero(["ls --nonexistentoption"]))
self.assertFalse(pfrl.utils.is... |
fd2b0fa36dbc9b89a470f6544be68306651d2cd2d592354317a18ff3e144bb6a | Python | 363 | 11 | from ipywidgets import widgets
from data_profiling.report.presentation.core import VariableInfo
from data_profiling.report.presentation.flavours.html import templates
class WidgetVariableInfo(VariableInfo):
def render(self) -> widgets.HTML:
return widgets.HTML(
templates.template("variable_in... |
1d789f074e0c99375e7ab1e7bbe9b1bf4e82f5da671f0e379926e8104add0a99 | Python | 364 | 13 | # flake8: noqa
from ...utils import is_note_seq_available
from .notes_encoder import SpectrogramNotesEncoder
from .continous_encoder import SpectrogramContEncoder
from .pipeline_spectrogram_diffusion import (
SpectrogramContEncoder,
SpectrogramDiffusionPipeline,
T5FilmDecoder,
)
if is_note_seq_available()... |
b9f70cc935a6c1748a315ba8eb1e3010b1f0bb3aed7642cea1abaaf4279223ea | Python | 365 | 17 | import sys
import pytest
from ray._common.network_utils import is_localhost
def test_is_localhost():
assert is_localhost("localhost")
assert is_localhost("127.0.0.1")
assert is_localhost("::1")
assert not is_localhost("8.8.8.8")
assert not is_localhost("2001:db8::1")
if __name__ == "__main__":... |
f0a943c1b5f3c99cd31e1405c175acfbddc6e690152acfe5339b24826de07459 | Python | 365 | 17 | import pandas as pd
import pytest
from data_profiling import ProfileReport
@pytest.mark.parametrize(
"test_data",
[
pd.DataFrame(),
pd.DataFrame(["Jan", 1]).set_index(0),
pd.DataFrame({"A": [], "B": []}),
],
)
def test_empty(test_data):
with pytest.raises(ValueError):
... |
a69abca43bb99266777c3b2c7e620779b53e71dd81152ee7e958d47169fa5ffc | Python | 366 | 17 | import numpy as np
import ivim
# sIVIM protocol
n = 5
f = np.repeat(np.linspace(0.02,0.1,n),n)
D = np.tile(np.linspace(0.6e-3,1.1e-3,n),n)
b,a = ivim.optimize.crlb.sIVIM(D,f,None,200,800)
print('Optimized b-values:')
print(np.round(b))
print()
print('Optimized proportions:')
print(a)
print()
print('Optimized distribu... |
44997af204138d76ea7bea37c9143f1e7ceb15d44906c267d240ca70c306d4df | Python | 367 | 12 | from diffusers.utils.testing_utils import require_onnxruntime
@require_onnxruntime
class OnnxPipelineTesterMixin:
"""
This mixin is designed to be used with unittest.TestCase classes.
It provides a set of common tests for each ONNXRuntime pipeline, e.g. saving and loading the pipeline,
equivalence of ... |
b2303ff104b9ba106a434947cb42791f078680d3f54eac3e74889e524a48c4cf | Python | 368 | 15 | r"""I/O utilities for single-cell datasets."""
from ._formats import read_10x_h5, read_10x_mtx, read_h5ad
from ._read import read
from ._rust import convert_adata_for_rust, convert_to_pandas, wrap_dataframe
__all__ = [
"read",
"read_10x_mtx",
"read_h5ad",
"read_10x_h5",
"convert_to_pandas",
"w... |
53b90215fdc752dba1d73c202ef8f92ef9dd08d57c031d560c692858acd6d978 | Python | 369 | 11 | from .class_names import * # noqa: F401,F403
from .duo import DUODataset
from .rtts import RTTSCocoDataset
from .ruod import RUODDataset
from .urpc import URPCCocoDataset, URPCXMLDataset
from .xml_dataset import XMLDatasetWithMetaFile
__all__ = [
'XMLDatasetWithMetaFile', 'URPCCocoDataset', 'URPCXMLDataset',
... |
324ab1e58ef9441987748512eb649de4822338e18e638c7a36c548c8a405d66e | Python | 370 | 9 | # emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
from .ica_reclassify import ica_reclassify_workflow
from .t2smap import t2smap_workflow
# Overrides submodules with their functions.
from .tedana import tedana_workflow
__all__ = ["tedana_workflo... |
6c5612f177d4fc04048ee24ad68058ef022bed14785f095952dff07851813fc0 | Python | 370 | 18 | """
========
Gaussian
========
:class:`~sinabs.activation.Gaussian` surrogate gradient.
"""
import matplotlib.pyplot as plt
import torch
import sinabs.activation as sina
x = torch.linspace(-2, 4, 500)
plt.plot(x, sina.Gaussian()(v_mem=x, spike_threshold=1.0), label="Gaussian")
plt.xlabel("Neuron membrane potential")... |
7e68fffe64460a5d21b99c857af017fd71f6529fb055eba195673f10e65ec1b3 | Python | 370 | 9 | from .base_models import * # noqa: F401,F403
from .data_preprocessor import * # noqa: F401,F403
from .editor_heads import * # noqa: F401,F403
from .editors import * # noqa: F401,F403
from .layers import * # noqa: F401,F403
from .losses import * # noqa: F401,F403
from .post_processor import add_pixel_pred_to_datas... |
b9024d5c0f92a0a3f2cf9a64f582602696e9bed2428a0b46e65383071f449cc9 | Python | 370 | 20 | from torch.utils.data import Dataset
class HumanPoseEstimationDataset(Dataset):
"""
HumanPoseEstimationDataset class.
Generic class for HPE datasets.
"""
def __init__(self):
pass
def __len__(self):
pass
def __getitem__(self, item):
pass
def evaluate_accuracy... |
627b94f4de364cb25802080f4b27fe641be3556ed86f72f8e52b913fd3490cce | Python | 371 | 11 | #Test augmentation
import numpy as np
from src import augmentation
import torch
def test_train_augmentation():
image = torch.randn(20, 369, 11, 11)
transformer = augmentation.train_augmentation(image_size=11)
transformed_image = transformer(image)
assert transformed_image.shape == image.shape
a... |
3407562ecdf73d4cd9d83459edaf66a887baa357bf0f1e3de3e2c8758fa61229 | Python | 372 | 17 | # -*- coding: utf-8 -*-
"""Top-level package for neuron_morphology."""
import os
from logging.config import fileConfig
version_path = os.path.join(os.path.dirname(__file__), "VERSION.txt")
with open(version_path, "r") as version_file:
__version__ = version_file.read().strip()
fileConfig(os.path.join(
os.p... |
77787103db0d5bac168fa727225d22b9385fcf2c9b7fcb590d061bb8e85b016c | Python | 372 | 14 | from pfrl.functions.bound_by_tanh import bound_by_tanh
from pfrl.nn.lmbda import Lambda
class BoundByTanh(Lambda):
"""Bound a given value into [low, high] by tanh.
Args:
low (numpy.ndarray): lower bound
high (numpy.ndarray): upper bound
"""
def __init__(self, low, high):
supe... |
9a54731655cc68ac575892fa86a1eec1b6a8557754662d91b89d3efd9734749f | Python | 372 | 10 | from .CGRU import CGRU
from .CGRU_v2 import CGRU_v2
from .CGRU_c2h import CGRU_c2h
from .NNShortCut import NNShortCut
from .SimpleShortcut import SimpleShortcut
from .SimpleMemory import SimpleMemory
from .SimpleContext import SimpleContext
from .SimpleTracker import SimpleTracker
from .Vanilla_iSITH import Vanilla_iSI... |
b53005f30ac9bebe3da079779f9b3b4e79b2ffe5c2a7562ad20ea67a6f6b1727 | Python | 372 | 13 | import torch
from torch_pgn.args import TrainArgs
class FPEncoder(torch.nn.Module):
"""Pass-through encoder module for fp datasets."""
def __init__(self, args: TrainArgs):
super(FPEncoder, self).__init__()
self.args = args
self.fp_dim = args.fp_dim
def forward(self, data):
... |
5e7bddff23fb71bd8eae751bdee97648093e783b3ade489efbefc29b938f29d4 | Python | 373 | 14 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""High level inference tools."""
# Convenience imports for easier access to the classes.
from .calibration import (
InputRangeCalibrationType,
calibrat... |
8f10eab6261e2e4ecabda13f6fc3171f433c27600d36d199d9ed60b0ec41edd4 | Python | 373 | 13 | #!/usr/bin/env python
"""
# Author: Kangning Dong
# File Name: __init__.py
# Description:
"""
__author__ = "Kangning Dong"
__email__ = "dongkangning16@mails.ucas.ac.cn"
from .STAGATE import STAGATE
from .Train_STAGATE import train_STAGATE
from .utils import Transfer_pytorch_Data, Cal_Spatial_Net, Stats_Sp... |
193b9f3526c15e5e5705a6bdcc002aa74a945a421a70f02259f993ceb55061c8 | Python | 374 | 14 | import numpy as np
class Noise(object):
def __init__(self, seed):
self.rand = np.random.RandomState(seed)
class WhiteNoise(Noise):
"White noise generated from a standard normal distribution"
def __init__(self, seed=42):
super(WhiteNoise, self).__init__(seed)
def value(self, dt, tau, ... |
df82fe61d7f4a3e63551cb9cf3a9675f889cad77f85592662f32f77ee6757a3f | Python | 374 | 9 | # docstyle-ignore
INSTALL_CONTENT = """
# Diffusers installation
! pip install diffusers transformers datasets accelerate
# To install from source instead of the last release, comment the command above and uncomment the following one.
# ! pip install git+https://github.com/huggingface/diffusers.git
"""
notebook_first_... |
9764a924332cd5dba6ceb06a5a11e2c70cb0bb6bff94ccb0446f04bdb43a83c4 | Python | 375 | 17 | """
=========
Heaviside
=========
:class:`~sinabs.activation.Heaviside` surrogate gradient.
"""
import matplotlib.pyplot as plt
import torch
import sinabs.activation as sina
x = torch.linspace(-2, 4, 500)
plt.plot(x, sina.Heaviside(window=0.5)(v_mem=x, spike_threshold=1.0), label="Heaviside")
plt.xlabel("Neuron memb... |
b0eef56a7b2b9ed96ceca193c935b543c485562236a8ff1b30f5782deee262a4 | Python | 375 | 13 | import random
import torch
import os
import numpy as np
def seed_everything(seed=42):
random.seed(seed)
np.random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed) # type: ignore
torch.backends.cudnn.deterministic = True # type: ignore
... |
cb00216c4afc25cbf77f76135e3f11b5b3d86cbf4c8657a73d79b025b92c8aff | Python | 375 | 10 | from data_profiling.report.presentation.core.alerts import Alerts
from data_profiling.report.presentation.flavours.html import templates
from data_profiling.utils.styles import get_alert_styles
class HTMLAlerts(Alerts):
def render(self) -> str:
styles = get_alert_styles()
return templates.templat... |
b818e1860d6c278e9f288278ab626710fe59053c7fa338206997ff9d78d77584 | Python | 376 | 13 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Package version string."""
import os
VERSION_FILE = os.path.join(os.path.dirname(__file__), "VERSION.txt")
with open(VERSION_FILE, encoding="utf-8") as vers... |
86b9308b57a3db09d5d83e399dfcb802576ba7af0febe749595dfdacf58b9161 | Python | 377 | 11 | """Scope management utilities for refining project requirements.
This package provides tools to interactively clarify project scope and
summarize conversations into concise briefs.
"""
from .clarifier import Clarifier
from .brief import BriefGenerator, ProjectBrief
from .manager import ScopeManager
__all__ = ["Clari... |
883fdbac7da6119c064f3dff50bb369c7bdf3559edb68f302ac3fa13271b2dee | Python | 377 | 11 | # -*- coding: utf-8 -*-
import sys
from mozaik.meta_workflow.parameter_search import CombinationParameterSearch, SlurmSequentialBackend
import numpy
import time
if True:
CombinationParameterSearch(SlurmSequentialBackend(num_threads=1, num_mpi=16,slurm_options=['--hint=nomultithread'],path_to_mozaik_env=PATH_TO_EN... |
cf26d9097b4ba64cca1fc12845997a035cfe545c502b4de56e90f4dfd2eb449d | Python | 378 | 15 | from rpy2.robjects import r
from rpy2.robjects.packages import importr
from rpy2.robjects import pandas2ri
pandas2ri.activate()
def get_mat_path(sc_path, pa_path, output_path):
importr("GSEABase")
importr("AUCell")
importr("SingleCellExperiment")
print('R package load!')
r.source('./A... |
e1fe2473df68e1a6b30c694f70e5f121ec7a49d02504dcf1e2334a76cd6ff4b3 | Python | 379 | 13 | #!/usr/bin/env python
"""
# Author: Yahui Long
# File Name: __init__.py
# Description:
"""
__author__ = "Yahui Long"
__email__ = "long_yahui@immunol.a-star.edu.sg"
from .utils import clustering, project_cell_to_spot
from .preprocess import preprocess_adj, preprocess, construct_interaction, add_contrastive_label, get_... |
fb4642b952e5e8227f8767d947913142d5fe422a03a64daf3b0637d3e3ef72c6 | Python | 379 | 13 | from dataclasses import dataclass
from typing import List, Optional, Union
import numpy as np
import PIL
from PIL import Image
from ...utils import is_torch_available, is_transformers_available
if is_transformers_available() and is_torch_available():
from .image_encoder import PaintByExampleImageEncoder
fro... |
7107de6bf64940fa3da6c2cc6812710bd7ed7a61419ae155f8aded66644f5233 | Python | 380 | 14 | from typing import Any
from data_profiling.report.presentation.core.item_renderer import ItemRenderer
class ToggleButton(ItemRenderer):
def __init__(self, text: str, **kwargs):
super().__init__("toggle_button", {"text": text}, **kwargs)
def __repr__(self) -> str:
return "ToggleButton"
d... |
8d6821c51f73111f553b46c58983cfb7a41790a25d58accdd9ac8f50aee35934 | Python | 380 | 17 | import torch
from torch import nn
from pfrl.nn.lmbda import Lambda
from pfrl.testing import torch_assert_allclose
def test_lambda():
model = nn.Sequential(
nn.ReLU(),
Lambda(lambda x: x + 1),
nn.ReLU(),
)
x = torch.rand(3, 2)
# Since x is all positive, ReLU will not have any e... |
069b174829e03fb8b426d89a0f3d19759bdd9640485e187c12e03d4006e8002b | Python | 381 | 18 | import ray
import numpy as np
@ray.remote
def f(arr):
# arr = arr.copy() # Adding a copy will fix the error.
arr[0] = 1
try:
ray.get(f.remote(np.zeros(100)))
except ray.exceptions.RayTaskError as e:
print(e)
# ray.exceptions.RayTaskError(ValueError): ray::f()
# File "test.py", line 6, in f
# ... |
a544a787b98810d7e0ca895962fa92f804621209f026ac5895a9993692eb215b | Python | 381 | 14 | """
Entry point for running the verifier as a module.
Usage:
python -m omicverse.utils.verifier verify ./notebooks
python -m omicverse.utils.verifier validate
python -m omicverse.utils.verifier extract --directory ./notebooks
python -m omicverse.utils.verifier test-selection --task "Analyze DEGs"
"""
... |
c23cb726d39e421b2790a4ce29837425f4f5819c08cc1c2d357512ccc4a14600 | Python | 381 | 12 | from ..distances import SNRDistance
from ..utils import common_functions as c_f
from ..losses.contrastive_loss import ContrastiveLoss
class SignalToNoiseRatioContrastiveLoss(ContrastiveLoss):
def __init__(self, **kwargs):
super().__init__(**kwargs)
c_f.assert_distance_type(self, SNRDistance)
... |
e9d6339b6ce5c67729be830e821f427ef276792f6cd7f239e83d2c3588201d7f | Python | 381 | 26 | import requests
import ray
ray.init()
@ray.remote
class Counter:
def __init__(self):
self.counter = 0
def inc(self):
self.counter += 1
def get_counter(self):
return self.counter
counter = Counter.remote()
for _ in range(5):
ray.get(counter.inc.remote())
print(ray.get... |
0c611a51407cb08f229887d02148d003f80fcc91b05f2e5c8a150d360bb022b9 | Python | 382 | 15 | import os
import pickle
import numpy as np
import pandas as pd
from utils import EventLabel
evlab = EventLabel()
human_bond_fpath = '../data/high_level_events/seg_data_analysis_clean.csv'
human_bond_df = pd.read_csv(human_bond_fpath)
human_bond_df.head()
len(human_bond_df)
len(list(human_bond_df['Movie']))
np.sum(['... |
a375ced5890a8b3bafa98215b8cba69ba9a584d14f0325fdaa43053f35948ad2 | Python | 382 | 12 | from .build import build_loader as _build_loader
from .data_simmim_pt import build_loader_simmim
from .data_simmim_ft import build_loader_finetune
def build_loader(config, simmim=False, is_pretrain=False):
if not simmim:
return _build_loader(config)
if is_pretrain:
return build_loader_simmim(c... |
9d4aad5a6ee38c746e3992930e8b472cc8ff719947f10f99933e52bcde8aaf3d | Python | 383 | 10 | # Imports for filters and formatters tests
pytest_plugins = ["ray.tests.conftest"]
# pytest_plugins doesn't reliably activate autouse fixtures from the plugin, so
# import the token-auth isolation fixtures by name to register them here.
from ray.tests.conftest import ( # noqa: E402, F401
_isolate_token_auth_state... |
40cc44dd9e4e142d1ba44af85679300fea0555e821485a5131f5cec5b93eb716 | Python | 384 | 17 | """
=================================
Exponential Leaky Layer (ExpLeak)
=================================
:class:`~sinabs.layers.ExpLeak` layer.
"""
import torch
from utils import plot_evolution
import sinabs.layers as sl
const_current = torch.ones((1, 100, 1)) * 0.03
exp_leak_neuron = sl.ExpLeak(tau_mem=60.0, rec... |
bdf775ece1ca5696fbf9a6c27c9df135eed31dc41b71593a30482ed1f068e2c9 | Python | 384 | 14 | # -*- coding: utf-8 -*-
import sys
from mozaik.meta_workflow.parameter_search import CombinationParameterSearch, SlurmSequentialBackend
import numpy
import time
if True:
CombinationParameterSearch(SlurmSequentialBackend(num_threads=1, num_mpi=16,slurm_options=['--hint=nomultithread'],path_to_mozaik_env='[PATH_TO_... |
0cc834a6f7ea0d32fef9d3ff4580b9890da1c96d8dc5d5f3cb81b6bf853e3f4c | Python | 385 | 10 | from siapy.features.spectral_indices import get_spectral_indices
# Get indices computable from Red and Green bands
bands = ["R", "G"]
available_indices = get_spectral_indices(bands)
print(f"Found {len(available_indices)} indices")
# Display the names and long names of the available indices
for name, index in list(ava... |
5a26b31663e19a75355b1b538d837d467a8652807a1f7d81a5d53800440671c5 | Python | 385 | 4 | from ._flow_expressions import construct_flows_from_cellchat, construct_flows_from_commot, construct_flows_from_cellphonedb, construct_flows_from_liana
from ._flow_preprocessing import determine_informative_variables
from ._gem_construction import construct_gems_using_pyliger, construct_gems_using_nsf, construct_gems_u... |
4de118ac3134dc2ef9748841a5859ca09afc5f06162fab0fcff13d2b09e496bc | Python | 386 | 17 | # Generated by Django 4.1.6 on 2023-02-06 03:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("infer", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="weights",
name="organisms",
fi... |
4cb3f8061c2a826764c0974771a59a9211f061bf084ac107786807304c901495 | Python | 387 | 16 | """
WSGI config for site1 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTING... |
cd440d65fa4e7024a54c2c361171db498b8059d6c3a5210d7a138d2a6c535e99 | Python | 387 | 16 | """
ASGI config for site1 project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTING... |
28ab64a27ce93ef52d1c5f5feb08eae6ef3d2d025a552bb4654db13693caa3b9 | Python | 388 | 11 | from sinabs.backend.dynapcnn.utils import parse_device_id, standardize_device_id
def test_device_id_no_index():
assert parse_device_id("speck") == parse_device_id("speck:0")
def test_standardize():
assert standardize_device_id("speck2f") == "speck2f:0"
assert standardize_device_id("speck2f:00") == "spec... |
e0d9f3e4f42da70b8e1b209c52e16a14bd4f73ffe6b8a8a68bfe3850a1a77978 | Python | 388 | 17 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use("Agg")
from model import SelfSustainedPushPull
from experiments import create_experiments
import mozaik
from mozaik.controller import run_workflow
from mpi4py import MPI
mpi_comm = MPI.COMM_WORLD
data_store, model = run_workflow("LSV1M", SelfSustainedPushPull... |
926ea3a1e55fe15c97b9572d76104ad907cbcde24d8bb785da83e0b8bb0c33cb | Python | 389 | 27 | #!/usr/bin/env python
import numpy
import record
import layer
frame = record.next_frame() # Generator
def baseline():
pass
# net=layer.net(baseline)
net = layer.identity()
def error(out, data):
return numpy.sum(numpy.abs(out-data))/len(data)
if __name__ == '__main__':
prediction=0
while 1:
data= next(frame... |
9edb9362fa0480d6569c4a078a707325863da9f5670a9c6742fb6c1d3d147c14 | Python | 389 | 17 | # Generated by Django 4.1.6 on 2024-01-04 20:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("infer", "0021_alter_proteometask_id"),
]
operations = [
migrations.AddField(
model_name="weights",
name="enabled",
... |
58a994723e423bd73230a5c384adf819c5f4908db79615be9ab46b4144465f08 | Python | 390 | 15 | """Tests that Ray Tune works with the working_dir set in Jobs.
Ray Tune internally sets environment variables using runtime_env.
If the inherited internal runtime environment overwrites the working_dir
from jobs with an empty working_dir, this test will fail. See #25484"""
from ray_tune_dependency import foo
from ra... |
966e1b35301f0d2d994e58e88c0a4ca802839834d5945a6af840b98e36d2df54 | Python | 390 | 7 | # Ultralytics YOLO 🚀, GPL-3.0 license
from ultralytics.yolo.v8.classify.predict import ClassificationPredictor, predict
from ultralytics.yolo.v8.classify.train import ClassificationTrainer, train
from ultralytics.yolo.v8.classify.val import ClassificationValidator, val
__all__ = 'ClassificationPredictor', 'predict',... |
969a49009c7b929f0d7ea3585e9644b518bfec3b0217e5019b2c347314e62e97 | Python | 391 | 17 | # Generated by Django 4.1.6 on 2023-02-06 03:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("infer", "0003_organism_ncbi_taxon"),
]
operations = [
migrations.AlterField(
model_name="organism",
name="ncbi_taxon"... |
2f22dfd9ae1ce802eec8cd991eda9d617a4965834bacbf4aed59d4846f4adaab | Python | 392 | 14 | from spliceai_rocksdb.spliceAI import SpliceAI
import snakemake
if snakemake.params["lookup_only"]:
model = SpliceAI(db_path=snakemake.params["db_path"])
else:
model = SpliceAI(
snakemake.input["fasta"],
annotation=snakemake.params["genome"],
db_path=snakemake.params["db_path"],
)
... |
cda0479ac3c65ac6778171ec240de27dd0f3689fd5b8e1c65d35209e7fee32de | Python | 392 | 16 | import matplotlib
matplotlib.use("Agg")
import pandas as pd
import seaborn as sns
df = pd.read_table(snakemake.input.tsv)
subjdf = df.drop(columns=["subject", "hemi", "Cyst"]).transpose()
subjdf.columns = ["L", "R"]
sns_plot = sns.lineplot(data=subjdf)
sns_plot.set_title(str(snakemake.wildcards))
sns_plot.set_ylab... |
e925875ec58528a88feb4359deb17a1c2c4eb201844e7e45a998484682008944 | Python | 393 | 15 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import annotations
from importlib.metadata import PackageNotFoundError, version
try:
__version__ = version("fairchem.... |
e82e2992dc04dacdde749433b9e12a87e70dbea0d92e675edae40a550dd25ec9 | Python | 394 | 11 | # __register_start__
"""vLLM plugin entry point: register the custom architecture."""
def register() -> None:
from vllm import ModelRegistry
if "Qwen3CustomRewardModel" not in ModelRegistry.get_supported_archs():
ModelRegistry.register_model(
"Qwen3CustomRewardModel",
"qwen3_rew... |
99d3137a318cffab97821c949ea6f12ba33a793bc982aa1410de969e503dd8cf | Python | 395 | 18 | import logging
from pokeformer.config_wrapper import load_class
logger = logging.getLogger(__name__)
class DatasetBuilderFactory:
def __init__(self):
self.data = {}
@staticmethod
def get_class(class_name):
factory = DatasetBuilderFactory()
if class_name in factory.data:
... |
1c6f884e7ede4dccb724d44273556cf00a6d1ac1d6bc829f4e5eaa3ac260272a | Python | 398 | 17 | import pytest
import torch
from pfrl.testing import torch_assert_allclose
def test_torch_assert_allclose():
x = [torch.zeros(2), torch.ones(2)]
y = [[0, 0], [1, 1]]
torch_assert_allclose(x, y)
def test_torch_assert_allclose_fail():
with pytest.raises(AssertionError):
x = [torch.zeros(2), to... |
8fc6abf10f9fe603f743493f1e2efbea87b61819d1de929a9c401639361d8e5d | Python | 398 | 18 | """
=============
MultiGaussian
=============
:class:`~sinabs.activation.MultiGaussian` surrogate gradient.
"""
import matplotlib.pyplot as plt
import torch
import sinabs.activation as sina
x = torch.linspace(-2, 4, 500)
plt.plot(x, sina.MultiGaussian()(v_mem=x, spike_threshold=1), label="MultiGaussian")
plt.xlabel(... |
9317078c79bec41dd912e5eb93e2b7f8d29eea591c021401253a6af1894b408c | Python | 398 | 5 | # this is a template reminding on how to test module functions in notebooks during development
# %load_ext autoreload # load extension for the auto-reload magic
# %autoreload 1 # set the autoreload for module functions only for those imported with the %aimport magic
# %autoreload 2 # set the autoreload for all module f... |
c35d0dbc63c31d097d72b5f4bf1daa61c9dfdd2304f9a6e61727ef74777c59f2 | Python | 398 | 18 | #!/bin/python
#------------------- Description & Notes --------------------#
#------------------- Dependencies ---------------------------#
# Standard imports
# Third-party imports
# Internal imports
#------------------- Constants ------------------------------#
#------------------- Classes & Functions ---------... |
e15f2cb0124c4455d29f19a311d8af3ba25cc57d2ca531a0173eb60f329e316d | Python | 398 | 19 | import torch
import numpy as np
class Dataset(torch.utils.data.Dataset):
def __init__(self, data, data_type='pos'):
self.data = data
if data_type == 'pos':
self.label = np.ones(self.data.shape[0])
else:
self.label = np.zeros(self.data.shape[0])
def __len__(self):
return len(self.label)
def __getite... |
02c75f9127a9186219cdcf97a2330ba4879631859d462bc9ae71835aeb0b97a9 | Python | 399 | 16 | """
ASGI config for rapppid_org project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_S... |
05ef5e42e751252879c879b078f68c0d0bcd65a3b18e959b523ea914c7be0a9d | Python | 399 | 11 | from .recipes import recipe_preprocess, recipe_annotate, recipe_full
from .correlation import (
calculate_correlation,
calculate_correlation_estimate,
calculate_correlation_estimate_sd,
calculate_margin_genes
)
from .covariate_correlation import vcorrcoef, calculate_svd_covar_corr
from .multigraph impor... |
182d670719918cadadb65cd587cfcfe98b597405fa218a052110bf529b2458b8 | Python | 399 | 16 | """
WSGI config for rapppid_org project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_S... |
b9b76179e680e9cd1eb3dd7a343d5f4af406113a2faa68f315c3117998a6a9f0 | Python | 399 | 16 | """
AVA package for plotting and analysis
Contains
--------
`ava.plotting.grid_plot`
Plot grids of spectrograms.
`ava.plotting.latent_projection`
Plot scatterplots of latent means.
`ava.plotting.mmd_plots`
Plot MMD matrices.
`ava.plotting.shotgun_movie`
Make a movie out of a shotgun VAE projection and an audio fil... |
0d8d443350dbd0091fd1499732cceaccfda254bfc6e8d39375b31d862b3212db | Python | 400 | 18 | import pytest
@pytest.fixture(autouse=True)
def close_all_windows():
"""Close all open Qt Windows before and after each test."""
import vtkplotlib as vpl
def _close_all_figures():
for figure in vpl.figure_history:
try:
figure.close()
except RuntimeError:
... |
4d98a0723be8fcee79a5a323afa7083e84f1d3a6b933953cf6d9b6f7465f66a7 | Python | 400 | 16 | __all__ = [
'particles'
]
import numpy as np
from typing import Tuple
from numpy.typing import NDArray
def particles(vol : NDArray[np.float32], threshold : float = 1e-6) -> Tuple[NDArray[np.float32]]:
n = vol.shape[0]
vol = np.where(vol < threshold, 0, vol)
xs = np.nonzero(vol)
rho = vol[xs]
x... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.