sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
191a70871a2cbf33f5d31509a43ee925052bc11164dd1ec638e3fcf982f73ab4
Python
2,897
92
import pandas as pd import time import csv import spacy from tqdm import tqdm import content_features as cf import os nlp = spacy.load('en_core_web_lg', disable=['parser', 'ner']) def get_content_vector(tweets): links = cf.count_urls(tweets) mentions = cf.count_mentions(tweets) content_vector = { ...
4ab22d9cefdec5bdf4e8689d417cd0dbf1e5c230c82887c1649d6b361b4784f4
Python
2,897
90
# # common/tools/base.py # 2021-05-10 # Written by SK Park, NIRAL, UNC # # External tool wrapper base class # import sys import time from pathlib import Path import subprocess as sp import dtiplayground.dmri.common common = dtiplayground.dmri.common ### decorators def measure_time(func): ## decorator ...
8d63b6628b410b19ed56c4e226719cc6e716f8a09ffaeeff8fa4fc9537bf728e
Python
2,897
64
#!/usr/bin/env python3 # Copyright 2024 Image Analysis Lab, German Center for Neurodegenerative Diseases (DZNE), Bonn # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apac...
2c6ffc1f579059af151534419663fe9d54035af9eb24f33dd2ab94dc227dcb50
Python
2,898
113
from dataclasses import dataclass, field import torch from torch import nn from torchvision.ops import StochasticDepth from eir.models.layers.norm_layers import LayerScale @dataclass class ResidualMLPConfig: """ :param layers: Number of residual MLP layers to use in for each output predictor after f...
70fddbcbb3e6a8619490bc0e9af76d623455264eb96688f8e1ff43b37865d40f
Python
2,898
91
import numpy as np from rsatoolbox.data import TemporalDataset from rsatoolbox.rdm import calc_rdm_movie import pickle from joblib import Parallel, delayed from mne import read_epochs, setup_source_space, spatial_dist_adjacency, add_source_space_distances from mne.minimum_norm import ( read_inverse_operator, ...
07cf6d057bc171b6001a4a919a8fe388a11f9933ad38ebdf70fca6de921d2ff5
Python
2,899
86
import argparse import os import os.path as osp import time import numpy as np import torch import torch.nn.functional as F from sklearn.metrics import f1_score import pandas import json import torch_geometric.transforms as T from torch_geometric.nn import ChebConv, GCNConv # noqa from tqdm import tqdm parser = argpar...
74c96587bfaef7d9f180784096b4df496a343b90a7c63e338d8c10cd89f8ec6b
Python
2,899
88
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path import runpy her...
7c1e45f7fb51975639a396461f1f10ea016f82a5b360708e593b7b4e101fe2b2
Python
2,899
82
############################################################################# # Copyright (C) 2020-2026 MEmilio # # Authors: Henrik Zunker # # 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 Lice...
8206d60fcfa81269ecf834d8b2808d27b9e448056f913f0de482244b3eb49fa0
Python
2,899
91
"""The ISH upsampling helper. Always called with a small ``target_volume_shape``: the default allocates a 1320 x 800 x 1140 float array, several gigabytes, which no test should do. """ import numpy as np import pytest from ccf_streamlines.dataset import upscale_ish_volume @pytest.fixture def small_volume(): ""...
cce47525ef8c2c72b959f7c4a22b73d6e49ce3f449c8f4f17c3fe1d28da39dcb
Python
2,899
93
import glob import os import numpy as np import cv2 import multiprocessing.pool as mpp import multiprocessing as mp import time import argparse import torch import random SEED = 42 CLASSES = ('background', 'building', 'road', 'water', 'barren', 'forest', 'agricultural') PALETTE = [[255, 255, 255], [255, 0...
d0732fbbbc1c625cdac957e716eed9efa9c8cf95570c2659fad3a7c6ac38b05a
Python
2,899
83
"""Augment images for classification Usage: augment_images.py [options] <input-dir> <output-dir> augment_images.py -h | --help augment_images.py --version Arguments: <input-dir> Path to the input directory with images. <output-dir> Path to the output directory with augmented images. ...
98d270733e7628011a628ae5ee1def471cb490d2176a97944b8814dc348f3ecb
Python
2,900
114
"""Dannce module and default parameters""" # Default parameters, which can be superseded by CL arguments or # config files _param_defaults_shared = { "immode": "vid", "verbose": 1, "gpu_id": "0", "loss": "mask_nan_keep_loss", "start_batch": 0, "exp": None, "viddir": 'videos', "io_config"...
f143f2303d26f93a8800779086690ffa6b876248e82a3ac3038541ebbebdaed3
Python
2,900
100
import numpy as np import torch import os from tqdm import tqdm import yaml from argparse import Namespace import pandas as pd import SimpleITK as sitk def load_nii(path, prob_map=False): img = sitk.ReadImage(path) img = sitk.GetArrayFromImage(img) if prob_map: img = (img > 0.5).astype(np.uint8)...
b6561a007dedd683608e4b2cbdd997ab7d0dbf2dea936957cebe64a1b29a35f1
Python
2,901
59
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import torch from ultralytics.models.yolo.detect.predict import DetectionPredictor from ultralytics.utils import ops class NASPredictor(DetectionPredictor): """Ultralytics YOLO NAS Predictor for object detection. This class extends the Det...
e688b5e9af6955f6e283cb05018d0b36f13661f47ec936a75321b7b8e17e6e69
Python
2,901
64
from tests.common import * class Test_AS_Pipeline: def test_pipeline_no_run(self,demo_dir): LOGGER.info("run aberrantSplicing pipeline with \'run: false\'") # change the second instance of "run: true" to "run: false" to turn off the AS module # run the AS module using this config_AS_norun...
9509f9cb020e45c42d7b95e635e3d7ac4a43964e333e0c8537b1de0e025ba32c
Python
2,903
82
""" Variant: numba (JIT-compiled Gaussian inner loop) The Gaussian evaluation loop is compiled with ``@numba.njit(cache=True, fastmath=True)``. ``fastmath=True`` allows LLVM to reorder and approximate floating-point operations for speed (safe for a smooth Gaussian curve). Voigt falls back to ``scipy.special.wofz`` ...
a1ec2ad1f2d82cb706e5a6c35952678b2844e6c80ec287455a1e6acce68e6947
Python
2,903
81
from pydantic import BaseModel, Field class Psi4Calc(BaseModel): """PSI4 quantum chemistry calculator configuration. This class defines the configuration parameters for PSI4 quantum chemistry calculations. It supports various quantum chemical methods, basis sets, and SCF convergence parameters. ...
b80475fe676b74f79dbed66cae830ad5e9ce558ca3b6da15ed503b847f6d70fc
Python
2,903
79
#!/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']) tmp_dir = tempfile.T...
e202c40f12ded812c4e113e4427b793c9ead1a363b07ed9f0db719996b148fa3
Python
2,903
72
import numpy as np import torch from distances import LpDistance from utils import common_functions as c_f from utils import loss_and_miner_utils as lmu from losses.base_metric_loss_function import BaseMetricLossFunction class AngularLoss(BaseMetricLossFunction): """ Implementation of https://arxiv.org/abs/1...
7383a0ce4f90ef4b7943fbcc56b2dc59f022afb85d8b03aa25f5a340b9f24f79
Python
2,904
72
# -*- coding: utf-8 -*- """ Created on Tue May 14 10:57:42 2024 @author: Administrator """ import torch from torch import nn import numpy as np class FinerLayer(nn.Module): def __init__(self, in_features, out_features, bias=True, is_first=False, omega_0=30, first_bias_scale=None, scale_req_grad=False): ...
bdb29f7c2582e3665e37567d98697bc5cae127272eed7097616d91af3fd15c46
Python
2,904
82
#!/usr/bin/env python import numpy as np import pandas as pd import click as ck from sklearn.metrics import classification_report from sklearn.metrics.pairwise import cosine_similarity import sys from collections import deque import time import logging from sklearn.metrics import roc_curve, auc, matthews_corrcoef from...
dd1b2acfbfdfd5028e3cf74df1db60def16a85cbfc2a6411cc6fd4ff597497eb
Python
2,904
82
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from types import SimpleNamespace from unittest import TestCase from unittest.mock import MagicMock, patch from rest_framework import status from rest_framework.test import APIRequestFactory from rq.job import JobStatus as RQJobStatus from cvat.app...
99053bdd5f5bf5cffdb6aa68da166dec098418f55d5ce65c72e611e1f9769f85
Python
2,905
99
from __future__ import annotations from collections.abc import Callable from collections.abc import Iterator import pytest from PySide6 import QtCore from PySide6.QtWidgets import QApplication from pytestqt.qtbot import QtBot from labelme import _locale from labelme._widgets._label_dialog import LabelDialog @pytes...
e1676ed2429e01d139ef0f31875342485adbec4542b08854de8f58dbb3890176
Python
2,905
81
#!/usr/bin/env python import warnings warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") import pandas as pd import numpy as np from sklearn.externals import joblib from PAINTeR import global_vars import PAINTeR.connectivity as con...
acbcdffd377b89948715b354ee72e0e108694458b4f200123295b12257f3d162
Python
2,906
74
from torch.utils.data import DataLoader from geoseg.losses import * from geoseg.datasets.isic2018_dataset import ISIC_Dataset from geoseg.models.deepunet.DeepUnet import Model from catalyst.contrib.nn import Lookahead from catalyst import utils CLASSES=('background', 'foreground') # training hparam max_epoch = 100 i...
c88eec27953cef63ded46be616ae462128579f76e43ff62c906f139ed0376abb
Python
2,906
97
""" Kernels. """ # Author: Oualid Benkarim <oualid.benkarim@mcgill.ca> # License: BSD 3 clause import numpy as np import scipy.sparse as sp from scipy.stats import rankdata from scipy.spatial.distance import pdist, squareform from sklearn.metrics.pairwise import rbf_kernel from .utils import dominant_set def _bu...
5e38b33a832dab48c154a9e6699d5c0748b7049fe2ac59ca30c2cab20faf34f3
Python
2,907
89
import glob import json from run import parse_config from run import check_dict class colors: GREEN = '\033[32;1m' RED = '\033[31;1m' ENDC = '\033[0m' def print_diffs(test_path, tmp_path, verbose=False, failed_only=False): error_files = glob.glob(tmp_path + "/**/*_diff.json", recursive=True) error_boundari...
b5e0e9dc9937ce07213bf50169ed9a511b8784f535e6420c1c7eccca7a12d0f5
Python
2,908
83
import pytest from eir.predict_modules.predict_target_setup import _load_labels_for_predict from eir.setup import config from eir.target_setup.target_label_setup import ( gather_all_ids_from_output_configs, get_tabular_target_file_infos, ) from tests.setup_tests.fixtures_create_data import TestDataConfig @py...
f455c83108fa59772a9823fd340efca6b6baff5d3c7cf38c9df4fde328fbaeb0
Python
2,908
92
import numpy as np def notnan(x, start=0, increment=1): while np.isnan(x[start]) and 0 <= start < len(x): start += increment return start def fill_nans(x): """ :param x: 1D array -- will :return: the array with nans interpolated The input argument is modified. """ nans = np...
ae6c84a8f19916ca2d3823114acbc2efd67754aba9dbbe73c54f4c5852b53050
Python
2,909
63
# !/usr/bin/env python # coding: utf-8 # @Time : 2022/7/17 13:54 # @Author : Z.-H. G. # @Email_0 : guozhenhao17@mails.ucas.ac.cn # @Email_1 : guozhenhao@tongji.edu.cn # @File : params.py # @IDE : PyCharm import pandas as pd # TODO yaml PARAMS = \ {'preprocess': { # We only recommend...
b8c6c70cb3d138c3ef21b21ae136710dbfcbc1d3f8b2c1ca0cb988199254e284
Python
2,909
83
#!/usr/bin/env python2.4 """ Returns all positions of a maf with any pwm score > threshold The positions are projected onto human coordinates """ import sys from bx import intervals from bx.align import maf as align_maf from bx.pwm.pwm_score_maf import MafMotifScorer def main(): if len(sys.argv) < 5: pr...
ba8bfb78cc97d123f5c211691e2f15a682787236218935da079b277259d8fe70
Python
2,909
91
import torch.utils.data as data_utils import torch from PIL import Image import numpy as np import random import glob import os import math from Utils import utils Map = { 'Normal':0, 'NETU': 1, 'ELSE': 1 } utils.seed_torch(seed=0) class ZSData(data_utils.Dataset): def __init__(self, path, path2, tra...
ee581e05dd552153a54faeb1b199ae81cbdf2821b23c3ea218e03600ba2418bb
Python
2,909
85
import subprocess import sys import yaml import os from glob import glob import pandas as pd import numpy as np print ('starting script Meanvar Quantities!') pathpath = 'PATHS/general_paths.yml' with open(pathpath,'r') as f: pdict = yaml.safe_load(f) genpath = pdict['metricsextraction'] script = 'metrics_extraction...
8108a10403cfd2c90273572ac4fee6a557a6152eb9edc8c7d41a67a5ca7cc672
Python
2,910
91
from __future__ import annotations from collections.abc import Callable from typing import TYPE_CHECKING, cast from ._container_widget import ContainerWidget if TYPE_CHECKING: from magicgui.widgets import protocols from magicgui.widgets._concrete import MenuBar, StatusBar from ._widget import Widget c...
42a093281d722fb89a2eaf63c60bdb248346899ba1f90fba90bbabe17e45853e
Python
2,911
103
import os from types import SimpleNamespace os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") import pytest pytest.importorskip("PySide6") from PySide6.QtWidgets import QApplication _APP = QApplication.instance() or QApplication([]) from musclex.modules.ProjectionProcessor import ProcessingBox from musclex.ui...
6d587a670309abcd1ae866e87d64250f39f436fa641c1a859ccca4917c237dcf
Python
2,911
83
############################################################################# # Copyright (C) 2020-2026 MEmilio # # Authors: Henrik Zunker # # 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 Lice...
9519691aa5cd80a238efcdb19a48ff0bc02e5b5fa25662067ff996132d33360a
Python
2,912
91
# Copyright (c) OpenMMLab. All rights reserved. from collections import OrderedDict def swin_convert(ckpt): new_ckpt = OrderedDict() def correct_unfold_reduction_order(x): out_channel, in_channel = x.shape x = x.reshape(out_channel, 4, in_channel // 4) x = x[:, [0, 2, 1, 3], :].transp...
b4ad9521239368cea245369487c45cc449907814753f4462e5e444b1d5ef611d
Python
2,912
78
# Generated by Django 4.2.21 on 2025-07-10 17:28 from django.conf import settings from django.db import migrations from django.db.models import Exists, F, OuterRef def delete_email_addresses_for_dummy_users(apps, schema_editor): EmailAddress = apps.get_model("account", "EmailAddress") SocialAccount = apps.ge...
0057289806c86f5a66188ddff27947464c4e99d6182f9b675bbe2a1104f1de9f
Python
2,913
72
from torch.utils.data import DataLoader from geoseg.losses import * from geoseg.datasets.loveda_dataset import * from geoseg.models.DCSwin import dcswin_small from catalyst.contrib.nn import Lookahead from catalyst import utils # training hparam max_epoch = 30 ignore_index = len(CLASSES) train_batch_size = 8 val_batch...
0cc0153259b3b068be956ba4a297514b264e6a0508003aee3a3f2fa8783ca779
Python
2,914
95
from collections.abc import Sequence from pathlib import Path from docs.doc_modules.experiments import AutoDocExperimentInfo, run_capture_and_save def get_tutorial_01_run_1_fusion_info() -> AutoDocExperimentInfo: base_path = ( "docs/tutorials/tutorial_files/b_customizing_eir/01_customizing_fusion_tutoria...
3c340b1a4573236f585de9a99c5339673003f3b5797b7feae979d524226a39aa
Python
2,914
87
''' Script to perform dimensionality reduction over activation values from Wav2Vec2.0. OPTIONS n_features - Number of features to use (default = 50) EXAMPLE USAGE: python audio_w2v2_pca.py n_features=10 ''' import os, sys, glob, gzip, pickle from typing import Any, Union, Callable import numpy as np impo...
5c0d7682bd0cc430ee97b9ac15af17e50bf2bd3093080e8a66b576bc2d9af964
Python
2,914
93
'''Test write csv functionality''' import unittest from ogo.util.write_csv import write_csv import subprocess import shutil, tempfile, filecmp import os class TestWriteCSV(unittest.TestCase): '''Test write csv functionality''' def setUp(self): self.test_dir = tempfile.mkdtemp() self.csv_file...
63fb1e005cfd989d6daeb5d8fe9c1a9ef5e3ccba19a14f21bc7ea375f366c706
Python
2,914
85
#!/usr/bin/python3 # import os import sys import argparse import numpy as np from uac import utils # Create the parser my_parser = argparse.ArgumentParser(description="Calculation of labels using laplace solves only") # Add the arguments my_parser.add_argument("target_path", metavar="path", type=str, help="Path for ...
cefcbdce170ef49fc3b8b6cd1e9f8776ba337f2cace30349dbaea42bcb0e5b62
Python
2,914
80
"""Load Anthropic models using LangChain.""" import os from getpass import getpass from langchain_anthropic import ChatAnthropic from chemgraph.models.supported_models import supported_anthropic_models from chemgraph.utils.logging_config import setup_logger logger = setup_logger(__name__) def load_anthropic_model( ...
da7828f3bd64cc4c1c041b775e63f3864a20c1bc155ad31dfe08f7fcdd8dd1e9
Python
2,914
74
from torch.utils.data import DataLoader from geoseg.losses import * from geoseg.datasets.isic2018_dataset import ISIC_Dataset from geoseg.models.Unet import UNet from catalyst.contrib.nn import Lookahead from catalyst import utils CLASSES=('background', 'foreground') # training hparam max_epoch = 100 ignore_index = ...
c9cdfd05037b11cf316fdee3b32a042376492fff3282dbc3c6e414ae795994fd
Python
2,916
110
import matplotlib.pyplot as pl import numpy as np def confusion(seqs1, seqs2, n1, n2): """Compute the confusion matrix between two labbelled sequences.""" C = np.zeros((n1, n2)) for i in range(len(seqs1)): b3, b4 = seqs1[i], seqs2[i] C[b3, b4] += 1 C = C / C.sum(axis=1)[:, np.newaxis] ...
db8e75e43ddd60a0fe8b39ee89d4e51d2a5905d92c384f4b398f7b176912bd4c
Python
2,916
70
import ctk from slicer.util import VTKObservationMixin import slicer import qt class MultiModelSelectorWidget(ctk.ctkCheckableComboBox, VTKObservationMixin): def __init__(self, parent=None): ctk.ctkCheckableComboBox.__init__(self, parent) VTKObservationMixin.__init__(self) self.addObserve...
18a94dff039379e5f089a95c52a73f3fb01c04494dcfba208c402d4739f4c9b3
Python
2,917
43
from brainscore_core.supported_data_standards.brainio.assemblies import DataAssembly from brainscore_vision import data_registry, stimulus_set_registry, load_stimulus_set from brainscore_core.supported_data_standards.brainio.s3 import load_assembly_from_s3, load_stimulus_set_from_s3 BIBTEX = """@Article{Kar2019, ...
1ab4cd6ead4e3813c4bb9cdf3d2e75205ebe02a6bbe873d0162243e23eafadd5
Python
2,917
71
import os from dataset_src.cath_imem_2nd import Cath_imem,dataset_argument from torch.optim import Adam from torch_geometric.data import Batch,Data from dataset_src.utils import NormalizeProtein from Bio.PDB import PDBParser from Bio.PDB.DSSP import DSSP import torch.nn.functional as F import torch from tqdm import tqd...
f6ff6b57b71e0ce4d8873948c1f2ed11cfafc1e30e422f74d800f1baf4a69345
Python
2,917
59
"""Post-hoc analysis of inferred state/mode dynamics. This subpackage provides tools for analysing the output of trained models (HMM states, DyNeMo modes, etc.) and for static (time-averaged) analysis. Modules ------- - :py:mod:`~osl_dynamics.analysis.connectivity` — Functional connectivity analysis (coherence, ima...
b02ec847fa582b29e5505d73296f0fb1211299571e88459741dd92abd80b69c9
Python
2,918
57
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from fixres.hubconf import load_state_dict_from_url from fixres.transforms_v2 import get_transforms from brainscore_vision.model_helpers.activations.pytorch import load_images import numpy as np from importlib import import_module import ssl...
fdd239bdb379ebcf66862f465e694b6f5f742789c32efb4a800a1bcfae0d0ff0
Python
2,918
80
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path import torch from ultralytics.utils import LOGGER from ultralytics.utils.checks import check_requirements def _remainder_scalar(x: torch.Tensor, s: float) -> torch.Tensor: """Decompo...
31ec806aacebc06093e3561e74aff114d092057e67bdf2e78ef011fdbcf167db
Python
2,919
91
import numpy as np import pandas as pd from scipy.stats import zscore import pickle import fire from joblib import Parallel, delayed from rsatoolbox.rdm import RDMs from rsatoolbox.model import ModelWeighted from rsatoolbox.model.fitter import fit_regress import rsatoolbox from mne import read_source_estimate from ...
66d990c228febc698d75613dd110e8be8f46fe2404ba064be38cc4a873dc4645
Python
2,919
107
"""Utilities for lazy generation of FastSurfer crop volumes.""" import logging import os from concurrent.futures import ThreadPoolExecutor import nibabel as nib from nibabel.spatialimages import SpatialImage from tqdm import tqdm from pyment.preprocessing import conform logger = logging.getLogger(__name__) def en...
ec0529408415933fad0918224771bffdc398eace9518e6921d602d55386250c7
Python
2,920
49
"""Rebuild current figure scripts in an isolated staging directory and compare outputs.""" import fitz import hashlib import json import re import shutil import subprocess import tempfile from pathlib import Path ROOT=Path(__file__).resolve().parents[2] NAMES=['primary_enrichment','npp_oxphos_evidence','oxphos_gene_lan...
dfd4cde062b0f2647f9e344401d3ee1bb7aac1cbe81999aabab57770f4f8414d
Python
2,921
87
""" Classes to support nib files. :Author: James Taylor (james@bx.psu.edu), Bob Harris (rsharris@bx.psu.edu) A nib sequence is a sequence of DNA, using the 10 character alphabet A,C,G,T,N (upper and lower case). The file is packed as 4 bits per character. nib file format --------------- Fields can be in big- or li...
4eca8451c879c0f733111e75b711513bb25b8ff718b4148683dc807f05c4d47a
Python
2,922
110
""" Evaluation plotting utilities for score prediction. """ from pathlib import Path from typing import Optional, Sequence import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import ( roc_curve, auc, precision_recall_curve, average_precision_score, confusion_matrix, ConfusionMatrixDisp...
65067cf0056a7b404bcf4052f0664117c0f10234d39a06180cf3f64eee3f2615
Python
2,922
82
#!/usr/bin/env python3 import torch import matplotlib.pyplot as plt import SimpleITK as sitk from time import time from fireants.io import Image, BatchedImages from fireants.registration.affine import AffineRegistration from fireants.registration.greedy import GreedyRegistration from fireants.interpolator import firea...
d840912d2a8982820d0d661e7f893d5298e375ad7f5f372705d01d290f1f177b
Python
2,922
94
import numpy as np import pandas as pd import scipy.ndimage as nd from skimage import io as skio import sys import getopt def usage(): print(""" Usage : python3 gen_stacked_tif.py < -i mask.lst> < -a anno.txt> < -o output prefix> ...
fcb21c6d9d9de019259152ffda28dd39785382cc27f0438c437fa9f2ca5cb027
Python
2,922
57
import numpy as np def one_tailed_bootstrap(sample1, sample2, iterations=1000, direction='greater'): # Perform bootstrap resampling resampled_mean_diffs = [] one_tailed_p_value = [] for _ in range(iterations): resampled_sample1 = np.random.choice(sample1, size=len(sample1), replace=True) ...
8fc9555ccf04997d73d33852b07309660e75ac1bd608201c89ea9792ca56a308
Python
2,924
97
from dataclasses import dataclass from functools import reduce from typing import Any, Literal, Protocol, TypeGuard from torch import Tensor, nn from eir.models.input.array.models_cnn import CNNModelConfig class ImageModelClassGetterFunction(Protocol): def __call__(self, model_type: str) -> type["ImageWrapperMo...
e3c701c4829d4bba9bed0a4e9dd35fc12a14445b23c57c91e167ede9e5e19a09
Python
2,924
85
import pytest from pathlib import Path import numpy as np from unittest.mock import Mock, patch from stack_corr.image import um_to_pixel, pixel_to_um class TestUmToPixel: """Test the um_to_pixel function.""" def test_um_to_pixel_basic(self): """Test basic conversion from micrometers to pixels.""" ...
23848ea2cf7e8f87275e9b5b1f24a9e85b2a430e5ce36bcaef07ccc7a9912ad6
Python
2,925
93
"""Roundtrip testing of npy-matlab. Write data in NPY format to be read and rewritten using npy-matlab. Then re-read the matlab written data again and check if it is still the same. """ import os import os.path as op from subprocess import call import numpy as np import skimage.data # For numpy data types see: # ht...
8eccd1b8ffc5d952788cc1f9594cc21fda950b5d585decf97efc898c394fa793
Python
2,925
80
import os from typing import Tuple from batchgeneratorsv2.helpers.scalar_type import RandomScalar, sample_scalar from batchgeneratorsv2.transforms.base.basic_transform import ImageOnlyTransform import torch class GaussianNoiseTransform(ImageOnlyTransform): def __init__(self, noise_variance: Rand...
07b0d32b2ce972fa884a18dca07ab6d8d2c6b933bf20e006f93dfe6cc72f6f7c
Python
2,926
86
############################################################################# # 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...
f5ad0397ef54b3745340b345c1a0cde5a5e3f06cf74c720090efd0cd0673c9d0
Python
2,926
88
"""Coordinate conversion between native atlas pixels and display pixels.""" from collections.abc import Sequence import numpy as np def scale_coordinate( value: float, source_extent: int, target_extent: int, ) -> float: """Map one coordinate between endpoint-aligned pixel coordinate systems.""" ...
0a6c949955a39c2228873f2ee6cb03839e311c94e756cce1c8d1303cf09aac28
Python
2,929
83
#!/usr/bin/env python # Copyright International Society for Tractography (IST) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
5308ecc512317fe555ae6b497b5356e4d5ee8e052cf6d89670b795e99ff5ea47
Python
2,929
81
from typing import cast, Final import numpy as np from matplotlib.axes import Axes from rscvp.util.cli import DataOutput, PlotOptions, StimpyOptions, Suite2pOptions, get_neuron_list, NeuronID from scipy.ndimage import gaussian_filter1d from tqdm import tqdm from argclz import AbstractParser from neuralib.io import cs...
a6e515905d8424598f1e41e5f69e59eef6cd614c823bf9be4224afb532307061
Python
2,929
38
import numpy as np from ..spherical_cartesian_conversion import cartesian_to_spherical, spherical_to_cartesian class TestSphericalCartesianConversion: def test_cartesian_to_spherical(self): np.testing.assert_allclose(cartesian_to_spherical([[0, 0, 1], [0, 0, -1], [0, 0, -20]])[:, 1:], [[0, 1], [180, 1],...
ce804c52c4ac06183f50cb9c5f6418f7d260db7cd82adb98181bf3fd9a720a36
Python
2,929
127
#!/usr/bin/env python # ## @file # # Generate a pattern for the SLM. # # Hazen 01/15 # import numpy import scipy import scipy.misc import sys size_x = 1080 size_y = 1920 image = numpy.zeros((size_x, size_y)) + 127.0 # vertical grating. if 0: for i in range(size_y): image[:,i] += -51.2 * i # horizontal g...
106272fa82f175e96baba0b1561b6754ac133f013e7067ce9544568a53aa4765
Python
2,930
72
import os import subprocess import shutil import nibabel as nib import time import numpy as np import pandas as pd from nipype import Node, Workflow from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec, TraitedSpec, File, Directory, traits, CommandLineInputSpec, File, TraitedSpec, CommandLine, Direc...
3b74f4570c8016d838b9f308f77c48424ff10c10b705cb63da2280fb9d5d2b61
Python
2,930
59
single_agent_prompt = """ You are a computational chemistry expert. Your goal is to solve the user's request using only the **minimum number of necessary tools**, without guessing or overusing functionality. Responsibilities: 1. Carefully extract all relevant inputs from the user's request, including: - Molecule n...
a1debaff71d0ea2ec2bdc179f71c96666d20b22a4a11ed11ca2e8d72ca751d95
Python
2,931
83
import torch.nn as nn def conv_layer(in_channels, out_channels, kernel: int = 3, stride: int = 1, padding: int = 1, dropout_rate: float = 0.0): return nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=(kernel, kern...
a259dc074c2fa201f1dec7f8b637d92f1d7c3d50a7a8f526f813c1cd97290000
Python
2,931
111
#!/usr/bin/env python2 import sys import os import signal import gzip from optparse import OptionParser USAGE = """ extract-from-fastq36-pair.py --in1 <fq .gz file> --in2 <fq .gz file> """ parser = OptionParser(USAGE) parser.add_option('--in1',dest='inFQ1', help = 'input 1 fqFILE .gz') parser.add_option('--in2'...
8d1b89e15e1645ceb2b647dd3d694e6079991be97fa91148aadc92ff5b455858
Python
2,933
78
#!/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=['others.zip']) tmp_dir = tempfile.Tempo...
f3431b41ec521183227e6c5d0cd031a3a4d386cd866d55c92d257a9b6b399d3f
Python
2,933
98
#!/usr/bin/env python """ Masks an AXT or MAF file based on quality (from a binned_array) and outputs AXT or MAF. Binned array form of quality scores can be generated with `qv_to_bqv.py`. usage: %prog input output -i, --input=N: Format of input (axt or maf) -o, --output=N: Format of output (axt or maf) -...
68113881bdb236b8e001ad462ce877d3643eb7f663f04d87886d87c086ceed96
Python
2,934
79
# @String(value="<HTML><b>Scale: Apply Scaling Factor(s)",visibility="MESSAGE") msg1 # @double(label="X", min=0d, stepSize=0.05, style="format:#.00000") xscale # @double(label="Y", min=0d, stepSize=0.05, style="format:#.00000") yscale # @double(label="Z", min=0d, stepSize=0.05, style="format:#.00000") zscale # @double(...
389426990334ab10c6d427c8c0743298ed00112b6c67cf8c95e411db95722d5a
Python
2,935
106
import contextlib import platform import sys from unittest import mock import pytest from qtpy import PYQT5, PYSIDE2 @pytest.mark.skipif(not PYQT5, reason="Targeted to PyQt5") @mock.patch.object(platform, "mac_ver") def test_qt59_exception(mac_ver, monkeypatch): # Remove qtpy to reimport it again with conte...
8784adf85efb4aafbd19801165e18dbf4335ecffdf33ee070741be29625723b8
Python
2,936
87
import os import sys sys.path.insert(0, os.path.abspath('../../src')) import traceback try: from rscvp.statistic.csv_agg.core import NeuronDataAggregator except Exception as e: print("####### Import NeuronDataAggregator failed:", e) traceback.print_exc() project = 'rscvp' copyright = '2025, yu-ting wei'...
8b3ef3d2ae9ae5c8a5cced7a6477567c8f358688aa4b020f7ab70ae6c6fb8bfc
Python
2,936
89
import itertools cfg = snakemake.params.dropConfig exportCounts = cfg.exportCounts sampleAnnotation = snakemake.params.sampleAnnotation # adapt sample annotation data frame sa = sampleAnnotation.annotationTable.copy() sa["STRAND_SPECIFIC"] = sa["STRAND"] != "no" if "ICD_10" in sa: sa["ICD_10"] = sa["ICD_10"].str....
ca44fa160bfffe0397dc4a269f253a7565033afd746bdff8e88390972a299de2
Python
2,936
71
import sys,os from Bio import SeqIO import pandas as pd import numpy as np def generate_sequences(): filepath = sys.argv[1] RESIZED_LEN = 2000 fasta_sequence_dict = SeqIO.to_dict(SeqIO.parse(open('hg19.fa'), 'fasta')) locations = pd.read_csv(filepath, sep = '\t', names = ['chr', 'start', 'stop', 'label'...
7762590b3ecd77d5d14a2aa4605e18a5c9e3d6ac46d1cc240c8b26e44d915c9b
Python
2,937
86
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT """Create a project with labels, then list, filter, retrieve, and rename it. Steps: 1. Create a project with a simple label schema. 2. List all projects visible to you (pagination is handled by the SDK). 3. Filter projects by a name substring....
9bbeb7183161ce8f85a7481b561c0221a9c76ca20f1354cac6bbda5c36dbf748
Python
2,937
100
#!/usr/bin/env python import os import sys sys.path.append('.') import click as ck import numpy as np import pandas as pd import time import math from utils import Ontology, NAMESPACES import gzip from extract_esm import extract_esm from pathlib import Path import torch as th from Bio import SeqIO @ck.command() @ck.o...
bdde0cf4fc5f5b081d80cbab137313cca5ca334f198ed850cd19bd42a270e3f2
Python
2,937
93
# -*- coding: utf-8 -*- import unicodedata def ispunct(token): return all(unicodedata.category(char).startswith('P') for char in token) def isfullwidth(token): return all(unicodedata.east_asian_width(char) in ['W', 'F', 'A'] for char in token) def islatin(token): return a...
0debc92d5cda84c74b31601c54ffb9c96040501550f11fb975e9bef329a2f952
Python
2,938
93
# -*- coding: utf-8 -*- # python standard library inputs import random # external inputs import numpy as np import nibabel as nb from nibabel.freesurfer.io import read_label from scipy.stats import ttest_ind, levene def analyze_alff_between_conditions(input_label, input_contrast1, ...
555b160457796f35d05a99c537f9f26ec2d07e8da0868f237a854d4636dd9ae8
Python
2,939
79
"""Contains grouped scoring functions.""" import logging import pandas as pd from ..core.score_bcf import score_bcf def score_grouped(bed, config, full=False, variant_log_path=None, prs_name=None): """Generate grouped scores by cluster.""" group_total_cols = [] total_available, total_estimated, total_mis...
4c97b37c626391f0ee316e380d50639937a500f245831872f5f164e13f4fe429
Python
2,940
92
import nibabel as nb import glob import numpy as np import os import pandas as pd import seaborn as sns import matplotlib.pyplot as plt root = '/media/sebastian/Data/S1ANFUNCO/raw_data/S1ANFUNCO_BIDS' subs = sorted(glob.glob(f'{root}/derivatives/sub*')) subs = [fileName.split('/')[-1] for fileName in subs] # test whe...
262e592c07cb88a699d900c74cf9d62cf3b1bc7bd4b6421a53e759d8859c58b3
Python
2,942
110
#!/usr/bin/env python """Tests return widget types""" import pathlib from contextlib import suppress from datetime import date, datetime, time from inspect import signature import pytest import magicgui from magicgui import widgets def _default_equals(object1, object2): assert object1 == object2 def _genera...
555eeef9c0789dd125f5089385d4a74f0efe767953fd594143c673ae57228e8a
Python
2,943
94
#!/usr/bin/env python # coding: utf-8 # In[1]: # In[12]: import anndata import scvelo as scv import scvi import numpy as np from velovi import preprocess_data, VELOVI import torch import os import argparse import time # In[23]: #TLS TLS_path = '/VeloVAE/data/processed/TLS.h5ad' # In[24]: TLS = anndata.read_h5ad(T...
b1174599d8dfbb32e9bd0b69b716bb152d7eddfe763bcb7c9aafb855b168026f
Python
2,943
75
"""Fetch the next recording while the current one is being analysed. The pipeline is a loop over recordings that are independent until the batch-wide barrier, and analysing one takes far longer than fetching it — measured on the CAT-NAP example data, roughly 275 s of compute against 95 s of transfer. Run serially that...
c7f01f00bec66c5365703553bf3af56766f7a983a79308ce6ef60ceb8ed83a6f
Python
2,944
90
#!/usr/bin/env python """ Purpose ---- Batch convert a directory of CMRR physiolog DICOM files to BIDS format and populate a subject/session directory tree. - Adapt parsing logic from extractCMRRPhysio.m (Ed Auerbach) - Wrap previous single-file dcm2physio.py script in this repo Authors ---- Mike Tyszka, Caltech Brai...
0321b2d41f27f324148761173f8070c7c89dc90751507200231ab69073319e79
Python
2,945
75
#!/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 from scilpy.io.streamlines import load_tractogram # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dic...
9305b40587d75e3347c2c5b3c670b947b9acb41e9a72d7325cc9dda69e9df109
Python
2,945
111
#!/usr/bin/env python3 import sys import os import signal import gzip from optparse import OptionParser USAGE = """ extract-from-fastq36-pair.py --in1 <fq .gz file> --in2 <fq .gz file> """ parser = OptionParser(USAGE) parser.add_option('--in1',dest='inFQ1', help = 'input 1 fqFILE .gz') parser.add_option('--in2'...
9eea1e8d945efbfffe8e65f93916a0d4e1c8e682767049dddcdfe7bf0240ef6c
Python
2,945
90
# -*- coding: utf-8 -*- # python standard library inputs import math # external inputs import numpy as np import shapely.geometry as geometry from scipy.spatial import Delaunay from shapely.ops import cascaded_union, polygonize def alpha_shape(points, alpha): """Alpha shape. This function computes the ...
f20a229865eb4f985c546c3b73733bbf92e553f0cf78222f0751148704660e39
Python
2,945
74
import pandas as pd import plotly.graph_objects as go from pathlib import Path # ground ground_x = [] ground_y = [] ground_z = [] for ith_x in list(range(0, 45)): for ith_y in list(range(0, 45)): ground_x.append(ith_x) ground_y.append(ith_y) ground_z.append(0) z = [0.01] * len(ground_x) p...
4cf955c1858a47f6027467bc5bd2f7700ab20f02625d7ab51839620659544b33
Python
2,948
72
import os import torch import argparse import esm import esm.inverse_folding from glob import glob from tqdm import tqdm from transformers import T5EncoderModel, T5Tokenizer def get_args(): parser = argparse.ArgumentParser(description='Generate embeddings from PDB directory') parser.add_argument('--pdb_dir', t...
0f95ade52f481144907f08e94993a73b58388eeb4ad071ee6805472f04174c74
Python
2,949
64
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './designerFiles/alert.ui' # # Created by: PyQt5 UI code generator 5.12.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_alertBox(object): def setupUi(self, alertBox): ...
2a491780eb9c4672f3c0f526094eaccc18ebb1f2a0fb8e9765ecd90843e3a062
Python
2,949
61
#!/usr/bin/env python3 # Author: Francois Aguet import argparse import os.path import subprocess from datetime import datetime import contextlib @contextlib.contextmanager def cd(cd_path): saved_path = os.getcwd() os.chdir(cd_path) yield os.chdir(saved_path) parser = argparse.ArgumentParser(descripti...
ed38e253782746d80ca52dd633803119fe7bef7b127dddb023fb565592dbc2bf
Python
2,949
81
import torch import numpy as np import os from PIL import Image import torchvision.transforms as Trans import pandas as pd class FCDDataset(torch.utils.data.Dataset): def __init__(self, size, path, use_cond=True, test=False, tsv_path=None): super().__init__() self.img_directory = os.path.expanduser...
eee8b40b8f20721ce705d6ae3a778ca06ccacd41933ca865bd1e72ac68265b9a
Python
2,950
139
from .aq2009 import ( AQ2009GM, AQ2009Counts, ) from .base import ( AbstractBenchmarkDataset, BenchmarkDataset, Bucketer, GeometricBucketer, MultiWaveformDataset, WaveformBenchmarkDataset, WaveformDataset, WaveformDataWriter, ) from .bohemia import BohemiaSaxony from .ceed import...