sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
17e333d77bfa8d8b1e92541ff537bd27a9f370b0e6ab8ee03916bad4adf9fc50 | Python | 444 | 12 | # -*- coding: utf-8 -*-
from .tz import *
from .tz import __doc__
__all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange",
"tzstr", "tzical", "tzwin", "tzwinlocal", "gettz",
"enfold", "datetime_ambiguous", "datetime_exists",
"resolve_imaginary", "UTC", "DeprecatedTzFormatWarning... |
ec024a58e8c6e3e2998347f8ec032deb588f448718242c72cb0ccb555a406ba1 | Python | 444 | 20 | from __future__ import annotations
def get_lang_root(lang: str) -> str:
"""Get the root of a language. For example, "en_US" returns "en".
If the language is already the root, it is returned as is (e.g. "en").
Parameters
----------
lang : str
The language of the text.
Returns
----... |
be5cd92e53c434d7bded3b0843fa362cbc8856f1dc65cbbaa1b851ea6f4c41e3 | Python | 445 | 11 | ##########################################################################
# NSAp - Copyright (C) CEA, 2016
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########... |
a6cac9a3c6566f9d75ec8a8b9022b84f561120577eb89c59330b04d40e060b73 | Python | 446 | 16 | import numpy as np
import pytest
import optimap as om
def test_activationmap():
vid = np.zeros((100, 100, 100), dtype=np.float32)
for i in range(100):
vid[i, i, i] = 1
amap = om.activation.compute_activation_map(vid, fps=100, show=False)
assert amap.shape == (100, 100)
for i in range(100)... |
6ce5374d4bac913d760e9a7e4ac098b4259d1ef043a773167f712dab864c753f | Python | 447 | 23 | """
Public toolkit API.
"""
from pandas._libs.lib import infer_dtype
from pandas.core.dtypes.api import * # noqa: F403
from pandas.core.dtypes.concat import union_categoricals
from pandas.core.dtypes.dtypes import (
CategoricalDtype,
DatetimeTZDtype,
IntervalDtype,
PeriodDtype,
)
__all__ = [
"in... |
47376046560b56642488b79f001c106fd0ad9d90cb4049964e41585cd9a78a89 | Python | 449 | 22 | # TO GET DATA READY FOR THE TESTER
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--dataset", type=str, choices=["abide1", "hcpRest", "hcpTask"], default="abide1")
parser.add_argument("-a", "--atlas", type=str, choices=["schaefer7_400"], default="schaefer7_400")
argv = parser.parse_ar... |
4ef45256aafe82496cf2b8fe44605b34d343109426e7afa7037140fa19b198ab | Python | 449 | 9 | from monai.losses import DiceCELoss, DiceLoss
def loss_funtions(config, beta=200, gamma=400, total_epochs=600):
if config["loss"] == "Dice":
loss_function = DiceLoss(include_background=False,to_onehot_y=True, softmax=True)
if config["loss"] == "DiceCE":
loss_function = DiceCELoss(include_backg... |
d27c8b000adc6cde894100ea0612e427f9d88f9cf4ce94276992d620c3cef0f4 | Python | 449 | 21 | from typing import Any, NamedTuple, cast
import numpy as np
# Subtype of tuple[int, int]
class XYGrid(NamedTuple):
x_axis: int
y_axis: int
# TODO: remove this cast after: https://github.com/numpy/numpy/pull/27171
arr: np.ndarray[XYGrid, Any] = cast(
np.ndarray[XYGrid, Any],
np.empty(XYGrid(2, 2)),
)... |
0dec01f175e42c610382d42a20260f9a7919677638b4deb33e84d8be936e2461 | Python | 450 | 23 | from pandas.core.window.ewm import (
ExponentialMovingWindow,
ExponentialMovingWindowGroupby,
)
from pandas.core.window.expanding import (
Expanding,
ExpandingGroupby,
)
from pandas.core.window.rolling import (
Rolling,
RollingGroupby,
Window,
)
__all__ = [
"Expanding",
"ExpandingGr... |
9c2d2ae5e4b8a615f5dec025c93629bb4b5302418a150b2c94d667c2790cc3c9 | Python | 451 | 18 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 10:04:33 2018
@author: am985309
"""
import os
# MathLangage experiment
# IMPORTANT: adapt TOTAL_EXPE_DURATION in file audiovis.py if necessary
# Higher onset for last white cross : 567000 ms = 567 s = 9,46 min = 9 min 27 s
# subject 01 ###############... |
890504e48cb46a321479f32626a0f7d6d46e71ba84eb9863e26fcb92f85fc906 | Python | 453 | 18 | import os
from pathlib import Path
from typing import Tuple
import yaml
config_folder = Path(os.getenv('LOCALAPPDATA')) / "Grimace Recorder" / "config"
camera_ids_file = config_folder / "camera_ids.yaml"
def load_camera_ids() -> Tuple[str | None, str | None]:
if not camera_ids_file.exists():
return None... |
9999de04182e363b2e7bedeaa56f7f35757b8a20cc5ddd8e6dd8fa81648dc6b6 | Python | 455 | 23 | from .download import download_file
from .pipelines import (
check_cfg_parameters,
close_loggers,
init_wandb,
load_envs,
load_from_checkpoint,
seed_everything,
set_additional_params,
write_predictions_to_db,
)
__all__ = [
download_file,
check_cfg_parameters,
close_loggers,
... |
280569705120f8546a49f8b2f11a4011dec6cf49fdfda8298e86ec02da2dd24b | Python | 456 | 15 | import cedalion.data
import cedalion.sigdecomp.dummy
def test_split_frequency_bands():
recordings = cedalion.data.get_snirf_test_data()
amp = recordings[0].timeseries["amp"]
assert amp.dims == ("channel", "wavelength", "time")
x = cedalion.sigdecomp.dummy.split_frequency_bands(amp)
assert x.dim... |
7286858ac6b4f584622ad5347c115929d5aaf953b8dee4d1abd44f2a8f8c9051 | Python | 456 | 15 | import json
import os.path
from os.path import join
def JsonSort():
path = r'G:\qxz\DataSet\BrainSegDataSet301\DataSet4\Predict3\info.json'
savePath = join(os.path.dirname(path), 'info_sort.json')
with open(path, 'r') as f:
data = json.loads(f.read())
data = sorted(data, key=lambda x: x[-1]... |
504220d0b4e34ada1cbed3c2125ac7f5076d820b612a661c73e2b3207198187a | Python | 457 | 12 | # -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2019
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
#... |
37fdd2aa85b98909b2f4494c140adbff32c9e27f1b78c08907ef27fccec4f0c8 | Python | 458 | 12 | # 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.
""" Classes representing complex qualifiers for features.
"""
from .asf import ActiveSiteFinderQualifier
from .gene_functions import GeneFunction, GeneFunctionAnnotations... |
c94950e21d899aa838202bf096b1a0c28afdd2b903008168a9bb32c13180fbd5 | Python | 459 | 15 | #!/usr/bin/env python3.7
"""Initialize the utils package.
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
"""
from .configur... |
3e790112df128f6d3ce891156c559ac1c83675acb2eac80383602c7a688799b9 | Python | 460 | 15 | from dp5.neural_net.nfp.layers import *
from dp5.neural_net.nfp.models import *
custom_layers = {
'MessageLayer': MessageLayer,
'EdgeNetwork': EdgeNetwork,
'ReduceAtomToMol': ReduceAtomToMol,
'ReduceBondToAtom': ReduceBondToAtom,
'GatherAtomToBond': GatherAtomToBond,
'GRUStep': GRUStep,
'Em... |
7a2ebd9b31cd0bbe6eedbeb8b41c47582cd76f3bd0d3d989ee6dc83d4fb4d52b | Python | 460 | 18 | from rdkit.Chem.AtomPairs import Pairs
from rdkit.Chem import DataStructs
import numpy as np
_type = 'topological-based'
def GetAtomPairFPs(mol, nBits = 2048, binary = True):
'''
atompairs fingerprints
'''
fp = Pairs.GetHashedAtomPairFingerprint(mol, nBits = nBits)
if binary:
arr = np.zer... |
ea992172cde9841c08efbdecb0019c3120c07a4320fc09de123dbe3ea30e26ac | Python | 460 | 16 | import os
import mrcfile
import numpy as np
def read_mrc(filename: os.PathLike) -> np.ndarray:
with mrcfile.open(filename, permissive=True) as mrc:
data = mrc.data
return data
def get_image_dimensions(filename: os.PathLike) -> np.ndarray:
"""Get array of image dimensions (xyz) from an MRC file ... |
62206840ddc3a2bda9df61c2502a255886411fadb41f568f6b879ab00e453207 | Python | 462 | 18 | import numpy as np
import pytest
from pandas import (
CategoricalIndex,
Index,
)
import pandas._testing as tm
@pytest.mark.parametrize("na_value", [None, np.nan])
def test_difference_with_na(na_value):
# GH 57318
ci = CategoricalIndex(["a", "b", "c", None])
other = Index(["c", na_value])
resu... |
b10bc2cd18d22831715cb3efb160d043d9e3d12a1970a234f45bff4c8cde5a10 | Python | 463 | 13 | from .snirf import read_snirf, write_snirf, compress_snirf
from .probe_geometry import (
read_mrk_json,
read_digpts,
read_einstar_obj,
load_tsv,
export_to_tsv,
read_fieldtrip_elc,
)
from .anatomy import read_segmentation_masks, read_parcellations, read_parcel_colors
from .photogrammetry import r... |
13e8acba80d2f9c612fcacfcf5851b91adebbc36560e2d694c8b29b63b44000b | Python | 464 | 21 |
import os
import nilearn as nil
import nilearn.datasets
datadir = "./Dataset/Data"
def prep_atlas(atlas):
if(atlas == "schaefer7_400"):
if(not os.path.exists(datadir + "/Atlasses/{}".format(atlas))):
atlasInfo = nil.datasets.fetch_atlas_schaefer_2018(n_rois=400, yeo_networks=7, resolutio... |
d01bfc43a6d6e4ff67f717880ef659409c50b89ca96fbe84832e862f6612be21 | Python | 464 | 14 | import scanpy as sc
import pandas as pd
adata = sc.read_h5ad(snakemake.input.merged_atac_anndata)
# Import the RNA annotation
rna_annot = pd.read_csv(snakemake.input.annot_csv)
# Convert to a dictionary
celltype_bc = dict(zip(rna_annot['atlas_identifier', 'cell_type']))
# Assign cell types from RNA data
adata.obs['c... |
3b310939fcc25a8cd79a4df52974ea5e874c2796f710584d3f4464dad0f0cd4a | Python | 465 | 20 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, expected",
[
(resources.EMPTY_STR, 0.0),
(resources.EASY_TEXT, 1.182),
(resources.SHORT_TEXT, 1.0),
(resources.PUNCT_TEXT, 1.4),
... |
2c6b30dca3164ea75efc320a85f5f5410167aa8ec3c5c3b69033934777a0c947 | Python | 467 | 18 | from gym.envs.registration import register
# Multiagent envs
# ----------------------------------------
register(
id='MultiagentSimple-v0',
entry_point='multiagent.envs:SimpleEnv',
# FIXME(cathywu) currently has to be exactly max_path_length parameters in
# rllab run script
max_episode_steps=100,
... |
9f3b674e05c19dd80478b8cb0e5db7ffb519f22566f1f40350b08064a5cdc3c4 | Python | 469 | 17 | """Cali package."""
from __future__ import annotations
import warnings
from importlib.metadata import PackageNotFoundError, version
# need to suppress the cvxpy warning from oasis before importing cali
warnings.filterwarnings("ignore", "Could not find cvxpy.*", UserWarning)
try:
__version__ = version("micromana... |
d6bd78ce2f79a00f66cd9b03f40fe607e3b47cd21ff989f6861e11d290ec215f | Python | 470 | 16 | import torch
from torch import optim
from protgps.utils.registry import register_object
from protgps.utils.classes import ProtGPS
from ray.tune.suggest import BasicVariantGenerator
@register_object("basic", "searcher")
class BasicSearch(BasicVariantGenerator, ProtGPS):
"""Description
See: https://docs.ray.io... |
587bfd075dc7e428999fee4324b406189897e9254d9eb728c91272563fe28fa3 | Python | 471 | 26 | IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]
OPENAI_MEAN = [0.48145466, 0.4578275, 0.40821073]
OPENAI_STD = [0.26862954, 0.26130258, 0.27577711]
MODEL2CONSTANTS = {
"resnet50_trunc": {
"mean": IMAGENET_MEAN,
"std": IMAGENET_STD
},
"uni_v1":
{
"mean": IMAGENET_MEAN,
"std": IMAG... |
eeb630b8e91ca286a75c2557452adc4219205143eeea1af026475b257530ece8 | Python | 471 | 20 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, expected",
[
(resources.EMPTY_STR, 0.0),
(resources.EASY_TEXT, 22.131),
(resources.SHORT_TEXT, 25.0),
(resources.PUNCT_TEXT, 23.808)... |
b2017cb613dba9fd426d5dfdec63890224772a8904448e6987ff0649bdcd057d | Python | 472 | 18 | import pytest
import yass
def test_can_initialize_config(path_to_config):
yass.Config.from_yaml(path_to_config)
def test_throws_error_if_channels_mismatch(path_to_config_with_wrong_channels):
with pytest.raises(ValueError):
yass.Config.from_yaml(path_to_config_with_wrong_channels)
def test_cannot_... |
fc647df5b6c8b5b4db51657b92ed34215889a123d6dfe48d116ecf529bebdee0 | Python | 472 | 21 |
import pytest
import xarray as xr
import cedalion
import cedalion.data
@pytest.fixture
def rec():
rec = cedalion.data.get_snirf_test_data()[0]
rec["od"] = cedalion.nirs.cw.int2od(rec["amp"])
# differential pathlenght factors
dpf = xr.DataArray(
[6, 6],
dims="wavelength",
coord... |
c0f4069a07b6c99f77dbc107285ea069d19ec866022502b1b54fa22ca13a5270 | Python | 473 | 18 | from __future__ import annotations
import json as _json
import typing as t
class _CompactJSON:
"""Wrapper around json module that strips whitespace."""
@staticmethod
def loads(payload: str | bytes) -> t.Any:
return _json.loads(payload)
@staticmethod
def dumps(obj: t.Any, **kwargs: t.Any... |
39be55ad7378e8c534cad395b279cbd9afeb474a1c33338f7eef1490701661d8 | Python | 474 | 24 | from rdkit.Chem import AllChem
from rdkit.Chem import DataStructs
import numpy as np
import pandas as pd
import os
_type = 'SMARTS-based'
file_path = os.path.dirname(__file__)
def GetMACCSFPs(mol):
'''
166 bits
'''
fp = AllChem.GetMACCSKeysFingerprint(mol)
arr = np.zeros((0,), dtype=np.bool... |
765fa32cc4d178eaa777b629d96e5abcc5430526918ed8a4eb1b7b0d9cbdad13 | Python | 475 | 18 | from rdkit.Chem.AtomPairs import Torsions
from rdkit.Chem import DataStructs
import numpy as np
_type = 'topological-based'
def GetTorsionFPs(mol, nBits = 2048, binary = True):
'''
atompairs fingerprints
'''
fp = Torsions.GetHashedTopologicalTorsionFingerprint(mol, nBits = nBits)
if binary:
... |
4fa236132a29748b4a6a6728906d3296f853ee4ad9621054ea1177505201af68 | Python | 476 | 17 | """See https://github.com/numpy/numpy/pull/10676.
"""
import sys
import pytest
from . import util
class TestQuotedCharacter(util.F2PyTest):
sources = [util.getpath("tests", "src", "quoted_character", "foo.f")]
@pytest.mark.skipif(sys.platform == "win32",
reason="Fails with MinGW64 G... |
ab29fb90fe5bd78332c2da8e50be42f8d3af8dfdaa2b83ec5c6a42bea9a8fb81 | Python | 476 | 14 | import numpy as np
from pandas.core.dtypes.cast import dict_compat
from pandas import Timestamp
def test_dict_compat():
data_datetime64 = {np.datetime64("1990-03-15"): 1, np.datetime64("2015-03-15"): 2}
data_unchanged = {1: 2, 3: 4, 5: 6}
expected = {Timestamp("1990-3-15"): 1, Timestamp("2015-03-15"): 2... |
724f7fb19f466ee53432221684ea35b20f888031888518a3b1d997e1fb6ad7fc | Python | 480 | 14 | """Analysis module for computing metrics from extracted calcium imaging traces.
This module provides tools for analyzing extracted trace data:
- AnalysisRunner: Main class for running analysis on FOVs with existing Traces
- Peak detection in denoised traces
- Inter-event interval (IEI) calculation
- Event frequency co... |
7a998fb65318fac9f4e9c652e46989db1bfe6ba0fe9103bdc6b85af5946f7424 | Python | 480 | 17 | import json, os
from os.path import join
import numpy as np
def MeanPR():
path = r'G:\qxz\DataSet\BrainSegDataSet301\HaiNanDataSet1\DataSet128\Predict\info.json'
with open(path, 'r') as f:
data = json.loads(f.read())
prs = []
for item in data:
prs.append(np.array(item[-1].sp... |
253f650616c5f749b6cd1808c1aae13ea3ed55baef90b8a2859c4efb8587bd35 | Python | 482 | 18 | import numpy as np
import pytest
from pandas import (
NaT,
PeriodIndex,
period_range,
)
import pandas._testing as tm
class TestInsert:
@pytest.mark.parametrize("na", [np.nan, NaT, None])
def test_insert(self, na):
# GH#18295 (test missing)
expected = PeriodIndex(["2017Q1", NaT, "2... |
ba902099706db9f584c40c65ab36942e7a9329d6f37a6eb077b23b85f30e14a3 | Python | 482 | 27 | from ._datasets import (
bonemarrow,
dentategyrus,
dentategyrus_lamanno,
forebrain,
gastrulation,
gastrulation_e75,
gastrulation_erythroid,
pancreas,
pbmc68k,
toy_data,
)
from ._simulate import simulation
__all__ = [
"bonemarrow",
"dentategyrus",
"dentategyrus_lamann... |
cb01772b661f35e5f1ad575861466e5639c621bc7b300641d3920b1b29197a45 | Python | 482 | 11 | from pathlib import Path
def test_public_page_contains_scpportal_tool_routes() -> None:
html = (Path(__file__).parents[1] / "site" / "index.html").read_text(encoding="utf-8")
assert "Dataset Browser" in html
assert "https://peterponyu.github.io/scportal/datasets/" in html
assert "Continuity Explorer" ... |
b960e8bb20337da1767d208d9dcd07c25ae1a57f9f8188d30c36705f6fc88906 | Python | 483 | 18 | """Contains code to execute hmmpress, hmmsearch and hmmalign"""
from .hmmer import HMMer, cds_to_input_task, cds_batch_generator # type: ignore
from .hsp import HSP, HSPAlignment
from .legacy_filter import legacy_filter_overlap
from .hmmsearch import run_hmmsearch
from .hmmalign import run_hmmalign
__all__ = [
"... |
3f9762e3c63cc5c7c880fb8547d43dd627f91f81e0718c77a5bab7aa3c1caa7e | Python | 484 | 14 | import sys
sys.path.append("../")
import time
from model import cortex_thalamus
if __name__ == '__main__':
starttime = time.time()
myCortex = cortex_thalamus.Cortex_Thalamus(1000) # create a cortex object and specify the neuron number scale
myCortex.CreateCortexNetwork() # create cortex-thalamus network ... |
a60dd00f13f7e865b6aa7c1efc2a4fb644613dc87255218ceb3941356b8d0851 | Python | 484 | 16 | from __future__ import annotations
import typing as t
from flask import current_app
def add_models_to_shell() -> dict[str, t.Any]:
"""Registered with :meth:`~flask.Flask.shell_context_processor` if
``add_models_to_shell`` is enabled. Adds the ``db`` instance and all model classes
to ``flask shell``.
... |
ef2e868438e1e879d8f742a2ec7835dbe239494a2d8d7569f67796d9f7fcab6c | Python | 485 | 12 | # -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2019
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
#... |
2a7ecbb3713bb2b274952427704c09c1535252fcf98f01875fd4c02e7e911094 | Python | 486 | 16 | # -*- coding: utf-8 -*-
import numpy as np
def calc_score(answer_list, pt_fdbk_list):
"""
Calculate the final score of the participant based on the number of
correct answers.
"""
answer = np.array(answer_list)
pt_fdbk = np.array(pt_fdbk_list)
score_list = np.where(answer == pt_fdbk, 1, 0)
... |
c3ada01d0f671775e004e9a384cf1e1e657e61717b81f973d6516ac45abb8a8f | Python | 486 | 19 | from pandas.io.excel._base import (
ExcelFile,
ExcelWriter,
read_excel,
)
from pandas.io.excel._odswriter import ODSWriter as _ODSWriter
from pandas.io.excel._openpyxl import OpenpyxlWriter as _OpenpyxlWriter
from pandas.io.excel._util import register_writer
from pandas.io.excel._xlsxwriter import XlsxWrite... |
6f70c97322e8840115dcf9ca5367ffeb6bc8ad8b34ea703e6aeb16f06348263d | Python | 488 | 24 | '''
Created on 2018.9.7
@author: liangqian
'''
import time
import sys
import stomp
def createMSQ():
queue_name = '/queue/SampleQueue'
conn = stomp.Connection([('localhost',61613)])
#conn.start()
print("building connection to activemq......")
conn.connect()
#return conn
# for i in range (10... |
c5908f2fa91a6153be4eeb6064728f8e8990afe84d1642e25ed62ef49de65b0e | Python | 488 | 20 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, expected",
[
(resources.EMPTY_STR, 0.0),
(resources.EASY_TEXT, 4.354),
(resources.SHORT_TEXT, 5.0),
(resources.PUNCT_TEXT, 4.66),
... |
fad124a29eea63d8bb7160f91335d71bf7060aa250ff91ae4dafda8a1ad58956 | Python | 490 | 13 | # 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.
""" Contains Exception subclasses for more specific communication of issues """
class SecmetInvalidInputError(ValueError):
""" An error for when input is invalid or ... |
1d916842b779c6f684253bc9de8c9382a2b63dba4d7e71a12ef0358267276dfa | Python | 492 | 17 | import sys
import os
# List of directories to be added to sys.path
directories = ['components',
'curation',
'data',
'features',
'networks',
'notebooks',
'output',
'train',
'... |
1b31bb6c60d45b81ad8d5af89fcb92a409bdeed95f1e61014500abda6e6566fc | Python | 493 | 20 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, expected",
[
(resources.EMPTY_STR, 0.0),
(resources.EASY_TEXT, 4.222),
(resources.SHORT_TEXT, 4.8),
(resources.PUNCT_TEXT, 4.283),
... |
c7d6611b1f689ee8d4a3b0f476c4d2d590dad629b1c8d188a60120e6a3d67fdb | Python | 493 | 16 | import torch.nn as nn
def get_activation(activation_choice):
if activation_choice == 'relu':
return nn.ReLU()
elif activation_choice == 'leakyrelu':
return nn.LeakyReLU(negative_slope=0.2)
elif activation_choice == 'elu':
return nn.ELU()
elif activation_choice == 'gel... |
f195b70313241e3dc8575c1580cefded21ffad12ca43dce57755159219350bc4 | Python | 493 | 18 | import numpy as np
from pandas import (
DatetimeIndex,
Series,
)
import pandas._testing as tm
class TestToSeries:
def test_to_series(self):
naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B")
idx = naive.tz_localize("US/Pacific")
expected = Series(np.array(idx.t... |
764e136bfbe67552716070dc7f286f40dc3c5773e0481a2628d5ea83e0f62436 | Python | 494 | 15 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
__title__ = "packaging"
__summary__ = "Core utilities for Python packages"
__uri__ = "https://github.com/pypa/packaging"
__version__ = "24... |
ff470388f55fd92f9b35f566660bb1c739ab2185a5c804b1a6aa61e2ab095947 | Python | 494 | 15 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
__title__ = "packaging"
__summary__ = "Core utilities for Python packages"
__uri__ = "https://github.com/pypa/packaging"
__version__ = "25... |
5cee011f984404c5cfb46e0f57688362bffc09b4893e1c3523da3583125852cf | Python | 495 | 20 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, expected",
[
(resources.EMPTY_STR, 0.0),
(resources.EASY_TEXT, 9.0),
(resources.SHORT_TEXT, 5.0),
(resources.PUNCT_TEXT, 10.6),
... |
c351e5b90d874de3d144d8f9f036d7c17236aee34cb8161bed0e9912671e9310 | Python | 495 | 16 | import os
import random
folder_path = "/media/MD3400-2/Cailin/training_data/image"
all_files = os.listdir(folder_path)
train_percent = 0.8
num_files_80_percent = int(train_percent * len(all_files))
selected_files = random.sample(all_files, num_files_80_percent)
output_file_path = "/media/MD3400-2/Cailin/training_data... |
397be90ab0c1cf470d6fad874389e326d05768dd53eb01e6987c0715ed0e8b02 | Python | 496 | 21 | import pandas as pd
import numpy as np
import scanpy as sc
import pickle
import os
import anndata as ad
import scanpy as sc
# Load samples matched to
sample_loc = dict(zip(snakemake.params.samples, snakemake.input.atac_anndata))
adatas = {key: sc.read_h5ad(sample_loc[key]) for key in sample_loc.keys()}
adata = ad.... |
cab0e3cdbc96f07de25ac2494d99f7064352021a0733b0ccab4330fd847f0862 | Python | 496 | 20 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, expected",
[
(resources.EMPTY_STR, 0.0),
(resources.EASY_TEXT, 5.4),
(resources.SHORT_TEXT, 6.12),
(resources.PUNCT_TEXT, 6.249),
... |
fa09a4fe7cfef711d2ec8f1cf72881270aecd7209ebf8d276a7a821480f96313 | Python | 497 | 20 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, expected",
[
(resources.EMPTY_STR, 0.0),
(resources.EASY_TEXT, 0.111),
(resources.SHORT_TEXT, 0.2),
(resources.PUNCT_TEXT, 0.094),
... |
ae0c1c69f19bc09ced97f37809a96f0275ba14a7ca54dcc9704f918dc5cca51f | Python | 498 | 19 | import pandas as pd
import pandas._testing as tm
def test_array_setitem_nullable_boolean_mask():
# GH 31446
ser = pd.Series([1, 2], dtype="Int64")
result = ser.where(ser > 1)
expected = pd.Series([pd.NA, 2], dtype="Int64")
tm.assert_series_equal(result, expected)
def test_array_setitem():
# ... |
39813fa76ecf479be09b88fbd9eb60ea7b3f179e0a9259dfe4abe062558eecd1 | Python | 500 | 18 | from __future__ import annotations
from textstat import textstat
import pytest
from ..backend import resources
@pytest.mark.parametrize(
"rm_apostrophe,expected",
[
(True, resources.PUNCT_TEXT_RESULT_WO_APOSTR),
(False, resources.PUNCT_TEXT_RESULT_W_APOSTR),
],
)
def test_set_rm_apostroph... |
704d9b658470229c5768bd122e720ab504b48d164f0c5de4d5ea7dae97ac2d55 | Python | 500 | 17 | """
Interfaces bridging different backends
"""
from . import tensortrans
from .tensortrans import (
which_backend,
numpy_args_to_backend,
general_args_to_numpy,
general_args_to_backend,
args_to_tensor,
)
from .numpy import numpy_interface, np_interface
from .scipy import scipy_interface, scipy_opti... |
d92d76424be1cf796e36b31bb2e2424d276741ff1f980021b87ec71920dcc819 | Python | 500 | 19 | from ._get_cmudict import get_cmudict
from ._get_grade_suffix import get_grade_suffix
from ._get_lang_cfg import get_lang_cfg
from ._get_lang_easy_words import get_lang_easy_words
from ._get_lang_root import get_lang_root
from ._get_pyphen import get_pyphen
from ._typed_cache import typed_cache
from . import constants
... |
53b09271a2c6a4f8e2fd44281686648aa1f7a0fffd6304f6cf7d45670ceaaaf2 | Python | 501 | 16 | import sys
sys.path.append('.')
from plotting.utils import load_results, mesh_name, sim_name, gap_size_histo
import matplotlib.pyplot as plt
if __name__ == '__main__':
sim_name = sys.argv[1]
mesh_name = sys.argv[2]
results = load_results(mesh_name, sim_name)
gap_size_histo(results["pvs_volume_counts"], resu... |
078be99b9dd1d150f7a2dab07446bce1c4abeef4cc5a20ff4ffe09a5691a4af3 | Python | 502 | 18 | from __future__ import annotations
import pytest
from textstat.backend import counts
from .. import resources
@pytest.mark.parametrize(
"test,lang,expected",
[
(resources.EASY_TEXT, "en_US", 6),
(resources.SHORT_TEXT, "en_US", 1),
(resources.PUNCT_TEXT, "en_US", 4),
(resources... |
03088ab94720ee6ff7a62430c73391f4ee829bbf1b4b480a9522fcc4d714c1ab | Python | 505 | 18 | from __future__ import annotations
import pytest
from textstat.backend import counts
from .. import resources
@pytest.mark.parametrize(
"test,lang,expected",
[
(resources.EASY_TEXT, "en_US", 65),
(resources.SHORT_TEXT, "en_US", 4),
(resources.PUNCT_TEXT, "en_US", 41),
(resourc... |
85762e1463b68e823873323a4666465a2af6e93dcf8671d6942434adb58e3669 | Python | 509 | 16 | import pytest
from wordfreq import tokenize, word_frequency
def test_tokens():
assert tokenize("감사합니다", "ko") == ["감사", "합니다"]
def test_combination():
gamsa_freq = word_frequency("감사", "ko")
habnida_freq = word_frequency("합니다", "ko")
assert word_frequency("감사감사", "ko") == pytest.approx(gamsa_freq /... |
4a05493bc0bf038ceb28558764269e4f78806cba4ef6bf98391acb8c47f5738a | Python | 510 | 13 | from yass.batch.batch import BatchProcessor
from yass.batch.reader import RecordingsReader, BinaryReader, MemoryMap
from yass.batch.generator import IndexGenerator
from yass.batch.pipeline import PipedTransformation, BatchPipeline
from yass.batch.vectorize import vectorize_parameter
__all__ = ['BatchProcessor',
... |
6c65ce5be70b9eeb2df09ed0baf81d0e157d5f9329fcb261ef2317de8883d704 | Python | 510 | 12 | from configs.Config import Config
class Experiment(Config): # 这个还没改且里面没有
def __init__(self, steps, episodes, random_seed, env_config, controller_config, learner_config):
super(Experiment, self).__init__() # TODO device 在env里面加入了
self.steps = steps
self.episodes = episodes
self.r... |
97a645257c2f35bf8f429ec8e7c47c7d0c9762a5664710ca19b67bbca40024e0 | Python | 510 | 21 | from __future__ import annotations
import pytest
from textstat.backend import utils
@pytest.mark.parametrize(
"lang, n_words",
[
("en", 2941),
("es", 20000),
("de", 2941),
("fr", 2941),
],
)
def test_get_lang_easy_words(lang: str, n_words: int) -> None:
if lang not in ... |
4bb8bd0e7f5a4994b4306fb65abbdeddd57d4c898fcef427e638e1a7db7fb9fd | Python | 511 | 18 | from __future__ import annotations
from pip._internal.utils import _log
# init_logging() must be called before any call to logging.getLogger()
# which happens at import of most modules.
_log.init_logging()
def main(args: list[str] | None = None) -> int:
"""This is preserved for old console scripts that may stil... |
e2bba3c052aa819f4841d0eefac2fdddffb9fcd0afcb0544d9e286a6ff245d27 | Python | 511 | 17 | def calc_signal_var(baseline, value, maxPSC):
"""
Calculates NF Signal.
Args:
baseline: float - baseline value for current time point
value: float - BOLD value at current time point
maxPSC: float - maximum variation (percent value)
Returns:
float: Normalized signal vari... |
ac3a4557f782ec0258a289c3f3ca9df08fd2e364fe40f1b491d5a6e672e1ae45 | Python | 513 | 18 | #!/usr/bin/env python
"""
Setup configuration for iaode package.
This file is kept for backward compatibility. Modern build uses pyproject.toml.
"""
from setuptools import setup # type: ignore
# Read long description from README
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
#... |
110b573d4d746c2f75c9db169e57d7e9aaa9c094d757a36d6fd299a08b05370b | Python | 514 | 21 | import os
from pathlib import Path
import pytest
import cedalion.io.nirs
skip_if_snirf_zoo_unavailable = pytest.mark.skipif(
"SNIRF_ZOO" not in os.environ, reason="snirf zoo not available"
)
testfiles = []
if "SNIRF_ZOO" in os.environ:
snirf_zoo_dir = Path(os.environ["SNIRF_ZOO"])
testfiles.extend(sorte... |
4d53f19842938764c274ab261bc9a380da6fe4b958dd4857d8ac3cc890074fbb | Python | 516 | 21 | import numpy as np
class RunningStatsArray:
"""Class to compute running mean for complex arrays."""
def __init__(self):
self.n = 0
self.mean = None
def push(self, x):
"""Update the running mean with a new array x."""
x = np.asarray(x)
if self.mean is None:
... |
5a0772ab09176f60c18ac715a5bfd1fe31e1a50d2aa3c54db393db03ab81a3da | Python | 516 | 16 | import mne
# Path to the EDF file
edf_path = "/sub-01_task-BT_acq-BLP_eeg.edf"
# Load the EDF file (preload=True loads data into memory for faster plotting/processing)
raw = mne.io.read_raw_edf(edf_path, preload=True)
# Print a short summary of the Raw object (optional)
print(raw)
# Plot the raw time-ser... |
7b57b38c4710dbda5b0e88c3c7e39d0be539e1525a2a4503d07e9ee891facae0 | Python | 516 | 20 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, expected",
[
(resources.EMPTY_STR, 0.0),
(resources.EASY_TEXT, 3.575),
(resources.SHORT_TEXT, 4.62),
(resources.PUNCT_TEXT, 5.82),
... |
7c3e49ba06edff7f676757958cf35d020a0346e3574dc9d907d940e30ebceef3 | Python | 517 | 19 | """
Tests for Indexes backed by arbitrary ExtensionArrays.
"""
import pandas as pd
class BaseIndexTests:
"""Tests for Index object backed by an ExtensionArray"""
def test_index_from_array(self, data):
idx = pd.Index(data)
assert data.dtype == idx.dtype
def test_index_from_listlike_with_d... |
9169099036ff746fa1b1d930d888ab340f0559ccc1d87b51b432787dd2a510a4 | Python | 517 | 16 | from rna3db.utils import read_json
from pathlib import Path
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Converts a JSON produced by RNA3DB's parse command to a FASTA file."
)
parser.add_argument("input_path", type=Path)
parser.add_argument("output_... |
d11425068c8d499fc0fbb1dd0558d5fd008afbcef5e5d1ffd9279f4d3821b429 | Python | 517 | 7 | from dp5.nmr_processing.proton.integrate import find_integrals, weighted_region_centres
from dp5.nmr_processing.proton.peak_picking import gradient_peak_picking
from dp5.nmr_processing.proton.fid_corrections import spectral_processing
from dp5.nmr_processing.proton.solvent_removal import solvent_removal
from dp5.nmr_pr... |
0f4e246d144fd1eb51c4c77f1a0b70f4e2aae6cf66e762176b954c33f6b138f3 | Python | 518 | 18 | from rdkit.Chem import AllChem
from rdkit.Chem import DataStructs
import numpy as np
def GetMorganFPs(mol, nBits=2048, radius = 2, return_bitInfo = False):
"""
ECFP4: radius=2
"""
bitInfo={}
fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=radius,
... |
675b782140b630ed1ae4a6c0d0bbab59f4592f8c0d92c1d50432e9ac6b4f2e5a | Python | 520 | 27 | from pandas.core._numba.kernels.mean_ import (
grouped_mean,
sliding_mean,
)
from pandas.core._numba.kernels.min_max_ import (
grouped_min_max,
sliding_min_max,
)
from pandas.core._numba.kernels.sum_ import (
grouped_sum,
sliding_sum,
)
from pandas.core._numba.kernels.var_ import (
grouped_v... |
741a1019e6e18a16cbf310a2e92c27fcb15608a2e30872da54077632e658c5ad | Python | 520 | 15 | import pandas as pd
# Read the top 200 candidates file
top_200 = pd.read_csv('CT2_log/euclidean/final_candidate/top_200_candidates.csv')
# Create a new dataframe with just the gene names
genes_only = pd.DataFrame({'Gene Name': top_200['Gene']})
# Save to a new file
genes_only.to_csv('CT2_log/euclidean/final_candidat... |
a19a9697f1b2bc7294f99b00c9390c4a2d18c94f28a81cc5d301d16ed470059f | Python | 520 | 17 | import sys
sys.path.append('.')
from plotting.utils import load_results, mesh_name, sim_name, gap_size_histo
import matplotlib.pyplot as plt
if __name__ == '__main__':
sim_name = sys.argv[1]
mesh_name = sys.argv[2]
results = load_results(mesh_name, sim_name)
gap_size_histo(results["ecs_volume_counts"], resu... |
075bfce9f69d1de89374bf1cc5a8b32ce86c1c306a916607f489b3d9061cb190 | Python | 521 | 17 | import sys
sys.path.append('.')
from plotting.utils import load_results, mesh_name, sim_name, gap_size_histo
import matplotlib.pyplot as plt
if __name__ == '__main__':
sim_name = sys.argv[1]
mesh_name = sys.argv[2]
results = load_results(mesh_name, sim_name)
gap_size_histo(results["ef_volume_counts"], resul... |
a303e47aa771821ce206c14584f7871f4b2bb6b4f54c302f47d23f0995546a4b | Python | 522 | 13 | EVEN_SUFFIX = '_half1' #The suffix given to even tomograms during split tomogram generation. This will be removed from the names of the output tomograms
PREDICT_CONFIG_PREFIX = 'predict_config' #Name (minus the suffix) of the predict_config.json file
TRAIN_DATA_CONFIG_PREFIX = 'train_data_config' #Name (minus the suf... |
17f1de5ce5ed28f5451b7986739b2116bf216e8670978d44a5d083ddf9e7f9ec | Python | 524 | 17 | import pandas as pd
import pyranges as pr
# Load bed file
peak_file = pd.read_csv(snakemake.input.xls, delimiter='\t', skiprows=1)
# Only for gappedPeak
peak_file.columns =['chr', 'start', 'end', 'name', 'score', 'blank1', 'blank2', 'blank3', 'summit', 'blank4', 'blank5', 'blank6', 'blank7', 'blank8', 'blank9']
# Con... |
0d8d92b8db5bb8de0cca54d56145c4c0ba600980dc5ac04356a150e2ab02b03a | Python | 527 | 20 | import muon as mu
import scanpy as sc
# Read in data
mdata = mu.read_h5mu()
# Split out only the celltype AnnData, and reduce the size of the object
mdata = mdata[mdata.obs['rna:cell_type'] == snakefile.params.cell_type].copy()
# Split out the RNA AnnData
rna = mdata['rna'].copy()
# Split out the ATAC AnnData
atac ... |
7980fa49248f457c9525e45d76d50aff40afbed2d481f34911b6558b77b3c653 | Python | 527 | 22 | from __future__ import annotations
def get_grade_suffix(grade: int) -> str:
"""Select correct ordinal suffix.
Parameters
----------
grade : int
The grade of the text.
Returns
-------
str
The ordinal suffix.
"""
ordinal_map = {1: "st", 2: "nd", 3: "rd"}
teens_m... |
e31624f307403b09c91af01ce5aa9ac6892581150228b1299b56f912d54e87f9 | Python | 527 | 27 | from __future__ import annotations
import re
from ..utils._typed_cache import typed_cache
@typed_cache
def count_chars(text: str, ignore_spaces: bool) -> int:
"""Count the number of characters in a text.
Parameters
----------
text : str
A text string.
ignore_spaces : bool, optional
... |
9bdb05edfa57e9c4f015482f39c83390a2127a42e237c23712157a609be12e24 | Python | 528 | 14 | from crystal_tracer.algorithm.tracking import independent_match
import pickle
import pandas as pd
from pathlib import Path
import math
if __name__ == '__main__':
df_folder = Path('../../data/case2/detection')
frames = [pd.read_csv(df_folder / f"{i}.csv") for i in range(len([*df_folder.glob('*.csv')]))]
for... |
3db2faff4042dd47bd9a25a3a88a83bf24af698613446981cc119f9271e64d09 | Python | 529 | 18 | """
Shared path helpers for notebooks/Final_Figures scripts so they all agree on
where the project root and data tables live.
"""
import os
from pathlib import Path
from typing import Union
PROJECT_ROOT = Path(__file__).resolve().parents[2]
_default_data_root = PROJECT_ROOT / "data"
DATA_ROOT = Path(os.environ.get("F... |
5439a50aabd93f66080f0a9ca364a4d34787b573833d436ac0041202137ca6a7 | Python | 531 | 26 | from __future__ import annotations
import re
from ..utils._typed_cache import typed_cache
from ..transformations._remove_punctuation import remove_punctuation
@typed_cache
def count_letters(text: str) -> int:
"""Count letters in a text. Spaces are ignored.
Parameters
----------
text : str
A... |
1d0fea728d6caec8824678858b1c054c2dc2d6c28be1920107629be977d09a9d | Python | 534 | 21 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, expected",
[
(resources.EMPTY_STR, 0.0),
(resources.EASY_TEXT, 78.798),
(resources.SHORT_TEXT, 99.0),
(resources.PUNCT_TEXT, 70.698)... |
dd8b647da746a14e7b54c110164d9337231956e77590391a91640b856836166f | Python | 536 | 24 | """distutils
The main package for the Python Module Distribution Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
import sys
import importlib
__version__ = sys.version[:sys.version.index(' ')]
try:
# Allow Debian and pkgsrc (only) to customize system
... |
dffaf23a49a22533be89340095afc0a4425fa7757f94295b9dea523371a2f52e | Python | 536 | 30 | """
_constants
======
Constants relevant for the Python implementation.
"""
from __future__ import annotations
import platform
import sys
import sysconfig
IS64 = sys.maxsize > 2**32
PY310 = sys.version_info >= (3, 10)
PY311 = sys.version_info >= (3, 11)
PY312 = sys.version_info >= (3, 12)
PYPY = platform.python_im... |
d736418c7f44e2a4d61831519453fb8e3eb864caa8d337cb86d4b7aeae7acfe6 | Python | 539 | 21 | from .cluster import Cluster
from .genrelifneuron import GenreLIFNeuron
class GenreCluster(Cluster):
'''
classdocs
'''
def __init__(self, neutype, neunum):
'''
Constructor
'''
Cluster.__init__(self, neutype, neunum)
def createClusterNetwork(self):
for i in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.