sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
8798935eac127953c3f4a741a1ed1f3611a95961546ff5cc5bfb48c505a1ba30 | Python | 2,652 | 77 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import os
from urllib.request import urlretrieve
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_prepro... |
6e98230477922f6ffc60eafb9736b57f135d2bf3cddcf6851098db15c1f7c308 | Python | 2,653 | 81 | # -*- coding: utf-8 -*-
# python standard library inputs
import os
# external inputs
import numpy as np
import nibabel as nb
from numpy.fft import fft2, fftshift
from numpy.random import shuffle
def get_fft(arr, write_output=False, path_output="", name_output="",
normalization=False, n=1000):
""... |
7a054f5a6bed2c0abce5eaee35c2f40a67f2d64fd3acec1e8628f5048acc52ad | Python | 2,653 | 77 | import abc
import torch
class BasicTransform(abc.ABC):
"""
Transforms are applied to each sample individually. The dataloader is responsible for collating, or we might consider a CollateTransform
We expect (C, X, Y) or (C, X, Y, Z) shaped inputs for image and seg (yes seg can have more color channels)
... |
983138594e3360867125d6951cad6cb1b012a1b74702731323006a17bb133279 | Python | 2,653 | 76 | import skimage.io as skio
import numpy as np
import napari
import tifffile
import argparse
def load_image(path):
'''
Load .tif file which is generated from Amira with skimage.io
Args:
path: path of .tif file
'''
tif_stack = skio.imread(path, plugin='tifffile')
#tif_stack = tifffile.imre... |
bc7abc861eba4f244256d3c75b173f70f8a744856357b3ab6421dc0018145620 | Python | 2,653 | 80 | """
Example script for visualizing Rat 7M data. 3D ground truth is projected into each
camera view, plotted into a figure, and saved as a png.
To load the correct video file, the input mocap data structure filename must contain the subject
number and recording day number as 'mocap-s{subject#}-d{day#}.mat'
Usage:
... |
bd024d38b2167f475587a72beacb8599f271a86298b475b242df3ab74a44ee91 | Python | 2,653 | 94 | import math
import tensorflow as tf
def rectangular_kernel1d(kernel_size: int) -> tf.Tensor:
"""
Return a the 1D rectangular kernel for LocalNormalizedCrossCorrelation.
:param kernel_size: scalar, size of the 1-D kernel
:return: kernel_weights, of shape (kernel_size, )
"""
kernel = tf.ones(... |
c289394444fb0554bf9a3418da2bcd480bc5fd9416a505b05a92b4952f070daf | Python | 2,653 | 83 | #!/usr/bin/env python3
"""
layers.py
---------
Self-Attention Graph Pooling (SAGPool) layer used in MoAGNN.
- Scores nodes via a 1-dim GCNConv: score = GCN(x, edge_index)
- Select top-k (ratio) per-graph using torch_geometric.nn.topk
- Filters edges with filter_adj
- Applies gating with non_linearity(score)
Reference... |
386237975c7a04ce4f98dd605cd1536e5daf55d6fdc53899915adf41f1c69f27 | Python | 2,654 | 82 | import numpy as np
from matplotlib import pyplot as plt
from rich.pretty import pprint
from argclz import as_argument, argument
from neuralib.plot import plot_figure
from neuralib.util.verbose import publish_annotation
from rscvp.statistic.cli_gspread import GSPExtractor
from rscvp.statistic.core import StatPipeline
f... |
601e913d5adb4a7d9d278d1749ce2e6b8a205b08edec50c0a08fb1c6e58e2f67 | Python | 2,654 | 72 | #!/usr/bin/env python3
"""
networks.py
-----------
MoAGNN: GCN + 3×SAGPooling with hierarchical readouts.
Readout uses global max + mean at each pooling stage, then CONCAT T1||T2||T3.
"""
import torch
import torch.nn.functional as F
from torch import nn
from torch_geometric.nn import GCNConv
from torch_geometric.nn im... |
31574417b5e1d2b5dd0466ec84b4341dd27d8941b3211640a1296a26cd265405 | Python | 2,655 | 75 | """Unrecognised `kind` and `scale` arguments raise, rather than fail silently.
Pins AllenInstitute/ccf_streamlines#21. Before the fix, a typo'd `kind` gave an
all-zeros view from ``Isocortex2dProjector`` -- indistinguishable from a
legitimately empty projection -- and an ``UnboundLocalError`` naming a local
variable f... |
1270e249432298cc16bdf648de95d8d891b8712618a5cc953bb4e6db79c41a24 | Python | 2,657 | 78 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import os
from urllib.request import urlretrieve
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_prepro... |
6d761e9032535e37584e022bf0b4d32cbc5193e1a3a641ebc890ea7ee6c9244f | Python | 2,657 | 68 | import pytest
import numpy as np
from comet import utils
@pytest.fixture(scope="module")
def summary():
"""
Create 3 subjects, each with two 'true' states (values 1 and 2)
and different dwell proportions.
"""
dfc_list = []
dwells = [(30, 70), (50, 50), (20, 30, 50)]
for i in range(3):
... |
71226cb4600b088388a4325c328677cc6b0c79849b7d9c4f9cac57b4c9d14dd6 | Python | 2,657 | 81 | #!/usr/bin/env python
"""
Peak finder for use by the camera based focus locks. This
version uses numpy/scipy only.
Hazen 11/17
"""
import numpy
import scipy
import scipy.optimize
import time
import storm_control.sc_library.hdebug as hdebug
last_warning_time = None
def fitAFunctionLS(data, params, fn):
"""
... |
bbc32429b6bae04fce3e525f0ec9d52283186affcd19c4777a69d337382eac42 | Python | 2,657 | 87 | import os
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import matplotlib
# QuadrantFoldingGUI selects QtAgg at import time, while these tests do not
# render figures and may run without a display server.
_matplotlib_use = matplotlib.use
matplotlib.use = lambda *_args, **_kw... |
2168475bf522c0dae9d0a5e2bcb63c11b8c15931a622035cb8905d1e77e94f84 | Python | 2,659 | 100 | from __future__ import absolute_import, unicode_literals
import re
import os
import sys
import pickle
from .._compat import *
MIN_FLOAT = -3.14e100
PROB_START_P = "prob_start.p"
PROB_TRANS_P = "prob_trans.p"
PROB_EMIT_P = "prob_emit.p"
PrevStatus = {
'B': 'ES',
'M': 'MB',
'S': 'SE',
'E': 'BM'
}
For... |
7f9c029d421e2160c41fc988a20741ae8afa0297bac80942a9656c55287a88c3 | Python | 2,659 | 97 | from pathlib import Path
import numpy as np
from tifffile import tifffile
from tqdm import tqdm
from typing_extensions import Self
from neuralib.typing import PathLike
from stimpyp import STIMPY_SOURCE_VERSION, PyCamlog, LabCamlog, RiglogData, PyVlog
__all__ = ['WfieldResult']
class WfieldResult:
__slots__ = (... |
1afe0c9a0b747e205f60792ce532e96678d6665b9d3c6409751b8ebb17a2cb57 | Python | 2,660 | 83 | #! /usr/bin/env python3
"""Pmolecule class is the main object to deal with protein contact networks."""
from __future__ import absolute_import
from biographs.lib.bpdb import pdb_model
from biographs.lib.bgraph import network
class Pmolecule(object):
"""Create a Pmolecule object.
The Pmolecule calls a number... |
fdd5cd674ac66e20c92f8845c32fe3ad492c1763d0d281b58e6e879d32099952 | Python | 2,660 | 88 | # Imports
from experimental_condition import ExperimentalCondition
from experimental_localiser import Localizer
import pandas as pd
from eye_tracker import EyeTracker
from const import N_RUNS
import pylink
from psychopy import core, gui
from datetime import datetime
import json
import os
# Settings
debugging = False... |
21b6e7f2bbe2104eea2eab3d13622a8eb1cba392b4f0b35e09770946f2c80bf4 | Python | 2,661 | 73 | import numpy as np
from tqdm import tqdm
from argclz import AbstractParser, argument
from neuralib.io import csv_header
from neuralib.plot import plot_figure
from rscvp.spatial.main_cache_occ import ApplyPosBinCache
from rscvp.util.cli.cli_output import DataOutput
from rscvp.util.cli.cli_suite2p import NeuronID, get_n... |
25e836997de336d56ef6ab3a9359e7f4c85cfd62f20ba7edf1d2b4005cca4cdc | Python | 2,661 | 106 | # -*- coding: utf-8 -*-
# external inputs
import numpy as np
__all__ = ["linear_interpolation3d", "nn_interpolation3d"]
def linear_interpolation3d(x, y, z, arr_c):
"""Apply a linear interpolation of values in a 3D volume to an array of coordinates.
Parameters
----------
x : (N,) np.ndarray
... |
749a014506ffb6221024d6c426866e88ba78bc41258f53966a9dce61e24bc13c | Python | 2,662 | 85 | # Copyright 2016 Numenta Inc.
#
# Copyright may exist in Contributors' modifications
# and/or contributions to the work.
#
# Use of this source code is governed by the MIT
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
import math
import numpy
from nab.detectors.base impo... |
c6ce902385977384a407a6fca479f274e0848323d0f94b539946e2a7cd5fac89 | Python | 2,662 | 81 | # 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.
import argparse
REGISTRIES = {}
def setup_registry(
registry_name: str,
base_class=None,
defaul... |
da9077bfada124e4741c7dc8f9e86b35f222167a8b6fd159c52b4d6acbc5e199 | Python | 2,662 | 75 | import sys
import subprocess
from datetime import date
if __name__ == "__main__":
contrib = sys.argv[1]
headless = sys.argv[2]
rolling = sys.argv[3]
ci_build = sys.argv[4]
opencv_version = ""
# dig out the version from OpenCV sources
version_file_path = "opencv/modules/core/include/opencv2... |
294fde783d8a08b2438e50964497e7f405e17a9638dc9dd3cb9458c08c3ca307 | Python | 2,663 | 87 | from __future__ import annotations
import pytest
from pytestqt.qtbot import QtBot
from labelme._widgets._label_dialog import LabelDialog
def _labels(dialog: LabelDialog, /) -> set[str]:
label_list = dialog.label_list
return {label_list.item(i).text() for i in range(label_list.count())}
@pytest.fixture
def... |
0698273125c1b8bc4f8ec5da07d23ff503a203cb5c5cac79d0055bfbf6e1be91 | Python | 2,664 | 72 | # -*- coding: utf-8 -*-
"""
Split VASO and BOLD
This scripts splits the vaso and bold time series into separate files. Splitted
time series are names as bold (not-nulled) and vaso (nulled), respectively.
Additionally, volumes at the beginning (non steady-state volumes) can be
overwritten by following steady-state volu... |
0d99485da8a32e22cba7fa2e5e9d0fa4271c01f8c579722a69a10014208eeb93 | Python | 2,664 | 69 | # 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 typing import List
from unicore.optim.lr_scheduler import UnicoreLRScheduler, register_lr_scheduler
@re... |
7084fa52e0e518bc9c0c0be56f83c9286dd9aff3af9573d83af9fc6d0e66bcb3 | Python | 2,664 | 84 | # -*- coding: utf-8 -*-
import logging
import os
import nibabel as nib
import numpy as np
from dipy.io.utils import is_header_compatible
from nibabel.streamlines import LazyTractogram
def lazy_streamlines_count(in_tractogram_path):
""" Gets the number of streamlines as written in the tractogram header.
Para... |
bc069c993bce4de24ba7818c5989f379b1d84363ed0d126f3ccaad2a88cb923a | Python | 2,665 | 74 |
"""
This tutorial plugin demonstrates how to overlay dynamically generated
point data onto the plot axes. The plugin does the following:
* Upon starting, the plugin generates 100 independent random points in
each view and overlays them onto the axes.
* Upon each re-painting of the axes a new set of 100 points are ... |
c49e2e0fa17a022528880d9e8fc4ad03d4cbb8c6292d3779e446bd359150ebd8 | Python | 2,665 | 53 | from result_caching import store
from brainscore_vision import load_dataset, load_metric, load_ceiling
from brainscore_vision.benchmark_helpers.neural_common import NeuralBenchmark, average_repetition
from brainscore_vision.data.freemanziemba2013 import BIBTEX
from brainscore_vision.utils import LazyLoad
VISUAL_DEGRE... |
ccc8a5d2d2973af887033ffb9e2ebec81f2cb02ccd16b6a1d254c9ac4e9b6341 | Python | 2,665 | 86 | # 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.
"""isort:skip_file"""
import argparse
import importlib
import os
from .unicore_task import UnicoreTask
# reg... |
54ef318279ed81a5a45e69e9c351df52f6ab4265fe189f6b3e69713f50755fc0 | Python | 2,666 | 64 | import os
import torch
import os.path as osp
from torch_geometric.data import Data
def get_transfer_data():
path = '../../BotRGCN/twibot_22/processed_data'
labels = torch.load(osp.join(path, 'label.pt'))
des_embedding = torch.load(osp.join(path, 'des_tensor.pt'))
tweet_embedding = torch.lo... |
eb2b8c1f88315b80c534f6dcbb8c13ddf823d22ee66332eda996b57c20d60e98 | Python | 2,666 | 73 | from labdatatools.analysis import *
import argparse
class AnalysisMptracker(BaseAnalysisPlugin):
def __init__(self,subject,
session = None,
datatypes = [''],
includes = [''],
excludes = default_excludes,
bwlimit = None,
... |
3f90b9e4804de18762866256e477e9cd0484c3c782724581623d5c421ac72bf4 | Python | 2,667 | 107 |
#!/usr/bin/env python3
import sys
from optparse import OptionParser
USAGE = """
python combine-trf.py --fai <genome .fai file> --segments < segments file> --rmdir <dir where trf out .dat files are> --out <out file name>
combine the split trf files into a single file
"""
#########################################... |
4c8e4b415f1c1766c66696c54df682d12e6c646da93d5a6dbb3652d308c8a7d3 | Python | 2,668 | 64 | import imageio.v3 as iio
import matplotlib.pyplot as plt
import numpy as np
from skimage.filters import gaussian
from argclz import AbstractParser, as_argument, argument, float_tuple_type
from neuralib.atlas.ccf import slice_transform_helper, load_transform_matrix, SLICE_DIMENSION_10um
from neuralib.util.verbose impor... |
6a84e7f0cb6605a5527f8cfb0782f07d440f6f717a800d90de6a4599a3ad98a2 | Python | 2,668 | 78 | # 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.
import inspect
from typing import Any, Dict, List
from unicore import metrics, utils
from torch.nn.modules.los... |
be7542ead9fcb6c19a431a949249ed992eceed95cd0c7b975cb1f7ddac5145f3 | Python | 2,668 | 71 | # 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.
class DynamicLossScaler(object):
def __init__(
self,
init_scale=2.0 ** 15,
scale_f... |
04874d9678002d541bcff59a29ba9dba091e5adc60437ae607e0e6efc701743d | Python | 2,669 | 88 | # The ImpedanceFitter is a package to fit impedance spectra to
# equivalent-circuit models using open-source software.
#
# Copyright (C) 2018, 2019 Leonard Thiele, leonard.thiele[AT]uni-rostock.de
# Copyright (C) 2018, 2019, 2020 Julius Zimmermann,
# julius.zimmermann[AT]un... |
2568c1997fd7b8c9e9c2766082589ae32ddbc91dda48894d0c143c94d34bc94a | Python | 2,669 | 88 | import torch
def varargin(f):
""" Decorator to make a function able to ignore named parameters not declared in its
definition.
Arguments:
f (function): Original function.
Usage:
@varargin
def my_f(x):
# ...
is equivalent to
def my_... |
4612d9babe188e23cd4592cab0aa83b71b81d41d3b91324119780e1798e990ab | Python | 2,670 | 61 | import torch
import torch.nn as nn
class Translator(nn.Module):
def __init__(self, context_dim, num_hidden_layer, num_hidden_neuron, dropout_p):
super(Translator, self).__init__()
self.input_layer = nn.Sequential(nn.Linear(context_dim, num_hidden_neuron),
... |
ad6ae357f8618bd5eb96d500d0fb0b135109efefdca669b0bac68b5945222118 | Python | 2,670 | 81 | import numpy as np
from datetime import datetime
from typing import Any, Dict, Tuple
def loss_wrapper(cache: Any, opt_params: np.ndarray) -> float:
"""
Wrapper function to compute loss using the cache.
Parameters:
cache: An instance of LossAndGradientCache.
opt_params: Parameters for which... |
b373e978f37053901b3458ad6be30b2ac7890595d972030d926ac6d24904720c | Python | 2,671 | 78 | import json
from tqdm import tqdm
from MyBotometer import Botometer, NoTimelineError
from tweepy.error import TweepError
import tweepy
from argparse import ArgumentParser
import os
from queue import Queue
from threading import Thread
def crawling(data_q, pbar):
while not data_q.empty():
item = data_q.get()... |
090cc56e3da34eab6f86d5ab87de5ff3b8214dd884d1cac08d6a75905ad58fa9 | Python | 2,672 | 76 | from pathlib import Path
from typing import Optional, Union
import shutil
from enum import Enum
from brainles_preprocessing.brain_extraction.brain_extractor import BrainExtractor
from brainles_hd_bet import run_hd_bet
class Mode(Enum):
FAST = "fast"
ACCURATE = "accurate"
class HDBetExtractor(BrainExtractor... |
3239cd94602e5e86fedc417b93f69ffad022f2f667d285fa31e24bb08401d521 | Python | 2,672 | 80 | from collections.abc import Sequence
from dataclasses import dataclass
from typing import Literal
al_broker_projection_types = Literal[
"lcl",
"lcl_residual",
"linear",
"grouped_linear",
"pool",
"cnn",
"interpolate",
]
al_broker_fusion_types = Literal["cross-attention", "sum", "cat+conv"]
... |
3375013d62480fc59f9c81dbbbba204672b0251b109ae3f02b42bfb515da8f5c | Python | 2,672 | 105 | # -*- coding: utf-8 -*-
"""Interpolaton functions."""
import numpy as np
__all__ = ["linear_interpolation3d", "nn_interpolation3d"]
def linear_interpolation3d(x, y, z, arr_c):
"""Apply a linear interpolation of values in a 3D volume to an array of coordinates.
Parameters
----------
x : (N,) np.ndar... |
8ec14019cac65338dc83799a683aeeaed34537273a09421c001872a761e1b389 | Python | 2,672 | 100 | import brainpy as bp
import brainpy.math as bm
import numpy as np
import matplotlib.pyplot as plt
from cann import CANN1D
#%%
#set default ramndom seed for reproducibility
np.random.seed(0)
#set backend to cpu
bm.set_platform('cpu')
def intrinsic_speed(mbar=0, duration=5000):
np.random.seed(0)
cann = CANN1D(... |
c62bcc3bbb20e19cc3109d63451143e0edb34ea1de463367e78a9505ac450269 | Python | 2,672 | 76 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
"""Variant of ``loaddata`` that topologically sorts the fixture records by
model dependencies before loading.
Plain ``loaddata`` requires the fixture file to already be in dependency
order: when a record references another via a natural foreign key,... |
15753792ac0dfc9abd11d148372bc914374af424d4196671812d456c41cc231b | Python | 2,673 | 101 | from nilearn import plotting as nl_plotting
from nilearn._utils import check_niimg
import numpy as np
import nibabel as nib
import copy
def img_to_voxel_space(img):
if img is not None:
img = check_niimg(img, dtype="auto")
img_voxel_space = copy.deepcopy(img)
xform = np.eye(4)
if np... |
46f6f2223bbc47c21f92fd05b00ec9ce92a47f10074c6e65b42f4d056e674926 | Python | 2,673 | 65 | # coding: utf-8
import pytest
import lightgbm as lgb
from .utils import SERIALIZERS, pickle_and_unpickle_object
def reset_feature_fraction(boosting_round):
return 0.6 if boosting_round < 15 else 0.8
@pytest.mark.parametrize("serializer", SERIALIZERS)
def test_early_stopping_callback_is_picklable(serializer):
... |
784860c7d063e5c87349beb5b66dc3e0d9affd553bd43d15f531d0674a4faa6d | Python | 2,673 | 81 | # Generated by Django 4.2.21 on 2025-07-09 11:09
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("engine", "0092_labeledi... |
41c3c191caac308e3f416e10375908ed8e02eb2208b6e47105955b0df8c31b2e | Python | 2,674 | 69 | #!/usr/bin/env python3
import pandas as pd
import numpy as np
import argparse
import os
import gzip
def load_pair_data(path):
if path.endswith('.txt.gz'):
return pd.read_csv(path, sep='\t', usecols=['pair_id', 'pval_nominal'], index_col=0, dtype={'pair_id':str, 'pval_nominal':np.float64})
elif path.en... |
5f69b23d76885023ebc21dc4f5e8415811d2f9aa97beb4d256a7ff464c3dbb95 | Python | 2,674 | 123 | # Configuration file for the Sphinx documentation builder.
# -- Project information
import sys
import os
import subprocess
import memilio
project = 'MEmilio'
copyright = '2020-2026 MEmilio'
author = ''
release = ''
version = '1.3.0'
read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'
if read_the_d... |
e9eed189316739989e5fb68579023896366fbbf9ab6edb498b1be76368b1bef6 | Python | 2,674 | 69 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
2fcb3236121391c3bc99cf8a84bd9a47948ae2c7b94cae1a0c63533c94a32601 | Python | 2,675 | 81 | import unittest
import numpy as np
from numpy.testing import assert_array_equal
from argclz import AbstractParser
from rscvp.util.cli import StimpyOptions
from rscvp.util.util_trials import TrialSelection
class TestRiglogData(AbstractParser, StimpyOptions):
exp_date = '210315'
animal_id = 'YW006'
plane_... |
5b46ad995c28e3a45cbc5a393bd12ba0be7cd402bb36afca814ef5e3399ef47a | Python | 2,675 | 75 | 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
stimuli = []
image_paths = {}
stimuli_directory = '../datasets/sketch/dnn/session-1'
'''
Dataset Meta Info (from https:... |
dd00358fb6fbe4c8b0bebebcee563f419acfd3b6ce3f6fa49cbccb04422f62cc | Python | 2,675 | 65 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from django.utils.timezone import now
from rest_framework import serializers
from cvat.apps.engine.serializers import BasicUserSerializer
from .models import UserGrowthData
from .policies import is_github_prompt_enabled, is_github_prompt_on_cooldow... |
13a5cfe93ab4ac2db56a14ab55d603300b2e0460dfe35d7b053370188044f52e | Python | 2,676 | 87 | #############################################################################
# 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... |
6b2bbc3ee41c1deb4b1239276fc178a178a7acab60d3ea7f49a102734775afbe | Python | 2,676 | 83 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Visualize seeds used to generate the tractogram or bundle.
When tractography was run, each streamline produced by the tracking algorithm
saved its seeding point (its origin).
The tractogram must have been generated from scil_tracking_local or
scil_tracking_pft with t... |
4fca25e207ce966136a165aaf2d9b877c8e4f7ba8b64e09d5f72a40bd6fc4347 | Python | 2,677 | 100 | import torch
from torch._C._nn import pad
from eir.setup.input_setup_modules.setup_sequence import (
ComputedSequenceInputInfo,
SpecialTokens,
get_special_tokens,
)
def prepare_sequence_input_for_sequence_output(
input_object: ComputedSequenceInputInfo,
cur_seq: torch.Tensor,
input_name: str,... |
1f687ab80116742b32e31accb45e4b4d824b04bef56a4200953d79e8220947f3 | Python | 2,678 | 70 | #!/usr/bin/python3
#
import os
import sys
import argparse
import numpy as np
from uac import utils
# Create the parser
my_parser = argparse.ArgumentParser(description="Calculation of labels using laplace solves only")
# Add the arguments
my_parser.add_argument("target_path", metavar="path", type=str, help="Path for ... |
301594af8f199f654578316e8e385f075c599d99d434f1fe9bf6a15d2281b222 | Python | 2,678 | 84 | #encoding=utf-8
from __future__ import unicode_literals
import sys
sys.path.append("../")
import jieba
import jieba.posseg
import jieba.analyse
print('='*40)
print('1. 分词')
print('-'*40)
seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
print("Full Mode: " + "/ ".join(seg_list)) # 全模式
seg_list = jieba.cut("我来到北京清华大学... |
34e8e2da4455e4420ceff6f9ea65dcddc575a96ff95c09560f423737abc4a639 | Python | 2,678 | 94 | #!/usr/bin/env python
"""
Tests of the C libraries.
"""
import numpy
def testCImageManipulation():
import storm_control.hal4000.halLib.c_image_manipulation_c as cIM
# Create a random image.
nim = numpy.random.randint(200, size = (64,64)).astype(numpy.uint16)
all_ori = [[False, False, False],
... |
932b16fb2dc696eb1c1b92df6ea166b3af51812293d9509948bd10606736b3a5 | Python | 2,679 | 91 | # -*- coding: utf-8 -*-
"""
Analysis of behavioural data
Analysis of the behavioural performance of the dummy fixation task during
scanning. The script essentially performs the same calculation as directly done
automatically after single functional runs.
"""
# python standard library inputs
import os
# external inp... |
73652fc2b9eecd9964e66ad387da8e7a63ec5e50f3c222fd2bce2ed884eadd04 | Python | 2,680 | 78 | import torch
import torch.nn as nn
# Domain-specific BatchNorm
class DSBN2d(nn.Module):
def __init__(self, planes):
super(DSBN2d, self).__init__()
self.num_features = planes
self.BN_S = nn.BatchNorm2d(planes)
self.BN_T = nn.BatchNorm2d(planes)
def forward(self, x):
if ... |
073dad33c4f1931e7a19b2c382b33ccf3ede6fb58461728b4c6292d634086d8e | Python | 2,681 | 80 | from typing import Final, Literal
from argclz import AbstractParser, argument
from neuralib.atlas.view import get_slice_view
from neuralib.plot import plot_figure
__all__ = ['SliceViewOptions']
class SliceViewOptions(AbstractParser):
DESCRIPTION = 'Plot the slice view of the injection site'
resolution: Fin... |
526b8e76680d2eef2e8946a3f0a68e9c09830c4ba5933811077b0bb4a984f614 | Python | 2,681 | 93 | from seisbench.data.base import WaveformBenchmarkDataset
class PNW(WaveformBenchmarkDataset):
"""
PNW ComCat dataset from Ni et al. (2023)
"""
def __init__(self, **kwargs):
citation = (
"Ni, Y., Hutko, A., Skene, F., Denolle, M., Malone, "
"S., Bodin, P., Hartog, R., ... |
554555b8d3599dc79c25ed9ff1a537a22136aac0fd9b2705a06738930b806dc1 | Python | 2,681 | 100 | #!/usr/bin/env python3
"""Generate a minimal samplesheet for the Snakemake RNA-seq pipeline.
This script scans a directory for paired-end FASTQ files:
*_R1.fq.gz / *_R2.fq.gz
It then writes a TSV samplesheet with columns:
sample, condition, subject, batch, fastq1, fastq2
Notes
-----
- The script cannot infer con... |
d3923ec41a7cfaf0aba72503d4057ee3a63f95bd582d0768d1c9eb4ab2760202 | Python | 2,681 | 69 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
7533c9faa9e0831fd505924b7ed534544f298208cd9627ed62717acf8e0ff631 | Python | 2,682 | 75 | import numpy as np
# https://stackoverflow.com/questions/46091111/python-slice-array-at-different-position-on-every-row
def take_per_row(A, indx, num_elem):
"""
Matrix A, indx is a vector for each row which specifies
slice beginning for that row. Each has width num_elem.
"""
all_indx = indx[:,Non... |
c88700d05f653b030d5ed26bf24ca7bbd64b37e5589038ecf7cf88cf4fd9cded | Python | 2,682 | 60 | import pandas as pd
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
import scipy.stats as stats
import h5py
import sys
if __name__ == '__main__':
if len(sys.argv) <= 2:
print('Usage: process_results.py <bim> <fname> [<out>], where')
print(' bim - path to bim file (refere... |
1ba9836bce48da9fd672edfd43f3e1e02a333df8b391919e2837f8d9cb94188f | Python | 2,684 | 95 | """
Extract and preprocess frames from video files.
Usage:
python scripts/preprocess_video.py \
--input_dir data/raw_video/ \
--output_dir data/video/ \
--fps 30
"""
import argparse
import sys
from pathlib import Path
import cv2
import numpy as np
from tqdm import tqdm
sys.path.insert(0,... |
48c86f896c1b9ea13f2bae0c6942171811fc698e0d181b4e5504fff7100395d2 | Python | 2,684 | 90 | """Wakeman-Henson: Preprocessing."""
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import mne
from osl_dynamics.meeg import parallel, preproc
# ----------------------------------------------------------------------------
rawdir = Path("data/ds117")
outdir = Path("data/preproc")
log_dir = Path("lo... |
f69b889611bdb606dc57a8e477c5c917213a207d6c08a1befdb47ac9bfea3589 | Python | 2,684 | 80 | import argparse
import numpy as np
from contextlib import redirect_stdout
import io
from scipy.spatial.distance import cdist
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from pathlib import Path
import pickle
from pstimutils import PertStimDataSimple
from perturbatio... |
87f903c03f0292cda6e100b236bf0d8895a4177064765b89d967b4d8ca18c6f9 | Python | 2,685 | 58 | from MyClient import MyClient
from UserExpand import UserExpandSampler, needed_segments
from utilities import get_user_dict
from utilities import bearer_token
from utilities import get_user_followers_list_by_id, get_user_following_list_by_id
import json
import random
import os
import tqdm
from tweepy.errors import (
... |
99003bad502ae8f86906e72ca7de3b9e6cddec130f445615eaf61400c6896435 | Python | 2,685 | 82 | from pathlib import Path
from typing import Callable, Optional, Union
import SimpleITK as sitk
from auxiliary.io import write_image
from brainles_preprocessing.n4_bias_correction.n4_bias_corrector import N4BiasCorrector
class SitkN4BiasCorrector(N4BiasCorrector):
def __init__(
self,
mask_func: ... |
bfd178de15822e6e2b61552462982b440e88742fcf52cef1181d9cbff53b5dad | Python | 2,685 | 70 | import numpy as np
import numpy.testing as npt
from brainways.pipeline.brainways_params import TPSTransformParams
from brainways.transforms.tps_transform import TPSTransform
def test_tps_transform_points():
points_src = np.random.randint(0, 10, (5, 2))
points_dst = points_src + np.random.randint(0, 2, (5, 2)... |
19b50d0ee9fa15dc527918b015d2a796b10bc91120c6aa6317de40994ec5f1a2 | Python | 2,686 | 99 | #!/usr/bin/env python3
"""Run pylint for a given memilio package and write the jsonextended report."""
from __future__ import annotations
import argparse
import subprocess
import sys
from pathlib import Path
def parse_args(pycode_root: Path) -> argparse.Namespace:
parser = argparse.ArgumentParser(
descr... |
a395883bf2eb95862aa2997437aaaebf1ab6269d50c99a59a4a11ca7e6482ab3 | Python | 2,686 | 48 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... |
ab74d1065ae10c5729698d99346b56aea7f0b2bbab3301d8c8989bd9e8cb0dc6 | Python | 2,686 | 82 | import numpy as np
import os
import pandas as pd
import SimpleITK as sitk
root_path = r''
output_dir = r''
patients = {}
for item in os.listdir(root_path):
item_dir = os.path.join(root_path, item)
if os.path.isdir(item_dir):
name = item
patient_dir = item_dir
patients[n... |
8165b05428385f7d07f9dd751a2c84f8136f7ae4c7cf10bac66ca861daaeab74 | Python | 2,689 | 108 | import numpy as np
import nibabel as nib
import scipy.ndimage
def normalize_img(img, max_img, min_img, max, min):
# Scale between [1 0]
img = (img - min_img)/(max_img - min_img)
# Scale between [max min]
img = img*(max - min) + min
return img
def unnormalize_img(img, max_img, min_img, max, min... |
9f46930256c4a0e20d21c6608cf6f10387b924781512e790bd3a755905fc25ee | Python | 2,689 | 75 | 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
stimuli = []
image_paths = {}
stimuli_directory = '../datasets/stylized/dnn/session-1'
'''
Dataset Meta Info (from http... |
ba7c27fe837488eaa18ef63133a625feee6ba25e4553b991657a91c93ba5a50e | Python | 2,689 | 76 | #! /usr/bin/env python3
"""
Define interface and run in if in command line mode. Use a workflow?
"""
from nipype import Node, Workflow
from nipype.interfaces.freesurfer import MRIConvert
from nipype.interfaces.ants import Registration
from nipype.interfaces.io import FreeSurferSource
# TODO:
# - implement use of mask
... |
01d428c2000cf6cdcc413fcd80bd58443bac184503aa9b9ae740041cacee1390 | Python | 2,690 | 73 | """
Populates event .tsv files in subject-specific BIDS directory
"""
import pandas as pd
import glob
import os
ROOT = '/Volumes/sDresBackUp/s1Anfunco/Nifti'
subs = sorted(glob.glob(os.path.join(ROOT, 'sub*')))
for sub in subs:
sub = sub.split('/')[-1]
print(sub)
funcDir = f'{ROOT}/derivatives/{sub}/... |
11ccb2c6b11a0885685c365e789be0dab27fe0b7dda87053c24d1e924a40e324 | Python | 2,690 | 53 | from dtiplayground.dmri.common.tools.base import ExternalToolWrapper
class FiberProcess(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
... |
1ed7e5783d44d638a94a08e8e91da663ce5684084327e94cc7cb7bae8fd9c324 | Python | 2,690 | 82 | #!/usr/bin/env python
import numpy as np
import pandas as pd
import click as ck
import sys
from collections import deque
import time
import logging
from deepgo.utils import FUNC_DICT, Ontology, NAMESPACES
import os
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
@ck.command()
@ck.option(... |
d6b5321cc1db11a974855774d6a7db9985a905ed96b4c67d0f5004fb11c47cc3 | Python | 2,690 | 70 |
from pycurv import run_gen_surface, THRESH_SIGMA1, TriangleGraph, MAX_DIST_SURF, io
import numpy as np
from scipy import ndimage
from graph_tool import load_graph
import time
fold = r"/Users/benjaminbarad/Dropbox (Scripps Research)/Grotjahn Lab/Data/Surfaces/Lam2_TS1/" # output will be also written there
base_filena... |
afddb370acb667703cff1da6b2ac5d2f0c149153d4c61bb1d63126af45fbaf4d | Python | 2,691 | 77 | """Configuration and constants for data loading operations."""
from typing import ClassVar
class DataConfig:
"""Configuration class containing all data loading constants and mappings."""
# Supported simulation types
SUPPORTED_SIMULATIONS: ClassVar[list[str]] = [
"generic_sims",
"lan_sims... |
cf6f38de93051b93c98ad0143900ddf46e139ccf1035f0ea97465e1bffc9bda8 | Python | 2,692 | 85 | import os
from typing import Any
from docs.doc_modules.user_guides.single_sample_simulation import simulate_health_sample
from eir.utils.logging import get_logger
logger = get_logger(__name__)
class DataSimulator:
def __init__(
self,
sequence_length: int = 64,
max_iterations: int | None ... |
0d5edc17c1c20c3bec4b91e439a56b53d7c302385737474c0d923a3a34e064d1 | Python | 2,694 | 72 | from __future__ import annotations
import numpy as np
import numpy.typing as npt
from ._model import Shape
from ._oriented_rectangle import _get_rotation_handles
from ._oriented_rectangle import _is_full_oriented_rectangle
def _find_closest_index_within(
*, distances: npt.NDArray[np.float64], epsilon: float
) -... |
38da593038bffc7e761e833a8abb9f296f804846f9618a5ca4c04280a0798865 | Python | 2,694 | 69 | from nipype.pipeline.engine.nodes import *
from nipype.interfaces.io import DataSink
from hashlib import sha1
import re
class NestedNode(Node):
def output_dir(self):
"""Return the location of the output directory for the node"""
# Output dir is cached
if self._output_dir:
retu... |
57a1e1d61a834318beb4c76f85f3c3e4a1625a85250b0e4b298cc9e2270c8946 | Python | 2,694 | 59 | # from https://github.com/gaussian37/pytorch_deep_learning_models/blob/master/cosine_annealing_with_warmup/cosine_annealing_with_warmup.py
import math
from torch.optim.lr_scheduler import _LRScheduler
class CosineAnnealingWarmUpRestarts(_LRScheduler):
def __init__(self, optimizer, T_0, T_mult=1, eta_max=0.1, T_up... |
861797a306b1fe52972218c512ba9c95e59e3ed568e216bdb377f1b28c63b172 | Python | 2,694 | 94 | """
Protein Structure Relaxation Script using PyRosetta
This script performs energy minimization (FastRelax) on a protein structure.
It can either:
1. Determine an optimal number of iterations (`max_iter`) for relaxation, or
2. Perform relaxation a fixed number of times with a user-specified `max_iter`.
Usage:
py... |
dff5adc008bdd9328cac2a5f884eeca8cf41194b3cf2667ea9038020383becbf | Python | 2,694 | 73 | import csv
import os
import tempfile
import shutil
chunk_size = 400000 # Adjust as needed based on available memory
# Define the input and output file paths
input_file = r'./data/mobility/bs.csv'
output_file = r'./data/mobility/bs_sorted.csv'
# Define the primary and secondary columns to sort by (0-based indices)
p... |
5054916cce1aa2f892821e4f074b39e2405a5ccd2a13d5e0feb5bece7123c092 | Python | 2,695 | 90 | # -*- coding: utf-8 -*-
"""
Module to set *ClearMap's* internal parameter and paths to external programs.
Notes:
Edit the :func:`setup` routine to point to the ilastik and elastix paths
for specific hosts
See Also:
* :const:`IlastikPath`
* :const:`ElastixPath`
* :mod:`~ClearMap.Parameter`
"""
im... |
f00512ceb36bfec15ad65937e90ea186399d5a11cbd116d683689ba0d8aeae56 | Python | 2,695 | 86 | import shutil
import numpy as np
import tensorflow as tf
from deepreg.callback import build_checkpoint_callback
def test_restore_checkpoint_manager_callback():
"""
testing restore CheckpointManagerCallback
"""
# toy model
class Net(tf.keras.Model):
"""A simple linear model."""
... |
1973015754cf2504d6fe9e7dbb0ba91ef0093464a359a25ecff4041757659c17 | Python | 2,696 | 98 | """HMM Fisher kernel example.
"""
import os
import numpy as np
from sklearn.svm import SVC
from sklearn.multiclass import OneVsOneClassifier
from sklearn.model_selection import KFold
from osl_dynamics import simulation, data, inference
from osl_dynamics.analysis import fisher_kernel
from osl_dynamics.models.hmm impo... |
723f68eddb725a533676c710770c19882386b7c619aa1065a949f33faf1f7279 | Python | 2,696 | 103 | from __future__ import annotations
import os
import pathlib
import socket
import sys
from collections.abc import Mapping
from typing import Any
from chemgraph.academy.observability.event_log import EventLog
MPI_RANK_ENV = (
'PMI_RANK',
'PMIX_RANK',
'OMPI_COMM_WORLD_RANK',
'PALS_RANK',
'SLURM_PROC... |
85f18d2b60ab99580fe62e1a6e5fff5f3e62209250b1948828f96043d99ebc29 | Python | 2,696 | 70 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import unittest
from unittest.mock import patch
from rest_framework import serializers
from cvat.apps.engine.serializers import JobReadSerializer
from cvat.apps.events import handlers
class TestGetCleanedUpSerializer(unittest.TestCase):
def s... |
a7ab5c4491f9c02515e971685194dc1630e4df18505a29c1c9ec432485905f08 | Python | 2,696 | 93 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#
import os
import numpy as np
from unicore.data import (
NestedDictionaryDataset,
EpochShuffleDataset,
)
from unimol_plus.data import (
LMDBDataset,
StackedLMDBDataset,
Is2reDataset,
)
from unicore.tasks... |
608b8045b9dbbf32d94a3e7253c4fa5f44a2802a3fb1286ca0eb6ab7579af8d8 | Python | 2,697 | 67 | import torch
from torch import nn
from torch.nn import Parameter
from smart.layer import SAGEConv_Encoder,SAGEConv_Decoder, GCNConv_Encoder, GCNConv_Decoder, GCN2Conv_Encoder, GCN2Conv_Decoder, GATConv_Encoder, GATConv_Decoder, GraphConv_Encoder, GraphConv_Decoder
import torch.nn.functional as F
class SMART(torch.nn.M... |
7a677b29f0166de8eadc86ace5c7368e5d8b861fc1d570163c955ae0a124a0b9 | Python | 2,697 | 95 | from collections.abc import Sequence
from copy import deepcopy
from unittest.mock import patch
import numpy as np
import pytest
import torch
from eir.data_load.data_preparation_modules import prepare_omics
def test_prepare_genotype_array_train_mode():
test_array = torch.zeros((4, 100), dtype=torch.uint8).detach... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.