sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
2f8e7e1ef70f5ca099c7da28619784061c9f9328db29ec7a49f8c7e3a03b5208
Python
869
22
import pytest from pgmpy.models import DiscreteBayesianNetwork from pgmpy.structure_score import K2 class TestK2: def test_score(self, small_df, small_df_models): m1, m2 = small_df_models scorer = K2(small_df) assert scorer.score(m1) == pytest.approx(-10.73813429536977) assert sco...
6c20538112be2805d007f8bd5b9a78e5312a7256c6e86881665c9ef276bcd9df
Python
869
31
import pytest from hashlib import md5 from time import localtime from vak.common.constants import RESULTS_DIR_PREFIX @pytest.fixture def previous_run_path_factory(generated_test_data_root): def _previous_run_path(model): learncurve_results_root = generated_test_data_root.joinpath( f"results...
00707aba5a8e58333681aa338be355ff11d86baa20555f5b69d455c80315d87b
Python
872
31
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser from params import train, explain modules = ['train', 'explain'] __version__ = "1.0.0" def main(): parser = ArgumentParser(prog='pglcn', formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('-v', '--...
7e814129042d5bf578b99feaaf977ca4593e145d7634c62f503972eef8c99fb0
Python
872
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 math import torch from torch.nn.modules.loss import _Loss class HeadSelectionLoss(_Loss): def __init__(self, args): sup...
860f59d9b316e3ca4968b11dc5f418867619117246a3e7bcbb2b9337d343c2be
Python
872
34
from pgmpy.datasets._base import BaseDataset class Superconductivity(BaseDataset): """ References ---------- - :footcite:t:`uci_superconductivity` """ _tags = { "name": "superconductivity", "n_variables": 82, "n_samples": 21263, "has_ground_truth": False, ...
97ad93d016347f970ee473dad3ab39b9bd3349123aa0204d5f87e2d24e2701bc
Python
872
37
from __future__ import annotations from typing import TYPE_CHECKING from tomlkit.toml_file import TOMLFile as BaseTOMLFile if TYPE_CHECKING: from pathlib import Path from tomlkit.toml_document import TOMLDocument class TOMLFile(BaseTOMLFile): def __init__(self, path: Path) -> None: super().__...
13210297b96d5e33de1bee71d01551b025a600ff36a4a400bc49b1474c3b362d
Python
873
22
# 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 src_ckpt = "/checkpoint/wnhsu/w2v/archived/hubert_base_ls960_it2.pt" ref_ckpt = "/checkpoint/wnhsu/w2v/hubert_icassp_oss_v3/iter...
a783833ba8dec9ecda3f99e132a43453fe82ad7d8868df3da81891d96d285522
Python
873
22
import pytest from pgmpy.models import DiscreteBayesianNetwork from pgmpy.structure_score import AIC class TestAIC: def test_score(self, small_df, small_df_models): m1, m2 = small_df_models scorer = AIC(small_df) assert scorer.score(m1) == pytest.approx(-15.205379370888767) assert...
d3c052c17cb91716fc73639453a824dd9b6d4ace720a3a4982748973b2832164
Python
873
22
import pytest from pgmpy.models import DiscreteBayesianNetwork from pgmpy.structure_score import BIC class TestBIC: def test_score(self, small_df, small_df_models): m1, m2 = small_df_models scorer = BIC(small_df) assert scorer.score(m1) == pytest.approx(-10.698440814229318) assert...
0876e69e118884c6d3dc164199c465ed42a11585f8a10e01668298ff867ceda5
Python
875
39
# ------------------------------------------------------------ # Get Python package versions for reporting summary # ------------------------------------------------------------ import sys import importlib.metadata as metadata import pandas as pd packages = [ "numpy", "pandas", "scipy", "scikit-learn"...
d173fa68ddf9758445cbe51a3d5d4c5b2fede86733d012f8b6611917a5320dbc
Python
875
35
from __future__ import annotations import pytest from cleo.commands.command import Command from cleo.exceptions import CleoLogicError from poetry.console.command_loader import CommandLoader class _DummyCommand(Command): name = "dummy" class _OtherCommand(Command): name = "other" def test_register_facto...
ef9e63f00816f4ec6f68778e77732b6e57e6f16857a1bd8997ee3f94bbe08779
Python
875
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 unittest from tests.speech import TestFairseqSpeech class TestXMTransformer(TestFairseqSpeech): def setUp(self): self.set...
453a8146fad9cad30636553a1960dda6d64a5388accf7db5048f38e854698324
Python
877
36
from pathlib import Path import os cwd = Path(".").resolve() print("running 'check_installation.py' from:", cwd) # Old versions of numpy/torch can prevent loading the .so files import torch print("torch:", torch.__version__) import numpy print("numpy:", numpy.__version__) import fairseq print("Fairseq installed a...
b9c5e6b05c86cc734857f0f106ad09d69df218580f7d82b7dbd372f5e6639477
Python
877
37
from __future__ import annotations from typing import TYPE_CHECKING from typing import ClassVar from cleo.helpers import argument from poetry.console.commands.command import Command if TYPE_CHECKING: from cleo.io.inputs.argument import Argument class EnvUseCommand(Command): name = "env use" descripti...
98afabedd16cb480de36500a1c6e660bedc3cda7071e594410a9b24cb7df785e
Python
878
26
"""Regression test for `entity_stats`'s dict/list entity-shape branching.""" import pathlib from tinydb import TinyDB from tinydb.storages import JSONStorage from scripts.statistics import entity_stats TESTDB_PATH = pathlib.Path(__file__).parent / "test_files/testdb.json" def test_entity_stats_reads_dict_and_list...
077c25967da0f276fa7003675c2ea925b3a52ef51a5cdf3cbb8516efffbbb12a
Python
879
27
"""Simulation Lightning datamodule wiring (registered via ``datasets.plugins``).""" from __future__ import annotations import os from typing import Any from omegaconf import DictConfig from datasets.Simulation import ImagePatchDataset def setup_simulation_datamodule(dm: Any, cfg: DictConfig, stage: An...
e8d2f2c52a0319bf4f38d4c79f70b59d2cc387c9499eda922b2bfb0b77fd1889
Python
880
34
from pgmpy.datasets._base import BaseDataset class YachtHydrodynamics(BaseDataset): """ References ---------- - :footcite:t:`uci_yacht_hydrodynamics` """ _tags = { "name": "yacht_hydrodynamics", "n_variables": 7, "n_samples": 308, "has_ground_truth": False, ...
7d96830a4c9ff0e01c333c1ad005fceafd569f469fa0823116b020a82d0f3946
Python
881
25
# Authors: Christian O'Reilly <christian.oreilly@sc.edu> # Scott Huberty <seh33@uw.edu> # License: MIT """Tests for topo_viz.py.""" import mne from pylossless.dash.mne_visualizer import MNEVisualizer # chromedriver: https://chromedriver.storage.googleapis.com/ # index.html?path=114.0.5735.90/...
875fa105527a64bfdd331d89ef1c384230e540320a4c3d766046f3c6aa9edb94
Python
881
35
from pgmpy.datasets._base import BaseDataset class AngristKrueger(BaseDataset): """ References ---------- - :footcite:t:`angrist_krueger_1991` - :footcite:t:`angrist_krueger_qob_dataset` """ _tags = { "name": "angrist_krueger_qob", "n_variables": 5, "n_samples": 32...
35a2363827506b30ee9b6bd6427979d55dca22ac79551eb2386ad635af5f7344
Python
882
31
import torch import torch.nn as nn class RadialFunction(nn.Module): ''' Contruct a radial function (linear layers + layer normalization + SiLU) given a list of channels ''' def __init__(self, channels_list): super().__init__() modules = [] input_channels = channels_list[0] ...
4c000bd13e3408a405d3afce0f75b0454bed0637ce260490c3b940309a7393bf
Python
883
39
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import shutil from glob import glob from vlpp.utils import gzipd, run_shell, run_matlab, TPL_PATH def main(): anat = "${anatInputNii}" nu = "${nuInputNii}" atlas = "${atlasInputNii}" dsts = [] for niigz in [anat, nu, atlas]: nii =...
fec55489f3c3ad5053275eae3b7a298ac9e34e0f66855c9a7821eb28a439477c
Python
884
29
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from tractseg.data import dataset_specific_utils from tractseg.experiments.dm_reg import Config as DmRegConfig class Config(DmRegConfig): EXP_NAME = os.path.basename(__file__).split(".")[0] DATASET = "HCP_all" DATASET_FOLDER = "HCP_preproc_all" ...
bd6e0067b210d30cd9ace7a4646eb1f233f92464a8e689b15fc07ee60f8d0c46
Python
888
31
# 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 ScalarBias(torch.autograd.Function): """ Adds a vector of scalars, used in self-attention mechanism to allow ...
fa25e2d8bbbdb835f469375d5a46d2bf53c432528196d2210c05228150d0bc70
Python
888
28
# @license # Copyright 2019 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...
7f6f28dfd6d15318e850f866222a656f0f9e206dcbd36eeffa29bb936aa1a33a
Python
890
31
"""Script for verifying the status of documents marked as not pmc_open.""" import asyncio from aiotinydb import AIOTinyDB from tinydb.middlewares import CachingMiddleware from tinydb.storages import JSONStorage from tqdm import tqdm from brenda_references.config import config from apiadapters.ncbi import AsyncNCBIAd...
ba256828fb127f1b2d073ad9678e7c0778998acaef2b16c0fc7125888c9a09b3
Python
890
17
__author__ = "alvaro barbeira" from .. import Exceptions from ..misc import KeyedDataSource def gtex_snp(gtex_snp_file, gtex_release_version): if not gtex_release_version: gtex_snp = KeyedDataSource.load_data(gtex_snp_file, "VariantID", "RS_ID_dbSNP142_CHG37p13", numeric=False) elif gtex_release_versi...
6bb9adc59f3fc9110f19d7dcb4940f1ed6eaf29aeeb30a85409115394b3bbb81
Python
893
44
from __future__ import annotations from typing import TYPE_CHECKING import pytest if TYPE_CHECKING: from pathlib import Path from cleo.testers.command_tester import CommandTester from poetry.utils.cache import FileCache from tests.types import CommandTesterFactory @pytest.fixture def tester(comm...
13d7c09fba4606bac79cb1f3fc2342f94a18b24515412432321689786b192167
Python
896
34
import gl gl.resetdefaults() kframesperrotation = 180 gl.meshcolor(210, 148, 148) gl.meshload('BrainMesh_ICBM152.lh.mz3') gl.edgeload('LPBA40.edge') gl.clipazimuthelevation(0.3, 0, 130) gl.nodesize(6, 1) gl.edgesize(3,1) gl.nodehemisphere(-1) gl.azimuthelevation(250, 35) gl.edgecolor('actc',1) gl.nodecolor('red',1) gl....
8bac7748573c9e69054b287d52d2958f289eb9728e67e5b179dfa3cb68164e55
Python
897
34
from __future__ import annotations from typing import TYPE_CHECKING from poetry.packages.dependency_package import DependencyPackage if TYPE_CHECKING: from collections.abc import Iterable from poetry.core.packages.dependency import Dependency from poetry.core.packages.package import Package class Pac...
9a2839b142f61c46b40f1b8900b6ed814a57fcede5b65dfdf4c5824f92aec441
Python
898
29
import numpy as np from pytorch_grad_cam.base_cam import BaseCAM from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection class GradCAMElementWise(BaseCAM): def __init__(self, model, target_layers, reshape_transform=None): super( GradCAMElementWise, ...
7f5a3a3787983eb4d23144559d6618a169d3d6fa75228cacbae2888d9cc5e0fd
Python
899
32
""" Simulate tree sequences """ import os import zarr import yaml import numpy as np import ts_simulators indices = yaml.safe_load(open(snakemake.input.yaml))["indices"] output_dir = os.path.dirname(snakemake.input.yaml) config = snakemake.params.simulator_config model = config["class_name"] simulator = getattr(ts_...
51e53b32fa01f821e98948a73eb39926d6bf5ba95bdee7378445dc4d380d9e52
Python
900
29
from . import fixtures # keep this import here, we need it for fixtures from .fixtures import * def by_slow_marker(item): return 1 if item.get_closest_marker('slow') is None else 0 def pytest_addoption(parser): parser.addoption('--dtype', action="store", default="float32") parser.addoption('--slow-last...
d9a4be7cc0d31959f48deb7675565f342349f8e8f3e0596f858eb562e0d90c4c
Python
900
24
import jax import jax.numpy as jnp from .loss import ClipMaskFunction from .types import Energy, Mask class MedianAbsDeviationClipAndMask(ClipMaskFunction): def __init__(self, width, exclude_width=jnp.inf, balance_grad=False): self.width = width self.exclude_width = exclude_width self.bal...
bb28df4e0feea6e827edced2f385aba468193b9b1fcbd50253cff6a3c999ba9d
Python
901
26
import streamlit as st from st_pages import add_page_title, get_nav_from_toml st.image("logo.png") main_page = st.Page("pages/help.py", title="Main") extract_page = st.Page("pages/extract.py", title="Import MSI data", icon='🔍') viewer_page = st.Page("pages/viewer.py", title="Viewer", icon='🔍') pipeline_page...
cfd0915945ee64739c9fd6ab764de7ea29ecc25a0618934185c4f46c2b913927
Python
901
24
# 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...
d322ee9b0c7b9dc790a65b7c18869346d2ea4c6d1910dfeaec15e22c4f3af37b
Python
901
28
import hashlib from pathlib import Path from typing import Union def calculate_checksum(filename: Union[str, Path]): assert Path(filename).exists(), f"file '{filename}' does not exist!" with open(filename, 'rb') as file_to_check: # read contents of the file data = file_to_check.read() ...
bbbcb5ad4f9b64d5c1ae959d3c5de4a4e2189cb6de3e15c0bbce17c76e161278
Python
902
30
from .. import Exceptions class ExpressionManager(object): def expression_for_gene(self, gene): raise Exceptions.ReportableException("Unimplemented expression_for_gene") def get_genes(self): raise Exceptions.ReportableException("Unimplemented get_genes") def enter(self): pass def exit(self): pass clas...
762c5765576a0cfa42f65aa3ca92f3cdb9d4be6bbef57b21d2b6914b2b0d5283
Python
903
31
import numpy as np import torch from .._constants import Nums @torch.no_grad() def spectral_stats(z: np.ndarray) -> tuple[float, float, np.ndarray]: """Compute spectral statistics on a batch of embeddings. Args: z: A batch of embeddings of size `(B, O)`. Returns: A tuple containing: ...
c1ea11843c33baaf9d6b0185d20f08086e919c0099b503065f54cc3f93317073
Python
903
31
"""Script for verifying the status of documents marked as not pmc_open.""" import asyncio from aiotinydb import AIOTinyDB from aiotinydb.storage import AIOJSONStorage from tqdm import tqdm from brenda_references.config import config from brenda_references.utils import CachingMiddleware from apiadapters.ncbi import A...
b62014021f93d6563ddb3e6512f93639fa7be9fa0e734320483942bad02bb22d
Python
904
41
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from vlpp.utils import filename2dict, add_suffix from vlpp.operation import computeSuvr, ImgStatsFromAtlas def main(): os.mkdir("pet") os.mkdir("centiloid") os.mkdir("stats") pet4070 = "${pet4070}" pet5070 = "${pet5070}" #centiloid ma...
94b010d3099c2fbe5189d7d5dde01555882a72128a376b4d2a5d27c6453ee71a
Python
906
38
from __future__ import annotations from typing import TYPE_CHECKING from poetry.installation.operations.operation import Operation if TYPE_CHECKING: from poetry.core.packages.package import Package class Install(Operation): def __init__( self, package: Package, reason: str | None = None, priority:...
f7363bce1b01e4be63b5b5ac215509ee67d5df9863ae0ac433bf2d4573228da0
Python
906
24
from typing import List import numpy as np def collate_outputs(outputs: List[dict]): """ used to collate default train_step and validation_step outputs. If you want something different then you gotta extend this we expect outputs to be a list of dictionaries where each of the dict has the same set o...
e2490901d38633f7d1907f003eff84e54880ba1eb79e72ca6435226bddc2d4ba
Python
907
33
# for backwards compatibility, this was moved to scvi.data from scvi.data import AnnTorchDataset from ._ann_dataloader import AnnDataLoader from ._anncollection import CollectionAdapter from ._concat_dataloader import ConcatDataLoader from ._custom_dataloaders import ( AnnbatchDataModule, MappedCollectionDataM...
d3ed843ba02ecff001a483193bdedc6449c88c97beac3249970b3df0ab53c5a1
Python
909
30
# 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 encoders def get_whole_word_mask(args, dictionary): bpe = encoders.build_bpe(args) if bpe is n...
e07873660ba65c57491da0f7ab91a31a0549acb40b2555a66a98ff86b5b8e571
Python
909
28
rec.begin( { "dimensions": {"x": [8e-9, "m"], "y": [8e-9, "m"], "z": [8e-9, "m"]}, "position": [3242.833251953125, 3334.499755859375, 4045.5], "crossSectionScale": 1, "projectionOrientation": [ 0.23160003125667572, 0.20444951951503754, -0.017615893...
e8103eb05d383366cfc3e876f8e8c7f2405ac65943a062a0851b78baa600b21a
Python
910
35
# import from plugins/cluster_view_styling.py """Show how to customize the styling of the cluster view with CSS.""" from phy import IPlugin from phy.cluster.supervisor import ClusterView class colorSelectorPlugin(IPlugin): def attach_to_controller(self, controller): # We add a custom CSS style to the Clu...
547ece721d45473b4b14c015922e6c3a0ce3d45c2144e8f93dd7654b2e108e17
Python
913
32
import numpy as np from pytorch_grad_cam.base_cam import BaseCAM class GradCAM(BaseCAM): def __init__(self, model, target_layers, reshape_transform=None): super( GradCAM, self).__init__( model, target_layers, reshape_transform) ...
c7c22fb37abe9a88a5e055bc52ef75f56fcf10998b0eb5aede0d53d292655171
Python
913
44
""" @file type.py @author Simon Yu @date 02/06/2023 @brief Global types. """ import enum class LogLevel(enum.Enum): all = 6 trace = 5 debug = 4 info = 3 warn = 2 error = 1 fatal = 0 off = -1 def __ge__(self, other): if self.__class__ is other.__class__: re...
ac6f9c60c28b520482b44099d4e6343f56ed026028305bf1be068d9d3153c4e0
Python
916
28
import numpy as np import glob import sys from sklearn.cluster import KMeans from sklearn.neighbors import KNeighborsClassifier import joblib paths = glob.glob(sys.argv[1] + "/*h.npy") groups = [] data = [] for path in paths: h = np.load(path) data.append(h) data = np.float32(data) Percentile R...
723a4dad95ade765a794f1a1ebc370822f7eaee477249478eb2abc484e77c5af
Python
917
23
import tskit import argparse ############################################################################### # read parameters ############################################################################### if __name__ == '__main__': parser = argparse.ArgumentParser(description="") parser.add_argument("-i", "--Input"...
f738db9c0b67f5b8aeee22c297bd849c3e64fd000a05d70ac5dedad971f5faad
Python
917
24
"""Guards on the ad-hoc scripts that read and write the data files.""" import pytest from brenda_references import data_paths as package from scripts import pull_data def test_every_script_agrees_with_the_package_on_the_data_dir() -> None: """One home for the path, or a writer misses every reader. `pull_da...
e118ac1eb48315c4741d610b74d48086ad7968e208722343bf64bc9b1bfce096
Python
918
27
import unittest from unittest.mock import patch from pyecharts import options as opts from pyecharts.charts import ThemeRiver class TestThemeRiverChart(unittest.TestCase): @patch("pyecharts.render.engine.write_utf8_html_file") def test_themeriver_basefake_writer(self, fake_writer): data = [...
49f8c0ab679f14c761198945db1694ada6b6e56ff28ab48668a00d4b50a2ba46
Python
919
34
from pathlib import Path import pytest REPO_ROOT = Path(__file__).parent.parent SCRIPTS_DIR = REPO_ROOT / "scripts" def pytest_addoption(parser): parser.addoption( "--pytorch", action="store_true", default=False, help="Run tests that require PyTorch CNN training (slow on CPU, ski...
aabcd42911438d06b19db1115b3f4ddc91c3c3d054dfc6ce170f362a26365aa5
Python
919
34
"""Common class for sequence datasets.""" from typing import Tuple import torch from Bio import SeqIO from .sequence import ( Sequence, CodonSequence, AminoAcidSequence ) class SequenceDataset(torch.utils.data.Dataset): """Common class for sequence datasets.""" def __init__(self, fasta_file: s...
caff940c03c6b9036ee6bcb5429a04b599715776e5e2ebff81b6efbb93713f3a
Python
920
23
import time import torch.utils.data as d import torchvision import torchvision.transforms as transforms if __name__ == '__main__': BATCH_SIZE = 100 transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) train_set = torchvision.datas...
f967189bdf6d55fbc04c8c78930a45e3fdfbfbd9eb9f5df6e1a15623d1deee6f
Python
920
28
from src.dashboard.catalog import ( DEFAULT_APP_ID, get_app_definition, iter_app_definitions, ) def test_feature_catalog_points_to_feature_entrypoints(): definitions = {definition.app_id: definition for definition in iter_app_definitions()} assert DEFAULT_APP_ID == "raw_analysis" assert defin...
8fbe899687137095b2c4ddd12fc5fdde46ba7bb78771a71497d3943cc0373edf
Python
924
29
"""Ownership boundaries for transient PyQt6 graphics items.""" from PyQt6 import sip from PyQt6.QtCore import pyqtSignal from PyQt6.QtWidgets import QGraphicsScene def release_item(owner, name): """Forget first, then detach and destroy an exclusively held temporary item. Scene ownership ends at removeItem()...
9601fd7f2e9369fc1c7d3eca241c9d7fa6c8bc5f6e093e56c5da28211976cf2d
Python
925
38
from pgmpy.datasets._base import BaseDataset class AppleWatchFitbit(BaseDataset): """ References ---------- - :footcite:t:`khan_2025` """ _tags = { "name": "apple_watch_fitbit", "n_variables": 18, "n_samples": 6264, "has_ground_truth": False, "has_exper...
a574f0127293f652027050baa6d2a2f29db3114c567aac5f63c592659d2259ac
Python
925
30
from typing import NamedTuple class _SCVIVA_REGISTRY_KEYS_NT(NamedTuple): SAMPLE_KEY: str = "sample" Z1_MEAN_KEY: str = "latent_mean" NICHE_INDEXES_KEY: str = "niche_indexes" NICHE_DISTANCES_KEY: str = "niche_distances" NICHE_COMPOSITION_KEY: str = "niche_composition" Z1_MEAN_CT_KEY: str = "la...
512fbae0751a31e314df18cc6bac9ebb63596c5368e3f7da8dac9f493003fcd7
Python
926
31
"""Basic plotting utilities for training curves.""" import os import matplotlib.pyplot as plt def plot_training_history(train_losses, val_losses, val_accuracies, out_dir): os.makedirs(out_dir, exist_ok=True) plt.figure(figsize=(8, 5)) plt.plot(train_losses, label="Training Loss") plt.plot(val_losses...
35acb495239bd9cd12404c97ee9e6b279661e21485d71c3fb9bbf38260c48189
Python
930
21
""" Path management """ # Update with your path stem here! path_stem = "/oak/stanford/groups/kalanit/biac2/kgs/projects/Dawn/streamlined/" # This data path corresponds to the following project on OSF: https://osf.io/qy32x/files/osfstorage DATA_PATH = path_stem + "data/" RESULTS_PATH = path_stem + "results/" # These f...
43cfa76f224b7dfd0e6ad8bde92d815aef8f545b7383bb43c3e9cb4c4ca2cdea
Python
930
33
import numpy as np from ._constants import Nums class Settings: # misc settings auto_preprocessing: bool = True disable_multimodal: bool = False scale_to_microns: float = 1.0 def disable_lazy_loading(self): """Disable lazy loading of subgraphs in the NovaeDataset.""" Nums.LAZY_LO...
51d4ed9ae31d668f11e466db41ff01b729dba7e40b55da0ec11bd7a486401fb2
Python
930
26
from dipy.data import get_sphere from dipy.reconst.shm import sh_to_sf import numpy as np def get_sf_range(data, sh_order, full_basis, sphere_name): sphere = get_sphere(sphere_name) sf = np.array([sh_to_sf(sh, sphere, sh_order, full_basis=full_basis) for sh in data], dtype=np.float32) v...
c7c62a1a3eb2c26fc40625f78db490bd862cef8597e0bcc3880380c2c1501d50
Python
930
21
_MAJOR = "2" _MINOR = "2" # On main and in a nightly release the patch should be one ahead of the last # released build. _PATCH = "2" # This is mainly for nightly builds which have the suffix ".dev$DATE". See # https://semver.org/#is-v123-a-semantic-version for the semantics. _SUFFIX = "" #_SUFFIX = "dev-2025-09-09" V...
9145570977e4988777e184ecbbbbc4b3cde15ffdaab348f1b8f55f4ab8555f0a
Python
931
29
import argparse import math from tqdm import tqdm from Bio.SeqIO.FastaIO import Seq, SeqRecord from tape.datasets import LMDBDataset parser = argparse.ArgumentParser(description='Convert an lmdb file into a fasta file') parser.add_argument('lmdbfile', type=str, help='The lmdb file to convert') parser.add_argument('fas...
a54367b354080bfe049f9dfb4aba3822a453d517702ec573c1471f0950cbd21c
Python
931
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 """Reads in a fairseq output file, and verifies that the constraints (C- lines) are present in the outpu...
172ddedbe7107657872d1b3050f6f47526300bd4ead7ab413061c1ec6662faae
Python
932
28
def normalize_deduplicate_and_order_strings(strings: list[str]) -> list[str]: """Normalize, deduplicate, and alphabetically order a list of strings.""" allowed_special_chars = "-'" normalized_strings = [ clean_string(string, allowed_special_chars) for string in strings if string.s...
34ab137e7c00c08ff0293deda09a57a9b3c0d9b74727aaf8504dfedfe6092cd1
Python
932
29
"""`rapidfuzz`'s upper bound must not silently harden into an exact pin. `b6f6215` turned `rapidfuzz>=3.14.1,<4` into `rapidfuzz==3.14.1,<4` as a side effect of an unrelated python-version change; nothing in that commit's message mentioned rapidfuzz. An exact pin beside a `<4` upper bound is the tell that survives suc...
600da90f5779f1f333cfdd0fd4bb1dcda4c52d0c37f04f8e8ecf311fd01055d3
Python
932
34
#!/usr/bin/env python """ # Author: Kui XU # Created Time : Mon 3 Jul 2017 09:42:31 PM CST # File Name: setup.py # Description: """ from setuptools import setup, find_packages with open('requirements.txt') as f: requirements = f.read().splitlines() setup(name='prismnet', version='0.1.1', description=...
e9ed4c58f59719c17cb7b53a53d2827078ab6d4852d874453a9afca3762db1ab
Python
933
30
rec.begin( { "dimensions": {"x": [8e-9, "m"], "y": [8e-9, "m"], "z": [8e-9, "m"]}, "position": [3242.833251953125, 3334.499755859375, 4045.5], "crossSectionScale": 1, "projectionOrientation": [ 0.23160003125667572, 0.20444951951503754, -0.017615893...
3b69ac12abb9d473ac91931f573bb43defe722bbdd6afc75d6ebea3f695c41be
Python
938
28
# utils/audio_utils.py import numpy as np def seconds_to_index(seconds, sample_rate): """Convert time in seconds to index based on the sample rate.""" index_size = int(seconds * sample_rate // 1000) return index_size def seconds_to_chunk_index(seconds, chunk_size, sample_rate): """Convert...
57d64862e959e22f3e582048cf556381399fbcc50b8477c45e953cdaf0edfccf
Python
939
36
from __future__ import annotations import argparse import sys from pathlib import Path from st_risk.data.validate import validate_ready_directory from st_risk.paths import project_root def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Validate a prepared ready-data directory....
7d21f43adef6d6a52dbe832fd0d22fce052bd83d1dacf5c13d4ebd68576670dd
Python
939
40
#!/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 fairseq.data import Dictionary def get_parser(): parser = argparse.ArgumentPa...
2678ea86994ddbfa0f3b4cfe4e1699d41cfbeb582a02f48525c55304f8fe9f7c
Python
940
36
"""Create individual experiment files for a parameter sweep.""" from itertools import product from pathlib import Path import yaml def set_value(dct, keys, val): for key in keys[:-1]: if isinstance(dct, dict) and key in dct: dct = dct[key] else: raise KeyError(f"{keys} do...
f1c3c4ae2f704380d166dbad459df3f65cc5fa0a2d97ca58bb7817a2e6d6fbe6
Python
940
29
"""Utilities for grouper modules.""" __copyright__ = "Copyright (C) 2016-2017, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" import collections as cx def get_hdridx_flds(): """Return "hdr idx" named tuple fields used in Excel spreadsheets.""" return ["format_txt", "hdr_idx", ...
686b0ef432d5bb27df04b1b2f2096bf3b11de3627c4302e5e952702e3fcfab2f
Python
942
30
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from poetry.core.packages.package import Package from poetry.utils.env import Env def format_build_wheel_log(package: Package, env: Env) -> str: """Format a log message indicating that a wheel is being built for ...
b39ad606d242753b9f61bac59d5cfdbbd59c9c7115da363452683af9676bf112
Python
942
34
from __future__ import annotations import pytest from packaging.tags import Tag from poetry.repositories.legacy_repository import LegacyRepository from poetry.repositories.pypi_repository import PyPiRepository from poetry.repositories.repository_pool import RepositoryPool from poetry.utils.env import MockEnv @pyte...
b601decf2d370d9948b6d3027b69079fe193c53324a3e5697efe35152855a4ff
Python
942
30
import argparse import webbrowser import neuroglancer import neuroglancer.cli if __name__ == "__main__": ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) viewer = neuroglancer.Viewer() with viewer.tx...
73cd5672064472496da808014c5c54849de5db37ae9c3b330e2b766894b2f008
Python
943
36
from setuptools import find_packages, setup setup( name="spacestream", version="1.0", packages=find_packages(), install_requires=[ "attrdict==2.0.1", "deepdish==0.3.7", "eagerpy==0.30.0", "foolbox==3.3.4", "geopandas==0.13.2", "h5py==3.11.0", "mat...
614ab26f62b772a1c8ec8213cce1449bab0925f7056f9c1f8fb52600e8abcb33
Python
944
32
#!/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. from typing import Union from fairseq.data.dictionary import Dictionary from .decoder_config import DecoderConfig, F...
b5bfc9eb3e3f8858d892299e7da139d1134fdc63afe8f190ef80d685b0b30d15
Python
944
31
import loompy import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import balanced_accuracy_score def decision_boundary(ds: loompy.LoomConnection, clf, transformed, y_true, score, out_file) -> None: plt.figure(None, (10, 10)) plt.scatter(ds.ca.UMAP3D[:, 0], ds.ca.UMAP3D[:, 1], c='grey', alpha=...
0d312a765ba62fd1880786e933ff0fa926ca7e5a807a0484dcad49189551ad0c
Python
946
40
from .check_functions import _check_1d_array_object, _check_length_equal from .mathext import cartesian, sample_discrete from .optimizer import optimize, pinverse from .state_name import StateNameMixin from .tabular import ( build_state_names, collect_state_names, encode_columns, get_state_counts, g...
fb04639b7893ef817fdf0b96105fc76214bfed28189c45cd8537a01bdc84ed68
Python
946
30
import numpy as np import pytest from pgmpy.factors.continuous import LinearGaussianCPD def test_class_init(): beta = np.array([7, 13]) std = np.array([[4, 3], [3, 6]]) cpd1 = LinearGaussianCPD("Y", beta=beta, std=std, evidence=["X1", "X2"]) assert cpd1.variable == "Y" assert cpd1.evidence == ["...
743ba0d3300e65974ee3874af7ecc16b938265095d6ec7ddbceea9fafe54f219
Python
949
30
from typing import Callable import jax import jax.numpy as jnp SUPPORTED_FFN_ACTIVATIONS = ["gelu", "gelu-no-approx", "relu", "swish", "silu", "sin"] def get_activation_fn(activation_name: str) -> Callable: """ Return activation fn given its name. Args: activation_name: Activation name. Ret...
8d53863bdf191d9c2cb59bb0352bbda188265103a323598596bcc03e3097fc9e
Python
949
26
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 ...
9cae04072b964805b6ee9ccbc99ff9a5ab0763f18d68ccc21c12e40f7ac3d5fc
Python
949
33
#!/usr/bin/env python # -*- coding: utf-8 -*- from vlpp.utils import splitext_, run_shell, warn def main(): img = "${img}" _, ext = splitext_(img) output = "${participant}_input${suffix.pet}" if ext == ".mnc": run_shell("mnc2nii -nii -short {0} petconvert.nii".format(img)) #run_shel...
c2e4c7f4965d7115907b869069e53cb4a72a96e61b67f79d0708a96abf64e4d0
Python
950
35
# 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 setuptools import setup with open("fm/version.py") as infile: exec(infile.read()) with open("README_backup.md") as f: readme =...
84e2fa3c81fb2dd4bc7dafda70895bb44d44d591bfb323c16c15ceb466bb1c65
Python
951
32
import py3Dmol import qcelemental as qcel from ..convert_geo import xyz_string from ..molecule import ANGSTROM, Molecule from ..types import MolecularConfiguration def mol_conf_to_xyz(mol_conf: MolecularConfiguration) -> str: assert mol_conf.nuclei.charges.ndim == 1 mask = mol_conf.nuclei.mask return xyz...
af394f4252d59912e27724105cc251618a3b9b340218fcd085131820cf1aa82a
Python
952
31
import torch import numpy as np class Dataset(torch.utils.data.Dataset): def __init__(self, count_matrix, gene_ids, vocab, pad_value, batch_ids=None): self.count_matrix = count_matrix self.gene_ids = gene_ids self.batch_ids = batch_ids self.vocab = vocab self.pad_value = pa...
0197ca5967ebb7fb11c50989ffd9d79a68b941f733da603fb1e0a8725e8b6e36
Python
953
41
from __future__ import annotations from typing import TYPE_CHECKING from poetry.installation.operations.operation import Operation if TYPE_CHECKING: from poetry.core.packages.package import Package class Uninstall(Operation): def __init__( self, package: Package, reason: str | None...
1b1c9516b80f3a2e19d79691d54f0383681daceeaa47876f73bc1d7415acf30e
Python
953
39
from pgmpy.datasets._base import BaseDataset class ResidentialBuilding(BaseDataset): """ References ---------- - :footcite:t:`uci_residential_building` """ _tags = { "name": "residential_building", "n_variables": 109, "n_samples": 372, "has_ground_truth": False...
51a7236b5bd48e2af2ad33d1b6f0bde44396b22a17d27fa0417e29eb4bbe8483
Python
953
24
import numpy as np def _setup_vmin_vmax(data, vmin, vmax, norm=False): """Handle vmin and vmax parameters for visualizing topomaps. This is a simplified copy of mne.viz.utils._setup_vmin_vmax. https://github.com/mne-tools/mne-python/blob/main/mne/viz/utils.py Notes ----- For the normal use-c...
5e5ff3237fd7679e07b919efcfc8f7583b68285c3ea3588bae7d148ddfc52e48
Python
953
27
OrderList = ['1234', '1324', '2134', '2314', '3124', '3214'] OrderList = ['ABC', 'BAC', 'ACB', 'CAB', 'BCA', 'CBA'] for i in range(6): for j in range(2): with open('Training_dataset_R%s_weights_length.tab' % (i*2 + j +1), 'r') as fin: lines = fin.readlines() with open('Training_dataset_R%s_%s_weights_length.ta...
638342c3bedbbb9b7fdcfb0fa6e7b29a89253ea6583189cee4ad543c81c1dda9
Python
953
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 numpy as np import torch from . import BaseWrapperDataset class PrependDataset(BaseWrapperDataset): def __init__(self, dataset, ...
ed7ed75ee5b5060d8ba7628a3d595332f428512e9429a550d12a7d7571e61991
Python
953
25
# Compare Koopman spectra for REST: remote (S1) vs recent (S2) -- ASCII only import os, numpy as np EXP_REMOTE = r".\exp_remote_rest\K_weight.npy" EXP_RECENT = r".\exp_recent_rest\K_weight.npy" def eigs(p): return np.linalg.eigvals(np.load(p)) def summary(name, w, thr=0.95): m = np.abs(w) print("{}...
913cb1ba000e4c463a77128c00d2e8b1646fddd5bb1efcf35604cfe454b4d0ce
Python
954
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 MILNCETask(Task): def reshape_subsample(self, sample): if ( hasattr(self....
da6a606c98787965e6412565d0e483feadf2296e2e2a8993831fd54496d15e0e
Python
954
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. from dataclasses import dataclass from fairseq.dataclass import FairseqDataclass from fairseq.scoring import BaseScorer, register_scorer @...
169ef9b9a2896899d6aa80e9eb61b3ee3c8cf719c42fe9ddd4db5a8f597d366f
Python
955
37
#!/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 os import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("--tsv", required=True...
f072e55cd11100fa4f789e984c330716cd7428c25df0ed59409413fa241f38b3
Python
956
33
from ..misc import GWASAndModels class GF(object): RSID=0 CHROMOSOME=1 POSITION=2 REF_ALLELE=3 ALT_ALLELE=4 FREQUENCY=5 FIRST_DOSAGE=6 def force_mapped_metadata(generator, sep): for line in generator: varid = line[GF.RSID] allele_0, allele_1 = line[GF.REF_ALLELE], line[...
6ab2641b5d2ceeca4659977b69d88a88eb1a95153071771fcd34088d406f16fe
Python
957
25
# Compare Koopman spectra for ENCODING: remote (S1) vs recent (S2) -- ASCII only import os, numpy as np EXP_REMOTE = r".\exp_remote_enc\K_weight.npy" EXP_RECENT = r".\exp_recent_enc\K_weight.npy" def eigs(p): return np.linalg.eigvals(np.load(p)) def summary(name, w, thr=0.95): m = np.abs(w) print("...