sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
f4d02bec96f7f7fcdb08716c2458ab2be552c10d74eedf307192029a9801cef2
Python
1,119
40
import shutil from pathlib import Path import numpy as np from datasets.download import DownloadManager from brainways.utils.paths import get_brainways_dir def _load_sample_project(annotated: bool): if annotated: project_name = "sample-project-annotated" else: project_name = "sample-project"...
0af6f97d2763af34d540e079c90a5c69e00a4961adc9668c5ae3d229ffbc78d0
Python
1,120
45
#!/usr/bin/env python3 from pathlib import Path import arbor as A from arbor import units as U cat = Path("cat-catalogue.so").resolve() class recipe(A.recipe): def __init__(self): A.recipe.__init__(self) self.tree = A.segment_tree() self.tree.append(A.mnpos, (0, 0, 0, 10), (1, 0, 0, 10)...
802cd1373d70289fa853ce4a5015c2b284898b699bd610eeea80307a9e636d57
Python
1,120
53
"""Get inferred parameters. """ from sys import argv if len(argv) != 3: print("Please pass the number of states and run id, e.g. python 3_get_inf_params.py 8 1") exit() n_states = int(argv[1]) run = int(argv[2]) #%% Import packages print("Importing packages") import os import pickle import numpy as np from...
b37eca5fad2ef27d30f9796c3405436f55d9d19c64a7f0bbdbc0d9c98d52e266
Python
1,120
33
import subprocess import sys import yaml script_gao = 'connectivity_correlations/gao_vs_enrichment.py' script_harris = 'connectivity_correlations/harris_vs_enrichment.py' script_harris_zeta = 'connectivity_correlations/harris_vs_zeta_enrichment.py' script_gao_modules = 'connectivity_correlations/gao_module_hierarchy....
d40306271beaddaf2f79518d7c522d8abc3de53ca8f99074bd9ca9e15f021d12
Python
1,120
28
#!/usr/bin/env python import common import chromatics import os import sys from glob import glob config_fn = sys.argv[1] cell_line = config_fn.split('/')[0] config = common.parse_config(config_fn) os.chdir(os.path.expanduser(config['working_dir'])) segmentation_df = chromatics.read_bed(glob('../segmentation/*.bed.g...
f346f18ee28dd3f4b4c82b6348e7d9774ac2781bfd17bce16e2d3c5e1de3d2f3
Python
1,120
27
import pytest from qtpy import PYQT6, PYSIDE2, PYSIDE6 @pytest.mark.skipif((PYSIDE6 or PYQT6), reason="not available with qt 6.0") def test_qtxmlpatterns(): """Test the qtpy.QtXmlPatterns namespace""" from qtpy import QtXmlPatterns assert QtXmlPatterns.QAbstractMessageHandler is not None assert QtXm...
4c9533fc0fa5fd30a2222fe02ed661dca6b9f6d1e29fdcc7340f7c745149b873
Python
1,121
32
import torch from torch.sparse import to_sparse_semi_structured, SparseSemiStructuredTensor SparseSemiStructuredTensor._FORCE_CUTLASS = True # Sparsity helper functions def apply_fake_sparsity(model): """ This function simulates 2:4 sparsity on all linear layers in a model. It uses the torch.ao.pruning flo...
0b70561b6e9696df160d7642f1aa70e2cf18e4d5798e8f28ab19e68e4d09841b
Python
1,122
32
# Created by David Coggan on 2024 06 26 import pytest import numpy as np import brainscore_vision @pytest.mark.private_access def test_Coggan2024_behavior_stimuli(): stimulus_set = brainscore_vision.load_stimulus_set('Coggan2024_behavior') assert len(stimulus_set) == 22560 assert len(set(stimulus_set['obj...
6166618d65327371e52e2c1e3e6886af66c7a41542b8067f00d87599034a128a
Python
1,122
26
# Created by David Coggan on 2024 06 23 from brainscore_core.supported_data_standards.brainio.assemblies import NeuroidAssembly from brainscore_vision import ( stimulus_set_registry, data_registry, load_stimulus_set) from brainscore_core.supported_data_standards.brainio.s3 import ( load_assembly_from_s3, load_...
75e1de558c07efe7464ec186b23f8e1c76e41d0b15ed4b42528d26776a862952
Python
1,122
39
"""# Main window Use `MainWindow` to build an application shell with a menu bar, tool bars, dock widgets, and a status bar around a central widget area. """ from magicgui import widgets main = widgets.MainWindow() # toolbar toolbar = widgets.ToolBar() toolbar.add_button(text="Folder", icon="mdi:folder") toolbar.add...
81f4617a7322dc739e85bf782e051fda4d0a5a27b40428f90bf7f8d3734f2bf1
Python
1,122
27
import sys sys.path.append('/extra/mccolgan/work') from spikepy.developer.file_interpreter import FileInterpreter, Trial import pyXdPhys as xd import os class ExampleText(FileInterpreter): def __init__(self): self.name = 'XDPhys' # this name must be unique self.extentions = ['.bf','.itd'] # Spikep...
be12eb53a4557fcc99fc13bebe5636e6f696dc16deb9e8eb8bc5128cb9dfe49c
Python
1,122
31
from argparse import Namespace from typing import TYPE_CHECKING from eir.setup.config_validation import validate_input_configs, validate_output_configs if TYPE_CHECKING: from eir.setup.config import Configs def validate_predict_configs_and_args( predict_configs: "Configs", predict_cl_args: Namespace ) -> No...
3f271bdfcaef841dbbda452f947da44a25671e49c3b465709ebb4850c52d11f7
Python
1,123
29
# wfield - tools to analyse widefield data # Copyright (C) 2020 Joao Couto - jpcouto@gmail.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your...
7a4c2b847552669f350bcee811bedd508a8d43d86419330aeb0380a21c9fe467
Python
1,123
49
# coding=utf-8 """ Tests for deepreg/download.py pytest style """ import os import shutil from filecmp import dircmp from git import Repo from deepreg.download import main def has_diff_files(dcmp): if len(dcmp.diff_files) > 0: return True for sub_dcmp in dcmp.subdirs.values(): has_diff_file...
324d1e028a5830d04f4b11dd32747d581562bc06780b5b24bf42292fb8204703
Python
1,124
48
import functools from typing import Callable from ..config import is_dry def dryable(dry_func: Callable) -> Callable: """Function decorator to set a function as dryable. When this decorator is applied, the provided `dry_func` will be called instead of the actual function when the current run is a dry ru...
e5036bb1a5f05d95793919a6be7229f6fff0e7ad00bc5d184742be9fc73f51ae
Python
1,124
42
import yaml from dataclasses import dataclass, asdict @dataclass class Config: weights_path: str = './checkpoint/' batch_size: int = 32 NUM_STEPS: int = 2000 patience: int = 10 learning_rate: float = 0.001 save_freq: int = 50 val_freq: int = 100 def update(self, config_dict: dict): ...
7fbf2678ed0dd3ed1c86f487be61ad048f928f3f8dbb9b514ce3a83b1af2404d
Python
1,125
31
import torch from torch.utils.data import Dataset class DeltaDataset(Dataset): def __init__(self, data, dim_embedding, inv = False): self.data = data self.dim_embedding = dim_embedding self.inv = inv def __len__(self): return len(self.data) def __getitem__(self...
055367e967c6d9afa8d37ceca948edd11f23cd42059e949772740920ca9d3a81
Python
1,127
47
# -*- coding: utf-8 -*- # python standard library inputs import os # external inputs import numpy as np import nibabel as nb def average_time_series(img_input, path_output, name_output): """Average time series. This function computes the element-wise average of multiple nifti files. Parameters ...
289c3fad3352816d8031a5ca4e8d8b725d44a20d95d982a87351d549989834bd
Python
1,127
48
#!/usr/env python import numpy as np import sys inp = sys.argv[1] xmin = float(sys.argv[2]) xmax = float(sys.argv[3]) ymin = float(sys.argv[4]) ymax = float(sys.argv[5]) zmin = float(sys.argv[6]) zmax = float(sys.argv[7]) nx = int(sys.argv[8]) ny = int(sys.argv[9]) nz = int(sys.argv[10]) area_tot = (xmax-xmin)...
8eb1a7a85f43305feadae66a4fc438ebdb092b6edd58eb0db6e911a8f53bc6d3
Python
1,127
54
"""Get inferred parameters. """ from sys import argv if len(argv) != 3: print("Please pass the number of states and run id, e.g. python 3_get_inf_params.py 8 1") exit() n_states = int(argv[1]) run = int(argv[2]) #%% Import packages print("Importing packages") import os import pickle import numpy as np from...
09de2fe65dfeaad69aca5e370ee4d4277e2d48e268a7907270e7ffb69fc4cf04
Python
1,128
35
# Copyright (C) 2019-2022 Intel Corporation # # SPDX-License-Identifier: MIT from django.conf import settings from rest_framework.exceptions import ValidationError from rest_framework.pagination import PageNumberPagination from cvat.apps.engine.types import ExtendedRequest class CustomPagination(PageNumberPaginatio...
c65a61ca47548c06f57b8fbf886fd03c609614e45c5942f33cef854dc187cc6a
Python
1,128
36
# Generated by Django 4.2.16 on 2024-10-22 08:41 from django.conf import settings from django.db import migrations, models def set_has_analytics_access(apps, schema_editor): User = apps.get_model(settings.AUTH_USER_MODEL) for user in User.objects.all(): is_admin = user.groups.filter(name=settings.IAM...
e1b0c13f5e13972ab181f98cd4112be9faba8a4207f59e5ffdc554a47a26096e
Python
1,128
26
from pathlib import Path from brainscore_core.supported_data_standards.brainio.stimuli import StimulusSet from brainscore_core.supported_data_standards.brainio.packaging import package_stimulus_set import csv import pandas as pd stimuli = [] # collect meta image_paths = {} # collect mapping of image_id to filepath s...
7fe428def4e4ff8dde52ffc935e16744483d06314331caf0852c11cbabb66dff
Python
1,129
33
caner_related_lncrnas = [ "NEAT1", "MALAT1", "SNHG16", "ZFAS1", "MIR22HG", "LINC-PINT", "MIR4435-2HG", "FGD5-AS1", "CYTOR", "PVT1", "FTX", "FOXCUT", "FENDRR", "LINC00461", "DLEU2", "MIR34AHG", "LINC00511", "LINC02582", "DLGAP1-AS1", "THORLNC" ] enhancer_lncrnas = [ "NEAT1", "ABALON", "MALAT1", "ASB16-A...
a279dd8b48fdc62d02867d89fa3f4a28a8730d1c03dd9f16285e12b801455e95
Python
1,129
44
""" This is a minimalist benchmark to compare different versions of the annotate function """ import time import numpy as np import obspy import seisbench.models as sbm def main(n_stations: int = 2, n_samples: int = 8640000): models = [sbm.PhaseNetLight(), sbm.PhaseNet(), sbm.EQTransformer()] # models = [s...
a03b185d321ec4a09ee19b7b5ef3c33dd92445e267b10573eeeec23e40edd112
Python
1,130
45
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from __future__ import annotations from abc import ABCMeta, abstractmethod from dataclasses import dataclass from io import BytesIO from typing import Generic, TypeVar from cvat.apps.engine import models _T = TypeVar("_T") @dataclass class DataW...
a93b5ec720ad83aa78b763b47e3fe85ffc099284fb47aae234408d51b0bb6a31
Python
1,131
31
# %% ### import modules from pathlib import Path import pandas as pd # %% read results table results_dir = Path(__file__).resolve().parents[1] / "results" df = pd.read_excel(results_dir / "summary_table.xlsx") # %% rename and structure columns: new_columns = [ ("", "Group"), # diagnosis -> Group ("Scans", "M...
42f6f0df393a163c53fc7e9b26f20a1ce9984aaa8f334454fded4625b4d9e1fc
Python
1,132
39
from torch import nn from eir.models.input.array.array_models import ( ArrayModelConfig, ArrayWrapperModel, al_array_model_configs, al_array_model_types, al_array_models, get_array_model_class, get_array_model_init_kwargs, ) from eir.setup.input_setup_modules.common import DataDimensions ...
c1e113e73a791b5102abc8f942a2c40617fc269c42732a20967c661cf572fd56
Python
1,132
34
import pytest from transcode_dataset import get_component_order_mapping import seisbench.data as sbd def test_get_component_order_mapping(): dataset = sbd.DummyDataset(missing_components="pad") # Wrong missing components with pytest.raises(AssertionError): get_component_order_mapping(dataset) ...
e20fb4abf4700689fee5b388c6f5478d31b5792319cc37e994dba292c3787165
Python
1,132
33
# This file is part of connectome-manipulator. # # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2024 Blue Brain Project/EPFL """Test that alternate morphologies work.""" import os import pytest import bluepysnap from connectome_manipulator.connectome_manipulation.converters import EdgeWriter from connectome_ma...
c3eea7ebe1d9fb152e907d13b65c2eb4a187f55b9b884b32b759e577442b10ea
Python
1,133
51
import os # Model MODEL_NAME = 'vnet' # wandb logging WANDB_LOG = False # Classes ORGANS = ['glomeruli'] NUM_CLASSES = len(ORGANS) + 1 # +1 for background # Lab Machine PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print("Project path: ", PROJECT_PATH) DATA_PATH = '/hdd/yang/projects/g...
c87b696b17db0b861d79678bca32fab205f67e177b16b2c56d520c386e4bf649
Python
1,133
24
from pathlib import Path from brainways.project._utils import update_project_from_previous_versions from brainways.project.brainways_project import BrainwaysProject def test_update_project_from_v0_1_1(brainways_project_path_v0_1_1: Path): update_project_from_previous_versions(brainways_project_path_v0_1_1) B...
09d412c747c5583845d8cceef3490d8adeeb26bc0d7895eba91e47ffb9768b4b
Python
1,135
31
#!/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=['bst.zip']) tmp_dir = tempfile.Temporar...
4440b4ca41323cfe43e1bebc2a89f70e5d62969d93e319a7fc9c675968091b17
Python
1,135
46
#! /usr/bin/env python """Generate a VTK style vtp file from a ply file usage: ply2vtp.py mesh.ply mesh.vtp""" __author__ = "Benjamin Barad" __email__ = "benjamin.barad@gmail.com" __license__ = "GPLv3" import gc import click @click.command() @click.argument('input_ply', type=str) @click.argument('output_vtp', typ...
a1fc5100045e71828beb61420dc4968e1f577ec6a89811bc1be5e7a4b87f6b15
Python
1,135
43
from pathlib import Path from typing import Union import torch from PIL.Image import Image from eir.setup.input_setup_modules.setup_image import ( ComputedImageInputInfo, default_image_loader, ) from eir.setup.output_setup_modules.image_output_setup import ComputedImageOutputInfo def prepare_image_data( ...
a8d8751d9362893c1c38d8fe8f87f5ec26affb0161e5974865ce44bcc1a9b9e7
Python
1,135
29
############################################################################# # Copyright (C) 2020-2026 MEmilio # # Authors: Maximilian Betz # # Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li...
3213e5aef73079fc26eb209ef12698591b80b5266b79e85356eb3704d5222e40
Python
1,136
30
from curvature_calculation import from_ply_workflow, new_workflow, extract_curvatures_after_new_workflow import time from sys import argv t_begin = time.time() fold = r"/gpfs/group/grotjahn/bbarad/Surface_analysis/" # output will be also written there base_filename = "TE1_ER" #surf_file = "TE2_OMM.ply" seg_file = # s...
5a843f409a41b98e0b868353e78ccde72fd4b63b0f090e9e58362f81eee7fe57
Python
1,136
28
import torch from utils import common_functions as c_f from reducers.base_reducer import BaseReducer class ClassWeightedReducer(BaseReducer): def __init__(self, weights, **kwargs): super().__init__(**kwargs) self.weights = weights def element_reduction(self, losses, loss_indices, embeddings,...
6d39b529378d555873bcaf62747436adeb859d277188b9c462e9bcedd7b30984
Python
1,138
46
import distinctipy def require_modules(modnames): """ Given a list of module names, skip the test if any of them dont exist """ import importlib import pytest for modname in modnames: try: importlib.import_module(modname) except (ImportError, ModuleNotFoundError):...
8bc75c0ab4eb5b5a29bd02256fb40ec52ae6e2a8a84ad90bdb33490f4f63712d
Python
1,138
45
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT _caches = {} def _default_cache_value(): from cvat.apps.engine.models import Comment, Issue, Job, Task return { Task: {}, Job: {}, Issue: {}, Comment: {}, } class DeleteCache: def __init__(self, ca...
f75b014595be97a424ee14a904da35fd721b657ee23d0d2e2e65cd1c9cd380a4
Python
1,138
44
import pandas as pd import ijson import csv import time def process_posts(posts): post = posts.replace("'","").strip("[").strip("]") post = post.split(", ") post = post[:200] return post def get_all_tweet(): df = pd.read_csv('./user_post.csv') all_tweet_list = [] for index, row in df.i...
3b0d21b8dce7e608f77070483175b041151dcdc9942024ae030e1d0784cd9a51
Python
1,139
31
# ------------------------------------------------------ # This is a simplified version of filter_ko_hierarchy.py # ------------------------------------------------------ # USAGE modify_ko_hierarchy_keep_all_occurences.py [ORIGINAL_HIERARCHY.tms] [REANNOTATION_FILE.csv] # 1. read KO hierarchy from tms file # 2. add ...
82ef02f948d0120966b611d3847cd2f20acfcba9ebf3e50d688323ae54ff19c4
Python
1,141
31
from dtiplayground.dmri.common.tools.base import ExternalToolWrapper class ImageMath(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 ...
bae03c7bfe64e44237b441aa640eba011f084ca2763ccfcdd6f4056d74d0b738
Python
1,141
44
import pyvisa as visa def main(): _rm = visa.ResourceManager() sds = _rm.open_resource("USB0::62700::60984::SDSMMEBD2R5477::0::INSTR") sds.write("chdr off") vdiv = sds.query("c1:vdiv?") ofst = sds.query("c1:ofst?") div = sds.query("tdiv?") sara = sds.query("sara?") sara = float(sara.rst...
d4874c098521a73187964d1917ef7f5b7cd6c313f3d8f7cb5ead55cfbdfc9e8d
Python
1,141
39
# ----------------------------------------------------------------------------- # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Provides QtWebEngineQuick cl...
78767d95afc80e71d93e9c90e4820484d6b15094b29703b287446486769740f1
Python
1,142
48
"""Public pipeline API for Waven. These functions re-export the current implementation in :mod:`Waven.pipeline`. They are intentionally granular so users can run only the stages they need. """ from __future__ import annotations from Waven.pipeline import ( PipelineOutputs, RFAnalysisResult, SimpleModelRes...
1864f039e22f034b70c239aa5c66a71a612a50d3e7797452be6338fdcc637404
Python
1,143
46
import shutil import tempfile from pathlib import Path import pytest import seisbench import seisbench.data as sbd import seisbench.models as sbm DATA_DIR = Path(__file__).parent / "examples" @pytest.fixture(scope="session") def data_dir() -> Path: return DATA_DIR @pytest.fixture(scope="session", autouse=Tru...
62ca2e756c09d9c1045228a670f87f792ab7eb40f024bbd7c398c084f3b6c228
Python
1,143
41
from warnings import warn import numpy as np from . import pre import datajoint as dj schema = dj.schema('pipeline_aod_preprocessing', locals()) @schema class Spikes(dj.Computed): definition = ... def _make_tuples(self, key): raise NotImplementedError("""This is an old style part table inherited f...
78a5900d1cd5933879b273cda567fbfefde2e331a578c64623cd80f7a42be0bc
Python
1,143
45
#!/usr/bin/env python # -*- coding: utf-8 -*- from itertools import product from PIL import Image from progress.bar import Bar from torchvision import transforms class Loader: shapes = [ "square", "rectangle", "isoTrapezoid", "parallelogram", "losange", "kite", ...
0e15c51d3ebff5aa953e744ddc6f4da562146ba1b351ee9781f0018e200f7346
Python
1,144
33
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from __future__ import annotations from typing import TYPE_CHECKING from cvat.apps.quality_control.backends.base import QualityBackend if TYPE_CHECKING: from cvat.apps.quality_control.data_providers import JobDataProvider def make_quality_ba...
9a5f1ffa93f20b33f68e746e37f99e5a55ca2d3e21e517b46576fa83a0ea90e7
Python
1,144
46
from typing import List, Optional, Dict from fastapi import APIRouter from service.dto.topic import TopicDto from model.topic import UserEvaluationModel, UserEvaluationDao, TopicModel router = APIRouter( prefix="/topics", tags=["topics"], responses={404: {"description": "Not found"}}, ) @router.get('/on...
80d061fb4ff249ad08e24a673b8563d0e5484c712c23ef752ac354fbe4dc5b89
Python
1,145
43
from scipy import stats import numpy as np from .base import Distribution class Gamma(Distribution): """Gamma prior. Parameters ---------- alpha : scalar or ndarray Parameter of distribution beta : scalar or ndarray Parameter of distribution Examples -------- To crea...
ad7ba3205e3315dac1d264428782db958f0dc7b9664c99be108f65b1e71d6e07
Python
1,145
37
import os import subprocess from dataclasses import dataclass @dataclass(frozen=True) class ReadsData: dir_path: str fwd: bool = True rev: bool = False def run_cmd(command: list): os.system(" ".join(command)) def qiime2_version(): o, e = run_cmd(["conda", "env", "list"]) qiime_version = "" ...
72ea629af046bc487506ee595ce3fb1bbe21aec8dfba6e886ba6ce43fc8a3bdd
Python
1,146
34
#Import packages import cv2 import numpy as np import nibabel as nib import matplotlib.pyplot as plt #Load in the image, identify superior slice with mask, and slice 100mm inferior to that ants_mask=nib.load('t1name_here_T1wT2w_mask.nii.gz') a = np.array(ants_mask.dataobj) tmp=a.mean(axis=0) tmp=tmp.mean(axis=0) tmpnz...
e78d35456b9a124e88ced7a040167e6067541754a6109514c08cba60cc703e1c
Python
1,146
41
# example_plugin.some_module from pathlib import Path from typing import Callable, List, Optional, Sequence, Union import napari from napari.types import LayerData from brainways.ui import BrainwaysUI PathLike = str PathOrPaths = Union[PathLike, Sequence[PathLike]] ReaderFunction = Callable[[PathOrPaths], List[Layer...
dde25d6492f6fd3ba3a9a5f3ec6bf658962a30b201bbe6a4631290e9ae9c0215
Python
1,147
41
# -*- coding: utf-8 -*- """Noise utilities.""" import os import nibabel as nb import numpy as np __all__ = ["make_gaussian"] def make_gaussian(input_file, path_output, mu=0, sigma=1): """Creates a NIfTI volume with Gaussian noise as voxel intensities and saves a nifti volume with matrix size and header inf...
06eb877de5be46f29a563613e3871645c7dfd72bdbd28c0d5ff1744a9b081f24
Python
1,148
42
import torch from torch import nn import torch.nn.functional as F class DeeProBot(nn.Module): def __init__(self,des_size=50,num_prop_size=9,dropout=0.1): super(DeeProBot, self).__init__() self.dropout = dropout self.des_size = des_size self.num_prop_size = num_prop_size ...
7109bc3b7bc63a4abf505421ccafc8b501f3e313c9c8edfdc9956b976b746b09
Python
1,150
28
import SimpleITK as sitk import os def zip_nifti(path): """ Zip all nifti files in a folder :param path: path to folder containing nifti files :return: None """ files = os.listdir(path) for file in files: if file.endswith(".nii"): img = sitk.ReadImage(os.path.join(path, ...
7335a0dde2e2271dadf32f436fe0882d7f7cc30434549f1e32a4c2f5eb5e026c
Python
1,150
27
import numpy as np import pytest from impyute.dataset.base import randc from impyute.ops import error def test_raise_error_nlevel_exceed_shape(): with pytest.raises(error.BadInputError) as e: randc(shape=(2, 2)) expected = "nlevel exceeds the size of desired dataset. Please decrease the nlevel or incre...
de9159c8b4ab9e463f777de9fdebb3c311eb3f1aafa9613e12a6cbc09cfa3e42
Python
1,150
26
import torch from torch import nn class GlobalSpatialAttention(nn.Module): def __init__(self, in_channels, num_reduced_channels): super().__init__() self.conv1x1_q = nn.Conv2d(in_channels, num_reduced_channels, 1, 1) self.conv1x1_k = nn.Conv2d(in_channels, num_reduced_channels, 1, ...
53e163d8c008c5c257fbee66e6c334001497bb8ac2a75d75ac14a724f0c66383
Python
1,151
48
"""Tests for logger.""" import logging import os from pathlib import Path import pytest from deepreg import log @pytest.fixture() def log_file_path(tmp_path_factory) -> Path: """ Fixture for temporary log file. :param tmp_path_factory: default fixture. :return: a temporary file path """ ret...
088fae3c36738523026bf044d40aea6e75047698590208c38baa237e1bd505c0
Python
1,152
42
# -*- coding: utf-8 -*- """ Read bandwidth per pixel in phase encoding direction This scripts reads the bandwidth per pixel phase encode from siemens dicom data. This parameter is needed for fieldmap undistortion. """ # python standard library inputs import os # external inputs import pydicom # input data file_in ...
79f180cf2c30ea4a6b1bb0028f2b9d9a4724bd027f242f4235f865ca4eb3dd71
Python
1,152
30
from curvature_calculation import from_ply_workflow, new_workflow, extract_curvatures_after_new_workflow import time t_begin = time.time() fold = r"/gpfs/group/grotjahn/bbarad/poisson_test/" # output will be also written there base_filename = "fission.ply" surf_file = "fission.ply" #seg_file = "" # surf_file = lbl=1 ...
10777da3513b7444dc3f9e40b5af5d1ee0c32d02b16d9fca9fa65c96c5c0ace9
Python
1,153
35
import pytest from pytest import approx from brainscore_vision import benchmark_registry, load_benchmark, load_model class TestExist: @pytest.mark.private_access @pytest.mark.parametrize("identifier", [ 'Papale2025.V1-ridge', 'Papale2025.V4-ridge', 'Papale2025.IT-ridge', 'Papa...
29d2c45cbf5dfe9bb328b0ac8fc8ba8dbb0f9eeec11d24c890f314614e68b7a4
Python
1,153
35
import abc from pathlib import Path from typing import Generic, TypeVar, get_origin, get_args import numpy as np from neuralib.persistence import PickleHandler, PersistenceHandler from neuralib.persistence.cli_persistence import PersistenceOptions from .cli_core import cast_opt, CommonOptions __all__ = ['Persistence...
ffb551e87067a7d325683399f02899f36f0149cce41e00ac00ea0dbd1eed3c1a
Python
1,153
39
import sys import re class ProgressBar(object): DEFAULT = 'Progress: %(bar)s %(percent)3d%%' FULL = '%(bar)s %(current)d/%(total)d (%(percent)3d%%) %(remaining)d to go' def __init__(self, total, width=40, fmt=DEFAULT, symbol='=', output=sys.stderr): assert len(symbol) == 1 ...
6b8cb25e2ec150f5824fece0b2a050cc7e67ad552ad73e07f61b2bd635aafaf7
Python
1,154
44
from typing import Literal from argclz import AbstractParser, argument from rscvp.util.database import * __all__ = ['DBtoGspreadOptions'] class DBtoGspreadOptions(AbstractParser): DESCRIPTION = 'Push a local sql database to a self gspread' db_type: Literal['base', 'bayes', 'sftf', 'dark', 'blank', 'vr'] = ...
93481599fab740c0c16f0e0ef19aa76e3acb6e5ac0624e5007f338612e9f8891
Python
1,154
13
from brainscore_vision import benchmark_registry from . import benchmark benchmark_registry['Malania2007.short2-threshold_elevation'] = lambda: benchmark._Malania2007Base('short2') benchmark_registry['Malania2007.short4-threshold_elevation'] = lambda: benchmark._Malania2007Base('short4') benchmark_registry['Malania200...
a845f0b0a0cac5dca73b9c5805b6490539c53bd65c9bd0e2158e21f6c1bd19a4
Python
1,154
35
""" After fine-tuning, all of our model weights, up until the last conv. layer, are contained within a single layer model object, making it difficult for Keras to load in these layer weights by name for any subsequent fine-tuning. Here, the model is loaded, the interior model is extracted, and its weights are saved. U...
414694471fa70ab45f86a31444ae215b6d9ff549c7cc67d09ed7327b7d2a5c14
Python
1,156
24
"""Bundled data files shipped with osl-dynamics. This subpackage provides brain atlases, MNI surfaces, masks, and other reference files needed by the processing and analysis pipelines. Each submodule exposes a ``directory`` attribute pointing to its data directory so files can be resolved by name at runtime using :py:...
4a83f4e61b42e33a1251325ac4480782b389f388b6b5daf0f679c336cb60b2c4
Python
1,156
40
from sklearn import svm from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from preprocess import preprocess_dataset import sys sys.path.append("..") from utils.eval import evaluate_on_all_metrics import argparse if __name__ == '__main__': ...
a08c18c32fc63edfa1fa69731b0bbcd2d3d534a794d47524efd2273b406cf922
Python
1,156
35
#!/usr/bin/env python # mr-to-pct_script.py # Runs mr to pct as a python script # Inputs: # input_mr_file Filename of your T1w MRI including full path # output_pct_file Filename to give the output pCT including full path # # SNY: Wed 23 Nov 08:51:11 GMT 2022 import sys, os, torch sys.path.append('../') f...
a13d3d57153350817090b556a6557c29b1e5883ee4377254bc5a2fecb272e258
Python
1,156
26
import pytest from brainscore_vision import load_dataset, load_stimulus_set from brainscore_vision.benchmark_helpers import check_standard_format @pytest.mark.memory_intense @pytest.mark.private_access def test_assembly(): assembly = load_dataset('Igustibagus2024') check_standard_format(assembly, nans_expect...
a8aaa1aa776ef632a8c176134c7c7ae65d7b78b945f1e418a64e7f372bcc4cd1
Python
1,156
38
"""Deprecated compatibility shim for Gemini model loading. Construction now lives in ``chemgraph.models.endpoints.google_direct`` behind the Google-native protocol builder. Prefer ``chemgraph.models.loader.load_chat_model``. """ from __future__ import annotations import warnings from langchain_google_genai import C...
f8d53bc9235af9ba3305f7edc98c948535856630df4a11fa4d73661dd535b5f1
Python
1,156
32
#!/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...
8cd913e245d97669a4f6ef286a2660b9e004b706063e5e5eca892a96fe618c52
Python
1,157
39
import pickle import os from musclex.modules.QuadrantFolder import CACHE_FORMAT_VERSION, QuadrantFolder def test_nested_result_parent_can_be_created(tmp_path): result_file = ( tmp_path / "qf_results" / "F10_cre-flnc-224" / "F10_cre-flnc-224_21_00001_folded_compressed.tif" ) ...
f3d03e3b8910f73ae2c1f501b5f4a9e8b6529b504c0488cae9c59bafe9674d6f
Python
1,157
35
import subprocess import sys import yaml script_compare = 'flatmaps/compare_flatmap_enrichments.py' pathpath = 'PATHS/filepaths_carlen.yml' with open(pathpath, 'r') as myfile: pathdict = yaml.safe_load(myfile) sys.path.append(pathdict['code']['workspace']) from pfcmap.python import settings as S setkeys = [key for k...
2ae17b6a0ba1679ce80e99f411b92088cd7c41bc9c13bc7c21c8b37f5ecc5675
Python
1,159
48
# noinspection PyUnresolvedReferences import math # noinspection PyUnresolvedReferences import pathlib # noinspection PyUnresolvedReferences from neuron import h # noinspection PyUnresolvedReferences import neuron_interface.neurosim from .cell_modification_parameters.cell_modification_parameters import ( CellMod...
8115ae4ec7246147d305e0e7571e124e7aaf03b5e1ee7c87b45a79eb3f11c392
Python
1,159
36
""" Full assembly of the parts to form the complete network """ from .unet_parts import * class UNet(nn.Module): def __init__(self, n_channels, n_classes, bilinear=False): super(UNet, self).__init__() self.n_channels = n_channels self.n_classes = n_classes self.bilinear = bilinear...
d132aa7286a671c893a3aaefb29e0a22ade7b8f1695935468f5abc1be273571b
Python
1,159
39
import socket from time import time, ctime list_clients = [] list_connections = [] sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) local_hostname = socket.gethostname() local_fqdn = socket.getfqdn() ip_address = 'IP' port = PORT print("working on %s (%s) with %s" % (local_hostname, local_fqdn...
595d913a11a6598973545aaf3bee12c93da2d2a61f4ff04ecf7be988de3c8aff
Python
1,160
32
#!/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=['tracking.zip']) tmp_dir = tempfile.Tem...
94987fd4b717d0409d717c63ce915afd9289ab40e23248fe6b87d943131d3c58
Python
1,161
30
import sys sys.path.append("..") from utils.dataset import merge_and_split, simple_vectorize import torch from torch.utils.data import Dataset, DataLoader class simple_dataset(Dataset): def __init__(self, data, labels): super().__init__() self.data = torch.FloatTensor(data) self.labels = t...
b0d712c81465adc89eca46bbab55d85a808db85317e6cff87c38fcdb9b30bc18
Python
1,161
51
#import serial from psychopy import visual, core, parallel class Simulated: ''' ''' def __init__(self): ''' ''' pass def setData(self, code: str): ''' ''' print(f'trigger::Simulated::setData(): Received `code`={code}.') c...
ff616f9964f02a3a16bf31895f7672d4b4a71bcc88021b88fefb59b7ef688356
Python
1,161
40
import os import sys import scipy import numpy as np import pandas as pd import scanpy as sc import celltypist from celltypist import models import seaborn as sns import scipy.io as sio import scanpy.external as sce import matplotlib.pyplot as plt os.chdir("/data/wuqinhua/phase/covid19") adata = sc.read('./Alldata.h...
54ea78bfa0a7aca47f5d409071779140cb3ec9fe16695b6ed80c5927b84cb62e
Python
1,163
34
from abc import ABCMeta, abstractmethod class Parser(metaclass=ABCMeta): """Abstract base class that represents a parser of an onnx operator. Example: Conv, MatMul, etc. """ def __init__( self, node_id, node, nodes_outputs, mapping, onnx_model, accelerator=None ) -> None: self.nod...
57a015a17e21550185962762fdb64671fc6015e0cb646e06ae977754cb72918d
Python
1,163
33
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from .command_base import CommandGroup, DeprecatedAlias from .commands_config import COMMANDS as COMMANDS_CONFIG from .commands_functions import COMMANDS as COMMANDS_FUNCTIONS from .commands_profile import COMMANDS as COMMANDS_PROFILE from .commands_...
909ba6c649914e5528ba48eabde116ff6f09ca6abc42d34bbd246cb74365953b
Python
1,163
45
"""Examples copying utility function.""" from pathlib import Path import mkdocs_gen_files EXAMPLES_DIRECTORY_PATH = Path("tutorials") def write_file(file_path: Path) -> None: """ Copies file from examples directory into mkdocs scope. Args: file_path (Path): Current file path. """ root_...
c0dbef56062920abf89bfdd9a1d12db17789e0d1552d3dd0ca0f3a8dc4922563
Python
1,163
61
import re # maybe item = item.replace('\n',' ') def count_characters(text): text = text.replace('\n',' ') return len(text) def count_hashtags(text): hashtags = re.findall(r'#\w', text) return len(hashtags) def count_words(text): text = text.replace('\n',' ') return text.count(' ') def hasta...
e5f6b218f29def3350fe734d64b536306413592051fb5f4b8fc3d43879d0d283
Python
1,163
40
import os import sys # Add the project's root directory to sys.path sys.path.insert(0, os.path.abspath('../..')) # -- Project information ----------------------------------------------------- project = 'Comet Toolbox' copyright = '2026, Micha Burkhardt' author = 'Micha Burkhardt' release = '2026' # -- General config...
1e2bfde597f7a216520a4cb005a523852f331ea74166d1be36bee966a59022b2
Python
1,164
30
import torch from utils import common_functions as c_f from losses.mixins import WeightRegularizerMixin from losses.nca_loss import NCALoss class ProxyNCALoss(WeightRegularizerMixin, NCALoss): def __init__(self, num_classes, embedding_size, **kwargs): super().__init__(**kwargs) self.proxies = tor...
242cb9c1f1bca1d8c047a6e9f6324007bf3b663bde90a8b6d35c77cd15babb2f
Python
1,164
39
"""Build the Academy exchange factory matching a daemon config.""" from __future__ import annotations from typing import Any from chemgraph.academy.core.campaign import ChemGraphDaemonConfig def build_exchange_factory(config: ChemGraphDaemonConfig) -> Any: """Return the Academy exchange factory matching ``conf...
85d0adcc6613cf1917e4fe8d31e98910331eb06ad46125576a28469793030aee
Python
1,164
36
from nipype.interfaces.fsl import Reorient2Std from PUMI.engine import BidsPipeline, NestedNode as Node, BidsApp from PUMI.pipelines.anat.segmentation import bet_deepbet @BidsPipeline(output_query={ 'T1w': dict( datatype='anat', extension=['nii', 'nii.gz'] ), 'bold': dict( datatype=...
97290807e108c1a35799644c0b780083d3bbfe1665fe58b6fa82a80a901c1a29
Python
1,164
45
""" Helper utility functions. """ import os import numpy as np def create_dir(directory): if not os.path.exists(directory): os.mkdir(directory) return directory def log_string(log_file, log_str): log_file.write(log_str + '\n') log_file.flush() print(log_str) def iterate_in_chunks(l, n)...
99b9c814ab233ae04bbeb8c1238013c443080dcb9dcdbaa0f125b2f5d2f519d0
Python
1,164
41
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved import math class InverseSquareRootParamScheduler: def __init__( self, base_lr: float, warmup_steps: int, cooldown_steps: int, timescale: int, ): self.base_lr = base_lr self.warmup...
cacdf93d1a0b2a540f570a1a136d45220f752766429a6bf5a6d393fe8018728f
Python
1,164
43
import pandas as pd import sys def find_unique_combinations(path): # Combine path with params.txt file_path = f'{path}/params.txt' # Read the data from params.txt df = pd.read_csv(file_path, sep="\s+", header=0) # Group the data by the specified columns grouped = df.groupby(['lambda', 'mu', ...
9e235f889448ed34d7632f6e57fcd03fca720d1628eb4236766f9b55fe27e062
Python
1,165
53
from .annotations import ( ClassifyOutput, DASPick, Detection, DetectionList, Pick, PickList, ) from .arraytools import pad_packed_sequence, torch_detrend from .auxiliary import in_notebook, MissingOptionalDependency from .decorators import log_lifecycle from .file import ( callback_if_uncac...
0322c10d83cac2443b46b7f59b4f7df8de2ac117b06207be041d5a22127d1410
Python
1,166
49
import os.path import sys template=''' # Execute job in the queue "std.q" unless you have special requirements. ##$ -q std.q ##$ -q all_24.q # The SGE batch system uses the current directory as working directory. # Both files (output.dat and error.dat) will be placed in the current # directory. The batch system assum...
1d749f9120318c5bc04ad8a2c64793cde4e0d08e2f75049133e18a0d46631ca1
Python
1,166
46
""" Build the Cython extension for the model_cython variant. Run from this directory:: python setup.py build_ext --inplace Or use the helper script:: python -m musclex.tests.fitting_ab.model_variants.model_cython.build After building you will see a file named ``_eval_cy.cpython-3XX-*.so`` (Linux/macOS) or ...
a2f58032c3051443251156395caeedabadd3a22adf2c04953389f187e692b780
Python
1,166
40
from glob import glob import os import numpy as np import h5py import git dsdir = 'IBLPATH/IBL_Passive' dstdir = 'ZENODOPATH/preprocessing/metrics_extraction/timeselections/IBL_Passive'# tintdur = 3. ttag = 'passive' savepattern = '%s__TSEL{}{}.h5'.format(ttag,int(tintdur)) # myfiles = glob(os.path.join(dsdir,'*.nw...
a6544505e9588ce2e7d3a728f256408dea47e54aae2270c67f3a7f4ce7234ae1
Python
1,166
27
# /------------------------------------------------------------------------------+ # | 22-AUG-2022 | # | Copyright (c) Bone Imaging Laboratory | # | All rights reserved ...