sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
6fee2a91204c3b4c18f8158ada853aa99c924754ec8093999bb74e7d2b66e131 | Python | 1,579 | 40 | 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:
- From Hebart 2023: https://elifesciences.org/articles/82580v1
- Participants were s... |
a630f7d2570375046c9208f47fd064b2fe689f9b8097fff3672e91274ea996f3 | Python | 1,580 | 38 | """
Iter-10 — ConvNeXt-XXLarge CLIP (LAION-2B) fine-tuned on ImageNet-1k (convnext_xxlarge.clip_laion2b_soup_ft_in1k).
Biggest CLIP-pretrained ConvNeXt. The board shows CLIP+ft and supervised ConvNeXts both near the top, and for
these (unlike DINOv2) SCALING HELPS (convnext_xlarge 0.45 > large 0.44). This is the large... |
286181a42d04a7b0a6ba6825e64508ce4206c9e1db0865e5ba7352760570cfee | Python | 1,581 | 57 | """ Norm Layer Factory
Create norm modules by string (to mirror create_act and creat_norm-act fns)
Copyright 2022 Ross Wightman
"""
import functools
import types
from typing import Type
import torch.nn as nn
from .norm import GroupNorm, GroupNorm1, LayerNorm, LayerNorm2d, RmsNorm
from torchvision.ops.misc import Fr... |
69796966d57f4d0d31f50b093c4fafc6ffd2f266b72996eaf8d8a773494ed639 | Python | 1,581 | 50 | #!/usr/bin/env python
"""
HAL module for emulating an AOTF.
Hazen 04/17
"""
import storm_control.hal4000.halLib.halMessage as halMessage
import storm_control.sc_hardware.baseClasses.amplitudeModule as amplitudeModule
import storm_control.sc_library.parameters as params
class NoneAOTFFunctionality(amplitudeModule.Amp... |
a585b20d195ff123c0dd198b84547ea2595072715d6322ad9e2f7f0679e9a3f7 | Python | 1,581 | 50 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import mixins, viewsets
from cvat.apps.engine.mixins import PartialUpdateModelMixin
from .models import UserGrowthData
from .permissions import UserGrowthDataPe... |
d49b1fe25c7a6d4ef726ffcfe5d303b4e346b76297f6c2ef9694c2e5cc4f6902 | Python | 1,581 | 51 | import shlex
import subprocess
from pathlib import Path
from typing import Optional
from loguru import logger
import click
@click.command()
@click.option("-s", "fs_surface_dir", type=Path, required=True)
@click.option("-o", "output_dir", type=Path, required=True)
@click.option("-l", "license", type=Path, required=Tr... |
e2e838d008502fe3e9e0dacf6a5b53250793b2093894624f2e0c02bcccefcc9d | Python | 1,581 | 73 | import re
def count_characters(all_text):
cnt = 0
for item in all_text:
item = item.replace('\n',' ')
cnt += len(item)
return cnt
def count_hashtags(all_text):
cnt = 0
for item in all_text:
hashtags = re.findall(r'#\w', item)
cnt += len(hashtags)
return cnt
de... |
4049a48196809a2b18f331eef4a996fd495c08db159ebe182e5d601cd8a7ec7b | Python | 1,582 | 35 | import nibabel as nib
import numpy as np
def copy_lh_to_rh_with_rh_header(lh_mgh_path, rh_mgh_path, output_path_rh):
# Load left hemisphere (for data)
lh_img = nib.load(lh_mgh_path)
lh_data = lh_img.get_fdata().squeeze()
# Load right hemisphere (for header and shape reference)
rh_img = nib.load(rh... |
613fde3c900a70bc1eec82d62e609a6798dc30a80f3bc6bd9f6d74e50b35bd83 | Python | 1,582 | 56 | from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout, CMakeDeps
class MCMLRecipe(ConanFile):
name = "mcml"
version = "0.0.3"
package_type = "application"
# Optional metadata
license = ""
author = ""
url = ""
description = "Library to generate s... |
9890fc6ffe7f1dc35d1164b3b03653099b30fcf46548c410bcb5620f7f4d6f25 | Python | 1,582 | 58 | #!/usr/bin/env python3
import sys
import genutils3
import os
from optparse import OptionParser
USAGE = """
python extract-chunks.py --fa <genome fa> --segments < segments file> --outdir <output dir>
uses samtools cmds to split genome into segments indicated
"""
##############################################... |
ec5ecdbc99600b0e8a3bcd631adb3ade9769de8bf04b954cecc33810803f0a8b | Python | 1,582 | 58 | from pathlib import Path
import shutil
import os
import sys
import time
import requests
HF_DATASET_REPO = "neheller/KiTS-Challenge-Imaging"
HF_DATASET_REVISION = "main"
HF_DATASET_BASE_URL = (
"https://huggingface.co/datasets/{}/resolve/{}"
.format(HF_DATASET_REPO, HF_DATASET_REVISION)
)
temp_f = Path(__file_... |
2e81d486725a43c95f59b091a13ffd88a0f2466c7c7baad27a8232096f0eca4d | Python | 1,583 | 51 | import numpy as np
import nelpy as nel
def test_standardize_asa_numpy():
@nel.preprocessing.standardize_asa(asa="X")
def dummy(X=None, **kwargs):
return X
arr = np.arange(10)
result = dummy(X=arr)
assert isinstance(result, np.ndarray)
assert np.all(result == arr)
def test_standardi... |
4aae6947496e7be7788c272901be0b98fe4b315c41f8e5450899aae3e6c79669 | Python | 1,583 | 54 | from scipy.signal import butter, lfilter, freqz
class HighPassFilter:
def __init__(self, cutoff, fs, order=5):
self.cutoff = cutoff
self.fs = fs
self.order = order
self.b, self.a = butter(self.order, self.cutoff / (0.5 * self.fs), btype='high', analog=False)
def apply(self, dat... |
8a236866e623b0a16fe775ef84597b3284b233196eb9a1a51c97f372aa88c21c | Python | 1,583 | 61 | # Random Forest
import numpy as np, pandas as pd, sklearn.ensemble as ske
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.inspection import DecisionBoundaryDisplay
df=pd.read_excel("solo_zonas.xlsx")
df... |
bb8fa86d9b9bcc8e1b5de4e239eaaea127440f8ff4696e4d3bdb9a61b0927691 | Python | 1,583 | 49 | import os
from datetime import datetime
from importlib.metadata import version, PackageNotFoundError, metadata
import re
import sys
import signal
__package__ = "lyroi"
creation_date = datetime(2025, 11, 26)
try:
__version__ = version(__package__)
except PackageNotFoundError:
__version__ = "0.0.0"
meta = meta... |
fb29643ae2a58ea24c9c9af17ef47386e48818d9a82e5e818414c2f2755456e2 | Python | 1,583 | 61 | #!/usr/bin/env python
"""
Read a MAF from stdin and break into several mafs based on the source of
each block. If the `component` option is provided then only that component
will be used to determine the new file for each block, otherwise the src
for *all* components will be used.
TODO: Should be able to specify comp... |
0dd8acb05bd19085d3993815c2b77704e00a4b81590688e212028dd6d777e868 | Python | 1,584 | 60 | """Example script for simulating an HMM state time series and running TINDA on it.
"""
import os
import numpy as np
from matplotlib import pyplot as plt
from osl_dynamics import simulation
from osl_dynamics.analysis.tinda import tinda, plot_cycle, optimise_sequence
# Directory for plots
os.makedirs("figures", exis... |
72d1615f38524544fac30b5862ed04b48933009d3af5d62305e78b9d3da76a22 | Python | 1,584 | 39 | from __future__ import absolute_import
from torch import nn
from torch.nn import functional as F
from torch.nn import init
import torchvision
import torch
from .pooling import build_pooling_layer
from . import *
#------------------------Ensemble Model-----------------------
class EnsembleModel(nn.Module):
de... |
deb2edbfe0d6aacbc6efc651e2e8e847e5b0d648488f32e36b8c76d648daf066 | Python | 1,585 | 38 | #!/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
fetch_data(get_testing_files_dict(), keys=['commit_amico.zip'])
tmp_dir = tempfile.TemporaryDirectory()
def test_help_option(script_runner):
r... |
8aecb37936a26f6a23c8b18985bc18cbc014033c875aa49a536d267ff1b16f19 | Python | 1,587 | 52 | import argparse
import os
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from bendnet.model import BendNet
from bendnet.data import load_all_data, preprocess
from bendnet.evaluate import evaluate
def main(args):
X, y = load_all_data(args.data_dir)
... |
ce49f32aa58ebbfba85771959b0ba7f5f96c524f868a694b79e0df4eb6efb490 | Python | 1,588 | 49 | # Generated by Django 3.2.18 on 2023-02-21 09:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("engine", "0064_delete_or_rename_wrong_labels"),
]
operations = [
migrations.AlterUniqueTogether(
name="label",
uniq... |
f784d8b67594f7c9ffd2b8c6b90bfbb70861ce832667f5215e4fb38733281a8e | Python | 1,588 | 50 |
from matplotlib import gridspec
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
cur_path = Path.cwd() / "data" / "bar_6_fold_para34567.txt"
with open(cur_path) as f:
lines = [line for line in f]
num_each_row = len(lines[0].split())
data_set = np.zeros((len(lines), nu... |
160123d2211085648de284a0d9adc7ecb698fcb49ca58700903895b24b3586dd | Python | 1,589 | 42 | from __future__ import annotations
import sys
from PySide6 import QtGui
from PySide6 import QtWidgets
from pytestqt.qtbot import QtBot
from labelme._widgets._ai_text_to_annotation_widget import AiTextToAnnotationWidget
from labelme._widgets._info_button import InfoButton
def test_focusable_controls_expose_accessib... |
2c344b6f546e96a069104b49391b698804382916ec7166510759f754b837a59f | Python | 1,590 | 60 | import pytest
import AFQ.api.bundle_dict as abd
import AFQ.data.fetch as afd
from AFQ.api.group import GroupAFQ
from AFQ.tests.test_api import create_dummy_bids_path
def test_AFQ_custom_bundle_dict():
bids_path = create_dummy_bids_path(3, 1)
bundle_dict = abd.default_bd()
GroupAFQ(bids_path, dwi_preproc_... |
319e663ca00ac81c67d99c542e00736166892d0b61289acb46925b16da42ee00 | Python | 1,590 | 34 | """
Copyright 1999 Illinois Institute of Technology
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publis... |
394a7e39a69c4ab7e575340a322ab443d3928354921edf5591f75108560901da | Python | 1,591 | 49 | """ipynb.py -- helper functions for working with the IPython Notebook
This software is licensed under the terms of the MIT License as
follows:
Copyright (c) 2013 Jessica B. Hamrick
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"S... |
f15868a0bd439c1d48dd65f4dfd7bd3aea0e66833ec73ccfc74730db8511aa90 | Python | 1,591 | 67 | import arbor as A
from arbor import units as U
import matplotlib.pyplot as plt
from pathlib import Path
here = Path(__file__).parent
ctr = "(location 0 0.5)"
mrf = A.load_swc_neuron(here / "Acker2008.swc")
dec = (
A.decor()
.set_property(Vm=-55 * U.mV)
.paint('"soma"', A.density("hh"))
.paint('"den... |
010f12afa1dde9be4fb390aee89ad66f7487f4feab005bac8902f16cf6566529 | Python | 1,592 | 56 | from pathlib import Path
import click
from _cli import LazyGroup
@click.group(
cls=LazyGroup,
lazy_subcommands={
"reslice-dti": "dti.reslice_dti.reslice_dti",
"clean": "dti.clean_dti_data.clean",
"eddy": "dti._cli.eddy_cli",
"topup": "dti._cli.topup_cli",
"dtifit": "d... |
626590b3beaf9295a25b37e3fac4c20bd7d1a15c26b87e80d48d4519e3167e53 | Python | 1,592 | 55 | """
Created on 2025.04.25
Updated on 2026.02.17
Author: Lina Jeantin
Linear mixed models to study the variation in the values of EEG markers of complexity across sleep stages
Taking into account the variable number of recordings between patients
(patient ID set as random effect)
Requirements:
df_full: dataframe c... |
6808b51e66e3fbaef949effd6a161c953668154f93536d21213fff4a532c4a14 | Python | 1,592 | 56 | from pathlib import Path
import numpy as np
import pytest
from napari_dmc_brainmap.segment.processing.presegmentation_tools import (
CellsSegmenter,
)
@pytest.mark.parametrize(
"fixture_name",
["grayscale_uint16_tiff", "grayscale_uint8_tiff"],
)
def test_load_single_channel_tiff_preserves_intensities(
... |
96c7beb349a7bc84321068a476dc53f1fc0d13938c4ce54c24e63a449832cca3 | Python | 1,592 | 45 |
# Based on https://github.com/MuggleWang/CosFace_pytorch/blob/master/layer.py
import torch
import torch.nn as nn
from torch.nn import Parameter
def cosine_sim(x1: torch.Tensor, x2: torch.Tensor, dim: int = 1, eps: float = 1e-8) -> torch.Tensor:
ip = torch.mm(x1, x2.t())
w1 = torch.norm(x1, 2, dim)
w2 = ... |
28aaf155cde02ac17f7aa2e5fdbdf5ea2463ed9ea45701332488f93fe3137e28 | Python | 1,593 | 27 | auddur = 0.2
valvedur = 0.5
stimplotfns = {
'AudStim_10kHz': lambda timestamps,ax: [ax.axvspan(timestamp, timestamp + 0.2, **{'color': 'k', 'alpha': 1, 'lw': 0}) \
for timestamp in timestamps],\
'valve_opening': lambda timestamps,ax: [ax.axvspan(timestamp, timestam... |
8e62986deec3f9ebe79d3e2fd1d02441f7ee8455e2b996db6cbbe9f2c90d4635 | Python | 1,593 | 66 | """Train an HMM on amplitude envelope data.
"""
from sys import argv
if len(argv) != 3:
print("Please pass the number of states and run id, e.g. python 1_train_hmm.py 8 1")
exit()
n_states = int(argv[1])
run = int(argv[2])
#%% Import packages
print("Importing packages")
import pickle
from osl_dynamics.data... |
f2b1359a875fce85ce12fbaccd7cf2853813a1f1c2a4d9ec2c2220b1a6852505 | Python | 1,593 | 76 | from pathlib import Path
from typing import Optional
import click
from tqdm import tqdm
from brainways.project.brainways_project import BrainwaysProject
from brainways.project.info_classes import ExcelMode
@click.command()
@click.option(
"--project",
"project_path",
type=Path,
required=True,
hel... |
47fb432577f299f82c5643bdac7ace27f3a62821c80bf3983efcee55daad0875 | Python | 1,594 | 55 | #!/usr/bin/env python3
import argparse
import numpy as np
from ase import Atoms
from ase.io import read, write
from ase.optimize import *
from KerNNCalculator.KerNNCalculator import *
'''
Script to calculate the potential energy of a structure.
Usage: python predic_mol.py -i structure.xyz
'''
#parse command line argu... |
ea92e64d010a150d29ea20f7040d0fa330bdba0a37e1b3ce02ec15944683eb40 | Python | 1,594 | 42 | import pandas as pd
def compute_missingness(df):
return df.isnull().sum() / len(df)
def extract_diagnosis(df: pd.DataFrame):
"""Extracts diagnosis from dataframe index"""
diag_list = []
for id in df.index:
if id.startswith("NC"):
diag_list.append("NC")
elif id.startswith(... |
1a21315290208038431b94dda86c1c424a79de311183eded030ff348edcf7b47 | Python | 1,595 | 46 | import json
import csv
from tqdm import tqdm
import time
import os
import ijson
import pandas as pd
def to_csv(header, dic, filename):
with open(filename, 'a', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=header)
writer.writerows([dic])
if __name__ == '__main__':
f... |
29e104dd46274c3e283c805f2013387e33d51a99047d43d204001d58571bf717 | Python | 1,595 | 46 | ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
'''Test multiple utils'''
import os
import numpy as n... |
411b825fbd0752818adeeecf0e0ce4b9206f6c96bcfe9286011e24d54cb9b60f | Python | 1,595 | 46 | import json
import csv
from tqdm import tqdm
import time
import os
import ijson
import pandas as pd
def to_csv(header, dic, filename):
with open(filename, 'a', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=header)
writer.writerows([dic])
if __name__ == '__main__':
f... |
4bec5144e2120fc8a029343007b40199861fcd37d0a3259501a72173be617415 | Python | 1,595 | 43 | import os
import gzip
import csv
import sys
def reduce_output_file_size(input_file:str, output_file:str):
"""
Simplify the data generated by the analysis pipeline by retaining only the essential information required for the frontend.
"""
if os.path.exists(input_file):
# Open the input and outpu... |
55c0c218fa865f61d72c681bb9b89b8958b559cf59be9f4ee22ca1d55efe05dd | Python | 1,595 | 46 | import json
import csv
from tqdm import tqdm
import time
import os
import ijson
import pandas as pd
def to_csv(header, dic, filename):
with open(filename, 'a', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=header)
writer.writerows([dic])
if __name__ == '__main__':
f... |
b9738a55545bd1420d01b6a7fb17c6cdad179907abc859f5b385d26c4d8125d0 | Python | 1,595 | 31 | import numpy as np
import argparse
from preprocess.pair_generation import load_data, get_clusters, get_neg_pairs, get_cluster_sizes, print_total_pairs
from preprocess.pair_generation import save_neg_pairs
if __name__=='__main__':
parser = argparse.ArgumentParser(description="Generate random pairs of anchors")
... |
c3e02a30687b88e44edced4a348e16cc50637ac29f0b2909af1c6430f7265e4e | Python | 1,595 | 61 | #! /usr/bin/env python
# Copyright 2014-2015 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 argparse
import os
... |
7a9456881824ddbd3de40c7175758809bf000fb854a155b4f50c6bcd91df70b6 | Python | 1,596 | 46 | """
:class:`~allennlp.common.tqdm.Tqdm` wraps tqdm so we can add configurable
global defaults for certain tqdm parameters.
Adopted from AllenNLP:
https://github.com/allenai/allennlp/blob/v0.6.1/allennlp/common/tqdm.py
"""
from tqdm import tqdm as _tqdm
# This is neccesary to stop tqdm from hanging
# when exceptio... |
9bae5c4c6552a16e538306a42db1cb9f3b7e92e192691cc4971dbda9cce412d7 | Python | 1,596 | 40 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['commit_amico.zip'])
tmp_dir = tempfile... |
c3dc73effa3ce3a63464a558339c3a5c56d3472f4e94c1e3ca7bd40b67065bef | Python | 1,598 | 48 | import random
import pytest
from bx.seq import twobit
def quick_fasta_iter(f):
current_header = None
current_sequence = []
for line in f:
if line.startswith("#"):
continue
if line.startswith(">"):
if current_sequence:
yield current_header, "".join(... |
f9b75d1eddf7491c405b84d05548d8a31a71a6be26bae01eb29ce1e1a27fe725 | Python | 1,598 | 51 | # Run this script after doing the pyinstaller build
import os
import shutil
import subprocess
from musclex import __version__
os.sys.path.append(os.path.abspath(os.path.join("..", "..")))
deb_path = os.path.join(".", "musclex-{}_amd64(linux)".format(__version__), "DEBIAN")
exc_path = os.path.join(
".", "musclex-... |
4cb10f41d8d514d8374c3b6ac233dfca4fa0ab2e71aa27a294b7b6532389344f | Python | 1,599 | 46 | import json
import csv
from tqdm import tqdm
import time
import os
import ijson
import pandas as pd
def to_csv(header, dic, filename):
with open(filename, 'a', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=header)
writer.writerows([dic])
if __name__ == '__main__':
f... |
5288afecfab6ed5ab380b780df724e7ed2bcdc173a6b4e64ceb4ff6d661574eb | Python | 1,599 | 46 | import json
import csv
from tqdm import tqdm
import time
import os
import ijson
import pandas as pd
def to_csv(header, dic, filename):
with open(filename, 'a', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=header)
writer.writerows([dic])
if __name__ == '__main__':
f... |
62ddecb8e96f01f5a82656fa542e7c679d536ef05874be5d3de985ded17a5aa1 | Python | 1,599 | 61 | from __future__ import annotations
from chemgraph.models.openai import _normalize_argo_model
def test_local_argo_shim_keeps_openai_style_model_name(monkeypatch):
monkeypatch.delenv("CHEMGRAPH_ARGO_MODEL_FORMAT", raising=False)
assert (
_normalize_argo_model(
"argo:gpt-4o-mini",
... |
8534e7fe7f8ae78c828603cad63c4b1abb85039a845c4881c0120f77aa51795f | Python | 1,599 | 46 | import json
import csv
from tqdm import tqdm
import time
import os
import ijson
import pandas as pd
def to_csv(header, dic, filename):
with open(filename, 'a', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=header)
writer.writerows([dic])
if __name__ == '__main__':
f... |
968d9cce2fdf74edcf61a53e937628136164c4e8527d59fe82e4533bebcc847a | Python | 1,599 | 51 | #!/usr/bin/python
#
## @file
#
# Work around for 32 bit COM library.
#
# Hazen 02/14
#
import socket
import sys
import hsFilterWheel
my_hsfw = hsFilterWheel.HSFW()
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.connect(("127.0.0.1", 9002))
running = True
while running:
next_cmd = my_soc... |
c75a6575284ee8e3a2066f9a4424243c994a26569fdca4757dd4ed24165b2835 | Python | 1,599 | 45 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from __future__ import annotations
import argparse
from cvat_sdk.core.auth import AuthStore
from .command_base import CommandGroup
from .common import CriticalError
COMMANDS = CommandGroup(description="Manage local CVAT CLI configuration.")
@CO... |
e75aa4d4181803557ed1ea885ca98e5cbdd666e871bc20232f1c515af16c4a82 | Python | 1,599 | 39 | import nibabel as nib
import os
import numpy as np
from dipy.denoise.gibbs import gibbs_removal
from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec, TraitedSpec, File, Directory, traits, CommandLineInputSpec, File, TraitedSpec, CommandLine, Directory, Str
class DipyDegibbsInputSpec(BaseInterfaceIn... |
ebdcaed150dcbec52107d6c0e696031dfd5120c7231d05c9ad5fdf7ce21ff94e | Python | 1,599 | 59 | # coding: utf-8
"""LightGBM, Light Gradient Boosting Machine.
Contributors: https://github.com/lightgbm-org/LightGBM/graphs/contributors.
"""
from pathlib import Path
# .basic is intentionally loaded as early as possible, to dlopen() lib_lightgbm.{dll,dylib,so}
# and its dependencies as early as possible
from .basic... |
0531cc37cfc4407f981efb66b27fd03ba9b4eb168a8f8f089010c17242bc9dd9 | Python | 1,600 | 42 | import nibabel as nib
import numpy as np
def convert_gii_to_mgh(
gii_path: str,
mgh_output_path: str,
reference_mgh_path: str
):
"""
Replace the data of an existing MGH image using value from a GIfTI file,
while preserving all metadata (affine, header, qform, sform) from the reference.
Par... |
1e98fdaf19ecec028906e70e4faa5e09213d7310d75a70f05b76e46b9e48020c | Python | 1,600 | 50 | import pytest
import flair.datasets
from typing import Tuple
from flair.data import Dictionary, Corpus
from flair.embeddings import WordEmbeddings, DocumentRNNEmbeddings
from flair.models.text_classification_model import TextClassifier
def init(tasks_base_path) -> Tuple[Corpus, Dictionary, TextClassifier]:
# get... |
d0d06fc12df51348b74fcc6770c976b9c2d0a32fbbeeb79c2e6605f315299415 | Python | 1,600 | 53 | from pathlib import Path
import numpy as np
import torch
from eir.data_load.data_preparation_modules.common import (
process_tensor_to_length,
)
from eir.setup.input_setup_modules.setup_bytes import ComputedBytesInputInfo
from eir.setup.schemas import ByteInputDataConfig
def bytes_load_wrapper(
data_pointer... |
8021c594170ac0e8c20ee02052be202e79e06c25358e21a36ad41ec57ca75405 | Python | 1,601 | 47 | import os
import sys
# Add project root to path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.llm_orchestrator.self_correcting_agent import SelfCorrectingAgent
from src.physics_validator.validator import PhysicsValidator
def run_cross_solver_test():
print("="*70)
print... |
23f7f01be04f8d2afd536d26d6a9247ab4253958dc4186644b19898d386a6c38 | Python | 1,602 | 51 | """RNN Model."""
# pylint: disable=import-error
import abc
import matplotlib.pyplot as plt
import numpy as np
import torch
plt.switch_backend("agg")
class AbstractModel(torch.nn.Module, metaclass=abc.ABCMeta):
"""Abstract class for rnn models."""
def __init__(self):
"""Constructor only calls torch... |
26525dc87abd0d0ac936e7e92f99211447513ce4c9c7d121c865e0b842bac690 | Python | 1,602 | 52 | '''
metrics
Contact: adalca@csail.mit.edu
'''
# imports
import numpy as np
def dice(vol1, vol2, labels=None, nargout=1):
'''
Dice [1] volume overlap metric
The default is to *not* return a measure for the background layer (label = 0)
[1] Dice, Lee R. "Measures of the amount of ecologic associatio... |
7a6daa83a11d2b14eafa70c13ab58274f7b360390197ecbc95f444e9d5bd82e0 | Python | 1,602 | 56 | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Qt3DAnimation class... |
a839db3cd8f558235f6bb36ac56a1895de036e4abc10a79705a09cfb6f1f31a1 | Python | 1,602 | 58 | import argparse
from datetime import datetime
from deepreg.predict import predict
name = "paired_mrus_prostate"
# parser is used to simplify testing, by default it is not used
# please run the script with --full flag to ensure non-testing mode
# for instance:
# python script.py --full
parser = argparse.ArgumentParse... |
057b6f773d5d876997664fe64100c820ca8fe55e1114d71dd8f4124a67f78ca7 | Python | 1,604 | 56 | import pytest
from tensorflow.keras.layers import (
GlobalAveragePooling3D,
GlobalMaxPooling3D,
MaxPooling3D,
)
from pyment.models.sfcn import BinarySFCN
INPUT_SHAPE = (32, 32, 32)
_POOLING_TYPES = (GlobalAveragePooling3D, GlobalMaxPooling3D, MaxPooling3D)
def test_default_input_shape():
model = Bin... |
4a2d00ab976df0ce7d396e064b1b0e32c5df89d35137fdbd3f7ae5f36adcd692 | Python | 1,604 | 49 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from setuptools.extension import Extension
from Cython.Build import cythonize
import ClearMap
import numpy
with open('README.rst') as fptr:
readme = fptr.read()
with open('LICENSE.txt') as fptr:
license = fptr.read()
extensions = [Extensio... |
6cf7517bafefca2a6c017658fd522b9302f0d8f5c43b7a9cdaf17353fdf39be8 | Python | 1,604 | 63 | """ Plotting stimulation sound for manuscript """
from unicodedata import decimal
from scipy.io import wavfile
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('dark_background')
soundFile = "30_5_unpredictable.wav"
samplerate, data = wavfile.read(soundFile)
x = np.linspace(0, len(data), len(data))
... |
c2e8d39062a99b509906545636758e81230c131def348edafc415b8d5c255250 | Python | 1,604 | 40 | import torch
import torch.nn as nn
from .encoder import CausalCNNVEncoder
from .decoder import CausalCNNVDecoder
class VAE(nn.Module):
"""
The VAE method is able to encode a given input into
mean and log. variance parameters for Gaussian
distributions that make up a compressed space that represents
... |
1bf11fa783df8c11065427f24d96d18c0e931780f0e5e90eef8a8400f237cba3 | Python | 1,605 | 57 | import unittest
import warnings
from unittest.mock import patch
from rscvp.selection.main_motion_drift import MotionDriftOptions
from rscvp.selection.main_neuropil_error import NeuropilErrOptions
from rscvp.selection.main_trial_reliability import TrialReliabilityOptions
from .util import check_attr
class TestSelecti... |
4a732b08765f0f0055d0d9c3e6104f4413f47540950a6814f55e53f4ab339411 | Python | 1,605 | 49 | import os
def parse_pdb_confidence(pdb_content):
atom_lines = [line for line in pdb_content.splitlines() if line.startswith('ATOM')]
confidence_values = []
for line in atom_lines:
b_factor = float(line[60:66].strip())
confidence_values.append(b_factor)
average_confidence = sum(confiden... |
f197e8c1d0b44f3841404c7d00fc343a600be36f5c3ccdbb3e99187f53bbae42 | Python | 1,605 | 60 | import random
from tempfile import mktemp
from bx import interval_index_file
from bx.interval_index_file import Indexes
def test_offsets():
assert interval_index_file.offsets_for_max_size(512 * 1024 * 1024 - 1) == [
512 + 64 + 8 + 1,
64 + 8 + 1,
8 + 1,
1,
0,
]
def te... |
f7b5aa498664bfc5e6e16a83952a672d529b2546f7b0159758f4718b37863a23 | Python | 1,605 | 46 | # Copyright 2024 Google LLC
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
013dc860cdf7733a1344a49f89f7868630fe3b21dc82db696eac6fd200206c27 | Python | 1,606 | 53 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
"""Ultralytics YOLO inference backends.
This package provides modular inference backends for various deep learning frameworks and hardware accelerators.
Each backend implements the `BaseBackend` interface and can be used independently or through the u... |
54cccb0f59d4fae667d69f6d32a8c166861631fc7212e4f2ba44ff75df94363b | Python | 1,606 | 67 | """Train an HMM on time-delay embedded/PCA data.
"""
from sys import argv
if len(argv) != 3:
print("Please pass the number of states and run id, e.g. python 1_train_hmm.py 8 1")
exit()
n_states = int(argv[1])
run = int(argv[2])
#%% Import packages
print("Importing packages")
import pickle
from osl_dynamics... |
2860f13ae370f6e1d1b3d3a33103fb410e85e0233d6e9fe9509c5b8eccc66788 | Python | 1,608 | 58 | import argparse
from datetime import datetime
from deepreg.predict import predict
name = "grouped_mr_heart"
# parser is used to simplify testing, by default it is not used
# please run the script with --full flag to ensure non-testing mode
# for instance:
# python script.py --full
parser = argparse.ArgumentParser()
... |
37420ead50766531a6c23e742a517d73feb75a91a0cb73ca642c80f776d5bdc4 | Python | 1,608 | 53 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from __future__ import annotations
from pathlib import Path, PurePath
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from _typeshed import StrPath
def problem_with_untrusted_path(
untrusted_path: str, /, *, allow_trailing_slash: bool ... |
cdad02fb7bd4be140dac8924e77e125a28768b0f1aa7e81d634fb7214d8e6ded | Python | 1,608 | 64 | # coding=utf-8
"""
Tests for deepreg/train.py
pytest style
"""
import os
import shutil
from deepreg.predict import build_config, build_pair_output_path
def test_build_pair_output_path():
"""
Test build_config for labeled and unlabeled cases
"""
save_dir = "logs/save_dir_example"
# labeled
... |
123951d28bdce18a44b3f9673d65df41b8003107ad8b71f2393fcf9cba1b218f | Python | 1,609 | 42 | import pandas as pd
import re, sys
input_file = sys.argv[1] # "variant.csv"
output_file = sys.argv[2] # "new_file.csv"
offset = int(sys.argv[3]) # The offset between the Rosetta and Original residue index
offset_residue_num = int(sys.argv[4]) # The residue number from which the offset will start
# input the variant f... |
5959d7933f93f4400d200ba608209554e4a10d92bdbd9c4f4e65289762f867b3 | Python | 1,609 | 45 | import torch
from torch import Tensor
import torch.nn as nn
def drop_path(x: Tensor, drop_prob: float = 0.0, training: bool = False) -> Tensor:
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
From TIMM
This is the same as the DropConnect impl I created for Eff... |
77fb6baa49ffedaab902d1e4fd7ee3ae15ee59d0bed97f3a9deb27435beb51a8 | Python | 1,609 | 33 | import os
import numpy as np
import argparse
from chinn.pair_features import load_pairs_as_dict
from preprocess.pair_generation import sample_from_neg_pairs
if __name__=='__main__':
parser = argparse.ArgumentParser(description="Sampling 5x negative samples.")
parser.add_argument("name", help="The prefix of th... |
7fe9797e02071c885655adfed3a6af1a652342a28e353d0c15767428af80349a | Python | 1,609 | 50 | """
Example usage of HarveST package for spatial gene discovery
"""
from harvest import Harvest
def example_spatial_gene_discovery():
"""Example of spatial gene discovery using HarveST."""
print("Running spatial gene discovery...")
# Initialize HarveST (assuming you have preprocessed data)
harves... |
0376662f3a918c267f378e78bac1b5d47dbcb5920a9a196d3efbf2ae80923c58 | Python | 1,610 | 47 | # Copyright 2024 Google LLC
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
3e4102f58cb9a50511e4d4cecebfe8cbf76590d44f18233c5a2350b6c1a6efd7 | Python | 1,610 | 60 | #!/usr/bin/env python3
#
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import subprocess
import sys
from argparse import ArgumentParser, Namespace
from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from pathlib import Path
REPO_R... |
aaa6dc08186cd4bffcbdfc4e1602a1c7c22e7176b5e532dab595ce08bf3329e7 | Python | 1,610 | 53 | import sys
import operator
MIN_FLOAT = -3.14e100
MIN_INF = float("-inf")
if sys.version_info[0] > 2:
xrange = range
def get_top_states(t_state_v, K=4):
return sorted(t_state_v, key=t_state_v.__getitem__, reverse=True)[:K]
def viterbi(obs, states, start_p, trans_p, emit_p):
V = [{}] # tabular
mem_p... |
861b5bd039dc0f14f22bdb5af96c8a9f5a0b0fa16ec67dba07f1e61daf1a6380 | Python | 1,611 | 48 | # flake8: noqa
from .. import _timing
from ._base_metric import _BaseMetric
class Count(_BaseMetric):
"""Class which simply counts the number of tracker and gt detections and ids."""
def __init__(self, config=None):
super().__init__()
self.integer_fields = ["Dets", "GT_Dets", "IDs", "GT_IDs"... |
9d118ace34b1d33066e7decf59cdb602029f3ec8912c3fa162c02452303c23cd | Python | 1,611 | 58 | #! /usr/bin/env python3
"""
Flip the volume according to the specified axis.
"""
import argparse
import logging
import nibabel as nib
import numpy as np
from scilpy.image.volume_operations import flip_volume
from scilpy.io.utils import (add_overwrite_arg, assert_inputs_exist,
add_verbos... |
ac62951d830683af6f3af4f1bb75465dd4ec33fbc31ba7a8f48d37e3c118123d | Python | 1,611 | 51 | import numpy as np
import pickle
import fire
import matplotlib.pyplot as plt
based = "../../bids_data/derivatives"
where, result = pickle.load(open("clusters.pkl", "rb"))
morphed = pickle.load(open(f"{based}/msm/sub-average/meg/sub-average_task-POGS_all+rsa+many.pkl", "rb"))
def make_picture(stc, fname):
# pos... |
5e15d832f7e430243ae5725e680229f4be60edffd6ca0331b82f206625e6648a | Python | 1,612 | 57 | from __future__ import annotations
import numpy as np
import pytest
from scipy.sparse import csr_matrix
from ntac import GraphData, Ntac
def test_seeded_ntac_uses_external_node_features_for_assignment() -> None:
adjacency = csr_matrix((3, 3), dtype=float)
labels = np.array(["A", "B", "?"], dtype=object)
... |
87cb363ea8e47b3a724266f0147b7f4eda72db5bdaf02df913db91def99fc87b | Python | 1,612 | 56 | import numpy as np
import pandas as pd
from enigmatoolbox.utils.parcellation import parcel_to_surface
from enigmatoolbox.plotting import plot_cortical
from cvdproc.config.paths import get_package_path
# -------------------------
# User configuration
# -------------------------
# 1. A csv file containing the DK68 val... |
359428a33ddccc94a6293efd2de357ce7b0a959b8e0738b3a4e875988a79122d | Python | 1,613 | 65 | import csv
import numpy as np
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):... |
35f6880fc22ca9fa9a3948c8a734c0994fee13cfabba332611b9fed3f233d80b | Python | 1,613 | 38 | from torch.optim.lr_scheduler import _LRScheduler
# Exponential learning rate scheduler
class ExpLRScheduler(_LRScheduler):
def __init__(self, optimizer, initial_lr: float, max_steps: int, exponent: float = 0.9967, current_step: int = None):
self.optimizer = optimizer
self.initial_lr = initial_lr
... |
914fdafd72cc6d1de1745bc0b1778627c9282a148c37fcb4a77429c7b401a30a | Python | 1,613 | 52 | from PyQt5.QtWidgets import QFrame, QHBoxLayout, QApplication
def validate_path(path):
return path and path.strip() != ""
def visualize_grid(grid_layout):
"""Wrap each widget in a QFrame to show cell boundaries"""
# Store items to process (can't modify while iterating)
items_to_wrap = []
for i in... |
a01728b3c46c7564a738a0497931fcd728485dfb49501a57dfb0325250eb56fa | Python | 1,613 | 39 | import warnings
warnings.filterwarnings("ignore", message="It is not recommended to directly access")
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttentionFusion(nn.Module):
def __init__(self, hidden_size, num_heads=4, dropout=0.1):
super(MultiHeadAttention... |
e0fe370f15d74b7e092b5400865e7803261cbb2b1e3a4226fbc1aab635d5e792 | Python | 1,613 | 48 | from typing import Annotated
import pytest
from magicgui.signature import magic_signature, make_annotated
def test_make_annotated_raises():
"""Test options to annotated must be a dict."""
with pytest.raises(TypeError):
make_annotated(int, "not a dict") # type: ignore
with pytest.raises(TypeErr... |
4569bdda7401b30bd065fc782f378ee1983754be1eb5121ba3f2b6228728c0dc | Python | 1,614 | 42 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import os
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
from pathlib import Path
fr... |
7651ab37862223ea3c159b8f7670f3a4c31ec1c7fb96eb2f12ab527ec24068da | Python | 1,614 | 64 | # Copyright (c) DP Technology.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch.utils.data.dataloader import default_collate
from functools import lru_cache
from . import UnicoreDataset
class RawLabelDataset(UnicoreDat... |
1a37546aaf13562a78327968addea9c8c0a5a059bef2ea924c8abbe03001eca9 | Python | 1,615 | 35 | #! /usr/bin/env python
"""Generate an area weighted histogram of a single feature from a single mesh from a single segmentation
Useful to get a sense of how your configuration for meshing and quantification looks. Also nice for responding to reviewer requests!
Usage: python single_file_histogram.py input_csv.csv -n fe... |
41d475ca6093587f11977ca47f50ad168e214b93dab791ae7755257301077491 | Python | 1,615 | 46 | #this script with assistance from ChatGPT3.5 20231204
# the function is to create a mean of all the normalized images
# python nii2meanLesion.py
import os
import nibabel as nib
import numpy as np
import fnmatch
def create_mean_image(folder_path, output_path):
# Ensure the output folder exists
os.makedirs(os.... |
78defb87d16bfdc048570f91256949368f17588a2c4c9805f1824a0d95b704ce | Python | 1,615 | 46 | #!/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=['others.zip'])
tmp_dir = tempfile.Tempo... |
9eca2fb2b7af2ec733dcfff938aa992ca7ce39c6a8b790b6c3798ca977cc8519 | Python | 1,615 | 66 | import os, random
import numpy as np
import torch
def set_seed(seed=42):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True)
os.environ["CUBL... |
f30eb9c670e5cb955a5395627e190b082974a4d4bd927337fe744aa58c3d1de2 | Python | 1,615 | 66 | import json
import numpy as np
from pyment.utils.json_serialize import json_serialize
def test_json_serialize_nan_is_strict_json_safe():
payload = {'value': np.array([np.nan])}
serialized = json_serialize(payload)
# Should not raise under strict JSON rules.
json.dumps(serialized, allow_nan=False)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.