sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
80e90047e4713c0a32862bfea2f551f6c1d75c0f8cc43ec470f02f94e290012d | Python | 5,366 | 131 | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import mmcv
import pytest
from mmseg.datasets.transforms import * # noqa
from mmseg.registry import TRANSFORMS
def test_multi_scale_flip_aug():
# test exception
with pytest.raises(TypeError):
tta_transform = dict(
typ... |
4a25d524fc5696e0f594172c1e811f870d5faacf23a5fc0eb35ad66e35a23fdd | Python | 5,367 | 137 | # coding=utf8
import os
import pytorch_lightning as pl
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
from transformers import AutoTokenizer
class GPT2QADataset(Dataset):
'''
Dataset Used for yuyuan medical qa task.
Just surpport small datasets, when deal with large datasets it may... |
662549601a2c9c542ab5d76c0eb79e436ed1ab03e066de5916c4f97eb245144c | Python | 5,367 | 148 | import inspect
from pprint import pprint
from CybORG.Agents.SimpleAgents.BaseAgent import BaseAgent
from CybORG.Simulator.Actions.ConcreteActions.Withdraw import Withdraw
from ipaddress import IPv4Network
class RandomSelectRedAgent(BaseAgent):
""" Red Agent that random selects an action (with parameters) to execu... |
fe21b25c617a2c1ed221931f0825746989e3745c0fa22afbb345becb9cf2ff0d | Python | 5,370 | 174 | #!/usr/bin/env python
#
# Compute DTI.
#
# Copyright (c) 2015 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import sys
from typing import Sequence
import textwrap
from spinalcordtoolbox.utils.sys import init_sct, printv, set_loglevel
from spinalcordtoolbox.utils.shell import Metavar, S... |
091460dea3bd2ee6e812ce322ee1a7c5cacacf5fa64cbea75ded88e176f01407 | Python | 5,371 | 152 | import os
from medperf.entities.interface import Entity
from medperf.entities.schemas import ExecutionSchema
import medperf.config as config
from medperf.account_management import get_medperf_user_data
from medperf.utils import remove_path
import yaml
from medperf.entities.utils import handle_validation_error
class E... |
0f8424f9f7b477efdcabb7a9cf352b2b59c1e532ae4112e581cc894a7bc3fc6c | Python | 5,371 | 138 | import copy
from typing import List
import torch
import torch.nn as nn
from .radial_function import RadialFunction
from .so3 import SO3_Embedding
class EdgeDegreeEmbedding(torch.nn.Module):
"""
Args:
sphere_channels (int): Number of spherical channels
lmax_list (list:i... |
eb479ca1c0a38c35e925b25918a50f22ca73870b64c020226ef94ca9be748e7e | Python | 5,372 | 143 | import pandas as pd
import numpy as np
from scipy.spatial import Delaunay
from igraph import Graph
import os
import argparse
from scipy import stats
import csv
def parse_args():
parser = argparse.ArgumentParser(description='Transfer input to gml file')
parser.add_argument('-target', type=str, default='demo_da... |
52d8062048a3aba65cac30ee9a0cbee9b8a7f9689af2187b2882d0d51dc2ea34 | Python | 5,373 | 127 | # Pixel value display for figure footers
# Author: David Young, 2018, 2020
"""Customize values displayed in Matplotlib figure footers.
"""
import numpy as np
from magmap.io import libmag
class PixelDisplay(object):
"""Custom image intensity display in :attr:``Axes.format_coord``.
Translates pixel coordinat... |
4c7227572fe537926c7b00c3ba12b6d29181fc0ef2a472cecb057051dc7b91ce | Python | 5,375 | 157 | import os
import sys
import numpy as np
import pandas as pd
from sklearn.svm import SVC, SVR
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.metrics import mean_absolute_error, f1_score
# Dynamically append project root to sys.path
ROOT_DIR = os.path.abspath(os.path.join(os.path... |
0b04eeb4aa852e89ed5a5029b6256e543e58995b44094cdb385658575696bb28 | Python | 5,377 | 128 | from CybORG.Simulator.Actions.ConcreteActions.LocalAction import LocalAction
from CybORG.Simulator.Actions.ConcreteActions.PhishingEmail import PhishingEmail
from CybORG.Simulator.State import State, Session, Host
from CybORG.Shared import Observation
from ipaddress import IPv4Address
class GreenLocalWork(LocalAction)... |
fd789753ae99d2cd2c41905a526384485306da8f03652fa05e73961e14dd50a0 | Python | 5,377 | 124 | import json
class read_config:
def __init__(self, config_file_path):
# Initialize with a configuration file path
self.config_file_path = config_file_path
self.config = None
self.patch_size = None
self.augment_data = False # Default value if not specified
se... |
0a013b07776fc58262c86c76b09b739221a2d0332e6b404ec00426830edc3d8b | Python | 5,379 | 182 | """E2E test: StateFileSource discovers a running server via state.json.
Uses a real uvicorn server via server_factory to verify that StateFileSource
can locate the server from a state.json file backed by a real running process.
"""
from __future__ import annotations
import os
from datetime import UTC, datetime
from ... |
9c22f1077e359c33743aac69f7b609b1ec06b70b6b0fa5ff0beb39d848eeb92d | Python | 5,380 | 139 | import glob
import os
import sys
import shutil
import pandas as pd
import numpy as np
from characterize_data import inspect_series
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import util.config as config
def create_data_catalog(data_dir, catalog_path):
"""
Create data catalog... |
82d51fe75e8ae57de4f99df05d6b467f7f97048b4412d68204668343bf62faed | Python | 5,384 | 161 | """
MIT License
Copyright (c) 2023 Yi-Lun Liao
"""
import logging
import hydra
import torch
import torch_geometric
from omegaconf import DictConfig
from torch_geometric.data import DataLoader
from ccdvaeplus.common.data_utils import frac_to_cart_coords
from ccdvaeplus.common.utils import PROJECT_RO... |
1c7b56ffceb8c7aa81930841aec0b3b4b03839e2181948ac3fe6c0329713e929 | Python | 5,386 | 166 | """
1. Modify ``CMakeLists.txt`` in source tree and ``python-package/xgboost/VERSION`` if
needed, run CMake .
If this is a RC release, the Python version has the form <major>.<minor>.<patch>rc1
2. Modify ``DESCRIPTION`` and ``configure.ac`` in R-package. Run ``autoreconf``.
3. Run ``mvn`` in ``jvm-packages``
If... |
db0044c32966785e6211591d66bed37da60bba80002edb6e1bf270fb0906de07 | Python | 5,387 | 167 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
####################
#SVM classification Patient vs Control --> PERMUTATION
####################
"""
import pandas as pd
import numpy as np
import os
import sys
from pcntoolkit.dataio.fileio import load as ptkload
import matplotlib.pyplot as plt
from sklearn import sv... |
ae5f5150dc42e0f02b1480b9b01ad6d27c7e3d8c5417f70f42d27b92daa730b5 | Python | 5,390 | 136 | # coding=utf-8
# Copyright 2021 The IDEA Authors. 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 a... |
eb8be9bdff404c810de664834a28c0022f34e4d801c92a2b04f808a6dbf52268 | Python | 5,390 | 106 | import SimpleITK
import numpy as np
from batchgenerators.utilities.file_and_folder_operations import *
import shutil
import SimpleITK as sitk
from nnunet_mednext.paths import nnUNet_raw_data
from nnunet_mednext.dataset_conversion.utils import generate_dataset_json
from nnunet_mednext.utilities.sitk_stuff import copy_g... |
46346af7638aadd6dd8fd5e1fbeceb0e671fadd97bce7df4b5699fde8ef34ee7 | Python | 5,394 | 180 | import gymnasium as gym
from gymnasium.spaces import Box
from gymnasium.spaces import MultiDiscrete, Discrete
import numpy as np
class BinaryAction(gym.ActionWrapper, gym.utils.RecordConstructorArgs):
"""
Clip the continuous action within the valid :class:`Box` observation space bound.
"""
def __ini... |
45234ecb0a7ce088f0935fa874527b8ee76c07dab99958845f04a641de7e0d83 | Python | 5,399 | 180 | from typing import Union, List, Dict
from pathlib import Path
from enum import Enum
import tensorflow as tf
from zipfile import ZipFile
from csbdeep.utils import save_json
from ..models.n2v_config import N2VConfig
class Extensions(Enum):
BIOIMAGE_EXT = ".bioimage.io.zip"
KERAS_EXT = ".h5"
TF_EXT = ".zip... |
ecd54748a5c182d2aea0fe75f09faa83233ede47e7fb5879b96e8daee09f7f29 | Python | 5,399 | 176 | #!/usr/bin/env python
from setuptools import find_packages, setup
import os
import subprocess
import sys
import time
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
CUDAExtension)
version_file = 'basicsr/version.py'
def readme():
return '... |
143f1465ede29f09c3e2ec7f62c4381ee88ac9140d5fb1c273a4866a9b8340b1 | Python | 5,400 | 134 | # to run the TargetNet evaluation you need to install it first
# run: pip install git+https://github.com/katarinagresova/TargetNet.git
#
# you also need to donwload a pretrained TargetNet model into Models
# wget https://github.com/katarinagresova/TargetNet/blob/master/pretrained_models/TargetNet.pt?raw=true -O Models/... |
2cac7f8a0f5205732b03539e9d9121776f5ac45b11b030f2d93d87c656a29a6a | Python | 5,401 | 139 | # -*- coding: utf-8 -*-
"""
Created on Sep 8, 2023.
@author: Claire Cooper
"""
import numpy as np
import os
import scipy.io
from butter import lowpass
import re
def dataset_generator(data_path, annotations_path, fs):
"""Create the train and test (validation) dataset."""
first_round = True
binary_traces... |
14df6d9f55d7f56c61016a2549ce46e821b825129b01369afd157b96d2a6431d | Python | 5,402 | 150 | ##
## CPCantalapiedra 2020
import gzip
from os.path import isfile
from os.path import join as pjoin
from os.path import isdir as pisdir
import shutil
import subprocess
from sys import stderr as sys_stderr
from tempfile import mkdtemp, NamedTemporaryFile
from ..emapperException import EmapperException
from ..common im... |
493280f57fffacce95a71fabe028319892edb2b64cd4ef0c960c4809e8da8311 | Python | 5,407 | 146 |
import json
import pandas as pd
import numpy as np
import qtools as qt
from qtools.encoding import onehot_encoding
def create_df_every_fifth(data, label):
"""
Build a DataFrame with every fifth epoch's data for plotting.
Args:
data (list of lists): Effect sizes per epoch.
label (str): Co... |
52f2ce9796139963d0a3759899f9caa060215854025308c60da6fb47071b2b2c | Python | 5,407 | 152 | """Display-time rendering for behavioral covariates against binned photometry metrics.
Two views of the same numbers: the covariate's own trace with the per-bin means it was
reduced to, drawn on the ``time (s)`` dimension so it stacks and links with the photometry
panels of :mod:`guppy.visualization.binned_metrics`, a... |
53d6394910a207908c2d8de3b2033d84852916119fb586ba43b9caefd9be880b | Python | 5,407 | 150 | """
(optional) script to generate a matplotlib figure window with the loss plot (live update)
"""
import os
import sys
import time
from datetime import datetime
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from functools import par... |
3bf44490db08bda23643f3d6648604126064c7ec5b1ce49f59fe539db054d513 | Python | 5,408 | 154 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 jianhao2 <jianhao2@illinois.edu>
#
# Distributed under terms of the MIT license.
"""
"""
import torch
import numpy as np
from collections import defaultdict, Counter
from itertools import combinations
from torch_scatter import sc... |
905ab59b58a00257d9745f12917b27a0e8b4fbaf7449edd48111993f34ebb39a | Python | 5,408 | 159 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
the TestInterval class
@author: Andrei Istudor andrei.istudor@gmail.com
"""
import numpy as np
from EthoCNN import EthoCNN#, getTensors
import torch
from sklearn.metrics import accuracy_score
# from DataReader import DataReader
from DataReaderAV import DataReader... |
c2fd2825c02f8168874b26375a3a1374243e8cf4f39371f84c11984dce4b7b6e | Python | 5,410 | 148 | import pytest
from pprint import pprint
from CybORG import CybORG
from CybORG.Simulator.Scenarios.EnterpriseScenarioGenerator import EnterpriseScenarioGenerator
from CybORG.Agents.SimpleAgents.ConstantAgent import SleepAgent
from CybORG.Shared.Enums import ProcessName, TernaryEnum, ProcessType
from CybORG.Simulator.Se... |
83801b8ebcb67f957ef72310895b0eab7a02dac72ef1e8e861eb8940a666e645 | Python | 5,414 | 154 | import numpy as np
import pytest
from guppy.analysis.psth_peak_and_area import compute_psth_peak_and_area
def _make_psth_mean(n_timepoints=101, n_trials=1):
"""Flat psth_mean array shaped (n_timepoints, n_trials)."""
return np.zeros((n_timepoints, n_trials))
def test_known_positive_peak_detected_at_correct... |
e0d7b1eda1df8a52589513c3b7ac74c84596e52dd9f4ffec02cf0f8f243d0637 | Python | 5,414 | 155 | import os
import secrets
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography import x509
import logging
import hashlib
from utils import run_command
def generate_encryption_key(encryp... |
51b704a6ea9173287bbb6af45b0e282839759599579e1eb11570208d9b9cb1a9 | Python | 5,415 | 129 | """
This scripts runs the interpretability experiments.
Dependencies:
- outputs/graphtrip/weights/
Outputs:
- outputs/graphtrip/grail/
Author: Hanna M. Tolle
Date: 2025-05-31
License: BSD 3-Clause
"""
import matplotlib
matplotlib.use('Agg') # Set non-interactive backend
import sys
sys.path.append("../")
import os... |
d223781553dad6a0bce1521ef80c09446be29053ce8efb2ddc5ee3dfe921d9f4 | Python | 5,416 | 150 | """Unit tests for src/datahandlers/clo.py (CLOgraph)."""
import io
import pyoxigraph
import pytest
from src.categories import CELL_LINE
from src.datahandlers.clo import CLOgraph
from src.prefixes import CLO
from tests.datahandlers.conftest import RDFS_NS, SKOS_NS, lit, make_graph_from_store, nn, quad
_CLO_NS = "htt... |
327028c1f3b836d23fe0aa07181d01873e45a0458a1cc9da27d35870f7c08d1b | Python | 5,419 | 146 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmseg.models.backbones import ERFNet
from mmseg.models.backbones.erfnet import (DownsamplerBlock, NonBottleneck1d,
UpsamplerBlock)
def test_erfnet_backbone():
# Test ERFNet Standard Forward.... |
5c37ce2887eed838225dc43940628fb455a4a41ea58cd72b88614eea846ebd0b | Python | 5,421 | 187 | """Test model IO with pickle."""
import os
import pickle
import subprocess
import numpy as np
import pytest
import xgboost as xgb
from xgboost import XGBClassifier
from xgboost import testing as tm
model_path = "./model.pkl"
pytestmark = tm.timeout(30)
def build_dataset():
N = 10
x = np.linspace(0, N * N... |
a2046f1285544bd2fd73f2df2398bf274d528276a64bbb9e2f7363992828a1a8 | Python | 5,421 | 193 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utility functions for downloading datasets from OSF
"""
import os
import re
from collections import defaultdict
from pkg_resources import resource_filename
import json
MATCH = re.compile(
r'space-(\S+)_(?:den|res)-(\d+[k|m]{1,2})_'
)
def _groupby_match(fnames):
... |
876dd53cd62911f2ca60cb80a1b84705e2dfcb4f48c8427b3d700d1b0c08d12d | Python | 5,425 | 152 | # Shared code used by Snakemake files
import gzip
import shutil
import src.util
logger = src.util.LoggingUtil.init_logging(__name__, level="INFO")
def duckdb_memory_limit_mb(mem_mb, fraction=0.75):
"""Convert a Snakemake `resources.mem_mb` value into a DuckDB memory limit in MB.
DuckDB otherwise auto-sizes... |
6e0be549dc37782105146402bc69fc98caad2214d167e3f3192857d6f49376dc | Python | 5,426 | 145 | # -*- coding: utf-8 -*-
from io import StringIO
import mock
from rest_framework.authtoken.models import Token
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase
from django.test.client import Client
from guardian.shortcuts import assi... |
91072bb0051a0ad4f580d85b13deb67faeef4913d641f3d1f6f66f379f629c92 | Python | 5,427 | 192 | # pylint: disable=invalid-name,unused-import
"""For compatibility and optional dependencies."""
import functools
import importlib.util
import logging
import sys
import types
from typing import Any, Sequence, cast
import numpy as np
from ._typing import _T
assert sys.version_info[0] == 3, "Python 2 is no longer suppo... |
6b58d8a42e1af3389dd14ca0cc3fc4e608c3af07d2173a5b183d8265ef716c8e | Python | 5,428 | 232 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
# the type of float to use throughout the session.
_FLOATX = 'float32'
_EPSILON = 1e-7
_IMAGE_DATA_FORMAT = 'channels_last'
def epsilon():
"""Returns the value of the fuzz factor used ... |
23b9624ce7fa66031fb3eac65b668a707f4a0017b469d52f49a428030427d767 | Python | 5,429 | 156 | from datetime import datetime
import os
from medperf.entities.interface import Entity
from medperf.entities.schemas import TrainingEventSchema
import medperf.config as config
from medperf.account_management import get_medperf_user_data
import yaml
from medperf.entities.utils import handle_validation_error
from medperf.... |
74341d64fc699ea18bab5d758a217b4f22cc57a71c5334214b9e32199ff84ee3 | Python | 5,429 | 136 | """Offline tests for the concord rows that ``build_sets()`` writes.
These cover the output-ordering guarantee that keeps concord files reproducible between
builds. ``tests/test_uber.py`` holds the live-endpoint UberGraph tests; everything here
stubs the endpoint out so it runs in the default (offline) CI pass.
"""
im... |
8e18182fd006b449d2e821d8e13caa40cf5ab1c1a7218980425391b1c2190c8a | Python | 5,429 | 113 | import csv
from os import listdir, path, rename
from zipfile import ZipFile
import requests
from src.prefixes import NCIT, UNII
from src.util import get_config
# Columns in Latest_UNII_Records.txt that, when populated, mark a UNII as a whole organism or
# crude organism-derived substance (a plant, animal, fungus, et... |
2fbfc0228096fbb7ba2c79269b172a73172dac106854cea2f6acae8b6b496834 | Python | 5,433 | 132 | from __future__ import annotations
from typing import Optional
from heudiconv.utils import SeqInfo
# Dictionary to specify options for the `populate_intended_for`.
# Valid options are defined in 'bids.py' (for 'matching_parameters':
# ['Shims', 'ImagingVolume',]; for 'criterion': ['First', 'Closest']
POPULATE_INTEND... |
56edc95448519c116ae26137a8612fdc28b0f293d6dd6e8a3d38caf6bd05c7dd | Python | 5,434 | 155 | import cv2
import os
import tensorflow as tf
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Input, Conv2D, BatchNormalization, Activation, MaxPool2D, Conv2DTranspose, Concatenate
from tensorflow.keras.models import Model
from tensorflow.k... |
bd952d1dc3c3b18a90b07060bb500d532effb7830cceecded52d9d4efe18e0e8 | Python | 5,436 | 139 | #!/usr/bin/env python
"""
MetaWIBELE: gene_abundance module
Get gene abundance for each sample
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software ... |
ea6fa26bfb1eb0a70ea6b9d822c5057b4407c8d27e1bad6f063c480b36581c28 | Python | 5,436 | 188 | # pylint: disable=too-many-locals
"""Tests for callback functions."""
import json
from itertools import product
from typing import Dict, List, Tuple
from ..callback import LearningRateScheduler
from ..core import Booster, DMatrix
from ..training import cv, train
from .utils import Device
def run_eta_decay(
tree... |
ae4abf8adbb8ddb39752845ba1055e7164186677bbb462e5264d38379735d74c | Python | 5,437 | 119 | """
List every UBERON term that cross-references more than one EMAPA term.
These are the cliques that decided whether `EMAPA` belongs in `anatomy_unique_prefixes`
(config.yaml). Restricting a prefix makes `glom()` refuse any merge whose union would hold two
identifiers sharing it, so each UBERON term below would have ... |
3b75629e6ea842beb3762f5b52b843e31d2485fae7e7503bbbdc4b773e66d610 | Python | 5,439 | 143 | from keras import backend
import tensorflow as tf
from keras.layers import Conv2D, BatchNormalization, ZeroPadding2D, ZeroPadding3D, Layer
from .utils import get_image_data_format
class Subpixel(Conv2D):
def __init__(self,
filters,
kernel_size,
r,
... |
6023a148dac0593c821ec78d98fc419faf7964aa19e11958aafe77dfa357bbd6 | Python | 5,439 | 149 | import mne
from scipy.signal import detrend
import sys, os
from tqdm import tqdm
from glob import glob
import numpy as np
import itertools
import pandas as pd
try:
from braindecode.preprocessing import exponential_moving_standardize
from braindecode import EEGClassifier
from braindecode.util import set_ran... |
772d2e360d6a446c1e0f70951c3af54b4c9fb5299331cdd5af06ef38f246ce73 | Python | 5,443 | 177 | #!/usr/bin/env python3
#
# Figure 4: Highlighted subgroups
#
import sys
import numpy as np
import matplotlib.pyplot as plt
import base
# Exclude ooocytes
nooocytes = True
# Gather data
print('Gathering data')
with base.connect() as con:
c = con.cursor()
qand = 'and cell != "Oocyte"' if nooocytes else ''
... |
d35bf4e851ddb14d1e9051d464a90fd834a33b7d31453a257876711737aab3b5 | Python | 5,445 | 142 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This script checks your database for some common
# inconsistencies or errors that may have arisen from
# past bugs.
# You may need to install psycopg2, e.g. with:
# sudo apt-get install python-psycopg2
# Requires the file .catmaid-db to be present in your
# home dire... |
04762143fbc38c0b6322e076144ba8a0186e90a0d750309b942480fbf67971b6 | Python | 5,447 | 149 | # Copyright (c) OpenMMLab. All rights reserved.
import hashlib
import logging
import os
import os.path as osp
import warnings
from argparse import ArgumentParser
import requests
from mmengine import Config
from mmseg.apis import inference_model, init_model, show_result_pyplot
from mmseg.utils import get_root_logger
... |
7768816030d475d50221d61dbb0049d571306d4b99085e8746d0cf52b93efbd9 | Python | 5,447 | 116 | """TensorBoard callback for training visualization.
This is the TF v2 version. A lot of the functionality
from the v1 version isn't currently supported (but will
likely be added back later).
The docstring is left unchanged
to avoid creating confusion on the docs website.
"""
from __future__ import absolute_import
fro... |
7a2d861e3f74bab78f8e6c3c966491dc40fb9142b6293d6e2468f552de59fe15 | Python | 5,448 | 199 | import numpy as np
from n2v.utils import n2v_utils
from n2v.utils.n2v_utils import tta_forward, tta_backward
def test_get_subpatch():
patch = np.arange(100)
patch.shape = (10, 10)
subpatch_target = np.array([[11, 12, 13, 14, 15],
[21, 22, 23, 24, 25],
... |
ddd296531f93794d2a7c1987d04943471f85eb0beb12bc5ff0953d67ecc9d699 | Python | 5,448 | 96 | # %% libraries
import os, glob, re
import shutil
import gzip
from os.path import join
from nilearn import image, plotting, masking
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import itertools
import pathlib
import argparse
# %%
# load fieldmap ____________________________... |
5fe8796ab3117be4e2b4d6596281a0929b612a15b3fbbeba09278e91e75d9cb2 | Python | 5,450 | 173 | import os, sys, time
from datetime import datetime
from inspect import stack as __call_stack
from builtins import print as __builtinprint
__version__ = "0.0.1"
CONFIG = {
"tempfolder" : "/tmp/",
"clear" : True,
"verbose" : False,
"usegpu": True,
"debug" : False,
"reportdatetime": False
}
class confi... |
693d21e7bae332a0408a11941e3d144110168884b02fb88afd11aa31354bcab6 | Python | 5,450 | 139 | """This is a beta-version of harmonic-percussive source separation.
Currently it only returns the separated magnitude spectrograms. Once we have inverse-STFT,
we can extend it to get waveform results.
TODO: add test
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class HPSS(nn.Module):
"""... |
5082e0cd2d915c9660218f08529fa2f836e4abd0b840847f99f41bbcf87b7e25 | Python | 5,455 | 148 | import sys, os
from tqdm import tqdm
from glob import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# go to base directory and import globals
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#ptmp_dir = "/ptmp/kroma/m4d/"
os.chdir(base_dir)
sys... |
309448cdf657459a050662a4fc4c58e350a8af6b0cbc5af288903d8ee7828a59 | Python | 5,458 | 151 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# pyre-strict
# pyre-ignore-all-errors[2,33]
from collections import defaultdict
from typing import Any, Counter, DefaultDict, Dict, Optional, Tuple, Union
import torch.nn as nn
from torch import Tensor
from .jit_analysis import JitModelAnalysi... |
0cbc88e59987f95789a904a978f6a024a66b6a12fd83f655ee63b17d5fd76178 | Python | 5,460 | 203 | # src/zndraw_joblib/exceptions.py
"""RFC 9457 Problem Details for HTTP APIs."""
import re
from typing import ClassVar, NoReturn
from fastapi import Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
def _camel_to_kebab(name: str) -> str:
"""Convert CamelCase to kebab-case."""
... |
ca4af88e4afbebe183dfd2891e5b452d89e0aca54f059da1a67eb92ab68646cf | Python | 5,461 | 154 | from rest_framework import status
from medperf.tests import MedPerfTest
from parameterized import parameterized, parameterized_class
class BenchmarkTest(MedPerfTest):
def generic_setup(self):
# setup users
bmk_owner = "bmk_owner"
prep_mlcube_owner = "prep_mlcube_owner"
ref_model_... |
ff2a493b194e15fbaa3c2d541624f56fa522b2083f31367c7bb516496609a342 | Python | 5,461 | 155 | import numpy
import matplotlib.pyplot as plt
try:
import cPickle as pickle
except:
import pickle
import gzip
import math
import os
import json
import collections
import quantities
from quantities import mV, nA, ms, V, s
amps = numpy.arange(0,1.65,0.05)
num_AP_min=13
num_AP_max=82
data_dict=collections.Orde... |
3051b4cfffea19104064cf7c56b8b49f70dc26eaab431c83deaac29546d1f09b | Python | 5,464 | 140 | from sklearn.metrics import homogeneity_score
from sklearn.metrics import completeness_score
from sklearn.metrics import v_measure_score
from sklearn.metrics import adjusted_rand_score as ARI
from sklearn.metrics import normalized_mutual_info_score as NMI
import numpy as np
import pandas as pd
import os
import sys
imp... |
cf0452d0759e3ef087c63b093b584c7415d5ea7dd2ef0818815f6a1f87778df4 | Python | 5,468 | 145 | from rest_framework import serializers
from django.utils import timezone
from django.conf import settings
from .models import Benchmark
from .utils import resolve_committee_member_emails
class BenchmarkSerializer(serializers.ModelSerializer):
committee_member_emails = serializers.ListField(
child=serializ... |
7dffbc1be159bc48acdfd363c618711bcbd88f72c7ecd5e4aad2dc1830de264c | Python | 5,470 | 146 | from __future__ import annotations
import torch
from torch import Tensor, nn
from chgnet.model.basis import Fourier, RadialBessel
class AtomEmbedding(nn.Module):
"""Encode an atom by its atomic number using a learnable embedding layer."""
def __init__(self, atom_feature_dim: int, max_num_elements: int = 94... |
f8d849526ac842f1e003a62e197bdd207d21eb10795864f5f862fdf2bd0a2ac5 | Python | 5,473 | 129 | import numpy as np
import matplotlib.pyplot as plt
import hickle as hkl
from sklearn.decomposition import PCA
import os
from sklearn.linear_model import LogisticRegression
from grid_cell.grid_cell_processor import Speed_Processor
from grid_cell.locf_grid_cell import compute_locf # locf is also called as lca
from grid_c... |
b061f15dd87004bb1adcac894a88b25b370bcad9ff9548f4e53235c63e9ca25b | Python | 5,475 | 161 |
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "1" # Dual GPU
import tensorflow as tf
from keras import layers, models
from tensorflow.python.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras.optimizers import Adam
from tensorflo... |
66ff4dafcff6a09c4a5324cb3560a8fd37058e4c6b400e3e7950c962168ebb86 | Python | 5,477 | 148 | import torch
from preprocess import preprocess_adj, preprocess_adj_sparse, preprocess, construct_interaction, \
construct_interaction_KNN, add_contrastive_label, get_feature, permutation, fix_seed
import time
import random
import numpy as np
import sys
sys.path.append('/home/luxin1/stGRL')
from model impo... |
0099bdeaa122c2f0c9e150de1d54575828168e5dfc1e54d8f38c0dad7111040e | Python | 5,478 | 123 | # -*- coding: utf-8 -*-
import json
from urllib.parse import urlencode
from .common import CatmaidApiTestCase
class DatastoresApiTests(CatmaidApiTestCase):
def test_client_datastores(self):
url = '/client/datastores/'
response = self.client.get(url)
self.assertEqual(response.status_code, ... |
a55c3887ee928bd77e2230ee7606ece8cdc539a3258458724117ce1eca8fe827 | Python | 5,482 | 140 | #!/usr/bin/env python
# Author: Jonathan Meyer
# Simplified from logic developed by Alexey Vasiliev
# https://github.com/le0pard/pgtune/blob/master/source/javascripts/pgtune.coffee
from collections import OrderedDict
from distutils.util import strtobool
from os import getenv
import math
import shutil
INSTANCE_MEMOR... |
7ca8e59779c2c61aff9ecf27c79ff92064d1b03b77655c2bb6dab41702f56c30 | Python | 5,487 | 186 | """Utility and system routes.
Handles version, global settings, health checks, and other system endpoints.
"""
import json
from fastapi import APIRouter
from pydantic import BaseModel
import zndraw
from zndraw.broadcast import broadcast_to_room
from zndraw.config import SettingsDep
from zndraw.dependencies import (... |
af7ab4bcbbc77c6b4267b5d7c70835fbd104dbdedc0743c711cab7cdf51f932c | Python | 5,487 | 133 | import pandas as pd
data = pd.read_csv(
'./results/eval_1000cs_70tr_PublicPST_1000_13_algos_100_exp_2024_07_30_508748/data.csv')
data2 = pd.read_csv(
'./results/eval_1000cs_70tr_PublicPST_1000_1_algos_100_exp_2024_07_30_392080/data.csv')
# concatenate the dataframes
data = pd.concat([data, data2], axis=0)
#... |
3fb69b3935d0df87c97cb6c63cf8ddf13fbe5850a1c120ae55b57cc889e91fbe | Python | 5,491 | 184 | """Test functions."""
import atexit
import contextlib
import io
import json
import os
import shutil
import subprocess
import sys
from collections.abc import Generator, Mapping
from contextlib import ExitStack
from importlib.resources import as_file, files
from pathlib import Path
from typing import Any
import pytest
... |
87c0bea1a4795bf7b3082467753219b9759bc0156770ea83e3655e470222f411 | Python | 5,496 | 207 | """Admin REST API endpoints for user management and server control.
All endpoints require admin privileges via AdminUserDep.
"""
import asyncio
import os
import signal
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Query
from pydantic import BaseModel, ConfigDict
from sqlmodel impo... |
687ee2259740f1cc6e0fc2e0437921bf0983d60774693249cd34ff305f95f772 | Python | 5,498 | 141 | import scanpy as sc
import numpy as np
import pandas as pd
import h5py
###
###
### reading expression data
###
###
filename = "ppfctx_snRNAseq_processed_data_2024_05_16.h5seurat"
with h5py.File(filename, "r") as f:
cols = np.array(f["assays"]["RNA"]['features'])
indices = np.array(f["cell.names"])
age_l... |
b230b77a4da5da7f06879cec9828401788b0ff78f244d8d31b94206bec1669e8 | Python | 5,508 | 150 |
# This script produces Fig 3b of the paper "Model mimicry limits conclusions about neural tuning and can mistakenly imply unlikely priors"
# It generates the output of the perfect cube model as describe in "Orientation Decoding in Human Visual Cortex: New Insights from an Unbiased Perspective" (2014)
import numpy as ... |
07358cb7f58ec3788e88ff4e6415f8a9d628a3963529d6e2c915494a5347c8e2 | Python | 5,509 | 169 | # 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
import torch
from torch import nn, Tensor
from sam2.modeling.sam.transformer import RoPEAtte... |
3177aea4611869568d0477ecbe5685711fb1e3ce8d56cf11295ba32e31303409 | Python | 5,509 | 143 | # pytest unit tests for spinalcordtoolbox.register.algorithms::find_angle_hog
from math import degrees
import numpy as np
from scipy.ndimage import center_of_mass
from skimage.transform import rotate
from spinalcordtoolbox.image import Image
from spinalcordtoolbox.registration.algorithms import normalized_sobel, wei... |
f130237144abbf7f35e1f71580299c0ccd04b8a7c808c90d4df9cb989733baab | Python | 5,509 | 171 | from torch import nn
from nnfabrik.utility.nn_helpers import set_random_seed, get_dims_for_loader_dict
from neuralpredictors.utils import get_module_output
from neuralpredictors.layers.encoders import FiringRateEncoder
from neuralpredictors.layers.shifters import MLPShifter, StaticAffine2dShifter
from neuralpredictors... |
549f3226b2c996bbf4adb28be2e70418dda12fe2272773f2aa1e0e359873bf13 | Python | 5,513 | 186 | #!/usr/bin/env python
# coding: utf-8
# ## 1. Image Processing to generate binary image
import numpy as np
import matplotlib.pyplot as plt
from skimage.filters import threshold_local
from PIL import Image
import cv2
import pandas as pd
import imutils
import argparse
import math
import os
ap = argparse.ArgumentPars... |
a902e7ba0bf7ec9dbb007407db96ef64d655f9be9db055a1fe6e99c1c3477906 | Python | 5,513 | 137 | '''
Note: this is a bizarre test due to the fact that scoop can't be started from
within python:
https://github.com/soravux/scoop/issues/29
Therefore, the way this works is for the test_ that's detected by nt then
creates a subprocess that runs scoop using the normal command line arguments
It then captures the output... |
899b55456db496f63c395476a196edad82e65eaf1121c8a8677c9b5fa77d6d73 | Python | 5,521 | 187 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
0413033cd3b85a7d21b39d77b41497084ffc764ee115d7c817e19041ce96cb2a | Python | 5,522 | 145 | import logging
import pathlib
import ase
import ase.io as aio
import numpy as np
import torch
import typer
from rdkit import Chem
from simgen.utils import setup_logger
from models.bond_predictor import BondPredictor
from models.scaffolded_model import ScaffoldedMolDiff
from utils.data import traj_to_ase
from utils.re... |
311aa5bcbd8276ad5efcaa09ad3e81b20d8ab0b7ad34228c876db88e4f4172ac | Python | 5,525 | 164 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 9 08:59:48 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
from ..data.handlers.particle_image_preprocessor import \
Partic... |
473a661df45a729981f6876201c8921f2cf0f42a41bcc7e6c4e96a60c4bb8ca3 | Python | 5,525 | 154 | """Frame-dimension aggregation: correct, and no longer capped at 512 frames.
The aggregation kernel used to stage each grid point's time series into a
``float tmp_array[MAX_FRAME_NUMBER]`` per thread. That array was the frame
limit: past it, ``marching_observer`` raised and ``density_flow`` silently
aggregated only th... |
bc967474af544ea2611a128865b606daf41317823fd389165b9c7485bf2bc0c0 | Python | 5,525 | 134 | # SPDX-License-Identifier: BSD-3-Clause
# BSD 3-Clause License
# Copyright (c) 2017,
# 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 copy... |
c94f15ab68fc8df75595710346cf0f4fc0b30a686573d259526112eaaa16e35d | Python | 5,526 | 133 | # please run fit_torus_speed_cov.py first to obtain the g-covnet model
import os
import numpy as np
import matplotlib.pyplot as plt
import hickle as hkl
from grid_cell.gpr_covnet import GPR_CovNet, save_gpr_covnet_all, load_gpr_covnet_all
from grid_cell.manifold_fitter import label_mesh
import grid_cell.ploter as plote... |
260760448578fe4b0159b26d424bf72d1fd7b937cfc891ca817faa1267a3d2c6 | Python | 5,532 | 230 | #!/usr/bin/python
import sys, subprocess
import re
from argparse import ArgumentParser, FileType
from collections import defaultdict, Counter
flag_include_N = True
"""
"""
def read_genome(genome_file):
chr_dic = {}
chr_name, sequence = "", ""
for line in genome_file:
if line.startswith(">"):
... |
43780a89fe58ac550ee63210766d579e9e9f2a3ee75deba62870f869d30d1a0c | Python | 5,532 | 183 | #!/usr/bin/env python
# coding=utf-8
# Copyright 2023 Statistics and Machine Learning Research Group at HKUST. All rights reserved.
"""
The finetuning of each epoch will be splitted into `--num_stages_per_epoch`
stages, where each stage will restart finetuning and continuously train from
the finetuned model of previous... |
577357d2132af711027a9c19bb3e8d1e66935dd7b72c6633b17610b7c3bd185f | Python | 5,532 | 102 | # This script takes in a command line args for the exc/inh ratio
# in the hidden layer
from surrogateParams import surrParams
import simLogger
import argparse
import surrogateTraining
from weightAnalysis import getWeightFromUniqueId
# collect command line args (all have defaults)
parser = argparse.ArgumentParser(desc... |
fc069d3ca7efaeca4a1e2106ecd9593e791586862d3ddb285e2aabf974cf7469 | Python | 5,532 | 170 | import argparse
import os
import random
import logging
from datetime import datetime
from time import perf_counter as t
import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
import dgl
from torch.utils.data import DataLoader
from const import *
from Cell.model import GATEncoder, Cell... |
6ee6fd02a3552e1d9d54a8740125838ae9490eee338d4929cfb7861d793661ee | Python | 5,533 | 152 | import os
import numpy as np
import SimpleITK as sitk
import json
def check_image_dims(path):
base_size = np.array([240, 240, 155])
base_spacing = np.array([1.0, 1.0, 1.0])
image = sitk.ReadImage(path)
size_array = np.array(image.GetSize())
spacing_array = np.array(image.GetSpacing())
assert ... |
916c9025ba67ff33abf08fd9beddee4f1734fbe23250e010f5222a4c693864fb | Python | 5,533 | 153 | # from https://gist.githubusercontent.com/wckdouglas/3f8fb27a3d7a1eb24c598aa04f70fb25/raw/a9f019ae71f7ae46d576b2c4603a8123753b29eb/py_deseq.py
import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri, numpy2ri, Formula
numpy2ri.activate()
pandas2ri.activate()
from rpy2.robjects.packages import importr
des... |
b23d152fc8a3776678af23dc76a389e43b7de4c858cf8f8f7b77f6cb806c89a3 | Python | 5,534 | 147 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# pyre-strict
import itertools
import math
import unittest
import torch
import torch.nn as nn
from fvcore.nn.weight_init import c2_msra_fill, c2_xavier_fill
class TestWeightInit(unittest.TestCase):
"""
Test creation of WeightInit.
... |
67cbf28f4f3533a387dd00f03e29167c993defc6a3f9a717d7910054fb4d7f23 | Python | 5,537 | 146 | from sklearn.metrics import homogeneity_score
from sklearn.metrics import completeness_score
from sklearn.metrics import v_measure_score
from sklearn.metrics import adjusted_rand_score as ARI
from sklearn.metrics import normalized_mutual_info_score as NMI
import numpy as np
import pandas as pd
import os
import sys
imp... |
967dda990ce67682b92e3daf7bec9388528560b14df9b297f78da5e8b85ee468 | Python | 5,537 | 142 | import os
from rano_monitor.constants import BRAINMASK, BRAINMASK_BAK, DEFAULT_SEGMENTATION
from rano_monitor.utils import (
finalize,
is_editor_installed,
review_brain,
review_tumor,
brain_has_been_reviewed,
tumor_has_been_finalized,
)
from textual.app import ComposeResult
from textual.contain... |
a641fda9a3362b937574ef30e54a6e2ea489777eda279f21e5afa9743113265f | Python | 5,538 | 158 | """Module used to provide a simple API to a database in which the results are stored."""
import re
import pandas as pd
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import bindparam
from sqlalchemy import create_engine
from sqlalchemy import insert
from sqlalchemy import schema
from sqla... |
53c21597150e32a3475725b6a3c2a30ae04eaf6d520a1d26dc4e39e337a5451a | Python | 5,541 | 159 | import json
from tqdm import tqdm
import os
import re
import argparse
mask_token='[MASK]'
label_mask='__'
def load_schema(train_answer,dev_answer):
with open(train_answer,'r',encoding='utf-8') as f:
train2id = json.loads(''.join(f.readlines()))
with open(dev_answer,'r',encoding='utf-8') as f:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.