sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
44c665736bbc2afb1f7d85326b43ab5e3ad560a11ebfe9f15b301fe2cabf51eb | Python | 1,040 | 30 | import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
def plot_mean_spectra(ds, out_path):
fig, ax = plt.subplots(figsize=(11, 6))
for col, lab in [(0, "Pure tahini"), (2, "Pure sunflower"), (1, "Pure peanut")]:
mask = ds.y[:, col] >= 99.0
if mask.sum():
... |
1314af174a74ef07289fa12692e7436eb0748a7033d81cf78ca3be467951c557 | Python | 1,041 | 39 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from typing import Protocol
import torch
from mattergen.diffusion.corruption.sde_lib import SDE
class TimestepSampler(Protocol):
min_t: float
max_t: float
def __call__(self, batch_size: int, device: torch.device) -> torch.FloatTe... |
be2df25bb9d6560f3834c90437e6a438499458e969b4b0fe8a3f1d8b97d8ed45 | Python | 1,042 | 23 | import pandas as pd
import numpy as np
import seaborn as sns
fname='/home/oleksanf/vmshare/data/mixer_test/perf_cluster7/PGC_SCZ_2014_EUR.csv'
#fname='/home/oleksanf/vmshare/data/mixer_test/perf_cluster7/PGC_SCZ_2014_EUR_vs_SSGAC_EDU_2018_no23andMe.csv'
#fname='/home/oleksanf/vmshare/data/mixer_test/perf/PGC_SCZ_2014_E... |
89134c59fdd395c221396b5eef3b18bd609f9162caba928370ce4585907a0aff | Python | 1,043 | 41 | import pytest
import novae
from novae._constants import Keys
adatas = novae.data.toy_dataset(n_panels=2, xmax=200)
novae.utils.spatial_neighbors(adatas)
model = novae.Novae(adatas)
model.mode.trained = True
model.compute_representations()
model.assign_domains()
@pytest.mark.parametrize("hline_level", [None, 3, [2... |
be8f6768c0fd64ad0caaa453487fd0e2035d0583cacaeb4e7e64329de7d09cad | Python | 1,043 | 35 | from __future__ import annotations
from typing import TYPE_CHECKING
from typing import ClassVar
from poetry.console.commands.self.install import SelfInstallCommand
if TYPE_CHECKING:
from cleo.io.inputs.option import Option
class SelfSyncCommand(SelfInstallCommand):
name = "self sync"
description = (
... |
7ce1423764020ca5fd418983d7d122b62ec49d702e2162068250674bc3a51265 | Python | 1,044 | 29 | import setuptools
with open('README.md', mode='r', encoding='utf-8') as fh:
long_description = fh.read()
with open("requirements.txt", "r") as f:
requirements = f.readlines()
setuptools.setup(
name='grad-cam',
version='1.5.5',
author='Jacob Gildenblat',
author_email='jacob.gildenb... |
28d97601946f5a40e5fbcff242806298cf899b3fd51a07300924cd087ec5a4b9 | Python | 1,048 | 26 | """Shared publication figure style for Paper #2 (Food Chemistry). Apply once per module at import;
`save()` writes a vector PDF alongside the PNG (Food Chemistry accepts vector artwork)."""
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
RC = {
"figure.dpi": 150, "s... |
2231051d8414a40cc2a84fc6d2e8510f660ab6e86a10d7b352cef72df525a5cc | Python | 1,052 | 47 | #!/usr/bin/env python3
"""Verify core dependencies for SegJointGene-CID standalone package."""
from __future__ import annotations
import importlib
import sys
REQUIRED = [
"torch",
"torchvision",
"numpy",
"cv2",
"PIL",
"hydra",
"omegaconf",
"pytorch_lightning",
"te... |
8a86d58c6ddd53daaa4b58d4eb782e1f5c6e95464a14f0b4658ad04519c9bd2f | Python | 1,052 | 32 | import os
import sys
import subprocess
import numpy as np
import glob
import json
import pandas as pd
'''
This script creates a folder "Extracted_data" inside which it extracts all the wav files in the directories date-wise
'''
coswara_data_dir = os.path.abspath('.') # Local Path of iiscleap/Coswara-Data Repo
extract... |
cfc7127f933f98586306a2462f401efab97e275cc8609bfc7b4f1ab211392fb5 | Python | 1,052 | 32 | import numpy as np
# Colours and types
def asymmetric_mad(data):
"""
Computes the asymmetric median absolute deviation in a vectorized manner.
"""
# Calculate the median for each column (axis=0)
median = np.nanmedian(data, axis=0)
# Calculate absolute deviations from the median
# Broadc... |
06369bf7af6953dafed9271952c88a4266e68e13d02607cd727efa8ccefc6824 | Python | 1,053 | 30 | def replace_layer_recursive(model, old_layer, new_layer):
for name, layer in model._modules.items():
if layer == old_layer:
model._modules[name] = new_layer
return True
elif replace_layer_recursive(layer, old_layer, new_layer):
return True
return False
def r... |
0ff2b15658e79da8e4ecafe16c583eb2a2e3e974476acec3861f80440a77bc73 | Python | 1,053 | 36 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""isort:skip_file"""
import importlib
import os
from fairseq import registry
from fairseq.criterions.fairseq_criterion import ( # noqa
... |
1dd8fe5b3ebb5ec56db22c1b5aea21ee7f30403fa328d320cef9ea61c938ffa9 | Python | 1,053 | 36 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""isort:skip_file"""
import importlib
import os
from fairseq import registry
from fairseq.optim.lr_scheduler.fairseq_lr_scheduler import ( ... |
d5f8823a13bc6b5b5b38f0a4580a5d8ed522ef75029889211bb1bfeaf822b5e8 | Python | 1,053 | 28 | import torch.nn as nn
import torch
import torch.nn.functional as F
class PSPModule(nn.Module):
def __init__(self, features, out_features=1024, sizes=(1, 2, 3, 6)):
super().__init__()
self.stages = []
self.stages = nn.ModuleList(
[self._make_stage(features, size) for size in siz... |
44113b42795c79f20643d47c2f34ee2551e65f696d3222ef01cf6bdad2cfaa9d | Python | 1,054 | 38 | #Import all the dependencies
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
data = ["I love machine learning. Its awesome.",
"I love coding in python",
"I love building chatbots",
"they chat amagingly well"]
tagged_data = [TaggedDocument(words... |
a4c023b2d1d81b430417890a726249d0fe4e7e1c551fa410f9ef88e59705632c | Python | 1,054 | 39 | import torch
import torch.utils.data as Data
import torchvision
from lib.network import Network
from torch import nn
import numpy as np
test_data = torchvision.datasets.MNIST(root='./mnist/',
transform=torchvision.transforms.ToTensor(),
tra... |
0a93682a8e0b7c0f3f353e58b9bbd9b29b21099bb5bdce6936dd1c672eeae0b2 | Python | 1,055 | 29 | from __future__ import annotations
import pytest
from poetry.console.logging.formatters.builder_formatter import BuilderLogFormatter
@pytest.mark.parametrize(
"input_msg, expected_output",
[
("Building package", " - Building <info>package</info>"),
("Built package", " - Built <success>pack... |
1eaf485e93ee7d55419c92be833a66f0ccbedf55329224695199c80096f8519b | Python | 1,058 | 40 | from __future__ import annotations
import sys
from pathlib import Path
"""
Central path configuration shared by the embedded dfer package.
Output files are written relative to the project root by default.
Call configure_paths() to redirect them anywhere (e.g. user Documents).
"""
def _resolve_default_root() -> Pat... |
81eedce724f0a190cc0745f11193a73ce681ab516c76173ce0e6bf02fc673425 | Python | 1,059 | 46 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from glob import glob
from vlpp.utils import save_json
from vlpp.qamosaic import Mosaic
def main():
# Usefull directories
os.mkdir("data")
# Informations
participant_id = "${sub.sub}"
# Images Path
try: anat = glob("${sub.anat}")[0]
... |
ec1e1151f6121767cff5fbd6a135ab8ac783caefcdf8209c287ba9c83d933b8a | Python | 1,060 | 29 | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import warnings
def truncated_laplace(mean, T, truncate_by_zero=False):
"""Generating a sample from a Laplace distribution, ... |
16477a9352c22ab30762c190c34d89eb06704ecdc3621a83cbf6c8adca32035f | Python | 1,063 | 20 | """Repeated stratified GroupKFold: run the tested `kanfood.validate.run_group_cv` across several
shuffles (seed+r) and pool the per-fold metrics. Gives a robust distribution for CIs and paired
significance tests at modest n, while every fold remains leakage-free (preprocessing + PLS fit on
train fold only, inside run_g... |
1eb2b8cc9efa87afab8a885a187e9f930ec135cb1184a0ce0f7cb0346ef6ace2 | Python | 1,064 | 7 | Copyright 2026 Joonas Iivanainen
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, subl... |
ef3c5b7231f6213ed81456dab4e4616d99421ab7378c0a6daff2e468d87e75e9 | Python | 1,064 | 34 | import pytest
import numpy as np
import os
#from ecephys_spike_sorting.modules.mean_waveforms.extract_waveforms import extract_waveforms
#mport ecephys_spike_sorting.common.utils as utils
#DATA_DIR = os.environ.get('ECEPHYS_SPIKE_SORTING_DATA', False)
def test_extract_waveforms():
sample_rate = 30000.0
numC... |
3ad3e065327d25dfc92188632ed4687eb26c473f154834611f8f80ca3c89c972 | Python | 1,065 | 41 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
from . import BaseWrapperDataset
class AppendTokenDataset(BaseWrapperDataset):
def __init__(self, datas... |
60c3cabc61cfa1051c7a177ba7386117a58d713b37fb8c675d77303bda06c9bb | Python | 1,065 | 30 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from functools import partial
import pytest
import torch
from mattergen.diffusion.model_target import ModelTarget
from mattergen.diffusion.model_utils import convert_model_out_to_score
from mattergen.diffusion.tests.conftest import SDE_TYPES
... |
afa097cef600711628bd6663682ebfb19f1654ea09f49b11a662f799563d97f5 | Python | 1,065 | 26 | import random
for file in ['Training_dataset_R1_1234.txt','Training_dataset_R2_1234.txt','Training_dataset_R3_1324.txt','Training_dataset_R4_1324.txt','Training_dataset_R5_2134.txt','Training_dataset_R6_2134.txt','Training_dataset_R7_2314.txt','Training_dataset_R8_2314.txt','Training_dataset_R9_3124.txt','Training_data... |
918000a0556229b99299e5de9506fe11efdf228321e85b6e64b2da383e4ec788 | Python | 1,066 | 41 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
from . import BaseWrapperDataset
class PrependTokenDataset(BaseWrapperDataset):
def __init__(self, data... |
ad800e9ea35f1e4a83c414930d2d3859f264ef9fcf7fa1faa70258098c56d17f | Python | 1,066 | 33 | from mdt import CompositeModelTemplate
__author__ = 'Robbert Harms'
__date__ = '2017-07-19'
__maintainer__ = 'Robbert Harms'
__email__ = 'robbert@xkls.nl'
__licence__ = 'LGPL v3'
class AxCaliber(CompositeModelTemplate):
"""The AxCaliber model with Gamma distributed cylinders."""
model_expression = '''
... |
9dc04b327c7dd11ab209c57377f533494a45a5a63d29ae39d992959d7a1c6f3a | Python | 1,067 | 36 | import novae
from novae._constants import Nums
adata = novae.data.toy_dataset(xmax=200)[0]
def test_settings():
novae.settings.disable_lazy_loading()
novae.utils.spatial_neighbors(adata)
model = novae.Novae(adata)
model._datamodule = model._init_datamodule()
assert model.dataset.torch_converter.... |
06a581e419e7bd2450302667438ac7ab9f7b197e7dee0c92966cf67c5078394a | Python | 1,068 | 29 | import torch
def montecarlo(f:torch.Tensor,pdf:torch.Tensor):
return torch.sum(f) / f.data.nelement() # 默认是面积是1,所以不用除以pdf
# return torch.sum(f/pdf) / f.data.nelement()
def trapz1D(f:torch.Tensor,x:torch.Tensor):
d = x[1:] - x[:-1]
return 0.5 * torch.sum(d * (f[...,1:] + f[...,:-1]) , -1)
def trapz2D(... |
99ee12f131614a8096a8ea2aeb1fbf9676fa5e7aa41f002746b232d675b4caa3 | Python | 1,068 | 45 | from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from cleo.io.null_io import NullIO
from poetry.core.packages.project_package import ProjectPackage
from poetry.puzzle.provider import Provider as BaseProvider
from poetry.repositories import Repository
from poetry.repositories import ... |
b830b16b8bb83e60aa052efd766f4ef2b4e46970a38c4c4ec6ec2734aac2d89c | Python | 1,068 | 36 | import torch
import torch.nn.functional as F
def masked_mse_loss(
input: torch.Tensor, target: torch.Tensor, mask: torch.Tensor
) -> torch.Tensor:
"""
Compute the masked MSE loss between input and target.
"""
mask = mask.float()
loss = F.mse_loss(input * mask, target * mask, reduction="sum")
... |
fed927490fe66ddb1aa51eaf2db8064c05c5fd49187c6316f6089a61a8bfce02 | Python | 1,068 | 31 | # created by DebarpanB
# date 26th August, 2022
import argparse, configparser
from ast import parse
from turtle import pd
import numpy as np
import pandas as pd
def main(featslist, labellist, pathlist):
df_feats = pd.read_csv(featslist, header=None, delimiter=' ')
df_feats.columns = ['id', 'feat_path']
d... |
b1e77944c1a716b01504be727fc5175ca7480d77791747c542fce02f374f5a3d | Python | 1,069 | 35 | import numpy as np
import pytest
from src.dfer.msbackadj import msbackadj, msbackadj_window_size
def test_msbackadj_window_is_ten_percent_of_recording_span():
time_values = np.linspace(0.0, 100.0, 101)
assert msbackadj_window_size(time_values) == pytest.approx(10.0)
def test_msbackadj_removes_slow_baselin... |
ee37ac711e285ec8aac7d5c88e6471ea20369d7f353a17fbd19a40e0ebcf4322 | Python | 1,070 | 31 | from Bio.PDB import PDBParser
import numpy as np
import warnings
warnings.filterwarnings('ignore')
from .utils import *
def is_contact(res1,res2,radius=6):
for atom2 in res2.get_atoms():
# if atom2.get_name() in ['CA','CB','C','N','O']:
if atom2.get_name() in ['CA']:
for atom in res1.... |
6765be2152777e60e0ec6606966a4fb7ba8af23881d3c15bd88a19e49ca4ab79 | Python | 1,071 | 25 | ## Wrapper for crystalgrw.cli.compute_metrics.main ##
import argparse
from crystalgrw.cli.compute_metrics import run_compute_metrics
def main(cfg):
run_compute_metrics(cfg)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--root_path", required=True, type=str)
parse... |
c03b1ab64c23814ac063117301728df7cf7d91552a8434979ded7c0f74ea2274 | Python | 1,071 | 45 | """
modify from: https://github.com/marakeby/pnet_prostate_paper
"""
def require_ML_params(model_type):
if model_type == "sgd":
"""
L2 Logistic Regression
"""
params = {'loss': 'log_loss', 'penalty': 'l2', 'alpha': 0.01}
if model_type == "svc_rbf":
"""
RBF Supp... |
3d92c23d8bba7b14376d614da64f604673658a3f0ae2b59ad6b5ebd5e3e2c65d | Python | 1,074 | 43 | import pytest
from numpy import nan
from pandas import DataFrame
from pgmpy.estimators import ParameterEstimator
from pgmpy.models import DiscreteBayesianNetwork
@pytest.fixture
def m1():
return DiscreteBayesianNetwork([("A", "C"), ("B", "C"), ("D", "B")])
@pytest.fixture
def d1():
return DataFrame(data={"... |
f5fc35a777d31718a465548f33567e7fbda3583f543ac79626ae2f5c910bbfac | Python | 1,074 | 38 | """crossda — cross-session EEG classification and domain-adaptation pipelines.
Public API
----------
Config runtime configuration dataclass
run orchestrate a full multi-dataset run from a Config
process_subject run all pipelines for a single subject
generate_me... |
60d079e561efbca28b5de3ee8eea84ef176e2c51e5d31eb6fbb58f65b6ca5263 | Python | 1,075 | 40 | """Qt background-analysis and logging bridges for raw photometry."""
from __future__ import annotations
import logging
from PySide6.QtCore import QObject, Signal, SignalInstance
class AnalysisWorker(QObject):
finished = Signal(object)
failed = Signal(object)
def __init__(self, fn, kwargs: dict) -> Non... |
ef89ae30d9040fd8cacc6ddec59105c688bf42e65819579c0a7cecb5abf732c1 | Python | 1,076 | 38 | import numpy as np
import pandas as pd
import pytest
from pgmpy.ci_tests import GSq
@pytest.fixture
def test_data():
df_adult = pd.read_csv("pgmpy/tests/test_estimators/testdata/adult.csv")
test = GSq(data=df_adult)
return test
def test_discrete_tests(test_data):
assert not test_data("Age", "Immig... |
fcbf55102082badafd6cfad9524c9797105887b84ef3e2962e5cc056356c69fb | Python | 1,076 | 35 | import numpy as np
from matplotlib.ticker import LinearLocator
__author__ = 'Robbert Harms'
__date__ = "2014-02-14"
__license__ = "LGPL v3"
__maintainer__ = "Robbert Harms"
__email__ = "robbert@xkls.nl"
class MyColourBarTickLocator(LinearLocator):
def __init__(self, min_val, max_val, round_precision=3, **kwargs... |
ff0b557517ae5ec71c038fd7d921dc73d38a707defeb796fe10d5b54c61c9ee2 | Python | 1,076 | 35 | # code from https://github.com/theislab/scanpy/blob/master/docs/extensions/typed_returns.py
# with some minor adjustment
from __future__ import annotations
import re
from sphinx.ext.napoleon import NumpyDocstring
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from sphinx.application import Sphinx
from co... |
04b5320b034ca9cc8993ea8a473bd078c6b038d0d055c17a70502907e95d8841 | Python | 1,077 | 32 | # Load required packages
import os
import sys
import pandas as pd
import json
from absl import flags
from absl import app
from glob import glob
import MDAnalysis as mda
fn=sys.argv[1]
out_dir=sys.argv[2]
json_output_path=sys.argv[3]
with open(fn) as fh:
out_json=json.load(fh)
#get CDR3s confidence scores
def ge... |
dffb55036bc69e2004a1e0413038e40b31dcebbd61518b0d2c0c3b64d665cd66 | Python | 1,078 | 48 | from pgmpy.datasets._base import BaseDataset
class PittsburghBridges(BaseDataset):
"""
References
----------
- :footcite:t:`uci_pittsburgh_bridges`
"""
_tags = {
"name": "pittsburgh_bridges",
"n_variables": 12,
"n_samples": 108,
"has_ground_truth": False,
... |
2ac13a3332c4545b3951fba1d06f83fdf2da1ddd9210596ce0dd505c5eea34ce | Python | 1,082 | 38 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from fairseq.data import data_utils
from . import BaseWrapperDataset
class PaddingMaskDataset(BaseWrapperDataset):
def __i... |
44e1f7b553d8f76f1f23f965b220b0bfb50cc586bcf6345044cc997882f4a1ff | Python | 1,084 | 34 | import warnings
from Bio import SeqIO
def fasta_extraction(fasta_file, auto_fix=False):
"""Using biopython to check sanity of fasta file"""
ids = []
seqs = []
sanity = False
# check if file exists and sanity
try:
SeqIO.read(fasta_file, "fasta")
except FileNotFoundError or IOError... |
1630135cf0c85e7a3c69a9643271e51a2c8716ff7014444ac9370d2ef0ab433f | Python | 1,085 | 32 | import pandas as pd
def load_trec_relevance_pairs(input_path: str) -> pd.DataFrame:
trec_df = pd.read_csv(input_path, delimiter="\t")
return trec_df
def get_trec_repurposed_with_topic(trec_df: pd.DataFrame) -> pd.DataFrame:
trec_df['Rel-d2d'] = trec_df[['Rel1','Rel2']].min(axis=1)
trec_df = trec_df.d... |
34b0413d06b1e9987497e0ab8e9370596222a3fa9f2df8f0ce34758f97a6c948 | Python | 1,085 | 23 | import torch
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3" ## set your available devices, each use ~2G GPU-MEMORY
import scanpy as sc
import scMulan
from scMulan import GeneSymbolUniform
adata = sc.read('Data/liver.h5ad', backup_url='https://cloud.tsinghua.edu.cn/f/45a7fd2a27e543539f59/?dl=1')
adata_GS_unifo... |
70b31a2afa22d297fef38c64dd792fac996268dd8a31087b56383ea26b1a5ad1 | Python | 1,086 | 39 | # @license
# Copyright 2016 Google Inc.
# 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... |
76bde04f4a79b26e060a9d059d79c2515b1d775b68191f83240a69b22785c331 | Python | 1,088 | 30 | import unittest
from unittest.mock import patch
from pyecharts import options as opts
from pyecharts.charts import EffectScatter
from pyecharts.faker import Faker
class TestEffectScatterChart(unittest.TestCase):
@patch("pyecharts.render.engine.write_utf8_html_file")
def test_effectscatter_base(self, fake_wri... |
177505db49a773bf0080b33f60da68ab52397a407ba575acac971501fc857c15 | Python | 1,089 | 47 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import multiprocessing
import os
import pdb
import sys
__all__ = ["set_trace"]
_stdin = [None]
_stdin_lock = multiprocessing.Lock()
try:
... |
3837e6e42354460a8c7402c1bf462b31faf71a6d3354de57c41f848b127c2cda | Python | 1,089 | 40 | # Authors: Christian O'Reilly <christian.oreilly@sc.edu>
# Scott Huberty <seh33@uw.edu>
# James Desjardins <jim.a.desjardins@gmail.com>
# Tyler Collins <collins.tyler.k@gmail.com>
#
# License: MIT
"""Utility Functions for running the Lossless Pipeline."""
import numpy as np
import pandas as... |
8969215d9f9274b4c18e60177d082b0910a4e86513d88f7a3bed7f75147af27f | Python | 1,090 | 46 | #!/usr/bin/env python
"""Helper script to compare two argparse.Namespace objects."""
from argparse import Namespace # noqa
def main():
ns1 = eval(input("Namespace 1: "))
ns2 = eval(input("Namespace 2: "))
def keys(ns):
ks = set()
for k in dir(ns):
if not k.startswith("_"):
... |
a8726f3a83cd4e4243f6069ff31fb36b390de863fc28f25575f8f6ac08536326 | Python | 1,090 | 38 | import numpy as np
import pandas as pd
import pytest
from pgmpy.ci_tests import LogLikelihood
@pytest.fixture
def test_ll():
df_adult = pd.read_csv("pgmpy/tests/test_estimators/testdata/adult.csv")
test = LogLikelihood(data=df_adult)
return test
def test_discrete_tests(test_ll):
assert not test_ll... |
ebc28b2ff5c02127464e85c321368dc8a4a1403d68b19a742e2af4c880c2669b | Python | 1,090 | 31 | from mdt import CompartmentTemplate
__author__ = 'Robbert Harms'
__date__ = "2015-06-21"
__maintainer__ = "Robbert Harms"
__email__ = "robbert@xkls.nl"
class CHARMEDRestricted(CompartmentTemplate):
parameters = ('g', 'b', 'G', 'Delta', 'delta', 'TE', 'd', 'theta', 'phi')
dependencies = ('SphericalToCartesia... |
ce473e6591625d8f9b5ef54d10ee187bf1e190f653dee5c861992cb37e9a0d0c | Python | 1,091 | 36 | from __future__ import annotations
import pytest
from packaging.tags import Tag
from poetry.utils.env import MockEnv
from poetry.utils.wheel import Wheel
@pytest.mark.parametrize(
("filename", "supported_tags", "expected"),
[
("demo-1.0.0-py3-none-any.whl", [Tag("py3", "none", "any")], True),
... |
8e02ab8b761542928c3d08c188eac722b396f793d88cb1d5105fb5d9d1fbee7d | Python | 1,092 | 36 | import numpy as np
import pylab as plt
import skfmm
X, Y = np.meshgrid(np.linspace(-1,1,501), np.linspace(-1,1,501))
phi = (X+0.8)**2+(Y+0.8)**2 - 0.01
speed = 1+X**2+Y**2
plt.subplot(221)
plt.title("Zero-contour of phi")
plt.contour(X, Y, phi, [0], colors='black', linewidths=(3))
plt.gca().set_aspect(1)
plt.xticks([... |
93f05c059fa0c9583bd232153f43e064742c480e08e623e3f2c86b2aa110670d | Python | 1,092 | 33 | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # to avoid any CUDA issues
import sys
import numpy as np
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from tensorflow.keras.models import load_model
SIDE_SUFFIX = ['_rh','_lh']
'''
By K. Butenko
MATLAB interfaced function to get pathway percent activation usi... |
cec66d2c3a38b9e0f6b57931a5b0be102fc31f815a445902cd9d016a2861c3fe | Python | 1,092 | 29 | import unittest
from pathlib import Path
import torch
from tangle_tracer.object_detection.modules_yolo import YOLOModule
class YOLOModuleTestCase(unittest.TestCase):
"""YOLOModuleTestCase class."""
@classmethod
def setUpClass(cls) -> None:
cls.rand_data = torch.rand(1, 3, 1024, 1024)
cls.d... |
d102d2cdef8b004e71028e99d399e0ea7c533b8558544a1438749cb4d8878894 | Python | 1,092 | 40 | from __future__ import annotations
import subprocess
from typing import TYPE_CHECKING
import pytest
from poetry.utils.pip import pip_install
if TYPE_CHECKING:
from pathlib import Path
from pytest_mock import MockerFixture
from poetry.utils.env import VirtualEnv
from tests.types import FixtureDir... |
8e0608476fe50b0d7367c32c429f7594aa05f7c76d1f5799842b975bce44042c | Python | 1,093 | 41 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
description = """Villeneuve Lab PET Pipeline"""
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
from glob import glob
from setuptools import setup
DISTNA... |
c765393fd933d2f42796a93a980a80ce24071de918eebf57c758204d9ab0af2e | Python | 1,093 | 31 | """CLI parser for generate test data script"""
import argparse
from . import constants
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
'--step',
choices=constants.GENERATE_TEST_DATA_STEPS,
help=f"Which step of generating test data to perform, one of: {constan... |
db0a3cb1f8628148bf45023ef89d2aebe91a03cb70c857ea9d2ec4e9a0c288dc | Python | 1,095 | 35 | import sys
if sys.version_info < (3, 6):
sys.exit("garfield requires Python >= 3.6")
from setuptools import setup, find_packages
from pathlib import Path
version = {}
with open("Garfield/_version.py") as fp:
exec(fp.read(), version)
setup(
name="Garfield",
version=version["__version__"],
author=... |
fba2d4f1a166e300a2cd927afa0e1e7b8a0199bcbeaf977422b60b094828fbc8 | Python | 1,095 | 33 | import statsmodels.api as sm
from statsmodels.api import GLS, OLS, WLS
class LinearEstimator:
"""
A simple linear model built on statmodels.
"""
def __init__(self, graph, estimator_type="linear", **kwargs):
self._supported_models = {"linear": OLS, "OLS": OLS, "GLS": GLS, "WLS": WLS}
i... |
63d4e7e450ca71b043db18891f9c786ab71ae1be0b2c86fc7b3ac30d6b129b3e | Python | 1,096 | 38 | from os.path import join
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
# base_dir = '../../data/prostate/input'
from config_path import DATA_PATH
base_dir = DATA_PATH
# filename = 'final/P1013_Clinical_Annotations_MAF.txt'
# filename = 'study_view_clinical_data.txt'
filename = 'prostat... |
893b1f013be9f1dbcaf84d0ea9e73268d6a0356b6f8523f818761632630c2673 | Python | 1,097 | 33 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
89baf40283725ebdbc201f8fd05adaccc6afa3da7e172e87aec8e51dbb6616c0 | Python | 1,097 | 39 | from __future__ import annotations
from copy import deepcopy
import pytest
from poetry.core.packages.package import Package
from poetry.repositories.lockfile_repository import LockfileRepository
@pytest.fixture(scope="module")
def packages() -> list[Package]:
return [
Package("a", "1.0", source_type="... |
aa87cbd5361440cfc556614a9ff3638c4c06a4d3242852e5eae88a0587aeac7e | Python | 1,097 | 56 | def eval(toml_path):
from .eval import eval
eval(toml_path=toml_path)
def train(toml_path):
from .train import train
train(toml_path=toml_path)
def learncurve(toml_path):
from .learncurve import learning_curve
learning_curve(toml_path=toml_path)
def predict(toml_path):
from .predict... |
dcf46a5237a9cc480af8b2cd96996d135ef874448a9e528cf6a9c388ed74ea06 | Python | 1,099 | 27 | import random
import gzip
#for file in ['Training_dataset_R1_1234.txt','Training_dataset_R2_1234.txt','Training_dataset_R3_1324.txt','Training_dataset_R4_1324.txt','Training_dataset_R5_2134.txt','Training_dataset_R6_2134.txt','Training_dataset_R7_2314.txt','Training_dataset_R8_2314.txt','Training_dataset_R9_3124.txt','... |
393ac1c49d225cb1e166b1bee7bd055aa0cb8ca691f99b17951a823b850e2e0e | Python | 1,100 | 31 | #!/usr/bin/env python3
import argparse
import polars as pl
def main():
parser = argparse.ArgumentParser(description="Get read names for PITA genes from spearman TSV + BED.")
parser.add_argument("--spearman", required=True, help="Per-sample spearman TSV")
parser.add_argument("--bed", required=True, help="7... |
6703eb021d50b2791f63c41f8ba9dfeeb903372a922521ee94ef637e6abfa94b | Python | 1,103 | 32 | import numpy as np
class AutoColorizeRandom:
def __init__(self, color_schemes):
self.color_schemes = color_schemes
def colorize(self, ratio, k):
num_low = int(ratio * k)
colors_low = np.random.choice(self.color_schemes["low"], num_low)
colors_high = np.random.choice(... |
d9cce14ba70d15742eba2ee69dc96e1e253d02f3eb2a7181a76fe7c408e44828 | Python | 1,103 | 45 | """Smoke test for scripts/symm_net/salnet_symm.py.
No dataset needed. Runs in tmp_path so pytest cleans up the runs/ output
directory automatically.
"""
import json
import subprocess
import sys
import pytest
from conftest import SCRIPTS_DIR
SCRIPT = SCRIPTS_DIR / "symm_net" / "salnet_symm.py"
@pytest.mark.timeout... |
0c8cc2da4789e8fca6bcbecdd2fbb34c922a382f34a873f1594ab80d61d0728a | Python | 1,104 | 45 | #!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import sys
from g2p_en import G2p
def main():
parser = argparse.ArgumentParser()
parser.a... |
4910f69baceb3d05f74ee88033698548fb5e99e042e1f7fb077830b7f8042bd0 | Python | 1,105 | 39 | # isort: skip_file
# else segmentation fault during imports
import pyarrow # noqa: F401
from pathlib import Path
import numpy as np
import scanpy as sc
other_dir_names = [f"X_scConcept{2 + i}" for i in range(3)]
def _print_stats(adata: sc.AnnData, name: str) -> None:
X = adata.obsm["X_scConcept"]
mean_l2_... |
5d2dd6cbcba0766f8370ee162182da1637c075118e6927d18b63288fc0b4d1ae | Python | 1,106 | 28 | from pymol import cmd
class PDBQTCombiner:
def __init__(self, receptor_pdbqt_path, ligand_pdbqt_path):
self.receptor_pdbqt_path = receptor_pdbqt_path
self.ligand_pdbqt_path = ligand_pdbqt_path
def convert_pdbqt_to_pdb(self, pdbqt_path, output_pdb_path):
cmd.load(pdbqt_path)
cmd... |
09c852b406e4104d00e95c9e3f4854b70d37b8d9a449ed5d061cab86be88d84d | Python | 1,108 | 36 | import sys
from pathlib import Path
from types import SimpleNamespace
import unittest
MODULE_DIR = Path(__file__).resolve().parents[1]
if str(MODULE_DIR) not in sys.path:
sys.path.insert(0, str(MODULE_DIR))
from gpu_runtime import get_torch_build_archs # noqa: E402
class GpuRuntimeTests(unittest.TestCase):
... |
8f7823d55e02f4b1a6e3834c4d65a9b2acd6b43cce3d8a4691fd91238cd9611f | Python | 1,108 | 34 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import soundfile as sf
import torch
import torchaudio.compliance.kaldi as kaldi
class LogMelFeatureReader:
"""
Wrapper class to run ... |
a142728e0bbf98314c1f3ef25fff48a77b9a49517c9070bf0e29c6bfc75d7125 | Python | 1,108 | 35 | from __future__ import annotations
import pytest
from packaging.utils import canonicalize_name
from poetry.core.packages.dependency_group import MAIN_GROUP
from poetry.core.version.markers import parse_marker
from poetry.packages.transitive_package_info import TransitivePackageInfo
DEV_GROUP = canonicalize_name("d... |
e9789b599565ca82fe0f05b735d704ee852f76ed8f76fba30dfe6fa84709e1d7 | Python | 1,109 | 22 | import torch
from nnunetv2.training.nnUNetTrainer.variants.data_augmentation.nnUNetTrainerDA5 import nnUNetTrainerDA5
class nnUNetTrainer_2000_epochs_DA5NoMirroring(nnUNetTrainerDA5):
def __init__(self, plans: dict, configuration: str, fold: int, dataset_json: dict, unpack_dataset: bool = True,
d... |
f8ad8524136185b6c71b0715cf8073b101b8e20d4289f96d23927216eef6f0c1 | Python | 1,111 | 31 | import numpy as np
import os
from meld_classifier.paths import BASE_PATH, COMBAT_PARAMS_FILE
from meld_classifier.meld_cohort import MeldCohort
from meld_classifier.data_preprocessing import Preprocess
#Define combat file path
combat_file = os.path.join(BASE_PATH, COMBAT_PARAMS_FILE)
#Generate feature names
features ... |
6c08f6b31dedba1514e36f16d1ef3db3039818d8b6a1a55305dc59354d5f8635 | Python | 1,112 | 49 | import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
# ================= USER CHOICE =================
n_to_plot = [2,3,5] # e.g. [3] or [2,5]
# =================================================
mat = loadmat("/content/DSB_results_n2_n3_n5_A1_vs_rest_0.92_p1.mat")
eta = mat[... |
cb8ca69e1a4be1562239e48cbf6b11fec5b4001d1d1dde074e81fd52a35120c9 | Python | 1,112 | 27 | import torch
def fuse_conv_and_bn(conv, bn):
# https://tehnokv.com/posts/fusing-batchnorm-and-conv/
with torch.no_grad():
# init
fusedconv = torch.nn.Conv2d(conv.in_channels,
conv.out_channels,
kernel_size=conv.kernel_size... |
de09c4bb3ec0b0111f0d3e7479b0bc5946e224187a13b8ced8f598a21876f04b | Python | 1,112 | 23 | import torch
from pff_model import PFFModel
from material_properties import MaterialProperties
from network import KAN, init_xavier
def construct_model(PFF_model_dict, mat_prop_dict, network_dict, domain_extrema, device):
# Phase field model
pffmodel = PFFModel(PFF_model = PFF_model_dict["PFF_model"],
... |
2a2e951d83cd8a1dc83dcf31eb9d952df456f9551bae0b90f3f0ee202103f6bc | Python | 1,113 | 32 |
class SetDict(object):
# set_dict(self, dTarget, dSource, bPreserve)
# Takes a target dictionary, and enters values from the source dictionary, overwriting or not, as asked.
# For example,
# dT={'a':1, 'b':2}
# dS={'a':0, 'c':0}
# Set(dT, dS, True)
# dT is {'a':1, 'b':... |
b1ec6899d2167fa8de3ce5f565f547ff94714693ab8408dec58c72f1775cca8e | Python | 1,113 | 32 | """Method-bank construction."""
import pytest
from crossda.core.method_bank import generate_method_bank
REQUIRED_COLUMNS = {
"pipeline", "feature", "classifier", "da", "dist_type",
"combiner", "mode", "space_id",
}
@pytest.mark.parametrize("mode", ["smoke", "mini", "svm_radial_add", "fair", "practical"])
d... |
74ae4b58e5e0009f610dd19e3420356659232bdcc5b7bdbcdb599f5159c31b44 | Python | 1,114 | 35 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import numpy as np
from numpy.typing import NDArray
from mattergen.common.data.dataset import BaseDataset
# Dataset transforms
# These transforms are used to modify the dataset in various ways, such as filtering out
# structures with missing pro... |
96a42f1d8d03a240a5dd611470705bbc085183fe82c1496c2485ea1e5cbf7580 | Python | 1,117 | 39 | import h5py
import nibabel
import numpy as np
import tifffile
from typing import Union
from voluseg._tools.constants import dtype
def load_volume(fullname_ext: str) -> Union[np.ndarray, None]:
"""
Load volume based on input name and extension.
Supports tiff, hdf5, and nifti formats.
Parameters
-... |
f5cdc07d7468a801d2e1960dcaa96951c61af80cc8d2f7b408c9e12c9878eb6b | Python | 1,118 | 45 | import argparse
import neuroglancer
import neuroglancer.cli
import numpy as np
def add_example_layer(state):
ix, iy, iz = np.meshgrid(
*[np.linspace(0, 1, n) for n in [100, 100, 100]], indexing="ij"
)
b = (
np.asarray(
np.floor(np.sqrt((ix - 0.5) ** 2 + (iy - 0.5) ** 2 + (iz -... |
0cd36b14be75a74d0f926e81ae9d868d90e1cc1f9a34f999e2f4903c18cbb9f8 | Python | 1,120 | 41 | #!/usr/bin/env python
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# 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 absolute_import
from __future__ import division
from __future__ import print_fu... |
10b083bbd951b0d3353ceab5780d716f14d5e608d0532cda11d37e8b8fb1c39a | Python | 1,121 | 28 | from __future__ import annotations
from st_risk.models.base import BaseSpatialModelRunner
from st_risk.models.cell2location_model import Cell2LocationRunner
from st_risk.models.destvi_model import DestVIRunner
from st_risk.models.precomputed_model import PrecomputedTableRunner
from st_risk.models.rctd_model import RCT... |
755f0e70a6da22fff224e1642297ce9152cac71137fcb38486774b3a5997ee4c | Python | 1,121 | 41 | from argparse import Namespace
from pathlib import Path
import glob
import os
def display_path(path):
try:
metadata = eval(
open(
Path(path) /
"args.txt").read().replace(
"\\",
"/"))
bins = metadata.bins
... |
75e83b95ab201155ae3a6b885f685675d8245331037c065e43d3062bc3ad4a9b | Python | 1,121 | 29 | """Shared session-roles schema helpers."""
from crossda.pipelines.session_roles import EMPTY_DIST, distance_fields, target_rows
DIST_KEYS = {"dist_to_session", "dist_est_method", "dist_est", "dist_lwr", "dist_upr"}
def test_empty_dist_is_all_none():
assert set(EMPTY_DIST) == DIST_KEYS
assert all(v is None f... |
61d640a024e45e837b12da9d2b7e8056dc51b2aeb7a8ec7d83a7052ae2f57cf3 | Python | 1,122 | 38 | """
DLBase: portable training utilities.
Heavy imports (e.g. PyTorch / Lightning) are **lazy** so ``dlbase.runtime_check`` can run
before optional dependencies are validated.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
__all__ = [
"TaskModule",
"apply_lightning_... |
6f1991ed8c1e4bd88cc52062fd9efa0a7b76c5e723adc94435374c256cfd40b5 | Python | 1,123 | 39 | import numpy as np
import pandas as pd
import pytest
from pgmpy.ci_tests import ModifiedLogLikelihood
@pytest.fixture
def test_mll():
df_adult = pd.read_csv("pgmpy/tests/test_estimators/testdata/adult.csv")
test = ModifiedLogLikelihood(data=df_adult)
return test
def test_discrete_tests(test_mll):
... |
94075441a8150510bd1bae53e55afae89452ceeacf864ea661bdd27895d4d7e3 | Python | 1,123 | 45 | from collections.abc import Iterable
from itertools import chain, combinations
def _variable_or_iterable_to_set(x):
"""
Convert variable, set, or iterable x to a frozenset.
If x is None, returns the empty set.
Parameters
---------
x : None, str or Iterable[str]
Returns
-------
f... |
ad85b17d55dbd626218413c9ca97b4d7ab1a22ded539da26ba7f1e7464d1a223 | Python | 1,123 | 45 | # encoding: utf-8
"""
@author: Jiayang Chen
@contact: yjcmydkzgj@gmail.com
"""
from .batch_converter import BatchConverter
def LofD_to_DofL(raw_batch):
"""
list of dict to dict of list
:param raw_batch:
:return:
"""
batch_size = len(raw_batch)
example = raw_batch[0]
new_batch = {}
... |
4a60986e171dc9a078a9e5a53b41a2b1ea58c93e94aa4ce293cdedb790270de2 | Python | 1,124 | 23 | from .utils import int_or_str # noqa: F401
from .utils import check_is_file # noqa: F401
from .utils import check_is_dir # noqa: F401
from .utils import path_to_datetime # noqa: F401
from .utils import get_expname # noqa: F401
from .utils import get_effective_num_gpus # noqa: F401
from .utils import get_effective... |
8bc3b53a12d299bcaf04ff5f4b414dc65550847e8fbf8da68b09c232e5cdafc3 | Python | 1,129 | 22 | #!/usr/bin/env python3
# MIT License
#
# Copyright 2025 Broad Institute
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use... |
408cf3e2adbc22b7e467d0785e097dce527e8dcadf1115f135e107a87bf593c9 | Python | 1,130 | 39 | from __future__ import annotations
from typing import TYPE_CHECKING
from poetry.console.commands.env_command import EnvCommand
from poetry.console.commands.group_command import GroupCommand
from poetry.utils.password_manager import PoetryKeyring
if TYPE_CHECKING:
from cleo.io.io import IO
from poetry.insta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.