sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
2ecb2d7dbb8b4b697e21f0acc5100e966ce52f57bc9eb05d14e23c8b721ec866 | Python | 7,286 | 208 | import cv2
import lmdb
import sys
from multiprocessing import Pool
from os import path as osp
from tqdm import tqdm
def make_lmdb_from_imgs(data_path,
lmdb_path,
img_path_list,
keys,
batch=5000,
com... |
4c2ad7b475369992f667ad58bb07df8e3c71157373f8ec6a4416b8369db23e0d | Python | 7,289 | 217 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import pickle
import time
import logging
import fastai
import numpy as np
import pandas as pd
import torch
import hydra
from hydra.utils import get_original_cwd
from omegaconf import DictConfig, OmegaConf
# tsai/fastai imports
from fastai.callback.tracker imp... |
04340d3392b75777dd0e609188452d9310e6bb620186b44c481d86477ca80348 | Python | 7,290 | 189 | from __future__ import annotations
from typing import Any
import numpy as np
from scipy.optimize import linear_sum_assignment
from soccertrack import BBoxDataFrame
from soccertrack.utils.utils import list2dict
def hota_score(bboxes_track: BBoxDataFrame, bboxes_gt: BBoxDataFrame) -> dict[str, Any]:
"""Calculates... |
0f2b3ea467e34fbe3a52c2c7e19d6f2a6a3dd8148282f7543842d2baa0efba02 | Python | 7,295 | 172 | #!/usr/bin/env python
# encoding: utf-8
import itertools
import logging
import os
import re
from pathlib import Path
import numpy as np
import pandas as pd
from .. import utils
# from .utils import preprocess
# from . import get_logger, set_logger_level
def ttl_extraction(physio_df, dict_beforettl, dict_afterttl, ... |
6c2fd1c5408a299c03d84fef8b44fbccdf4b304370437d54aba5ee6824a0573f | Python | 7,295 | 221 | import os
import copy
import random
import pickle
import math
import torch
import numpy as np
import pandas as pd
from torch.utils.data import Dataset
from tqdm.auto import tqdm
from Bio.PDB.PDBParser import PDBParser
from Bio.PDB.Polypeptide import one_to_index
from rde.utils.protein.parsers import parse_biopython_st... |
485d2127a82e3dd0e4219a9d75798bd7ce47194fe11a733b2367e495ce673d7e | Python | 7,298 | 131 | # Download CC-0 licensed data from DrugBank (https://go.drugbank.com/releases/latest)
import csv
import os.path
import shutil
from zipfile import ZipFile
import requests
from src.categories import COMPLEX_MOLECULAR_MIXTURE, FOOD
from src.datahandlers.ncit import read_ncit_code_set
from src.datahandlers.unii import re... |
1e8b7d1c7f814fb5ab71c76e124ab0b11ea25b152553e6aaadcb5e1792c2c9fc | Python | 7,307 | 211 | # model twi-esn
import numpy as np
from scipy import sparse
from scipy.sparse import linalg as slinalg
from sklearn.linear_model import Ridge
import gc
from utils.utils import calculate_metrics
from utils.utils import create_directory
from sklearn.model_selection import train_test_split
import time
class Classifi... |
7b613cec8ca3354868d0d7f20fde81d9657dffd31d95da3829a938ef95b7d436 | Python | 7,308 | 170 | """Contract tests for CsvRecordingExtractor."""
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from guppy.extractors.csv_recording_extractor import CsvRecordingExtractor
from .recording_extractor_test_mixin import RecordingExtractorTestMixin
# ----------------------------------------... |
9e39811a7bb91c67b8a5a227aac53ac0d598a9883db7c9792b0e1fd45aae3dc8 | Python | 7,309 | 151 | # -*- coding: utf-8 -*-
import json
from catmaid.models import ClassInstance
from .common import CatmaidApiTestCase
class SearchApiTests(CatmaidApiTestCase):
def test_search_with_no_nodes(self):
self.fake_authentication()
response = self.client.get(
'/%d/search' % self.test_pro... |
b67ce537f1dabbe46dab8ecf1a9f132c2a51b24adf98c24f12955c8370c91ef9 | Python | 7,310 | 174 | # testing install from https://pytorch-geometric.readthedocs.io/en/latest/notes/installation.html
# https://pytorch.org/get-started/locally/#macos-version
# https://www.jetbrains.com/help/pycharm/conda-support-creating-conda-virtual-environment.html
from __future__ import print_function
import torch
import torch.nn.f... |
1b28a8bd708220469745184945b3485059c195c266bcb98d9dd96b3fa72f3578 | Python | 7,316 | 198 | """Tax scope filtering for v7+ integer-encoded databases.
v7 databases use NCBI taxids in OG names, not the v5-style taxonomic
level names. This module provides a thin ``LineageFilter`` delegate that
forwards all ceiling resolution and species-set queries to a
:class:`~eggnogmapper.annotator.e7.ceiling.TaxScopeCeilin... |
94818244b528fc094d59ca6162c16619c83d66ad777b859a66d266a0c2909480 | Python | 7,318 | 180 | """
Save the simulated test data in the BIDS format for the mqBOLD processing.
"""
import glob
import os
import shutil
import h5py
import numpy as np
import nibabel as nib
from data.t2star_loader import compute_coil_combined_reconstructions
def save_as_bids(data, folder_bids, folder_scanner_bids, acq="fullres",
... |
551fe437c68b424ca0d2d8475beab45cb129fa08024b1b026b6c24bc92ef24b2 | Python | 7,324 | 136 | from src import helper_functions as hf
from src import config as cfg
from src import data_io as io
import os
import traceback
import logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
#logger.setLevel(logging.ERROR)
#logger.setLevel(logging.CRITICAL)
... |
2ea4b9959b8a29b18887c62da8114f76d61a039084a96c245b0204cd64999c6d | Python | 7,326 | 216 | from aggregator.serializers import (
AggregatorSerializer,
)
from traindataset_association.serializers import (
TrainingExperimentListofDatasetsSerializer,
)
from trainingevent.serializers import EventDetailSerializer
from dataset.serializers import DatasetWithOwnerInfoSerializer
from django.http import Http404... |
b2c4eae47a9edf19f878598e5780d16677247a575b58e0d4a3c49b23c5f368c6 | Python | 7,330 | 185 | #!/usr/bin/env python
"""
# Author: ChangXu
# Created Time : Mon 23 Apr 2021 08:26:32
# File Name: his_feat.py
# Description:`
"""
"""
test:
import scanpy as sc
from integrated_feat import image_feature, image_crop
data_path = "/home/xuchang/Project/STMAP/Human_breast/output/Breast_data/STMAP_Breast_15.h5... |
0ebeb61faddf548484a6a75d2f46425f735ea007a2aa4ea7aa180287d380c2d6 | Python | 7,337 | 188 | import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
import networkx as nx
from .annotation import feature_to_feature_search
def network_analysis(feature_list, annotation_type="hybrid_and_identity", feature_quality="all", show_node_name=False, output=False):
"""
A function to... |
27db16f7d6c494de599d679d979e2c10d9967b8502cf1366a08adf78bc231985 | Python | 7,338 | 197 | import os
import matplotlib.pyplot as plt
from auditory_cortex import results_dir
from auditory_cortex.plotters.plotter_utils import PlotterUtils
# from auditory_cortex.neural_data.deprecated.neural_meta_data import NeuralMetaData
# from auditory_cortex.neural_data.deprecated.recording_config import RecordingConfig
fr... |
5297e6f980c40bf91e63b21eb1828ab30ec12855de6116743e2931c5f57b5cf5 | Python | 7,339 | 153 | # -*- coding: utf-8 -*-
import json
from .common import CatmaidApiTestCase
class LabelsApiTests(CatmaidApiTestCase):
def test_labels(self):
self.fake_authentication()
response = self.client.get('/%d/labels/' % (self.test_project_id,))
self.assertStatus(response)
returned_labels =... |
cd807dc57fab5b74a1445a73967be52fce9ba251098d85c1ed87e65f72310d22 | Python | 7,339 | 212 | #!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... |
364c1356d3ff51d203b68f9c87557ffe9a8dd883a7c0241a0b5846b981c7d3e2 | Python | 7,340 | 187 | # Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import pytest
import torch
from mmengine.utils import digit_version
from mmengine.utils.dl_utils import TORCH_VERSION
from mmseg.models.utils import (InvertedResidual, InvertedResidualV3, SELayer,
make_divisible)
def test_mak... |
9355364cf23dfc3c8de09d161b631bcdaa127ddaf9e6d8b1aa981c5ceb2fafc8 | Python | 7,341 | 229 | # Copyright (c) OpenMMLab. All rights reserved.
"""pytest tests/test_forward.py."""
import copy
from os.path import dirname, exists, join
from unittest.mock import patch
import numpy as np
import pytest
import torch
import torch.nn as nn
from mmengine.model.utils import revert_sync_batchnorm
from mmengine.registry imp... |
b4051ba61673fee4cbb7ff196a2b78ccf9b0dc7071b87532ea1745335e1d9412 | Python | 7,354 | 153 | from django.db import migrations
forward = """
SELECT disable_history_tracking_for_table('catmaid_samplerdomain'::regclass,
get_history_table_name('catmaid_samplerdomain'::regclass));
SELECT drop_history_view_for_table('catmaid_samplerdomain'::regclass);
ALTER TABLE catmaid_samplerdomain ALTE... |
9596d6854bd6de7003f2932e27efaeb7dff6f8ffe133e970e24257a3e642dceb | Python | 7,355 | 224 | #
# Tests for reproin.py
#
from collections import OrderedDict
from mock import patch
import re
from . import reproin
from .reproin import (
filter_files,
fix_canceled_runs,
fix_dbic_protocol,
fixup_subjectid,
get_dups_marked,
md5sum,
parse_series_spec,
sanitize_str,
)
def test_get_du... |
02b1ff270ddc617f5568c82bf6b3aff5eecf5c9fe44bae9e194c7c8690af99a5 | Python | 7,362 | 147 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The scikit-ribo is design for analysis of yeast data, which does not have UTR annotation.
In order to run with other genomes, the boundaries of exons in gtf should be confined to CDS regions (including stop codons).
This script merges the start and stop position of the ... |
bedd73b68e52e93dbcac17742978e5ce35bea136e453a7bbb00a9222e8a71412 | Python | 7,375 | 233 | import os, time, random, argparse
import numpy as np
import open3d as o3d
from pytraj import Trajectory
from matplotlib import colormaps
from feater import io, constants
from siesta.scripts import view_obj
element_color_map = {
# BASIC ELEMENTS
12: [0.5, 0.5, 0.5],
1: [1, 1, 1],
14: [0, 0, 1],
15: [1, 0,... |
9985d8502a311fd67a71401348df00506151aad19c8c56bdd0e248f69beb68da | Python | 7,379 | 212 | # Copyright DST Group. Licensed under the MIT license.
from inspect import signature
from CybORG.Shared import CybORGLogger
from CybORG.Shared.Enums import SessionType
MAX_SUBNETS = 10
MAX_ADDRESSES = 10
MAX_SESSIONS = 8
MAX_USERNAMES = 10
MAX_PASSWORDS = 10
MAX_PROCESSES = 50
MAX_PORTS = 50
MAX_GROUPS = 15
MAX_FILE... |
7c45e4c8c9748b4ffa360355a55da725f068fb5b6d7fcb30a10a92c54c3e9659 | Python | 7,389 | 167 | import matplotlib.pyplot as plt
from umap import UMAP
import matplotlib.cm as cm
from sklearn.decomposition import PCA
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.gridspec as gridspec
def better_spine(ax, spine_width=2, labelsize=20):
ax.spines['top'].set_visible(False)
ax.spin... |
288dca326afa08b4db958c6bd182e2ed93f0897d9b24de7b81469a99eb97cc62 | Python | 7,393 | 227 | ###########################################################################################
# Checkpointing
# Authors: Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
import dataclasses
import loggi... |
45052c848f14d9e40e04f472d6ac1538e7a98d8116d5f267142a02e6e8e0075a | Python | 7,393 | 161 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-10-18 18:26
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
forward_create_tables = """
CREATE TABLE point (
radius real DEFAULT 0 NOT NULL,
confiden... |
7e5c16d1b5b3565f3d46a3456384225a709e4a217e260446c373a5413a19d0d8 | Python | 7,393 | 211 | from __future__ import annotations
from glob import glob
import inspect
import logging
import os
import os.path as op
from typing import TYPE_CHECKING, Optional
from ..info import MIN_DATALAD_VERSION as MIN_VERSION
from ..utils import SeqInfo, create_file_if_missing
lgr = logging.getLogger(__name__)
if TYPE_CHECKIN... |
def01d44ccbfd6268271b8619f4bc45bddd7321f54df2c23f790396effc485c1 | Python | 7,397 | 216 | """Visualization for Geometric Statistics."""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from geomstats.hyperbolic_space import HyperbolicSpace
from geomstats.hypersphere import Hypersphere
from geomstats.special_euclidean_group import SpecialEuclideanGroup
from geomsta... |
7a09732d07076483a2f7529fbff89fa9a55207940e27e93256955dab65962b17 | Python | 7,400 | 163 | import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import r2_score
import pandas as pd
import numpy as np
# Step 1: Load the data
print("Loading data...")
data = pd.rea... |
e16918cef0b579e2fe1d98b2e67a3d337d711dfa71927d39c57341a740ad6bb9 | Python | 7,403 | 197 | import torch
from mr_utils.parameter_fitting import T2StarFit
class ModelFitError:
"""
Computes the ModelFitError as averaged residuals of a least squares fit
(model: exponential decay) to the input data.
"""
def __init__(self, mask_image=True, te1=5, d_te=5,
error_type='squared_... |
69951fec1a84e6414a015bf1de367821077bab0da18304b9cc2acb5e2a07d65e | Python | 7,406 | 183 | from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from diffusers import DDPMPipeline
from diffusers.utils.torch_utils import randn_tensor
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class DDPMPipeline_Costum(DiffusionPipeline):
r"... |
74070627c539c1caad995650d46bcd644f4fdba5dae81c6a7b28f33169c03bda | Python | 7,407 | 220 | import os
from importlib import import_module
import torch
import torch.nn as nn
import torch.nn.parallel as P
import torch.utils.model_zoo
class Model(nn.Module):
def __init__(self, args, ckp):
super(Model, self).__init__()
print('Making model...')
self.scale = args.scale
self.id... |
42ca19f2b545a9313250638b645931051fe412053eb3ebdd79866e91db728e1d | Python | 7,413 | 209 | import base64
from medperf.asset_management.gcp_utils import CCWorkloadID
from medperf.entities.cube import Cube
from medperf.entities.model import Model
from medperf.entities.dataset import Dataset
from medperf.entities.execution import Execution
from medperf.entities.certificate import Certificate
import medperf.con... |
bdfb9345989bf98cbebc90202f5d38e3251f6e681e4b2f47f33cf0344865b203 | Python | 7,423 | 176 | from transformers import GPT2LMHeadModel
from data.task_dataloader.medicalQADataset import GPT2QADataModel
from transformers.optimization import get_linear_schedule_with_warmup
from pytorch_lightning import Trainer, loggers
from pytorch_lightning.callbacks import ModelCheckpoint
import pytorch_lightning as pl
import ar... |
c4d2d806db19c2dae994694c4e36692984c8efe5609ef8526af6c9122fa3028b | Python | 7,423 | 194 | # This file to simulate single cell RNA-seq reads based on real bulk RNA-seq
# expression profile and input dropout rate and number of reads.
import os
import sys
import time
import subprocess
import numpy as np
import scipy.stats as st
from optparse import OptionParser, OptionGroup
# import pyximport; pyximport.ins... |
0448a8cc60cc6c09aacd256d2d3ba61b4c1fb0a5e88c6fea6f8c5872c6568f59 | Python | 7,425 | 180 | import argparse
import numpy as np
import pandas as pd
import scanpy as sc
import os
parser = argparse.ArgumentParser(description='PyTorch scRNA-seq format transformation and preprocessing')
# input & ouput
parser.add_argument('--input_h5ad_path', type=str, default=None,
help='path to input h5ad f... |
9cf38862235a408a7784c5626dbac39a6fb4bacd1183a9e5051db9aa61df3297 | Python | 7,425 | 222 | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.cnn import ConvModule, build_norm_layer
from mmengine.model import BaseModule
from mmseg.models.utils import DAPPM, BasicBlock, Bottleneck, resize
from mmseg.registry import MODELS
from mmseg.utils import OptConfigType
@MODELS.register_m... |
3d5d81c3c3891ffa52efcc62448dc6f476d5f7b8cfb2675e4070d8a822020ada | Python | 7,427 | 206 | # bases functions supporting Brie
import os
import subprocess
import numpy as np
from .sam_utils import load_samfile
from .bias_utils import BiasFile, FastaFile
from .tran_utils import TranUnits, TranSplice
def get_count_matrix(g, g_idx, sam_files, bias_mode, ref_file,
bias_file, FLmean, FLst... |
aca2ae54db8baf289aaeffcf2b8a4b4e82e7b17c24e30e394708e53657c0611c | Python | 7,430 | 196 | import pandas as pd
import numpy as np
import zipfile
import torch
from functools import lru_cache
import os
from copy import deepcopy
from synergy.combination import MuSyC, BRAID, Zimmer
from utils import *
import argparse
from sklearn.metrics import mean_squared_error, r2_score
from scipy.stats import pearsonr
import... |
cab4ca475a2b55af2dd6be580ccff8e91c80ac43d19c91ff3fa0453902751b28 | Python | 7,430 | 239 | import os
import math
import time
import datetime
from multiprocessing import Process
from multiprocessing import Queue
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import imageio
import torch
import torch.optim as optim
import torch.optim.lr_scheduler as lrs
class time... |
ee60e9f6e006340dceb8fdc32a7701b2e753ba1eb1030e7f700f6316b2df1f58 | Python | 7,433 | 212 | pretrained = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/swin/swin_tiny_patch4_window7_224_20220317-1cdeb081.pth' # noqa
crop_size = (512, 512)
data_preprocessor = dict(
type='SegDataPreProcessor',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
bgr_to_rgb=True,
pad_v... |
3845d384b16bab08b6e31860453b29513c47e1e38f390964a6d160b59f2ed9d0 | Python | 7,434 | 132 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
255d7b1cc65986f867c414ab5fd7e581c28b405fdb2cfdf2117057336b1b46a7 | Python | 7,435 | 212 | pretrained = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/swin/swin_small_patch4_window7_224_20220317-7ba6d6dd.pth' # noqa
crop_size = (512, 512)
data_preprocessor = dict(
type='SegDataPreProcessor',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
bgr_to_rgb=True,
pad_... |
277eaae0a8ba2c51288c1720987bf3fd4c0b6d4a6300c311ca18930a26c03adf | Python | 7,435 | 145 | import numpy as np
import random
import os
import requests
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
def loadNetwork(filename, folder, device, k_poses=3, scale_factor=0.15):
"""Load the SDCNN network with pre-trained weights.
Args:
path (str): Path to the saved mode... |
ffe030d0a6732c641352afb0e2bc59b931f3d60949485fcfc951419a35cfec17 | Python | 7,435 | 180 |
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.base import BaseEstimator, TransformerMixin
# ---------------- CAOA Implementation ------------------- #
class CAOAFeatureSelector(BaseEstimator, TransformerMixi... |
e76f02a8b20398137d0b4eac9a72d7af8a7ea27c4f405646398758cee390f4cd | Python | 7,436 | 187 | #!/usr/bin/env python
## ----------------------------------------
## scikit-ribo
## ----------------------------------------
## rna-fold output processing
## ----------------------------------------
## author: Han Fang
## contact: hanfang.cshl@gmail.com
## website: hanfang.github.io
## date: 12/28/2016
## ------------... |
9d12043b61c56d70397bf5385ce107b781441422ce882355646a4d8f1b716e3f | Python | 7,438 | 172 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 2 14:59:21 2023
@author: george
"""
import pyqtgraph as pg
from qtpy.QtCore import *
from qtpy.QtGui import *
from qtpy.QtWidgets import *
from distutils.version import StrictVersion
# determine which version of flika to use
flika_version = flika... |
6ebd6ff49aa92c1682728354d4779544880688712bf5fe705ebb1c6baa564960 | Python | 7,441 | 197 | import logging
import numpy as np
def uniform_atoms_lengths(atoms_lens) -> bool:
# If all of the structures have the same number of atoms, it's really hard to know
# whether the entries are intensive or extensive, and whether
# some of the entries are per-atom or not
return len(set(atoms_lens)) == 1
... |
c0c2356ccbc3c3bb6ece74dfc9a016ab5e0b451cc1b9bbe2f312ffb8d3845a1e | Python | 7,444 | 233 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from tensorflow.keras.optimizers import Nadam
import qtools as qt
from qtools.lossfunctions import siamloss_siamnet, Xsq_SiamReg, siamloss, eloss
from qtools.quartettroutines import siamesemodel, quartetmodel
from qtools.data_trac... |
04ac820db4fb65da3e9d1f4eeda72a206a7265305c74aa1cc617a017529a4633 | Python | 7,445 | 189 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/022_data.mixed.ipynb.
# %% auto 0
__all__ = ['MixedDataLoader', 'MixedDataLoaders', 'get_mixed_dls', 'get_test_mixed_dls']
# %% ../../nbs/022_data.mixed.ipynb 3
from packaging import version
from torch.utils.data.dataloader import _MultiProcessingDataLoaderIter, _... |
b299dd6339056147f9fede8ade61935116472d9e50c43032a1c6b9ce871fb747 | Python | 7,445 | 123 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
d1c77ee49bf31c16564062fad648649c0513c8100d1f9aad8249625ef40e010d | Python | 7,445 | 223 | import numpy as np
import pytest
import xgboost as xgb
from xgboost import testing as tm
from xgboost.testing.metrics import (
check_precision_score,
check_quantile_error,
run_pr_auc_binary,
run_pr_auc_ltr,
run_pr_auc_multi,
run_roc_auc_binary,
run_roc_auc_multi,
)
rng = np.random.RandomSt... |
25eec98d93e04b4cbac3cf5f5375a9794b6f1b044b220701dee24c714919f492 | Python | 7,450 | 169 | # pytest unit tests for sct_dmri_moco
import numpy as np
import pytest
import logging
from numpy import allclose, genfromtxt
from spinalcordtoolbox.scripts import sct_dmri_moco, sct_image, sct_crop_image, sct_create_mask, sct_deepseg, sct_apply_transfo
from spinalcordtoolbox.image import Image
from spinalcordtoolbox... |
3c766ae09e1a8c3a77b23faf2c5ecbeb4f18978ba057efbff24358e270928f83 | Python | 7,450 | 206 | # I tested with torch==2.4.0 (2.6.0 gives troubles, but we an deal with those if we want to go with that version)
# note there is a folder I am pulling from for imports aa couple of lines down, then also NNUnet V1 needs to be
# installed in the environment
import os
import argparse
import pandas as pd
import yaml
f... |
9561500f2c230b6b9f2df20cb71a0c73d6e10729220bc3c2407aae2a40ef85ce | Python | 7,454 | 202 | import numpy as np
import scipy.special as special
class HRLParticleFilter:
def __init__(self, alpha, beta, n_particles, n_states, initial_state_probs=None):
"""
Initialize Particle Filter for HRLParticleFilter
Args:
alpha: Learning rate in HRL model
beta: Softmax t... |
a9d5d9e9c7c6bb21dc4b961a565aecbd84b0eae9827442996bf8f49da8e1f2ac | Python | 7,454 | 167 | from collections import defaultdict
import src.datahandlers.ec as ec
import src.datahandlers.obo as obo
import src.datahandlers.reactome as reactome
import src.datahandlers.rhea as rhea
import src.datahandlers.umls as umls
from src.babel_utils import get_prefixes, glom, read_identifier_file, remove_overused_xrefs, wri... |
d307f7a840c6030e6e1d38ffb958652683c9aab7c0127aeba3adc9caf63b280c | Python | 7,454 | 202 | """Tests for authentication flows."""
import pytest
from httpx import AsyncClient
from zndraw_auth import TokenResponse, UserCreate, UserRead
@pytest.mark.asyncio
async def test_register_user(client: AsyncClient) -> None:
"""Test user registration."""
user_data = UserCreate(email="test@example.com", passwor... |
0ec24b039657e44d29043031c6c92a26b92c4b7277aaf14eac10453f7b580269 | Python | 7,460 | 213 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import glob
import hashlib
import json
import os
import os.path as osp
import shutil
import torch
from mmengine import Config
from mmengine.fileio import dump
from mmengine.utils import mkdir_or_exist, scandir
# build schedule look-up table to automatica... |
aae26b472eb0478f8ba988f7e8f010329d7f345603bba0a7f2153c57f454ce84 | Python | 7,462 | 189 | from anndata._core.anndata import AnnData
from torch.utils.data import Dataset
import torch
from copy import deepcopy
import numpy as np
from torch_geometric.data import Data
from torch_geometric.loader import NeighborLoader
import warnings
class Matrix(Dataset):
def __init__(self,
adata: AnnData... |
3b69692f888e61cd39a2d7f907cb161636fc5e5f53e769ec921d473b07d59ffc | Python | 7,464 | 226 | """
Pipelining primitives for overlapping CPU preprocessing with GPU compute.
The :class:`Featurizer` pipeline has three distinct phases per task:
1. **CPU preprocessing** -- trajectory loading, focal-point parsing, weight
caching and coordinate cropping (``Feature.query``).
2. **GPU compute** -- the CUDA kernels ... |
7bc60b7b0f1c18d05c1272ece079e253b8d2bcb2b62e1d6fb2db29e7786a433e | Python | 7,464 | 200 | # Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import platform
import shutil
import sys
import warnings
from setuptools import find_packages, setup
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content
version_file = 'mmseg/ve... |
787e56b38ca4a94cc677022045ebb9feb89777b6b1eb2b6277adce1b5eee4bf5 | Python | 7,474 | 253 | import re
from functools import partial
# === Regexp replacement machinery ============================================
role_expr = re.compile(r"(:.+:(?:`.+`)?)")
def safe_replace(istr, expr, rpl):
""" Perform a role-safe replacement of all occurrences of "expr", using
the callable "rpl".
"""
out... |
3923ce0be0afa89a51346d61e1279a7b62aaac4c78636f4d0b6dc120cb550eab | Python | 7,478 | 220 | import cv2
import math
import numpy as np
import os
import torch
from torchvision.utils import make_grid
def img2tensor(imgs, bgr2rgb=True, float32=True):
"""Numpy array to tensor.
Args:
imgs (list[ndarray] | ndarray): Input images.
bgr2rgb (bool): Whether to change bgr to rgb.
float3... |
8cf8a96ea893786a0aae207a560343eebc7482994184cfc4cfc0b4b4b75265ed | Python | 7,482 | 190 | def parseEventAlign(eventAlign, outfile, reads, print_sequence = False, header = True):
'''
This function reads nanopolish eventalign file, aggregates signals and the number of
signals correspinding to one base movement for read in readname list.
input:
eventAlign: nanopolish eventalign ou... |
e9a70901c2e5734f9b0b2a572d8e37ec07ff23611e95a537addd282050193d63 | Python | 7,483 | 215 | from typing import Optional
from medperf.entities.training_exp import TrainingExp
import typer
import medperf.config as config
from medperf.decorators import clean_except
from medperf.commands.training.submit import SubmitTrainingExp
from medperf.commands.training.set_plan import SetPlan
from medperf.commands.trainin... |
c62d324a3d0cf33ce64531b85a36bac58b439b8a05627c466fb30e664a747939 | Python | 7,484 | 184 | import os
import io
import cv2
import tqdm
import torch
import imageio
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class ReportGenerator():
"Generate markdown document, summarizing the training"
def __init__(self, run_id, out_dir=None, log_dir=None):
self.run_id, se... |
e15cb8dcc8ae10acf09eff3409a1513fd93a2ea3e2942883a2587cbbe03bfc7f | Python | 7,486 | 170 | """
Functions dealing with image cropping
Copyright (c) 2019 Polytechnique Montreal <www.neuro.polymtl.ca>
License: see the file LICENSE
"""
import logging
import numpy as np
from .image import Image, zeros_like
logger = logging.getLogger(__name__)
class BoundingBox(object):
def __init__(self, xmin, xmax, ym... |
d33ecb3f7b28b28b56e91d31c5cb6d3cf6d5c977e04607e3693e4d476ddd1e57 | Python | 7,487 | 161 | import argparse
import template
parser = argparse.ArgumentParser(description='EDSR and MDSR')
parser.add_argument('--debug', action='store_true',
help='Enables debug mode')
parser.add_argument('--template', default='.',
help='You can set various templates in option.py')
# Hard... |
0a1a7184c5d35c9296d7d5986357eb88c5139ef87b73398525486018e4673ac7 | Python | 7,489 | 286 | import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
# load wandb_export_2024-06-18T13_30_46.429+02_00.csv as df
# df = pd.read_csv('./Results_Analysis/raw_data/SAC_1000.csv')
# df = pd.re... |
0a20305357382b634e197747c41072e9df96d0888cc93b445641ba9c33b8704c | Python | 7,493 | 173 | import os
import sys
import time
import dask
import numpy as np
from dask.distributed import Client, LocalCluster, performance_report
import nearl
from nearl import _tempfolder, features
# Only needs the fingerprint of the
def parallelize_traj(traj_list, focused_res):
traj_list = [i for i in traj_list]
st_... |
d4cead31a93907605bbbcd4a80e4c36891710c4c3a775e0176f898717ce7ad6a | Python | 7,496 | 170 | import numpy as np
import os
import torch
from utils import post_processing
from model import RSTN
import glob
def coarse2fine_testing(imgs_path, output_path, ckpts, device, params):
max_rounds = params["max_rounds"]
fine_threshold = params["fine_threshold"]
crop_margin = params["crop_margin"]
low_ra... |
c1267d7d77810dea992c6cc962ff2236ff9d72c67bdaf50247c739eef9b8dbac | Python | 7,498 | 192 | import torch
from mace.tools.utils import AtomicNumberTable
def load_foundations_elements(
model: torch.nn.Module,
model_foundations: torch.nn.Module,
table: AtomicNumberTable,
load_readout=False,
use_shift=True,
use_scale=True,
max_L=2,
):
"""
Load the foundations of a model into... |
db018a6864a0d41af02ab6bfa3c92ad3893097151a84f54d3990c3f1d32d8460 | Python | 7,500 | 234 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def setup():
import sys
paths = get_paths()
create_dir(paths['log'])
setup_logger(paths['log'])
#get_data(files=paths['task'])
#if sys.platform == 'linux':
# enable_siblings(path_dataset=paths['behavior'])
# update_dataset(path_datase... |
a1d3cb70ee8e25fadc83fc2bd729cfdaf8a32a0887060b68a41dd5571470f869 | Python | 7,502 | 182 | """Input layer code (`Input` and `InputLayer`).
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from .base_layer import Layer
from .base_layer import Node
from .. import backend as K
from ..legacy import interfaces
from ..utils.generic_utils import unpac... |
fbff1e2937dc62635d3a8544e8bdbe2cd716da212364c5dbe4e8d254ed6f6a7d | Python | 7,502 | 233 | """Integration tests for geometry ownership and admin lock enforcement.
Tests use the real server (server_auth fixture) with admin/guest role separation
and the Pydantic model API: vis.geometries["key"] = Sphere(owner=...).
"""
import jwt
import pytest
from zndraw.client import ZnDraw
from zndraw.geometries import S... |
25b9361bef5090373badf35cfced919920777495b32ff7b9e73c5000ca6df989 | Python | 7,503 | 208 | import typing
from typing import Set, Optional, Generator, Any
import rdflib
from rdflib import Namespace, URIRef, OWL, RDFS, RDF
from kgx.config import get_logger
from kgx.source import RdfSource
from kgx.utils.kgx_utils import (
current_time_in_millis,
generate_uuid,
sanitize_import
)
log = get_logger(... |
1bf583a90ffa8614d73bbf466d2fdc19e792b0dfe0e8f9a4163e0ea1058fb69e | Python | 7,506 | 211 | import pandas as pd
import os
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# experiments and subjects to be analyzed
experiments = ['ERN', 'LRP', 'MMN', 'N170', 'N2pc', 'N400', 'P3']
subjects = [f"sub-{str(i).zfill(3)}" for i in range(1, 41)] # TODO: 40 subjects
# define triggers and stuff... |
dd2ff7459a1566c750193d84fa863bdfa40d56f950712898a8f3f1c0942b660e | Python | 7,506 | 251 | from queue import Queue
from contextlib import contextmanager
from yaspin import yaspin
import typer
from medperf.ui.cli import CLI
from medperf.web_ui.schemas import Event, EventsManager, GlobalEventsManager
class WebUI(CLI):
def __init__(self):
super().__init__()
self.responses: Que... |
1afbc12d612b1c5045b2bb8dc1faa22144ebc69309bf1439230e17a05f966ea6 | Python | 7,508 | 172 | import matplotlib.pyplot as plt
import numpy as np
import itertools
import seaborn as sns
import math
from sklearn.cluster import KMeans
import meld
from sklearn.decomposition import PCA
from scipy.spatial import KDTree
import pandas as pd
def create_spatialKDTrees(coordinate_set_1, coordinate_set_2):
# construct... |
bfcfedcdd9acf0eb0cb92a64066f3c885f8ead7cbcd1432e1e2d4e526ee14d23 | Python | 7,514 | 260 | ## The following code contains work of the United States Government and is not subject to domestic copyright protection under 17 USC § 105.
## Additionally, we waive copyright and related rights in the utilized code worldwide through the CC0 1.0 Universal public domain dedication.
"""
Implements misinformation actions... |
db375d7e502b628f21a8d6d513ef4e46d48ff758f341ed3709417ee6dff374ac | Python | 7,519 | 217 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import tempfile
import os.path as op
import os
import re
import sys
from random import choice
# Import everything from the configuration file
from configuration import *
def exit_err(msg):
print(msg)
sys.exit(1)
def backup_existing_copy(path):
... |
754c477e0dae0fb206e76d82786589dd9de454749a961e5844e826594dea47f1 | Python | 7,524 | 197 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmseg.registry import MODELS
from ..utils import resize
from .decode_head import BaseDecodeHead
try:
from mmcv.ops import PSAMask
except ModuleNotFoundError:
... |
507693db0bd58ec5c9577db37961bb6fadcd2f3c598598df9ec6755368d89587 | Python | 7,530 | 253 | # src/zndraw_joblib/events.py
"""Socket.IO event models for real-time notifications.
All models are frozen for hashability, enabling set-based deduplication
of emissions via the Emission NamedTuple.
"""
from __future__ import annotations
import json
import uuid as _uuid
from datetime import datetime # noqa: TC003
f... |
2d00d587214a312e47e737a8b4fb0aec2728aaaca4efa8f17aeae57a33857729 | Python | 7,531 | 209 | from typing import Dict, List, Optional, Tuple
from pathlib import Path
import torch
from torch import nn
from torch.utils.data import DataLoader, RandomSampler, BatchSampler
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts, StepLR
from pytorch_lightning import LightningModule
from torchmetrics import... |
8c01f269c25a6f8e61916524321aca2ecf5c1b572f6568cc71eb18f89a7ce28d | Python | 7,532 | 229 | import inspect
import time
from statistics import mean, stdev
from CybORG import CybORG, CYBORG_VERSION
from CybORG.Agents import SleepAgent, EnterpriseGreenAgent, FiniteStateRedAgent
from CybORG.Simulator.Scenarios import EnterpriseScenarioGenerator
from datetime import datetime
import json
import sys
import os
... |
8f2ac333c7a50caf7c8f71e352d76241b0202c360ff595d65b3294c6342094d3 | Python | 7,533 | 184 | import numpy as np
import torch
from torch.utils.data import Dataset
import pandas as pd
from deepchem.feat.smiles_tokenizer import SmilesTokenizer
class DataSetSMILES(Dataset):
"""
A custom PyTorch Dataset for handling SMILES data.
This dataset is designed to read multiple CSV files containing SMILES da... |
46091474b63ff40d5ad617d8de35d19c3a8f2c35109eb156366aafd30aff814a | Python | 7,534 | 239 | import data_utils as du
import os
import sys
import tensorflow as tf
from tensorflow.keras.optimizers import Adam, SGD
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten,\
Conv2D, MaxPoolin... |
14fb2bf23d7dcd7a0939db305b1cd0419b1a437876488a3601edaae9003fddcd | Python | 7,537 | 224 | import json
import os
import tempfile
from collections.abc import Sized
from functools import partial
from io import StringIO
from pathlib import Path
import pytest
from schema_salad.utils import yaml_no_ts
import cwltool.pack
import cwltool.workflow
from cwltool.context import LoadingContext
from cwltool.load_tool i... |
93eaf6c6874100cf04fc758f9a04f4c3b851462b11ffa49443a263557fdba3b6 | Python | 7,539 | 183 | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def declust_marker_boxplot(sc_adata, sc_marker_gene, gene_index, celltype_col='celltype_major'):
"""
Create a boxplot showing the expression of a specific marker gene across different cell types.
Parameters:
sc_adata (anndat... |
2848cbe2c7e634b3b0c5a28869651c1c726080226cb0b3341ec452438efe7420 | Python | 7,540 | 219 | from dataset.models import Dataset
from django.db.models import OuterRef, Subquery
from dataset.serializers import DatasetWithOwnerInfoSerializer
from benchmarkmodel.serializers import BenchmarkListofModelsSerializer
from benchmarkdataset.serializers import BenchmarkListofDatasetsSerializer
from result.serializers impo... |
4965ccb4a4504aa4d7246b2ad66ffeacd2626415c86a261dc1c65ffd8ae1d40d | Python | 7,541 | 202 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional, Tuple, Type
import torch
from torch import nn
from sam2.modeling.position_encoding import P... |
f24627730d70a5947eadf752a0a3d3dbafdba7ba1baa9078b95793e91e8bdf9a | Python | 7,542 | 212 | import argparse
import os
import shutil
import sys
sys.path.append(".")
import torch
from tqdm import tqdm
torch.multiprocessing.set_sharing_strategy("file_system")
import torch.utils.tensorboard
from torch.nn.utils import clip_grad_norm_
from torch_geometric.loader import DataLoader
from models.model import MolDif... |
dc8286e72ec875ef41341a7e2d6d252bf8017db99a4b453da8b760d61f8ee387 | Python | 7,547 | 265 | from __future__ import annotations
import csv
from glob import glob
from io import StringIO
import logging
import os
import os.path as op
from os.path import dirname
from os.path import join as pjoin
from pathlib import Path
import re
from unittest.mock import patch
import pytest
from heudiconv.cli.run import main a... |
1ca5a2e287d705c35ebe8aefaa48c3c9f0b933d205569a00dc037652031f78ab | Python | 7,552 | 200 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 3 10:34:51 2023
@author: schwab
"""
from pathlib import Path
from typing import Optional
import torch
from torch.utils.data import DataLoader
from typer import Option
import os
import sys
from ..data.handlers.particle_image_preprocessor import \... |
0992cef63df1af2b970ed481502fe274ad7f24da4524f73a3bbf6e094cb86e33 | Python | 7,559 | 174 | import SimpleITK as sitk
from natsort import natsorted
import numpy as np
from pathlib import Path
import pandas as pd
from collections import defaultdict
from shutil import copyfile
import os
from os.path import join
from tqdm import tqdm
import gc
import multiprocessing as mp
from nnunet_mednext.dataset_conversion.ut... |
f580b1f66df0196957ca2c2cce79e4a92940f5e9262b2f1de2daaf1f004ba17e | Python | 7,562 | 219 | import os
from pdb import set_trace as bp
import matplotlib.pyplot as plt
from matplotlib.pyplot import scatter
import numpy as np
from matplotlib.lines import Line2D
colors = ["#e06666", "#189AD3"]
# Plotting font size to 22
plt.rcParams.update({"font.size": 22})
PRJDIR = "/mnt/d/Experiments/Experiment2-Blink_Tic/... |
d79ca8a7be801406be21b051ec4cc9075654de2356cf230ee79af9c40a74e00d | Python | 7,564 | 192 | # The following code contains work of the United States Government and is not subject to domestic copyright protection under 17 USC § 105.
# Additionally, we waive copyright and related rights in the utilized code worldwide through the CC0 1.0 Universal public domain dedication.
"""
Handling of privilege escalation ac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.