sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
403749a2d978ce386a00385a416f654cded47cc0fd1f48f91a191e1d09a7c48e | Python | 1,504 | 52 | from model.builders.builders import build_simple
import os
filename = os.path.basename(__file__)
data ={'type': 'manual_label' , 'params': {'outcome': 'progression'}}
pre = {'type' : None}
vocab_size = 20000
report_max_length = 1000 # number of words per report
embedding_dims = 150
filters = 250
kernel_size = 3
hidden... |
535a8ec0738c479347c2e591435aa364ee43282fe88151c4853b11960bf0fe7d | Python | 1,504 | 52 | # Copyright (c) OpenMMLab. All rights reserved.
import collections
from mmcv.utils import build_from_cfg
from ..builder import PIPELINES
@PIPELINES.register_module()
class Compose:
"""Compose multiple transforms sequentially.
Args:
transforms (Sequence[dict | callable]): Sequence of transform objec... |
21a95363bd91eb79cbfa59fd6f6efa13ea7c6f6101e7284df999312d0851acdb | Python | 1,506 | 49 | import numpy as np
import pandas as pd
import typing
from matplotlib_setup import plt, colors,get_figure_size
def fit_scatter(y_true: pd.Series, y_pred: pd.Series, true_label: str, pred_label: str, title: typing.Optional[str],
without_description: bool = False):
import matplotlib.colorbar
# r... |
acb12c2d6bc480ce4971ee3dcff2862cd354f150c833a5c259ceff3c29ff243a | Python | 1,506 | 47 | # Copyright (c) OpenMMLab. All rights reserved.
# This file add snake case alias for coco api
import warnings
import pycocotools
from pycocotools.coco import COCO as _COCO
from pycocotools.cocoeval import COCOeval as _COCOeval
class COCO(_COCO):
"""This class is almost the same as official pycocotools package.
... |
20b97d97e8ea0574288222c70dfd3b100570558d4dccaf54f33a94da31db4538 | Python | 1,507 | 37 | import numpy as np
class Padding:
def __init__(self, load_size, training=True):
"""
Padding the image: C x H x W, if H or W less than load_size, and will keep the overflow side.
"""
# TODO: Not just support static filling of the padding, but also mirror, etc...
if isinstan... |
67863a9344e72c7915e7128050199fbef72dd8e3a9e3ec88294e809a40623ee4 | Python | 1,507 | 48 | # Copyright (c) OpenMMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
from mmcv.runner import BaseModule
from ...builder import build_loss
class BasePanopticFusionHead(BaseModule, metaclass=ABCMeta):
"""Base class for panoptic heads."""
def __init__(self,
num_things_class... |
c1fd3320bd44c0fb0a591e1e0799da3a57d5cc4b73678ceb02f00800988a98bc | Python | 1,511 | 48 | #!/usr/bin/env python
# Copyright [1999-2017] EMBL-European Bioinformatics Institute
#
# 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
#
# Unl... |
940a5a8b1e11fa06583214710b4863725c47404d99898636294215c942bc2c84 | Python | 1,514 | 51 | # coding: utf-8
"""LightGBM, Light Gradient Boosting Machine.
Contributors: https://github.com/lightgbm-org/LightGBM/graphs/contributors.
"""
from pathlib import Path
# .basic is intentionally loaded as early as possible, to dlopen() lib_lightgbm.{dll,dylib,so}
# and its dependencies as early as possible
# isort: sp... |
bffc514753554cc0f5c4b73477e96377ff71f760b11351fd459863ea68fecbdb | Python | 1,514 | 33 | import shutil
import os
from A_config import a10_config
import manager_0_user_params as upar
if __name__ == '__main__':
"""
Main function getting outputs once condor has terminated
Files are zipped and copied here on bdap: /mnt/cidstorage/cidportal/data/cid-bulk22/Shared/tmp/projectData/ML4CAST/
In the... |
2ff38beae8b8a31ea31af15cd7deda03e40c51da3fc72720ac86fccc2d5e33a2 | Python | 1,515 | 52 | from model.builders.builders import build_simple
import os
filename = os.path.basename(__file__)
data ={'type': 'manual_label' , 'params': {'outcome': 'any_cancer', 'text':'NARR'}}
pre = {'type' : None}
vocab_size = 2000
report_max_length = 500 # number of words per report
embedding_dims = 150
filters = 250
kernel_siz... |
250e01104feace09a3f755fc1d30a152df124179f11ebb3a036fc946a4a85c27 | Python | 1,518 | 33 | import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesClassifier
from metstab_shap.config import utils_section, csv_section
from metstab_shap.config import parse_data_config, parse_representation_config, parse_task_config
from metstab_shap.data import load_data
# load data (and change to class... |
07131fda4bf34fdd87944c0563d37428c8e419685af4f7469b23781cc2519829 | Python | 1,527 | 44 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
from scipy.ndimage.filters import gaussian_filter1d
from scipy.signal import medfilt
from .builder import FILTERS
from .filter import TemporalFilter
@FILTERS.register_module(name=['GaussianFilter', 'gaussian'])
class GaussianFilter(TemporalFilter):
... |
1585d3694977eb4dc89ba6c35c4c5d43035e18118d57c93f86976b64f24850ad | Python | 1,529 | 58 | import os.path
import random
import sys
import cv2
import h5py
import numpy as np
import scipy.ndimage as ndimage
from PIL import Image
from data.base_dataset import BaseDataset, get_params, get_transform
from data.brats1db_dataset import Brats1dbDataset
from data.brats_dataset import BratsDataset
from data.fsl1db_da... |
52e31df90643643b19520d65b756e38051b1fa9b65c8202b060f8da9faa0e225 | Python | 1,532 | 74 |
'''
Convert Canvas output to a common format
'''
import myvcf
import SV
import os
import sys
import re
class Canvas:
@staticmethod
def doparse ( canvas_data ):
# Y 59020307 Canvas:GAIN:Y:59020308-59028273 N <CNV> 2 q10;L10kb SVTYPE=CNV;END=59028273;CNVLEN=7966 RC:BC:CN:MCC 364:6:7:5
E=canvas_data
#if type (ca... |
41f77137ebb519b33b6edac40ade2c9674a8a95eb556288b3116b649f683d685 | Python | 1,534 | 52 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Tomoki Hayashi
# 2023 Jiatong SHi
# Adapted from espnet/espnet/net/pytorch_backend/duration_predictor.py
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Duration predictor related modules."""
import torch
class DurationPredict... |
513e28a451385e689c2109130c6985c1e478098f2eba4b5c675a4a1e5b03d58c | Python | 1,535 | 47 | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.utils import Registry, build_from_cfg
TRANSFORMER = Registry('Transformer')
LINEAR_LAYERS = Registry('linear layers')
def build_transformer(cfg, default_args=None):
"""Builder for Transformer."""
return build_from_cfg(cfg, TRANSF... |
552500756503d782d87cb5d860d5f86cb20034bb2a55573ed7737279c83a226e | Python | 1,538 | 51 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Unit tests for Octave """
import numpy as np
from numpy.testing import assert_allclose
from oct2py import octave
import pytest
import scipy
from pystoi.stoi import FS, N_FRAME, NFFT
from pystoi.utils import resample_oct
ATOL = 1e-5
def test_hanning():
""" Compare... |
d7b69476b6f1bae293de48ae8578a2379b23a863cf8dd3ba9fbc7bed13b343bd | Python | 1,538 | 40 | from enum import Enum
class SiteClassificationType(Enum):
parsimony_informative = "parsimony-informative"
constant = "constant"
singleton = "singleton"
other = "other"
def determine_site_classification_type(
character_counts: dict,
) -> SiteClassificationType:
"""
Determines if a site is... |
e18d3d16252bd06547c100996d4b727deb058cb691b613cdae20aea6e858872d | Python | 1,538 | 41 | from torchmdnet.priors.base import BasePrior
import torch
from torch import nn
from pytorch_lightning.utilities import rank_zero_warn
class Atomref(BasePrior):
r"""Atomref prior model.
When using this in combination with some dataset, the dataset class must implement
the function `get_atomref`, which retu... |
71f957f5af9d3a0219d954e0f3f17013271e2b2edbdfd7ba82eb68493b58589c | Python | 1,539 | 56 | from multiprocessing import cpu_count
from clipkit.clipkit import determine_effective_threads
from clipkit.modes import TrimmingMode
def test_effective_threads_respects_single_thread_request():
effective = determine_effective_threads(
requested_threads=1,
mode=TrimmingMode.kpi,
n_sequence... |
d47963462bd9c8a0c55b16ce61bf5a31ca30b1972dd3ef48878b9bf3b866cabd | Python | 1,539 | 34 | #!/usr/bin/env python
import CNVworkflowlib
import argparse
####################################
### Parse command-line arguments ###
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("algorithm_CNV_filename", type=str)
parser.add_argument("benchmark_CNV_fil... |
1494671dfd7afea5cb9b605c94e18b38263ac85869ff9d34ab7bdfa951d673a2 | Python | 1,541 | 58 | import os.path
import random
import sys
import cv2
import h5py
import numpy as np
import scipy.ndimage as ndimage
from PIL import Image
from data.base_dataset import BaseDataset, get_params, get_transform
from data.brats1db_dataset import Brats1dbDataset
from data.brats_4ch_dataset import Brats4chDataset
from data.br... |
b594861ab63d66cea795f47e334d1820b0e355949e9b14ea4d0a7e45744a9987 | Python | 1,542 | 38 | import cv2
import numpy as np
def contour(contours, hierarchy):
contour = list()
hierarchy = hierarchy[0]
for component in zip(contours, hierarchy):
currentContour = component[0]
currentHierarchy = component[1]
#x,y,w,h = cv2.boundingRect(currentContour)
if current... |
a9a0c22dcdc49ed6f91a2fe784980df7b2909be5656fbebad22cdb6da2138dd5 | Python | 1,547 | 53 | import pytest
import eagerpy as ep
from foolbox import accuracy
from foolbox.attacks import (
LinfBasicIterativeAttack,
L1BasicIterativeAttack,
L2BasicIterativeAttack,
)
from foolbox.models import ExpectationOverTransformationWrapper
from foolbox.types import L2, Linf
from conftest import ModeAndDataAndD... |
46a88ac06f8d88eb0ed71190427ec5d5f7f150eb00a39c4bc8201fd3158a048b | Python | 1,548 | 64 | """Command-line interface for daart video model pre-training package."""
import logging
import sys
from argparse import ArgumentParser
from daart.cli import formatting
from daart.cli.commands import COMMANDS
def build_parser() -> ArgumentParser:
"""Build the main argument parser with all subcommands."""
pa... |
8301e5758b7eb959081fbc9be25dd9dca6c034334100c5b06c40868190a26a1d | Python | 1,549 | 52 | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import xml.etree.ElementTree as ET
import mmcv
from .builder import DATASETS
from .xml_style import XMLDataset
@DATASETS.register_module()
class WIDERFaceDataset(XMLDataset):
"""Reader for the WIDER Face dataset in PASCAL VOC format.
Con... |
2aa02c86cae3c838e3f4259baa70015f947135fdaea84eb48929216c80316f9d | Python | 1,550 | 46 | """This module contains unit tests for general functions in
:mod:`~prody.dynamics.analysis`, i.e. ones that are not tied to a
particular model or to a more specific test module."""
import numpy as np
from prody import calcCollectivity, LOGGER
from prody.tests import unittest
LOGGER.verbosity = 'none'
class TestCal... |
4a594cac05747cd2f8e42c21be7b6c2cfa30ec938e3aec28ac4d9aa3f572dc98 | Python | 1,550 | 56 | import xarray as xr
import numpy as np
import rasterio
from rasterio.transform import from_bounds
import os
nc_file = r"V:\asap\asap_analysis\AgERA5\Precipitation flux\2025\Precipitation-Flux_C3S-glob-agric_AgERA5_20250625_final-v2.0.0.nc"
output_tif = r"V:\asap\asap_analysis\ERA5 from C3S\agERA5\Daily_Precipitation-F... |
7839ef64953850477470afa8867147fd251847e8300325449fb027213c4905dd | Python | 1,551 | 43 | #!/usr/bin/env python
# -*- coding: UTF-8 -*import numpy as np
import tensorflow as tf
# A Control instance stores most of the configuration information.
class Control:
def __init__(self):
self.data = None
self.workers = 4
self.coarsen_to = 500 # 1000
self.coarsen_level = 2 #
... |
8c4170718f509d42e24768f4e764bcdd2a45a4ff16aad7ea5632246d4cda45e5 | Python | 1,554 | 50 | ''' adapted from https://github.com/all-umass/ManifoldWarping '''
import numpy as np
import scipy.spatial.distance as sd
from sklearn.metrics.pairwise import euclidean_distances
'''Distance functions, grouped by metric.'''
class Metric(object):
def __init__(self, dist, name):
self.dist = dist # dist(x,... |
91eaf5b79b7d7017cbfbe7831560d1390b2eda5eb84f8438bad73fd310d3803b | Python | 1,556 | 45 | import gensim, logging, spacy, os
import utils
from doc_reader import FileIterDocs, QueryResultDocs
def train_word2vec(doc_ids, doc_path_template, model_file):
docs = FileIterDocs(doc_ids, doc_path_template)
model = gensim.models.Word2Vec(docs)
model.save(model_file)
print 'model trained & saved'
... |
123f6b63624ccedf6182f3a1eccf97ef87c439cd9fb09f54f1cc8b02e411ce90 | Python | 1,560 | 38 | import numpy as np
import pandas as pd
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import Normalizer
from tpot.export_utils import set_param_recursive
from metstab_shap.config import utils_section, csv_section
from metstab_shap.config import parse... |
bd6bef7f22eadcf624a2f5c70b174c4aa4e23e4b6c8d4b5c410b4aacaed42c3b | Python | 1,562 | 62 | # Copyright (C) 2022-2025 ETH Zurich, Niels Maeder and other DASH contributors.
class ExtractionError(Exception):
"""
Error thrown if Feature extraction did not work properly.
Called by Extractor.check_final_csv()
"""
def __init__(self, message: str) -> None:
"""
Args:
... |
c27a354f47475bf0c248013e7f80e0ee12de1b8d129dc0206bc1144a02f24ed2 | Python | 1,562 | 44 | from model.builders.builders import build_full_network
import os
filename = os.path.basename(__file__)
vocab_size = 500
data ={'type': 'manual_label' , 'params': {'outcome': 'progression'}}
pre = {'type' : None}
# mode = {'count', 'freq', 'tfidf', 'binary'}
features = { 'type' : 'keras_tokenizer', 'parmas': {'mode': ... |
48c00555c08764453a0640a3aa8312bb3e9a53a8fd385edb30e5875cf96f201e | Python | 1,563 | 53 | import sys
sys.path.append("./")
import time
import traceback
import os
import gc
import time
import traceback
import pandas as pd
from helpers.parallel_process_old import ParallelProcess
# https://github.com/AllenInstitute/AllenSDK/issues/1436#issuecomment-610082420
from allensdk.brain_observatory.ecephys.ecephys... |
c57e927787f4359335763c975869f07130fe4544a7854209dc64b83738ec84f9 | Python | 1,563 | 51 | from typing import Dict, List, Tuple
from Bio.Align import MultipleSeqAlignment
import torch
class SelfSupervisedCompose:
"""
Composes several transforms together.
similar to torchvision.transforms.Compose.
"""
def __init__(self, transforms: List[object]) -> None:
"""
Initializes ... |
68c2aa4efa42a527eac820d92d51e94a39779d1e26595158c2a02b891c49998c | Python | 1,566 | 47 | import torch
import torch.optim as optim
import numpy as np
import itertools
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
class get_opt... |
031ce28074a80a8989e301362d6d757ff28e0d32d68eb9c1f6cac137c01e4dda | Python | 1,574 | 53 | from model.builders.builders import build_simple
import os
filename = os.path.basename(__file__)
data ={'type': 'manual_label' , 'params': {'outcome': 'any_cancer', 'text':'IMPRESS'}}
pre = {'type' : None}
vocab_size = 2000
# report_max_length = 1000 # number of words per report
report_max_length = 150 # number of wor... |
c6d5c524f5faebe94f035851e70bd21c54957683e4bd3123976d246a4951633f | Python | 1,574 | 53 | from model.builders.builders import build_simple
import os
filename = os.path.basename(__file__)
data ={'type': 'manual_label' , 'params': {'outcome': 'any_cancer', 'text':'IMPRESS'}}
pre = {'type' : None}
vocab_size = 2000
# report_max_length = 1000 # number of words per report
report_max_length = 500 # number of wor... |
26190eb710810376307de43c5c0bdc16e0ad1100c6648e9eb4aaeb1e56e83cc0 | Python | 1,575 | 61 | # This script shows how to use the Atomic Simulation Environment Calculator (ASE)
# inferface of TorchMD-Net with an AceFF model
import time
import sys
import ase
from ase.io import read
from torchmdnet.calculators import TMDNETCalculator
# The AceFFs models are available from HuggingFace under an Apache2.0 license
fr... |
e2d049cd41159a54c7faa4c17f1af6a3c7e80f47dffe936984d8526ae2abb2b3 | Python | 1,575 | 53 | from model.builders.builders import build_simple
import os
filename = os.path.basename(__file__)
data ={'type': 'manual_label' , 'params': {'outcome': 'any_cancer', 'text':'IMPRESS'}}
pre = {'type' : None}
vocab_size = 2000
# report_max_length = 1000 # number of words per report
report_max_length = 1000 # number of wo... |
cea5f21d8d718aa1c81600f0391f10180a349b0ddcb4ef144521e558de75da25 | Python | 1,576 | 48 | import pathlib
import re
import zipfile
# Alias string as UUID so we can specify types more clearly
UUID = str
# Alias string as FileName because that's what some strings mean
# FileNames are not path objects - just strings that describe paths
FileName = str
def get_root_uuid(zf: zipfile.ZipFile) -> UUID:
"""
... |
d84387d29fd97184066cdd179b68a1c7bad3a88c0c333892069cc69b68233f6f | Python | 1,576 | 67 | import numpy as np
import torch
from PIL import Image
class Normalize(object):
"""Normalize a tensor image with mean and standard deviation.
Args:
mean (tuple): means for each channel.
std (tuple): standard deviations for each channel.
"""
def __init__(self, mean=(0., 0., 0.), std=(1., 1., 1.)):... |
cf6e751cd8e856bf04a9f2e1e614f6b4964c86878e1135eadb654cf127833ca3 | Python | 1,577 | 44 | # import numpy as np
from .common_func import crop
class CenterCrop:
"""
Crop the 2D numpy [c, h, w] and mask [h, w] in a sample
"""
def __init__(self, output_size, padding=0, training=True):
assert isinstance(output_size, (int, list))
if isinstance(output_size, int):
self.... |
d3fe771a29583f7956757ee62ca7369104bdc3eb4af570a64089b9916b80ada2 | Python | 1,577 | 44 | from model.builders.builders import build_full_network
import os
filename = os.path.basename(__file__)
vocab_size = 500
data =[{'id':'response','type': 'manual_label' , 'params': {'outcome': 'response'}}]
pre = {'type' : None}
# mode = {'count', 'freq', 'tfidf', 'binary'}
features = { 'type' : 'keras_tokenizer', 'par... |
ffc61d29cf97696626ea0b915e853c35625ba21fb2f1a32f0bcfd7559eb6a731 | Python | 1,579 | 58 | from logging import getLogger
import numpy as np
from base.results.sleep_stage_tracker import (
add_f1_to_results,
SleepStageResultTracker,
)
logger = getLogger(__name__)
class FastSleepStageResultTracker(SleepStageResultTracker):
"""
Lightweight result tracker for training metrics.
A simplifi... |
9408e054d1d176019717aca78c2f05d7384d5e28022a4feb0e78b3de386c3787 | Python | 1,583 | 36 | import numpy as np
class ExpPadding3d:
def __init__(self, load_size, training=True):
"""
Padding the image: C x H x W x D, if H, W, D less than load_size, and will keep the overflow side as it is.
"""
# TODO: Not just support static filling of the padding, but also mirror, etc...
... |
e287524e68a201bd42afff3f9bae7a43bc0eb0106fa3112920de8174682cbf87 | Python | 1,583 | 43 | from sklearn.metrics import accuracy_score
from sklearn import metrics
import pandas as pd
import sys
def evalualte(y_test, y_pred, y_pred_score =None):
accuracy = accuracy_score(y_test, y_pred)
if y_pred_score is None:
fpr, tpr, thresholds = metrics.roc_curve(y_test, y_pred, pos_label=1)
else:
... |
69e0cd11a1ee4021007d9a62cf7bac19c5f872acaa4aedf209d8af0bf199b3db | Python | 1,585 | 45 | import multipagetiff as mtif
import argparse
import logging
import os
import numpy as np
from . import utils
def main(*args, **kwargs):
parser = argparse.ArgumentParser(description="Calculate the mean of a set stacks.")
parser.add_argument("-s", "--stack_paths", help="The paths to the stacks to average", nargs... |
9ae3b854852d622145257000c0ba3f227ab2e311293f8de6a4f8e010a4f2f2ff | Python | 1,585 | 35 | from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Align import MultipleSeqAlignment
from .shrinked_force_permutations import ShrinkedForcePermutationsDataset
from ..utils import rna2index
class DummyDataset(ShrinkedForcePermutationsDataset):
def __init__(self, transform=None):
super().... |
acc0b1a07bf7c53ab1abc2bbef27e80293e8ab0bf92d50cffcccec00ec188201 | Python | 1,592 | 38 | # -*- coding: utf-8 -*-
"""
Convert time stamps to float32 dtype.
"""
import shelve, os, fnmatch, sys
import numpy as np
in_path = sys.argv[1]
out_path = sys.argv[2]
for root, dirnames, filenames in os.walk(in_path):
# print(root)
for filename in fnmatch.filter(filenames, '*.dat'):
os.makedirs(out_pat... |
984b3b6048929a946f25d64e640f3bcdb7dab2c53c0a293fe3430693248e3547 | Python | 1,595 | 47 | import torch
def discretize_box(box, subcell_size):
xbins = torch.arange(0, box[0, 0] + subcell_size, subcell_size)
ybins = torch.arange(0, box[1, 1] + subcell_size, subcell_size)
zbins = torch.arange(0, box[2, 2] + subcell_size, subcell_size)
nxbins = len(xbins) - 1
nybins = len(ybins) - 1
nz... |
bd186ade4f408cc345bea0371c32b57136da223e06cf7b71a5cfc5d292e4adad | Python | 1,597 | 47 | import numpy as np
class RandomRotate3d:
"""
Crop the 3D numpy [c, h, w, d] and mask [h, w, d] in a sample
"""
def __init__(self, angle, training=True):
assert isinstance(angle, (float, list, tuple))
if isinstance(angle, float):
self.angle = (angle, angle, angle)
e... |
3f572e645689e508f71a3a8305bb3bddac92bf5b26960c6a233c85eb82a104fe | Python | 1,598 | 37 | import numpy as np
class Padding3d:
def __init__(self, load_size, training=True):
"""
Padding the image: C x H x W x D, if H, W, D less than load_size, and will keep the overflow side as it is.
"""
# TODO: Not just support static filling of the padding, but also mirror, etc...
... |
a628e4173d8132ebb9fb8f672e7243432cd3394a1cda00f8fb55f5783c50fed5 | Python | 1,605 | 42 | import numpy as np
def calc_filters(
num_channels: int, depth: int, complexity: float, scale: float
) -> tuple[np.ndarray, np.ndarray]:
"""
Calculate encoder and decoder filter sizes for U-Sleep architecture.
Computes filter counts that grow geometrically through the encoder
and shrink symmetrica... |
b2fb6d08574526af05c30170379fc4bb5b878f8b5b9dadeb522ef28fadfcef8a | Python | 1,605 | 55 | """__main__.py
This file is part of keras2c
Copyright 2020 Rory Conlin
Licensed under MIT License
https://github.com/f0uriest/keras2c
Runs keras2c
"""
import argparse
import sys
from keras2c.keras2c_main import k2c
__author__ = "Rory Conlin"
__copyright__ = "Copyright 2020, Rory Conlin"
__license__ = "MIT"
__maintai... |
0ea4cd7cb3fbb7e0d775404f5da554978f02c9059ee272fab058eadfdf96f8f0 | Python | 1,607 | 59 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 13:03:29 2021
@author: fhu14
"""
#%% Imports, definitions
import numpy as np
from Rotations import rotation_matrix_bond
#%% Code behind
def testRotateOper(verbose = True, eps = 1e-12):
# make a random axis and symmetric operator
if verbose:
print("Tes... |
1807b824dedea9b42ef60d3092fd5910799fb66881b43fefc21071a5d291fa82 | Python | 1,609 | 42 |
import numpy as np
import pandas as pd
from lmoments3 import distr
import scipy.stats as stat
def computeSPIonDF(df, column_name):
# Compute SPI using gamma function
# df: dataframe
# column_name: the column name of teh column containing the precipitation data (same dek over multiple years)
data = ... |
4d46001f096a534423accc13a90ae3de1d7754442377a34ce0d7b10a46b1ee51 | Python | 1,609 | 48 | from statistics.shap_viz.utils import *
from statistics.shap_viz.shap_brains_cnn import *
from statistics.shap_viz.shap_stats_cnn import *
import matplotlib as mpl
import matplotlib.pyplot as plt
def plot_brain_diffs() -> None:
map_ = {0: 'H', 1: 'IH', 2: 'IL', 3: 'L'}
cuts = None
for cluster in range(3):
... |
90b876df3e8f562279d73968c9930ac55ce90ecc0af5f087f57e6cd93b543a03 | Python | 1,610 | 44 |
def hist_match(source, template):
"""
Adjust the pixel values of a grayscale image such that its histogram
matches that of a target image
Arguments:
-----------
source: np.ndarray
Image to transform; the histogram is computed over the flattened
array
templa... |
e6ee2c4580d3e2668ce73486ccac5e7b6f50bffc1cb7ac5992f3604106e41be9 | Python | 1,610 | 52 | ############################################
# imports
############################################
############################################
# Custom Exception Classes
############################################
class OligoDesignerError(Exception):
"""
Base exception class for all Oligo Designer Toolsui... |
45058f3b7918ca35b48768cddbbf32d3a1e1b08ec5197036d9f4632381d40dfd | Python | 1,611 | 58 | # This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/>
from __future__ import annotations
import time
import warnings
import pytest
import torch
from sbi.simulators.linear_gaussian import diagonal_linear_ga... |
807783d4b8947e362c29d251f3a5eae68b17ae366dbc1c82b7da04e65c9896ab | Python | 1,611 | 35 | import numpy as np
import pandas as pd
from sklearn.pipeline import make_pipeline, make_union
from sklearn.svm import LinearSVR
from tpot.builtins import StackingEstimator
from tpot.export_utils import set_param_recursive
from metstab_pred.grid import SVR_poly, SVR_rbf
from metstab_shap.config import utils_section, cs... |
8cd41174883747780330a0703ab08290b8aa4a97647091e0678386dff0566208 | Python | 1,611 | 53 | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master... |
9a5094596394f51b7b25a7df08ccb1ba9a5334cc515d189282182ca69326bf27 | Python | 1,612 | 53 | # Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org
# Distributed under the MIT License.
# (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT)
import torch
from torchmdnet.models.model import create_model
from utils import load_example_args
def test_scalar_inv... |
ab185dad80b92962f0683d8d23f2042ac2a70ff80bd28e3a5aa9783a81cb8b34 | Python | 1,621 | 52 | from typing import Union, Any
from typing_extensions import Literal
import pytest
import eagerpy as ep
import foolbox as fbn
@pytest.mark.parametrize("logdir", [False, "temp"])
def test_tensorboard(
logdir: Union[Literal[False], None, str], tmp_path: Any, dummy: ep.Tensor
) -> None:
if logdir == "temp":
... |
1f49d1ba0f9fccd361b6584db60b3c2da66b690cf534fdd5ad8e141fcf9661ef | Python | 1,622 | 57 | import sys
from graphviz import Digraph
def plot(genotype, filename):
g = Digraph(
format='pdf',
edge_attr=dict(fontsize='20', fontname="times"),
node_attr=dict(style='filled', shape='rect', align='center', fontsize='20', height='0.5', width='0.5',
penwidth='2', fon... |
8590ad41fa0b8d963e54d9e1294a21912df2d06b6fdb4a4453f8e9bd101b4939 | Python | 1,622 | 45 | import nengo
import nengo.spa as spa
#from nengo.network import Network
import mem_voja2_pes_hop_twolayers
import importlib
#from nengo.spa.vocab import Vocabulary
importlib.reload(mem_voja2_pes_hop_twolayers)
class SPA_Mem_Voja2_Pes_Hop_TwoLayers(spa.module.Module):
#input_vocab = Vocabulary(
# 'input_vo... |
463759bb537b0b3e4d0c35a3979ba90bbfb083a9edf83003411aeadbb62acfb2 | Python | 1,623 | 57 | import random
from collections import OrderedDict
def reverse(colors):
res = OrderedDict()
for k, v in colors.items():
res[k] = v[::-1]
return res
def normalize(colors):
res = OrderedDict()
for k, v in colors.items():
res[k] = tuple([x / 255. for x in v])
return res
RGB_COL... |
b395c64ac91f5fad6d615809197725f6679108edea6cd90f287283bf2a487d04 | Python | 1,623 | 55 | import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
from collections.abc import Iterable
from flystim.util import normalize
COLOR_LIST = ['b', 'g', 'r', 'c', 'm', 'y']
def draw_screens(screens):
if not isinstance(scre... |
7fd3cde9e6b5db41fc79e257e92bebed335a63f7f2bf0d45a55d78c3cb72db86 | Python | 1,628 | 50 | import numpy as np
from scipy.spatial.distance import euclidean
def intersect(
u1, v1, u2, v2, constraint1=[-np.inf, np.inf], constraint2=[-np.inf, np.inf]
):
"""
Calculate intersection of two line segments defined as:
l1 = {u1 + t1*v1 : u1,v1 in R^n, t1 in constraint1 subseq R},
l2 = {u2 + t2*v2 ... |
f753dd35e655e46c3927d571910f07ab89c8e5df4b73d5fa13ab6582a3c74685 | Python | 1,629 | 75 | import requests
import sys
import argparse
import json
import os
import os.path
import re
ap = argparse.ArgumentParser()
ap.add_argument('-i','--input', help = 'Input file')
ap.add_argument('-n','--num', help = 'num')
ap.add_argument('-c','--cls', help = 'cluster file')
ap.add_argument('-o','--out', help = 'Output fi... |
09bad0f8aea6764e53f638aa10ffdfa5ff20edeca2b97ff249c7bdadcf1f7681 | Python | 1,631 | 69 | import os
import numpy as np
RACE_MAP = {
# "NACC": {
# 1: "White",
# 2: "BlackOrAfricanAmerican",
# 3: "AmericanIndianOrAlaskanNative",
# 4: "NativeHawaiianOrPacificIslander",
# 5: "Asian",
# 50: "Other",
# 99: "Unknown",
# },
"NACC": {
1: "W... |
2b819229d75c9c494518ea37ead77c3aa00a123594205415b3fe23bc9228c323 | Python | 1,632 | 53 | # -*- coding: utf-8 -*-
"""Process the outputs"""
__author__ = "Sean Benson"
__copyright__ = "MIT"
from dtor.utilities.utils_stats import stats_from_results
import numpy as np
import torch
from dtor.utilities.utils import set_plt_config
from dtor.utilities.model_retriever import load_model
from dtor.datasets.dataset_... |
6b167e9842908a18666f532a5b3436bbbb96cc9d4e0bb99c4f9ed638e75bc287 | Python | 1,632 | 59 | import json
import os
import random
from torch.utils.data import Dataset
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
from data.utils import pre_caption
import os,glob
class pretrain_dataset(Dataset):
def __init__(self, ann_file, laion_path... |
d05e2ef51f283708d42c42c03394a0581be8def9186a7be1c0680e73b775a309 | Python | 1,632 | 45 | import nengo
import nengo.spa as spa
#from nengo.network import Network
import mem_voja2RF_pes_hop_twolayers
import importlib
#from nengo.spa.vocab import Vocabulary
importlib.reload(mem_voja2RF_pes_hop_twolayers)
class SPA_Mem_Voja2RF_Pes_Hop_TwoLayers(spa.module.Module):
#input_vocab = Vocabulary(
# 'in... |
42f98a82cc2d7d90b1c19279697380b5e82e4da925f278cc0b40448b730c7879 | Python | 1,634 | 80 | from multiprocessing import Process, Event
import time
import pygame
from pygame.locals import *
import math
from random import randint, randrange
import sys
sys.argv = ['openvibe']
class OVProcess(Process):
def __init__(self):
Process.__init__(self)
self.initialized = Event()
self.stop_asked = Event()
def i... |
daa123391aec55a087da27974cc214b2eeb748950889f85dc869922e94207ed6 | Python | 1,634 | 74 |
'''
Convert GENOMESTRIP output to a common format
'''
import myvcf
import SV
import os
import re
import sys
class Genome_STRiP:
@staticmethod
def doparse ( genomestrip_data ):
E=genomestrip_data
#if type (genomestrip_data) is str:
E = genomestrip_data.rstrip('\n').split('\t')
#if re.search ('\.\/\.', E[-... |
da3768970c4daac5b4b35464a8e50b26e830a4e8879d9b11f20cb43dd7f276d7 | Python | 1,636 | 67 | def f_getRRtimeserie(mu,N):
gamma=2.1
b=0.75
import numpy as np
x=np.empty((N,1))
x[:]= np.NaN
k=np.empty((N,1))
k[:]=np.NaN
y=np.empty((N,1))
y[:]=np.NaN
t=np.empty((N,1))
t[:]=np.NaN
global tau
tau=np.empty((N,1))
tau[:]=np.NaN
for i in range(0,N... |
e279c3b91829e3bf8cb56eff49680cdec3f2125607f2380f39866d408de302fe | Python | 1,636 | 63 | """
Shared helpers for databases, sequence file parsers, format checks, and logging.
"""
from ._checkers_and_helpers import (
CustomYamlDumper,
cast_to_int,
cast_to_list,
cast_to_list_of_lists,
cast_to_string,
check_if_dna_sequence,
check_if_key_exists,
check_tsv_format,
generate_un... |
0403f81dec4931b0c37bfee28864a19cfadf15fd45885fc9bda6a890ff1236da | Python | 1,637 | 47 | import struct
from Bio import AlignIO
from clipkit.ecomp import read_ecomp, write_ecomp
from clipkit.ecomp.reader import (
HEADER_MAGIC,
HEADER_STRUCT,
INLINE_METADATA_VERSION,
)
def test_write_ecomp_sanitizes_inherited_metadata_and_roundtrips(tmp_path):
alignment = AlignIO.read("tests/unit/examples... |
a493ab84b58364584cda5b06d7be95cbf7ebcb5237b67657afa393a4e12482f1 | Python | 1,637 | 40 | # This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/>
from sbi.inference.posteriors.direct_posterior import DirectPosterior
from sbi.inference.posteriors.ensemble_posterior import EnsemblePosterior
from sbi.i... |
297b4645b80ea79d02629dc8a5179e34ca9389734a64a17d9df7185ba486120d | Python | 1,638 | 28 | # Copyright (c) OpenMMLab. All rights reserved.
from .auto_augment import (AutoAugment, BrightnessTransform, ColorTransform,
ContrastTransform, EqualizeTransform, Rotate, Shear,
Translate)
from .compose import Compose
from .formating import (Collect, DefaultFormatBu... |
d7d14486729af0fb7d867d55f3ad16cdd8ea3c5f5f40e1fcc905d0d978a15cb0 | Python | 1,638 | 54 | import subprocess
import sys
def get_commits(branch: str, start_tag: str, end_tag: str) -> list[str]:
try:
commits_raw = subprocess.check_output([ "git", "--no-pager", "log", branch, "--no-color", "--pretty=oneline", "--abbrev-commit", f"{start_tag}..{end_tag}"], stderr=subprocess.DEVNULL).decode("UTF-8").... |
77f85f60d9dbca9ee10520006a8f0b1041883d9564882d7783590b3dbb200270 | Python | 1,639 | 45 | """
create_strict_splits.py
Removes data leakage between the Universal Foundation Set (BindingDB)
and downstream evaluation benchmarks (Davis, KIBA) by enforcing a
strict cold-drug zero-overlap policy.
"""
import pandas as pd
import os
def generate_strict_benchmarks(data_dir="../data"):
print("--- GENERATING ST... |
93868826c0a70896b0535c684aa18ac8650ca17156b65aaba0a136d911825747 | Python | 1,643 | 56 | from typing import Callable, Tuple, Type
import eagerpy as ep
from .types import BoundsInput, Bounds
from .attacks.base import Attack
def evolutionary_strategies_gradient_estimator(
AttackCls: Type[Attack],
*,
samples: int,
sigma: float,
bounds: BoundsInput,
clip: bool,
) -> Type[Attack]:
... |
a936602831f5124188823aa0ddafef404bab246ac437a3cc7dfec6b009d4a558 | Python | 1,644 | 64 | #!usr/bin/env python
#coding:utf-8
"""
@author: Haidong Zhang
@contact: haidong_zhang14@yahoo.com
@time: 2020/12/10 18:21
@project: MalariaDetection
@description:
"""
from keras.layers import Flatten, Dense, BatchNormalization, UpSampling2D
from keras.models import Model
from keras.optimizers import adam
... |
275256a17a83a8fd462e1c640355b573c65293d4667eb5dcb56c5a8204436606 | Python | 1,646 | 28 | # Copyright (c) OpenMMLab. All rights reserved.
from .assigners import (AssignResult, BaseAssigner, CenterRegionAssigner,
MaxIoUAssigner, RegionAssigner)
from .builder import build_assigner, build_bbox_coder, build_sampler
from .coder import (BaseBBoxCoder, DeltaXYWHBBoxCoder, DistancePointBBoxC... |
e3417731e8c1499cb219677a23310a26ff4779c60297c823ce5f381cbca36f40 | Python | 1,647 | 37 | import logging
import socket
import torch
import yaml
def mapping_processes_to_gpu_device_from_yaml_file(process_id, worker_number, gpu_util_file, gpu_util_key):
if gpu_util_file == None:
device = torch.device("cpu")
logging.info(" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
... |
18f23f7438a670b849790000cfae821a3294305b1368b5c78cb5548567e9fa31 | Python | 1,649 | 36 | import argparse
def main(args):
index_file = open(args.CompletePath+"/DWI/eddy/index.txt","w+")
index_file.writelines(' '.join(str([1 for _ in range(args.Directions)])[1:-1].split(',')))
if args.PhaseEncodingDirection == 'j':
string_vector = "0 1 0 "
elif args.PhaseEncodingDirection == 'j-':
... |
badf78a146994286ba3c9f1c7b76474a18dbe6866e697b72625f8d65a548e733 | Python | 1,653 | 41 | import sys
import os
import shutil
from A_config import a10_config
from D_modelling import d090_model_wrapper
def launcher(fn, config_fn, run_name, runType):
# limit threads for Condor
modelSettings = a10_config.mlSettings(forecastingMonths=0)
os.environ['MKL_NUM_THREADS'] = str(modelSettings.condor_param... |
5298511bd6890c94853096afd870575060d6371df7846ea0c1ab31f1aaf15705 | Python | 1,655 | 64 | #!usr/bin/env python
#coding:utf-8
"""
@author: Haidong Zhang
@contact: haidong_zhang14@yahoo.com
@time: 2020/12/10 18:21
@project: MalariaDetection
@description:
"""
from keras.layers import Flatten, Dense, BatchNormalization, UpSampling2D
from keras.models import Model
from keras.optimizers import adam_v... |
be9dd7d2cbbf17cdbe956c75dc921e700ee3d47f23e6789d8d76258062ee7a74 | Python | 1,655 | 42 | # Copyright (c) OpenMMLab. All rights reserved.
from torch.nn import functional as F
def interpolate_as(source, target, mode='bilinear', align_corners=False):
"""Interpolate the `source` to the shape of the `target`.
The `source` must be a Tensor, but the `target` can be a Tensor or a
np.ndarray with the... |
89e24cb6403ca435605e95a9dcdb4e024249a9a2cf82b9bb176af1d9d7246a87 | Python | 1,660 | 46 | import os
from pathlib import Path
import shutil
import glob
import time
from A_config import a10_config
from B_preprocess import b100_load
from D_modelling import d090_model_wrapper
if __name__ == '__main__':
# USER PARAMS
config_fn = r'V:\foodsec\Projects\SNYF\stable_input_data\DZ\DZMultiple_WC-Algeria-AS... |
1f6eef1aac6ab7a9f423e024ae5406fbd084f0df3476bba8dc77d3f5fef494db | Python | 1,667 | 58 | # Author: Akshara Balachandra
# Date: Thursday 26 November 2020
# Description: Module to read and parse XML output of Cat12
import xmltodict
from typing import Dict, List
class Cat12Reader:
def __init__(self, filename: str = None):
self._filename = filename
def parseXML(self, key1: str, key2: str) ... |
607fa525f2e8f182de3889e6fa817a5c6b2c6d1c977904557c3a56c803a6ff4d | Python | 1,668 | 46 | import cv2
from csutil.util import kp_to_numpy
class ImageFeature:
def __init__(self, img, featurename='sift', detectAndCompute=None, detector=None, computer=None, num_feature=None, mask=None, points_format=None):
self.img = img
self.featurename = featurename
self.detectAndCompute = de... |
8d00c5a4e7697a1bc7b4d69f102914ba7ef2ed5db9bac04ab6efe2ada49df11d | Python | 1,673 | 66 | """__main__.py
This file is part of keras2c
Copyright 2020 Rory Conlin
Licensed under LGPLv3
https://github.com/f0uriest/keras2c
Runs keras2c
"""
import argparse
import sys
from keras2c.keras2c_main import k2c
__author__ = "Rory Conlin"
__copyright__ = "Copyright 2020, Rory Conlin"
__license__ = "MIT"
__maintainer__... |
9634c8bbc4db7ea54887929bf95eac1761ee26e1349c03a039bb91587de106c8 | Python | 1,673 | 36 | import numpy as np
import pandas as pd
from sklearn.feature_selection import VarianceThreshold
from sklearn.pipeline import make_pipeline, make_union
from tpot.builtins import StackingEstimator
from tpot.export_utils import set_param_recursive
from metstab_shap.grid import SVR_poly, SVR_rbf
from metstab_shap.config im... |
cd97f00736835ad21b7d6410ea718b143a69b0c5bb9c4389797fdaafd3d5a6ba | Python | 1,674 | 60 | #!/usr/bin/env python3
"""
Extract supported Python versions from pyproject.toml's
[project].requires-python field and emit a JSON list.
Expected format:
">=3.10,<3.14"
Example output:
["3.10", "3.11", "3.12", "3.13"]
"""
from __future__ import annotations
import json
import re
from pathlib import Path
de... |
c4f0643de6e66f62547241473a2f98c77c41529834ecd9ad45adc1eada393d29 | Python | 1,676 | 65 | import json
import utils
from os.path import split
"""
this is a script for supporting glowing bear UI
"""
def load_tree_node_file(file_path, node_name=None):
if node_name is None:
p, fn = split(file_path)
node_name = fn
folder_node = create_folder_node('\\', node_name)
for l in utils.rea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.