sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
401e5ffcca79d89ef14061e6812d2522af090a556298cfdb5d3315e013c576de | Python | 2,598 | 79 | # -*- coding: utf-8 -*-
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
forward = """
CREATE FUNCTION refresh_skeleton_summary_table() RETURNS void
LANGUAGE plpgsql AS
$$
BEGIN
-- Remove all entries
TRUNCATE catmaid_skeleton_summa... |
87d6c465fd22c7d2974e386529dc3be33e676f7560c1f8ca7cab075423e0b9da | Python | 2,598 | 58 | import numpy as np
import matplotlib.pyplot as plt
from grid_cell.grid_cell_processor import Grid_Cell_Processor, Speed_Processor
from matplotlib.ticker import FuncFormatter
import os
from global_setting import *
#################### Hyperparameters ####################
# dataset_name = ['r1m1', 'r1m2', 'r1m3', 'r2m1'... |
b3f8b35292689a07d27b0c0f7fe44e586dcbdb99663f0510d439671889b129a6 | Python | 2,598 | 77 | # Copyright (c) OpenMMLab. All rights reserved.
from unittest import TestCase
import numpy as np
import pytest
import torch
from mmengine.structures import PixelData
from mmseg.structures import SegDataSample
def _equal(a, b):
if isinstance(a, (torch.Tensor, np.ndarray)):
return (a == b).all()
else:... |
0ee16191b1f6fae6311e0c3f921a1c77ab8f96c13623cf78cf0deb122a66c586 | Python | 2,600 | 90 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
###
# File: /home/richard/projects/pepland/data/eval/statistics.py
# Project: /home/richard/projects/pepland/data/eval
# Created Date: Thursday, July 18th 2024, 11:32:56 am
# Author: Ruochi Zhang
# Email: zrc720@gmail.com
# -----
# Last Modified: Thu Jul 18 2024
# Modified ... |
a5439d63c545e669a1bd99a1597af5f4de05febab5c0972f30b2ca0c380e6363 | Python | 2,600 | 46 | import os
import pandas as pd
def save_scores_to_csv(args, test_losses, test_scores, val_losses, val_scores, best_threshold):
info ={
'test_seg_mean_f1': test_scores['seg_mean_f1'],
'test_seg_mIoU': test_scores['seg_miou'],
'test_cone_mean_f1': test_scores['cone_mean_f1'],
'test_co... |
cf22b060434bfd410caadf2c3e34afea2f2cae06e2f45f8d9b4de35d2467d1a1 | Python | 2,600 | 87 | import os
import yaml
import argparse
import pandas as pd
def get_statistics(data_df: pd.DataFrame) -> dict:
"""Computes statistics about the data. This statistics are uploaded
to the Medperf platform under the data owner's approval. Include
every statistic you consider useful for determining the nature o... |
000d68e8665ceb26dd351924f973c05b2d18e9718c45fa1c8b42a12b16804eb1 | Python | 2,602 | 65 | from collections.abc import Sequence
from dnaio import SequenceRecord
from cutadapt.adapters import (
BackAdapter,
AnywhereAdapter,
BackAdapterStatistics,
Adapter,
)
from cutadapt.modifiers import AdapterCutter, ModificationInfo
def test_statistics() -> None:
read = SequenceRecord("name", "AAAACC... |
74ee8e120560e3d2b7d046209b801c2bb25e853fa7d6162c17e9110c8b6265a0 | Python | 2,602 | 102 | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import numpy as np
import torch
from .base_layers import Dense
from ccdvaeplus.pl_modules.embeddings import MAX_ATOMIC_NUM
... |
be9be6eb82a13f085c76bc3a554f7d7446836679c534fe94d2ce8a45fc2ecd68 | Python | 2,602 | 79 | import os
from collections.abc import MutableSequence
from datetime import datetime
from pathlib import Path
from cwl_utils.types import CWLDirectoryType, CWLFileType
from pytest_httpserver import HTTPServer
from cwltool.pathmapper import PathMapper
def test_http_path_mapping(tmp_path: Path) -> None:
input_file... |
c2a19bb226254055b84718eea5b8b1b5bbce2aa41714a552d7bb9d3faa16eea7 | Python | 2,605 | 88 | '''
Created on 29 Nov 2022
@author: Francois STÜDER
'''
from setuptools import setup, find_packages
from SysISTD import __version__
setup(
name='SysISTD',
version=__version__,
description='Demultiplexer for SysFate Illumina spatial transcriptomic',
license='GNU Affero General Public License v3.... |
147b6d654f5d014dc1dd5203cf3ed00e9a640c98ac86951e22bcddf86ce12369 | Python | 2,606 | 104 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 29 10:23:58 2024
@author: max
"""
import numpy as np
from scipy.io import loadmat
from nilearn import plotting
import matplotlib.pyplot as plt
p_thresh = 0.001
data = loadmat('../results/spatial_plots/fig4_matrices_rest_movie_coords.mat')
varx_R... |
8ed5bf528f12eeb30fbf3b475c00d639d7125bfa4adbbda576a1ee5f3d26ee15 | Python | 2,608 | 72 | """Unit tests for src/datahandlers/chembl.py (ChemblRDF)."""
from pathlib import Path
import pyoxigraph
import pytest
from src.datahandlers.chembl import ChemblRDF
from src.prefixes import CHEMBLCOMPOUND
from tests.datahandlers.conftest import RDF_NS, RDFS_NS, lit, make_graph_from_store, nn, quad
_CHEMBL_MOL_NS = "... |
5c515685b7e0fd7a05c1e55787921c6321d5048eee6f6374fdba47127833cdda | Python | 2,611 | 80 | import logging
import socket
from pathlib import Path
from random import randint
logger = logging.getLogger(__name__)
def default_root_path() -> str:
"""Starting directory for the GUI's directory pickers before a root folder is chosen.
Returns
-------
str
The user's home directory.
"""
... |
7121e6c86778d5cb7ff9defbd51545145b2585924102d58e790c16e91172721e | Python | 2,611 | 83 | """Finetune utilities for SO3LR models."""
import jax
import jraph
import numpy as np
import jax.numpy as jnp
import time
import pprint
import pathlib
import logging
from typing import Dict, List, Tuple, Union, Optional, Any
from tqdm import tqdm
import yaml
from ase.io import write
from mlff.utils import jraph_utils,... |
95cf88fbe568d864856b0d417bdb196bb17d274ff8e39b431bc3c70b1b811403 | Python | 2,611 | 65 | from CybORG.Shared import Observation
from CybORG.Simulator.Actions.ConcreteActions.LocalAction import LocalAction
from CybORG.Simulator.State import State
class RedSessionCheck(LocalAction):
"""Red Agents check they have access to a primary session"""
def execute(self, state: State) -> Observation:
... |
434ca5690908d9180da4b50e104314ed0f838b9110546d9a24a52d783bfc6e28 | Python | 2,613 | 80 | import typer
import medperf.config as config
from medperf.decorators import clean_except
from medperf.commands.cc.dataset_configure_for_cc import DatasetConfigureForCC
from medperf.commands.cc.model_configure_for_cc import ModelConfigureForCC
from medperf.commands.cc.dataset_update_cc_policy import DatasetUpdateCCPoli... |
f35f8369222b6854e8b95489ffa1f577c5388c3b80675ab645b3927499450f61 | Python | 2,613 | 87 | import itertools
import warnings
from typing import Type
import numpy as np
import pytest
import scipy.sparse
import xgboost as xgb
from xgboost import testing as tm
@pytest.mark.filterwarnings("error")
@pytest.mark.parametrize(
"DMatrixT,CSR",
[
(m, n)
for m, n in itertools.product(
... |
24699360a6f8f32409359b6775fe2d3a4a0fb9aaa60cc8129ea1adfd866a3542 | Python | 2,614 | 41 | import argparse
from synmi.models import PredictionModel
from synmi.generators import NiftiPredictionGenerator
from synmi.sinks import NiftiOutputSink
if __name__ == '__main__':
parser = argparse.ArgumentParser()
main = parser.add_argument_group('main')
main.add_argument('--input-file', required=True, nar... |
485dde758e7434a90792cb5edaaf6a30e59610858adb201b5ab325c76d1d7d57 | Python | 2,614 | 92 | from rest_framework import status
from medperf.tests import MedPerfTest
from parameterized import parameterized, parameterized_class
class MlCubeTest(MedPerfTest):
def generic_setup(self):
# setup users
mlcube_owner = "mlcube_owner"
data_owner = "data_owner"
other_user = "other_u... |
56770fcd8ceff6b1e18fd3d1af7b04c51d8ea5188154453482e54dd8a64e9f8b | Python | 2,614 | 82 | import os
import argparse
import sys
import re
import pandas as pd
import yaml
def create_csv(predictions, labels):
"""A function that creates a ./data.csv file from input folders."""
# labels
labels_dict = {}
pattern = r".*(\d{5}-\d{3})-seg\.nii\.gz$"
for file in os.listdir(labels):
reg ... |
9ee47396d9d07cac4d3df9f3b8cd64d7e6058f67eb75edb9a05fe67b96ca898d | Python | 2,616 | 75 | # -*- coding: utf-8 -*-
import cv2
import numpy as np
import pandas as pd
import time
import modules.functions as functions
import modules.segmentation as segmentation
from pathlib import Path
folder = Path("data_segmentation/cell_line")
folder_out = Path("output")
functions.create_folder(folder_out)... |
2e938e818de710725e885d2c878d9590464c8af830f7d21bb33d7a65b144b9fc | Python | 2,617 | 67 | import torch
import warnings
from Bio import BiopythonWarning
from Bio.PDB import PDBIO
from Bio.PDB.StructureBuilder import StructureBuilder
from .constants import AA, restype_to_heavyatom_names
def save_pdb(data, path=None):
def _mask_select(v, mask):
if isinstance(v, str):
return ''.join(... |
3d75e4ba5020011a28b8ef84501bcc455dfbe24a0752e5eb8cbcbdb095c43101 | Python | 2,617 | 75 | import numpy as np
import igraph as ig
import json
import random
from itertools import chain, combinations
def generate_png(dot_filename, png_filename=None, prog="neato"):
if png_filename is None:
png_filename = dot_filename.replace(".dot", ".png")
os.system("%s.exe -T png %s > %s" % (prog, dot_filenam... |
68499676bcf17e924501eae653bcf5d4f077a39921d686e038f63e1ac70fac74 | Python | 2,617 | 81 | """Script to make pypesto ready for compiling + time comparison of compile"""
import amici
import time
import pandas as pd
import libsbml
sbml_file_dir = "models/manual_implementations/sbml_export"
output_dir = "results/PyPESTO_comparison/"
model_name = "glycolysis_feastfamine_pulse1_pypesto"
sbml_file = f"{sbml_fil... |
8be49ebc8c1d049826fcace2c6d2ff699c54beb3be9ee91eaae42e22d34e3dd5 | Python | 2,617 | 83 | # Modified from https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/dist_utils.py # noqa: E501
import functools
import os
import subprocess
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def init_dist(launcher, backend='nccl', **kwargs):
if mp.get_start_method(allow_none=... |
10121ebfb1548a808eb0f972c8ba43d75ca817f052e21a6c704666de8f604d61 | Python | 2,618 | 68 | import ase
import numpy as np
import vesin
from ase.neighborlist import natural_cutoffs
T_CONNECTIVITY = list[tuple[int, int, int | float | None]]
def add_connectivity(atoms: ase.Atoms, scale: float = 1.2) -> None:
"""Add connectivity information to an ASE Atoms object.
This function determines atomic conne... |
17ca8ba738b8d6ecb07fc09dfac6092a50304b4706e583111c2e236efd2f5508 | Python | 2,618 | 87 | # Copyright (c) OpenMMLab. All rights reserved.
import os
import tempfile
import torch
from mmengine.registry import init_default_scope
from mmseg.registry import MODELS
init_default_scope('mmseg')
def test_pidnet_backbone():
# Test PIDNet Standard Forward
norm_cfg = dict(type='BN', requires_grad=True)
... |
51d3819cfc5f9376a48940307094fb3025a89cd7dfe4de9e5a87bfb7899cebad | Python | 2,618 | 76 | # MagellanMapper unit testing
# Author: David Young, 2018, 2020
"""Unit testing for the MagellanMapper package.
"""
import os
import unittest
from magmap.cv import stack_detect
from magmap.io import cli, importer, np_io
from magmap.settings import config
TEST_IMG_CZI = "test.czi"
TEST_IMG_BASE = "sample_region"
TEST... |
cac7d6f9b60ea4b42c0f44897fcfd3395862b199775314fb6114af2bb8bc5223 | Python | 2,619 | 80 | # MLCube Entrypoint
#
# This script shows how you can bridge your app with an MLCube interface.
# MLCubes expect the entrypoint to behave like a CLI, where tasks are
# commands, and input/output parameters and command-line arguments.
# You can provide that interface to MLCube in any way you prefer.
# Here, we show a wa... |
051604fa5238801e3372d122ced6a765c9e02279e0476cd5af73e376a0e90645 | Python | 2,620 | 77 | import numpy as np
import torch
from e3nn import o3
from mace.modules import interaction_classes
from simgen.utils import get_mace_config
def test_get_mace_config(mace_model, z_table):
atomic_numbers = z_table.zs
config = get_mace_config(mace_model)
expected_config = dict(
r_max=4.0,
num_... |
3e0b563e36bb44a9bbd53d4186b2216badeddf3e715c4592ba1540eab4bb48e3 | Python | 2,620 | 94 | """Tests for metric objects training and evaluation."""
import pytest
import numpy as np
from keras import metrics
from keras import backend as K
from keras.layers import Dense
from keras.models import Sequential
if K.backend() == 'cntk':
pytestmark = pytest.mark.skip
METRICS = [
metrics.Accuracy,
metr... |
8ba53a3346c744e7ae706eedef08ab24be0574ec605844d087108bcf813bbbec | Python | 2,621 | 90 | from Utils.dataloader_GRAZPEDWRI import *
from Utils.config import *
from Utils.models import *
from Utils.TrainModel import *
from multiprocessing import Process
def task(lr, data_partition:float=None, run_idx:int=None, backbone: str='eff0'):
_cuda = 'cuda:0'
_image_size = get_image_size_for_backbone(backbone=backb... |
b107592348687b50ef8d9e81f3a515e0481fcdc2c99689131db5cf4a47d80fe5 | Python | 2,621 | 81 | """
Collection of examples for using sklearn interface
==================================================
For an introduction to XGBoost's scikit-learn estimator interface, see
:doc:`/python/sklearn_estimator`.
Created on 1 Apr 2015
@author: Jamie Hall
"""
import pickle
import numpy as np
from sklearn.datasets imp... |
f348d34707e47ff5642608a70b1e2f12cdf4fb37b363dc8d773d68acea879dec | Python | 2,621 | 80 | # MLCube Entrypoint
#
# This script shows how you can bridge your app with an MLCube interface.
# MLCubes expect the entrypoint to behave like a CLI, where tasks are
# commands, and input/output parameters and command-line arguments.
# You can provide that interface to MLCube in any way you prefer.
# Here, we show a wa... |
46e205ccbf5e19faefd6363bca7938f71e03de2a4f5bb48971ebd70a33df5e1d | Python | 2,622 | 75 | import argparse
import os
import shutil
# select 15 images from GID dataset
img_list = [
'GF2_PMS1__L1A0000647767-MSS1.tif', 'GF2_PMS1__L1A0001064454-MSS1.tif',
'GF2_PMS1__L1A0001348919-MSS1.tif', 'GF2_PMS1__L1A0001680851-MSS1.tif',
'GF2_PMS1__L1A0001680853-MSS1.tif', 'GF2_PMS1__L1A0001680857-MSS1.tif',
... |
670cdf56157386957ae30eba3d0f076412efa08a0e27e49a92c92e578ef890b3 | Python | 2,622 | 81 | # dataset settings
dataset_type = 'PascalVOCDataset'
data_root = 'data/VOCdevkit/VOC2012'
crop_size = (512, 512)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations'),
dict(
type='RandomResize',
scale=(2048, 512),
ratio_range=(0.5, 2.0),
keep_ratio=T... |
bac3d6f4dc774f4faa261f6c1848dbe04dc5854a5dae8ab139164381f37e8f7a | Python | 2,622 | 69 | import torch
import pandas as pd
from sklearn.decomposition import PCA
import joblib
import numpy as np
import os
from params import langs, nanfiller
def phoneme_representations(state_dict_path, langs, layer='phone_linear', pca=None, pca_o=None, normalize=True):
state_dict = torch.load(state_dict_path,map_locati... |
23da834dacecefeace533364db34bda6b7743de762ce527128cec28adb20cf43 | Python | 2,623 | 79 | from __future__ import absolute_import, division, print_function
from os.path import join as pjoin
# Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z"
_version_major = 0
_version_minor = 1
_version_micro = '' # use '' for first of series, number for 1 and above
_version_extra = 'dev'
# _vers... |
ad0b466457356a6efd5ace06f711f6b337a16b4a317820cf5b9ba0eb0127fe9c | Python | 2,623 | 79 | import pytest
import numpy as np
from numpy.testing import assert_allclose
from keras import backend as K
from keras import constraints
def get_test_values():
return [0.1, 0.5, 3, 8, 1e-7]
def get_example_array():
np.random.seed(3537)
example_array = np.random.random((100, 100)) * 100. - 50.
exampl... |
ddd30b36404959138fb7ce51dfe5cdf548f3517957a9ebc83566f11e48afd904 | Python | 2,623 | 63 | import numpy as np
import os
import hickle as hkl
from sklearn.decomposition import PCA
from grid_cell.grid_cell_processor import Speed_Processor
from grid_cell.gkr import GKR_Fitter
from global_setting import DATAROOT
# Combined data loading and processing function
def load_and_process_data(dataset_name, preprocessed... |
05ff806635d8ae0863eaadd583d77eb99b690b1f75a897b6dc1a7e68b07f6288 | Python | 2,624 | 64 | from ast import parse
import os
import psutil
import time
import random
import numpy as np
import scanpy as sc
import torch
from torch.utils.data import DataLoader
import argparse
from train import train
import warnings
warnings.filterwarnings("ignore")
if __name__ == '__main__':
parser = argparse.Argu... |
09fa569c92f6349ce651dcdf74eaa32e3daf5bdc7131655e3c21814bb07295ad | Python | 2,626 | 89 | import pytest
from nearl.io.trajloader import TrajectoryLoader
DUMMY_TRAJS = [("a.nc", "a.pdb"), ("b.nc", "b.pdb")]
class _DummyTraj:
"""Stand-in trajtype so loader tests don't need real trajectory files on disk."""
def __init__(self, traj_file, top_file, **kwargs):
self.traj_file = traj_file
... |
e2aa6184f580bf3c2624914a0df717f17c09e7ffc41862c26008b038086b1e23 | Python | 2,626 | 79 | # Start your first Nearl featurization
######################################
from collections import OrderedDict
import nearl
import nearl.features
import nearl.featurizer
import nearl.io
if __name__ == "__main__":
# Get the example data
EXAMPLE_DATA = nearl.get_example_data("/tmp/nearl_test")
# Initia... |
fffb24c4a724bb470a6d77446da7f3f42569685bf94551747d9651f9d6014f89 | Python | 2,626 | 91 | from Utils.dataloader_COVID import *
from Utils.config import *
from Utils.models import *
from Utils.TrainModel import *
from multiprocessing import Process
def task(lr, data_partition:float=None, run_idx:int=None, backbone: str='res152'):
_cuda = 'cuda:0'
_image_size = 224
_lr = lr
_info = "ImageNet_"+str(lr)+f... |
06c9bc559502a383c92ff8028649b3ddf2d76964b1b46dbf3c667e67ce7f9bc7 | Python | 2,627 | 96 | from kgx.graph.nx_graph import NxGraph
from kgx.source import GraphSource
from kgx.transformer import Transformer
def test_read_graph1():
"""
Read from an NxGraph using GraphSource.
"""
graph = NxGraph()
graph.add_node("A", **{"id": "A", "name": "node A"})
graph.add_node("B", **{"id": "B", "na... |
cc0717aaa530d6cf4435c24615eed8738acd4193178d536423092cedd1a26fc0 | Python | 2,627 | 74 | """Detection utilities."""
from typing import Optional
import numpy as np
from podm.bounding_box import BoundingBox
from soccertrack.utils.camera import Camera
class CandidateDetection(BoundingBox):
def __init__(
self,
camera: Camera,
frame_idx: Optional[int] = None,
detection_id... |
ee1ccd8d49658736189dc11492e73561a1b576419e8b4ffdd2eb05f97533883d | Python | 2,627 | 89 | import h5py
import numpy as np
class HDF5Attr:
def __init__(self, key=None):
self.name = key
def __set_name__(self, owner, name):
if not self.name:
self.name = name
self.private_name = "_" + self.name
def __get__(self, instance, owner):
try:
retur... |
b0689d5bd4b8ffd29f664b905f4d661d4869c85be45ec035f030eb8d7e1ce364 | Python | 2,629 | 59 | import hickle as hkl
import os
import numpy as np
import matplotlib.pyplot as plt
from grid_cell.ploter import error_bar_plot
from global_setting import *
# Assuming DATAROOT is defined and points to your data directory
tm_name = ['ori_tuning', 'place_cell'] # You can add more if needed
# model_names = ['gpr', 'kerne... |
c7450b1f8295b8e0701d85eb99be3d35a70c2c6b03a80e0109379381e58a3e58 | Python | 2,629 | 90 | from Utils.dataloader_COVID import *
from Utils.config import *
from Utils.models import *
from Utils.TrainModel import *
from multiprocessing import Process
def task(lr, data_partition:float=None, run_idx:int=None, backbone: str='res152'):
_cuda = 'cuda:0'
_image_size = 224
_lr = lr
_info = "SCRATCH_"+str(lr)+f"... |
50d6e28312e57fb49b0eb258e9ed1666f44fac4a39604feb49d6cd19a5a7b35c | Python | 2,630 | 102 | import argparse
import yaml
import pandas as pd
from sklearn.metrics import roc_auc_score, f1_score
class AUC:
@staticmethod
def run(labels, preds):
results = roc_auc_score(labels, preds, average=None)
return results.tolist()
class F1:
@staticmethod
def run(labels, preds):
pr... |
84a35291779896cde515e11fe240fd3c953405bc37fc51d77defb3034d14106d | Python | 2,630 | 91 | from transformers import TrainingArguments
from trl import SFTTrainer, DataCollatorForCompletionOnlyLM
from unsloth import FastLanguageModel
from datasets import load_dataset
import pandas as pd
import argparse
import torch
def preprocess_logits_for_metrics(logits, labels):
with torch.no_grad():
logits = logits.cpu... |
aa2487b96e417c44ecb45e7fc24eec396b423042c8b3d301ee7904b63aa234f2 | Python | 2,630 | 69 | import pytest
from guppy.orchestration import select_artifact_windows
@pytest.fixture
def preprocessed_run_folder(tmp_path):
"""A run folder holding the Step-3 outputs the marking page reads."""
run_folder = tmp_path / "session_output_1"
run_folder.mkdir()
(run_folder / "cntrl_sig_fit_dms.hdf5").touc... |
c354a6411bb98d0bb8ae8979ed34d9732fee6abec84e8d083358eef407e845fb | Python | 2,630 | 67 | # SPDX-License-Identifier: MIT
import cv2
import onnxruntime as ort
import argparse
import numpy as np
from dependencies.box_utils import predict
# ------------------------------------------------------------------------------------------------------------------------------------------------
# Face detection using Ul... |
761b967ca75fd8189c104cfea20f88cfc5e46a1b0970e399af7aea2c41be23c4 | Python | 2,631 | 91 | import pytest
from medperf.exceptions import CleanExit
from medperf.commands.mlcube.revoke_user_access import RevokeUserAccess
from medperf.tests.mocks.encrypted_key import TestEncryptedKey
PATCH_REVOKEUSERACCESS = "medperf.commands.mlcube.revoke_user_access.{}"
KEY_ID = 1
@pytest.fixture
def revokeuseraccess(mocker... |
d4d421e9c9131ade8b83bdbd19e74ff55d89d9b76db8f1b2eb8544ce71e92d23 | Python | 2,631 | 51 | # 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... |
6c63c9e64fbedc1a89cd8734c762a038b3331b0bd59552c4a5161725d6cf08cd | Python | 2,636 | 70 | import numpy as np
import matplotlib.pyplot as plt
import os
from grid_cell.grid_cell_processor import Grid_Cell_Processor
from sklearn.decomposition import PCA
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import ConstantKernel, RBF, WhiteKernel
from disentangle.mo... |
117e725cf8f848680a7e97a9f932d323df1adf215a8335184419330e82c4368e | Python | 2,638 | 70 | import os, sys
import scipy
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import scanpy as sc
import scanpy.external as sce
from sklearn.linear_model import Ridge
def diffusionMap(h5ad_file, n_pcs, meta_col, root_ident, root_idx = 0, use_rep = 'X_pca', out_dir = './'):
# Rea... |
ba01d9646240851228ae9a58f9ff53606c5de4111eddfd00deb7375ccad16db3 | Python | 2,639 | 88 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 14:27:23 2023
@author: ingvieb
"""
from glob import glob
import shutil
import os
import datetime
import DeMBA_functions as dfs
path = r"C:\Users\ingvieb\elastix_testing\ordinal_ids//"
fixedAge = "P21"
movingAge = "P28"
# give the paths of the volumes to be used as f... |
185317440c90fba9ab544393aad42c2c4ff4857e8c115754c8ab7595648a6d27 | Python | 2,640 | 82 | # -*- coding: utf-8 -*-
import json
import logging
from typing import Optional, Union
from django.http import HttpRequest, HttpResponseRedirect, JsonResponse
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
from catmaid.models import Message, ChangeRequ... |
d5f550d53464bda4da48237eca39671d78f0152364663aa4cff11222cc3f2a71 | Python | 2,640 | 78 |
import snapatac2 as snap
import pandas as pd
import os
import argparse
import scanpy as sc
# Input files
# fragment_file = '/mnt/HDD1/Users/FFPE_S1.fragments.sort.bed.gz'
# bin_size_set = 5000
# n_features_set = 250000
# path_save = '/mnt/HDD1/Users/FFPE'
# python analysis.py /path/to/fragment_file /path/to/output_h5... |
63f7eb3e0ad94248f5efd1874adabdecccef645ea3a5cdbe8aa9deed70fc6942 | Python | 2,641 | 95 | from abc import ABC, abstractmethod
from contextlib import contextmanager
class UI(ABC):
@abstractmethod
def print(self, msg: str = ""):
"""Display a message to the interface. If on interactive session overrides
previous message
"""
@abstractmethod
def print_error(self, msg: s... |
0d77a8f2cf66c03a1ed3a41d4fe17cb31c9ce99df8e0e86a5e68df95b41585bb | Python | 2,642 | 66 | """Static audit: no long-polling handler (one that uses SessionMakerDep directly)
may transitively depend on a yield-based SessionDep. Because yielded FastAPI
deps are kept alive for the full request, holding a SessionDep while a handler
tries to open its own session deadlocks under SQLite serialization.
The "long-pol... |
a1e9cff0120774365560658f3553fbd13a130232525e519c47303b365a347be7 | Python | 2,643 | 73 | import unittest
import tempfile
import os
import numpy as np
import six
import caffe
from test_net import simple_net_file
class TestSolver(unittest.TestCase):
def setUp(self):
self.num_output = 13
net_f = simple_net_file(self.num_output)
f = tempfile.NamedTemporaryFile(mode='w+', delete=F... |
c6a89620f39f53375f10b95d91096a9ecadeaf531b975f5f6d7bb00d7005328c | Python | 2,643 | 76 | #!/usr/bin/python
import logging
import os
import shutil
import sys
from isorefiner.common import get_version, run_command
logger = logging.getLogger(__name__)
def main(args):
try:
# Set variables
raw_reads_files = [os.path.abspath(_) for _ in args.reads]
out_prefix = os.path.abs... |
d20e158286dd127cff095bb8167052f5eab2f1a2e079872394eb17a9d693075b | Python | 2,644 | 88 | # model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
data_preprocessor = dict(
type='SegDataPreProcessor',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
bgr_to_rgb=True,
pad_val=0,
seg_pad_val=255)
model = dict(
type='EncoderDecoder',
data_preprocessor=data_... |
136a69d95a33a562abf8709b861b6188f20a1fd1d7e0d374c49f5583eedc4ad3 | Python | 2,645 | 46 | # Generated by Django 3.2.20 on 2023-08-03 19:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('mlcube', '0001_initial'),
migrations.swappable_dependency(sett... |
20b2d0dde79644062c716be78da0f94e5dfc9a9433744ba356b24fd61029394f | Python | 2,647 | 73 |
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_selection import SelectKBest, f_classif
# ---- Placeholder CAOA Implementation ---- #
class CAOAFeatureSelector(BaseEstimator, TransformerMixin):
"""
Crossover-Boosted Archimedes Optimization Algorithm (CAOA)
... |
2ba82881855f47511a1c40221dfa5174e7e9f9512c575dddda7b661346259ce3 | Python | 2,647 | 96 | """Room share-link management."""
import secrets
from datetime import UTC, datetime
from uuid import UUID
from fastapi import APIRouter, status
from sqlmodel import col, select
from zndraw.dependencies import (
AccessManageDep,
CurrentUserDep,
SessionDep,
)
from zndraw.exceptions import (
Forbidden,
... |
d80678c377e26003f39eb4ab8ec413d07f8c584f9bbe3eef06620daeb056664f | Python | 2,648 | 103 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 23 13:37:46 2023
@author: george
"""
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui, QtWidgets
import cv2
from matplotlib import pyplot as plt
def update_plot():
# Generate random scatter plot data
num_poi... |
05a24d6657504e1add40aa22884835320c9050db1a070157d3ef9391cfb101f2 | Python | 2,649 | 90 | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import os
import random
import numpy as np
import pytest
import torch
from ase.io import read
from ocpmodels.common.registry import registr... |
82066b34863c12ba005be69c0725e32cadd9ce5350072f68e8a4461debed8bf7 | Python | 2,649 | 76 | import logging
import pathlib
import ase
import networkx as nx
import numpy as np
from zndraw.type_defs import CameraData
from znframe.frame import get_radius
from simgen.hydrogenation import get_edge_array_from_atoms
from simgen_zndraw import DefaultGenerationParams
def get_anchor_point_positions(
atoms: ase.A... |
ae32b721dfe751ed59c3916f6b60294613ba85c401a458c0346ca70989fb32cf | Python | 2,649 | 78 | # Generated by Django 4.2.23 on 2025-10-03 08:45
import catmaid.fields
from django.conf import settings
import django.contrib.postgres.functions
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... |
3a6920161b7b74d517c5901385e3c09c27c1e6b401de8bde8e47224b33a1e5a4 | Python | 2,650 | 68 | # please run test_num_time_point_gp first to get the gp data
import numpy as np
import hickle as hkl
from grid_cell.manifold_fitter import Avg_Fitter
from grid_cell.ploter import error_bar_plot
from grid_cell.tuning import ppdata_to_avg_ratemap
import matplotlib.pyplot as plt
import os
from global_setting import *
###... |
1decf153aeebb3744802e4c91cff8014b349d16d853c498e1488ae9201edcecc | Python | 2,651 | 98 | # %%
import pandas as pd
data = {
'index': [
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
16, 17, 18, 19, 20,
21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34
],
'sub': [
'0001', '0004', '0004', '0004', '0005',
'0007', '0014', '001... |
9587e3834d9bdb0a8f6fc079fb35449d45efe8d9e90a2974d2c9982680b4f0df | Python | 2,651 | 91 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 14 14:55:40 2023
@author: george
"""
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
from tqdm import tqdm
import os, glob
from scipy.signal import find_peaks, peak_widths
def detectIntensityPeaks(df, kernel_size = 100)... |
4257bebf3a81b3d08fbb0f8261101aacc88b28e808c325f43b235d42a8b8bbb2 | Python | 2,653 | 105 | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from typing import Optional
import numpy as np
import torch
from ocpmodels.common import gp_utils
from .base_layers import Dense
class A... |
ce24840c0c6d239ad17ab0a5f312ce1cd8eccf3e8389a83c1515d2d2b9b167c1 | Python | 2,653 | 74 | # usage: evaluaton_script.py [-h] [--gold_path gold_path]
# [--predictions_path PREDICTIONS_PATH] [--language LANGUAGE]
# optional arguments:
# -h, --help: show this help message and exit
# --gold_path: Path to umsab dataset
# --predictions_path: Path to predictions file
# --language... |
fa593ec347ec7997274e50a2177c8a72e5c1c5ce1a24d513098b7cc5f79a00ff | Python | 2,653 | 96 | """Tests for Camera model validation."""
import pytest
from pydantic import ValidationError
from zndraw.geometries.camera import Camera, CameraType
def test_defaults_are_valid():
"""Default Camera() creates a valid instance."""
cam = Camera()
assert cam.fov == 50.0
assert cam.near == 0.1
assert ... |
442cd254d9396c174b130bb616ea07b90f5023a3a7cdc4ae4e67e1ba7c605255 | Python | 2,654 | 75 | import cv2
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
# Load the nii volume
nii_files = [
"DeMBA_P7_brain.nii",
"DeMBA_P14_brain.nii",
"DeMBA_P21_brain.nii",
"DeMBA_P28_brain.nii.gz",
]
import numpy as np
def pad_to_square(arr):
"""
Pads a given array to be squar... |
c23d10d18417e465bb574814ad828e14eb6937f48a0a044257f8b77eda8ffda6 | Python | 2,654 | 92 | from Utils.dataloader_GRAZPEDWRI import *
from Utils.config import *
from Utils.models import *
from Utils.TrainModel import *
from multiprocessing import Process
def task(lr, data_partition:float=None, run_idx:int=None, backbone: str='eff0'):
_cuda = 'cuda:0'
_image_size = get_image_size_for_backbone(backbone=back... |
ca01df60d45354de5e302bc84e1cadbbaaccccf1cfb3bc8da92c33df6da51040 | Python | 2,654 | 68 | import json
import requests
import os
import base64
import loguru
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
# 从环境变量中获取TOKEN
TOKEN = os.getenv('TOKEN')
# 定义获取组织仓库的函数
def get_repos(org_name, token, export_dir):
headers = {
'Authorization': f'token {token}',
}
url = f'https://api.github.com... |
60fa367e30ae55217cb20c602af6bb2a6c2070b47ba498c865537640899e14f5 | Python | 2,658 | 71 | import socket
import time
import panel as pn
import pytest
from playwright.sync_api import expect
from guppy.frontend.frontend_utils import scanPortsAndFind
from guppy.orchestration.metadata import build_metadata_template
from guppy.utils.nwb_metadata import Channel
@pytest.fixture(scope="session")
def metadata_ser... |
01b0d3874df82928cfeb255a7575ae62805a0dae4ca27ba50e45a75d7e365f22 | Python | 2,659 | 106 | import os
from concurrent.futures import ThreadPoolExecutor
from typing import Type
import numpy as np
import pytest
import xgboost as xgb
from xgboost import testing as tm
from xgboost.testing.data import make_categorical
from xgboost.testing.ordinal import (
run_cat_container,
run_cat_container_iter,
ru... |
25f60570bebec1fd0fd4cbeb49b7f914231d80f917c1d21c5eac97248e440545 | Python | 2,659 | 57 | from grid_cell.gaussian_wishart.src.models.WishartProcess import WishartProcessBase
import numpy as np
import gpflow
import tensorflow as tf
from tensorflow_probability import distributions as tfd
from grid_cell.gaussian_wishart.src.likelihoods.WishartProcessLikelihood import WishartLikelihood
class FactorizedWishartM... |
9f4672e1457111310e5f23d04594e8c0004892fb86ba63c190c5316a5e89168d | Python | 2,659 | 68 | # phantom_displacement.py
import numpy as np
import SimpleITK as sitk
import scipy.ndimage
from scipy.ndimage import map_coordinates
def main():
# 1. Load the B0-corrected mouse MR volume
Mouse_Rigid_B0 = sitk.ReadImage(
'b0_correction_analysis/Analysis_08_10_2024/mouse/mouse_35_mr_b0_corrected.nii'
... |
bf100378eb480c02ced8c58592b77a7db5d637f145e9e91d1433b17b164cd5f0 | Python | 2,659 | 66 | import json
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import scienceplots
import matplotlib.gridspec as gridspec
import seaborn as sns
from matplotlib.lines import Line2D
def get_performance(file_name):
with open(file_name) as f:
d = json.load(f)
k = d.keys()
v ... |
e1806fc3e6b7657964d7f2b2c16d6531804518da32ea1d1fb2b8f2ead7dd9ebf | Python | 2,659 | 72 | # -*- coding: utf-8 -*-
def generate_mesh(request, project_id=None, stack_id=None):
skeleton_id = int(request.POST.get('skeleton_id',-1))
# retrieve all components for a given skeleton id
components = Component.objects.filter(
project = project_id,
stack = stack_id,
skeleton_id = ... |
c6bc69415d51c0ea595c3b8d3b34df5004daf5076acd36b4a63dc8edae2b63c9 | Python | 2,661 | 80 | import matplotlib.pyplot as plt
import os
import pickle
import torch
import json
from collections import defaultdict
def save_best_model(state_dict, model_dir: str, best_epoch: int, keep: int):
"""
Save the current best model, keep the most recent `keep` model checkpoints, and delete the remaining old models.... |
66d67495117eee4c52aedbf63f363a24225c264f18f9a598e15dc5948e7d3709 | Python | 2,662 | 73 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import shutil
import tempfile
import zipfile
from mmengine.utils import mkdir_or_exist
def parse_args():
parser = argparse.ArgumentParser(
description='Convert LoveDA dataset to mmsegmentation format')
par... |
fc703f43cea8835bdd5778180e3798d8fbc37f78def0d2e408de4f95f583d57b | Python | 2,662 | 76 | import numpy as np
from scipy.spatial import KDTree
import nearl
from nearl.features import Feature
import nearl.io, nearl.featurizer
# Result is a 4*9 (36 dimensions) contact map
# Rows (protein) : C, N, O, S
# Columns (ligand) : C, N, O, F, P, S, Cl, Br, I
PROT_MAP = {6: 0, 7: 1, 8: 2, 16: 3}
LIG_MAP = {6: 0, 7: ... |
6bacc39819eca18d18650ce1a806f6c35d101e42611abb1707089c7c5caf5f4e | Python | 2,663 | 79 | import numpy as np
import pytest
import xgboost as xgb
from xgboost import testing as tm
from xgboost.testing.plotting import run_categorical
try:
import matplotlib
matplotlib.use("Agg")
from graphviz import Source
from matplotlib.axes import Axes
except ImportError:
pass
pytestmark = pytest.mar... |
1bab9864d13ad4d940ca6788edd6ce3d2033bd7b01c9eadd1ba27fc2ae87a747 | Python | 2,665 | 80 | from rest_framework import serializers
def validate_approval_status_on_creation(last_association, approval_status):
if not last_association:
if approval_status != "PENDING":
raise serializers.ValidationError(
"User can approve or reject association request only if there are pri... |
360a210f171125333237ea739c7b95e6ccfbdee8d94d8417bab4222a34039be8 | Python | 2,666 | 83 | import os
import torch
import nibabel as nib
import numpy as np
import pandas as pd
def nii_loader(path):
img = nib.load(str(path))
data = img.get_fdata()
return data
def read_table(path):
return(pd.read_excel(path).values) # default to first sheet
def white0(image, threshold=0):
"standardize vox... |
c0160f5d4aef85b41e24558142c0285fe876e29bfda77cfc83bc73e2da5221d4 | Python | 2,666 | 63 | import numpy as np
import matplotlib.pyplot as plt
import SimpleITK as sitk
def formula(value):
G_read_percentFLASH = 5.563298 / 100
PVM_GradCal = 42797.5
new_value = value / (G_read_percentFLASH * PVM_GradCal)
return new_value
# Load MR volume
# MR_Volume = sitk.ReadImage('b0_correctio... |
ad88e2c6e6fedbe10cfd0796403662deaf67c621a91834d20e127ba02753088c | Python | 2,667 | 85 | # -*- coding: utf-8 -*-
"""
Created on Fri May 10 11:34:27 2024
@author: mbmad
"""
from functools import cache, wraps
class InvalidRecordingError(Exception):
"""
Raise this error when an abffile fails the assumptions of a given measure.
For example, attempting to find an action potential threshold when a ... |
f8ee4b9adb3c1491e259a17c0582eb2796d4c31a1c3181b9ec99e6c827b57d16 | Python | 2,667 | 59 | import torch
from torch.nn.utils.rnn import pad_sequence
class PadTensors:
"""This class implement the specific collate logic for our data
each call function are resolve at object creation
this prevent control flow inside the dataset loop
"""
def __init__(self, batch_first: bool = True, requi... |
33043c61b9ca27952a81e7a7eadfad704ca463f1b783d19f0d57a1283f4320fd | Python | 2,668 | 80 | import numpy as np
from pathlib import Path
from scipy.spatial.transform import Rotation as R
from biopandas.pdb import PandasPdb
try:
from base.atom_types.atom_types import Typer
except:
from atom_types.atom_types import Typer
def get_one_hot(targets, nb_classes):
res = np.eye(nb_classes)[np.array(targe... |
a47d1932595a44afee68a8ba94a1cc4c2e2c87f12f8562fc8802bbb49bc68d33 | Python | 2,669 | 69 | import torch
from torch.utils.data import Dataset
import numpy as np
CHARISOSMISET = {"#": 29, "%": 30, ")": 31, "(": 1, "+": 32, "-": 33, "/": 34, ".": 2,
"1": 35, "0": 3, "3": 36, "2": 4, "5": 37, "4": 5, "7": 38, "6": 6,
"9": 39, "8": 7, "=": 40, "A": 41, "@": 8, "C": 42, "B": 9, "E... |
7260a47b30ce8b0bec0ce4b684700677ec3f3a2616e76fc277dd9beefa80906a | Python | 2,671 | 66 | import pytest
from src.babel_utils import parse_rdf_literal, reduce_to_most_specific_tree_codes
@pytest.mark.unit
@pytest.mark.parametrize(
"literal,expected",
[
# Plain quoted literal — most common pyoxigraph SPARQL result form
('"Hello"', "Hello"),
('""', ""),
('"multiple wo... |
0b504b490ac424adb42d57c1b8e823fb16da7e368525fed584c28629376f2b96 | Python | 2,673 | 84 |
"""
Demonstrate the use of h5py in SWMR mode to monitor the growth of a dataset
on notification of file modifications.
This demo uses pyinotify as a wrapper of Linux inotify.
https://pypi.python.org/pypi/pyinotify
Usage:
swmr_inotify_example.py [FILENAME [DATASETNAME]]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.