sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
dd0e34a6808c88ed76cb1994c84ef7d71ab04a9abf0e6f4bae172b501305a6a8 | Python | 4,123 | 101 | import mne
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
def visualize_bem(fig_fname, subjects_dir, subject, src=None):
print('Visualizing BEM surfaces...')
plt.figure()
mne.viz.plot_bem(subject=subject, subjects_dir=subjects_dir,
... |
5dcce186f582eb1e8da2d5b82b58c72a88a81c8f240786463b15ad9cc1c055ff | Python | 4,124 | 95 | from unittest import TestCase
import numpy as np
from scipy import stats
import spateo.segmentation.em as em
from ..mixins import TestMixin
class TestEM(TestMixin, TestCase):
def test_nbn_em(self):
rng = np.random.default_rng(2021)
X = rng.negative_binomial(10, 0.5, 100) + rng.negative_binomial... |
a55f5ee9167dc4423619588c1f9d3fa207d71cffbd08e30ffc52383bb3a4d0d7 | Python | 4,124 | 109 | """A06 capture-options truth: the chunked path drops NO capture option.
WALKTHROUGH list-A row 26 (second clause): ``chunk_size=`` silently dropped
``save_budget`` -- the chunk path rebuilds a recursive ``CaptureOptions``
from a hand-enumerated field list, so session knobs absent from that list
reset to their defaults... |
0c960b4b63f480d196c605708ae5595bda2d5d3cc0c1296cd8ca456ab8554342 | Python | 4,125 | 130 | """P7 backward validation oracle and event-flow corruption tests."""
from __future__ import annotations
from dataclasses import replace
import pytest
import torch
from torch import nn
import torchlens as tl
from torchlens.ir.events import BackwardPassEnd, GradFnFired, OpGradObserved
from torchlens.validation.invari... |
c5f043ff9faf64fd524ce66caf90c015219939118844312af7b5916d077b3cce | Python | 4,125 | 110 | """Purity/state harness skeleton gates: templates, controls, vocabularies.
Wave 0 owes the SKELETON (invocation-template schema + history-cell schema +
the D10 purity vocabulary), not the harness: build item 7 (Wave 1) wires the
snapshot union and the postconditions over these exact templates. "Templates,
not compute,... |
f923ac176cce17e1c4f65f8c39c90a514da7153e5114c8bc977db3864b722f6f | Python | 4,126 | 121 | import torch.utils.data as data
from utils import canonicalize_smiles_from_file,replace_halogen,construct_vocabulary,create_var,one_hot
import re
import numpy as np
import torch
from rdkit import Chem
class MolData(data.Dataset):
def __init__(self, root_path, voc ):
self.voc = voc
self.root_path =... |
58035993045a29eabc76a766bc643d63b09de49dd183fc1b4b7bbfa7b996ece6 | Python | 4,128 | 127 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created in March 2023
@author: Thomas Bonald <thomas.bonald@telecom-paris.fr>
"""
from typing import Optional, Union
import numpy as np
from scipy import sparse
from sknetwork.linkpred.base import BaseLinker
from sknetwork.embedding.base import BaseEmbedding
from skn... |
5c7b092b6b17170f7c5b15292b3c767dd86a2d610e45361730a8a5353dfec83a | Python | 4,128 | 113 | import pandas as pd
from tqdm import tqdm
def verify_unicity_id_sequence(df_test):
"""
No sequences have two ids and "inversly"
"""
assert len(df_test["uniprot_id"]) == len(df_test["uniprot_id"].unique())
assert len(df_test["sequence"]) == len(df_test["sequence"].unique())
def convert_DeepEC_res... |
26782c95f8c5691e499334fe7caf4154f6c519aed046cfadb85bd9000388173b | Python | 4,129 | 148 | '''Tests for bdpy.stats'''
import unittest
import numpy as np
import bdpy.stats as bdst
class TestStats(unittest.TestCase):
'''Tests for bdpy.stats'''
def test_corrcoef_matrix_matrix_default(self):
'''Test for corrcoef (matrix and matrix, default, var=row)'''
x = np.random.rand(100, 10)
... |
7f9b8bca3232bf0b4f22742a7311a9f4157de9335b7ded08cc24372ed75c8b3d | Python | 4,130 | 105 | """face-rhythm: extract and decompose rhythmic facial movements from video.
The top-level package eagerly imports its submodules so that the public API
(e.g. ``face_rhythm.point_tracking``) is available directly after
``import face_rhythm``. The version string is kept in :mod:`face_rhythm._version`
so build-tooling an... |
2ad93367b62daee5bddf6da44f71e9122633541180b113ae144a45c16dd85dcd | Python | 4,132 | 101 | """
TODO: This look like this class is not used yet, but it will be nice to use it the future for readability of codecarbon/emissions_tracker.py
"""
from time import perf_counter
from codecarbon.external.hardware import CPU, GPU, RAM, AppleSiliconChip
from codecarbon.external.logger import logger
class MeasurePower... |
662dd74479fd166edac834d3cd6b9f9d87468a61e4ab80cde63aa8612dd7986f | Python | 4,132 | 118 | import tensorflow as tf
import random
import os
import pickle
from functools import partial
from sklearn.utils import shuffle
class Baseline_MLP(tf.keras.Model):
def __init__(self, feature_nums=None, dropout_rate=0, initializer=tf.keras.initializers.HeNormal(), **kwargs):
super().__init__(**kwargs)
... |
9edeb193fc5f5106fd4901a680e601956575a2510bbe752c6d7b8d68c65f0f35 | Python | 4,133 | 97 | """
Generate an HTML report with quality control figures.
"""
import sys
sys.path.append('..')
import argparse
import mne
from mne.preprocessing import read_ica
from config import fname
# Be verbose
mne.set_log_level('INFO')
# Handle command line arguments
parser = argparse.ArgumentParser(description=__doc__)
parser.... |
60397b9599605068d4ea1dcfb49fa60d7e8261ae8a6d0dc4bafc93b6a09970c2 | Python | 4,135 | 140 | from collections import OrderedDict
import numpy as np
import pytest
from gym.spaces import Box, Dict, Discrete
def test_dict_init():
with pytest.raises(
AssertionError,
match=r"^Unexpected Dict space input, expecting dict, OrderedDict or Sequence, actual type: ",
):
Dict(Discrete(2)... |
6451e7f25bcb6a102401400c9b761557089f1f7d5601122ab07e3c8f473052e2 | Python | 4,135 | 131 | from matplotlib import pyplot as plt
from PIL import Image
import pandas as pd
import matplotlib
import numpy as np
import networkx as nx
from typing import Optional, Union, Mapping # Special
from typing import Sequence, Iterable # ABCs
from typing import Tuple # Classes
from anndata import AnnData
import warnings... |
783402a47126a392d27be832cfa44ebcacbd853af3343c629fcbfb802d84c281 | Python | 4,135 | 159 | from tempfile import TemporaryDirectory
import numpy as np
import polars as pl
import pandas as pd
import seqpro as sp
import xarray as xr
from pytest import fixture
import seqdata as sd
import zarr
def read_fasta(file_path):
"""
Reads a FASTA file and returns a dictionary of sequences.
Parameters:
... |
70394df265c1dc11ebb9f4f34fe0992c467e2baabfd9491c68a43baa3b8fd0d4 | Python | 4,136 | 116 | # General imports
import os
import sys
import torch
import numpy as np
import pandas as pd
from copy import deepcopy
import pytorch_lightning
# EUGENe imports and settings
import eugene as eu
from eugene import dataload as dl
from eugene import models
from eugene import train
from eugene import settings
settings.data... |
fdd6d20762cd0477677dd4a565da7ddfdabb44d5bc92e16025a2c5628009fe37 | Python | 4,136 | 115 | """X.509 certificates."""
from __future__ import annotations
import datetime
import glob
import os
from typing import TYPE_CHECKING, Iterator
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.x509 import load_pem_x509_certific... |
3df2cdebfbf42f9627e1ab4be9b01e6a5ca5e1d6b1ccbe180fae4ea2effd10bf | Python | 4,138 | 130 | """
====================================================================
Manova for ERP data
====================================================================
"""
# Authors: Alexandre Barachant <alexandre.barachant@gmail.com>
#
# License: BSD (3-clause)
from time import time
from matplotlib import pyplot as plt
i... |
fdbcf9b4d5158d50fb319715579f5571161dbd028549baafda63158f71679fe4 | Python | 4,139 | 119 | from typing import Any, Dict
import copy
import re
import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
def rse_loss(prediction: torch.Tensor,
target: torch.Tensor) -> torch.Tensor:
"""
Function to calculate relati... |
b93d9177d7d9887f40012e7ed41e380634dfaaa76939fdde5af0853e2e6d2893 | Python | 4,140 | 121 | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Normalizing flow mapping only a subset of the input degrees of freedom.
"""
# ================================... |
a0f601bc58abb5882cdbaeda7a23af12561dfd6ad92d3281c104e9b5bc8371fa | Python | 4,141 | 65 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
ea7bef34970c2aa41248c10ed7b09c3c67efb1b4493d0c3fbb46281526a00cd4 | Python | 4,141 | 133 | """
Plot the results of the combinatorial analysis of different measured
parameters on the LDA accuracy measure
Scores for all combinations of measurements
are generated by CN_LDA, using '-c combo' flag
results are stored in LDA_Scores_CN.pkl, which we retrieve here
to plot
"""
import os
from pathlib import Path
impo... |
2e9889c106a180b903180db2f6520bc61013ff3ceba1be8d82e2423c50fc4925 | Python | 4,143 | 138 | """
Utilities for preparing real-data fixtures used in integration tests.
Run via:
python larvaworld/tests/init_datasets.py
The script performs three steps:
1. Initializes the registry default reference dataset (via `define_default_refID()`).
2. Imports key SchleyerGroup datasets from raw CSV files and persists p... |
459f512ec26ee68a6a0c995d4a4f0a53a46bf0df7409ad0da39313db4d015540 | Python | 4,145 | 95 | from __future__ import annotations
import pytest
import torch
from lightly.loss import CAPILoss
from lightly.loss.capi_loss import sinkhorn_knopp
class TestCAPILoss:
def test_forward__returns_positive_scalar(self) -> None:
criterion = CAPILoss(sinkhorn_iterations=3)
teacher_logits = torch.randn(... |
854ec1ae135c239e901d0ba56c40e0f5cd651890f3e81848ddfdd6fce0587640 | Python | 4,145 | 109 | """Tests for xcp_d.interfaces.bids."""
import os
from pathlib import Path
import pytest
from xcp_d.interfaces import bids
_XCPD_ATLASES = str(Path.home() / '.cache' / 'xcp_d' / 'XCPDAtlases')
def test_copy_atlas(tmp_path_factory):
"""Test xcp_d.interfaces.bids.CopyAtlas."""
tmpdir = tmp_path_factory.mktem... |
34195afde9ca523fa39275c1570664f51b76b13a30a7ab61e41fff30778e8a1e | Python | 4,146 | 144 | doc_spatial_base_plot = """\
adata
Annotated data matrix.
title
Title name of the figure.
figsize
Figure size with the format (width,height).
cmap
Color map to use for continous variables or discretes variables (e.g. viridis,
Set1,...).
use_label
Key for the label use in `adata.obs` (e.g. `leide... |
3217d2cf830ead4a342e2d494c9236eec1666859759dffc4c44a1fd904596a3e | Python | 4,148 | 141 | from unittest.mock import Mock, patch
import pytest
import t.skip
from celery.exceptions import ImproperlyConfigured
from celery.worker.components import Beat, Hub, Pool, Timer
# some of these are tested in test_worker, so I've only written tests
# here to complete coverage. Should move everything to this module at... |
0ce3b518d42f66abcc43acde2f2874b4845a06f0d88085596b3a6db94d1369f4 | Python | 4,149 | 95 | import pytest
import warnings
import torch
import numpy as np
import src.behav_analysis as ba
import constants.constants_expt1 as constants_expt_1
import types
import os
class TestWrapAngle:
def test_edge_case(self):
""" Test the edge case - pi should be converted to -pi."""
assert ba.wrap_angle... |
3d12dfdb488e52f6bea578661c735bee88673cca1f6b9762d15186bf6d232515 | Python | 4,149 | 165 | from datetime import datetime
import numpy as np
import torch
import os
import time
from constants import get_args
from spliceai_torch import (
SpliceAI,
load_model,
save_model,
SpliceAIDataset,
evaluate_model,
)
from load_psam_motif import read_motifs
from map_protein_name import get_map_protei... |
9389169a69031983206718f8ceddd38eaed41bdba5f4aecdccb07bdeac8688ff | Python | 4,150 | 127 | import gzip
import os
import numpy as np
import pandas as pd
import tqdm.auto as tqdm
from permacache import permacache, stable_hash
from .fasta import OneHotFasta
from modular_splicing.utils.run_batched import run_batched
@permacache(
"dataset/gtex/leafcutter_data/load_all_leafcutter_data_2", dict(spm=stable_h... |
c534a27c112459029e835e30b89764c911a31338a3ba95f3cdc60db32de38b21 | Python | 4,150 | 114 | """
CREaTor
Copyright (C) 2023 Microsoft Research
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed... |
e692f24cd4deabb7dea7a6226b45b018b2157605b677a02fd0073c62ca8f2982 | Python | 4,150 | 104 | # Mossy layer at 0 deg
from os.path import join
import numpy as np
import os
import pandas as pd
from library.comput_utils import cal_hd_np
from library.params import ParamsHolder
from library.shared_vars import sim_results_dir
from library.utils import save_pickle
from library.simulation import simulate_SNN
for analy... |
9977b93e38845a0b66657bb30c18ca7208e77442811e4d51604869d3172a2b80 | Python | 4,151 | 131 | """Lifecycle stage builders for the public-surface oracle."""
from __future__ import annotations
import pickle
import random
import tempfile
from collections.abc import Callable
from pathlib import Path
from typing import Any
import numpy as np
import torch
from capture_oracle._models import build_model_case
import... |
fd0a77a7e9f623e689f2045ba2d9a982ce8f868ef33c58121ebc4a22b16ca6c6 | Python | 4,151 | 108 | import pandas as pd
from typing import Dict, List, Union
import shortuuid
import warnings
import rdkit
from rdkit import Chem
from rdkit.Chem import AllChem, MolFromSmiles as mfs
from rdkit.Chem import MolToSmiles as m2s
from rdkit.Chem import rdFingerprintGenerator
from mordred import Calculator, descriptors
warnin... |
d6e198170fbae8dc66b2b2a13830a3af111b906d72c75fc6d3736076306ec906 | Python | 4,152 | 123 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Line(_BaseTraceHierarchyType):
_parent_path_str = "ohlc"
_path_str = "ohl... |
034d0dd926a8b7a00e86cd179caae0061cb6f491ca2ce8c8fc2a948d52d79650 | Python | 4,153 | 116 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 15 19:11:53 2021
@author: Adrien Peyrache
This script shows how to use pynapple to compute sleep reactivation, step by step.
See pynacollada_replayExample for a real case example
"""
import pynapple as nap
import pandas as pd
import numpy as np
import seaborn as sns; s... |
f8f12ef6d13859d916920e290ff5d9159642a86f723e3d22375925776cf1bdb2 | Python | 4,153 | 80 | import numpy
def innervation_location(vol, src_coordinates, tgt_coordinates, view='target', method='mean'):
"""
Calculates for each point in a volume the average location it is innervated from
:param: vol (numpy.array; shape: N x M) Array of innervation strength values shape: (source voxels x target voxel... |
1a83c56a0e815a198fd15dab70666dfc4f8af3a4fcc76441c77047d7c2b3fb5a | Python | 4,154 | 148 | import os
from pathlib import Path
import json
import argparse
import logging
from monty.serialization import dumpfn, loadfn
import basis_set_exchange as bse
from coeffnet.predata.matrices import TaskdocsToData
from yaml import safe_load
from instance_mongodb import instance_mongodb_sei
__input_folder__ = "in... |
5c2b55513439c02efcb02f70627113712047841dd42cd02463ef1cb3d4dfc10d | Python | 4,154 | 140 | # Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
from eelbrain import datasets, plot, testnd, Factor, concatenate, set_tmin
from eelbrain.testing import hide_plots
@hide_plots
def test_uts_stat():
"test plot.UTSStat plotting function"
ds = datasets.get_uts(utsnd=True)
p = plot.UTSStat('uts', ds=ds... |
6666d4b5a7da46e219bed59737feb07bf3f3a0f3a0cca8d872ccc73ab41686b4 | Python | 4,154 | 86 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
051b90522e0f7acc631c0b77ba94185489dba0714731b7bdbfa92827a96de719 | Python | 4,155 | 128 | import datetime
import os
from unittest.mock import Mock, patch
import pytest
from kombu.utils.encoding import ensure_bytes
from celery.exceptions import SecurityError
from celery.security.certificate import Certificate, CertStore, FSCertStore
from celery.security.key import PrivateKey
from celery.security.utils impo... |
eb4cf1ec7a2df73f7da9de9a858282d208c3de70828e7ac967479174a424aa6c | Python | 4,156 | 99 | """
GIS classes
"""
from galaxy.datatypes.binary import Binary
from galaxy.datatypes.protocols import (
DatasetProtocol,
HasExtraFilesAndMetadata,
)
class Shapefile(Binary):
"""The Shapefile data format:
For more information please see http://en.wikipedia.org/wiki/Shapefile
"""
composite_typ... |
962ea15542e1e5fda5731c187c3143b6c311a09fb7b5752d7b786884022d3c41 | Python | 4,157 | 113 | import numpy as np
import pytest
from keras.src import backend
from keras.src import ops
from keras.src import random
from keras.src import testing
from keras.src.backend.common import standardize_dtype
from keras.src.random import seed_generator
class SeedGeneratorTest(testing.TestCase):
def test_seed_generator... |
68189047d856fe9543be1d2f24aa4b0960ac8b8f44836fb656dcea404c6d7129 | Python | 4,158 | 141 | import numpy as np
import torch
def angle_axis(angle, axis):
# type: (float, np.ndarray) -> float
r"""Returns a 4x4 rotation matrix that performs a rotation around axis by angle
Parameters
----------
angle : float
Angle to rotate by
axis: np.ndarray
Axis to rotate about
R... |
4f3e3effb79e3f26df079ed912dc149fc90c638bf0ba450ba4c5dd74e78b6b77 | Python | 4,159 | 144 | """Tests for specparam.modes.funcs."""
import numpy as np
from scipy.stats import norm, linregress
from specparam.modes.funcs import *
###################################################################################################
##################################################################################... |
2e8c94e2c09ada1e76dee3181198148dd51cbd7d4f2b5a0f51071a2ed0876a42 | Python | 4,160 | 115 | import argparse
import subprocess
from typing import Generator, Tuple, List, Iterable, Optional, Dict
def RNAsubopt(
seq: str, RNAsubopt_bin: str = "RNAsubopt", delta_energy: float = 5.0
) -> List[Tuple[str, float]]:
"""
Uses RNAsubpot to return a list of secondary structures
and their associated ener... |
5f0ff6b0e071548ed2a97a8cfc6e632c3f1007869d750ae574aee311d8900ee2 | Python | 4,160 | 107 | """Gallery membership closure (testing memo 5.1: exact count, zero slack).
The gallery is a CLOSED enumerated set: the passed-ID manifest, the test
files on disk, and the RG01-RG20 roster must agree exactly, in every
direction. This gate runs everywhere (no venue skip): it reads source, not
models, so a renamed or van... |
720a44bf78d75c07a016436909b310ba38c23a69bcd571419616e59f01139bd0 | Python | 4,160 | 115 | import bottle
import json
import logging
import os
import datetime
import optparse
app = bottle.Bottle()
links_file = "./contents/links.json"
assert os.path.exists(links_file), f"File not found: {links_file}"
news_file = "./contents/news.txt"
assert os.path.exists(news_file), f"File not found: {news_file}"
# Open a... |
7d0c67bee5bbc5a6cbc8cee47dca0517d6ad8aec4c04a83df1660e8a00c0e8f9 | Python | 4,160 | 77 | """A.1 (часть 1): калибровка ВНУТРИАГЕНТНОЙ метрики.
Популяционную метрику уже калибровали (threshold@40 -> 0.586, random -> 0).
Внутриагентная становится главной (правка A.2), поэтому её надо откалибровать
теми же контролями: threshold с порогами 20..70 (положительный, зависимость
от состояния встроена руками) и rand... |
02c8c2f32ef379b25cdcb64ce36ac576e3fe0698b23230b74c190caa7ad811d0 | Python | 4,162 | 100 | # SOURCE: vendored from kit-cel/vae-equalizer @ main
# https://raw.githubusercontent.com/kit-cel/vae-equalizer/main/AWGN_channel/func_VAENN_MQAM.py
#
# "Communication VAE": a variational-autoencoder-based blind channel equalizer for
# wireless/optical constellation shaping, from the Karlsruhe Institute of Technology
# ... |
28c350f73e47a3c791b3058e3d44557d6e5db327aedf0dbd6f4c23cb537ad1fb | Python | 4,162 | 79 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
e6a78f923c40f960f164b5c4772fe16b6c09277ad6e3688f6253690da91d85c0 | Python | 4,162 | 79 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
91e47f7e5999aa9df7e65768ab297502ca263c2ed7b40d1e290224c70021d0ac | Python | 4,165 | 112 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Custom operators."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorchvideo.layers.swish import Swish
from slowfast.models.utils import get_gkern
class SE(nn.Module):
"""S... |
afdb7629522ec2cda0abbac0f10f92ede427ea21bfae961e8397b84b235c8395 | Python | 4,165 | 117 | from keras.src import backend
from keras.src import initializers
from keras.src.api_export import keras_export
from keras.src.optimizers import optimizer
@keras_export(["keras.optimizers.Adagrad"])
class Adagrad(optimizer.Optimizer):
"""Optimizer that implements the Adagrad algorithm.
Adagrad is an optimizer... |
6f664fdeb142ff7dc0076ff7f0cf740b2b61fa9dffc01c296174c1e3fab76fd8 | Python | 4,167 | 128 | """grind-p3 T11.1: property-shadowed namedtuple fields fail closed.
A namedtuple subclass shadowing a DECLARED field with a ``property`` bypassed
the whole declared-schema proof: physical arity matched, no instance state
existed, no ``__getattribute__``/``__getattr__`` was overridden -- so every
walker's ``getattr`` r... |
8456a0050457b4f958af4aeddfce7e4548b7b7d8c9589482a3ce0ccb5c10607e | Python | 4,167 | 129 | import argparse
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument("--clustering_mode",
help="choose if representations are provided or learned",
choices=["pretrained", "end_to_end"],
required=True)
parser.add_ar... |
e9290602e0c4f4855c5ee89ef9824d819632e8bab98ae42eb8f4315ff1961940 | Python | 4,167 | 115 | #!/usr/bin/env python
#=========================================================================
#
# Copyright NumFOCUS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://... |
bc4168c0a02f60e5e0586e25ab2ae3a912181fd24c5f2305dcc905a6e221f32a | Python | 4,168 | 130 | import os
from datetime import timedelta
import hydra
import torch
from torch.distributed import init_process_group
from wandb import AlertLevel
from data.loader import get_dataloader3d
from initial_setting import init_seed, get_instance, get_optimizer
from utils.calculate import margin_of_error
from utils.general im... |
bf07e11767d354a3af0dc2f868c7ead807cf0267c9c533d1703fe47a3dd8908e | Python | 4,168 | 100 | """The registered analysis of the odorous-food-patch assays.
The `patch` graphgroup used to ask for four plots of per-turn quantities that
`get_par` cannot serve, because they live in the epoch dictionaries rather than
in the step or endpoint data, so `ExpRun.analyze()` died on every patch
experiment. The group now ho... |
011fdcffe4e52890b7ae966e8d71f65adaa09ee60d58740d2530db8e47e4375d | Python | 4,169 | 79 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
7cb642580a4a5a8b207e9d446b9fea3c9c6b77f662a7751a62d620bacebf3264 | Python | 4,169 | 125 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 5 16:33:35 2022
@author: longzheng
"""
import numpy as np
import tensorflow as tf
from ECCdataset import *
from tensorflow.data import Dataset
from spektral.data import BatchLoader
from spektral.layers import ECCConv, GlobalSumPool, GraphMasking
from tensorflow.keras.ca... |
0a2929cfa7143675587f49cd856511cbac403e02005842131ad4fe9e35d89f7c | Python | 4,170 | 125 | import pandas as pd
import h5py
import tqdm.auto as tqdm
import numpy as np
from modular_splicing.dataset.alternative.merge_splice_tables import (
splice_tables_on_common_genes,
)
from modular_splicing.dataset.alternative.merge_dataset import merged_dataset
data_txt_file_paths = {
"spliceai_canonical": "can... |
ac1ea29ceb8f701e447ef281e996eaa66560cfa20e3c6a6dd5b0a5ceb244f084 | Python | 4,170 | 125 | import numpy as np
import torch
import matplotlib.pyplot as plt
import argparse
from sklearn import metrics
#from skchem.metrics import bedroc_score
from sklearn.preprocessing import minmax_scale,scale
import xlwt
import math
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_curve,roc_auc_sco... |
388f793bf86ee2b241712349ffcd71c68c3de6f4c0b1216ce0bf5e7cdb7ffa4b | Python | 4,172 | 147 | import os
from fastapi import FastAPI
from fastapi_pagination import add_pagination
from pydantic import ValidationError
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
... |
96032041c42caa5fa31347c5b24fe5edc7119b310673dc5523eeb48bedafbf78 | Python | 4,172 | 103 | import json
import os
from jsonschema import validate
_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
def test_json_schema():
with open(os.path.join(_PATH, 'dummy_distribution.json')) as f:
data = json.load(f)
validate(data,
schema={
'definitio... |
bcc32f252f77e8954faaf6300103da4e17a9cb945644d3a20914ae1a464c2a08 | Python | 4,172 | 80 | import matplotlib
import matplotlib.pylab as plt
from matplotlib.ticker import AutoMinorLocator
import seaborn as sns
import glob
import pandas as pd
import os
sns.set(style='ticks', context='talk', palette='Set1')
colors = [sns.color_palette('Set1')[0], sns.color_palette('Set1')[1], sns.color_palette('Set1')[2], sns.c... |
020c084b800c9162cf49f20379cf9c21ed954d2ca36871bbeb1188ebb39446df | Python | 4,173 | 139 | import numpy as np
from neurogym.core import TrialEnv
from neurogym.utils import spaces
class EconomicDecisionMaking(TrialEnv):
"""Economic decision making task.
A agent chooses between two options. Each option offers a certain amount of
juice. Its amount is indicated by the stimulus. The two options of... |
275be9f2288fadbc7cfee1c7c8ba2a491bdcb23971c1cd45da5349b42caa9b9a | Python | 4,173 | 120 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... |
88db8fc7c5de988a9b18de107d2035969c35f6c9e86cc518ed7319820395822f | Python | 4,173 | 109 | import numpy as np
from typing import Tuple, Dict
import torch
import h5py
def load_params(
fname : str,
device : torch.device="cpu",
checkpoint : int=None) -> Dict[str, torch.Tensor]:
"""Load the parameters of a previously saved RBM model.
Args:
fname (str): Path to the model.
dev... |
9b24289f460e94b6854ba8b19590ab5d81aab3ebdfd66895564f09794d77aefb | Python | 4,174 | 136 | """Utilities for object functionality - including running in parallel & progress bars."""
from functools import partial
from multiprocessing import Pool, cpu_count
from specparam.modutils.dependencies import safe_import
#################################################################################################... |
cf768e9e56fac9a1b987da994770ac1534488de5204145a0e45693a384fcc90a | Python | 4,175 | 117 | """F12 pins: the lens refusal taxonomy (themes memo section 2 item 5).
Overview/blueprint never refuse; speed/memory/compute/dims refuse on
missing EVIDENCE; transformer and sequence refuse on factual absence of
SUBJECT. Every refusal names the remedy; the teaching escape is
theme='overview'.
"""
from __future__ impo... |
13574dbf7a876c11b7dd722d2523bd19d7062261b30a4cd09fe83f8d77b72459 | Python | 4,176 | 138 | import numpy as np
import pytest
from BM3D.src.denoise import bm3d, bm3d_CEST
from test_support_function.src.CEST import generate_Z_3D
from Metrics.src.image_quality_estimation import IQS
# Create mock input data
img = (np.zeros((42, 42)) * 255).astype("int16")
config = {
"sigma": 25.0,
"lamb2d": 2.0,
"la... |
87edfba315db048d5a2a826429bb47688c37bdef31c35d3e19831f0b19d0f55d | Python | 4,177 | 89 | ##########################################################################
## ##
## Copyright (c) 2019-2025 Philipp Lösel. All rights reserved. ##
## ##
## This file is par... |
1b993d244bfbdfbb3f706f780351b3c12af03f010995085e5c87007b92935461 | Python | 4,178 | 79 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
23ca08232da054c6537bee9f253647b7bc309c3287b91444bc292a8b2134b0e2 | Python | 4,178 | 79 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
89498502c289b01dc5cfc6ce2f9b00324c80f86a40da68d03091b50f571265fd | Python | 4,178 | 121 | # Copyright (c) 2022 PaddlePaddle 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
7780f4ca5047edbeb5a5f76446d9a2e5f0e6b3f5eb25f8612776a977a9b602b2 | Python | 4,180 | 100 | import os
import argparse
import torch
import torch.nn as nn
import torch.distributed as dist
import torch.optim
from tensorboardX import SummaryWriter
from gluoncv.torch.model_zoo import get_model
from gluoncv.torch.data import build_dataloader
from gluoncv.torch.utils.model_utils import deploy_model, load_model, sa... |
e076fb9b2f79e694f839d58234fec1d44297f0c8e79d5f58dff8795235e18a4a | Python | 4,181 | 146 | """
Utility functions for the Healthy Brain Network (HBN).
Author: Dominik Kraft
"""
import pandas as pd
def load_loris_data():
"""
Function that loads demographic, site and diagnostic information
based on LORIS database download.
Note: we downloaded data from LORIS + COINS and merged both to use
... |
183918602dd3b70d01293bd863f30f5e8f7152565a80765ef04d6b4f84760f46 | Python | 4,182 | 147 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 11 17:53:55 2023
@author: fcheng
"""
#coding:utf-8
import os
import numpy as np
import PIL
from PIL import ImageFont
import cv2
from plot.image_process import img_process, gammaCorrection
# save dirs
save_dir = "./results/plots"
if not os.pa... |
481a0e8eaea69b64f6e072022115ba50d726f3bf1acef7cb8db8dfffde68fd5b | Python | 4,182 | 106 | """ PyTorch FX Based Feature Extraction Helpers
Using https://pytorch.org/vision/stable/feature_extraction.html
"""
from typing import Callable, List, Dict, Union, Type
import torch
from torch import nn
from .features import _get_feature_info
try:
from torchvision.models.feature_extraction import create_feature_... |
75de7be7088119c8233769fe7c1d50bf5bef30ead6879f187b9538c87d9524f9 | Python | 4,182 | 79 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
8003b432c5d982a330f62cc521267c150c9cbe36578c5d771cd70b35f9361053 | Python | 4,182 | 79 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
946be56796022ea3ac9fae8eb8d5c9e4deac3dcaffe389d9982fd51d2fb89f48 | Python | 4,182 | 79 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
99c59db31a53bda5a41be4011a71132dc75ebe5f9bcdaab7792392b06a36cbac | Python | 4,182 | 137 | """Useful mocks for unit testing."""
import numbers
from datetime import datetime, timedelta
from typing import Any, Mapping, Sequence # noqa
from unittest.mock import Mock
from celery import Celery # noqa
from celery.canvas import Signature # noqa
def TaskMessage(
name, # type: str
id=None, # type: str... |
bb1e3eac4b6826b72395236590d668463c17fd3eb9f1fe6c30a3f38893695cf4 | Python | 4,182 | 79 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
d1613a9bc6af33fa6d87f172d70807cad9d29ad5a815a4e331618bf33d0163d4 | Python | 4,182 | 119 | import numpy as np
import nltk
import string
from nltk.tokenize import word_tokenize
from collections import defaultdict
nltk.download('stopwords')
nltk.download('punkt')
stop_words = set(nltk.corpus.stopwords.words('english') + list(string.punctuation))
def tokenize(s):
return [i for i in word_tokenize(s.lower()... |
dd061e31bbb9bd9b4493e9488159d32daf22fe4e91bd75f1d458bd69d08bcdcf | Python | 4,182 | 139 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
c4cae4fa5640ba4e96d8e09f76c91784b151230b9d7d091b0091dec8be32af89 | Python | 4,183 | 131 | """Tests for the fp64 precision bisector in torchlens.debug."""
from __future__ import annotations
import pytest
import torch
from torch import nn
import torchlens as tl
class CancellingModel(nn.Module):
"""Model with an engineered fp32 catastrophic-cancellation site."""
def __init__(self) -> None:
... |
52bcc609746d22f46d0cb0f628753d5ac6647379334c4f6dd0a1f529600e0736 | Python | 4,184 | 86 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from ultralytics.utils import LOGGER
from ultralytics.utils.checks import check_requirements
from .base import BaseBackend
class Co... |
5ffa5b200183f48527062cce42042bd88777706b6a3a253b9bf46469fec64c2e | Python | 4,187 | 140 | import numbers
import numpy as np
from scipy.spatial.distance import cdist
from .. import mask
from .base import BaseShape, rotate_around_point
class Polygon(BaseShape):
def __init__(self, points=None, point_um=1):
"""Polygon
Parameters
----------
points: list-like
... |
021c4432ed7a93c608060488c4418390d8e4716ea7ced13cd07790ea84c9dbc3 | Python | 4,188 | 144 | import argparse
import numpy as np
import pandas as pd
from joblib import dump, load
from sklearn.model_selection import train_test_split
from tqdm.auto import tqdm
import utils
from pathlib import Path
SEED = 420
np.random.seed(SEED)
def read_dataset(splicing_analysis_csv_path, filter_cryptic_restriction_site=Tru... |
e11df0fae329cfd267e954c12b97a9238bdd046fba24d4b4b95194cb8e35a7a9 | Python | 4,188 | 125 | """Tests for the pixel observation wrapper."""
from typing import Optional
import numpy as np
import pytest
import gym
from gym import spaces
from gym.wrappers.pixel_observation import STATE_KEY, PixelObservationWrapper
class FakeEnvironment(gym.Env):
def __init__(self, render_mode="single_rgb_array"):
... |
7ff91b7c452093d2d313ce37cae65ce2325e0d93d7be4bfe699372825e3629d2 | Python | 4,189 | 153 | from __future__ import annotations
import os
import subprocess
import sys
from textwrap import dedent
import pytest
DIR = os.path.abspath(os.path.dirname(__file__))
MAIN_DIR = os.path.dirname(os.path.dirname(DIR))
WIN = sys.platform.startswith("win32") or sys.platform.startswith("cygwin")
@pytest.mark.parametrize(... |
1189909fd7a1b7b8166f91855126965abe48a6fa11cd331063b48111ebfc8808 | Python | 4,190 | 140 | """
This module includes the main interface that handles the predictions.
"""
# Python import(s).
from pathlib import Path
import joblib
import warnings
import numpy as np
# Custom code imports.
from src.metal_pdb_data import MetalPdbData
from src.metal_auxiliaries import (fast_entropy,
... |
423e0802effe22fe180e5a6241a8a8fbdb75e11d8139a75f1f1aa97f417837ef | Python | 4,190 | 108 | # Copyright (c) 2022 PaddlePaddle 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
9068d640d244d9a5368fa1538ff60748e437227fd4011145e472f247ecd5e6b1 | Python | 4,190 | 133 | import attr
from cached_property import cached_property
import torch
import torch.nn as nn
import numpy as np
@attr.s
class HSMMForwardBackward:
log_o = attr.ib(type="NxSxT")
log_pi = attr.ib(type="S")
log_p = attr.ib(type="Sx(D+1)")
log_a = attr.ib(type="SxS")
@classmethod
def from_logits(c... |
2254fe35a71467262d6062182950cb91149fb6083bbe40582a9626bd4d29e667 | Python | 4,191 | 122 | """
Integration tests for essay configuration helpers using real registry state.
These tests validate that the stored essay definitions can be instantiated with
real dependencies and provide coherent experiment dictionaries without running
full simulations.
"""
from __future__ import annotations
import pytest
pytes... |
fc7603af864374be77d8db7c975576782ab6c42d943b0f72ae78036d71553494 | Python | 4,191 | 107 | """Utility functions to save rendering videos."""
import os
from typing import Callable, Optional
import gym
from gym import logger
try:
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
except ImportError:
raise gym.error.DependencyNotInstalled(
"MoviePy is not installed, run `pip inst... |
16230dba30f64837cac5cd908c6bc68ba0d75faed2016850d4ed28fb361b49f8 | Python | 4,192 | 154 | import numpy as np
import pandas as pd
import functools
import warnings
def copy_td(func):
"""
Call copy on the first argument of the function and work on the copied value
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
# if there are no positional arguments
if len(args) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.