sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
ff1ed6d1d41e0fc6f4f547cabe4b15ced5127ba212e51dd8b80166f5960f68b5 | Python | 2,179 | 55 | #!/usr/bin/env python3
"""Build the shipped field-presence mask (``eggnog.db.fieldpresence.bin``).
Maintainer / release tool. Produces the fixed-name lazy-cascade field-presence
mask that ships in the data bundle alongside ``eggnog.db``, so end users do not
pay the one-time build (a full scan of ``prots``) on their fi... |
a462c4037db3a8b9e2f3bd115509c647907444b21eddf450285d7fac6620f043 | Python | 2,180 | 86 | import torch
import torch.nn.functional as F
from torch.optim import Adam
from einops import rearrange, repeat
import sidechainnet as scn
from equiformer_pytorch import Equiformer
BATCH_SIZE = 1
GRADIENT_ACCUMULATE_EVERY = 16
MAX_SEQ_LEN = 512
DEFAULT_TYPE = torch.float64
torch.set_default_dtype(DEFAULT_TYPE)
def ... |
d2009c745f9b71b5b23401568a9248f135a594240ac7ecf1505557ba3063cac5 | Python | 2,182 | 66 | """pytorchexample: A Flower / PyTorch app."""
import torch
import numpy as np
from sklearn.metrics import roc_auc_score
def train(net, trainloader, epochs, lr, device):
"""Train the model on the training set."""
net.to(device) # move model to GPU if available
criterion = torch.nn.CrossEntropyLoss().to(d... |
f0a2e57125997933e12e22ed2c458317c105e5173cca65a4cb4ad01e27af469c | Python | 2,184 | 74 | import numpy as np
import pytest
from ase import Atoms
from ase.data import covalent_radii
from simgen.hydrogenation import (
add_hydrogens_to_atoms,
check_hydrogen_position_is_valid,
get_exclusion_radii,
)
@pytest.mark.parametrize(
"atoms, idx, expected",
[
(Atoms("CC"), 0, np.array([0.0... |
c151c6c6d5ccc3985ba466de036002439f58f578e63dfcf04c1607eb7e429c8e | Python | 2,185 | 55 | import argparse
import os
import sys
from pathlib import Path
from string import Template
from dotenv import load_dotenv
def execute_program() -> None:
os.chdir(os.getenv(key='buildPath'))
os.system(f"sh {os.getenv(key='buildInstFilNme')}{os.getenv(key='buildInstExt')}")
def interpolate_template(template_p... |
e71fd423448abdb47039475bf87a71d7ec25ae92e7e62291c5aeca5d2d53eb58 | Python | 2,186 | 81 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Andrei Istudor andrei.istudor@gmail.com
"""
import sys
from PyQt5.QtCore import QModelIndex, Qt, QAbstractTableModel
from PyQt5 import QtWidgets
class TaskTableModel(QAbstractTableModel):
'''
Models the table representation of the processing queu... |
19d9522ae61f502c6b7c3a428e882ab38ab0c1b9f5f14da49b0a9ef8b22ebfa2 | Python | 2,187 | 44 | # 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... |
b56998aad232593078de8475c915d1cc29820fb1af98dfed636e214eee4c9358 | Python | 2,190 | 67 | # dataset settings
dataset_type = 'CityscapesDataset'
data_root = 'data/cityscapes/'
crop_size = (512, 1024)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations'),
dict(
type='RandomResize',
scale=(2048, 1024),
ratio_range=(0.5, 2.0),
keep_ratio=True... |
2e0b7e1e90425f949f8c1b807b05e65671659e0757c6e96b5d1d12bc3c6fbec9 | Python | 2,192 | 69 | import logging
import sys
from functools import lru_cache
from pathlib import Path
from rdkit import Chem
def ensure_dir(path):
import os
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
@lru_cache(maxsize=1000)
def canonicalize_smiles(smiles: str) -> ... |
89690732588b24054e1672f60d15c43a611dcdcdfb13e5a82458d3ea080dba8b | Python | 2,192 | 73 | import progressbar
from django.core.management.base import BaseCommand
from django.db import connection
class Command(BaseCommand):
help = "Prewarm heavily used tables"
tables_to_prewarm = [
'auth_group',
'auth_group_permissions',
'auth_permission',
'auth_user',
'auth... |
3d109e09bfeeaf2354b907f1bec34105baeee6bf7d5f2de285967672aa2100bd | Python | 2,193 | 54 | import pandas as pd
import os
import numpy as np
import nibabel as nib
from joblib import Parallel, delayed
from . import consts
class DiceNiiRois:
"""
Kinderseg helper class to calculate Dice similarity coefficient between all the ROIs of a NIfTI
It outputs a pandas DataFrame with the Dice similarity coe... |
99312ffe0d465da250c0b9c0580fa076d7d3b0c6b00be0cb2544bd1815bc88c5 | Python | 2,193 | 70 | # Copyright (c) OpenMMLab. All rights reserved.
# yapf: disable
from .class_names import (ade_classes, ade_palette, bdd100k_classes,
bdd100k_palette, cityscapes_classes,
cityscapes_palette, cocostuff_classes,
cocostuff_palette, dataset_aliase... |
c8ec823c13d80c7dd7e20c552db2d8cce77b923a69bb551f415b44d77a7f8990 | Python | 2,193 | 70 | _base_ = [
'../_base_/models/setr_pup.py', '../_base_/datasets/cityscapes_768x768.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py'
]
crop_size = (768, 768)
data_preprocessor = dict(size=crop_size)
norm_cfg = dict(type='SyncBN', requires_grad=True)
crop_size = (768, 768)
model = dict(
... |
360dc240efc502b559f57cfb7d3974a988f747d14329bba2ac3df65ce7d1659b | Python | 2,195 | 83 | """Create l5pc model with MEA"""
"""
Copyright (c) 2016-2022, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt>
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 3.0 as published
b... |
93fcd5417900e77ff6e48780a42945c79d66d9cc9cca5736307bb99ca6b97b90 | Python | 2,195 | 77 |
from random import shuffle
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import RandomForestClassifier
from mlp_classifier_constant import MLPClassifier_ConstantWeights
import uuid
import os
# import reader
import ppi
import fdr_utils
import ppi as ppiLib
import pandas as pd
import sys
import... |
9cbed0eabd1edfc5bbe0f2b27a79580fb508e9286487d61d26fb3276a9dd3738 | Python | 2,201 | 70 | import pandas as pd
import argparse
import os
import yaml
from utils import get_image_data_df
class Checker:
def __init__(self, data_path, data_file, labels_path, labels_file):
self.data_path = data_path
self.data_file = os.path.join(data_path, data_file)
self.labels_path = labels_path
... |
373c8e524f4c7734d2d1b9aa4f448d5cd0467c187af17ca395cb42092b6ed38d | Python | 2,203 | 71 | # -*- coding: utf-8 -*-
# For in a django shell
from catmaid.models import Component
from catmaid.control.stack import get_stack_info
from catmaid.control.neurohdf import extract_as_numpy_array
import numpy as np
project_id = 1
stack_id = 3
skeleton_id = 1443
# retrieve all components for a given skeleton id
compo... |
db708c8a585643ee7e4a75231b0ab12ca60fb4de32e34b979a230ead329136cc | Python | 2,203 | 75 | import contextlib
import platform
import threading
def emojis(str=''):
# Return platform-dependent emoji-safe version of string
return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str
class TryExcept(contextlib.ContextDecorator):
# YOLOv5 TryExcept class. Usage: @TryExce... |
c6cab3c4fa05b61f51425a5dfeb9e06f8a4e0b26662e182072e83ab3233d9a78 | Python | 2,204 | 68 | """
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.
"""
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# l... |
ea668cacc28b1cfd9041823ef3823799f6f3c72704667d9168099fcc96f83faf | Python | 2,204 | 76 | import pytest
from neo4j import GraphDatabase
from kgx.source import NeoSource
from kgx.transformer import Transformer
from tests.unit import (
clean_database,
DEFAULT_NEO4J_URL,
DEFAULT_NEO4J_USERNAME,
DEFAULT_NEO4J_PASSWORD,
load_graph_dictionary,
check_neo4j_container,
NEO4J_CONTAINER_NA... |
77d4f60ba338956f90a02bc74ea5f6ab4b5bb27c056d92a1e6ec78da9b32fbcf | Python | 2,205 | 72 | # dataset settings
dataset_type = 'NYUDataset'
data_root = 'data/nyu'
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadDepthAnnotation', depth_rescale_factor=1e-3),
dict(type='RandomDepthMix', prob=0.25),
dict(type='RandomFlip', prob=0.5),
dict(
type='RandomResize',
... |
9c456c5436f6a863bc9915801ba87ee7ceb7d933b0ea6ec7fa65d2d5b8cdf67a | Python | 2,205 | 67 | # dataset settings
dataset_type = 'COCOStuffDataset'
data_root = 'data/coco_stuff164k'
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=True... |
032cf4775070692c6fe5e6bcfe620e158f9200a7eb5dbb136210391817fa14cf | Python | 2,206 | 58 | import holoviews as hv
import numpy as np
import panel as pn
import pytest
from guppy.frontend.transient_peaks import (
PeaksReviewView,
build_peaks_view_page,
load_peaks,
)
from guppy.utils._hdf5_io import write_hdf5
from guppy_test_data import resolve_plot
TIMESTAMPS = np.arange(0.0, 11.0, 1.0)
Z_SCORE ... |
c3517e7acacca202e1f06689ea3ef2b3595fbcb989c0044543dafdb3ce304630 | Python | 2,206 | 73 | #!/usr/bin/env python3
#
# Calculates statistics about the standard deviations reported in the midpoints
# data.
#
import numpy as np
import base
filename = 't2-cell-counts.tex'
nooocytes = True
a = 'and cell != "Oocyte"' if nooocytes else ''
with base.connect() as con:
c = con.cursor()
# Get difference in ... |
984d1db35312d529d4ffe2beee858abd6bd775e02e88ba83279543c9b098ede7 | Python | 2,207 | 66 | # dataset settings
dataset_type = 'PotsdamDataset'
data_root = 'data/potsdam'
crop_size = (512, 512)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', reduce_zero_label=True),
dict(
type='RandomResize',
scale=(512, 512),
ratio_range=(0.5, 2.0),
k... |
e6ebb837ce03ce340128839c44bd30c4c583db66634374401f78cf4e55e4e5d7 | Python | 2,207 | 66 | # dataset settings
dataset_type = 'ISPRSDataset'
data_root = 'data/vaihingen'
crop_size = (512, 512)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', reduce_zero_label=True),
dict(
type='RandomResize',
scale=(512, 512),
ratio_range=(0.5, 2.0),
k... |
2c5a171ad53938f121c2d5baa982d96aa3f4335a3620a81fce3c30751961a99e | Python | 2,208 | 64 | # coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# 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... |
d31881ec592b0b480aad01f13e2e90603bd7b4973abdb5c7debc7d4a381788a8 | Python | 2,208 | 70 | # -*- encoding: utf-8 -*-
'''
Copyright 2022 The International Digital Economy Academy (IDEA). CCNL team. All rights reserved.
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.o... |
d8a3304326720880aefe9539e23145f68ecc6da60f2385e1b3cd504ac5f2603a | Python | 2,208 | 66 | # dataset settings
dataset_type = 'LoveDADataset'
data_root = 'data/loveDA'
crop_size = (512, 512)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', reduce_zero_label=True),
dict(
type='RandomResize',
scale=(2048, 512),
ratio_range=(0.5, 2.0),
ke... |
e395137109d0a6cd5c3bb9e9457878411ff3fc4f341cffa146c9ab16207786c4 | Python | 2,208 | 72 | #!/usr/bin/env python
import datetime
import os
import sys
def extract_datetime_from_line(line, year):
# Expected format: I0210 13:39:22.381027 25210 solver.cpp:204] Iteration 100, lr = 0.00992565
line = line.strip().split()
month = int(line[0][1:3])
day = int(line[0][3:])
timestamp = line[1]
p... |
19906d9e34d7a9978670ba7db8c281819319e7c1c822aeb5369cfc8e4d932531 | Python | 2,210 | 58 | from medperf import config
from medperf.entities.aggregator import Aggregator
from medperf.entities.training_exp import TrainingExp
from medperf.utils import approval_prompt
from medperf.exceptions import CleanExit, InvalidArgumentError
class SetAggregator:
@classmethod
def run(cls, training_exp_id: int, aggr... |
b6659e16fcc8410312bc5693153d77e640812ff1727f5d1e7873b44139ff10f6 | Python | 2,210 | 69 | from ipaddress import IPv4Network
from CybORG.Shared import Observation
from CybORG.Simulator.Actions import Action
from CybORG.Simulator.Actions.ConcreteActions.Pingsweep import Pingsweep
from CybORG.Simulator import State
class DiscoverRemoteSystems(Action):
"""
A high level Red action that discovers activ... |
cbc29b192a2036ca92503b5cac726164649eb80a828847fb9edb5c663f6a3881 | Python | 2,210 | 67 | # dataset settings
dataset_type = 'CityscapesDataset'
data_root = 'data/cityscapes/'
crop_size = (512, 1024)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations'),
dict(
type='RandomResize',
scale=(2048, 1024),
ratio_range=(0.5, 2.0),
keep_ratio=True... |
d32a98595a19b89723efea5045113552105754778c6118703f7901ed97f78420 | Python | 2,210 | 89 | import pytest
from unittest.mock import call
from typer.testing import CliRunner
from medperf.config_management import read_config
from medperf.commands.profile import app
runner = CliRunner()
PATCH_PROFILE = "medperf.commands.profile.{}"
@pytest.mark.parametrize("profile", ["local", "testauth"])
def test_activate_... |
054dcc6bd33964af4b1ff7420aab78c1a10bb8640abc62fe017f5f116f63ede3 | Python | 2,211 | 55 | import torch
import torch.nn as nn
from monai.networks.nets.unetr import UNETR as UNETR_Orig
from nnunet_mednext.training.network_training.nnUNet_variants.architectural_variants.nnUNetTrainerV2_noDeepSupervision import \
nnUNetTrainerV2_noDeepSupervision
from nnunet_mednext.network_architecture.neural_network impor... |
efb2978a7870c82ec047cb1997d5f8d1da749bac757b4b20425fe29e64fc4b75 | Python | 2,211 | 70 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Andrei Istudor andrei.istudor@gmail.com
"""
import os
import sys
from PyQt5 import QtWidgets, QtMultimedia, uic, QtCore
from PyQt5.QtWidgets import (QMainWindow, QTextEdit,
QAction, QFileDialog, QApplication)
from PyQt5.QtWi... |
d49530b0a48a83d3afff02cd17ce4f2375eda2f30ebb5b79bd0a790e3292f8ad | Python | 2,212 | 45 | # 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... |
ffcfb9fc0a723ef058c5b26d0b6a4416e92b7bb38c2a646da9b55f9bf0b58d1b | Python | 2,212 | 61 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from common import db_connection
import sys
if len(sys.argv) != 3:
print >> sys.stderr, "Usage: %s <PROJECT-ID> <USER-ID>" % (sys.argv[0],)
sys.exit(1)
project_id = int(sys.argv[1])
user_id = int(sys.argv[2])
c = db_connection.cursor()
c.execute("SELECT id FRO... |
cefa9496aba528d968b7235e5408c344aba1aab06b09a691d6929c439935b180 | Python | 2,214 | 59 | import pytest
from xgboost import testing as tm
from xgboost.testing.interaction_constraints import (
run_interaction_constraints,
training_accuracy,
)
class TestInteractionConstraints:
def test_exact_interaction_constraints(self) -> None:
run_interaction_constraints(tree_method="exact", device="... |
e43683c82853324f4005dc50f1772fed842c87c90a3f3f744f349fd84135b4f0 | Python | 2,214 | 66 | from collections import OrderedDict
import torch
from torch import nn
class DeepRankNetwork(nn.Module):
"""
DeepRank network model.
Notes
-----
This code block is adopted from DeepRank2:
https://github.com/DeepRank/deeprank2/blob/main/deeprank2/neuralnets/cnn/model3d.py
"""
def __i... |
04d02bf230700f023aceffa2347de763a1ad39fd9347b695ee5d4391bb6ca7e5 | Python | 2,215 | 63 | import torch
import torch.nn as nn
from mmengine import Config
from mmseg.apis import init_model
from mmseg.models.utils import resize
class Segformer(nn.Module):
def __init__(self, cfg):
super(Segformer, self).__init__()
mmcfg = Config.fromfile(cfg['config_file'])
pre_model = init_model... |
673908562d360de209a4884e6aae086a3980f7f436502382a84d2b15212d3802 | Python | 2,215 | 56 | import numpy as np
def impute_zeros(X, rem_neg = False, rem_neg_ONLY = False, seed = 0):
np.random.seed(seed)
X = np.asarray(X)
# print(f"Removing {len(np.where(X == 0)[0])} zero values")
# non-parametric single-column imputation
for i_col in range(X.shape[1]):
vals = X[:, i_col] #pick off ... |
1960d40d1d5c80ec6210e2421b9fced840b363ee32d77741faa671be7f80b1e4 | Python | 2,216 | 65 | from unsloth import FastLanguageModel
import transformers
from datasets import load_dataset
import numpy as np
from tqdm import tqdm
import torch
from scipy.optimize import minimize
# code from https://colab.research.google.com/drive/1GDbmEMmCVEOwhYk6-1AothdXeAlnqZ_j?usp=copy#scrollTo=L_mG7OJuumrZ
def get_logp(model,t... |
5e8729c0b1b552b930d3d4d968afc9f7f1b19f5b6e3f2caee1da29e74f7286d7 | Python | 2,217 | 64 | """
This file is part of the Firmware project to interface with small Async or Neuromorphic chips
Copyright (C) 2022 Willian Soares Girao - University of Groningen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
... |
0cfc898e2047e2e9e005ec6ee2439ea1a41eea1e3b2527fc8518425f6fba0d01 | Python | 2,218 | 64 | from __future__ import division
from builtins import str
from builtins import range
from sciunit import Score
import numpy
from sciunit.utils import assert_dimensionless
import collections
class ZScore_PathwayInteraction(Score):
"""
Average of Z scores. A float indicating the average of standardized differenc... |
aae9ed285ee784f91c9d3e728951080299d096e632ead5e07410187f9837b168 | Python | 2,218 | 75 | """Integration test for the share-token resolver."""
from datetime import UTC, datetime, timedelta
from uuid import uuid4
import pytest
from sqlmodel.ext.asyncio.session import AsyncSession
from zndraw.access import ShareAccess, ShareContext
from zndraw.dependencies import resolve_share_token
from zndraw.models impo... |
c53b943029282383c83acf43f509e1d8ac7eb474461a587ec0660168177046b5 | Python | 2,218 | 57 | from sklearn.preprocessing import StandardScaler
from pandas import read_csv
import numpy as np
import nibabel as nib
import os
def load_lesions_and_behaviors(lesion_folder, csv_file, max_score, do_regress_out_lesion_volume=False):
"""
Load lesion files, behavioral data, and covariates from CSV, and comp... |
62770b39e03b7d5dca8b52e3fb293d64e487efe236054e7a14bb119754f3ca84 | Python | 2,219 | 73 | """
Computations on the (n+1)-dimensional Minkowski space.
"""
import numpy as np
from geomstats.manifold import Manifold
from geomstats.riemannian_metric import RiemannianMetric
import geomstats.vectorization as vectorization
class MinkowskiSpace(Manifold):
"""The Minkowski Space."""
def __init__(self, di... |
ec2755ffd72d94b6408588f3a677c2b2c42e4bc5e9e8a165631a0b1f646030e3 | Python | 2,219 | 67 | """Tests for frame schemas."""
from zndraw.schemas import (
FrameBulkResponse,
FrameCreateRequest,
FrameResponse,
FrameUpdateRequest,
)
class TestFrameSchemas:
"""Tests for frame Pydantic schemas."""
def test_frame_response(self) -> None:
"""FrameResponse validates frame data."""
... |
0aea413521655f360a60583a230e0d894a76bbcb05c526aa02a0230fc1bb0239 | Python | 2,220 | 56 | """
Functions that use the template (e.g., PAM50)
Copyright (c) 2018 Polytechnique Montreal <www.neuro.polymtl.ca>
License: see the file LICENSE
"""
import logging
import numpy as np
logger = logging.getLogger(__name__)
def get_slices_from_vertebral_levels(im_vertlevel, level):
"""
Find the slices of the c... |
3759cbfa381405ec3dad7397aae0c611950afcfb0dfeaecae5877e3c44ede24e | Python | 2,220 | 61 | import unittest
import numpy as np
from PyQt5 import QtGui
from features.EventDetection import SpikeDetection
from tests.TestData import processed, DataManager, Plot, source, noise_std
from util.conf import sd_params
app = QtGui.QApplication([])
class SpikeDetectionTest(unittest.TestCase):
def setUp... |
fef7414e6597b4a85a8f2c4bb622277d966c5c4686503907091ddae9957fd267 | Python | 2,221 | 70 | from dataset import *
dataset = NasBench('./nasbench_dataset')
def get_spec(adj_indxs, op_indxs):
"""
Construct a NASBench spec from adjacency matrix and op indicators
"""
op_names = ['conv1x1-bn-relu', 'conv3x3-bn-relu', 'maxpool3x3']
ops = ['input']
ops.extend([op_names[i] for i in op_indxs]... |
5e1f54210044c94e2781c4b6ccf0958805daa6cb5bf56fd9d64a3d3eeee770fb | Python | 2,224 | 97 | from behavior_analysis.experiment import PreyCaptureExperiment, TrialData
__all__ = ("expt", "ARENA_SIZE", "get_trials", "get_params")
# =====================
# EXPERIMENT PARAMETERS
# =====================
directory = r"PATH_TO_EXPERIMENT_DIRECTORY"
video_directory = r"PATH_TO_VIDEO_DIRECTORY"
ARENA_SIZE = 30
_de... |
a5b41575081d157f304a763f76cb1c879b57a0bd862fdfa4ed419c50432fb676 | Python | 2,224 | 60 | #!/usr/bin/env python3
"""
Static regression checks for CICADA's Smoothing_Retention kernel configuration.
This test uses only source code text; it contains no participant-derived data.
Run from the CICADA repository root:
python validation/scripts/test_smoothing_retention_configuration.py
"""
from pathlib impor... |
137689b231c47351044645d096898874c3ac91c731b1f9f47d726d6a913aa877 | Python | 2,225 | 57 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pandas as pd
import datalad.api as dl
from zoo_bids.functions import setup
import nest_asyncio
nest_asyncio.apply()
project_name = 'zoo-bids'
paths = setup()
for file in paths['ratings']:
dl.get(file)
df_input = pd.read_csv(file)
df_output = d... |
243885e538e45ad32e95500f8831083dd199f42d5afcb3d53def0103e1fbef00 | Python | 2,225 | 80 | """
This script provides the functionality to generate metadata.npz files necessary
for load_balancing the DataLoader.
"""
import argparse
import multiprocessing as mp
import os
import warnings
import numpy as np
from tqdm import tqdm
from ocpmodels.common.typing import assert_is_instance
from ocpmodels.datasets imp... |
897603ad0c87e74e39069d10386e037ff1aca567e28ec352a35a0dfd9e463f30 | Python | 2,225 | 60 | from __future__ import division
from builtins import range
from sciunit import Score
import numpy
from sciunit.utils import assert_dimensionless
class ZScore_somaticSpiking(Score):
"""
Mean of Z scores. A float indicating the sum of standardized difference
from reference means for somatic spiking features.... |
dc71e7119103f4b5142f86c0a2101b21b9e13aab3ef806c3d2c802aa1a620808 | Python | 2,225 | 49 | from batchgenerators.utilities.file_and_folder_operations import *
import shutil
from nnunet_mednext.paths import nnUNet_raw_data
from nnunet_mednext.dataset_conversion.utils import generate_dataset_json
if __name__ == '__main__':
# this is the data folder from the kits21 github repository, see https://github.com... |
8237304f708fbac8b26c2e3f99fdf0c4c757014872b02d0cfc87e3435c49654a | Python | 2,226 | 67 | import h5py
import json
import numpy as np
import pandas as pd
from experiment import *
if __name__ == "__main__":
for species in expt.species_names:
print(species)
# Params
params = get_params(species)
percentile = params["alignment_percentile"]
gap_size = params["gap_... |
9e528d94c92d694aae998b90154b31e3f2a7003918895051c3efe8dce1dff1eb | Python | 2,226 | 61 | #!/usr/bin/env python
'''Example for generating a mixed JSON/ACC Arbor cable cell description (with optional axon-replacement)
$ python generate_acc.py --output-dir test_acc/ --replace-axon
Will save 'l5pc.json', 'l5pc_label_dict.acc' and 'l5pc_decor.acc'
into the folder 'test_acc' that can be loaded in Arbor wit... |
b10e6e9a8f6f7383cd639652b354fef48c561b50b7d07dfccfbebee3662dca7b | Python | 2,226 | 56 | # Classes
# OWL classes
OWL = "http://www.w3.org/2002/07/owl#"
OWL_CLASS = OWL + "Class"
OWL_ONTOLOGY = OWL + "Ontology"
# Biolink classes
# Keep all the biolink classes as constants to keep from having to handle name changes.
# of course bigger changes will require code changes as well.
ACTIVITY = "biolink:Activity"... |
f67aaee38b1422635ebdb77ba27529dab893c75d00c47d49855045a6b6e5095c | Python | 2,227 | 62 | import numpy as np
import networkx as nx
import torch
if torch.cuda.is_available():
device = torch.device("cuda")
else:
device = torch.device("cpu")
# graphical lasso
from sklearn.covariance import GraphicalLassoCV
# signed distance correlation
from scipy.spatial.distance import pdist, squareform
from scipy.s... |
18bee76b17c4d162b8a262031c9cd5e6bfb0dd62906afdac309021f129d52039 | Python | 2,228 | 68 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 16 13:48:14 2023
@author: george
"""
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import os
plotGraphs = True
def movingaverage(interval, window_size=10):
window= np.ones(int(window_size))/float(window_size)
... |
34587f052340636414c105277cfe01ef407d2731c79cce04df78f8a8cfd06307 | Python | 2,231 | 59 | import os
from medperf.entities.training_exp import TrainingExp
from medperf.entities.event import TrainingEvent
from medperf.utils import approval_prompt, dict_pretty_print
from medperf.exceptions import CleanExit, InvalidArgumentError
from medperf import config
import yaml
class CloseEvent:
"""Used for both eve... |
b0607620e0ab1a9ce29fe4edc6812a2f95bb3d6fbfce171b5d6b6ccbc646b330 | Python | 2,234 | 66 | import os.path as op
import json
import pytest
from heudiconv.external.pydicom import dcm
from heudiconv.cli.run import main as runner
from heudiconv.convert import nipype_convert
from heudiconv.dicoms import parse_private_csa_header, embed_dicom_and_nifti_metadata
from .utils import (
assert_cwd_unchanged,
T... |
0c2b42b28dec2cb66ea790b7aacba0f6ad74a7abc0af785d281a33ae3904b68d | Python | 2,235 | 45 | from PyQt5 import QtCore
from threads.WorkerSignals import WorkerSignals
class Worker(QtCore.QRunnable):
def __init__(self, work, kwargs = {}, callback = None, callback_kwargs = None, max_progress_callback = None, progress_callback = None):
'''
work:
function.
functi... |
70b8fcdde56585fc24dbabb4c5e26167dc7a9490b384483583bc746deba153a0 | Python | 2,235 | 70 | # dataset settings
dataset_type = 'BDD100KDataset'
data_root = 'data/bdd100k/'
crop_size = (512, 1024)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations'),
dict(
type='RandomResize',
scale=(2048, 1024),
ratio_range=(0.5, 2.0),
keep_ratio=True),
... |
fbafed3f0f9076f43401e10840be27267e8d989e0a156a057a7914961a8e65f8 | Python | 2,235 | 66 | import os
from glob import glob
import shutil
import argparse
import json
import urllib.request
import hashlib
from typing import Union
from bdpy.dataset.utils import download_file
from tqdm import tqdm
def main(cfg):
with open(cfg.filelist, 'r') as f:
filelist = json.load(f)
target = filelist[cfg.t... |
18ebbf9ea8ba3b03d30df2701a9259895b40ac4e0a531b81883af15a1eecaf47 | Python | 2,237 | 77 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
def test_tversky_lose():
from mmseg.models import build_loss
# test alpha + beta != 1
with pytest.raises(AssertionError):
loss_cfg = dict(
type='TverskyLoss',
class_weight=[1.0, 2.0, 3.0],
... |
0a8d8f1e0487f4a0edd23fc9f96fe0056fe072bbfdd1682e4981154865f42307 | Python | 2,238 | 54 | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# 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 required by appli... |
6e852f6b6e51b8265539b1fdcca1eeb793bff41debda1962dd8b64ec4e86c847 | Python | 2,239 | 68 | from .config_management import ConfigManager, read_config, write_config # noqa
from medperf import config
import os
def _init_config():
"""builds the initial configuration file"""
default_profile = {
param: getattr(config, param) for param in config.configurable_parameters
}
config_p = Confi... |
778b7569b8e7f47ea214ffd23f305af09d631c9be0e02e5c91565aae9f700d03 | Python | 2,239 | 76 | # 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_... |
99abe3ec9cc8a572743c109022a33cd839dce05ce3b8009cc685d5d38082a79f | Python | 2,239 | 62 | #!/usr/bin/env python3
from linkml_runtime.utils.schemaview import SchemaView
import yaml
import sys
def generate_transform_spec(schema_path, output_path):
"""Generate a comprehensive transformation spec with all classes and slots from the source schema."""
# Load the schema
view = SchemaView(schema_... |
a05b1069ec2a5849aee9e18b360fd381c615837dbdda4c81039d37fac9918f9d | Python | 2,239 | 59 | import os
from kgx.graph.nx_graph import NxGraph
from kgx.sink import ParquetSink
from kgx.transformer import Transformer
from tests import TARGET_DIR
from pyarrow.parquet import read_table
def test_write_parquet():
"""
Write a graph to a Parquet file using ParquetSink.
"""
graph = NxGraph()
gra... |
3d4237e76fdb62ed731c0e8e1ddf1f40f3da419d129ede1540c3eb5d4d91b358 | Python | 2,241 | 59 | """Run the behavioral-covariate sample session through Steps 1-4.
The session is written by ``_write_covariate_csv_session`` in
``guppy/testing/scripts/create_stubbed_testing_data.py``. Both the covariate integration
tests and the documentation screenshot script need the same four steps run against it
with the same st... |
7ab2168f5332ac2316e1c0a436fb4b89c28ce9db98bb66e49458e8f07fba989c | Python | 2,241 | 69 |
import argparse
import os
import re
parser = argparse.ArgumentParser(description='')
parser.add_argument('--input_pred_dir', type=str, help='Location of input i2b2 prediction formatted files')
parser.add_argument('--input_gold_dir', type=str, help='Location of input i2b2 gold formatted files')
parser.add_argument(... |
0767dcc01f2ede8210945fe2be7dbf6531045a09ac9fef296c4f1a593237a0ac | Python | 2,242 | 69 | import tensorflow as tf
import numpy as np
def MSE(y, y_, reduce=True):
ax = list(range(1, len(y.shape)))
mse = tf.reduce_mean((y-y_)**2, axis=ax)
return tf.reduce_mean(mse) if reduce else mse
def RMSE(y, y_):
rmse = tf.sqrt(tf.reduce_mean((y-y_)**2))
return rmse
def Gaussian_NLL(y, mu, sigma, ... |
829282c9d623bc655ad4bb949ece447108d7cbd518eee82d58a5d6ebb0cbf04a | Python | 2,242 | 89 | import gzip
import os
from typing import Optional, Dict, Any
import jsonlines
from kgx.sink.sink import Sink
class JsonlSink(Sink):
"""
JsonlSink is responsible for writing data as records
to JSON lines.
Parameters
----------
owner: Transformer
Transformer to which the GraphSink bel... |
b7563461661f952a39ea4ada4d5c1e091123cd3de86b17b5119f335fe769f4df | Python | 2,242 | 64 | # Copyright (c) OpenMMLab. All rights reserved.
from unittest import TestCase
import torch
from mmengine.structures import PixelData
from mmseg.models import SegDataPreProcessor
from mmseg.structures import SegDataSample
class TestSegDataPreProcessor(TestCase):
def test_init(self):
# test mean is None
... |
5d96cf8ceedda7273bddccc517fd0789ab60f92ed8b615c9c818ff56a42cd1d8 | Python | 2,243 | 68 | # dataset settings
dataset_type = 'MapillaryDataset_v2'
data_root = 'data/mapillary/'
crop_size = (512, 1024)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations'),
dict(
type='RandomResize',
scale=(2048, 1024),
ratio_range=(0.5, 2.0),
keep_ratio=Tru... |
7400e70e14cab596e3327a1f9ac3a9b49139d916a2cb8d502d503f8a34e41b31 | Python | 2,243 | 68 | # dataset settings
dataset_type = 'MapillaryDataset_v1'
data_root = 'data/mapillary/'
crop_size = (512, 1024)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations'),
dict(
type='RandomResize',
scale=(2048, 1024),
ratio_range=(0.5, 2.0),
keep_ratio=Tru... |
da9597ef7dcb547aaec46a55c09f5ba8006518283d01a0aa73924f12e8ee4756 | Python | 2,243 | 61 | """Tests for Problem documentation endpoints."""
import pytest
from httpx import AsyncClient
from zndraw.exceptions import ProblemDetail
@pytest.mark.asyncio
async def test_list_problem_types(client: AsyncClient) -> None:
"""Test listing all registered problem types."""
response = await client.get("/v1/prob... |
08f4bf58d98900287922b67684b6bfda16f7efee4953b60a22e7bb7d292facc6 | Python | 2,244 | 46 | from src.bold import calc_bold_signal
from src.plots import plot_bold,plot_activity_quadrants,plot_activity_plaid_grating,plot_interneurons,plot_total_activity
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import argparse
import warnings
warnings.simplefilter(action='ignore', category=Future... |
2526cddec11db80f42714aef59cce121d9d641133838e1e788f88a241b68eb13 | Python | 2,245 | 77 | import numpy as np
import os
import tensorflow as tf
from keras.layers import Dense, GlobalAveragePooling2D
from keras.models import Sequential
import json
import yaml
def preprocess(images):
if len(images.shape) != 4:
images = np.expand_dims(images, -1)
if images.shape[-1] != 3:
images = np.c... |
726fb1fd5d2f624efc10aecbda36c6959370af0fce128c698aad1651629e252a | Python | 2,245 | 70 | # See https://github.com/cytomining/copairs/issues/36 for details on why this file is needed
import itertools
import logging
import numpy as np
import pandas as pd
from copairs import compute
from copairs.map import create_matcher, build_rank_lists
logger = logging.getLogger("copairs")
def my_run_pipeline(
me... |
7ffc6a357d110f432befcb10be33d9299a35808ccb2fa688fe24d910f7b4e087 | Python | 2,246 | 45 | # 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... |
542154b2f6515177cb1a61d79838d1a76be6364e5f39d459a982f11efd1db383 | Python | 2,247 | 73 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import logomaker
from keras import Sequential
from keras.layers import AveragePooling1D, Conv1D, Flatten, Dense
# =============================================================================
# ge... |
7c7be3fca887dd5fb1d3f53d9fe145a5f567b9f68ae6f973e8983a523b45bfbc | Python | 2,248 | 77 | import pytest
import torch
from equiformer_pytorch.equiformer_pytorch import Equiformer
from equiformer_pytorch.irr_repr import rot
from equiformer_pytorch.utils import torch_default_dtype
# test equivariance with edges
@pytest.mark.parametrize('l2_dist_attention', [True, False])
@pytest.mark.parametrize('reversible... |
b2949c1c3e0890f10acaab8fe939a89cdb7535d3d1b0c0e1d55e0b623005b0be | Python | 2,252 | 49 | import os.path as op
from pathlib import Path
import numpy as np
from eigenstrapping.fit import SampledSurrogateMaps
from eigenstrapping_analysis.utils import (
get_rootdir, MSEED, join, save_npy, load_npy
)
from eigenstrapping.stats import compare_maps
ROOTDIR = get_rootdir()
DATADIR = Path(ROOTDIR, 'datasets',... |
13324c57ea395fb818abb68fa05851573256817c4e6f2a8a3153b3f547dbc6e1 | Python | 2,253 | 59 | import logging
import math
import numpy as np
import colorsys
def meshValidityTest(alphas, name):
probability_discrepancy = np.max(np.abs(np.sum(alphas, axis=1) - 1))
if probability_discrepancy > 1e-5:
message = '%s invalid: class probabilities in the mesh should sum to one in all nodes' % name
... |
c228841e0b69b4ea5974e9df15b8a85c66975d568fc2dcd71156ec3a3220d9de | Python | 2,253 | 45 | # 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... |
ee2cba85a53633a52248ed569d0d7a3e85081596b47d81da9be2484a99cb4fa8 | Python | 2,254 | 64 | """This module defines a wrapper around the existing token verifier in auth0-python library.
The library is designed to cache public keys in memory. Since our client is ephemeral, we
wrapped the library's `JwksFetcher` to cache keys in the filesystem storage, and wrapped the
library's signature verifier to use this new... |
efa27079c22357e718f596cbd60c7dc6395e00c3d138ae3859fa900093e10cb6 | Python | 2,254 | 62 | #!/usr/bin/env python
"""
Draw a graph of the net architecture.
"""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from google.protobuf import text_format
import caffe
import caffe.draw
from caffe.proto import caffe_pb2
def parse_args():
"""Parse input arguments
"""
parser = Argument... |
128d91f0065de69e2139d5c78655406e00300858bbb993f5ac4f44855e2ddae7 | Python | 2,255 | 77 | """
Brie - Bayesian regression for isoform estimate
See: https://brie.readthedocs.io
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from pathlib import Path
# Set __version__ for the project.
exec(open("./brie/version.py... |
156065d5e3c342984a8addc10b2f33e60febf0502150efb007a9e0c0c93d774a | Python | 2,256 | 68 | from .models import TrainingEvent
from django.http import Http404
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework import status
from .permissions import IsAdmin, IsExpOwner, IsAggregatorOwner
from .serializers import EventSerializer, EventDetailSerial... |
020c34b0a1dd7bb29b2dfc6912e7ed43555e3e2ba4aa0b5a3a368515711ddc6f | Python | 2,257 | 74 | """
Getting started with XGBoost
============================
This is a simple example of using the native XGBoost interface, there are other
interfaces in the Python package like scikit-learn interface and Dask interface.
See :doc:`/python/python_intro` and :doc:`/tutorials/index` for other references.
"""
import ... |
036a6fdd9541f83899a0bbc805a512759b67579a5c8297eb0eaa4a6eb144c2eb | Python | 2,257 | 56 | def normalize_sdf_tag(tag_line):
"""
Normalize an SDF data-item tag line ('> <ChEBI ID>') to the key used to look it up.
This is the single definition of that normalization: lowercased, spaces stripped, underscores
kept, with `formulae` folded onto `formula`. Anything that reasons about which tags a fi... |
15751f217caafeb161f394c4a6b3b61bea31e1c7503ba3ad3349cc5288a7c0bd | Python | 2,261 | 74 | import os
import sys
import json
import pandas as pd
import random
def load_labels(label_csv_path):
"""
:return: ['Anger', 'Anticipation', 'Disgust', 'Fear', 'Joy', 'Sadness', 'Surprise', 'Trust']
"""
data = pd.read_csv(label_csv_path, delimiter=' ', header=None)
labels = []
for i in range(dat... |
6896938d5407092da60ba066e901e36886afcf77c68205b5af90263dcf3c5baf | Python | 2,265 | 82 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Andrei Istudor andrei.istudor@gmail.com
"""
from threading import Lock
from PhenoTask import PhenoTask
from TaskState import TaskState
class TaskList:
'''
Class implementing a single access list for managing creation and accessing tasks.
... |
a2b1cbfa84c32ff358b5af8b952789616284e9e702919a329557d073a45a20c2 | Python | 2,265 | 64 | from django.db import migrations
from django.db.backends.postgresql.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def createmodelsfromcontainers(
apps: StateApps, schema_editor: DatabaseSchemaEditor
) -> None:
Benchmark = apps.get_model("benchmark", "Benchmark")
Benc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.