sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
30950ac7f3691447aea92abdca75f514948ae85e51854241f8faa1429d90d183 | Python | 2,091 | 40 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from ultralytics.models.yolo.segment import SegmentationValidator
class FastSAMValidator(SegmentationValidator):
"""Custom validation class for FastSAM (Segment Anything Model) segmentation in the Ultralytics ... |
788e1f8890caf8a790352cf887cd755a215915807a28d026cdd6afc68bbba392 | Python | 2,091 | 69 | """
Variant: cython (C-compiled Gaussian kernel)
Wraps the ``_eval_cy`` Cython extension and exposes the same
``layerlineModel`` / ``layerlineModelGMM`` API as the other variants.
The extension must be compiled before use::
cd musclex/tests/fitting_ab/model_variants/model_cython
python setup.py build_ext --... |
e74956847efcaad6e17a3dfda39f1a6606bdd822621fa93166166be46a1fb23b | Python | 2,091 | 67 | from ..util import NodeSelector
from ..qt import *
from .. import thalamus_pb2
from ..task_controller.util import create_task_with_exc_handling
class NormalizeWidget(QWidget):
def __init__(self, config, stub):
super().__init__()
self.config = config
node_selector = NodeSelector(config, 'Source', False)
... |
0b315670071b7a1cf20f35a71994c684b359ce43d66216f1ebca13be4d8ae8c3 | Python | 2,092 | 78 | """A nelpy session is roughly equivalent to a NEO segment.
It has a common clock.
This object is very much a work-in-progress!!!"""
__all__ = ["Session"]
import warnings
# Force warnings.warn() to omit the source code line in the message
formatwarning_orig = warnings.formatwarning
warnings.formatwarning = (
lam... |
f59fd65b181097d45c3f49db2ff7dd2428d00a0df417362ed278b1fdd1b652e7 | Python | 2,092 | 66 | # Copyright (C) 2018-2022 Intel Corporation
#
# SPDX-License-Identifier: MIT
# Inherit parent config
from .base import * # pylint: disable=wildcard-import
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
INSTALLED_APPS += [
"django_extensions",
]
ALLOWED_HOSTS.append("testserver")... |
091653ebcddaa400de772d2a49a7aacaf0bbaf0f016506db3cd1b7544d05f7e8 | Python | 2,093 | 78 | # material_laws.py
# Material law functions for trabecular and cortical bone
# Input density is in mg/cc (same as your bin_centers)
# === Morgan et al. (2003) ===
def morgan_trab_E(density_mgcc):
if density_mgcc < 0:
return 0.0001
rho = density_mgcc / 1000.0 # Convert to g/cc
return 4730 * rho ** ... |
def610f204d8456bb3cb51178297ff59abc7f1473540960d0a68bf0b276b9eb1 | Python | 2,093 | 51 | """Small widget helpers shared by the tabs."""
from __future__ import annotations
from PyQt6.QtWidgets import (
QCheckBox, QDoubleSpinBox, QPushButton, QScrollArea, QWidget,
)
def scrollable(widget: QWidget) -> QScrollArea:
"""Put *widget* in a frameless scroll area that resizes with it.
A column of se... |
c6c70cacf4fb7882bd03fb59e21212067fa23ec8058badcf785f10dee20d6b9e | Python | 2,094 | 57 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['processing.zip',
... |
d06099df788b6cfdf3790e7c2a437f0f998b6c7ce41de7d7c553befc89a9591c | Python | 2,094 | 44 | from tests.utils import pytest_importorskip
def test_qt3dextras():
"""Test the qtpy.Qt3DExtras namespace"""
Qt3DExtras = pytest_importorskip("qtpy.Qt3DExtras")
assert Qt3DExtras.QTextureMaterial is not None
assert Qt3DExtras.QPhongAlphaMaterial is not None
assert Qt3DExtras.QOrbitCameraController... |
df56287d4dbc8f3ad8bf9759d64a499b169427bbc8bca8ed8917562c2080b328 | Python | 2,094 | 64 | #!/usr/bin/env python3
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
matplotlib.rcParams['svg.fonttype'] = 'none'
def scale(a):
return (a - np.mean(a)) / n... |
fc0a23a2c58ea2c41d526094936920cb00b1086e872b2e39e79a88a2a6da37e6 | Python | 2,094 | 62 | import torch
import functools
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.check_submission import check_models
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
import os
import gdown
from .evnet.evnet import E... |
525a8400efe0de92724fc5e86663eff5e379f927b74a57a4c5318f155a903bb2 | Python | 2,095 | 70 | #!/usr/bin/env python
"""
Convert a qual (qv) file to several BinnedArray files for fast seek.
This script takes approximately 4 seconds per 1 million base pairs.
The input format is fasta style quality -- fasta headers followed by
whitespace separated integers.
usage: %prog qual_file output_file
"""
import fileinp... |
211b95cfe3796633ce4fb198871cffb8f711351da21d3c48fbffbfbb10623c71 | Python | 2,096 | 30 | from testsetclass import TestsetClass
class CDIE20(TestsetClass):
def __init__(self):
self.weak = 1.0
self.molecules = ['R25', 'R51', 'R47', 'R20', 'R22', 'R43', 'P26', 'P46', 'P51', 'R21', 'P40', 'R49', 'P48', 'P56', 'P49', 'R60', 'R29', 'R56', 'P44', 'P52', 'R46', 'R48', 'R57', 'R28', 'P43', 'R4... |
591ac8b13e4e8193c4ca38fc47d63db4137fe69b7c4eab134648ebc1ef715a40 | Python | 2,096 | 96 | # -*- coding: utf-8 -*-
"""Region of interest (ROI) manipulations."""
import os
from .. import execute_command
from ..io.filename import get_filename
__all__ = ["extract_vol", "erode_fsl", "dilate_fsl"]
def extract_vol(file_in, file_out, t_min, t_size):
"""Extract 3D volumes from nifti time series.
Parame... |
f899c8b0ff2cd0cd5c64363b751e1d274ce15878dcccb5993d9e1fba9ff60bc1 | Python | 2,096 | 62 | import pandas as pd
import time
import ijson
import content_feature_vec as cf
import csv
def get_content_vector(tweets_text):
content_vector = {
"characters":cf.count_characters(tweets_text),
"hashtags":cf.count_hashtags(tweets_text),
"words":cf.count_words(tweets_text),
"hashtags_t... |
1a23d766f22d1a888858607e21e5a5a9197107168737d1a4e69bd21431210fb5 | Python | 2,097 | 75 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from __future__ import annotations
from cvat_sdk.api_client import apis, models
from cvat_sdk.core.helpers import get_paginated_collection
from cvat_sdk.core.proxies.model_proxy import (
ModelCreateMixin,
ModelDeleteMixin,
ModelListMixin... |
9f81dd7207d3d36525721a0cdf4f3d8da391aee56320408e62a0776c0c854738 | Python | 2,098 | 73 | # %%
from pathlib import Path
import pandas as pd
import numpy as np
# %%
df = pd.read_excel(Path(__file__).parent.parent / "data" / "megamastersheet.xlsx")
# %%
df.head()
# %% keep: subject_id, session_id, gender, chron_age, education_level, diagnosis, ADNI_MEM, pad_brainageR, pad_brainage, pad_DeepBrainNet, pad_pyme... |
ddbb550243014920304c79db29f0053b683d14fdd98c571a861b06412942480e | Python | 2,098 | 66 | # import json
# import numpy as np
# import cv2
# from matplotlib import pyplot as plt
# # 假设我们处理一个JSON文件
# json_file = 'D:/桌面/project/atomai/testdata/1.json' # 替换为实际的JSON文件路径
# with open(json_file) as f:
# data = json.load(f)
# # 创建一个与图像尺寸相同的空数组
# image_height = data['imageHeight']
# image_width = d... |
32a5521c5d5ae19a59f4826cb99f7cd1bcf3eb940dc10b228f980c0e076dd590 | Python | 2,099 | 75 | from pathlib import Path
import numpy as np
import pytest
from napari_dmc_brainmap.segment.processing.native_presegmentation import (
_maximum_removed_area,
run_native_presegmentation,
segment_preprocessed_image,
)
@pytest.mark.parametrize(
("fixture_name", "single_channel"),
[
("graysca... |
1dcab7337697b7e27954e6f38c16c95e0c9089547b18d20912fd753360428c9f | Python | 2,100 | 75 | import h5py
import os
import matplotlib.pyplot as plt
import numpy as np
DIR = os.path.dirname(os.path.realpath(__file__))
HOME_DIR = DIR.rsplit('/', 1)[0]
HOME_DIR = HOME_DIR.rsplit('/', 1)[0]
print('> HOME: ', HOME_DIR)
DATA_DIR = HOME_DIR + '/data/'
print('> DATA: ', DATA_DIR)
# %%
props = dict(boxstyle='round'... |
804e48d1fb1662b2ed008b68f3ebaf461c06c6ed8bd9e5c98dc96c078239ffee | Python | 2,101 | 67 | # The ImpedanceFitter is a package to fit impedance spectra to
# equivalent-circuit models using open-source software.
#
# Copyright (C) 2018, 2019 Leonard Thiele, leonard.thiele[AT]uni-rostock.de
# Copyright (C) 2018, 2019, 2020 Julius Zimmermann,
# julius.zimmermann[AT]un... |
b6b296ed3d98080a004941ac7e09f1c7327b71d26abb54175e097b966e17217f | Python | 2,101 | 53 | """
(C) IBM Corp, 2019, All rights reserved
Created on Aug 25, 2019
@author: EHUD KARAVANI
"""
import unittest
import pandas as pd
from causallib.estimation.base_weight import WeightEstimator
class TestBaseWeight(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.y = pd.Series([0, 0, 0, 0, 0,... |
1995e2dee72c5f3f88a50351d9c5abc0b80497d2582c28fb383211b6ae874e27 | Python | 2,102 | 78 | import numpy as np
import pandas as pd
def select_trials_OI(data_subj, label, band = 'Data'):
idx_tr_OI = np.where(data_subj['Trials_type'] == label)[0]
data_OI = data_subj[band][idx_tr_OI]
return data_OI, idx_tr_OI
def get_dataframe_vals_stability(dict_vals):
all_vals = []
all_sessions = []
... |
634c0a71702e766c0d5206e696ef671155b2890ceca1ffce8b362ad934d8727a | Python | 2,102 | 64 | import csv
from PIL import Image
import os
import multiprocessing as mp
CROP_SIZE = 1024
OUT_FOLDER = "/path/to/output/" #replace with your output path
def readCSV(inpFile,delimiter=","):
with open(inpFile, 'r') as read_obj: return list(csv.reader(read_obj,delimiter=delimiter))
def cropAndScaleImg(img,squareS... |
b90f860e7484b143a4270fe3094811437fa6dfab90c4e0cbc025598db5afc269 | Python | 2,102 | 71 | """# Table widget
Demonstrating a few ways to input tables.
"""
try:
import numpy as np
except ImportError:
raise ImportError("This example requires the numpy package. ")
from magicgui.widgets import Table
# all of these are valid data types
dict_of_lists = {"col_1": [1, 4], "col_2": [2, 5], "col_3": [3, 6]... |
872fc94fd7d7becbc1881305266c9fd26ad0038a6aa6c5939c486fe90ce4f2ff | Python | 2,103 | 77 | """
Move needle down until surface is reached. Then, there will be a signal on the scope screen.
"""
import serial
import time
import numpy as np
ser = serial.Serial()
ser.baudrate = 115200
ser.port = "COM3"
ser.open()
# Home leveling X0 Y0 Z0
ser.write(b"G28\r\n")
ser.write(b"G1 Z25\r\n")
# flush buff... |
90eeb83bbe2aee54116eb55d6c262c032a7ea67a2cdba625fd081662117477f0 | Python | 2,103 | 59 | import os
import sys
import subprocess
from setuptools import setup, find_packages
# Check for python version
if sys.version_info.major != 3 or sys.version_info.minor < 7 or sys.version_info.minor > 10:
raise ValueError(
'Unsupported Python version %d.%d.%d found. AnalogNAS requires Python '
'3.7, ... |
f7f7e18f9362063e96c0e06913e62188193e65982c641e5ca9a2256bffe8bf53 | Python | 2,103 | 70 | #!/usr/bin/env python
# author: Jannes Spangenberg
# github: https://github.com/JannesSP
# website: https://jannessp.github.io
"""
Using 9mer Gaussian models might lead to overfitting.
Using this script, we reduce the 9mer models to 5mer models by only using the middle 5 bases.
Position-wise conversion:
012345678 -> 2... |
2076f6a0d5c08127b58573ed3e5c9e49aee294cf0aefe51a7bc0845d5c2c20b4 | Python | 2,104 | 46 | import numpy as np
from brainscore_core.supported_data_standards.brainio.assemblies import BehavioralAssembly
from brainscore_core.supported_data_standards.brainio.packaging import package_data_assembly
import pandas as pd
'''
Experiment Information:
- https://www.sciencedirect.com/science/article/pii/S2589004222011... |
4b481535e858ffd63e6d9e41d4b07ab35784e1da4b3051002084fc1fbc50ed45 | Python | 2,104 | 47 | from pathlib import Path
import boto3
import pytest
from pytest import approx
from brainscore_core.supported_data_standards.brainio.assemblies import DataAssembly
from brainscore_vision import load_benchmark
from brainscore_vision.benchmark_helpers import PrecomputedFeatures
@pytest.fixture()
def alexnet_features()... |
ff4b3d5c51ae03b07b95792a5272d25313495784f0dc5722a54e16b15450b4e0 | Python | 2,104 | 73 | """
Provides access to a large list of 200 colors for "normal" and "deuteranomaly"
vision.
"""
from . import distinctipy
from ._colorsets_data import colors
def list_colorsets():
"""
Get a list of the names of built-in distinctipy colours.
:return: A tuple of keys present in the dictionary distinctipy.co... |
42e482ed048a8c2d516139c413df2591c5790d79b397e727d119ee2ca4e5ce38 | Python | 2,105 | 57 | from zigzag.classes.hardware.architecture.accelerator import Accelerator
from zigzag.classes.mapping.spatial.spatial_mapping import SpatialMapping
from zigzag.classes.opt.temporal.loma.engine import LomaEngine
from zigzag.classes.workload.layer_node import LayerNode
from typing import Generator, Callable, List, Tuple, ... |
45543cd83911f96130d017bc9f61bb36aac48274f13d73cc27801dec7c67d9d6 | Python | 2,105 | 59 | from typing import Tuple, List, Union
import torch
from batchgeneratorsv2.transforms.base.basic_transform import SegOnlyTransform
from torch.nn.functional import interpolate
class DownsampleSegForDSTransform(SegOnlyTransform):
def __init__(self, ds_scales: Union[List, Tuple]):
super().__init__()
... |
9c0a5d830d4d4529dfe46ce872d8a0f8aa62f700701ef727b7e9c53c58b05865 | Python | 2,105 | 75 | import pubchempy
from langchain_core.tools import tool
from chemgraph.models.atomsdata import AtomsData
@tool
def molecule_name_to_smiles(name: str) -> str:
"""Convert a molecule name to SMILES format.
Parameters
----------
name : str
The name of the molecule to convert.
Returns
----... |
523ed10e57d625c642d281a5f4129ae95f4f17a53b0d56459fcfec135fe0eacd | Python | 2,106 | 79 | #%%
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import TwoD_gamma
import brainpy.math as bm
import scipy
#set default ramndom seed for reproducibility
bm.random.seed(1)
#set backend to cpu
bm.set_platform('cpu')
labelsize = 18
ticksize = 14
center_trace, step,... |
89fd3da1a2b0dbbac2d343fc2c1b273dc2bb4830f7b797ee548c63b296564257 | Python | 2,107 | 77 | from typing import ClassVar
import polars as pl
import seaborn as sns
from matplotlib.axes import Axes
from argclz import AbstractParser, as_argument, str_tuple_type
from neuralib.plot import plot_figure
from rscvp.util.cli.cli_hist import HistOptions
from rscvp.util.util_plot import REGION_COLORS_HIST
__all__ = ['R... |
9c41e69bdeb0da4075661443c5fdcc943b3c1eb2a2c7a511879e6710608d8eb0 | Python | 2,107 | 78 | from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Tuple, Union
import brainways._version
from brainways.pipeline.brainways_params import BrainwaysParams, CellDetectorParams
from brainways.utils.dataclasses import dataclass_eq
fro... |
ba9a963d7f8ce2c7434539daf10e0946ed51d82de7a091d24ac0c7778400f302 | Python | 2,107 | 56 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import re
from collections import Counter
from django.core.management.base import BaseCommand, CommandError
from cvat.apps.redis_handler.migration_loader import MigrationLoader
_MIGRATION_FILENAME_PATTERN = re.compile(r"^\d{3}_\w+$")
class Comma... |
16751d9e875782d0ee47ffe934cf4a292c6fa776f65f2d043f0727c3281bf2f0 | Python | 2,108 | 60 | import warnings
warnings.filterwarnings("ignore", message="It is not recommended to directly access")
from tqdm import tqdm
import torch
def train(model, device, loader, optimizer, criterion, contrastive_weight=0.2):
model.train()
for step, batch in enumerate(tqdm(loader, desc="Iteration")):
batch = b... |
543509a8974ad7acce449c9c9f73e17e672a492f92bdd22cbcb40a8733c9a2b7 | Python | 2,108 | 63 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors:
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... |
fcc2d4c92049fa184239709c898ea592a12b75a337befd36ac114bfc92d8ec46 | Python | 2,108 | 73 | """Direct Anthropic endpoint (Anthropic-native protocol).
Logic moved verbatim from ``models/anthropic.py``: ``ANTHROPIC_API_KEY`` with
interactive prompt, curated model validation, ``max_tokens=6000``.
"""
from __future__ import annotations
from chemgraph.models.endpoints.base import (
CredentialPolicy,
End... |
8085701260ef114d8cc27b37dc6c2bd0362c2db600b3d0e0b39c06fcc4e6d4a2 | Python | 2,109 | 71 | from pathlib import Path
from brainscore_core.supported_data_standards.brainio.stimuli import StimulusSet
from brainscore_core.supported_data_standards.brainio.packaging import package_stimulus_set
stimuli = []
image_paths = {}
stimuli_directory = '../datasets/silhouette'
'''
Dataset Meta Info (from https://github.c... |
b827150af04296e37061de09380a9ced5098d8189e84fecef0df7cd3fd7a8de5 | Python | 2,109 | 55 | '''
Python file with the purpose of a shell script.
Examples are given for running 1 image through the model, running the training script, the test script and the analysis script
'''
import subprocess
import shlex
import os
### Command line to run 1 image through the model and save the prediction in output
imagep... |
dfe8a11beef5ae7fd6d5aa712ac384de37caf56616b96aee8d2bff5268f297f5 | Python | 2,110 | 58 | import pytest
import numpy as np
from nems.layers.nonlinearity import DoubleExponential, RectifiedLinear
def test_constructors():
# dexp
with pytest.raises(TypeError):
# No shape specified.
dexp = DoubleExponential()
dexp = DoubleExponential(shape=(5,))
dexp = DoubleExponential(shape=... |
1c9e284ab1cf8efbdc9ed5dfd2dbe58d09f5ba3f52ad6b0c82ae125ecf60b384 | Python | 2,111 | 61 | """Lossless, strict serialization helpers for durable conversation messages."""
from __future__ import annotations
import hashlib
import json
from typing import Any
from langchain_core.messages import AIMessage, BaseMessage, ToolMessage, convert_to_messages
from langgraph.checkpoint.serde.jsonplus import JsonPlusSer... |
3342953dd7e3be74633dae29359781d257de066f33b3f684be9a796eb3e46b30 | Python | 2,111 | 52 | # This file is part of connectome-manipulator.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2024 Blue Brain Project/EPFL
"""Synapse subsampling module."""
import numpy as np
from connectome_manipulator import log, profiler
from connectome_manipulator.connectome_manipulation.manipulation import Manipulatio... |
54ee4a7aa3fc50cdf530a41202363247e6ad335cc12d3011e0f9a9022b12de4f | Python | 2,111 | 75 | import sys
import time
import json
import getopt
from PIL import Image
from save_miscdf import create_a_folder
def chopimages(roi_json,prefix):
Image.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
create_a_folder(prefix)
sinfo = roi_json
slice_tif = sinfo[0]
img = Image.open(slice_t... |
33d3ed52c420e366d4ba43222518f25b90bfc40a224ecbb05cbcfb84d2d40cec | Python | 2,113 | 65 | import sys
import getopt
import pandas as pd
from time import time
import pipeline
def usage():
cmds = [
'python all_in_one.py --in-mri <in_mri> --out_mri <out_mri> [options]',
'python all_in_one.py --in-csv <in-csv> [options]'
]
options = [
['--in-mri <input>','input MR image path,... |
c2d63fc2fe80d2b75311634b10e37e683bce59d71f7c54393de90602386a4a02 | Python | 2,113 | 69 | #!/usr/bin/env python
import argparse
import sys
from pathlib import Path
import imgviz
import numpy as np
import PIL.Image
from loguru import logger
from numpy.typing import NDArray
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import utils # noqa: E402 # examples/utils.py, vendored alongside th... |
c8e039ab08de6ae6d33bf4d9780a0771b4242cc8ade602bf39c9b7cf59d4b951 | Python | 2,113 | 70 | # -*- coding: utf-8 -*-
import numpy as np
from dipy.core.sphere import hemi_icosahedron
from scilpy.tests.arrays import (fodf_3x3_order8_descoteaux07,
fodf_3x3_bingham, fodf_3x3_bingham_sf,
fodf_3x3_bingham_fd, fodf_3x3_bingham_fs,
... |
545dfe650f02c470b1806a45a13456bb10235bfa57160990769d537e2d1b7540 | Python | 2,114 | 34 | import argparse
import pyBigWig
import numpy as np
import deepdish
import bigwig_helper
# need full paths!
parser = argparse.ArgumentParser(description="Convert importance scores in hdf5 format to bigwig. The output can be visualised using WashU Epigenome Browser as a dynseq track. Please read all parameter argument r... |
82b625cb80a8da03cf37166e8809b98d67d8dd7108fdea8d5b742056caad4ae2 | Python | 2,114 | 91 | import feature_tools as ft
import re
# user_to_post.csv获取tweet列表
# node.json获取post推文
# post是个字典
# maybe item = item.replace('\n',' ')
def count_characters(all_text):
cnt = 0
#all_text = ft.get_all_texts(post,tweet_id_list)
for item in all_text:
item = item.replace('\n',' ')
cnt += len(item... |
77768f0486805d642ad560f59facdd35bfbcf16788def994963ea1db0665491a | Python | 2,115 | 68 | """Extract cortical thinkness from perimeter"""
import nibabel as nb
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
subs = ['sub-05', 'sub-06', 'sub-07', 'sub-09', 'sub-10', 'sub-12', 'sub-14', 'sub-15', 'sub-16', 'sub-17', 'sub-18']
DIGITS = ['D2', 'D3', 'D4']
ROOT = "/... |
de282c9170640735db896ffb151ad4bfb2b24f57ad856f393913f94276651cdf | Python | 2,115 | 54 | from torch.nn.modules.loss import _Loss
from torch import Tensor
from torchvision.ops.focal_loss import sigmoid_focal_loss
from ..ops.loss import iou_loss, box_npll_loss
__all__ = ['SigmoidFocalLoss', 'IoULoss', 'BoxNpllLoss']
class _FocalLoss(_Loss):
__constants__ = ['reduction']
def __init__(self, size_av... |
eca8e8cfb6a5385ed8a10ea62f02bff85c4e2b26104fa0ed48dad7ff2823db4d | Python | 2,115 | 61 | import scipy as s
import scipy.stats as stats
from .basic_distributions import Distribution
from mofapy2.core.utils import *
class UnivariateGaussian(Distribution):
"""
Class to define univariate Gaussian distributions
Equations:
Class for a univariate Gaussian distributed node
p(x|mu,sigma^2) = ... |
5162e142d90f43c11bb10ec28d4334f58660707b3ff931b75e9c5ddc547d01c4 | Python | 2,116 | 70 | import os
import mne
from pyedflib.highlevel import write_edf
from tqdm import tqdm
sids = [
'11639535_20220704_143013_fil',
'12543262_20220913_142921_fil',
'11549585_20200702_143515_fil',
'11336460_20220725_100434_fil',
]
groups = [
'TD',
'TD',
'TD',
'ASD',
]
ch_names32 = ['EEG 1', 'EEG 2', 'EEG 3', 'EEG 4', 'EEG 5... |
9f164a9ca7cb832a5736f044332212cc4774c3638fd0795abd6f0d5e62b8301c | Python | 2,116 | 70 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
from collections import OrderedDict
import mmcv
import torch
from mmcv.runner import CheckpointLoader
def convert_vit(ckpt):
new_ckpt = OrderedDict()
for k, v in ckpt.items():
if k.startswith('head'):
... |
e78161a82662002b494800fead33f0294272d805a48e93a21362536154600f19 | Python | 2,116 | 76 | from abc import abstractmethod
from pytorch_lightning.core.mixins import HyperparametersMixin
import numpy as np
import cv2
from .misc import random_crop, normalize_percentile
__all__ = ['Transforms', 'BasicTransforms']
class Transforms(HyperparametersMixin):
def __init__(self, **kwargs):
"""Transforms.... |
ff9bac7f830f80feb83be031bc66ec1e0eeafb118a28d93ae86ef91ef7fbcaa1 | Python | 2,116 | 80 | import csv
from pathlib import Path
import numpy as np
def set_up_label_file_writing(
base_path: Path, fieldnames: list[str], extra_name: str = ""
):
label_file = str(base_path / f"labels{extra_name}.csv")
label_file_handle = open(str(label_file), "w")
writer = csv.DictWriter(f=label_file_handle, f... |
a41a342bbffedc2a95da6d8b4d4b09d839846a4bc96f6529d75411c1cdb5cc6d | Python | 2,117 | 62 | #CMU Multimodal SDK, CMU Multimodal Model SDK
#Multimodal Language Analysis with Recurrent Multistage Fusion, Paul Pu Liang, Ziyin Liu, Amir Zadeh, Louis-Philippe Morency - https://arxiv.org/abs/1808.03920
#in_dimensions: the list of dimensionalities of each modality
#cell_size: lstm cell size
#in_modalities: is ... |
d168fef5fe29943609017ddc67652b04464703bf8735ab34a87bc725844314e4 | Python | 2,117 | 76 | import os
from nipype.interfaces import BIDSDataGrabber
from nipype.utils.filemanip import list_to_filename
from PUMI.pipelines.anat.segmentation import defacing
from nipype import IdentityInterface, Function
from PUMI.engine import NestedWorkflow as Workflow
from PUMI.engine import NestedNode as Node
ROOT_DIR = os.... |
d31155340c8d049a21570c97e522f846d3dbffe8353f7c36fd20be1638671f8b | Python | 2,118 | 71 | """Reusable inference API for 3D ViT-UNet."""
from __future__ import annotations
from pathlib import Path
import numpy as np
import torch
try:
from ..model import SegNetwork
except ImportError:
from src.model import SegNetwork
def resolve_device(device: str | None = None) -> torch.device:
if device:
... |
f6ee38941f9f733b682c8d5f3e64e3cd8bfceccdb9eb540b61c0e5910d254620 | Python | 2,118 | 63 | import os
import tensorflow as tf
import numpy as np
from utility import _create_patient_data_df, _get_file_names, _parse_dicom_data
class OSICFibrosisDSI:
def __init__(self, csv_path, ct_path):
self.csv_path = csv_path
self.ct_path = ct_path
def _load_data(self):
self._test_patient_d... |
96bdea0ffdd11b711efcf42aa4f9f7f388a2b8d8d0c370ba6c0ec0301c87cd26 | Python | 2,119 | 84 | #!/usr/bin/python
#
## @file
#
# Control of various Nikon TiU accessories (using Micro-Manager).
#
# Hazen 4/15
#
import MMCorePy
## TiUMisc
#
# Encapsulates control of various TiU accessories.
#
class TiUMisc(object):
## __init__
#
def __init__(self):
self.mmc = MMCorePy.CMMCore()
self.m... |
a9e8aa6d9775eac2e17e7107742ccc8819114317771dc66e6bef0ad694445e34 | Python | 2,119 | 75 | import numpy as np
from ivim.constants import y
from ivim.seq.lte import calc_b, calc_c
from ivim.seq.fwf import (q_from_g,
B_from_q, b_from_q, C_from_q, c_from_q,
B_from_g, b_from_g, C_from_g, c_from_g,
G_from_b, c_from_b)
# Variables for ... |
e87d482db62f33694279112080f12c29453426376b7836b5e5899c8516bfda34 | Python | 2,119 | 63 | from enum import Enum
from typing import Dict
from bg_atlasapi import utils, descriptors
from skimage import filters as filters
def get_available_atlases() -> Dict[str, str]:
"""
Get the available BrainGlobe atlases.
This function fetches the available atlases from the BrainGlobe's configuration URL
... |
ed275ab1333d126c9d33ff427d9f1268286fff725cd7c9c995731360cbd21cc1 | Python | 2,120 | 65 | import os
import pytest
from magicgui.application import use_app
# Disable tqdm's TMonitor thread to prevent race conditions with Qt threading
# that can cause intermittent segfaults on CI (especially with PySide6 on Linux).
# See: https://github.com/tqdm/tqdm/issues/469
try:
from tqdm import tqdm as _tqdm_std
... |
e91afe33712467ebe2a3d1aec733e72521edda83ceaf69272ce36760693b84d1 | Python | 2,121 | 55 | import torch
import torch.nn as nn
from models import *
class CNNNet(nn.Module):
def __init__(self, my_pretrained_classifier, output_neuron_num):
super(CNNNet, self).__init__()
self.pretrained_clf = my_pretrained_classifier
self.clf_fc1 = nn.Sequential(nn.Linear(512, 500, bias=False... |
62e461dffcca9bd730da0b9278efa0372e4a8106b7119aebb39c0147e663f459 | Python | 2,122 | 78 | from __future__ import annotations
import dataclasses
from typing import Final
@dataclasses.dataclass(frozen=True)
class AiAssistModelOption:
model_name: str
display_name: str
supports_point_prompts: bool
AI_ASSIST_MODEL_OPTIONS: Final[tuple[AiAssistModelOption, ...]] = (
AiAssistModelOption(
... |
a57f3a47c8a87211387d5338f66061f1d5547b64475eb6b0a019f9372bde4dfb | Python | 2,122 | 65 | import json
import base64
import io
from PIL import Image
import torch
from detectron2.model_zoo import get_config
from detectron2.data.detection_utils import convert_PIL_to_numpy
from detectron2.engine.defaults import DefaultPredictor
from detectron2.data.datasets.builtin_meta import COCO_CATEGORIES
CONFIG_OPTS = ["... |
2cac322b48e4353c1364e148e4fdf08f650cf7da6e76e57e5635af83b343d8ee | Python | 2,124 | 59 | #%%
from pathlib import Path
import os
from warnings import warn
import deep_events.database.extract_yaml as extract_yaml
import deep_events.database.ome_to_yaml as ome_to_yaml
from deep_events.database.convenience import glob_zarr
# folder = "//lebsrv2.epfl.ch/LEB_SHARED/SHARED/_Lab members/Juan/230511_PDA_TrainingS... |
8c8f3bdb297dde92654c6ddf6675a7dfe0ed5424771db01d7664187c1f2e9e9c | Python | 2,124 | 62 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import shutil
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['tractometry.z... |
ff16a1b4bd92e55482a1cb4c7fb6270ee73767db26013d33d6dc9ad91efb58b7 | Python | 2,124 | 28 | from testsetclass import TestsetClass
class WCPT18(TestsetClass):
def __init__(self):
self.weak = 1.0
self.molecules = ['h2o', 'ts9h2o', 'ts8h2o', 'ts3h2o', 'ts5', 'ts2', 'ts7h2o', 'ts3', 'ts4', 'ts6h2o', 'reac2', 'reac5', 'reac4', 'ts2h2o', 'reac3', 'ts5h2o', 'ts1h2o', 'ts4h2o', 'ts8', 'ts1', 'ts... |
786ceabd95393ff3026d66a999933cc8c8cc14506e0eabf6a864ac32ac6087b3 | Python | 2,125 | 64 | from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, matthews_corrcoef, \
roc_auc_score, precision_recall_curve, auc
import torch
import torch.nn.functional as func
def null_metrics():
return {
'acc': 0.0,
'f1-score': 0.0,
'precision': 0.0,
'reca... |
7e6eb49bb86dc1d7781e5daab1af08d7c5378557dd8556408591076f95fec1b5 | Python | 2,125 | 50 | #!/usr/bin/env python3
import os
import datetime
import pandas as pd
from utils import TSVSheet
from utils import update_xlsx_datetime
# List of all TSV file paths to generate the xlsx spreadsheet
tsv_paths = [
os.path.join("..", "snv-frequencies", "results",
"gene-level-snv-consensus-annotated-mu... |
aa6f155f117fe24fe0d9474b4f6a552f318147be9b65b9916ac8b128d1733d5d | Python | 2,125 | 52 | #!/usr/bin/env python3
import argparse
import sys
import click as ck
def extract_uniprot_ids(fasta_file):
"""
从 FASTA 文件中提取 UniProt ID(Accession)
支持格式: >sp|P12345|... 或 >tr|Q9Y6K9|...
"""
uniprot_ids = []
with open(fasta_file, 'r') as f:
for line in f:
if line.startswith('>... |
41aa8e3e443008e11b33f0f8e83444264900778f3e27d8af66f27eb7716ae21b | Python | 2,127 | 59 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['tracking.zip'])
tmp_dir = tempfile.Tem... |
c14dc8d8d20b460bccc3c6c7c1073e9f20de5d902b800cc8faaa9237d99d2bc8 | Python | 2,127 | 65 | import datajoint as dj
from pipeline import experiment
anatomy = dj.create_virtual_module("anatomy", "pipeline_anatomy")
schema = dj.schema("pipeline_collection", create_tables=True)
@schema
class Study(dj.Manual):
definition = """
# class of experiments towards specific aim
study_name ... |
c47c1355e0cbf8df8ee6b79fbcfe77e8589510338347bb3e7205f6028f4bb1f2 | Python | 2,127 | 84 | import numpy as np
from impyute.ops import matrix
from impyute.ops import wrapper
@wrapper.wrappers
@wrapper.checks
def mean(data):
""" Substitute missing values with the mean of that column.
Parameters
----------
data: numpy.ndarray
Data to impute.
Returns
-------
numpy.ndarray
... |
d1b33e10fb8144f0a2eba9cc64f10edddcbf68e49529abc6bf9c9b4040067de5 | Python | 2,127 | 86 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import abc
from enum import Enum, auto
import attrs
import PIL.Image
import cvat_sdk.core
import cvat_sdk.core.exceptions
import cvat_sdk.models as models
class UnsupportedDatasetError(cvat_sdk.core.exceptions.CvatSdkException):
pass
@attrs... |
e1063e225db2cc48279aa3cdd8106209bcd5995229266748867e9300b6c3c121 | Python | 2,127 | 68 | """Runs the development web interface for ADMET-AI (Flask)."""
import random
import string
from datetime import timedelta
from threading import Thread
import matplotlib
from tap import tapify
from admet_ai.admet_info import load_admet_info
from admet_ai.drugbank import load_drugbank
from admet_ai.web.app import app
... |
0e785ed14859c53604607129657b5c8a36865f82bbf67049adee7fa4f832945e | Python | 2,128 | 27 | from testsetclass import TestsetClass
class ICONF(TestsetClass):
def __init__(self):
self.weak = 1.0
self.molecules = ['SI5H12_2', 'N4H6_1', 'S8_2', 'P7H7_2', 'SI6H12_1', 'N4H6_3', 'H4P2O7_4', 'N3P3H12_1', 'S4O4_1', 'H2S2O7_2', 'SI5H12_1', 'H4P2O7_2', 'N4H6_2', 'N3P3H12_2', 'S4O4_2', 'N3H5_3', 'H2... |
2f3fc662cb027b485d8444444de5570a11fd7c3b95bf9a8807458446d9c98b1b | Python | 2,128 | 62 | import torch
from reducers import AvgNonZeroReducer
from utils import loss_and_miner_utils as lmu
from losses.base_metric_loss_function import BaseMetricLossFunction
class TripletMarginLoss(BaseMetricLossFunction):
"""
Args:
margin: The desired difference between the anchor-positive distance and the
... |
4fcb60ea162245e0b36fb7e2de71096a675e1e61fa3aad98c9f8b68eddd5f820 | Python | 2,128 | 62 | #!/usr/bin/python3
#
import unittest
import numpy as np
from uac import utils
class TestUtils(unittest.TestCase):
def test_find_index(self):
ls = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.assertEqual(utils.find_index(ls, min), 0)
self.assertEqual(utils.find_index(ls, max), 8)
ls = [5, 3, 9... |
aec4dc03c8470e0fd7a4f31ea7bb4e1f07d6d266f1625d6320e7b0b64418bccb | Python | 2,128 | 47 | import pathlib
import h5py
import numpy as np
import argparse
from numpy.typing import NDArray
def all_chunks_complete(chunk_folder: pathlib.Path) -> tuple[bool, NDArray[bool]]:
"""
Checks if all chunks are complete in the given folder. Chunk files should be hdf5 with the naming scheme:
'*_<first_index>_<... |
46022eb77313392605141fee25c155973c9678b202520948a3c683679dfbcad8 | Python | 2,129 | 75 | from pathlib import Path
from typing import TYPE_CHECKING, Optional, Protocol
import numpy as np
from eir.data_load.label_setup import al_label_transformers_object
from eir.interpretation.interpretation_utils import (
TargetTypeInfo,
get_target_class_name,
)
if TYPE_CHECKING:
from eir.interpretation.inte... |
9fa0b62b53947208b09c2a685691ecabaa802290347198851c4856db28d6fccd | Python | 2,129 | 68 | import argparse
import os
from pathlib import Path
from scripts.workflow_functions import shipResults, runSmk
try:
from rich import print
except ImportError: # pragma: no cover - optional dependency for nicer CLI output
pass
def parse_args():
repo_dir = Path(__file__).resolve().parent
parser = argpa... |
0004ccb701089901c2cf272104f89fd74086442a1bc02347e5a0d6122c203b75 | Python | 2,130 | 52 | """Packing a finished run into a bundle, off the GUI thread.
Zipping an output folder is a couple of seconds on the example dataset and can
be a minute on a large batch — long enough that doing it in the GUI thread
would freeze the window mid-click, short enough that it does not want a
progress bar and a cancel button... |
1cac7ff8c70b914ac9205b90b80f05ce0690c9ca01f9fe137b0ec3519504c8f6 | Python | 2,130 | 53 | from typing import Optional, Union, List
import numpy as np
import pandas as pd
import scipy.sparse as sp
from anndata import AnnData
from torch_geometric.nn import knn_graph, radius_graph
from torch_geometric.utils import to_undirected
import torch
import scanpy as sc
def cal_spatial_network(
adata: AnnData... |
136acada26dbf050c5fca067c705c3f09b7420b0785684a344b9c28b6502fa4f | Python | 2,131 | 65 | # The ImpedanceFitter is a package to fit impedance spectra to
# equivalent-circuit models using open-source software.
#
# Copyright (C) 2018, 2019 Leonard Thiele, leonard.thiele[AT]uni-rostock.de
# Copyright (C) 2018, 2019, 2020 Julius Zimmermann, julius.zimmermann[AT]uni-rostock.de
#
# This program is ... |
452ec037992e820a985177bbbc0a99316b0f72a67d756b0da0d01d9d4336a3d8 | Python | 2,132 | 67 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Flip streamlines locally around specific axes.
IMPORTANT: this script should only be used in case of absolute necessity.
It's better to fix the real tools than to force flipping streamlines to
have them fit in the tools.
"""
import argparse
import logging
from scilp... |
4acfb731ff147939fb9898106d75ab49a831ca8405e91f4b382f47bc0174d7a4 | Python | 2,132 | 71 |
from typing import Any, List
from fastapi.encoders import jsonable_encoder
from bson.objectid import ObjectId
class BaseDao:
database:Any = None
@classmethod
def __call__(cls, database):
if cls.database != None:
return
else:
cls.database = database
... |
4d34fc5545eb7b0659dbbf7baa6087c17d76ea3e59ca2650b0002bd0f2e8fd87 | Python | 2,132 | 98 | #!/usr/bin/env python
import argparse
import sys
parser = argparse.ArgumentParser(description="")
parser.add_argument("-m", "--mpileup", help="input mpipleup, must be run with -r and --output-QNAME", type=argparse.FileType('r'))
parser.add_argument("-n", "--nucfreq", help="input nucfreq file", type=argparse.FileType... |
70f5aa2167c70449946b7c87a7567522e65dd850ceae7c96e5aacf2c08bf8c8f | Python | 2,132 | 70 | import glob
import os
import pandas as pd
import sys
import shutil
from fuse.utils.file_io.file_io import create_dir
CLASSES_SET1_v1 = [
{
"cls_id": 0,
"cls_name": "Melanoma",
"decease_codes": {"C43", "D03.9"}
},
{
"cls_id": 1,
"cls_name": "Malignant neoplasm",
... |
8910d86ab395283c272db01c4bc6e144505a113a3f3b5dfd906b328b5d9f459a | Python | 2,132 | 82 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 6 19:33:49 2022
@author: Artur Klepaczko
"""
import nibabel as nii
import cv2
import json
import numpy as np
from pathlib import Path
from tqdm import tqdm
from typing import Final
NII_ROOT: Final[Path] = Path(R'D:\TexturesKidneys\NIFTI-T2')
OUT_ROOT: Final[Path] = P... |
c1212dc1f72e222efcf954c1bbd2510d4c3d020757dd0c8c50a07caf43060d8e | Python | 2,132 | 50 | from scipy.ndimage import rotate
from tensorflow.random import uniform
from tensorflow import function as tf_function, roll as tf_roll, pad as tf_pad, constant as tf_constant, numpy_function
from .constants import IMAGE_SHAPE
@tf_function(jit_compile=False) # jit compile problem pad
def random_shift_vec(mri, shift_ma... |
17e510fa07f5c2264df95d651c63abd8c93408f7aa035016312da79749f53aea | Python | 2,133 | 84 | #!/usr/bin/env python
# coding: utf-8
# Modules
import os
from glob import glob
import numpy as np
import pandas as pd
import fastparquet # this is just to let pipreqs known we need this
# functions
def clean_my_file(file_name):
"""[summary]
:param file_name: [description]
:type file_name: [type]
:r... |
29410095eb1d66ace111c3f36fdf265f447c3b48d1df4a1c70ff70547b26798a | Python | 2,133 | 85 | """nsd_output
"""
import os
import numpy as np
import nibabel as nib
import nibabel.freesurfer.mghformat as fsmgh
__all__ = ["nsd_write_vol", "nsd_write_fs"]
def nsd_write_vol(data, res, outputfile, origin=None):
"""nsd_write_vol writes volumes to disk
Args:
data (nd-array): volumetric data to write... |
2fbf4c0727de872f1aa89a35d1435eba83b0f0616bb11a41ce9f6695b03f67d3 | Python | 2,133 | 74 | from __future__ import annotations
from typing import Any, Optional, Sequence, Union, Mapping
import numpy as np
from sklearn.metrics import roc_auc_score
from .fairness import generalized_equalized_odds
def _as_numpy_float(array: Sequence[Any]) -> np.ndarray:
if isinstance(array, np.ndarray):
return array.asty... |
01c1e3a6c313dd59442be68bc297fadfdf313c018afbad2292137e114844479b | Python | 2,134 | 65 | """Train Chemprop models on the Therapeutics Data Commons (TDC) ADMET Benchmark Group datasets"""
import subprocess
from pathlib import Path
from typing import Literal
from tqdm import tqdm
from tdc_constants import (
ADMET_GROUP_SEEDS,
ADMET_GROUP_SMILES_COLUMN,
ADMET_GROUP_TARGET_COLUMN,
DATASET_TO... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.