sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
2b849c48613d301ff450fd569c85a87b561d5209d400145f0f5dcde9c5dcc253
Python
794
30
"""Register UNet model (standalone Simulation + CID package).""" from __future__ import annotations from omegaconf import DictConfig from dlbase.registry import register_model def _register_builtin_models() -> None: def assert_unet(cfg: DictConfig) -> None: from models.unet.model_task_datase...
c8baa6b5529a0d34e382dca85f06e827c90cca60ac7e259c623435b2dba596db
Python
794
22
import argparse import json from collections import defaultdict import os from tqdm import tqdm import sys import subprocess import re if __name__ == "__main__": parser = argparse.ArgumentParser(description='Example argument parser') parser.add_argument('--dump', type=str) parser.add_argument('--model', ty...
e888ae358729fb380c1855b51c8766d70a5fc6659ca763c31c87bfbcb8b85c44
Python
794
18
# Nearly all of the code here comes from the original Lucid library # Copyright 2018 The Lucid Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://ww...
c96d08437388ff30580953d18ad7812fe680dc082b0b709d59641f647fddd169
Python
795
22
"""Forwarding for NCBI taxonomy identifiers NCBI has since retired. A taxid cached from an outside source can predate the taxonomy dump on disk. Reading such a taxid without forwarding it through ``merged.dmp`` first risks reading one taxon as two, or gold nothing current can match; any caller of a raw NCBI taxid shou...
e0b545a8f89b15302a56c2a7e829b06ffffa33186cfdc8b520cd03bf1f29be99
Python
796
29
#!/usr/bin/env python3 # 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 unittest import torch try: import huggingface_hub except ImportError: huggingface_hub = None from fai...
9a4341e698aa4beae6e42f35f52264a63587e14a1a279e19ce8da9d56ea485e9
Python
797
30
import torch import torch.nn.functional as F class SwishImplementation(torch.autograd.Function): @staticmethod def forward(ctx, i): ctx.save_for_backward(i) return i * torch.sigmoid(i) @staticmethod def backward(ctx, grad_output): sigmoid_i = torch.sigmoid(ctx.saved_variables[...
644104a5ef3e66963f52d3522ebda25d99b0458b965134c6a4f3b4a9b0682540
Python
799
15
from dual_echo_pcasl_ETLAS2_scripts import motion_correction_to_template import click @click.command() @click.argument('subject') @click.option('--rawdata', default="/mnt/projects/ETLAS2/data/rawdata") @click.option('--dual_echo_pcasl_folder', default="/mnt/scratch/projects/ETLAS2/data/derivatives/dual_echo_pcasl") @...
6ca0c6abed6ad0250144da501c32f78fcdb2d41f2baae0d36ac8b4e8110e8e11
Python
799
34
from pgmpy.datasets._base import BaseDataset class IQBrainSize(BaseDataset): """ References ---------- - :footcite:t:`cmu_iqbrain` """ _tags = { "name": "iq_brain_size", "n_variables": 9, "n_samples": 20, "has_ground_truth": False, "has_expert_knowledge...
0e589381ccb09e4ff7bdfa92e6f2ab7fdd8d848fa202da44205968cf8a1824fd
Python
800
25
import torch def get_grad(y,x)->torch.Tensor: '''计算单个y对x的偏导数''' return torch.autograd.grad(inputs = x, outputs = y, grad_outputs=torch.ones_like(y), retain_graph=True, create_graph=Tr...
554dbb18e578b3e8d87954dd1ab03c6bed34f08f159b50e6d6d79452fa654ca3
Python
800
32
from setuptools import setup, find_packages with open('evo/version.py') as infile: exec(infile.read()) with open('README.md') as f: readme = f.read() with open('requirements.txt') as f: requirements = f.read().split('\n') sources = { 'evo': 'evo', 'evo.scripts': 'scripts', } setup( name='ev...
186541de5364717d214a6f9de6b4d735a5cde75da1e2bd22980e8e1adfc8e316
Python
802
25
""" Custom Exceptions Used In Autonomouse Schedule """ """ Copyright (c) 2019, 2022 [copyright holders here] This file is part of NoSeMaze. NoSeMaze is free software: you can redistribute it and/or modify it under the terms of GNU General Public License as published by the Free Software Foundation, either version 3...
46567c38c17e9f39e56b8f54b6f7907f7b168dba1ae89d93336a1dd9f542828f
Python
802
37
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from vlpp.utils import add_suffix from vlpp.registration import applyAnat2Tpl def main(): os.mkdir("anat") os.mkdir("pet") os.mkdir("centiloid") anat = "${anat}" atlas = "${atlas}" pet4070 = "${pet4070}" pet5070 = "${pet5070}" #cen...
b81c8469f047a482b6876f307af373a5303ff7f10b202180a21b963ced7a997d
Python
802
23
from argparse import Namespace from pathlib import Path import numpy as np def get_extraction_mz_list(extraction_folder): extraction_args = eval( open( Path(extraction_folder) / "args.txt").read()) bins = extraction_args.bins extraction_star...
b58eb2d83c0f3c6c72503d7d65870e888937321e3b2fc86266e92236d232e923
Python
803
20
from torch.optim.lr_scheduler import _LRScheduler class PolyLRScheduler(_LRScheduler): def __init__(self, optimizer, initial_lr: float, max_steps: int, exponent: float = 0.9, current_step: int = None): self.optimizer = optimizer self.initial_lr = initial_lr self.max_steps = max_steps ...
cce904aef04ea4115227263eb2bfd7ec6bce0caf7993a610ad0d25224109b6ff
Python
803
26
import matplotlib.pyplot as plt import numpy as np import loompy def cell_cycle(ds: loompy.LoomConnection, out_file: str) -> None: cc = ds.ca.CellCycle tsne = ds.ca.TSNE plt.figure(figsize=(12, 5)) plt.subplot(121) plt.scatter(np.arange(cc.shape[0]), 100 * cc, marker=".", s=5) plt.ylim(0, 5) plt.hlines(1, 0, ...
fc8543bc65521ce4ac5d7a01754f189ff953c716e1873b2a0fde1b981392f95d
Python
803
36
import numpy as np from fairseq.data import FairseqDataset class DummyDataset(FairseqDataset): def __init__(self, batch, num_items, item_size): super().__init__() self.batch = batch self.num_items = num_items self.item_size = item_size def __getitem__(self, index): ret...
a44d4995eaa13daab9df9f60090dfc57828ff904768e4bd22b7018adafa74f95
Python
804
42
from typing import List from torch import distributed def barrier(): if distributed.is_initialized(): distributed.barrier() else: pass def broadcast(data, src): if distributed.is_initialized(): distributed.broadcast(data, src) else: pass def all_gather(data: List, s...
cdd08191cfac6a74137ff9fd923e542967e55d1f16a0ff42a8f0361f5c318ce9
Python
805
28
from pathlib import Path import pytest @pytest.fixture def specific_dataset_path(specific_config_toml): """Returns a function that will return the ``dataset_path`` corresponding to the ``prep``ared dataset from a specific configuration file, determined by characteristics specified by the caller: ...
7a9625e6cedc96670bd53ce9ce0f3f80ec13617b87f48de16b047ad776d46628
Python
808
29
#!/usr/bin/env python -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. """ Usage: $ python misc/get_sample_size.py <input_file> > <output_file> <input_file> contains list of w...
8dbe51b9b0d3470e091036c32d8445268ebdd23bb93eca800300b68399919c26
Python
810
33
import pandas as pd from src.dfer.pfer_detection import signal_specs def test_option_five_single_output_uses_signal_as_pfer_baseline(): frame = pd.DataFrame( { "dFoF_465": [0.1, 0.2], "dFoF_405": [float("nan"), float("nan")], } ) frame.attrs["dfer_option"] = 5 ...
428b0e8976359bd35b5aa51921a6c6a0532e4e19aabc2b13e367a7e96a27077c
Python
811
24
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from typing import List import pytest from mattergen.common.utils.globals import MAX_ATOMIC_NUM from mattergen.property_embeddings import ChemicalSystemMultiHotEmbedding @pytest.mark.parametrize("chemical_system", [["Li", "O"], ["Li", "O", "F...
5625fb55b4faa5f506ebd4851289f086ba366106c2cbdee472370a59be4d8519
Python
811
23
"""module that contains helper function to load metrics Metrics in separate packages should make themselves available to vak by including 'vak.metrics' in the entry_points of their setup.py file. For more detail on entry points in Python, see: https://packaging.python.org/guides/creating-and-discovering-plugins/#usin...
00f308040e9e085b352e13638fc9765a9a9c53adea8922ba2792d9da4f1c5430
Python
812
59
from . import ( __main__, cli, common, config, datapipes, datasets, eval, learncurve, metrics, models, nets, nn, plot, predict, prep, train, transforms, ) from .__about__ import ( __author__, __commit__, __copyright__, __email__, __...
91457589ca3a16036ecd51b9674f8c3933492841be81f02eb9ddcfb206df1c87
Python
812
20
# 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...
cb51fa607a8d43f109cd733c050167db6d972695ffdf03444c62b6dd4a4cb22d
Python
812
29
from transformers import PreTrainedTokenizer class scMulanTokenizer(PreTrainedTokenizer): def __init__(self, chars): super().__init__() self.chars = chars self.stoi = { ch:i for i,ch in enumerate(self.chars) } self.itos = { i:ch for i,ch in enumerate(self.chars) } def _tokeniz...
ed9d33983686f06d26a6ef1a47e63e3abd136c027aee63f1b9fd26c3aa829842
Python
812
34
from pgmpy.datasets._base import BaseDataset class HTRU2(BaseDataset): """ References ---------- - :footcite:t:`uci_htru2` """ _tags = { "name": "htru2", "n_variables": 9, "n_samples": 17898, "has_ground_truth": False, "has_expert_knowledge": True, ...
3356b977d942cdcfab1c717bcd229d81cbb31367af4334fd352a6f1250f5a8c4
Python
813
31
from __future__ import annotations from collections.abc import Sequence import pandas as pd DEFAULT_REFERENCE_CELLTYPE_COLUMNS = ( "cellType_k", "cellType_broad_k", "cellType_hc", "cellType_broad_hc", "cellType_layer", ) def intersect_gene_names(visium_index: pd.Index, ref_index: pd.Index) -> p...
27c2fcc1615bc31f706f955886b33db9ec615800d6e030052e92db1040c6a9bf
Python
814
15
import torch.optim as optim import numpy as np def get_optimizer(params, optimizer_type: str="LBFGS"): if optimizer_type == "LBFGS": optimizer = optim.LBFGS(params, lr=float(0.5), max_iter=20000, max_eval=20000000, history_size=250, line_search_fn="strong_wolfe", ...
d94aa63e487575394ffe8d958bf0d5abf07240b0ae09bba319a572e828784c40
Python
814
27
import scipy from scvi.data import synthetic_iid from scvi.external import SCAR def test_scar(): n_latent = 5 adata = synthetic_iid() adata.obs["batch"] = adata.obs["batch"].cat.rename_categories(["batch_2", "batch_3"]) adata.X = scipy.sparse.csr_matrix(adata.X) SCAR.setup_anndata(adata, batch_...
289ff32ee29f03ea1c4330a3414c1dcc2048886163215115aa1745e31d7c7fc0
Python
815
20
from .colors import colors75, colorize, tube_colors, Colorizer from .midpoint_normalize import MidpointNormalize from .manifold import manifold from .markerheatmap import markerheatmap from .factors import factors from .TF_heatmap import TF_heatmap from .radius_characteristics import radius_characteristics from .batch_...
ba9891d5def7983161e95122b3815464096a14bcc7c3931dcfc4c07aedd7b1a0
Python
819
18
def process_txt_file(input_file, output_file): with open(input_file, 'r') as infile, open(output_file, 'w') as outfile: for line in infile: # 提取文件名和坐标信息 parts = line.strip().split(' ') filename = parts[0].split('\\')[-1].split('.')[0] # 提取文件名部分,去掉路径和后缀 ...
35b1a58ebbfdea5dc4f431905891c321c47705637d450ba638071cb123709c6a
Python
820
23
from __future__ import annotations import logging class QtTextHandler(logging.Handler): def __init__(self, text_widget) -> None: super().__init__() self.text_widget = text_widget def emit(self, record: logging.LogRecord) -> None: if self.text_widget is None: return ...
a2e645a3bd81e557bb5a8c254405e3c7676c8ea25b7714c0bdf96ed935a6fa83
Python
820
32
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from typing import Iterable, Union import torch def get_grad_norm( parameters: Union[torch.Tensor, Iterable[torch.Tensor]], norm_type: float = 2.0 ) -> torch.Tensor: """ Adapted from: https://pytorch.org/docs/stable/_modules/torch/...
f2e569233e0ea795e5220834c6adc9fe75cf3513d3300d00143b9f6236758c28
Python
820
34
from pgmpy.datasets._base import BaseDataset class GaltonStature(BaseDataset): """ References ---------- - :footcite:t:`mcgill_galton` """ _tags = { "name": "galton_stature", "n_variables": 5, "n_samples": 898, "has_ground_truth": False, "has_expert_kno...
3b8fb0c964b9a2a4cddd4916a22180cc4cac07e6cba9dc6668f255465f878a20
Python
822
21
# # Copyright 2017 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government # retains certain rights in this software. # # See LICENSE for full license details # from .base_parameters import BaseParameters, BasePairedParameters from ...
ebd2a086074953a70629f8751cb9408f2a7c5ea1030cc70156e5b63a19009d62
Python
822
27
import random import unittest from unittest.mock import patch from pyecharts import options as opts from pyecharts.charts import Scatter3D from pyecharts.faker import Faker class TestScatter3D(unittest.TestCase): @patch("pyecharts.render.engine.write_utf8_html_file") def test_scatter3d_base(self, fake_writer...
d3217cc2c8f577b57dcbbdb5ed0f508ac8f829cd833cdf13aa9ec937c2890d25
Python
823
16
# scSGL - a python package for fene regulatory network inference using graph signal processing based # signed graph learning # Copyright (C) 2021 Abdullah Karaaslanli <evdilak@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
52e198c087ad756fc23f9379787b53d9b2d669c049e112eb712da0d6c12f3198
Python
824
35
from __future__ import annotations from typing import TYPE_CHECKING import pytest if TYPE_CHECKING: from cleo.testers.command_tester import CommandTester from tests.types import CommandTesterFactory @pytest.fixture() def tester(command_tester_factory: CommandTesterFactory) -> CommandTester: return co...
4c3c2a4daa01158f509340e3bb6ae24f689bcd1f7714a2c1132878d7bebed1b8
Python
825
32
#!/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 fileinput import sacremoses def main(): parser = argparse.ArgumentParser(description="...
60aa90016cc6e4c368d3eccc0a9cf2722ca0590e7183714b8eb9c7cf4f948862
Python
825
25
# Authors: Christian O'Reilly <christian.oreilly@sc.edu> # Scott Huberty <seh33@uw.edu> # License: MIT """Launching point for Lossless QC Dash app.""" import dash import dash_bootstrap_components as dbc from pylossless.dash.qcgui import QCGUI def get_app(fpath=None, project_root=None, disable_buttons=False,...
8b0e9752c461ce68e7f294547d6e58fdfc5e3c444dc8bc418a5baa11c0199bdb
Python
825
30
# encoding: utf-8 """ @author: sherlock @contact: sherlockliao01@gmail.com """ import logging import os import sys def setup_logger(name, save_dir, logfile_suffix, distributed_rank): logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) # don't log results for the non-master process if dis...
19926fc6bb936047cd95321ea83b6503877beab6708b10b11eb53e82b9d9dca1
Python
827
33
"""Convert every .mp4 in a folder to raw .avi via ffmpeg. Requires ffmpeg on PATH. Example: python dlc/convert_mp4_to_avi.py /path/to/folder """ import argparse import os import subprocess def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelp...
2132138810f77c9ea4831c66197105bad5a60776a751c8a1b5f182c47b220455
Python
827
34
"""Generate JSON schemas from Pydantic models in the d3types package. This module provides functionality to automatically generate JSON schemas for all Pydantic BaseModel subclasses defined in the d3types module. Example: $ python generate_json_schemas.py The script pretty-prints the JSON schema of each Pydantic...
5c7c46b906c3de1b45e7d34f7d085adcfc5e910c8f3a7c6ec060402a51ca22c3
Python
828
28
# 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 def _normalize_spaces(line): return " ".join(line.split()) def main(): parser = argparse.ArgumentParser...
e77d3d1f36b9093c610aded6dc29024cf778885fc4448355626cfe8042f12882
Python
828
43
"""The :mod:`vak.common` module contains helper or utility functions that are used in multiple other modules, e.g., validators or logging functions. If a helper/utility function is only used in one module, it should live either in that module or another at the same level. See for example :mod:`vak.prep.prep_helper` or...
ab2b9458825aa62ee668f1d16e38001070e015c8a13f5ddd58051e80175c066e
Python
829
29
# Copyright (c) Facebook, Inc. All Rights Reserved import numpy as np from torch.utils.data.sampler import Sampler class RandomSequenceSampler(Sampler): def __init__(self, n_sample, seq_len): self.n_sample = n_sample self.seq_len = seq_len def _pad_ind(self, ind): zeros = np.zeros(...
b452fb1d4bd0d36d92448b9b9b2842869e0d5b1e7b869bd39b7ec891bfbfa297
Python
829
32
#!/usr/bin/env python # Author_and_contribution: Jieran Sun; Implemented visualization import argparse import os from pathlib import Path import shutil # TODO adjust description parser = argparse.ArgumentParser(description="Merging all visualization pdfs into one big pdf") parser.add_argument("-d", "--out_dir", he...
e61e008cb386105b0879b9fec0c8b3cbb325257d2ff338256069e48a39a5e37b
Python
829
27
import jax import jax.numpy as jnp import numpy as np from laplacian_testcase import LaplacianTestCase from folx import forward_laplacian class TestForwardLaplacianJvp(LaplacianTestCase): def test_customjvp(self): @jax.custom_jvp def fn(x): return jnp.sin(x) @fn.defjvp ...
cee0a211c311ae9c153a896f71755e04d81d11cc12a94fd7ab41abb4f19f724d
Python
830
26
import numpy as np import loompy import logging from .heatmap import Heatmap def markerheatmap(ds: loompy.LoomConnection, dsagg: loompy.LoomConnection, out_file: str = "", layer: str = "pooled") -> None: if layer not in ds.layers: logging.warn(f"Cannot plot heatmap for layer {layer} because the layer doesn't exist...
fa89c8e349060ce4a19b8f6f9453a75c6cfbea1a5f6d23391db6bc46cf44f45b
Python
831
31
# File names and column IDs scd41_file = ["Temp_RH_CO2", ["Timestamp", "Temp[°C]", "RH[%]", "CO2 [ppm]"]] apds_file = ["Light", ["Timestamp", "ALS [digits]"]] spg_file = ["VOC", ["Timestamp", "VOC Raw [digits]", "VOC Index [digits]"]] mp_file = ["Microphone", ["Timestamp", "Microphone Amplitude [digits]"]] mics_file = ...
02f453e52cfaec65e34132923add80e7132f188706680fa86d7bd884976e09ef
Python
832
26
import torch class TriangularCausalMask(): def __init__(self, B, L, device="cpu"): mask_shape = [B, 1, L, L] with torch.no_grad(): self._mask = torch.triu(torch.ones(mask_shape, dtype=torch.bool), diagonal=1).to(device) @property def mask(self): return self._mask cla...
270f2151f404876b09d049a162dc799a579fa14ef6d20458523d1993419707ec
Python
833
34
from pgmpy.datasets._base import BaseDataset class DryBean(BaseDataset): """ References ---------- - :footcite:t:`uci_dry_bean` """ _tags = { "name": "dry_bean", "n_variables": 17, "n_samples": 13611, "has_ground_truth": False, "has_expert_knowledge": T...
45b3cc7e6b3b3571eba17ddd388a5160f35fc66579f84d3552fc7db9e6a76cfc
Python
833
27
from brenda_references.docdb import BrendaDocDB from tqdm import tqdm import re if __name__ == "__main__": nondigit = re.compile(r"[^\d]") count = 0 with BrendaDocDB() as docdb: for doc in tqdm(docdb.references): if doc["pubmed_id"]: try: int(doc["pu...
7a761246d870aa9fcd3c705693d5b03a84619e6b35ada2c98105f01040a8ffd0
Python
833
15
from . import GTExGenotype from . import DosageGenotype from . import ModelTrainingGenotype from .. import Exceptions def genotype_by_chromosome_from_args(args, snps=None): if args.gtex_genotype_file: return GTExGenotype.gtex_geno_by_chromosome(args.gtex_genotype_file, args.gtex_snp_file, snps, args.gtex_...
ab41057b8d648691632ce25d138c4ce690086e45fae3606f538edacec7ac8203
Python
833
35
from pgmpy.datasets._base import BaseDataset class Hitters(BaseDataset): """ References ---------- - :footcite:t:`islr_hitters` """ _tags = { "name": "hitters", "n_variables": 20, "n_samples": 322, "has_ground_truth": False, "has_expert_knowledge": Fals...
38f1a1b262ca832090b94495f2134587081089b77b2c3dbf3a663d9e8a056567
Python
836
25
from mdt import CompositeModelTemplate __author__ = 'Robbert Harms' __date__ = "2015-06-22" __maintainer__ = "Robbert Harms" __email__ = "robbert@xkls.nl" class VERDICT(CompositeModelTemplate): """Implements the VERDICT colorectal model, as in Panagiotaki et al Cancer Research 2014 paper. The diffusivity pa...
8656dd3f4b34b0b78c9de9ad45ef56ea921c7e70b75a332891ae50ff34cd268d
Python
836
23
import logging class Logger(object): def __init__(self,log_file_name,log_level,logger_name): # firstly, create a logger self.__logger = logging.getLogger(logger_name) self.__logger.setLevel(log_level) # secondly, create a handler file_handler = logging.FileHandler(log_file_...
8a7c1c35ad04e5a0977cb816471d432e4922655eb8e6e46d4e1f628feb845b59
Python
837
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. from fairseq.data.encoders import register_bpe from fairseq.data.encoders.byte_utils import ( SPACE, SPACE_ESCAPE, byte_encode, ...
8d116d8a8191ec1366c0a5b266ecc12762db7e2cfbc30626aae6c4752b677e71
Python
837
26
# 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 class LogSumExpMoE(torch.autograd.Function): """Standard LogSumExp forward pass, but use *posterior* for the backward. ...
99c7740a002b8e965745c7c6eb4a3c4871844775bb7cbf7941f9c9ad2c28a892
Python
838
30
"""Feature-local view state for telemetry alignment.""" from __future__ import annotations from dataclasses import dataclass @dataclass class TelemetryViewState: file_path: str = "" adjust_clustering: str = "" associated_temp_data: str = "" associated_act_data: str = "" light_off_time: str = "19...
67234f1e2b14f334ab7e1c5f3c19541d79e5546c69ded5eb5b374952638454af
Python
839
37
from pgmpy.datasets._base import BaseDataset class USCrime(BaseDataset): """ References ---------- - :footcite:t:`der_everitt_2002` - :footcite:t:`acswr_usc_dataset` """ _tags = { "name": "uscrime", "n_variables": 14, "n_samples": 47, "has_ground_truth": Fa...
7c4df5fee44f3de416606e8d04451fc66aa2e627aa3cb8bc63fa81abf5d73746
Python
841
19
import pandas as pd def test_func(): # test passes on pandas.__version__ == u'0.18.0' df = pd.DataFrame([[1, 2, 1, 1], [2, 2, 2, 2], [1, 2, 3, 1], [3, 2, 4, 2]], columns=['A', 'B', 'C', 'D']) assert all(df.duplicated('A', keep=False) ==...
f38e528e505bde8bcf1545940190ffa5e846c24b33e2dc868670c3501f91f34d
Python
841
27
""" Contains simple check functions """ import numpy as np def _check_1d_array_object(parameter, name_param): """ Checks whether given parameter is a 1d array like object, and returns a numpy array object """ if isinstance(parameter, (np.ndarray, list, tuple, np.matrix)): parameter = np.array...
addafe51d632841eecca684125f6aa0989775afa8820aba5c73479b0ffdecf8d
Python
843
25
# 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 . import BaseWrapperDataset class ColorizeDataset(BaseWrapperDataset): """Adds 'colors' property to net input that is...
e5ab6879be6a92245ee108f9b21b5c7102f26c9ef965a694ac306ff7b2156950
Python
843
34
# -*- coding: utf-8 -*- """ Created on Fri Feb 28 13:29:25 2025 @author: hanna """ import numpy as np def calcSSA(UA,UB): cov_shared_A = np.dot(UA,UA.T) cov_shared_B = np.dot(UB,UB.T) rB = np.linalg.matrix_rank(cov_shared_B) U, S, VT = np.linalg.svd(cov_shared_B) bB = U[:,:rB] #or...
ee935e3577f84f0d7860da892eeefdb41d8c702a8081089eabf035c09a0106f1
Python
843
38
import os.path __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__commit__", "__author__", "__email__", "__license__", "__copyright__", ] try: base_dir = os.path.dirname(os.path.abspath(__file__)) except NameError: base_dir = None __title__ = "vak" __su...
fdf40387834439700d91c9be63b1686c123a835f6cce0a91dfc1dfcbf1668aac
Python
843
23
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
c10f66d446e13a3b303ca8cb221a7d3e805216e7a934b79daf9b53c6a0c24019
Python
844
31
from dataclasses import dataclass, field from pathlib import Path from typing import List, Optional, Union @dataclass class Setting: """ The configuration for scBank :class:`DataBank`. """ remove_zero_rows: bool = field( default=True, metadata={ "help": "When load data fro...
e99f8aba6252b9e2734fb0032620a185f4b9d5c6adf3616b2b7a907d0552a933
Python
844
34
#!/usr/bin/env python3 # # 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 sys import sacremoses def main(args): """Tokenizes, preserving tabs""" mt = sacremoses.MosesTokeniz...
aa63994a48caf7c9f33c08c010d7c86e5cbfb2d97ebcfe686204339ef1ad1c21
Python
845
34
import sys import tensorflow as tf import numpy as np import tape.data_utils import json import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "1" # disable tensorflow info logging tf.enable_eager_execution() filename = sys.argv[1] funcname = sys.argv[2] outfile = filename.rsplit('.', 1)[0] + '.json' func = getattr(tape.d...
b0fe33a6a85cec4632dc8c2f0891b6ab3aec1675fc52bea757720009a4825734
Python
849
26
import numpy as np import pytest from moove.utils.label_utils import normalize_spectrogram class TestNormalizeSpectrogram: def test_zero_mean(self): spec = np.random.rand(64, 32) result = normalize_spectrogram(spec) assert abs(result.mean()) < 1e-6 def test_unit_variance(self): ...
7a446d3a58d45b3befcf816c97f0957c69cf5766f0e82db79a6221ccd4d442e5
Python
850
35
from pgmpy.datasets._base import BaseDataset class BostonHousing(BaseDataset): """ References ---------- - :footcite:t:`zhao_hastie_2019` - :footcite:t:`peerj_wine_quality` """ _tags = { "name": "boston_housing", "n_variables": 14, "n_samples": 506, "has_gr...
a1771b17b7113052ab380d3044ff62e7196350d66c0795d0f4e76c039e93796a
Python
850
29
#get drug features using Deepchem library import os import deepchem as dc from rdkit import Chem import numpy as np import hickle as hkl drug_smiles_file='../data/223drugs_pubchem_smiles.txt' save_dir='../data/GDSC/drug_graph_feat' pubchemid2smile = {item.split('\t')[0]:item.split('\t')[1].strip() for item in open(dr...
9d706ce1774a022b82f30a83bcb0746fa518bcc03562317fb22ffc486a3662d6
Python
851
22
import pandas as pd import json file_names = ['test_losses_TetraLoop_longer_bb.json'] feedback_types = ['1'] # Initialize an empty DataFrame columns = ['object_id'] #+ [f'({ft}, {nl})' for ft in feedback_types for nl in range(1, 6)] data = {col: [] for col in columns} df = pd.DataFrame(data) df['object_id'] = range(1...
afbcc0152fa9edacefc885b0d8ae2d0359b276a2fcb9f60c5a679694bb8d88e7
Python
851
26
import unittest from unittest.mock import patch from pyecharts.charts import PictorialBar class TestPictorialBarChart(unittest.TestCase): @patch("pyecharts.render.engine.write_utf8_html_file") def test_pictorialbar_base(self, fake_writer): c = ( PictorialBar() .add_...
b1787af16518eac6647932e89aefe3461d2930e2e766220fc97151500a5f85af
Python
851
34
from pgmpy.datasets._base import BaseDataset class PimaDiabetes(BaseDataset): """ References ---------- - :footcite:t:`lella_2022` """ _tags = { "name": "pima_diabetes", "n_variables": 9, "n_samples": 768, "has_ground_truth": False, "has_expert_knowledg...
c86c546065a29d82a2d9fa50270b1bba9477f36f729ba78eb34802428fe245cf
Python
851
25
"""Modules that act as activation functions.""" import torch class NormReLU(torch.nn.Module): """This module implements normalized ReLU activation, as used with the Encoder-Decoder Temporal Convolutional Model in [1]_. The output of the activation is normalized by the channel-wise maximum. .. [1] L...
d649ba1061fa3c6686b80a07d6b76d42ee3d6e819b20bd0c619bde395f0e8ead
Python
852
22
# Copyright 2022 InstaDeep Ltd # # Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://creativecommons.org/licenses/by-nc-sa/4.0/ # # Unless required by applicable law or a...
5a804893aa0edc2b3e1daad50fc5ea693c4f44f2496f2d67073f4c0ebf15d293
Python
853
23
# 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...
e98d86f41fac34f9b8a54c0739fa57cc20118bd18f983904deca8f33de76457c
Python
853
26
import pytest import vak.common.converters @pytest.mark.parametrize( ("toml_value", "labelset"), [ ("abc", {"a", "b", "c"}), ("1235", {"1", "2", "3", "5"}), ("range: 1-3, 5", {"1", "2", "3", "5"}), ([1, 2, 3, 5], {"1", "2", "3", "5"}), (["a", "b", "c"], {"a", "b", "c"}...
4b467613a7a51003fd15e22cea113a4cf66d3bb7a99eb57189777d6665ce2683
Python
854
31
import setuptools setuptools.setup( name="bigstream", version="5.1.0", author="Greg M. Fleishman", author_email="greg.nli10me@gmail.com", description="Tools for distributed alignment of massive images", url="https://github.com/JaneliaScicomp/bigstream", license="BSD-3", packages=setupto...
c0f8bbaa828221c2940e116928a13d2cdc5ff4abdfe87d69ccfdf53774e7fc56
Python
855
29
from pathlib import Path from huggingface_hub import constants, hf_hub_download HF_ETAG_TIMEOUT = max(constants.HF_HUB_ETAG_TIMEOUT, 30) constants.HF_HUB_DOWNLOAD_TIMEOUT = max(constants.HF_HUB_DOWNLOAD_TIMEOUT, 30) def read_hf_file( *, repo_id: str, filename: str, repo_type: str | None = None, ...
0fc244ed1e6405474a55da586e73ff89ee703ff081a918a3049eb70863fa1563
Python
856
36
from __future__ import annotations from src.dashboard.main import ( _is_pyside6_available, build_parser, logger, ) from src.dashboard.main import run_dashboard as _run_dashboard from src.dashboard.main import run_tool_window as _run_tool_window def run_dashboard() -> int: return _run_dashboard() de...
ef4e40b724695afd796ac84bda0885e3bec50c0c579666c6c57f0aff61452dc4
Python
856
27
# 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 .task import Task class VLMTask(Task): """A VLM task for reproducibility. the collator split subsamples into two s...
4efece7600494d09d7219c3ea8fa1e4d2b646fa2bd9bbd025029953354c37a69
Python
859
21
from pytorch_grad_cam.base_cam import BaseCAM from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection_kernel class KPCA_CAM(BaseCAM): def __init__(self, model, target_layers, reshape_transform=None, kernel='sigmoid', gamma=None): super(KPCA_CAM, self).__init__(model, ...
600eda7749f2c71e0811a42d4d2e15ad84f15ebdd3c1ced273e3999ee246271f
Python
859
32
from __future__ import annotations import os import shutil from setuptools import Distribution from setuptools import Extension from setuptools.command.build_ext import build_ext extensions = [Extension("extended.extended", ["extended/extended.c"])] def build(): distribution = Distribution({"name": "extended"...
a60c4f21dafe110e1022d3f8e066c6621ba32a82316822e678c2370f4e6eb20a
Python
861
23
import torch.nn as nn class DWConv(nn.Module): def __init__(self, in_plane, out_plane): super(DWConv, self).__init__() self.depth_conv = nn.Conv2d(in_channels=in_plane, out_channels=in_plane, kernel_size=3, ...
595c8bba544d26f7536a9a37cbd58a60e6a84b2d7965987a177a2cfc57bd2387
Python
862
33
from __future__ import annotations from typing import TYPE_CHECKING from poetry.utils._compat import decode if TYPE_CHECKING: from subprocess import CalledProcessError class EnvError(Exception): pass class IncorrectEnvError(EnvError): def __init__(self, env_name: str) -> None: message = f"En...
1cc4ce15839f42fb7820a8e123f34fd363183753f757c4c07c264214035b343e
Python
863
32
from cellpose import models, io # Define the directory and parameters directory = "/run/user/752424298/gvfs/smb-share:server=imgserver,share=images/CONFOCAL/IA/Projects/2024/2024_10_17_lalvaroe_0/output/cellpose" pretrained_model = "cyto3" stitch_threshold = 0.25 flow_threshold = 0.8 cellprob_threshold = -1.0 chan = 2...
c0e186583c363d509138d760c2cf5f234477ae0db94b8847c9752fee4dccb9c3
Python
863
33
# 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. from torch import nn class SamePad(nn.Module): def __init__(self, kernel_size, causal=False): super().__init__() if cau...
1aed1682b78fddd8d19506a711f775e53596c5ea55595216a2121660e12e1a53
Python
864
35
from pgmpy.datasets._base import BaseDataset class HungaryChickenpox(BaseDataset): """ References ---------- - :footcite:t:`rozemberczki_2021` - :footcite:t:`uci_hungarian_chickenpox` """ _tags = { "name": "hungary_chickenpox", "n_variables": 20, "n_samples": 522, ...
76c5c0ef76acf3377c889f60b47375d6b0e1e61e6bc144c14e8c0b28d4dd60f5
Python
866
31
from os.path import join import numpy as np from matplotlib import pyplot as plt from upsetplot import from_memberships from upsetplot import plot from setup import saving_dir def run(): fig = plt.figure(figsize=(8, 8)) data = np.array([795., 27., 182., 7.]) plt.rcParams.update({'font.size': 14}) ex...
585af32a5ca6cef34dd94af4510a348c384740750f8a018aaade9609a4317c4f
Python
867
38
""" Installation script for mapalign """ from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md')) as f: long_description = f.read() with open(path.join(here, 'requirements.txt')) as f: requirements = [v...
93a57bf0897f913bb90792fb901876ff56d2e519e0f84278e33a241be7eed4c5
Python
867
34
from pgmpy.datasets._base import BaseDataset class AutoMpg(BaseDataset): """ References ---------- - :footcite:t:`lopezpaz_2015` - :footcite:t:`uci_auto_mpg` """ _tags = { "name": "auto_mpg", "n_variables": 8, "n_samples": 392, "has_ground_truth": False, ...
c10e9d14d326e9611373d39bb5c394185108df2654a8fd5345011f8b37899592
Python
867
27
import os import pytorch_lightning as pl from pathlib import Path from pytorch_lightning.callbacks import ModelCheckpoint class PeriodicCheckpoint(ModelCheckpoint): def __init__(self, every: int, dirpath: str): super().__init__() self.every = every self.dirpath = dirpath if not os...
fb36afcceb28027981cfd83fd486a2c963132e476c91739eac8e3d6c7f54f119
Python
867
43
from __future__ import annotations from typing import TYPE_CHECKING import pytest if TYPE_CHECKING: from pathlib import Path @pytest.fixture def pyproject_toml(tmp_path: Path) -> Path: path = tmp_path / "pyproject.toml" with path.open(mode="w", encoding="utf-8"): pass return path @pytest...
7be2e0e9fc36de096f9da959a7146955e20dd298a4dcce8f7159c7c5ee65c3c5
Python
868
24
import importlib import pkgutil from batchgenerators.utilities.file_and_folder_operations import * def recursive_find_python_class(folder: str, class_name: str, current_module: str): tr = None for importer, modname, ispkg in pkgutil.iter_modules([folder]): # print(modname, ispkg) if not ispkg...
9a87858456db1779a7524d731a3f3c1d09b4974d1fe815fb34458f515a2a6bbe
Python
868
34
from valids import parser, main as valids_main import os.path as osp args = parser.parse_args() args.target = "valid_accuracy" args.best_biggest = True args.best = True args.last = 0 args.path_contains = None res = valids_main(args, print_output=False) grouped = {} for k, v in res.items(): k = osp.dirname(k) ...
ba45c4a8d9b4e340723320adadf679eac323b3ca3acfbd14afb8585935435b0e
Python
868
20
import haiku as hk import jax import jax.numpy as jnp class DeterminantApproxEqualInit(hk.initializers.Initializer): def __init__(self, n_determinants: int, stddev: float, noise_relative_level: float = 1e-3): self.n_determinants = n_determinants self.stddev = stddev self.noise_relative_lev...
0775eef7dfd37441237e0d93e3c6b45185f1e6303f0c237364792a5f88a92df2
Python
869
24
import importlib import pkgutil from batchgenerators.utilities.file_and_folder_operations import * def recursive_find_python_class(folder: str, class_name: str, current_module: str): tr = None for importer, modname, ispkg in pkgutil.iter_modules([folder]): # print(modname, ispkg) if not ispkg...