sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
fa99a0fd8bd71d08db3b3d3127d3a67d7b6e0afc4053660d8d214e08e7537d5a | Python | 1,954 | 58 | #!/usr/bin/env python
"""
Python interface to the focus_quality library.
Hazen 10/13
"""
import ctypes
import numpy
from numpy.ctypeslib import ndpointer
import os
import sys
import storm_control.c_libraries.loadclib as loadclib
focus_quality = loadclib.loadCLibrary("focus_quality")
c_imageGradien... |
1d97e515ed073ca5ab21b85d67a7cdee591d1962524b648d1024f65f2e2dee3a | Python | 1,955 | 67 | import os
import glob
import numpy as np
import tensorflow as tf
_gpu_configured = False
def _configure_gpu():
global _gpu_configured
if _gpu_configured:
return
gpus = tf.config.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experiment... |
e3bb53ad2766cef1d8f121c49679a550ee6a583c01faa785157af197c1e13179 | Python | 1,955 | 64 | from __future__ import annotations
import argparse
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from models import resnet8_cifar
from mps.supernet import convert_to_supernet, ChoiceConfig
from mps.aihwkit_backend import AnalogConfig
from mps.utils import accuracy_t... |
e0afa9e4f8ca1b352a42bc794b553d07ce9c4e43e3f48824dda05669cd753827 | Python | 1,956 | 44 | import unittest
import os
from PUMI.engine import BidsPipeline
from PUMI.engine import NestedWorkflow
from PUMI.engine import NestedNode as Node
from nipype.interfaces.fsl import Reorient2Std
from PUMI.pipelines.func.deconfound import despiking_afni
from PUMI.pipelines.anat.segmentation import bet_fsl, bet_hd
from PUMI... |
f12af17345613dd209ff4b389045347e87e530df34f8ee988a2f948d34bacb0e | Python | 1,956 | 83 | from os import listdir
import os
import gzip
import sys
from subprocess import call
from os.path import expanduser
import time
import subprocess
UNZIPPED_DIRECTORY = "unzipped/"
ASSEMBLED_DIRECTORY = "assembled/"
walk_dir = sys.argv[1]
if not os.path.exists(UNZIPPED_DIRECTORY):
os.makedirs(UNZIPPED_DIRECTORY)
if... |
5ea0db9ea7e35070139b69ef1cb08784a15be8841ab06bacf26b5981c1095628 | Python | 1,957 | 53 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 4 13:09:08 2019
@author: Yoshi
"""
from correlation_calculator import *
from area_calculator import *
from cell_excitatory_flagger import *
from cell_noise_flagger import *
def cell_flagger(path,cell_flags,key,frequencies,intensities,data,framerate_information,mode=0,t... |
d868275d0645c5b9dd0c3d370d8393807d92c7a3655251a314110d00314df413 | Python | 1,957 | 74 | """Post-hoc calculation of state-spectra using a multitaper.
"""
from sys import argv
if len(argv) != 3:
print("Please pass the number of states and run id, e.g. python 4_calc_multitaper.py 8 1")
exit()
n_states = int(argv[1])
run = int(argv[2])
#%% Import packages
print("Importing packages")
import os
imp... |
99d2a785005ab7509e2aef5eb3c9da469a93fc1d28e39763e8e67442911d1ab5 | Python | 1,958 | 68 | '''
Upsampling anatomy and polished segmentation
'''
import os
import glob
import subprocess
# Set data path
DATADIR = '/Users/sebastiandresbach/data/s1Anfunco/Nifti'
# Set subjects to work on
subs = ['sub-07','sub-09','sub-10']
# Set sessions to work on
sessions = ['ses-01']
for sub in subs:
file = glob.glo... |
49a1d5429d34b3e70d3c87e2db4564b11a23e1556524f29c6a720dd012908ef9 | Python | 1,959 | 52 | # @String(value="<HTML>This script creates an illustration of a tracing canvas.<br>N.B.: Paths can also be exported as vector graphics<br>using <i>Reconstruction Plotter...</i> or <i>Create Figure...</i>",visibility="MESSAGE") msg
# @String(label="Tracing Canvas", choices={"XY", "ZY", "XZ"}, style="radioButtonHorizonta... |
70010005f42d7e36d02a9fbd4c49edf3ed023a20e12a4afb77393fb455640d87 | Python | 1,959 | 39 | def calculate_velocities(directions):
# Separate function to reuse for each direction
def velocities_for_direction(movements):
velocities = {}
# Iterate over each track
for track in movements.keys():
velocities[track] = []
#... |
82fc272f8c524a07c63f26e67058787fbdfec011deb7b859804af3d3c1a66b22 | Python | 1,959 | 68 | #!/usr/bin/env python
"""
Find regions of first bed file that overlap regions in a second bed file. The
output preserves all fields from the input.
NOTE: -u and -d options are currently not functional!
usage: %prog bed_file_1 bed_file_2
-m, --mincols=N: Require this much overlap (default 1bp)
-u, --upstream_... |
c5d4840279c5a5d84babae063b7d830209b1ff7a6fcdb70d50ce1b3a44b5d37b | Python | 1,959 | 51 | #!/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... |
edf24d3cc48005605b7afe3c72f4703f04a74771f7000dd9005b9f9fc388fa80 | Python | 1,959 | 79 | """Abstract class for base evaluator."""
from analogainas.utils import kendal_correlation
"""Base class for Accuracy Evaluation Methods."""
class Evaluator:
def __init__(self, model_type=None):
self.model_type = model_type
def pre_process(self):
"""
This is called at the start of the ... |
2b4178f0a45fdad49c0dc92223f80f218c15e2960fbef5e682cdd2a30bb83614 | Python | 1,961 | 60 | # http://wiki.scipy.org/Cookbook/SignalSmooth
import numpy
def smooth(x,window_len=11,window='hanning'):
"""smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the sig... |
6735ab2f6c2c0aa6f9c5662838fbf34931eaaf9d46a53f366dd25a9441cba64e | Python | 1,962 | 56 | import scipy as s
import scipy.special as special
from .basic_distributions import Distribution
from mofapy2.core.utils import *
class Gamma(Distribution):
"""
Class to define Gamma distributions
Equations:
p(x|a,b) = (1/Gamma(a)) * b^a * x^(a-1) * e^(-b*x)
log p(x|a,b) = -log(Gamma(a)) + a*log(... |
6f82ab6006c50bbd98c773da4f2a2e6336f9d1f5266c6a5034b359775ae31654 | Python | 1,963 | 53 | from pathlib import Path
from typing import Optional
import click
import dolfin as df
import panta_rhei as pr
def collect_mesh_data(
domain_data: Path,
concentration_data: Path,
parcellation_data: Path,
output: Path,
dti_data: Optional[Path] = None,
):
hdf = df.HDF5File(df.MPI.comm_world, str... |
b79f4a48117c0c3138898cbc0d99728c9451021f122453c1eff04df31ba48f78 | Python | 1,963 | 47 | #!/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
from scipy.cluster.hierarchy import ClusterWarning
from warnings import simplefilter
# If they already exist, this only takes 5 seconds (check md5su... |
cdb02fcaa6ec29287598443f227545cacf4ef423f1539ff25bfddd0df14310f7 | Python | 1,963 | 61 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from logging import Logger
from pathlib import Path
import django_rq
from django.conf import settings
from rq.job import Job
from cvat.apps.engine.log import get_migration_logger
from cvat.apps.engine.utils import take_by
from cvat.apps.redis_handl... |
e9531916b1c0351e556e7e750d4c1f81f5d9508dead28a71927097e1ebf855a0 | Python | 1,963 | 89 | #!/usr/bin/python
#
## @file
#
# Nikon TiU stage communication (using Micro-Manager).
#
# Hazen 4/15
#
import MMCorePy
## TiUStage
#
# Encapsulates control of a Nikon TiU stage.
#
class TiUStage(object):
## __init__
#
def __init__(self):
self.dev_name = 'TIXYDrive'
self.mmc = MMCorePy.CMM... |
52e07584171e6e054ffbbf9c8e0b2f5beb1f1ed1543fb7f5694d8f79df8b6170 | Python | 1,964 | 63 | # !/usr/bin/env python
# coding: utf-8
# @Time : 2022/7/17 13:54
# @Author : Z.-H. G.
# @Email_0 : guozhenhao17@mails.ucas.ac.cn
# @Email_1 : guozhenhao@tongji.edu.cn
# @File : params.py
# @IDE : PyCharm
import pandas as pd
# TODO yaml
PARAMS = \
{'preprocess':
{
'path': './dataset/... |
ce21e9eed813b219a0f601e1106f89948cdfed130f033802dc4f2496d460904f | Python | 1,964 | 39 | import os
import numpy as np
import pandas as pd
import scanpy as sc
import anndata as ad
adata = sc.read_h5ad('adata_U54_BA9_splotch_lambdas.h5ad')
print(adata, flush=True)
# Cap lambdas for each gene to their 99th percentile to remove effect of outliers ... |
5c3c811f5c14cb46eb3699051c17617aa536f9a485aeedb0ffcde8a954b76af6 | Python | 1,965 | 49 | from brainvoice.configuration.configuration_yaml_loader import ConfigurationYamlLoader
import yaml
import os
import copy
class ConfigurationParser(object):
PARENT_NODE = 'parent'
def __init__(self, root_config_file):
self.root_config_file = root_config_file
self.root_config_dict = None
... |
c8d8e4c5882e2ffe251b99b23ac14fbc85b624cf7173830c0e667b89cf4f4be8 | Python | 1,965 | 72 | """
This script plots heatmap of eye gaze positions during collect phase of task.
"""
import numpy as np
import matplotlib.pyplot as plt
def plot_heatmap_from_trials(X, Y):
"""
Plots a 2D histogram (heatmap) of all (x, y) points aggregated from the
list-like objects X, Y. Returns the figure and axes hand... |
a7a0d67ddbfc6a7245c07b70b2e64e572d55afcc9227d0d364744258a016402b | Python | 1,966 | 62 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from logging import Logger
from pathlib import Path
import django_rq
from django.conf import settings
from rq.job import Job
from cvat.apps.engine.log import get_migration_logger
from cvat.apps.engine.utils import take_by
from cvat.apps.redis_handl... |
f64456d65ab90e155526c88587d0f30f1d1c90e71afb5ae11df4722a27a38328 | Python | 1,966 | 61 | from nelpy.utils import PrettyDuration
class TestPrettyDuration:
def test_1(self):
t = PrettyDuration(180)
assert str(t) == "3:00 minutes"
def test_2(self):
t = PrettyDuration(179.999999)
assert str(t) == "3:00 minutes"
def test_3(self):
t = PrettyDur... |
5cc1601af215881cf52d1f5651f90752e07e59faf30b3bc379114a826d6947ca | Python | 1,967 | 76 | import sys
import getopt
import numpy as np
import pandas as pd
import anndata as ad
def usage():
print("""
Usage : python3 s01.CellCor.py <-i in.lst>
[-o output folder, default ./]
example of in.lst
```
time0
time1
time2
time3
```
and we will load time0.h5ad, time1.h5ad, tim... |
70e68519264af856ccb77e222904a3c217c946bf9d5eae740c68aec46e5a2094 | Python | 1,967 | 43 | import numpy as np
from brainscore_core.supported_data_standards.brainio.assemblies import BehavioralAssembly
from brainscore_core.supported_data_standards.brainio.packaging import package_data_assembly
import pandas as pd
'''
Experiment Information:
https://www.sciencedirect.com/science/article/pii/S2589004222011853... |
cb954943de6c8bbd66520fffc90b8fc35adc93683bc34acaf18aa999814f86fc | Python | 1,967 | 58 | # Copyright (C) 2018-2022 Intel Corporation
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from django.conf import settings
from django.urls import include, path
from django.views.generic import RedirectView
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSw... |
b1f0b0960b993790d81b0933c68914ba5da5589d560e3859cf2f1e4cb7441e65 | Python | 1,968 | 52 | import argparse
from PUMI.engine import BidsPipeline
from PUMI.pipelines.anat.segmentation import bet_hd
import os
if __name__ == '__main__':
ROOT_DIR = os.path.dirname(os.getcwd())
input_dir = os.path.join(ROOT_DIR, 'data_in/pumi-unittest') # path where the bids data is located
output_dir = os.path.join... |
f86c6de93d1e12ba5ffdabd661becfcb91f8f4480b13b9426051ab3a7b9282bb | Python | 1,968 | 55 | try:
from setuptools import setup, Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
import sys, platform
sys.path.append('python')
extra_compile_args = ['-DHAVE_KALLOC']
include_dirs = ["."]
if platform.machine() in ["aarch64", "arm64"]:
include_dirs.appen... |
2bee49abea634562d1b59d207eac12c9dd0ca364e02da278c8c4152c3f2a495b | Python | 1,969 | 62 | """
PyVISAScope provides an interface to different scopes.
Copyright (C) 2016 Ye-Sheng Kuo <yesheng.kuo@gmail.com>
Copyright (C) 2019 Julius Zimmermann <julius.zimmermann@uni-rostock.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Publi... |
cf2b371490e86885502610f9d85c93ca59dc8847432d6025b257798c0a1e056a | Python | 1,969 | 53 | """Using for merged ab-ig graph
"""
import sys
sys.path.append('..')
from torch import nn
# from layers.predictor import Predictor
from torch.nn import Linear, Sequential, Dropout
from common import utils
from common.mapping_utils import get_pooling_operator, get_activation_layer
class AbEpitope(nn.Module):
def _... |
1dff15ff583f7bd58f1fca4fae155d026bec058686e0467c16c4a66c0b8cf1e6 | Python | 1,970 | 57 | import json
from copy import deepcopy
from pathlib import Path
from eir.experiment_io.io_utils import load_dataclass
from eir.experiment_io.output_object_io_modules.output_io_utils import (
load_output_config_from_yaml,
)
from eir.setup import schemas
from eir.setup.output_setup_modules.image_output_setup import (... |
eb8eb90ef1126da2b06bc4fbc9846ccd75f1f6fdd3449bfde6b06ea013c5ef73 | Python | 1,971 | 55 | import os
import sys
import pandas as pd
from pysnptools.snpreader import Bed
from pysnptools.snpreader import Pheno
from fastlmm.association import single_snp
import argparse
import pylab
import fastlmm.util.util as flutil
from fastlmm.util.stats import plotp
def main():
# Set up argument parser
parser = arg... |
01bd236f8ce3ecba9ee3408b08c3fba800f29d90dc194509d107d3f2dbbac5e9 | Python | 1,972 | 47 | class Defaults(object):
window_size = 7
filter_nums = [100, 100, 100]
filter_sizes = [3, 4, 5]
hidden_sizes = [1200]
hidden_activation = 'relu'
max_vocab_size = 1000000
optimizer = 'adam'
learning_rate = 1e-4
epochs = 20
iobes = True # Map tags to IOBES on input
max_tokens... |
6c1f48760d24f35012f7e1370c7796409746a19150327d7c735ffec4538cd590 | Python | 1,972 | 74 | """Utilities for cropping NIfTI images to a target shape."""
import nibabel as nib
import numpy as np
def calculate_bounds(
image: np.ndarray, target_shape: tuple[int, int, int]
) -> list:
"""Computes per-axis slice indices to crop image to target_shape,
centred on the bounding box of non-zero voxels.
... |
a6eeb7afe8f5e231a39a521f65d4b3be18a1ed10254f888786ac40d4dbae4948 | Python | 1,972 | 54 | from nilearn import datasets, plotting
import pandas as pd
import numpy as np
def plot_brain_map(data_dir, hemi, z2) :
""" Function to plot the brain map of the normative model predictions
Arguments
----------
data_dir: string
path to the data directory
hemi: string
... |
c36726ff23df456a2b27e6c19ad713ab41f1f783db9b4a324fb54fe2008940d5 | Python | 1,972 | 47 | import torchvision
import torch.nn as nn
import torch
class ScalePatchNet(nn.Module):
def __init__(self,patchSize,outFeatures=512) -> None:
super(ScalePatchNet, self).__init__()
self.baseBackbone = torchvision.models.efficientnet_v2_s(weights = torchvision.models.EfficientNet_V2_S_Weights.IMAGENET1... |
e2c867a4112f7138cac9ac4c1213e5fbbdd7e7de11268c2dc3529454c0f501b7 | Python | 1,972 | 52 | import sys
import os
import numpy as np
import pandas as pd
from MIND_helpers import calculate_mind_network, is_outlier
from get_vertex_df import get_vertex_df
def compute_MIND(surf_dir, features, parcellation, filter_vertices=False, resample=False, n_samples = 4000):
vertex_data, regions, features_used = get_vertex... |
7f557f988dca8640266634fdb7f9d97089f261d4593ee660b840d9c633d86663 | Python | 1,974 | 48 | from curses import meta
import torch
import torch.nn as nn
import torch.nn.functional as F
# inspired by : https://github.com/HobbitLong/SupContrast/blob/master/losses.py
# Metadata-aware Contrastive Loss
class MetaCL(nn.Module):
def __init__(self, temperature=0.06, weights=None):
super().__in... |
a592b9a34d41d4149f6984ca071c149f10762209327e0ee6845de0e24179dbc8 | Python | 1,974 | 56 | import os
from typing import List
import hydra
from omegaconf import DictConfig
from pytorch_lightning import LightningDataModule, LightningModule, Trainer, seed_everything
from pytorch_lightning.loggers import LightningLoggerBase
from {{cookiecutter.project_slug}} import utils
log = utils.get_logger(__name__)
def ... |
57a3dcb7bbae7abec12498aeef955fad028dd9cde8d19d9c743b208773d49330 | Python | 1,975 | 69 | # -*- coding: utf-8 -*-
"""
Visualization of PSF data across cortical depth.
"""
# python standard library inputs
import os
# external inputs
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter
# input
path = "/data/pt_01880/test" # path to saved input values
nlayer... |
b63f8dc2ce0d643cbb6813295ff52ebe0cb77ce6a17cc8b1a25ef8b6179f6716 | Python | 1,975 | 55 | """Input schema for the molecular docking tool."""
from typing import Literal
from pydantic import BaseModel, Field
class docking_input_schema(BaseModel):
"""Parameters for docking a small-molecule candidate into a receptor."""
candidate: str = Field(
description=(
"Molecule to dock, as... |
0aa4bbfcd3108a15fcf601301551dbc8c11981a1274a5246a72b96ab2de2f072 | Python | 1,976 | 48 | import torch
from torch import Tensor
import torch_geometric.typing
from torch_geometric import is_compiling
from torch_geometric.typing import torch_scatter
def segment(src: Tensor, ptr: Tensor, reduce: str = 'sum') -> Tensor:
r"""Reduces all values in the first dimension of the :obj:`src` tensor
within the... |
84e84c9068dbc91cc9b7d4b9e5664aa38bc6a953228d697f675bb3a39ec145bd | Python | 1,976 | 67 | """Local Parsl configuration for development and single-node runs.
Uses ``HighThroughputExecutor`` with a ``LocalProvider`` (no MPI
launcher, no PBS/Slurm dependency). Suitable for laptops, CI runners,
and single-node workstations where the Parsl backend is desired but no
HPC scheduler is available.
"""
from __futur... |
850f38fdb24ca566895098a9bc886c2f478adf825b1ace43f89996a952216880 | Python | 1,976 | 68 | from typing import Dict, List
import torch
from yacs.config import CfgNode
# DOCUMENTED
class Sigma:
"""an adjustable sigma parameter for training."""
def __init__(
self,
adjustments: List[Dict[str, float]],
initial_sigma: List[float] = [0.1, 0.1, 0.8],
device="cpu",
):... |
4f930f04f720c2e01dd78a7a945fcb6f2b0ad34d3f18b8c92d9bdb7beae0fc81 | Python | 1,977 | 53 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 31 11:12:54 2023
@author: axthi
"""
import sys
import argparse
path_to_utils = 'C:/Users/axthi/simnibsN/memoslap_utils/' # NOTE: change to your memoslap git directory
sys.path.append(path_to_utils)
import simnibs_memoslap_utils as smu
def _get_positions(project_nr, ... |
e9a344a242f0793644b3136e3a132d801212ba88931e62231d84d68781bb68ff | Python | 1,977 | 65 | from ..qt import *
from ..util import IterableQueue
from .. import thalamus_pb2
from .. import thalamus_pb2_grpc
from ..task_controller.util import create_task_with_exc_handling
import asyncio
import time
import logging
LOGGER = logging.getLogger(__name__)
class AnalogWidget(QWidget):
def __init__(self, config, stu... |
041cc20c64c4bc5989f0ddd42665d2e93f9c64cb133a07928b033ed32b90a894 | Python | 1,979 | 59 | #!/usr/bin/env python2.4
"""
Returns all positions of a maf with any pwm score > threshold
The positions are projected onto human coordinates
"""
import sys
import bx.pwm.position_weight_matrix as pwmx
from bx.align import maf as align_maf
from bx.pwm.pwm_score_maf import MafBlockScorer
def main():
if len(sys.a... |
6ffa8359b65d6cba08442c2d803ff9c01fc73a747dc4628edf7cba7f977a8d20 | Python | 1,979 | 72 | """Utilities for adding, merging, and splitting temporal dimensions."""
import torch
from torch import nn
class AddTemporalDim(nn.Module):
"""Add a temporal dimension to the input tensor."""
def __init__(self, T: int) -> None:
"""Initialize the temporal expander.
Args:
T: Number o... |
7f6f3cfa4a32e732681c34d18ccd75acccccc6532fdc162fed31d09a6201c96f | Python | 1,979 | 36 | import os
import shutil
from nipype.interfaces.base import CommandLineInputSpec, File, TraitedSpec, CommandLine, BaseInterfaceInputSpec, BaseInterface
from traits.api import Str, Int, Directory, Bool, Either
class SynthMorphInputSpec(CommandLineInputSpec):
moving_image = File(exists=True, desc="The moving image to... |
154fa0f4eb1302c35f31a68d55fae6944502523c0cb5920259c2917c689b3852 | Python | 1,980 | 51 | import sys
import subprocess
from glob import glob
import os
import yaml
import pandas as pd
import numpy as np
#whether offdet is usable will be obtained directly from offdetfile, licking is obtained directly from aRec, opto is blocked according to stimdir
script = 'quiet_active_stats/calc_proportionsExcluded.py'
... |
9b619eb9036775457af9b84891d65d96e34099e35e110486a2e679df6502b787 | Python | 1,980 | 87 | #!/usr/bin/env python
"""
This script is used to add splicing variations from STDIN .BED file.
Usage: addvariation2splicingbed.py {OPTIONS}
OPTIONS
ATTENTION:
HISTORY
01/09/2012
"""
from __future__ import print_function;
import sys;
import subprocess;
import pydoc;
import os;
import random;
import bisect;
impo... |
9e89e74bb37effb625a0221d9ccbd68b78abceb06881c1378a959b7b77486e9b | Python | 1,980 | 72 | """Utility for downloading files over HTTP with optional GitHub blob
decoding."""
import base64
import json
import math
import requests
from tqdm import tqdm
def download_file(
url: str,
destination: str,
description: str | None = None,
decode_github: bool = False,
) -> bool:
"""Downloads a file... |
9e9b77a672e51f5afba68208913ed4ce9449cf5f4d9e553036c4dafdbd7b7a50 | Python | 1,980 | 54 | import pytest
from qtpy import PYQT5, PYQT_VERSION, QT6
from tests.utils import using_conda
@pytest.mark.skipif(
QT6 and using_conda(),
reason="QPositioning bindings not included in Conda qt-main >= 6.4.3.",
)
def test_qtpositioning():
"""Test the qtpy.QtPositioning namespace"""
from qtpy import QtPo... |
b86186ab9c9b5d4344524ba1c8e90c7b9631797c14b3a9375cb97e86bcc20bfc | Python | 1,980 | 36 | import numpy as np
from numba.core import types
from numba.typed import Dict
def ParameterOptionsExperimental():
opt = Dict.empty(
key_type=types.unicode_type,
value_type=types.float64[:],
)
# Scanner properties
opt['gamma'] = np.asarray([2 * np.pi * 42.58 * 10**6], dtype='f8') # Gyro... |
d97ce37c4b155890c2740bfcfbad0413cd7e3aad18df6fcb5a6540af71de8129 | Python | 1,980 | 79 | #!/usr/bin/env python2
import sys
import os
import signal
import gzip
from optparse import OptionParser
USAGE = """
extract-from-fastq36.py --in <fastq.gz file>
"""
parser = OptionParser(USAGE)
parser.add_option('--in',dest='inFASTQ', help = 'input fastq.gz file')
#parser.add_option('--out',dest='outBase', help ... |
468b29a0bd2c67bb97d4e1b0b16d23e2efb6614ba27e0f5dff35fa19b82e26dc | Python | 1,982 | 86 | import os
import pytest
def pytest_configure(config):
"""Configure the test environment."""
if "USE_QT_API" in os.environ:
os.environ["QT_API"] = os.environ["USE_QT_API"].lower()
# We need to import qtpy here to make sure that the API versions get set
# straight away.
import qtpy
def ... |
600df8049c3919579b15d89c9fa88dc73735d46d1c300bbea396761ce3a1f1f5 | Python | 1,982 | 70 | # Generated by Django 3.2.15 on 2022-08-09 12:36
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("engine", "0057_auto_20220726_0926"),
]
operations = [
migrations.RemoveField(
model_name="labe... |
94b6f3d880c7cbfde719a377624822643d6abfd7cf42882ebeeceed388478cf6 | Python | 1,982 | 80 | from types import SimpleNamespace
from unittest.mock import Mock
import matplotlib
import pytest
# QuadrantFoldingGUI selects the interactive QtAgg backend at import time.
# Rendering is irrelevant here, and CI may not provide a display server.
_matplotlib_use = matplotlib.use
matplotlib.use = lambda *_args, **_kwarg... |
07e504d5f34fee3f6e2d5aa473130ed36330f46893efd074be746e8f5a56f4c3 | Python | 1,983 | 72 | """Pydantic configurations for prediction targets."""
from abc import ABC
from typing import Annotated, Any, Callable, Literal
import numpy as np
from numpy.typing import ArrayLike
from pydantic import BaseModel, Field
class BaseTargetConfiguration(BaseModel, ABC):
"""Base configuration for a prediction target.... |
9d06b6134e96b572a67e0262335bff8bc18fe913663a4421c323769490cdae2f | Python | 1,983 | 57 | import torch
import torch.nn as nn
import torch.nn.functional as F
# BS模块
class SqueezeBodyEdge(nn.Module):
def __init__(self, inplane):
"""
implementation of body generation part
:param inplane:
:param norm_layer:
"""
super(SqueezeBodyEdge, self).__init__()
... |
80bba06dd4baa395ee99af468a6f9510dea7cf8725b623d9dfd4d2acd8309797 | Python | 1,984 | 63 | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
import mmcv
from packaging.version import parse
from .version import __version__, version_info
MMCV_MIN = '1.3.7'
# MMCV_MAX = '1.4.0'
MMCV_MAX = '1.5.0' # have tested on mmcv==1.5.0
def digit_version(version_str: str, length: int = 4):
"""Convert... |
bcdd0238cdf224f3c8921e716b9f08e562f204e8fd871f9ae76b0455720d74c9 | Python | 1,984 | 55 | try:
from mamba_ssm import Mamba
except ModuleNotFoundError:
Mamba = False
from torch.cuda.amp import autocast
import torch
import torch.nn as nn
__all__ = ['MambaLayer']
class MambaLayer(nn.Module):
def __init__(self, channels, d_state=16, kernel_size=4, expand=2, nd=None):
"""Mamba Layer.
... |
383f526e540bf7a42957a7a02d531f3c4e4c0531d05c1eaf2a4a50ab0a4cc328 | Python | 1,985 | 76 | import torch.nn.functional as F
from scipy.stats import kendalltau
from scipy.stats import spearmanr
import math
ALPHA = 0.05
def accuracy_mse(prediction, target, scale=100.0):
prediction = prediction.detach() * scale
target = (target) * scale
return F.mse_loss(prediction, target)
def kendal_correlation... |
b30dc3b6a5b8ab174e0164cee2be785524002306ca1cf76e4734045aa5ba26dd | Python | 1,985 | 54 | """
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... |
deb2ee49e0c12cc9bec7dc8e8e204263a8f6988fe26c1af01a0d8fe23224e189 | Python | 1,985 | 52 | #!/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... |
062894efad7f4f39ab9dbfa53999eae1ab8e74611651ed8ee8869f75a20a64db | Python | 1,986 | 55 | import nilearn.reporting
import nilearn.glm.thresholding
from nilearn.image import new_img_like
import fire
import pickle
import numpy as np
def main(task="category", contrast="shape1", kids=False):
data_path = "../bids_dataset/derivatives"
iskids = 'kids' if kids else 'adults'
ref_data = pickle.load... |
2bda03b133b5baa51a61fdbdf7e15a9e0c23319c4a40833a687027c0c324bda1 | Python | 1,986 | 52 | from brainvoice.configuration.configuration import Configuration
import numpy as np
import os
import torch
import glob2
def load_model_and_data_from_config(checkpoint_path, device, experiment_name):
random_seed = 1234
experiment_name = f'models/{experiment_name}'
# Manual seed
torch.manual_seed(rand... |
48958e02385830c3af3ca1eb265dfca1e3218ee28dd3fcc60baa8bab7828a99f | Python | 1,986 | 61 | """Search Experiment Runner."""
import os
import csv
import numpy as np
from analogainas.search_spaces.config_space import ConfigSpace
from analogainas.search_spaces.resnet_macro_architecture import Network
"""Wrapper class to launch NAS search."""
class Worker():
def __init__(self,
cs: ConfigSp... |
fa66b62a5767a2749cb59272dda13a5a3e12702a2399adcf39e18b44bd5d11c1 | Python | 1,986 | 46 | """
Iter-6 record attempt — EVA-02 Large (MIM-pretrained ViT, merged-38M + IN22k/IN1k fine-tune, 448px).
Diversity bet #2. EVA-02 is masked-image-modeling pretrained (reconstructs CLIP features) then ImageNet
fine-tuned -> a self-supervised-style ViT with one of the strongest transfer/representation profiles, and
it s... |
21dde21cf50392b764ca5106180ddfd45b2924b834295a45527f29105c15f624 | Python | 1,987 | 78 | """Predict a class label using neuroimaging features.
Note, this script doesn't require osl-dynamics, it uses scikit-learn
to train a machine learning model.
This script should achieve an accuracy of ~0.78.
"""
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
... |
ac8001a72398cc0b91c379fda9774e7dba577a8eb334b45a4e76dc897775208a | Python | 1,987 | 64 | """Step 4: Forward Model and Source Reconstruction."""
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
from osl_dynamics.meeg import parallel, rhino, source_recon
from osl_dynamics.utils.filenames import OSLFilenames
# ----------------------------------------------------------------------------
input... |
2d64cec2f264efc40edfceccb093054b3a0a45fa6ad12bcbf400cbdd9e85aacc | Python | 1,988 | 57 | #!/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... |
c09bb1719517a29beea0df10a87eb16f750f40c37ee36a374c189a7ecabe821b | Python | 1,988 | 56 | # 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 torch import nn
class ModuleProxyWrapper(nn.Module):
"""
Wrap a DistributedDataParallel module a... |
4ec3f7d9b0ee78a00001646879c65b6abecb0cec92bcb7d89528f35e553373d1 | Python | 1,989 | 60 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from abc import ABC
from collections.abc import Sequence
from enum import Enum
from cvat_sdk import models
from cvat_sdk.core.proxies.model_proxy import _EntityT
class AnnotationUpdateAction(Enum):
CREATE = "create"
UPDATE = "update"
D... |
4ede290bf7c3a6c3cc03538aa2f7099397486caa01af0496bd371b7f866d030d | Python | 1,989 | 64 | from __future__ import annotations
from pathlib import Path
import pytest
# Skip when the optional 'academy' extra is absent; the runtime
# subpackage imports academy.* at module level.
pytest.importorskip("academy")
from chemgraph.academy.runtime import compute_launcher
from chemgraph.academy.runtime.compute_launc... |
7ed04552f02181f4fbfe68bb14e63853b8e0c75bebd1fe0eb7be4811c8dc5e33 | Python | 1,992 | 52 | """ Test Time Pooling (Average-Max Pool)
Hacked together by / Copyright 2020 Ross Wightman
"""
import logging
from torch import nn
import torch.nn.functional as F
from .adaptive_avgmax_pool import adaptive_avgmax_pool2d
_logger = logging.getLogger(__name__)
class TestTimePoolHead(nn.Module):
def __init__(sel... |
8a68a4267762d998374d956e52f8bce708ec2fc53531dbd7e98339d44c5bf618 | Python | 1,992 | 51 | #Lucas Sancéré -
import copy
from itertools import product
import numpy as np
from PIL import Image
##### SEGMENTER OUTPUT CONVERSIONS AND PROCESSING
def change_pix_values(file: str, valuestochange: list,
newvalues: list):
"""
Change given pixel values into given newvalues.
Follow... |
1bacd67ae58f04fd1f68f584345f447f992d71c6b2da93a1a2044531f962a973 | Python | 1,994 | 55 | import socket
import nidaqmx
import datetime
from time import time, ctime
from psychopy import visual, monitors, core
from VideoCallStim import liveactiveblock, staticactiveblock, restblock, liveruntask, staticruntask
import time as tm
# Initialise psychopy
win = visual.Window([1920, 1080], screen=1, monitor=... |
bb58865a5124d1f1a9aa221551e30c0c99aa589d342c36f2b7c634046e680dda | Python | 1,994 | 53 |
# plv distribution
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from numpy import loadtxt
from scipy.stats import ttest_rel
from pathlib import Path
cur_dataset = Path.cwd() / "data"/ "plv_distribution.txt"
raw_data = loadtxt(cur_dataset, dtype=str).astype(float)
cur_table = raw_data[:,0]
th... |
43d397b34eb26de83968b51868de7e883159679445e93a8388062357e94ebb3c | Python | 1,995 | 70 | # -*- coding: utf-8 -*-
#
# test_contexts_arbmpi.py
import unittest
import arbor as arb
from .. import cases
"""
all tests for distributed arb.context using arbor mpi wrappers
"""
@cases.skipIfNotDistributed()
class TestContexts_arbmpi(unittest.TestCase):
# Initialize mpi only once in this class (when adding c... |
61a13ffd310960751c1242268262aa77e145ab14ff80493ac9f9837a9b406379 | Python | 1,995 | 79 | #!/usr/bin/env python
import sys
import os
import signal
import gzip
from optparse import OptionParser
USAGE = """
extract-from-fastq36.py --in <fastq.gz file>
"""
parser = OptionParser(USAGE)
parser.add_option('--in',dest='inFASTQ', help = 'input fastq.gz file')
#parser.add_option('--out',dest='outBase', help =... |
a63ba8c15f976988dc6e2f26453fc384fb086fe9fbdf7e5b162028a9ba577cdd | Python | 1,995 | 57 | import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib
import TwoD_fun
xlabel = ['Brownian motion', 'Lévy flights']
ticksize = 14
labelsize = 18
linewidth = 1.5
custom_color1 = '#F18D00'
custom_color2 = '#009FB9'
def plot_4_3(simulation = 0):
fig = plt.figure(figsize = (9,4... |
1671f46cdd27c16c445e6f9ba370a6719e4f797a90eb5daefe7685dfe8c9273b | Python | 1,996 | 47 | import pytest
from qtpy import PYQT5, PYQT_VERSION, PYSIDE2
from tests.utils import pytest_importorskip
@pytest.mark.skipif(PYSIDE2, reason="QtDesigner is not available in PySide2")
def test_qtdesigner():
"""Test the qtpy.QtDesigner namespace."""
QtDesigner = pytest_importorskip("qtpy.QtDesigner")
asser... |
c2d922d6fd1c3de74f909c632fb4c5256eda83564753633726cd2e713a92f540 | Python | 1,996 | 64 |
from torch_geometric.data import Dataset, download_url,Batch,Data
import torch
import os
import numpy as np
from torch_geometric.loader import DataListLoader, DataLoader
import random
class Cath(Dataset):
'Characterizes a dataset for PyTorch'
def __init__(self, list_IDs, baseDIR,transform=None, pre_transform... |
42f47884bfae126c92ffe9d968f8e6fa55efd499b649f64c4b7dea0ec7f50e9e | Python | 1,997 | 59 | from fancyimpute import NuclearNormMinimization
import numpy as np
from low_rank_data import XY, XY_incomplete, missing_mask
from common import reconstruction_error
def create_rank1_data(symmetric=False):
"""
Returns 5x5 rank1 matrix with missing element at index (1, 2)
"""
x = np.array([1, 2, 3, 4, ... |
48a6ae868a927c6686aea54a014bcda3cbf6815f71115afc3ce5f296a3e04253 | Python | 1,997 | 73 | import datajoint as dj
from datajoint.jobs import key_hash
from . import experiment
schema = dj.schema('pipeline_notification', locals())
# Decorator for notification functions. Ignores exceptions.
def ignore_exceptions(f):
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
e... |
092ad33fee51321e638c794cbc14128ba447373de5d522b38a801f2fcd854831 | Python | 2,000 | 47 | import torch
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import softmax
import torch.nn.functional as F
class SimpleHGN(MessagePassing):
def __init__(self, in_channels, out_channels, num_edge_type, rel_dim, beta=None, final_layer=False):
super(SimpleHGN, self).__init__(aggr = "... |
5296a4141a7561bb77acf54cc4ab2c34e8a51c1a983d4845368c6e1eeac4f962 | Python | 2,000 | 64 | # !/usr/bin/env python
# coding: utf-8
# @Time : 2022/7/17 13:54
# @Author : Z.-H. G.
# @Email_0 : guozhenhao17@mails.ucas.ac.cn
# @Email_1 : guozhenhao@tongji.edu.cn
# @File : params.py
# @IDE : PyCharm
import pandas as pd
# TODO yaml
PARAMS = \
{'preprocess':
{
'path': './dataset/... |
6e0efbe4b1f4018b084d9f95a26f79db8ed2f94d77487fe047fe59e980a648c2 | Python | 2,001 | 61 | # -*- coding: utf-8 -*-
# external inputs
import numpy as np
# local inputs
from ..io.affine import vox2ras_tkr
from ..utils.apply_affine_chunked import apply_affine_chunked
from ..utils.interpolation import nn_interpolation3d, linear_interpolation3d
# linear and nearest neighbor sampling functions
_sampler = {"line... |
913f5e6b680d0f2f6dbf0604b0f5fff136a82e3062cc3f606a4e093be61abfc6 | Python | 2,001 | 58 | import user_features as uf
import csv
import ijson
import pandas as pd
import time
def get_user_vector(user):
user_vector = {
"id": uf.get_user_id(user),
"screen_name_length": uf.get_screen_name_length(user),
"description_length": uf.get_description_length(user),
"account_longvity"... |
f3e3ca57e3e9393e45cd79568c48e69e3fb12d1f2abce656b1d755afa2b5e613 | Python | 2,001 | 64 | import unittest
import warnings
from unittest.mock import patch
from rscvp.model.rastermap.main_rastermap_2p import RunRasterMap2POptions
from rscvp.model.rastermap.main_rastermap_wfield import RunRasterMapWfieldOptions
from rscvp.model.rastermap.rastermap_2p_cache import RasterMap2PCacheBuilder
from rscvp.model.raste... |
46e96105e7364496b03d9fbb2bbacdb3015ddda422032d36fe49a13576975847 | Python | 2,002 | 54 | import os
import sys
import tkinter as tk
from PIL import Image, ImageTk
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
class BaseWindow(tk.Tk):
def __init__(self, title="... |
6387b730f5b992a29bf9598c273f329f7fe26e3e659b3f2ba9574ee878ec26f2 | Python | 2,002 | 51 | """
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... |
e3ad83fd3850c7aeed63da70288f0e257180c2f1c622b5b17bba164787eef908 | Python | 2,002 | 62 | from __future__ import print_function, absolute_import
import time
from .utils.meters import AverageMeter
class ClusterContrastTrainer(object):
def __init__(self, encoder, memory=None):
super(ClusterContrastTrainer, self).__init__()
self.encoder = encoder
self.memory = memory
def trai... |
3be6ef4b6f6794d5fb281d249e83b12316ced3d8e52a3f90459c173c17b68ef3 | Python | 2,003 | 58 | #!/usr/bin/python
#
## @file
#
# Based on a quick read of the recipe xml file, chooses
# the appropriate generator to convert the xml into a
# series of DaveAction XMLs.
#
# Hazen 05/14
#
import os
from xml.etree import ElementTree
from PyQt5 import QtCore, QtGui, QtWidgets
import storm_control.dave.xml_generators.v... |
d8c35fdb5d1846bf227261bdfaee9ff8f846f19aef80a9348cf22a0dbec08fd0 | Python | 2,003 | 51 | from torch import nn, Tensor
from custom_layers.custom_module import BatchEvalModule
from custom_layers.dense import Dense
from custom_layers.multihead_attention import MultiHeadAttention
# Implements a transformer encoder as in "Attention is all you need" Vaswani et al. 2017
# Combination of Self-Attention and per ... |
dfd9a836d3a458150977fb7b51cc8d2f235b5f662eebd60d6f31edbdba66a515 | Python | 2,004 | 84 | # Figure 2
import numpy as np
from scipy.constants import epsilon_0 as e0
import impedancefitter as ifit
from impedancefitter.double_shell_wall import eps_cell_double_shell_wall
from impedancefitter.suspensionmodels import bhcubic_eps_model, eps_sus_MW
em = 5.0
R0 = 2.75e-6
dw = 250e-9
Rc = 2.75e-6 - dw
dm = 7e-9
km... |
881ab271e2a2456f35bca7ebb88acb22b0e4cc23cc5f04b479ee3f9ac15f7996 | Python | 2,006 | 59 | from typing import Annotated, Any, List, Tuple, Optional
from pydantic import BaseModel, Field
from container import Container
from model.base_dao import BaseDao
from model.bsom_object import PyObjectId
from bson.objectid import ObjectId
class TopicModel(BaseModel):
model_name: str
database_name: str
k: in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.