sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
4aa14e0ad2812f02a361a7d9f6a9c031147c0ffe14678edd8cfb5d816153aed3 | Python | 1,051 | 35 | import math
import torch
def find_event(interp_fn, sign0, t0, t1, event_fn, tol):
with torch.no_grad():
# Num iterations for the secant method until tolerance is within target.
nitrs = torch.ceil(torch.log((t1 - t0) / tol) / math.log(2.0))
for _ in range(nitrs.long()):
t_mid ... |
21566d0b65b62a50eb7e7c73c8806293d686992936a08e7e490b24ab56c3d905 | Python | 1,052 | 29 | import numpy as np
import pytest
from cardio_audio_sleep.tasks._config import N_OMISSION, N_SOUND, TRIGGERS
from cardio_audio_sleep.tasks._utils import generate_sequence, get_event_name
def test_generate_sequence():
"""Test sequence generation."""
if N_SOUND == 0 and N_OMISSION == 0:
pytest.skip("No ... |
1c656c1141ca3122c0965cf7b45b8a7406541895016c15d9ea38ae17f041cc19 | Python | 1,054 | 28 | from pathlib import Path
import pytest
from ase.db import connect
from nablaDFT.pipelines import run
@pytest.mark.optimization
def test_pyg_optimization(pyg_optim_config):
run(pyg_optim_config)
output_datapath = Path(pyg_optim_config.output_dir, f"{pyg_optim_config.name}_{pyg_optim_config.dataset_name}.db")
... |
de585091d25bbd63e82c33be0276089805a626f579765818342559f7b39168de | Python | 1,054 | 38 | from typing import NamedTuple, Tuple
class ColorTriplet(NamedTuple):
"""The red, green, and blue components of a color."""
red: int
"""Red component in 0 to 255 range."""
green: int
"""Green component in 0 to 255 range."""
blue: int
"""Blue component in 0 to 255 range."""
@property
... |
09c2b05cdbecb848b8c2b76fcfc43896ec3012d05e5317650ab045f223114b68 | Python | 1,055 | 38 | """
Convert a TensorCircuit circuit to TenCirPauli Pauli propagation.
This is a short integration preview. For the complete propagation VQE,
truncation semantics, gradient checks, and benchmark study, see:
https://github.com/tensorcircuit/TenCirPauli/tree/main/examples/research/pauli_propagation_julia_vqe
"""
from __... |
a6b7ee62673e8c65a19362072f4082493ca9dd912b459ed97b5e1ba415b087fb | Python | 1,055 | 28 | import tensorflow as tf
class WeightedMSE(tf.keras.losses.Loss):
"""
Confidence-weighted MSE:
L = mean( w_i * (y_i - yhat_i)^2 )
y_true is expected to have shape (batch, 2): [y, w]
"""
def call(self, y_true, y_pred):
y = y_true[:, 0]
w = y_true[:, 1]
y_pred = tf.sque... |
15bba8b002535d49079ffadc24dc3a6b09fb4cde40d879247030786ada9648aa | Python | 1,056 | 31 | import sys
sys.path.append('.')
from plotting.utils import load_results, mesh_name, sim_name, line_data_over_time, ecscolor
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
if __name__ == '__main__':
sim_name = sys.argv[1]
mesh_name = sys.argv[2]
"""
results = load_results(mesh_name, sim... |
1898b2e01481c7b50fedcb5a432ff45c30987583a1bb6f63e64b68f72bbb9c50 | Python | 1,056 | 37 | """Provides a set of utility functions that is used for evaluations.
This includes finding main channel and signal to noise ration for templates.
"""
import numpy as np
def main_channels(template):
"""Computes the main channel of a list of templates.
Parameters
----------
template: numpy.ndarray
... |
75d3c8ea9036eea9e9d48356b38622df00aaa15ca9491331b2d3bbef55904b97 | Python | 1,056 | 45 | from __future__ import annotations
from typing import Any, TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from numpy._typing import NDArray, ArrayLike, _SupportsArray
x1: ArrayLike = True
x2: ArrayLike = 5
x3: ArrayLike = 1.0
x4: ArrayLike = 1 + 1j
x5: ArrayLike = np.int8(1)
x6: ArrayLike = np.float64(1)
x7... |
d145dc796b2906a2088bf63c2f633b548414ac57489e44f7f709d0752f576692 | Python | 1,056 | 34 | import os
import pandas as pd
from argparse import ArgumentParser
from argparse import ArgumentDefaultsHelpFormatter
def argparser():
parser = ArgumentParser(
formatter_class=ArgumentDefaultsHelpFormatter,
add_help=False
)
# Required arguments
parser.add_argument("--input_dir",
... |
33d39e477f65dfe0c625206bf382159a760ca4cb3fdf155f0a049247cbbb9be9 | Python | 1,057 | 34 | from io import StringIO
import pytest
from pandas import read_sas
import pandas._testing as tm
class TestSas:
def test_sas_buffer_format(self):
# see gh-14947
b = StringIO("")
msg = (
"If this is a buffer object rather than a string "
"name, you must specify a fo... |
fd94030894c9f123f79155ae9d2a81b1164d3f38f673558556a6ddaf4f29cf75 | Python | 1,057 | 25 | import sys
from .compat import chardet
# This code exists for backwards compatibility reasons.
# I don't like it either. Just look the other way. :)
for package in ("urllib3", "idna"):
vendored_package = "pip._vendor." + package
locals()[package] = __import__(vendored_package)
# This traversal is apparen... |
966647b90f0e4a5c0fdf1711f17cb631fbe3c69dabcb6cd42f80ced8fe216e79 | Python | 1,058 | 40 | """
Tests involving custom Index subclasses
"""
import numpy as np
from pandas import (
DataFrame,
Index,
)
import pandas._testing as tm
class CustomIndex(Index):
def __new__(cls, data, name=None):
# assert that this index class cannot hold strings
if any(isinstance(val, str) for val in d... |
9b191f143dab35f83c9e7d69a7fe35dd2d2e09d617c9d3d605ccfd8a5806900d | Python | 1,058 | 30 | import numpy.distutils.fcompiler
from numpy.testing import assert_
intel_32bit_version_strings = [
("Intel(R) Fortran Intel(R) 32-bit Compiler Professional for applications"
"running on Intel(R) 32, Version 11.1", '11.1'),
]
intel_64bit_version_strings = [
("Intel(R) Fortran IA-64 Compiler Professional ... |
a544d607f06d8d3c3a0f9536a0742cc07ed7bb889c47c920f8166bbf56993e0c | Python | 1,059 | 29 | #!/usr/bin/env python
# ===================== #
# Preprocess of dataset #
# ===================== #
# Usage: python <path-to-this-file>/preprocess.py <your_config>.ini [-n NUM_THREADS]
# Default config for preprocessing data is DeepH-E3/deephe3/default_configs/base_default.ini
# You only have to fill in fields in [dat... |
0754f19626f5b4c9213a1ee1e818467ee34db6e0eb33d29b6c4450c2ef2bfad9 | Python | 1,060 | 36 | import torch
class CameraIdentifierModel(torch.nn.Module):
def __init__(self, device="cpu"):
super(CameraIdentifierModel, self).__init__()
self.conv_base = torch.nn.Sequential(
torch.nn.Conv2d(1, 8, kernel_size=3, stride=2),
torch.nn.ReLU(),
torch.nn.Identity()... |
89dea2cd1e2e61cb3ff6af5e8f7fbfd3b9fbbaf221f1e0bfa9bf591556234f4b | Python | 1,060 | 33 | import pytest
from pandas import (
Index,
NaT,
Series,
)
import pandas._testing as tm
def test_astype_str_from_bytes():
# https://github.com/pandas-dev/pandas/issues/38607
# GH#49658 pre-2.0 Index called .values.astype(str) here, which effectively
# did a .decode() on the bytes object. In 2... |
3221d56abebe6de504615129a97391217e1ff06dbd238ec3dfa92b7a5b5d7e84 | Python | 1,061 | 33 | from numpy.distutils.fcompiler import FCompiler
compilers = ['PathScaleFCompiler']
class PathScaleFCompiler(FCompiler):
compiler_type = 'pathf95'
description = 'PathScale Fortran Compiler'
version_pattern = r'PathScale\(TM\) Compiler Suite: Version (?P<version>[\d.]+)'
executables = {
'vers... |
3d794f9081094233d86e8034eac812c53c848ef88a151d3255e1afa71191539a | Python | 1,061 | 26 | import pandas as pd
import numpy as np
def clean_behavioral_data(df):
"""
Standardizes US expectancy ratings and maps functional CS types.
Based on the experimental phases: Acquisition, Reversal, and Test.
"""
# Mapping CS items to functional types (CS++, CS+-, CS-+, CS--)
# [cite_start]as defi... |
44195e3058ed469584c858ba1bded3ce06f30de795d672f1f2f895c7c2057581 | Python | 1,061 | 38 | import pytest
import os
from sinto import filterbarcodes
@pytest.mark.parametrize("nproc", [1, 2])
@pytest.mark.parametrize("barcodes", ["data/barcodes.tsv", "data/barcodes.tsv.gz"])
def test_filterbarcodes(tmpdir, nproc, barcodes):
basepath=os.path.dirname(os.path.realpath(__file__))
bam=os.path.join(basepat... |
117e5bbd1e287ab5563231be13cb35dc703ac5926511d983a4512c9b8ef33c9f | Python | 1,063 | 43 | import torch.nn as nn
from .residual_block import *
"""
Stack of pre-activation residual blocks
"""
class ResidualStack(nn.Module):
def __init__(
self,
num_blocks,
order,
num_features,
clebsch_gordan=None,
mix_orders=True,
activation="swish",
):
... |
15463efa11b4fa8a1bbed1ce63ae03e7406cffe24599ff8dcdaec2f485ce4456 | Python | 1,063 | 32 | """
Stores and defines the low-level format_options context variable.
This is defined in its own file outside of the arrayprint module
so we can import it from C while initializing the multiarray
C module during import without introducing circular dependencies.
"""
import sys
from contextvars import ContextVar
__all... |
6abdba333f668b011b857684b60c234dee4ec93e615a61aebac3e527f57ac771 | Python | 1,063 | 41 | import cedalion.sigproc.frequency as freq
import xarray as xr
import cedalion
import numpy as np
units = cedalion.units
def resample(data: xr.DataArray, Fs: float = 4):
"""Function for temporally resampling (up or down) a time series.
Args:
data: xr.DataArray
Fs: new sample rate (as float)
... |
9fe91c7adb04531d99526850adf78c35cfad79e1a1a6e490e45f153c1b32bc3a | Python | 1,064 | 32 | from typing import Callable, Match, Optional
import re
from ._emoji_codes import EMOJI
_ReStringMatch = Match[str] # regex match object
_ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub
_EmojiSubMethod = Callable[[_ReSubCallable, str], str] # Sub method of a compiled re
def _emoji_re... |
e259994590256c9127a61cf3c1f72fb0ee2412fd4b1bd977b8299a17ff247000 | Python | 1,064 | 39 | import operator
import numpy as np
import pytest
import pandas._testing as tm
from pandas.core.ops.array_ops import (
comparison_op,
na_logical_op,
)
def test_na_logical_op_2d():
left = np.arange(8).reshape(4, 2)
right = left.astype(object)
right[0, 0] = np.nan
# Check that we fall back to ... |
bd109e4a1ac52f850cfa61d5569db6adfd56ab98ef020742502a681322c824a8 | Python | 1,065 | 38 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
""" A collection of functions for running hmmsearch.
"""
from .base import execute, get_config, RunResult
def run_hmmpress(hmmfile: str) -> RunResult:
""" Run hmmpr... |
420fab177741e47faa4cf5e44cd04c171032292ad3adfba8632f794133c59869 | Python | 1,067 | 31 | from __future__ import annotations
import pytest
from textstat.backend import validations
from .. import resources
@pytest.mark.parametrize(
"word, syllable_threshold, lang, expected",
[
(resources.EMPTY_STR, 0, "en", False),
(resources.EMPTY_STR, 1, "en", False),
(resources.EASY_TEXT... |
7834ebcc98307dabacd13b3cebe1d1f589003cec0e48e3c898f4c7ba09f510e7 | Python | 1,069 | 30 | """
Test machar. Given recent changes to hardcode type data, we might want to get
rid of both MachAr and this test at some point.
"""
from numpy._core._machar import MachAr
import numpy._core.numerictypes as ntypes
from numpy import errstate, array
class TestMachAr:
def _run_machar_highprec(self):
# Inst... |
b8ebc9122d7922eead6afcbd2043373a2a59ad7abc31cb5a92ce6de63a4bb1db | Python | 1,069 | 41 | # Load in modules
import numpy as np
import pandas as pd
import scanpy as sc
import snapatac2 as snap
import pickle
# Import ATAC data
atac = sc.read_h5ad(snakemake.input.atac_anndata)
# Filter for only control data
control_atac = atac[atac.obs[snakemake.params.disease_param] == snakemake.params.control]
# Get mar... |
288dce76102d9570cd46d6f2b95d6af6ae2e6b90c6cd17541d7199c0cab3efbe | Python | 1,070 | 27 | """Look up items in large lists of frequencies, norms, or vectors."""
import argparse
def lookup(big_fname, items_fname):
"""Line-wise Lookup of a list of items in a large file.
:param big_fname: filename of large file to look up items in
:param items_fname: filename of list of items to look up
"""
... |
603b9801bd282a825cf5e3a7289ba83df2db20a3a011d134e3f098c514b85392 | Python | 1,070 | 57 | import numpy as np
dtype_obj = np.dtype(np.str_)
void_dtype_obj = np.dtype([("f0", np.float64), ("f1", np.float32)])
np.dtype(dtype=np.int64)
np.dtype(int)
np.dtype("int")
np.dtype(None)
np.dtype((int, 2))
np.dtype((int, (1,)))
np.dtype({"names": ["a", "b"], "formats": [int, float]})
np.dtype({"names": ["a"], "form... |
d1e135b95d71ba67ccf0f6523e884c0f9158a2ced7a2839e772d71b32d79b6f2 | Python | 1,070 | 36 | """
Signal filtering utilities (high-pass / low-pass / band-pass).
Implements Butterworth filter helpers for signal pre-processing.
"""
from scipy import signal
def butter_highpass(cutoff, fs, order=5):
"""Design a Butterworth high-pass filter."""
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = si... |
6d56cc2a6389dd2135f67ffcc7971103ef6de7a893fa37a72f5e87313324d31b | Python | 1,071 | 35 | import asap
# The below code is to be used for predicting SNV effects on ATAC-seq data using a trained model.
# It includes data paths, model parameters, and the creation of datasets for prediction.
def main():
# Data paths
signal_file = "../data/TCGA-A6-A567/TCGA-A6-A567.nodup.no_chrM_MT.tn5.pval.signal.big... |
29871c3b92f95a942918184f990384cb2164fe0a1f67a69a9f12f9eb7a5ed59f | Python | 1,073 | 35 | import torch
from torch.utils.data import Dataset
import numpy as np
import cv2
import random
class HRFDataset(Dataset):
def __init__(self, path_to_images, path_to_mask, augment=False):
self.path_to_images = path_to_images
self.path_to_mask = path_to_mask
self.augment = augment
... |
435d184e40a386d25830af1a3c4de6fa99594a9d37e70cd540e89f51702eb13d | Python | 1,073 | 33 | import numpy as np
import itertools
def augment_3d_image(image):
"""
As augmentation, we hold all combinations of horizontal and vertical flips
as well as transposition for the in-plane of a 3D image.
This function is written by GPT-4 Code Interpreter and edited by a human.
"""
assert len(ima... |
c586275f0bcf16f69ea4175b0a2c437c50128be6f3db228a6a77ff5b1619a610 | Python | 1,073 | 36 | from __future__ import annotations
from ..utils._typed_cache import typed_cache
from ..selections._set_difficult_words import set_difficult_words
from ..selections._list_difficult_words import list_difficult_words
@typed_cache
def count_difficult_words(
text: str, lang: str, syllable_threshold: int = 2, unique:... |
e65185396dbb4afdab6fd04bc1646c9ad20e1721dfdaece4f4898991307d6498 | Python | 1,074 | 21 | import numpy as np
def check_action(action,dim):
null_action = np.zeros(4,dtype=int) # 4, as each electrode gets one stim slot
message = "none"
if not isinstance(action,np.ndarray):
message = "Action is not a numpy array. Action was not used."
action = null_action
elif action.ndim ... |
001f9a03bb3db9092b09c1745e57ece4975bc1527f614a864eabba4f7778cf3f | Python | 1,077 | 29 | import itertools
import unittest
import string
from rna3db.utils import to_case_insensitive, to_case_sensitive
class TestCaseSensitivity(unittest.TestCase):
def test_to_insensitive(self):
self.assertEqual(to_case_insensitive("a"), "-a-")
self.assertEqual(to_case_insensitive("Aa"), "A-a-")
... |
7dde221fd752bcc421da88d6d151c16c77c4254c92a19d7b6324f13fc93f5e9c | Python | 1,077 | 32 | from setuptools import setup,find_packages
#generate install_requires from requirements.txt file
install_requires=open('requirements.txt','r').read().strip().split('\n')
print(f"install_requires:{install_requires}")
config = {
'name': 'chrombpnet',
'author_email': 'anusri @ stanford.edu',
'license': 'MI... |
8ef60f5da96cfedfa21f9498da573c5d6a857e66e0a3e7e048b587c278b7b64e | Python | 1,077 | 40 | from pathlib import Path
from aicspylibczi import CziFile
import sys
import os
def get_czi_shape(path: Path) -> tuple[int, int, int, int, float]:
czi = CziFile(path)
dim = czi.dims
size = czi.size
try:
interval = float(czi.meta.find('Metadata').find('Experiment').find('ExperimentBlocks').find(... |
230a637269d43c1e852981ebf990dcffdacebb83f4b954556be4deecc5733aa2 | Python | 1,078 | 41 | #!/usr/bin/env python3.7
# isort: skip_file
"""Defines imports for the src.core module.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-du... |
69e7df681c9cde5031c6cd74be2442daabaf09c1be764e7b48a340d7216a9072 | Python | 1,078 | 65 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
""" A collection of functions and classes for running external commands.
"""
from .base import (
execute,
parallel_execute,
parallel_function,
RunResult,
... |
83bdb9c0b5e5a68fd7b576069e80e32f5ec4f4f427e15e6b21cec03b0422440d | Python | 1,078 | 40 | """
jacobian calculation on different backend
"""
import numpy as np
import tensorcircuit as tc
def get_jac(n, nlayers):
def state(params):
params = K.reshape(params, [2 * nlayers, n])
c = tc.Circuit(n)
c = tc.templates.blocks.example_block(c, params, nlayers=nlayers)
return c.sta... |
d0cd813e2ba4748e8c64789082e15392752f4b5ffa5dd36d4bb25f4de64570e5 | Python | 1,081 | 34 | from smac.env import StarCraft2Env # import a package smac
class StarCraft:
def __init__(self, env_name, random_seed):
# map_name ->
self.env = StarCraft2Env(map_name=env_name, seed=random_seed, continuing_episode=True, difficulty="7") # TODO
env_info = self.env.get_env_info()
... |
6afcc8bb5759de996ce1233a835ef733b4388bcccc533780548d84788cd60b47 | Python | 1,083 | 39 | from pandas import (
DataFrame,
Series,
)
import pandas._testing as tm
class TestDataFrameCount:
def test_count(self):
# corner case
frame = DataFrame()
ct1 = frame.count(1)
assert isinstance(ct1, Series)
ct2 = frame.count(0)
assert isinstance(ct2, Series)
... |
823dcf57141a23a0b7f99b38daa6064ec3608dfe9bf171abbb10e26593315c2c | Python | 1,083 | 31 | from typing import Tuple
import torch
class RandomBoundingBoxPadding(torch.nn.Module):
def __init__(self, min_padding: float, max_padding: float):
super().__init__()
self.min_padding = min_padding
self.max_padding = max_padding
def forward(self, img: Tuple[torch.Tensor, torch.Tensor]... |
6da4d6b8ecb4a9e08924c6ff74021bba132179255a498133789987ee1be39830 | Python | 1,084 | 42 | from __future__ import annotations
import re
from ..utils._typed_cache import typed_cache
from ._count_arabic_syllables import count_arabic_syllables
from ..selections._list_words import list_words
@typed_cache
def count_faseeh(text: str, rm_apostrophe: bool = True) -> int:
"""Counts faseeh in arabic texts.
... |
65b35bfe1503e071c5d0fe531c763536c847f3a18f2060bba8e3709699bc9805 | Python | 1,086 | 35 | import torch
from sklearn.metrics import classification_report
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from model import FeatureMapContrast, TransformerClassifier
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
transform = transforms.Compose([... |
6c019c3c4a1fe6e353f0a5b268f99033f6e47f8187c4221a744f482910068a00 | Python | 1,086 | 30 | from __future__ import annotations
import pytest
from textstat.backend import transformations
from .. import resources
@pytest.mark.parametrize(
"in_text,out_text,rm_apostrophe",
[
("They're here", "Theyre here", True),
("They're here", "They're here", False),
("They're here, and they... |
29808cb706fb5d6cd95ec2191a28ed8f0f687ecd8322a13da6c7caa3146c1eec | Python | 1,087 | 28 | """
Implementation of pandas.Series.str and its interface.
* strings.accessor.StringMethods : Accessor for Series.str
* strings.base.BaseStringArrayMethods: Mixin ABC for EAs to implement str methods
Most methods on the StringMethods accessor follow the pattern:
1. extract the array from the series (or index)
... |
47fe64700cc6bbb2d18d8806add110269e668309408bba59fd376a3f8dd1cea9 | Python | 1,087 | 48 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
file_path = './result/ablation_result.xlsx'
df = pd.read_excel(file_path)
labels = df['model'].tolist()
metrics = df.columns.tolist()[1:]
data = df[metrics].values
num_metrics = len(metrics)
angles = np.linspace(0, 2 * np.pi, num_metrics, endpo... |
d98e81488edd8fdc26355d963716e2a1790dd66edfbddbe8220fc80c8e8a31c0 | Python | 1,087 | 34 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, lang, strict_lower, strict_upper, expected",
[
(resources.EMPTY_STR, "en_US", False, False, 0.0),
(resources.EASY_TEXT, "en_US", False, False, 4.045... |
3731302e6ed47c11f51b8d8a6ef4744e6ea71259151ab42ab801cc8aa55c5007 | Python | 1,090 | 37 | from __future__ import annotations
from textstat import textstat
import pytest
@pytest.mark.parametrize(
"num,points,expected",
[
(1.234, 0, 1),
(1.234, 1, 1.2),
(1.234, 2, 1.23),
(1.234, 3, 1.234),
(1.234, 4, 1.234),
(3.512589, 4, 3.5126),
(3.512589, 5... |
83c9a3e231cde718b8b397d95fae171aa04d5d8638f792c52d5ab18072551614 | Python | 1,090 | 40 |
COLORS = [
"#23445D",
"#9673A6",
]
OPACITY = 0.15
COLORS_REWRITES = [
f"rgba(35, 68, 93, {OPACITY})",
f"rgba(150, 115, 166, {OPACITY})",
f"rgba(219, 111, 189, {OPACITY})",
f"rgba(117, 231, 231, {OPACITY})",
f"rgba(219, 111, 111, {OPACITY})",
f"rgba(219, 181, 111, {OPACITY})",
f"rgba... |
12b654c34ee3a2676cfc5d318373ff724fc4c3b96d5966343f520859b048c727 | Python | 1,091 | 33 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, lang, expected",
[
(resources.EMPTY_STR, "en_US", 0.0),
(resources.EASY_TEXT, "en_US", 78.918),
(resources.SHORT_TEXT, "en_US", 83.32),
... |
cf00f06b0b420561311721053ba3914c61acb7da75deafacb7e75f8dd6b82788 | Python | 1,091 | 36 | import torch
import torch.nn as nn
from myutils.common import heaviside
from config import AdaLiConfig
def soft_sign_backward(grad_output: torch.Tensor, x: torch.Tensor, alpha: float):
return grad_output / (2 * alpha * (1 / alpha + x.abs()).pow_(2)), None
class soft_sign(torch.autograd.Function):
@st... |
8524007dd64e2817b63276d30605942e6b40e39f7372d8b18fb423cba6d1836d | Python | 1,094 | 41 | import pytest
from pandas.core.frame import DataFrame
@pytest.fixture
def dataframe():
return DataFrame({"a": [1, 2], "b": [3, 4]})
class TestDataFrameValidate:
"""Tests for error handling related to data types of method arguments."""
@pytest.mark.parametrize(
"func",
[
"qu... |
da0ee3e3aa122f04ed44420b5d8a07a71fb748ea7f3a4a7a6b1689d20d5df1af | Python | 1,094 | 27 | import openai
from fastapi import APIRouter, Body, HTTPException
from app.models.utils_models import OpenAIKeyRequest, OpenAIKeyValidationResponse
router = APIRouter(prefix="/utils", tags=["utils"])
@router.post("/validate_openai_key", response_model=OpenAIKeyValidationResponse)
async def validate_openai_key(reques... |
c0d7c4be1ff128b8d2a430454ac0533e381db09545ebabd208dd555ff7864399 | Python | 1,095 | 31 | from ._count_chars import count_chars
from ._count_arabic_long_words import count_arabic_long_words
from ._count_arabic_syllables import count_arabic_syllables
from ._count_complex_arabic_words import count_complex_arabic_words
from ._count_faseeh import count_faseeh
from ._count_difficult_words import count_difficult_... |
fe7e78f3b68529afd8b37ae00b761ab139c8e0e4a6071db58d65fc367c659124 | Python | 1,096 | 40 | """
Created on Jan 7, 2026
@author: mning
"""
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.base import ClassifierMixin
from sklearn.utils.estimator_checks import check_estimator
from sklearn.utils.multiclass import unique_labels
from sklearn.utils.validation import check_is_fitted
class Thr... |
4322c2fac56f26dca5452b7d2ac594e4d89969e9dc3e286b15d2c79af80be33d | Python | 1,098 | 34 | import pandas as pd
import os
import sys
from multiprocessing import Pool
import numpy as np
fun_taxon_filename=sys.argv[1]
output_dir=sys.argv[2]
abu_rel_df_name=sys.argv[3]
processors=int(sys.argv[4])
abu_rel_df=pd.read_csv(abu_rel_df_name,header=0,sep=',')
fun_taxon=pd.read_csv(fun_taxon_filename,sep=',',header=0... |
312bc473196c56de1867b9955d4f2afe193033423bc6cc567a312a9d4431ea11 | Python | 1,099 | 40 | import pytest
import numpy as np
from numpy.ma import masked_array
from numpy.testing import assert_array_equal
def test_matrix_transpose_raises_error_for_1d():
msg = "matrix transpose with ndim < 2 is undefined"
ma_arr = masked_array(data=[1, 2, 3, 4, 5, 6],
mask=[1, 0, 1, 1, 1, 0]... |
498f8b6c63e39aecb8e73b165a4a9ffd2e40d26536d4e455f0ea7ab642fb9459 | Python | 1,099 | 35 | from .cluster import Cluster
from .titlelifneuron import TitleLIFNeuron
class TitleCluster(Cluster):
'''
classdocs
'''
def __init__(self, neutype, neunum):
'''
Constructor
'''
Cluster.__init__(self, neutype, neunum)
self.averageFiringRate = 0
def createClu... |
0fe20237bce4660935009d001db87809dc63c509db1ff0dc8b14e24f09bb904f | Python | 1,101 | 34 | import json
import os
from os.path import join
def GenerateJsonV1():
maskPath = r'E:\NeronSegDataSet\HaiNanDataSet1\DataSet128Small\smallMask'
imgPath = r'E:\NeronSegDataSet\HaiNanDataSet1\DataSet128Small\images'
savePath = r'E:\NeronSegDataSet\HaiNanDataSet1\DataSet128Small\smallMask.json'
ls = os.lis... |
7bf07db23bc261ee9dcd5d836d73d3ad94c1b9956ad548a84c80cc801fbb8443 | Python | 1,101 | 38 | import torch
import torch.nn as nn
from myutils.common import heaviside
from config import AdaLiConfig
def sigmoid_backward(grad_output: torch.Tensor, x: torch.Tensor, alpha: float):
sgax = (x * alpha).sigmoid_()
return grad_output * (1. - sgax) * sgax * alpha, None
class sigmoid(torch.autograd.Funct... |
c7114e451710a081abbe3414f99242ec9adecad95896e892f313e50a311ea216 | Python | 1,101 | 26 | from distortion import ag_distort_28, ag_distort_224, ag_distort_silhouette, save_image, get_silhouette_data
from braincog.datasets import get_mnist_data
# An example of Abutting Grating Distortion applied on MNIST
train_loader, test_loader, _, _ = get_mnist_data(batch_size=100)
for images, labels in train_loader:
... |
08a1238a4ed855f48918be1a6ee72d92696421484086ffb1d9a51c5e24d1f5bd | Python | 1,102 | 22 | from numpy.testing import assert_
import numpy.distutils.fcompiler
nag_version_strings = [('nagfor', 'NAG Fortran Compiler Release '
'6.2(Chiyoda) Build 6200', '6.2'),
('nagfor', 'NAG Fortran Compiler Release '
'6.1(Tozai) Build 6136', '6.1'),
... |
4836287b45d4a406b2c84403abb661aef104cfb53dba92432d8ce171da1589f7 | Python | 1,103 | 44 |
from numpy.distutils.from_template import process_str
from numpy.testing import assert_equal
pyf_src = """
python module foo
<_rd=real,double precision>
interface
subroutine <s,d>foosub(tol)
<_rd>, intent(in,out) :: tol
end subroutine <s,d>foosub
end interface
end python modul... |
2c569f5f39cda5fba9e3877edf22f4eb89d4d463726346f61cf3100d78f93288 | Python | 1,104 | 35 | import os
from typing import List, Tuple
import mrcfile
import numpy as np
from .mrc import read_mrc
def stack_image_files(image_files: List[os.PathLike], output_image_file: os.PathLike):
n_images = len(image_files)
_, h, w = get_image_shape(image_files[0])
stack_shape = (n_images, h, w)
mrc = mrcfi... |
4cfa523d7e4289e3d5193154c278a6a5c0b961e04eb6300f2b6d3042f1bdd902 | Python | 1,104 | 50 | """
transforms.py is for shape-preserving functions.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from pandas._typing import (
AxisInt,
Scalar,
)
def shift(
values: np.ndarray, periods: int, axis: AxisInt, fill_value: Scal... |
f16497259d4917986013c53fe26961655159f189ffea4c9aba6fb72ba6f0db65 | Python | 1,104 | 29 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
""" Functions and classes for managing the signatures from HMM profiles """
from typing import List
from antismash.common import path
from antismash.common import signat... |
713bc0de9de3998fc4540bb32537f76dda4d1b4982e0a0cc0f3e12dfb82b5200 | Python | 1,106 | 47 | """
Time evolution of Heisenberg model realized by Trotter decomposition
"""
import numpy as np
import tensorcircuit as tc
K = tc.set_backend("tensorflow")
tc.set_dtype("complex128")
xx = tc.gates._xx_matrix
yy = tc.gates._yy_matrix
zz = tc.gates._zz_matrix
nqubit = 4
t = 1.0
tau = 0.1
def Trotter_step_unitary(in... |
073dcb7233505e4cf80aefffa4be0267cea8e3e1cd2d98f535959d949863baed | Python | 1,108 | 40 | from optparse import Values
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import SUCCESS
from pip._internal.exceptions import CommandError
class HelpCommand(Command):
"""Show help for commands"""
usage = """
%prog <command>"""
ignore_require_venv = True
... |
21e4243d6ea01834f3d211be329a8d16be25f21d7a05c64f9f51c5f5b38435bf | Python | 1,108 | 37 | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master... |
fc83f73c27bfbfe0345177b1c944d83c0a15a30bb76c0ac15b3fc44f68877f00 | Python | 1,108 | 29 | """Module that contains helper functions specifically related to the bigscape version
"""
import tomllib
from importlib import metadata
from pathlib import Path
def get_bigscape_version() -> str:
"""Get the version of BiG-SCAPE.
The way we retrieve the version is different depending on whether the package is... |
440f2072a2b5ed8a64c419cdc172556b5a1ad8bca058381f1759c0d4d3f0de6a | Python | 1,109 | 55 | # ruff: noqa: F401
import os
from .exceptions import * # noqa: F403
from .ext import ExtType, Timestamp
version = (1, 1, 2)
__version__ = "1.1.2"
if os.environ.get("MSGPACK_PUREPYTHON"):
from .fallback import Packer, Unpacker, unpackb
else:
try:
from ._cmsgpack import Packer, Unpacker, unpackb
... |
9deeded2b147f73dd231f0ba9bcd9e136c03bb370b56b374d6625230eba669be | Python | 1,109 | 64 | """
Created on Jun 24, 2024
@author: mning
"""
from src.pipelines.calc_Classification_BP_Bands_Ratio import (
calc_Classification_BP_Bands_Ratio,
)
calc_Classification_BP_Bands_Ratio(
op_Training="5050CV",
op_NumClass=2,
dist_Medn=2,
op_Num_Epoch=1,
op_PerEpoch=0,
op_RMT=0,
op_AMT=0,
... |
a55c069f589dfef3bf6fd9ebcf733d43f421f6fa83a82d1e647a26d3fa06afe0 | Python | 1,109 | 41 | import io
import pytest
import pandas as pd
class BasePrintingTests:
"""Tests checking the formatting of your EA when printed."""
@pytest.mark.parametrize("size", ["big", "small"])
def test_array_repr(self, data, size):
if size == "small":
data = data[:5]
else:
d... |
8d8b3ddc1f82a98bf89eebe1a7e817df88f2bc7ab9c2a764426e99b951372649 | Python | 1,110 | 37 | '''
Created on 2015.5.19
@author: liangqian
'''
import sys
import sys
from data.globaldata import *
class Dendrite():
'''
This class defines dendrite structure of a neuron.
A dendrite contains no more than 40 synapses
'''
def __init__(self):
'''
Constructor
'''
sel... |
5fa44e8d2dbb7d84d0026b41f0f6bf895db856a9da29c53e105007605b832d59 | Python | 1,113 | 34 | from typing import List
import numpy as np
import torch
from ultralytics import YOLO
def best_box_to_array(result) -> np.ndarray:
result = result.cpu().numpy()
confidences = result.boxes.conf
coordinates = result.boxes.xyxyn
if len(confidences) == 0 or len(coordinates) == 0:
return np.zeros(... |
d8645082c126bcf0e3b79c22a0c08eac89ab181cb38e8d95b7c1f139abbcc9f9 | Python | 1,113 | 37 | """Regression tests for the lightweight command-line information paths."""
from pathlib import Path
import os
import subprocess
import sys
REPO_ROOT = Path(__file__).resolve().parents[2]
PIMMS_SCRIPT = REPO_ROOT / "scripts" / "PIMMS"
def _source_tree_environment():
env = dict(os.environ)
env["PYTHONPATH"] ... |
095eb9c604382d725b535ba7de074ab22b5307b6bf928a3835d1759e38b3cc44 | Python | 1,114 | 40 | import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
nwires, nlayers, nbatch = 6, 3, 16
qubits = [cirq.GridQubit(0, i) for i in range(nwires)]
my_symbol = sympy.symbols("params_0:" + str(nwires * 2 * nlayers))
model_circuit = cirq.Circuit()
for j in range(nlayers):
... |
963928de21e1066e59bc456aac611bc06578cf47177784c4d6e4b37fe2d9950f | Python | 1,114 | 62 | """
Reversed Operations not available in the stdlib operator module.
Defining these instead of using lambdas allows us to reference them by name.
"""
from __future__ import annotations
import operator
def radd(left, right):
return right + left
def rsub(left, right):
return right - left
def rmul(left, rig... |
199e7b8ca43b131a524ad7503f612ff0d6c3fdc8545f644672b7a183c404801d | Python | 1,115 | 37 | #!/usr/bin/env python3.7
"""Compare thresholds across models using a boxplot.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent... |
75ca7604a7a938edadc14085fb74c0c9f13a69b6a634173b63db889f1fb7470e | Python | 1,115 | 38 | import os
import sys
import os
import sys
import tensorflow as tf
import numpy as np
import chrombpnet.training.utils.losses as losses
from chrombpnet.training.utils.data_utils import one_hot
from tensorflow.keras.utils import get_custom_objects
from tensorflow.keras.models import load_model
def get_seq(peaks_df, gen... |
c34f2d94ca442561c013289489b3e36e259391c91ead1e1002c4ef6b1a819f16 | Python | 1,115 | 26 | # Helpers for stability analyses: Latin Hypercube Sampling (LHS) and Partial Rank Correlation Coefficient (PRCC)
from __future__ import annotations
import numpy as np
# ---------- LHS + PRCC ----------
def latin_hypercube(n: int, d: int, rng: np.random.Generator) -> np.ndarray:
X = np.zeros((n, d))
for j in ra... |
cb4321bd74dc4084485518c61df4cd9648d3adcd07222d16762363ecc50a7888 | Python | 1,118 | 37 | #!/usr/bin/env python3.7
"""Compare thresholds across models using a barchart.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascen... |
bce0ba02694f2106d5c507f60e244bd3631acb920ae412b619414ad273fcdc53 | Python | 1,119 | 33 | import numpy as np
from numpy.lib import array_utils
from numpy.testing import assert_equal
class TestByteBounds:
def test_byte_bounds(self):
# pointer difference matches size * itemsize
# due to contiguity
a = np.arange(12).reshape(3, 4)
low, high = array_utils.byte_bounds(a)
... |
0c2ce3785f3551f1a5b937756d373829007cab96fcfdd068dd80a3f592a76604 | Python | 1,122 | 45 | # %%
import mne
import pickle
import numpy as np
import matplotlib.pyplot as plt
# load evoked potentials
f = open("../results/evokeds.p", "rb")
ev = pickle.load(f)
f.close()
# %%
jitters = [f"j{i}" for i in range(8)]
topo_times = [.1, .14, .18, .22, .26, .3, .34]
vlims = (-1.5, 1.5)
fig, axs = plt.subplots(
nro... |
1dfa6a2efeb877af3b510ec76847d423f6741dee4eac566a1dd907663bd0cdeb | Python | 1,122 | 35 | #!/usr/bin/env python
# coding: utf-8
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.loggers import CSVLogger
import pandas as pd
import numpy as n... |
9b0d4a59e1f4dbbf62c8e64b2d15a92425177e0812614fea835114d0a84fb30a | Python | 1,122 | 37 | """Generate a heatmap of activation thresholds.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent.
Note: if more than one heatm... |
97cf98db91f751ffc677bb4a8cd6a956e97418706cdb8aa81b5feb59f1c9b047 | Python | 1,123 | 37 | #!/usr/bin/env python3.7
"""Compare thresholds across models using a boxplot.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent... |
53801acb5d5500bbe6db66d6117d1e0d6b8de6ac49960fe11f922938beb63372 | Python | 1,125 | 47 | from __future__ import annotations
from typing import Any
import numpy as np
class Object:
def __ceil__(self) -> Object:
return self
def __floor__(self) -> Object:
return self
def __ge__(self, value: object) -> bool:
return True
def __array__(self, dtype: np.typing.DTypeLike... |
8c062769618cb94686f7ddf2c4bc2bd5e4fa275bade3709c05a29db3809edfed | Python | 1,125 | 41 | from pandas import (
Index,
NaT,
Period,
PeriodIndex,
)
import pandas._testing as tm
class TestFillNA:
def test_fillna_period(self):
# GH#11343
idx = PeriodIndex(["2011-01-01 09:00", NaT, "2011-01-01 11:00"], freq="h")
exp = PeriodIndex(
["2011-01-01 09:00", "2... |
c0d911df1b9f4f61890409ab4890f5505dd472d6d3966e894f768b587955bf10 | Python | 1,127 | 43 | """
example showcasing how circuit can be load from and dump to json:
useful for storage or restful api
"""
import numpy as np
import tensorcircuit as tc
tc.set_dtype("complex128")
def make_circuit():
c = tc.Circuit(3)
c.h(0)
c.H(2)
c.CNOT(1, 2)
c.rxx(0, 2, theta=0.3)
c.u(2, theta=0.2, lbd=-... |
443d4c5249602c1b4136f26ee49f7671565bacede7dfc533750be1e0102f02a2 | Python | 1,128 | 36 | import numpy as np
import pytest
from pandas.errors import DtypeWarning
import pandas._testing as tm
from pandas.core.arrays import ArrowExtensionArray
from pandas.io.parsers.c_parser_wrapper import _concatenate_chunks
def test_concatenate_chunks_pyarrow():
# GH#51876
pa = pytest.importorskip("pyarrow")
... |
223ac31f1919b73ba5b8334c9b40f9d0eeae336f2ade373b709890f47483e77b | Python | 1,129 | 34 | import xarray as xr
import cedalion.dataclasses as cdc
import cedalion.typing as cdt
from cedalion import units
from ..sigproc.frequency import freq_filter
@cdc.validate_schemas
def split_frequency_bands(ts: cdt.NDTimeSeries) -> cdt.NDTimeSeries:
"""Extract signal components in different frequency bands.
T... |
5c0e6144875cb3f20520b16faa907be7dfa9134af981e1809bca5ce759e8cf15 | Python | 1,129 | 36 | """Generate dose-response curves (% fibers activated as a function of stimulation amplitude).
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmg... |
3540f87d529d483d36ae2efe75bd2d9ced15a8b3fd687bb3992b5c5bbb40974f | Python | 1,130 | 31 | import ssl
import sys
import typing
# Hold on to the original class so we can create it consistently
# even if we inject our own SSLContext into the ssl module.
_original_SSLContext = ssl.SSLContext
_original_super_SSLContext = super(_original_SSLContext, _original_SSLContext)
# CPython is known to be good, but non-C... |
e586fe2201b8670f4768a7658d7fda3a920bae39bc40941e3a76aa6509c654ec | Python | 1,130 | 34 | import os
import sys
sys.path.insert(0, os.path.abspath('../../Readout_python/'))
sys.path.insert(0, os.path.abspath('../../Communication/'))
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.