sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
5157d25f2fc30f59d4fb20cdd8e10dd12b662d6be45addca9a790308663836e2
Python
1,616
58
""" This is ported from Matlab code from the original TDR codebase. """ import numpy as np def tdrVectorOrthogonalize(coef_fix, ortpars): """ tdrVectorOrthogonalize orthogonalize regression vectors Inputs: coef_fix: regression vectors .name: vector names {nvc 1} .response: vector coe...
71726e35742a5df17e159e96e1bfcf3fc3b545f4f3d6b8a084f845256571cc65
Python
1,616
39
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from django.core.management.base import BaseCommand, CommandError from cvat.apps.engine.models import Asset, Data from cvat.apps.engine.utils import get_path_size, take_by class Command(BaseCommand): help = "The command initializes 'content_si...
c92d1ff3be5d449c3a9a02fb6932fbee0f18310afad901c2f665dbe7942dcf87
Python
1,616
59
import argparse from datetime import datetime from deepreg.predict import predict name = "unpaired_us_prostate_cv" # parser is used to simplify testing, by default it is not used # please run the script with --full flag to ensure non-testing mode # for instance: # python script.py --full parser = argparse.ArgumentP...
f34ac6eb45a59887a2b8f0e0912b603c4c0fe78b9648170a88755f7de25d706e
Python
1,616
77
from typing import TypeVar import torch from torch import Tensor import my_setup from custom_layers.custom_module import BatchEvalModule T = TypeVar('T', bound='Module') class Dropout(BatchEvalModule): # A dropout layer following the idea of Tensorflow def __init__(self, p=0): super(Dropout, self)....
33fee08829514a9939df9cdc2a455939eb5cc4ff1e4342b8b4c3abda017cf4d9
Python
1,617
34
from .bedtools import * from .feature_generator import * from .interactions import * from .samtools import * chroms = ['chr{}'.format(_) for _ in list(range(1, 22 + 1)) + ['X', 'Y']] # http://genome.ucsc.edu/FAQ/FAQformat.html#format1 generic_bed_columns = ['chrom', 'start', 'end', 'name'] bed6_columns = generic_bed_...
57f663b028ddab9e9a8216e8ecfb95fbe6a1876ff509acf16bc3e57d9d2b705c
Python
1,617
46
#!/usr/bin/env python3 from pathlib import Path import shutil import subprocess import sys import os import glob _, new_data, old_data, test_case_path = sys.argv data_name = Path(old_data).name test_data_path = Path(old_data).parent subprocess.run(["git checkout master"], shell=True, cwd=test_data_path) subprocess.r...
52269b77be5e6f148664f2e66dd218dce13f0e5db5ea925b88cba957871c22d3
Python
1,618
45
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="mygene", version="3.2.2", author="Chunlei Wu, Cyrus Afrasiabi, Sebastien Lelong", author_email="cwu@scripps.edu", description="Python Client fo...
82dbe3ab6b5d2134d0125dcf517b2dd98574a501676ee06b5cc27652010eb3f8
Python
1,618
42
import logging import os import sys import boto3 from botocore import UNSIGNED from botocore.config import Config from tqdm import tqdm _logger = logging.getLogger(__name__) _DEFAULT_BUCKET = 'brain-score-models' _DEFAULT_REGION = 'us-east-1' _NO_SIGNATURE = Config(signature_version=UNSIGNED) def download_folder(f...
cc956d72a3a0a8b8df675479c6fce255a6fd35c5a279abd762c7f183880b81ae
Python
1,618
39
import torch from torch import Tensor def dice_coeff(input: Tensor, target: Tensor, reduce_batch_first: bool = False, epsilon=1e-6): # Average of Dice coefficient for all batches, or for a single mask assert input.size() == target.size() if input.dim() == 2 and reduce_batch_first: raise ValueError...
23c38a53b157301d309b39ad12d4b01b85f92bb0fb18f1fb8e632c9d78df678e
Python
1,619
71
"""Train DyNeMo on time-delay embedded/PCA data. """ from sys import argv if len(argv) != 3: print("Please pass the number of modes and run id, e.g. python 1_train_dynemo.py 6 1") exit() n_modes = int(argv[1]) run = int(argv[2]) #%% Import packages print("Importing packages") import pickle from osl_dynamic...
247b3692f88c3bbdba6c6a2133ae9db1416594bbd34a97c453fb2e4c282bfbf0
Python
1,619
62
# user feature generation: Alhosseini import json import datetime import pandas as pd import numpy as np import csv #path="/data2/whr/zqy/327/" #chooses = ["gilani-2017","cresci-stock-2018","cresci-rtbust-2019","cresci-2015","botometer-feedback-2019","Twibot-20"] chooses = ["cresci-2015"] for choose in chooses: ...
ee32d75be810847f051fb3d2c4a714a3b06eb6096aa8c23f4942a1453df50edc
Python
1,619
43
import numpy as np import torch from utils import common_functions as c_f from miners.base_miner import BaseSubsetBatchMiner class MaximumLossMiner(BaseSubsetBatchMiner): def __init__(self, loss, miner=None, num_trials=5, **kwargs): super().__init__(**kwargs) self.loss = loss self.miner =...
4745f731d7cec979277d0be7f2cf5f65895275f60e1dbebcf7936d5ae4b6bb65
Python
1,620
47
# encoding: utf-8 import numpy as np class BaseDataset(object): """ Base class of reid dataset """ def get_imagedata_info(self, data): pids, cams = [], [] for _, pid, camid in data: pids += [pid] cams += [camid] pids = set(pids) cams = set(cams)...
7253b911c26487c8388a6e5da635b836635ed2f7dde3336e9c51420ffa560d0f
Python
1,620
56
#!/usr/bin/env python """ Build windows of length `window_size` over the sequences defined by `len_file` excluding regions in `gap_file`. After removing the gaps, windows of exactly `window_size` units will be placed in the remaining regions, with the extra space evenly placed between the windows. `len_file` is LEN ...
d61d0372e0cc5e8a2fde571555953f7d7d398291d7323260deec2a80e5390502
Python
1,620
68
import re import os import spacy import zipfile def count_urls(tweets): total = len(tweets) unique =[] for text in tweets: urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text) unique += urls count = len(unique) unique_count = len...
db0d23f3e525810ddf863e01a1371fa4ce2e36c32952cccc5803d3067e43cd86
Python
1,620
68
#!/usr/bin/env python3 import sys from optparse import OptionParser USAGE = """ python convert-RM-to-bed.py --rmfile <rm file name> --bed <bed file name> combine the split trf files into a single file """ ############################################################################### parser = OptionParser(USAGE...
fbc1ab94bf757fac1303be5d620f91eef96f839786bce308e1eca3bdd5f3bceb
Python
1,620
41
import numpy from numpy import median def lowess(x, y, f=2./3., iter=3): """lowess(x, y, f=2./3., iter=3) -> yest Lowess smoother: Robust locally weighted regression. The lowess function fits a nonparametric regression curve to a scatterplot. The arrays x and y contain an equal number of elements; each pair (x[i]...
0c36fd934d56a2cf041a827a444343af9de95307273fc8621054d1a7d1589e9a
Python
1,621
42
from __future__ import annotations from PySide6 import QtGui from PySide6 import QtWidgets from PySide6.QtCore import Qt from ._label_list_widget import LABEL_COLOR_ROLE from ._label_list_widget import TrailingColorDotDelegate class _EscapableQListWidget(QtWidgets.QListWidget): def keyPressEvent(self, keyEvent:...
2b01e1c56481b325484aaa594302f262b551890ff2f7fceae3a638dbcaf5e94c
Python
1,621
67
#!/usr/bin/env python """ Read a MAF from standard input and print counts of alignments, bases, or columns. usage: %prog [options] -c, --cols: count alignment columns rather than number of alignments -b, --bases: count bases in first species rather than number of alignments -s, --skip=N: when counting bases,...
31faac9d703bedbd430f9ad06c96bad88ca9ec57e03ba894cd2ff9358145e53b
Python
1,621
51
import nibabel as nib import numpy as np from pyment.preprocessing.crop import ( calculate_bounds, crop_nifti_image_if_necessary, ) def test_calculate_bounds_centers_on_brain_with_left_adjustment(): image = np.zeros((10, 10, 10), dtype=np.float32) image[1:3, 1:3, 1:3] = 1.0 target_shape = (6, 6, ...
cb459aef90606f09a40089c1a221b696285043be1837aea443647d82d455f985
Python
1,621
33
import unittest import base class Test1(base.BaseScriptTest, unittest.TestCase): command_line = "./scripts/maf_build_index.py ${maf} ${maf_index}" input_maf = base.TestFile(filename="./test_data/maf_tests/mm8_chr7_tiny.maf") output_maf_index = base.TestFile(filename="./test_data/maf_tests/mm8_chr7_tiny.m...
2d5c8a987ca67dc813f8b12729f23388820435364a018eff32dab77a6ab9d4ae
Python
1,622
34
""" Copyright 1999 Illinois Institute of Technology 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 without restriction, including without limitation the rights to use, copy, modify, merge, publis...
556a71f0654fc79315867dbe9195eee87011fb2813277772bfbc5bd86a9253d0
Python
1,622
79
import numpy as np def test_simple_functions(): from cec2017.simple import all_functions assert len(all_functions) == 10 M = 2 dims = [2, 10, 20, 30, 50, 100] for i, f in enumerate(all_functions): assert f.__name__ == f"f{1 + i}" for d in dims: x = np.zeros((M, d)) ...
5f749bc4c0ad628e0cac67877f6df1fd7786d273cbe6f409f465c8934590daf6
Python
1,622
56
#!/usr/bin/python # ## @file # # Defines a series of abstract exceptions that can be sub-classed and which Hal # can recognize # # Jeffrey Moffitt 3/16 # class HalException(Exception): pass class HardwareException(HalException): """ A generic hardware exception. """ pass class ModuleException(Ha...
64e883ba3a4e273134354190af977bfed600bade2ba517b0afcbcd14610f2a94
Python
1,622
59
# Copyright (C) 2020-2022 Intel Corporation # Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import json import base64 from PIL import Image import io import numpy as np from model_handler import ModelHandler def init_context(context): context.logger.info("Init context... 0%") model = M...
f04f411f004e28836b48d54767c2e7f642aba991ba699a99687dd36d7bf422af
Python
1,622
62
"""Misc. tools for supporting Layer implementations.""" def pop_shape(keyword_options): """Parse first keyword option that begins with a digit as a shape. Parameters ---------- keyword_options : list of str. Result of `keyword.split('.'). Returns ------- shape : tuple or None ...
5932f3c50ce74c718c7b3599d5a5f8d976b3b5c5679a187275f43883296c6569
Python
1,623
64
# ----------------------------------------------------------------------------- # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Provides QtStateMachine clas...
2224eb23af303b1b8e175740f62d1d8fdee991b9ba32e74d4f805daf3f40fb92
Python
1,624
37
import numpy as np import torch import torch.nn as nn import torch.backends.cudnn as cudnn cudnn.deterministic = True cudnn.benchmark = True import torch.nn.functional as F from .gat_conv import GATConv class STAGATE(torch.nn.Module): def __init__(self, hidden_dims): super(STAGATE, self).__init__() ...
94c33c6ccde0831ba7bd016a40207de3749901f63b370d38c3e94568c064c6df
Python
1,624
49
from typing import Tuple import torch def ndgrid(*tensors) -> Tuple[torch.Tensor, ...]: """generate N-D grid in dimension order. The ndgrid function is like meshgrid except that the order of the first two input arguments are switched. That is, the statement [X1,X2,X3] = ndgrid(x1,x2,x3) produc...
e241c264d23c0bd40a9fd6e2c3793f64eb3953b1bf71dd9852fe5de5b6c14349
Python
1,624
32
from dtiplayground.dmri.common.tools.base import ExternalToolWrapper class DTIProcess(ExternalToolWrapper): def __init__(self, binary_path=None, **kwargs): super().__init__(binary_path, **kwargs) self.binary_path = None if binary_path is not None: self.binary_path = binary_path...
ebfd4e06dcd14ab48a46bb423e122f7a530a180088e81e3741774c0d5d73ed78
Python
1,624
48
# Copyright (C) 2021-2022 Intel Corporation # Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import zipfile from datumaro.components.dataset import Dataset from cvat.apps.dataset_manager.bindings import ( GetCVATDataExtractor, detect_dataset, import_dm_annotations, ) from cvat.apps.da...
63656a028e206749b6a97fa6284a485000b692f1a19880a2918effae5da3e70b
Python
1,625
65
import json import os.path import subprocess import textwrap from pathlib import Path def load_src_dst(name: str = 'phys', src_name: str = 'bkrunch2', dst_name: str = 'nerf2024') -> tuple[str, str]: p = Path('../../../res/sync') / 'backup.json' with p.open('rb') as f: ...
cd39704b65355f8a1835f82ffc8b327d1e3562b44c08c0181022da9a1c19671f
Python
1,626
40
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['processing.zip']) tmp_dir = tempfile.T...
1137006544d1682948feb5332436fae0084ce1158c34af3990ac75b696c94c18
Python
1,627
49
# -*- coding: utf-8 -*- import torch import torch.nn as nn from transformers import BertModel from .scalar_mix import ScalarMix class BertEmbedding(nn.Module): def __init__(self, model, n_layers, n_out, requires_grad=False): super(BertEmbedding, self).__init__() self.bert = BertModel.from_pret...
ad36d8ae6907056e020daf2a4c5a3612d04bf19ead81f5810c83cb882b0066ac
Python
1,627
63
import warnings from functools import wraps from time import time import numpy as np from scipy.optimize import OptimizeWarning, curve_fit, direct def time_this_function(f): @wraps(f) def wrap(*args, **kw): ts = time() result = f(*args, **kw) te = time() print("func:%r args:[%...
f9d074a266b9d3ae0ea91d218e2bd810efe78aecea9d5e16c25f3f3df8162091
Python
1,627
44
# -*- coding: utf-8 -*- import numpy as np from scilpy.gradients.bvec_bval_tools import is_normalized_bvecs from scilpy.gradients.utils import random_uniform_on_sphere, \ get_new_gtab_order def test_random_uniform_on_sphere(): bvecs = random_uniform_on_sphere(10) # Confirm that they are unit vectors. ...
4f17796b66718e7148f705bf2fda89a5badc34a80abde3001f750f24d0979d47
Python
1,628
59
import argparse from datetime import datetime from deepreg.predict import predict name = "grouped_mask_prostate_longitudinal" # parser is used to simplify testing, by default it is not used # please run the script with --full flag to ensure non-testing mode # for instance: # python script.py --full parser = argparse...
8465b81b23bc01d0b53616b1b2b511e52e15b11b4c757e807d947e789ccb3350
Python
1,628
52
import matplotlib.pyplot as plt import torch def visualize_input_and_segmentation(test_loader, model, device, epoch): model.eval() # Fetch one batch from the test loader inputs, labels = next(iter(test_loader)) inputs = inputs.float().to(device) # Predict using the model with torch.no_grad():...
d613234e93379d7528c8bdd9ec6f7838df31af4080c757e99d94dd877629325f
Python
1,628
59
# pylint: disable=line-too-long import argparse from datetime import datetime from deepreg.predict import predict name = "paired_ct_lung" # parser is used to simplify testing, by default it is not used # please run the script with --full flag to ensure non-testing mode # for instance: # python script.py --full parse...
9c2fb0ea58a8c037dfb64275546ca508936fb3dfe689bbf1dc2a310ad0b6f5c0
Python
1,629
44
import sys from pathlib import Path p_dir = str(Path(__file__).absolute().parents[2]) if p_dir not in sys.path: sys.path.insert(0, p_dir) import os from os.path import join import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np class enet_hydra(nn.Module): ...
fb8aab39811da8b0f2fe333a7cad41f3e81e452933d8ca4479835ac5a3578982
Python
1,629
55
#!/usr/bin/env python3 import argparse import numpy as np from ase import Atoms from ase.io import read, write from ase.optimize import * from KerNNCalculator.KerNNCalculator import * ''' Script to calculate the potential energy of a structure. Usage: python predic_mol.py -i structure.xyz ''' #parse command line argu...
4b0bd534c60ade59404d1dabd5b695080d21cbf7f02489060f5d7476ef56a28b
Python
1,631
52
import numpy as np from impyute.ops import matrix from impyute.ops import wrapper @wrapper.wrappers @wrapper.checks def em(data, eps=0.1): """ Imputes given data using expectation maximization. E-step: Calculates the expected complete data log likelihood ratio. M-step: Finds the parameters that maximize t...
4d6e38e10c00cc018739c8cdb8c0172aaefcee528520fa6ae82d7bba0ba6041c
Python
1,632
50
# Copyright (c) DP Technology. # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from argparse import Namespace from unicore.optim import UnicoreOptimizer class UnicoreLRScheduler(object): ...
b877acd1b32435de4a0c29036160d340db32e386df6f1a6714b5f70306f1693c
Python
1,632
45
import functools from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.check_submission import check_models import torchvision.models import ssl ssl._create_default_https...
0db0dd9c1352885d1b3be1174788092c128fc8efdbc1889bd5e4f4c8d411c929
Python
1,633
25
from testsetclass import TestsetClass class ACONF(TestsetClass): def __init__(self): self.weak = 1.0 self.molecules = ['H_t+g+x-', 'B_T', 'P_GX', 'H_x+g-x+', 'P_GG', 'P_TG', 'H_tgt', 'P_TT', 'H_ttt', 'H_tgg', 'H_gtt', 'H_g+x-g-', 'H_x+g-g-', 'B_G', 'H_ggg', 'H_gtg', 'H_g+t+g-', 'H_g+x-t+'] ...
289827a214b5983cc27d9b2a44e948abce02cbc78e1b10aaffa89812d0a7011a
Python
1,633
42
import gzip import os import glob from pathlib import Path gene = snakemake.params.simplegene smkout = snakemake.output.done countfiles = glob.glob(f"cats/*{gene}*/count/*tsv.gz") print(f"Countfiles globbed as {' '.join(countfiles)}") fragments = {} viewpoint = None for countfile in countfiles: with gzip.open(co...
3f9d435673e1bc505dd6cf4f1d43299ead0558d7a5c65a3de34c55aef9f9e44e
Python
1,633
52
from collections import OrderedDict import numpy as np from brainscore_vision.model_helpers.activations.core import ActivationsExtractorHelper from .descriptor import FoveatedGaborFilterEntropyExtractor, GaborEntropyConfig MODEL_IDENTIFIER = 'gabor_filter_entropy_4x4_v2' LAYER_NAME = 'gabor_entropy_foveate...
8d6e519cd45135d39163da95d14e038c38d02625bb125456535eec60d93e02b2
Python
1,633
44
from brainscore_vision.model_helpers.check_submission import check_models import functools import os import torchvision.models from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images from pathlib import Path fr...
2407bb7115761c403c8a1de1e73b336cd159fde7d89fb15023e66c3a766dd6fa
Python
1,634
55
import sys from qtpy.QtCore import QCoreApplication, Qt, QTimer from qtpy.QtWidgets import QApplication try: from qtpy import QT6 except ImportError: QT6 = False from magicgui.application import APPLICATION_NAME from magicgui.widgets.protocols import BaseApplicationBackend class ApplicationBackend(BaseAppl...
af1839826bf1e4219d3814cffe4c96b03c38ba0a8653ab4e0dc04a0111f6d244
Python
1,634
63
import os import sys import torch from model.Ouroboros import Ouroboros import pandas as pd if __name__ == '__main__': # check GPU print('CUDA available:', torch.cuda.is_available()) # Should be True print('CUDA capability:', torch.cuda.get_arch_list()) print('GPU number:', torch.cuda.device_count())...
c68c0a1b6c9d2bcbed30320fa3b204380efb8fdf08af3235d66bd85b32c9ccb7
Python
1,634
55
from scipy.signal import butter, lfilter, freqz class LowPassFilter: def __init__(self, cutoff, fs, order=5): self.cutoff = cutoff self.fs = fs self.order = order self.b, self.a = butter(self.order, self.cutoff / (0.5 * self.fs), btype='low', analog=False) def apply(self, data)...
0d0676f637d411a7e6e83bf922454069df73c7b5e59f2ed98165084c1c814236
Python
1,635
44
import os import scanpy as sc import pandas as pd import anndata as ad os.chdir("/data/wuqinhua/phase/covid19/datasets") all_adatas = [] adata1 = ad.read_h5ad('./pre_data/9_Schulte-Schrepping_2020/sce1.h5ad') adata2 = ad.read_h5ad('./pre_data/9_Schulte-Schrepping_2020/sce2.h5ad') adata1 = ad.AnnData(X=adata1.raw.X, ...
982b07dae7277b92a1bb53221c3bdc39e8d47c08abc89bfb241062eea3fd50db
Python
1,635
59
#!/usr/bin/python # ## @file # # Generate HTML for Dave web update & upload it to # a webserver using the the DAV protocol and the # tinydav library, available here: # # http://code.google.com/p/tinydav/ # # This is not used. # # Hazen 08/11 # import time import tinydav class HTMLUpdate(object): def __init__(self...
39c5bd14ba38908f75930c7eac281188ab9b5597d2b320e7da92ac3e63c8c309
Python
1,636
54
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import ConvModule, xavier_init from depth.ops import resize from depth.models.builder import NECKS @NECKS.register_module() class SkipNeck(nn.Module): """SkipNeck. Reshape the skip features. Simple hack of reassemble lay...
51ed7262cb81d3be94275a1d2f5ec2450b4fe18e7213374df16aef157e3aa182
Python
1,636
60
import argparse import os.path import sys import warnings from bism.config.config import get_cfg_defaults import torch import torch.nn as nn import torch.multiprocessing as mp from bism.utils.distributed import setup_process, cleanup, find_free_port from bism.train.default_engine import train from bism.models.constr...
611f328a12b9963524dfbba675c4186d0060248fca7192709af2e6066ba31eb8
Python
1,636
27
from .resnet import * from .vgg import * from .HMAX import * from .alexnet import * from .ALEXMAX import * from .RESMAX import * from .ALEXMAX3 import * from .ALEXMAX3_optimized import * from .HMAX_old import * from .hmax3 import * from ._builder import build_model_with_cfg, load_pretrained, load_custom_pretrained, r...
75197373c470afa34faf7eb7e525576afb15ae61979003d5d5633c284b698175
Python
1,636
50
from setuptools import setup, find_packages from os import path import sys from io import open here = path.abspath(path.dirname(__file__)) sys.path.insert(0, path.join(here, 'ogb')) from version import __version__ print('version') print(__version__) # Get the long description from the README file with open(path.joi...
406d87e199b456024260036b1de82cd3ac4e82ad2e063fa80f9fb8c77e959117
Python
1,637
48
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['mrds.zip']) tmp_dir = tempfile.Tempora...
5747f9d23ac91c0562f1bcff1f33600ad3226f2cdbd5c9c54c9c723106e895bd
Python
1,637
48
import os import random import torch import numpy as np import pandas as pd from utils import process_data, dataloader_generation_pred, model_performance_test, metrics, parse_arguments, load_model, process_and_predict, save_results from model import Cross_Attention_DDG, apply_masked_pooling, SinusoidalPositionalEncodi...
7d1a126bc6aaefd54aec15097ee4c91ce99df70f8b35fa3f26a25866c6b37081
Python
1,637
72
import numpy as np from scipy.constants import epsilon_0 as e0 from impedancefitter.double_shell import eps_cell_double_shell from impedancefitter.double_shell_wall import eps_cell_double_shell_wall omega = 2.0 * np.pi * np.logspace(0, 12, num=30) # for double_shell_model c0 = 1.0 em = 10.0 km = 1e-6 kcp = 0.5 ecp...
a37a0607288a82420d277029ea16b6498cd4e23aeca505b4b2349f68a2fd86d4
Python
1,637
57
# -*- coding: utf-8 -*- """ Created on Thu May 20 16:02:00 2021 @author: Yoshi """ from n2v.models import N2VConfig, N2V import numpy as np from csbdeep.utils import plot_history from n2v.utils.n2v_utils import manipulate_val_data from n2v.internals.N2V_DataGenerator import N2V_DataGenerator from matplotlib import pyp...
7c022a7ac0095b12abcb5198bc50a6d9f6cb860c3f35df449796a0820ca758e9
Python
1,639
52
from torch import nn import torch class EmbLayer(nn.Module): def __init__(self, hidden_dim=None, aggregate='sum', bias=True, activation=None, ntypes=None, dropout=0.0, conv_dict=None, ...
e6b6094359befdd6ce76894cce70e5f2b3d925a4c804df5cacaf16e337d9824f
Python
1,640
51
from os.path import join, dirname, basename, isdir from os import makedirs from imageio import imread from glob import glob import numpy as np from ..cpn import masks2labels import torchvision __all__ = ['download_bbbc038', 'BBBC038Train'] def download_bbbc038(directory): """Download BBBC038. Download and e...
67849f74cc5da327217b577e7a9508aac697a2c86826ea7c8ba3954f82476604
Python
1,641
60
# pylint: disable=line-too-long import argparse from datetime import datetime from deepreg.predict import predict name = "unpaired_ct_lung" # parser is used to simplify testing, by default it is not used # please run the script with --full flag to ensure non-testing mode # for instance: # python script.py --full pa...
cbdd1a4fce74e0c7955535c791d80b6a09c5e3013c59838c7b0ef772d5187612
Python
1,641
59
from rscvp.model.bayes_decoding.main_decode_analysis import DecodeAnalysisOptions from rscvp.selection.main_neuropil_error import NeuropilErrOptions from rscvp.selection.main_trial_reliability import TrialReliabilityOptions from rscvp.util.util_demo import run_demo from rscvp.visual.main_reliability import VisualReliab...
d9d9c2513fc420fbec9b47a01cf0c307bda6a6686fce3e574c3a160cf452e82c
Python
1,641
57
# Generated by Django 4.2.1 on 2023-07-18 07:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("engine", "0073_alter_attributespec_default_value_and_more"), ] operations = [ migrations.AlterField( model_name="labeledimage", ...
3b429bcad7e6a73577fd660c129a510f0df0afec0148b2d1bf2c26fd0db5c249
Python
1,642
51
from __future__ import annotations from dataclasses import replace from typing import Optional import numpy as np from brainways.elastix.elastix import elastix_registration from brainways.pipeline.brainways_params import BrainwaysParams, TPSTransformParams from brainways.transforms.tps_transform import TPSTransform ...
d2626227a6c5391b6c08d480c21960f3e74cfaf3167a74153b58c07726e327a0
Python
1,642
51
import logging import os from contextlib import contextmanager from pathlib import Path import pandas as pd logger = logging.getLogger("benchmark") @contextmanager def set_cwd(path: Path): """ Sets the cwd within the context and resets it afterwards Adapted from https://dev.to/teckert/changing-director...
e9b3e11725465c60aa3618c97ec63666db9f0bf1bc9b57898918b891c2dc3daa
Python
1,642
64
#!/usr/bin/env python """ For every column that occurs in a multiple alignment print the column and the number of times it occurs (one column/count per line, tab separated), sorted by count descending. This version allows special handling of the 'wildcard' symbol in alignments. Note: all blocks must have exactly the...
4fa325b6be9814fcaaa83ef9da026fa9fb7d923c08e0c08521a9e771a5884400
Python
1,643
50
import numpy as np import scipy.stats as stats def CPT(cpts, truncate=False): # truncate: set elements below zero to zero if truncate: cpts[cpts < 0] = -0.1 return np.nanmean(cpts, axis=1) def HPT(hpts): return hpts.mean(axis=1) def MPT(mpts): # logarithm of geometric mean return np...
8e2c0ffd892c6b4aab7c4332f289cf23c2088063bbb249735d80530d0166b4c1
Python
1,643
49
import os import numpy as np import pandas as pd import scanpy as sc import anndata as ad import hdf5plugin from anndata import AnnData os.chdir("/data/wuqinhua/phase/covid19/datasets/pro_data") adata1 = ad.read_h5ad('./1_Arunachalam_2020.h5ad') adata3 = ad.read_h5ad('./3_COMBAT_2022.h5ad') adata4 = ad.read_h5ad('./4...
a58966cfb87ea1b516618a5e9cdfa71337fc02ebfabcc26ac3d2f44882287c3c
Python
1,643
54
""" test_demultiplex.py ------------------------------- Tests for the `demultiplex.py` module """ import unittest import os import sys import shutil import utils # Include the parent directory in the PYTHONPATH for relative imports sys.path.append('..') import demultiplex TEST_SAMPLE_BARCODES = {'AGGCATGAGATCGC':...
f7fca686ebe95155b1db077dad5ae0f2526134f5a3612266700a0bca674481e6
Python
1,643
43
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys='surface_vtk_fib.zip') tmp_dir = tempfil...
036a99c26302a1e34709e77143749d8c69148e2cc14092b45c81c71b71205e35
Python
1,644
53
from django.db import migrations, models def fix_default_task_dimension(apps, schema_editor): Task = apps.get_model("engine", "Task") Task.objects.filter(models.Q(data_id__isnull=True) | models.Q(data__size=0)).update( dimension="" ) def restore_default_task_dimension(apps, schema_editor): ...
0a9809ee89d827d00e7140fed509bf68781fdb57abc69926cccc431b387f345a
Python
1,644
52
import scipy as s import scipy.stats as stats from .basic_distributions import Distribution from mofapy2.core.utils import * class Poisson(Distribution): """ Class to define Poisson distributions. Equations: p(x|theta) = theta**x * exp(-theta) * 1/theta! log p(x|a,b) = x*theta - theta - log(x!) ...
96ec5b9a6173d0498a381a60b09e66a3afb67eea3f5f1ea53604a86870114540
Python
1,644
53
"""Test the compat module.""" import sys import pytest from packaging import version from qtpy import PYQT5, PYQT_VERSION, QtWidgets, compat from qtpy.QtCore import QSize from qtpy.QtGui import QImage from tests.utils import not_using_conda @pytest.mark.skipif( ( (sys.version_info.major == 3 and sys.ve...
af163234170d68181d0e4be2fa7355aa980788968a72f5a6c9e01a82e71815d4
Python
1,644
51
import json import os import os.path as osp from argparse import ArgumentParser import pandas from sklearn.metrics import accuracy_score, roc_auc_score, f1_score, precision_score, recall_score def metrics(y: list, pred: list): plog = "ACC: {}".format(accuracy_score(y, pred)) + '\n' + \ "ROC: {}".form...
64d09cdd82f308c75e447519de7177394f33bef4b925e2df42bd71183b7822fc
Python
1,645
23
import argparse from .test import test import torch def main(): parser = argparse.ArgumentParser(prog="rapidparc-test", description="Program to benchmark RapidParc on the test split of the TractCloud dataset") parser.add_argument("--model_name_or_path", type=str, required=True, help="Name of the Model, i.e. `r...
fe7c1f3c497aca04f46175e73419de86ffd63544009efba489425d383fb21ad1
Python
1,646
69
# -*- coding: utf-8 -*- # python standard library inputs import os # external inputs import numpy as np import nibabel as nb def get_surface_voxel(file_in, path_output): """Get surface voxel. Compute surface voxels for to illustrate curvature dependence in surface representations as introduced in ...
1d149bbf1c7796a0f76c866a231f108561102d8afa5f29444148ca2780141963
Python
1,647
53
# -*- coding: utf-8 -*- """ Tools for the analysis of the Graph """ import matplotlib.pyplot as plt import networkx as nx import numpy as np import seaborn as sb import scipy as sc def laplacian(a): n_nodes, _ = a.shape posinv = np.vectorize(lambda x: float(1.0)/np.sqrt(x) if x>1e-10 else 0.0) ...
93cd9c1245820c689002edae219e1a9174fa5a9bf99f3b3392f9564cead91833
Python
1,648
36
import pandas as pd goif = snakemake.input.goi dots_npc = snakemake.input.dots_npc dots_aux = snakemake.input.dots_aux dots_ctrl = snakemake.input.dots_ctrl bedpe_out = snakemake.output.bedpe goi = pd.read_table(goif, header=None) goi.columns = ['chrom', 'start', 'end', 'gene', 'db', 'strand'] npcdf = pd.read_table(...
0cc539d461465b19395a856a0db2bc30f430f4ba851168c9667e5f2b70ed652e
Python
1,649
69
""" nelpy full API ============== ``nelpy`` is a neuroelectrophysiology object model and data analysis suite based on the python-vdmlab project (https://github.com/mvdm/vandermeerlab), and inspired by the neuralensemble.org NEO project (see http://neo.readthedocs.io/en/0.4.0/core.html). """ from . import decoding, fi...
410bb681ff10427c04d6e4e27e4fe5ae9ab23eb37449474c1742651f7dd15b6a
Python
1,649
53
import os import os.path as osp import torch import numpy as np import scipy import pandas as pd import argparse import os import torch_geometric.transforms as T parser = argparse.ArgumentParser(description='display graph features and summary.') #parser.add_argument('-d','--devices', help='Specify CUDA_VISIBLE_DEVICES...
b96668877a55cc7cf9bd158a673beab29110203941ec2b92881958b0d8a12e4c
Python
1,649
56
# 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...
d7787139f9264130f2bc3182f2c7079254d2161448d06a996e4bb6192330f220
Python
1,649
47
import json from copy import deepcopy from pathlib import Path from eir.experiment_io.input_object_io_modules.input_io_utils import ( load_input_config_from_yaml, ) from eir.experiment_io.io_utils import load_dataclass from eir.setup import schemas from eir.setup.input_setup_modules.setup_image import ( Comput...
84dce2d3766b1a2cde8011040011ebea43bf4d6bed7c1b86adbdb9cf169383b4
Python
1,650
46
# Example of how to read a PET DICOM file from a Siemens mMR scanner # The code reads all DICOM files in a folder, sorts them by InstanceNumber and creates a 3D array with the pixel data. # The code also scales the pixel data by the RescaleSlope and RescaleIntercept values to convert the data into the correct units. i...
c96958928297d0de062147bc4b5fb9036bb78e14c9ea0055568333feb3059d32
Python
1,650
54
import numpy as np import torch from eir.data_load.data_preparation_modules.input_preparation_wrappers import ( _should_skip_modality, ) from eir.train_utils.evaluation_modules.evaluation_handlers_utils import ( _streamline_tabular_data_for_transformers, ) class MockLabelTransformer: def __init__(self, n...
695f078280cf458e9c99c01f253f97e9e261410ea7ac0b0162efdbfa148c3be4
Python
1,651
65
import tempfile import pytest gtf_file = 'tests/data/test.gtf' fasta_file = 'tests/data/hg19.nochr.chr17.fa' vcf_file = 'tests/data/test.vcf.gz' exon_file = 'tests/data/test_exons.csv' junction_file = 'tests/data/test_junction.csv' junction_psi5_file = 'tests/data/test_junction_psi5_file.csv' junction_psi3_file = 'tes...
92c522fafd5d23ec695837881c721af89a1ed85825e1394999108aa8f9a641e2
Python
1,652
72
import matplotlib.pyplot as plt import numpy as np def plot_overlap( title, eval_frame, plot_keys=['Motorcortex', 'Hippocampus', 'Cortex'], metric=None, file=None, ): mean = np.zeros(len(eval_frame)) for k in plot_keys: if metric is None: m = eval_...
f73cf0e666bc78436aed624a1b380237246c525ace889e323216b368104035b5
Python
1,652
25
"""System prompts for the RAG agent workflow.""" rag_agent_prompt = """You are an expert research assistant specializing in computational chemistry and scientific literature analysis. You have access to tools for: 1. **Document retrieval** -- loading documents (.txt or .pdf) and querying them for relevant information...
662a7c1fcbc78d543326596dea9a96983882abc48726fb809da79da58902405a
Python
1,654
53
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Shuffle the ordering of streamlines. """ import argparse import logging from dipy.io.streamline import save_tractogram from scilpy.io.streamlines import load_tractogram_with_reference from scilpy.io.utils import (add_overwrite_arg, add_reference_arg, ...
72aea951ad0c9d2f6b3adec39889e0512681d32481efb923b75415ffd4a8c680
Python
1,654
37
import numpy as np def create_mask(cont,arr,x0): #contour, array to inscribe the mask on, position of arr[0,0] for i in range(min(np.array(cont)[:,0])-x0[0],max(np.array(cont)[:,0])-x0[0]+1): calcar=[y for x,y in cont if x==i+x0[0]] if len(calcar)!=0: mini=min(calcar) ma...
d531114fff7cc24ad6197828390ee240344c9ed1d36af9138caac2e4280c8a52
Python
1,654
56
# Generated by Django 3.2.12 on 2022-06-10 18:29 import os import shutil from django.conf import settings from django.db import migrations from cvat.apps.engine.log import get_logger MIGRATION_NAME = os.path.splitext(os.path.basename(__file__))[0] MIGRATION_LOG = os.path.join(settings.MIGRATIONS_LOGS_ROOT, f"{MIGRA...
0b31556fa41f8aa37429e074843da4efb3501ed1f330fee14d2772a6fdcaa610
Python
1,655
48
import sys import subprocess import yaml import pandas as pd import numpy as np script = 'preprocessing/quiet_extraction/extract_from_off_and_trans.py' pathpath = 'PATHS/merge_quiet_paths.yml' with open(pathpath, 'r') as myfile: pathdict = yaml.safe_load(myfile) sys.path.append(pathdict['code']['workspace']) t...
2c2d331c54f7197d1b01b6ed8bed06f7a7c2b29fee9de6a78e35582b476d337b
Python
1,655
51
"""Helper functions to help with reproducibility of models. """ import logging import os import random from typing import Optional import numpy as np import torch log = logging.getLogger(__name__) def seed_everything(seed: Optional[int] = None) -> int: """ Function that sets seed for pseudo-random number g...
ad521cf4ef3f0a142ed2feb1770b2c5344997484ee35e1ba7bfc3ad26c7d8741
Python
1,655
45
import fasttext import fasttext.util import os from pathlib import Path from Deps.CustomFuctions.classes import IMAGENET2012_CLASSES from collections import OrderedDict import torch from tqdm import tqdm script_dir = Path(__file__).parent project_root = Path(__file__).resolve().parent.parent def extract_before_comma(...
cb8aaf842b4c15c0f469ad5e87e07c858f6ac702793b6dedbb132e50a7d231ab
Python
1,656
49
_colors = [ '#d60000', '#e2afaf', '#018700', '#a17569', '#e6a500', '#004b00', '#6b004f', '#573b00', '#005659', '#5e7b87', '#0000dd', '#00acc6', '#bcb6ff', '#bf03b8', '#645472', '#790000', '#0774d8', '#729a7c', '#8287ff', '#ff7ed1', '#8e7b01', '#9e4b00', '#8eba00', '#a57bb8', '#5...
f8e9256e5027282d4822330d9be565ad5e581eda20c4655f6a3f6a931ee6f35b
Python
1,656
58
"""Download and unzip the FlyWire data if not already cached.""" import os import urllib.request import zipfile DATA_URL = ( "https://github.com/BenJourdan/ntac/releases/download/v0.1.0/dynamic_data.zip" ) def download_flywire_data( data_url=DATA_URL, cache_dir=os.path.join(os.path.expanduser("~"), ".ntac...
17d4793dcc8338c74e7e5ee9c131562fc083427a30e16eebadfe47efa284147f
Python
1,657
38
# ============================================================================================================================== # Author: Lucas Berg # ============================================================================================================================== import os import sys import numpy as np i...
1d4836966f7b93aaebad5c3dbd57f473fde510e108509c8dad5e4e3265963fb5
Python
1,657
55
#!/usr/bin/env python from __future__ import print_function import operator, os, sys, subprocess, time ############################################################ # exec_par # # Execute the commands in the list 'cmds' in parallel, but # only running 'max_proc' at a time. #############################################...