sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
da071fc3db4d5ad8b72a487ace92f7d8158f7d70e5e44e04d6bef9020bd0049c | Python | 1,746 | 59 | from pathlib import Path
import numpy as np
import torch
from eir.data_load.data_augmentation import (
make_random_omics_columns_missing,
shuffle_random_omics_columns,
)
def omics_load_wrapper(
data_pointer: Path | str | int,
subset_indices: np.ndarray | None,
) -> np.ndarray:
assert isinstance(... |
7bc3e1a5db7588d9e1524aba77d9ade71790a6f1860cf6d2dcf622f797ea293c | Python | 1,747 | 64 | import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
class MakeStyle2D(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
def forward(self, x: Tensor) -> Tensor:
"""
What is the in shape? [B, C, X, Y?]
... |
c15082bcf26a75f27ff992119a1fba48ae18992f9e402c12461fa59dd1366563 | Python | 1,747 | 43 | from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, f1_score, recall_score, roc_auc_score
import numpy as np
from tqdm import tqdm
train_features = np.loadtxt('train_features.txt')
train_labels = np.loadtxt('train_labels.txt')
valid_features = np.loadtxt('val... |
4bd0831449f5f2e1bb622440bfda9f4a4e1927403e46015830267ec4f70038b5 | Python | 1,748 | 49 | import os
import pandas as pd
import deepchem as dc
import numpy as np
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Draw, PyMol, rdFMCS
from rdkit.Chem.Draw import IPythonConsole
from rdkit import rdBase
from deepchem import metrics
from IPython.display import Image, display
f... |
7e30c7a9c0439c7ac260cae57fce81761a795329052db0c629df5bf45802da17 | Python | 1,748 | 57 | import importlib
import numpy as np
def instantiate_from_config(config):
if not "target" in config:
raise KeyError("Expected key `target` to instantiate.")
return get_obj_from_str(config["target"])(**config.get("params", dict()))
def get_obj_from_str(string, reload=False):
module, cls = string.rs... |
465222395d0fd50a9c2533d41877e84fa51f7e319773d93838c97cb8be608ee1 | Python | 1,749 | 61 | """ Create 3D mesh with two conforming edge helixes inside """
import SVMTK as svm
import numpy as np
from pathlib import Path
if __name__ == "__main__":
print("Start ",__file__)
surf = svm.Surface();
outdir = Path("results")
outdir.mkdir(exist_ok=True)
cube = svm.Surface()
sphere = svm.... |
e0a5cb55d6993cf8f1997421d6a0a7531bd0a0909994cd8d8053ea697d6610c9 | Python | 1,750 | 68 | import numpy as np
from parameters import *
import nest
# set up seed for random number
seed = seed
rng_seed = seed
# set up NEST kernel
nest.ResetKernel()
nest.SetKernelStatus({"resolution": dt, "print_time": False})
nest.SetDefaults(neuron_model, neuron_params)
# create generic neuron with Axon and Dendrite
nes... |
08f266b687bfb7e9856882016fa642f75ee8a5158574c483e5c4fad5864aa036 | Python | 1,751 | 46 | # This script takes the filtered alignment files for hgRNA libraries and removes chimeric molecules
# in a manner similar to TPT used by Hill et al 2018 and Dixit et al 2016
import sys
import pysam
import pandas as pd
# This function reads in the bam file and constructs a dataframe
# that can be used to calculate th... |
386583f7ad0011d0574bd1039b18d9b7fdc94b9221279b79adaa6179240bdfa4 | Python | 1,751 | 55 | import kornia
import torch
from .utils import Extractor
class DISK(Extractor):
default_conf = {
"weights": "depth",
"max_num_keypoints": None,
"desc_dim": 128,
"nms_window_size": 5,
"detection_threshold": 0.0,
"pad_if_not_divisible": True,
}
preprocess_con... |
775de06054d460154290ea93678feb0dc7ed522cf1e29d5f1a62a05fa871c405 | Python | 1,751 | 59 | '''
轮廓切割算法消除背景,将去除背景的图片存入到另一个文件夹中
'''
import os
import cv2
import numpy as np
def Remove_background(image_path, output_path):
'''
:param image_path:图像的路径
:param output_path: 保存裁剪图片的文件夹
:return:
'''
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, thresh... |
f6c51cfc2505716be7c0fc1566738396ffd400b2bb283224d9cbf523bddcb8f9 | Python | 1,751 | 48 | import os
import sys
sys.path.insert(0, os.path.abspath('../../'))
sys.path.insert(0, os.path.abspath('../../cellrefiner'))
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuratio... |
fd29ed14f8bef7a0d42a436bd718cb5a8ab1c7243e6a76f801b2c6a2b62745b8 | Python | 1,751 | 53 | import argparse
from contextlib import redirect_stdout
import io
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from pathlib import Path
import pickle
from pstimutils import PertStimDataSimple
from perturbation1 import *
#Set up argument parser
parser = argparse.Argu... |
254c89104a42c3d171e050ffbdc2ae10fbcdeed6d9cce4b5cbe04482969a7bd3 | Python | 1,752 | 55 | from scipy.signal import butter, lfilter, freqz
class BandPassFilter:
def __init__(self, lowcut, highcut, fs, order=5):
self.lowcut = lowcut
self.highcut = highcut
self.fs = fs
self.order = order
self.b, self.a = butter(self.order, [self.lowcut / (0.5 * self.fs), self.highcu... |
944f03a3b22efeb7440d468ce88c31e8858ae83c1305d66603346ce5b8961e67 | Python | 1,752 | 58 | """The label + line-edit + Browse row that every path setting is made of.
The panel this used to be is now :mod:`meanap.gui.panels.data`; what is left is
the widget the folder settings across the window are all built from.
"""
from PyQt6.QtWidgets import (
QFileDialog, QHBoxLayout, QLineEdit, QPushButton, QWidget... |
2f73cae0d7f0eb3145634e77a562ee6edfd7096828c34e5488d3479cf8859c96 | Python | 1,753 | 59 | import torch
from IT_NN import IT_NN
import logging
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
class AENN_TrainingLoop():
def __init__(
self,
training_data,
test_data,
n_labels,
max_label,
cortex_ln_rate,
device
... |
f0c60d2ee58d9e57412ec9a75185ea4f09b687e9d7f122e4cd30021f1eebb85b | Python | 1,753 | 63 | import tensorflow as tf
import numpy as np
def onehot(vocab_size, idx):
x = np.zeros(shape=vocab_size)
x[idx] = 1.
return x
if __name__ == '__main__':
with open('../data/text_data/japan.txt', 'r') as f:
txt = f.read()
X = []
y = []
char_to_idx = {char: i for i, char... |
8b5fab37cb79e1a5fb469e167225c4fb4420bc2b737605ae133d4d4ecf66442d | Python | 1,754 | 59 | import re
import numpy as np
import fasttext
from transformers import pipeline
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import json
from tqdm import tqdm
import os
from nlp_features import *
f1=open('Twibot-22/data_include.json','r')
f2=open('Twibot-22/tweet_include.json','r')
data_inc... |
a329a5570be12f5060b5404d6850a7a7359ebae9361efddfeeda18a75a80d6d0 | Python | 1,754 | 67 | """Downloads pretrained weights by identifier.
Used by CI workflows before building Docker images, and locally to
populate either the default cache or the checkpoints folder for a
manual docker build.
Examples
--------
# populate default cache (~/.pyment/weights/), all identifiers
python scripts/download_weights.py
... |
b270d766127a19b98feac8045c2eb199423da6ff31d80752c95579cf88b71d47 | Python | 1,754 | 62 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Correct B1 map header problem, by applying the scaling (slope) and setting
the slope to 1.
"""
import argparse
import json
import logging
import nibabel as nib
from scilpy.io.utils import (add_overwrite_arg,
add_verbose_arg,
... |
9fea9f1ff1500fe2ee0ba8937a0caf43bc3da5a312689e5ad65ca00edc219ab4 | Python | 1,755 | 52 | """LangChain ``@tool`` wrapper for molecular docking.
Delegates to the pure-Python implementation in
:mod:`chemgraph.tools.docking_core`.
"""
from __future__ import annotations
from langchain_core.tools import tool
from chemgraph.schemas.docking_schema import docking_input_schema
from chemgraph.tools.docking_core i... |
2aada9aadd0816a4abb733781286f691d665c6228c9c2923ec47d053c71c83b9 | Python | 1,756 | 50 | import torch
from utils import loss_and_miner_utils as lmu
from miners.base_miner import BaseTupleMiner
class PairMarginMiner(BaseTupleMiner):
"""
Returns positive pairs that have distance greater than a margin and negative
pairs that have distance less than a margin
"""
def __init__(self, pos_m... |
9c4628b410f6aad7fba1a13dfd030036dbe9516c9f022429a02f2cd9e77dbdb0 | Python | 1,756 | 54 | #!/usr/bin/python3
#
import os
import sys
import argparse
import shutil
import numpy as np
from uac import utils
# Create the parser
my_parser = argparse.ArgumentParser(description="Calculation of labels using laplace solves and landmarks")
# Add the arguments
my_parser.add_argument("target_path", metavar="path", ty... |
b2239aa23dac22853af4e25177812aba6b877ab06aa0b0c2936e585b9dc03326 | Python | 1,756 | 61 | from os import listdir
import os
import sys
import gzip
import subprocess
import time
import sys
from os.path import expanduser
import json
### FILE PATHS ###
FILTERED_DIRECTORY = sys.argv[1]
UW_DATABASE = sys.argv[2]
TAX_FILE = sys.argv[3]
# Create Log File
sample_dictionary = dict()
organism_database = []
def ge... |
e13add7f619c9b4e405e299e88b2f18d2b9b09194ed9946730ed8f99e9542605 | Python | 1,756 | 61 | import torch
import torch.nn as nn
from conf import global_settings as conf_set
# define approximate firing function
class ActFun(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
out = input.gt(conf_set.snn_fire_thresh).float()
# out = input... |
44e3f3a469936e91a09884c19e356f064c7ea515607531f32352c2a2c7c815c5 | Python | 1,757 | 41 | import torch
from torch import Tensor
import torch.nn.functional as F
from typing import List, Tuple, Optional, Union
import torch.nn as nn
import math
class LayerNorm(nn.Module):
r""" LayerNorm that supports two data formats: channels_last (default) or channels_first.
The ordering of the dimensions in the in... |
7a46495f6e9bfe8bfd31b20f75e0f1e23c85cbd8722621c7210e34b46dd9ba1e | Python | 1,757 | 59 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 22 20:21:50 2023
@author: rl05
"""
import sys
import os
import os.path as op
from mne import (setup_source_space, write_source_spaces, read_source_spaces,
compute_source_morph)
sys.path.append('/imaging/hauk/rl05/fake_diamond/sc... |
3a0a8762bf91af42792bf27f52c5972ea02b95d662727ea323e001a77a9a803e | Python | 1,758 | 37 | #!/usr/bin/python3
import os
import numpy as np
from nibabel.testing import data_path
import nibabel as nib
import sys
lobar_aseg_filename = os.path.join(data_path, sys.argv[1])
A = nib.load(lobar_aseg_filename)
A_data = A.get_fdata()
A_data[(A_data == 7) | (A_data == 8) | (A_data == 47) | (A_data == 46) | (A_data... |
6b72f5e621dbf22a27f7c4509bf10ba057755da241701cf6517f9cd980e16412 | Python | 1,758 | 60 | # pylint: disable=line-too-long
import argparse
from datetime import datetime
from deepreg.predict import predict
name = "unpaired_mr_brain"
# 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
p... |
7a1a5fb3e26cc7137dd1d411c869ab342b5c570e6e946f14665de25ce5965991 | Python | 1,758 | 54 | """Compare threshold based on 1/3 of maximum to FDR corrected threshold"""
import numpy as np
import nibabel as nb
import os.path
import nilearn
from nilearn.glm import threshold_stats_img
# Set data path
ROOT = "/Volumes/sDresBackUp/s1Anfunco/Nifti"
SUBS = ['sub-05', 'sub-06', 'sub-07', 'sub-09', 'sub-10', 'sub-12... |
84a2d6d5aacabec207201d3c11b84ef9a71ff7254c215a51da82d6800dcfe9cc | Python | 1,758 | 61 | from __future__ import print_function, absolute_import
import json
import os.path as osp
import shutil
import torch
from torch.nn import Parameter
from .osutils import mkdir_if_missing
def read_json(fpath):
with open(fpath, 'r') as f:
obj = json.load(f)
return obj
def write_json(obj, fpath):
m... |
d259d1569a055be6c6d635f06d4088542067cc012256e38a290248aa97818b94 | Python | 1,758 | 34 | import os
import nibabel as nib
from nipype.interfaces.base import (
TraitedSpec, CommandLineInputSpec, CommandLine,
File, traits, Str, Directory
)
class MarkVCIDFreeWaterInputSpec(CommandLineInputSpec):
in_dwi = File(exists=True, mandatory=True, desc='Input DWI file', argstr='%s', position=0)
in_dwi_m... |
d8f9bb1c4d19c819710ca14dc4b9bfe1661fb16349fceca949728a17f96e0b21 | Python | 1,758 | 71 | from __future__ import annotations
import dataclasses
from importlib import resources
from pathlib import Path
EXAMPLE_002 = 'example-002-mace-ensemble-screening'
CAMPAIGNS = {
'mace-ensemble-screening-20': f'{EXAMPLE_002}/campaign.jsonc',
}
LM_CONFIG_TEMPLATES = {
'argo-gpt54-mace-template': f'{EXAMPLE_00... |
13a7cbf11c3a563ff470d234c048ccaa28336807ff7a7fcd07ed603778ae0bf0 | Python | 1,759 | 51 | #!/usr/bin/env python3
import sys
import getopt
import time
############################################################################
# Main gateway:
#############################################################################
# usage
def main_usage():
print("""
Usage : SEAM.py action [options]
Actions:
--... |
33ddeafce2d8bd80fd2ed0ad096dd48a6079d5df28c7b6088acfa18347d83311 | Python | 1,759 | 50 | """
Classifier-Chain Head
─────────────────────
将基模型输出的表示向量 `rep` 依次生成 8 个标签的 *logits*,
后一个标签输入会串联前一个标签的 *概率*(sigmoid)。
实现方式:共享一层 `nn.Linear(rep_dim, hidden)` 提取中间
特征,再用 8 个单独的 `nn.Linear(hidden + 1⋯i, 1)` 逐步
累积条件信息。这样既轻量又能显式建模标签依赖。
"""
from __future__ import annotations
import torch
import torch.nn as nn
import torch... |
7c7348536e410fcef4fcdb79f87296e103964ed990cbdc92b7a60490858b1344 | Python | 1,759 | 61 | # Generated by Django 4.2.20 on 2025-05-01 11:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("engine", "0088_consensus_jobs"),
]
operations = [
migrations.AlterField(
model_name="labeledimage",
name="source",
... |
0d5dd3dba1e6ac688f9c7e349a1ba7244ab762ed88587333ca1ab72547a22ef9 | Python | 1,760 | 69 | #!/usr/bin/env python
import sys
from sys import argv
from commands import getoutput
from numpy import *
def usage():
print("Usage: " + argv[0] + " <input2standard mat> <output mat>")
print(" ")
print(" First argument is the FLIRT transform (12 DOF) from the input image to standard")
print(" ... |
9c27c8c6a879940a641c5f3ed0f101d1f2580d2454b9d2072bef99357008ed35 | Python | 1,760 | 66 | """
HMM: fMRI Dual Estimation
=========================
After training an HMM on fMRI data, we normally want to estimate subject-specific quantities based on the group-level model. We refer to this process as 'dual estimation'. We estimated subject/static-specific means and covariances. In this tutorial, we show how t... |
6cb9984fd7885b2adf5ff41d1207d72d3b945f05f18291e43b8af3de1254fd4f | Python | 1,761 | 53 | #!/usr/bin/env python
# Install script for widefield tools
# 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... |
eae625f2fb3bd3b712f61cae415ab00168c2ae9423e020ea3f06f9f6d1dc5f14 | Python | 1,761 | 47 | #!/usr/bin/env python3
"""Train and evaluate the eye movement artifact detector."""
import json
import logging
import os
from artifact_identification.detectors.eye_movement import EyeMovementDetector
def _save_thresholds(detector: EyeMovementDetector, evaluation: dict) -> None:
"""Persist the detector operating... |
1e76a8d187d7277cc938d881f460eabbc3d9ba172d6017e708c37d29c323380b | Python | 1,762 | 47 | import subprocess
import os
import argparse
# python is only used to create the slurm file
os.chdir('/home/lorincn/isilon/Cheng-Noah/GenT_results/gent_specific_traits_ondemand')
parser=argparse.ArgumentParser(prog='GenT',description='Perform genome-wide GenT analysis.')
##########
# defaults
ld_default='/home/lorincn/... |
481e1176f0c8ca030b690190040522a8f6ee67d600e585ed99cbe9a7e5753f55 | Python | 1,762 | 87 | # -*- coding: utf-8 -*-
"""
distinctipy is a lightweight python package providing functions to generate
colours that are visually distinct from one another.
Example:
>>> import distinctipy
>>> distinctipy.get_colors(5)
[(0, 1, 0), (1, 0, 1), (0, 0.5, 1), (1, 0.5, 0), (0.5, 0.75, 0.5)]
"""
# flake8: noqa
fr... |
7c7f07df8d5879ea63a7816ef95da7beeff00fcf046739a4ca6c30e49e9e2f44 | Python | 1,762 | 58 | from qtpy.QtWidgets import QWidget, QVBoxLayout, QMessageBox, QProgressBar
from pathlib import Path
class ProgressBar(QWidget):
"""
A QWidget subclass representing a progress bar.
"""
def __init__(self, parent: QWidget = None):
"""
Initialize the ProgressBar widget.
Parameters... |
f0330c320210a1811aa5c82b816dca2faac56bf27a3101d33d49daaf37fb6ee2 | Python | 1,762 | 76 | import torch
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
import os
from torchvision import transforms
import pandas as pd
import rdkit
from rdkit import Chem
from rdkit import DataStructs
from rdkit.Chem.Descriptors import MolWt, ExactMolWt
import decimal
from numpy.linalg import norm
... |
fdac8a1431f2286a8be6a8a1f309e53c988f67838ab7b3b1179178754232cb65 | Python | 1,763 | 85 |
import numpy as np
import zarr
from numcodecs import Blosc
from tqdm import trange
import os
# ======================
# CONFIG
# ======================
path = "/media/sophie/Expansion1/UCL/datatest/videos/2screens/30/"
npy_i = os.path.join(path, "dwt_videodata2_i.npy")
npy_r = os.path.join(path, "dwt_videodata2_r.np... |
61fe60ddff867ef5a6fad3f94e7ad960fa5328575ba8f1845d2ed7e31bc1dffe | Python | 1,764 | 44 |
import numpy as np
import xarray
from marques_utils import gen_sample
from brainscore_core.supported_data_standards.brainio.packaging import package_data_assembly
from brainscore_core.supported_data_standards.brainio.assemblies import DataAssembly
ASSEMBLY_NAME = 'devalois.DeValois1982a'
ORIENTATION_STIM_NAME = 'Marq... |
9d896ded249d46a735c51c8a4f31445fff774eca00c6eb083c49640312729eaa | Python | 1,764 | 55 | import matplotlib.pyplot as plt
import numpy as np
import csv
from download_aa_sequences import calculate_aa_dist_per_proteome as csp
from download_aa_sequences import normalize_aa_dist as nd
AA_LETTERS = sorted("ACEDGFIHKMLNQPSRTWVY")
aa_biosythesis_reader = csv.reader(open('aa_biosynthesis.csv'), delimiter='\t')
fo... |
445ed59bef242c764fc39791536332c0e04862cb3e399a49731ac20f9ec4da00 | Python | 1,765 | 45 | import sys
from pathlib import Path
p_dir = str(Path(__file__).absolute().parents[2])
if p_dir not in sys.path: sys.path.insert(0, p_dir)
import os
from os.path import join
import torch.nn as nn
class efficient_net_3d(nn.Module):
"""
hparams from https://www.kaggle.com/rluethy/efficientnet3d-with-one-mri-ty... |
6d620f8f68d286ebc822c3877b79d34e787364364040aa96805543ca5f406eff | Python | 1,765 | 81 | from .augmentation import (
AddGap,
ChangeDtype,
ChannelDropout,
Copy,
DKPNPreProcessor,
Filter,
FilterKeys,
GaussianNoise,
Normalize,
NullAugmentation,
OneOf,
RandomArrayRotation,
RealNoise,
RotateHorizontalComponents,
)
from .das_labeling import ProbabilisticDAS... |
8f15198a66da2a02151974600d25b23369959a4b9f0cc31573ec89c84ba6ce9f | Python | 1,765 | 79 | import sys
import numpy as np
try:
import cupy as cp
except ImportError:
pass
# --------------------------------------------------------
# Defalut is to use numpy, not cupy
# --------------------------------------------------------
gpu_mode = False
# --------------------------------------------------------
# ... |
bf73fd44b50689ff74b82d58193fecb8fc7921e80b4ad45bf1864400aece3614 | Python | 1,765 | 43 | import unittest
from causallib.positivity.datasets.positivity_data_simulator import make_1d_overlap_data
from causallib.positivity.datasets.pizza_data_simulator import pizza
class TestPositivityDataSim(unittest.TestCase):
def test_get_1d_data(self):
treatment_bounds = (0, 75)
control_bounds = (25... |
0638180b4ffeb5911bd8e1143365cae14e0aa4a0f4bbd48e47aee173a3065ec6 | Python | 1,766 | 51 | import numpy as np
import torch
from batchgeneratorsv2.transforms.base.basic_transform import ImageOnlyTransform
class InvertImageTransform(ImageOnlyTransform):
def __init__(self, p_invert_image: float, p_synchronize_channels: float = 1, p_per_channel: float = 1):
super().__init__()
self.p_invert... |
40daa6183c3323af819380cac78ef3acc8c5d9a8f8db650b86478a90e009ae28 | Python | 1,766 | 51 | #!/usr/bin/env python3
# This script is included in documentation. Adapt line numbers if touched.
import arbor as A
from arbor import units as U
import pandas as pd # You may have to pip install these.
import seaborn as sns # You may have to pip install these.
# (1) Create a morphology with a single (cylindrical) s... |
4aba9ad42a937da59e3d823f2225ea2b1c048e53a25e83a0898c7bce802bc26f | Python | 1,766 | 77 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from .driver import annotate_task
from .exceptions import BadFunctionError
from .interface import (
AutoAnnotationFunction,
DetectionAnnotation,
DetectionFunction,
DetectionFunctionContext,
DetectionFunctionSpec,
InteractionFu... |
4b04e5df25783d57508300410b0dfb42245ca7f6e27c27c2319200c2709b4f2d | Python | 1,766 | 62 | import os
import numpy as np
import torch
from fairseq.data import FairseqDataset
class DepBiasDataset(FairseqDataset):
"""
Wrap a base dataset; each sample adds dep_bias matrix from dep_dir/{idx}.npy
dep_bias is aligned to BPE token length (src side).
"""
def __init__(self, base_dataset: Fairseq... |
4f37dfba37a5cba2809bc0394e7337572630d52cd43d9609ea013057772755d7 | Python | 1,766 | 60 | import unittest
import os
try:
import mujoco_py
from mujoco_py import load_model_from_path, MjSim, MjViewer, load_model_from_xml, ignore_mujoco_warnings
except ImportError as e:
raise ImportError("(HINT: you need to install mujoco_py, and also perform the setup instructions here: https://github.com/openai/... |
7795605b6b3aadff213fc819d636402c07721259e9fd816ae2e93146980a6e01 | Python | 1,766 | 47 | #!/usr/bin/env python3
"""Train and evaluate the muscle artifact detector."""
import json
import logging
import os
from artifact_identification.detectors.muscle import MuscleArtifactDetector
def _save_thresholds(detector: MuscleArtifactDetector, evaluation: dict) -> None:
"""Persist the detector operating point... |
9e2e1655412274f9cb00eabcc4fe966d694d3c90591862bf978112b7d398d559 | Python | 1,766 | 51 | import torch
def sinkhorn(feature1, feature2, pcloud1, pcloud2, epsilon, gamma, max_iter, sim_k=50, dist_k=10):
feature1 = feature1 / torch.sqrt(torch.sum(feature1 ** 2, -1, keepdim=True) + 1e-8)
feature2 = feature2 / torch.sqrt(torch.sum(feature2 ** 2, -1, keepdim=True) + 1e-8)
# 计算余弦相似度矩阵
S = t... |
b7b1121b9022b6acf066e150d0f7556629930900e2b1577c6ec51680b393503d | Python | 1,766 | 58 | from typing import ClassVar
from argclz import argument, as_argument
from rscvp.util.util_gspread import GSPREAD_SHEET_PAGE
from .cli_core import CommonOptions
from .cli_io import HEADER
from .cli_selection import SelectionOptions
__all__ = ['StatisticOptions']
class StatisticOptions(SelectionOptions):
GROUP_ST... |
fad2e503bedfda2001626bf5f7efd78e049d0df5e86561b0512eb10fd49727a1 | Python | 1,766 | 61 | #!/usr/bin/python3
import os
import numpy as np
from nibabel.testing import data_path
import nibabel as nib
import sys
# Load Bullseye Parcellation
bullseye_filename = os.path.join(data_path, sys.argv[1])
bullseye_filename_bis = os.path.join(data_path, sys.argv[2])
bullseye = nib.load(bullseye_filename)
bullseye_bi... |
2d60ae4b6664556c417874b1dd87faf943fc5a754c10206226d8226c8c695a64 | Python | 1,768 | 43 | import os
import globus_sdk
from dotenv import load_dotenv
load_dotenv()
# ----------------------------------------------------------------------------
# The following is to generate an access token that will be valid for 48 hours
# ----------------------------------------------------------------------------
# Load y... |
3dea6a93471b7799e33d858d45878518f876d330dc5aa66ecaead046b1267013 | Python | 1,768 | 51 | ### Cloned from github milesial/pytorch Unet
""" 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_class... |
605bad8577c8546d350c294a5b32f0760eb3abc3cef29c297791c02b71690e54 | Python | 1,768 | 59 | import brainpy as bp
import brainpy.math as bm
import numpy as np
import matplotlib.pyplot as plt
from cann_fft import CANN1D
#set default ramndom seed for reproducibility
np.random.seed(0)
#set backend to cpu
bm.set_platform('cpu')
#create and run the network
cann = CANN1D(num=128, mbar=1)
v_ext = cann.a / cann.tau_v... |
e6bc6cac04157e15954fa56895be3111dc011721abd62ecf6b90b3ca3b1c612d | Python | 1,768 | 51 | from typing import Final
import polars as pl
from argclz import as_argument
from neuralib.plot import plot_figure
from neuralib.util.verbose import publish_annotation
from rscvp.statistic.core import StatPipeline
from rscvp.util.database import DB_TYPE
from rscvp.util.util_gspread import GSPREAD_SHEET_PAGE
__all__ =... |
f9e053d8a94119e478d2bf6c9eaa39afab6ad3c56109c21276e61acb4d7b32c5 | Python | 1,768 | 49 | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from pathlib import Path
from argparse import ArgumentParser
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster
parser = ArgumentParser()
parser.add_argument('-c', '--corr-mat', type=str, required=True,
help... |
41a6c71655ebc12e24276cc518f5a89ef3b8382c5d45d742582a4837019e1654 | Python | 1,769 | 50 | import torch
import torch.nn as nn
from transformers import BertModel, BertTokenizerFast
class BertTextEncoder(nn.Module):
"""
BERT-based text encoder.
Returns an L2-normalized sentence embedding (CLS token).
"""
def __init__(self, model_name: str = "bert-base-uncased", output_dim: int = 768, freez... |
83aaf034201dad8201c28c3364d35cc855b95649e4b07fb8e74e6434b42806d3 | Python | 1,769 | 75 | import copy
import h5py
import os
import pickle
import torch
import yaml
import scipy.stats as stats
from deepdwi.models import autoencoder as ae
import matplotlib.pyplot as plt
import numpy as np
import torch.utils.data as data
DIR = os.path.dirname(os.path.realpath(__file__))
HOME_DIR = DIR.rsplit('/', 1)[0]
HOME... |
095e31c66e0a865bcc558b86dcd90bce8a4b1cc2e04d84a00ddbc1b98f7e4e7b | Python | 1,770 | 87 | from impedancefitter.RC import rc_model, RC_model, drc_model, rc_tau_model
from impedancefitter.cole_cole import cole_cole_R_model
from scipy.constants import epsilon_0 as e0
import numpy as np
omega = 2. * np.pi * np.logspace(1, 8, num=20)
# for RCfull
Rd = 100
Cd = 1e6
# for Rctau
tauk = Rd * Cd * 1e-12
# for RC
c... |
197f6eccad70606c90703fa958b1d72f0f514c4b99bd383812bf50a060ee76dc | Python | 1,770 | 47 | """Functions used to manage files kept within osl-dynamics."""
from os import path
def check_exists(filename: str, directory: str) -> str:
"""Looks for a file in the current working directory and in osl-dynamics.
Parameters
----------
filename : str
Name of file to look for or a path to a fi... |
3ce1fd8dcc3813a78913d5e98a14f6f642d51a0aeeba1c9df85db6b06d7014c2 | Python | 1,770 | 81 | #!/usr/bin/env python3
import os
import logging
class DataFace(object):
""" Some data IFace bowtie can work with.
"""
def size(self):
raise NotImplementedError("size() needs to be implemented!")
class SamFile(DataFace):
def __init__(self,sam_desc):
self.file_desc = sam... |
637408a95091426cd1310e5ffb56eb5940fb5854bda68a4eee4968e80aa4112f | Python | 1,770 | 49 | import nibabel as nib
import numpy as np
from pyment.preprocessing.pad import pad_nifti_image_if_necessary
def test_pad_nifti_image_if_necessary_shape_and_edge_mode():
data = np.arange(2 * 3 * 4, dtype=np.float32).reshape((2, 3, 4))
image = nib.Nifti1Image(data, affine=np.eye(4))
target_shape = (4, 5, 6)... |
cf6f4fa2144f6995a725b8c032e1cfb1210ee660f9c9d7bf0ad4b1d7ccf236be | Python | 1,770 | 68 | # -*- coding: utf-8 -*-
"""
Average cycle periods
The purpose of the following script is to average a time points within a time
series depending on the stimulus cycle for display purposes.
"""
# python standard library inputs
import os
# external inputs
import numpy as np
import nibabel as nb
# local inputs
from f... |
060c986ee3d711d9337d8e89f51b9307a700e0556ed4cc9fe5359f5f9fb74a24 | Python | 1,771 | 63 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Transform bvecs using an affine/rigid transformation.
"""
import argparse
import logging
from dipy.io.gradients import read_bvals_bvecs
import numpy as np
from scilpy.io.utils import (add_overwrite_arg, assert_inputs_exist,
assert_outpu... |
58c9847b5c854931bbffdf861b7b81e224036cbc32981b09c47cd332b2482fae | Python | 1,771 | 67 | """Predict a class label using neuroimaging features.
Note, this script doesn't require osl-dynamics, it uses scikit-learn
to train a machine learning model.
This script should achieve an accuracy of ~0.8.
"""
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
f... |
323d80a7f41199584ce56bf14fb90e173a041cab97b01bfc717da31cdd213537 | Python | 1,773 | 48 | from brainvoice.utils import get_instance
from brainvoice.modules.utils import View
import torch.nn as nn
class ConvolutionalRegressor(nn.Module):
def __init__(self, conv_kernel_sizes, conv_strides, conv_paddings, block_activations, conv_in_channels,
conv_out_channels, view_layer, linear_layer,... |
bb1590c95002a0e7fd18f79054290eeda2f717087b2dafcfdd9800c9da179d00 | Python | 1,773 | 43 | import torch
def draw_contours_(canvas, contours, close=True):
"""Draw contours.
Draw ``contours`` on ``canvas``.
Note:
This is an inplace operation.
Args:
canvas: Tensor[h, w].
contours: Contours in (x, y) format. Tensor[num_contours, num_points, 2].
close: Whether ... |
2902d3036177ce928cae84420d865b98ef8760db016180baa391ca5c58fe95bb | Python | 1,774 | 54 | from collections import OrderedDict
import numpy as np
from brainscore_vision.model_helpers.activations.core import ActivationsExtractorHelper
from .descriptor import PositiveNegativeGlobalGaborFilterEntropyExtractor, GaborEntropyConfig
MODEL_IDENTIFIER = 'gabor_filter_entropy_4x4_v2_forcedCosine'
LAYER_NAME = 'gab... |
92fddd61ad53cbf41b9243037c6fbe1e264ff5588aa92053c2ae23b302addd81 | Python | 1,775 | 48 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
fetch_data(get_testing_files_dict(), keys=['processing.zip'])
tmp_dir = tempfile.TemporaryDirectory()
def test_help_option(script_runner):
ret... |
cadfc3097944d53961129df1555f36b10d75217167e9ca3f6ea43a274398fc61 | Python | 1,775 | 67 | #!/usr/bin/env python
#This script calculates the inclusion level of RNA-Seq reads
import sys
#Inc.txt
ofile=open(sys.argv[2],'w');
ofile.write('IncLevel1\tIncLevel2\tIncLevelDifference\n');
def vec2float(vec):
res=[];
for i in vec:
res.append(float(i));
return(res);
def vec2psi(inc,skp,effective_inclusion_len... |
7d4be85c2da60d827c67c675b9e04a65dff42c146b44d889f025ecd1a34171cd | Python | 1,776 | 55 | # 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, ... |
0799e8911eee68d16d1e72c7244422111d332ab7f7575ce1fdbf23fe2aaa389e | Python | 1,778 | 55 |
from tierpsy.helper.misc import IMG_EXT
from .Readers.ReadVideoFFMPEG import ReadVideoFFMPEG
from .Readers.readVideoHDF5 import readVideoHDF5
from .Readers.readDatFiles import readDatFiles
from .Readers.readImages import readImages
from .Readers.readVideoCapture import readVideoCapture
from .Readers.readLoopBio impor... |
37b9ac3e808c90ed2b081484ded725b0e997502764d1e2e58a28579d9a582305 | Python | 1,778 | 65 | import pytest
import numpy as np
import tensorflow as tf
from nems.layers.state import StateGain
def test_constructor():
with pytest.raises(TypeError):
# Shape has too few dimensions
sg = StateGain(shape=(1,))
sg = StateGain(shape=(2,2))
def test_evaluate(spectrogram, state):
# Don't th... |
479bfa7b6b67b45721fc972f1042e561d679829130cabeeefafdf827f73aab4d | Python | 1,778 | 53 | from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
class PatchDropout(nn.Module):
"""
https://arxiv.org/abs/2212.00794 and https://arxiv.org/pdf/2208.07220
"""
return_indices: torch.jit.Final[bool]
def __init__(
self,
prob: float = 0.5,
... |
5f5acf5465f4ec4fb94aa0c5a6dde7d031727b92d217315a7ab9a3f2d5b6e688 | Python | 1,778 | 61 | """Single-agent MCP example over stdio (remote via SSH).
Connects to ChemGraph's built-in MCP server running on a remote ALCF
compute node via SSH + stdio transport.
Usage
-----
# 1. Secure a compute node (qsub -I ...)
# 2. Edit REMOTE_HOST and REMOTE_ENV below
# 3. Run from a login node:
python run_c... |
ffab7eabb6eb5bbfa235eedb71ca4f64797710cba454f9be42ea4923c024e0f0 | Python | 1,778 | 65 | from torch import nn
from model.non_local_embedded_gaussian import NONLocalBlock1D
class Network(nn.Module):
def __init__(self):
super(Network, self).__init__()
self.conv_1 = nn.Sequential(
nn.Conv1d(in_channels=2, out_channels=32, kernel_size=9, stride=1, padding=4),
nn.B... |
b47ff66b7c6a01eb8ae8031315e24cc67fbbd79a0e97d6272c3c3eb24feb2efb | Python | 1,779 | 70 | #!/usr/bin/env python
"""
Check focus lock tests.
"""
from storm_control.test.hal.standardHalTest import halTest
def test_hal_tcp_cfl_1():
halTest(config_xml = "none_tcp_config.xml",
class_name = "CheckFocusLock1",
show_gui = True,
test_module = "storm_control.test.hal.tcp_tes... |
39666e01aad8427c4a45209265822b5404bbe3fc225cf98d8c03ee5fc40bc360 | Python | 1,780 | 47 | #!/usr/bin/env python3
"""
Usage: copy-record-pod5.py pod5.md5 copy_record output_path
"""
import pandas as pd
import os
import re
import sys
input_file = sys.argv[1]
copy_record = sys.argv[2]
output_file = sys.argv[3]
actual_md5 = pd.read_table(input_file, header=None, names=["actual_md5", "pod5"])
actual_md5["pod5"... |
49066b073d099ea943a2be4b6880af0811814d3c562ac2b44a73599991532bd0 | Python | 1,780 | 46 | import torch
from distances import CosineSimilarity
from utils import common_functions as c_f
from losses.generic_pair_loss import GenericPairLoss
class NTXentLoss(GenericPairLoss):
def __init__(self, temperature=0.07, **kwargs):
super().__init__(mat_based_loss=False, **kwargs)
self.temperature =... |
b1c4c5d6e0092e1d8cdd02e508c956b067c51515c7422ed4d5c216cfbedf282e | Python | 1,780 | 58 | path1 = r'C:\Users\YHR\Desktop\YHR\硕士\符号网络\数据\议员数据\投票数据\vote_net50.txt'
path2 = r'C:\Users\YHR\Desktop\YHR\硕士\符号网络\数据\议员数据\投票数据\vote_net50_weight.txt'
with open(path1, "r") as f:
data = f.readlines()
dic = {}
for i in data:
dic.setdefault(int(i.split('\t')[0]), [])
dic[int(i.split('\t')[0])].append(int(i.... |
7769f42de3eff1e40c143525d270e0a15b4732c1e93307e131dc43f6aae0e1f4 | Python | 1,782 | 50 | import numpy as np
import nibabel as nib
from scipy import sparse
from scipy.io import loadmat
from nilearn import plotting
from pathlib import Path
import sys
import multiprocessing
parcelfile=sys.argv[1]
outputdir=sys.argv[2]
outputsuffix=sys.argv[3]
matfiles=sys.argv[4:]
#parcelfile='/home/kwj2001/colossus_shared... |
89eecf1c16cc89bae393ed0dcd669fcda2b15cbc59c788da3b791f00096a5703 | Python | 1,782 | 63 | # Figures 1 and 2
# from Analysis of dielectric relaxations of w/o emulsions
# in the light of theories of interfacial polarization
# by T. Hanai, T. Imakita, and N. Koizumi
import numpy as np
from scipy.constants import epsilon_0 as e0
import impedancefitter as ifit
from impedancefitter.suspensionmodels import bhcubi... |
5f321db1f0c5f9e32b7eef3964d766845919d1d4b444351b0401aab7611ee257 | Python | 1,783 | 58 | #!/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... |
aa62e368b6d9ff33eb326d0c91d89dc684f3b9fbae719e77458418616267f927 | Python | 1,783 | 55 | # 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, ... |
f66dd80bd4d6e3f6a6290460c444ebd382fa3d90c40aaa2384d7e2d1b1975824 | Python | 1,783 | 48 | # 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]uni-rostock.de
#
# This program is ... |
f8860afee2f9b7c73e144ef5140569ac02f4c11b4f583793ef1563fedba62f37 | Python | 1,783 | 59 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
import scvelo as scv
import numpy as np
import torch
import matplotlib.pyplot as plt
import pyrovelocity as pv
from pyrovelocity.tasks.data import download_dataset
from pyrovelocity.tasks.preprocess import preprocess_dataset
from pyrovelocity.tasks.train import train_d... |
62914befb7fa69b1b97bb4c9f5accd5e18a4d222c3707eba44028c3de3ebabca | Python | 1,784 | 79 | import torch as th
import numpy as np
import dgl
def __random_aug(graph, x, feat_drop_rate, edge_mask_rate):
n_node = graph.number_of_nodes()
edge_mask = mask_edge(graph, edge_mask_rate)
feat = drop_feature(x, feat_drop_rate)
ng = dgl.graph([])
ng.add_nodes(n_node)
src = graph.edges()[0]
... |
f8c89cb3bdf10812601d30ef4af5ac5087429c46aa210888fc47dfa3d8f8e8d1 | Python | 1,785 | 49 | import sys
import subprocess
import os
import yaml
import pandas as pd
import numpy as np
#whether offdet is usable will be obtained directly from offdetfile, licking is obtained directly from aRec, opto is blocked according to stimdir
script = 'preprocessing/quiet_extraction/extract_transients.py'
pathpath = 'PATHS/... |
5246e1768d6886ba92bfcd1c19ea8b75196eec6d2f8414227a8ed4d094926937 | Python | 1,786 | 71 | # COCO limb sequence (0-based indexing)
coco_limb_sequence = [
(0, 1), # Nose to Left Eye
(0, 2), # Nose to Right Eye
(1, 3), # Left Eye to Left Ear
(2, 4), # Right Eye to Right Ear
(5, 7), # Left Shoulder to Left Elbow
(7, 9), # Left Elbow to Left Wrist
(6, 8), # Right Shoulder to Ri... |
4adb25c7d00ec373e7c78e06664451a8dfa17e817dbcd1736d9e8812ffa1955a | Python | 1,787 | 49 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Rene Schmieding
#
# 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... |
9895be28a8830c5722c8a2cc9ed03e86d97ef3704711475dc070d3ae668196ab | Python | 1,787 | 41 | #!/usr/bin/env python
"""Structure clustering script to group similar PDB models."""
import os
import argparse
from utils_trX2dy.utils import save_cluster_result
def main():
parser = argparse.ArgumentParser(
description="Cluster predicted structures based on GloCon or TM-score/RMSD."
)
parser.add_a... |
10e6ca43d1f928b394ebd641557911060009b4ae3696da12913f28a2dd56e797 | Python | 1,788 | 66 | from __future__ import annotations
import json
import os
import uuid
from pathlib import Path
from typing import Any
__all__ = [
'append_jsonl',
'read_json_file',
'read_jsonl',
'write_json',
'write_json_atomic',
]
def write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=Tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.