sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
60f80138fd762827433aefe5db35da018137f632c23f0c7a8927ac7cf3ac04f3
Python
3,424
103
import torch from bindsnet.network import Network from bindsnet.network.nodes import ( AdaptiveLIFNodes, IFNodes, Input, LIFNodes, McCullochPitts, Nodes, SRM0Nodes, ) class TestNodes: """ Tests all stable groups of neurons / nodes. """ def test_init(self): network...
62dffaefb4d0c456cbd46cfedc55c6edcb62c8958a6664a4dd447a94ea987a60
Python
3,424
103
targetMean = 8 targetStd = 1.5 initStep = 0 import pandas as pd resultsMean = [] resultsStd = [] for i in range(40): base_name = 'R:/Temp/Threads16/Thread'+str(i)+'/Simulation/output/Data.csv' df = pd.read_csv(base_name) if df.iloc[0,0]>1000: resultsMean.append(0) else: resultsMean.app...
a04ebab5ceed331a2c3202f65359f358c4b8fea8d23214e6a4371973d346977a
Python
3,425
112
# Copyright (c) MONAI Consortium # 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://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, so...
f32b4b816d701347dd3249c71b35640fa9c968b2829d754dc8944fe6f2931bb7
Python
3,425
87
import torch import torch_geometric from torch_geometric.data import Data as PyGData from torch_geometric.utils import dense_to_sparse, to_dense_batch, to_dense_adj from utils.tensor_operator import tensor2array, GraphTensorPacking from utils.tensor_operator import make_one_hot # ATOM_ENCODER = {'C': 0, 'N': 1, 'O':...
b9febb2128813800c3c045ff84a8d0e216298c7e34f32ecf659c0e35a07dced0
Python
3,426
93
import os os.nice(19) import numpy as numx import pydeep.rbm.model as MODEL import pydeep.rbm.trainer as TRAINER import pydeep.rbm.estimator as ESTIMATOR import pydeep.misc.visualization as VISUALIZATION import pydeep.misc.io as IO import pydeep.misc.numpyextension as npExt import mkl import scipy.io as sio mkl.set_nu...
55b8faf658b0558ff44bd2fabdd6c0e8b09444ded40a11ae1cc33dcf35fea09b
Python
3,431
104
import matplotlib matplotlib.use('agg') import sys from mantis_ml.modules.pre_processing.eda import EDA from mantis_ml.config_class import Config class EDAWrapper: def __init__(self, cfg): self.cfg = cfg self.high_corr_thres = self.cfg.high_corr_thres self.test_size = self.cfg.test_siz...
cdd8cea39030300d84491b557c9f12beb39007361c9d2badc7760e817cb81f1d
Python
3,431
100
import warnings from enum import Enum from typing import Any from typing import Callable from typing import Dict from typing import Optional from typing import Union import numpy as np from neuralpredictors.measures.np_functions import corr from torch.utils.data import DataLoader from .predictions import get_model_pr...
9666ea2bd7897544c7d87fedc4e4648cd45bad73b0137d239f1d740467b3fa70
Python
3,432
94
# Copyright (c) 2008-2026 the MRtrix3 contributors. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Covered Software is provided under this License on an "as is" #...
e4b3d00a155ae1f15407634318a49910a9c05b25c9c415fac435951a236480c3
Python
3,432
162
import pytest import yaml from unittest.mock import patch, mock_open from animalai.envs.arena_config import ( Vector3, RGB, Item, Arena, ArenaConfig, constructor_arena, constructor_item, ) item_yaml = """ !Item name: Wall positions: - !Vector3 {x: 13.3, y: 0, z: 33} - !Vector3 {x: ...
1709586ff10e2c7af7b9470ebffcc53dca5ed8a49471b11a2b2fc5069341af91
Python
3,435
74
# Script copied from https://github.com/flyyufelix/DenseNet-Keras/blob/master/custom_layers.py from keras.engine import Layer, InputSpec try: from keras import initializations except ImportError: from keras import initializers as initializations import keras.backend as K class Scale(Layer): '''Custom Laye...
3881c342cc2b528efa03935bfb5c12663f03e2aa0ec667458e1fa82115af95ac
Python
3,435
121
#!/usr/bin/env python import h5py import sys import pandas as pd import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons import numpy as np import sys W_JUST_HIT_ELEM = 1 def intensity(complexEField : np.ndarray): """ Calculate the intensity from the electric field components. """ ...
e9c654ec9c7b2bc6248f3be708a62af0b32bba9f46a7b8e72e086d0d5b9c366e
Python
3,435
117
#!/usr/bin/env python3 """ Smooth one or more labels within an integer atlas volume Usage ---- smooth_labels.py -i <input label image> -o <output label image> [label numbers] smooth_labels.py -h Example ---- >>> smooth_labels.py -i atlas.nii.gz -o atlas_smooth_5.nii.gz 5 10 11 Authors ---- Mike Tyszka, Caltech Brain...
1a69a13cb778a6c8b74e08b53318560c8d2300be177f59f864ca25bcee9dfc5f
Python
3,436
105
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import numpy as np import nibabel as nib import os DESCRIPTION = 'Swap the dimensions of acquired post-mortem dMRI data to resemble MNI space. Cornelius Eichner 2020' np.set_printoptions(precision=2) def buildArgsParser(): p = argparse.ArgumentP...
c9d9ecddab9baeb3f7593250c04554acb40141e9ec59b76fad01b3b922955e71
Python
3,438
97
import os import sys import time import torch import torch.nn import argparse from PIL import Image from tensorboardX import SummaryWriter from validate import validate from data import create_dataloader from earlystop import EarlyStopping from networks.trainer import Trainer from options.train_options import TrainOpt...
ffccafaa09954fdd75a1d9b2de286a527c9714e32b6c272276b9982a74f9d920
Python
3,439
109
""" Test that the examples in the repo run without errors. """ import pathlib import re import subprocess import tempfile import textwrap import pytest from openff.toolkit._tests.utils import _get_readme_path from openff.toolkit.utils import RDKIT_AVAILABLE, get_data_file_path, temporary_cd def run_script_file(fil...
58e65e4310550889e752597257f435ceaaa15eb37f3d7394fa11ec315dff092e
Python
3,440
83
from dival import TaskTable from dival.measure import PSNR, SSIM from dliplib.utils import Params from dliplib.utils.data.datasets import CachedDataset from dliplib.utils.helper import select_hyper_best_parameters, load_standard_dataset from dliplib.utils.reports import save_results_table from dliplib.utils.weights im...
8479563c0e56727c678ee2cb319e6350b70fc3f687f0acd7287e55d5554cb941
Python
3,440
85
import sys sys.path.append(".") import argparse import gzip import pickle import re import io import tarfile from tqdm import tqdm from mat2seq import CIFTokenizer PATTERN_COMP = re.compile(r"(data_[^\n]*\n)", re.MULTILINE) PATTERN_COMP_SG = re.compile(r"(data_[^\n]*\n)loop_[\s\S]*?(_symmetry_space_group_name_H-M[^\n]...
37746c8ffa842e78d1baafb430a94db34eec6109f4a7357c5734d1a8b2a223b1
Python
3,441
108
"""Test formatting functionality.""" import pytest from langchain_core.agents import AgentAction, AgentActionMessageLog, AgentFinish from langchain_core.documents import Document from langchain_core.messages import ( AIMessage, AIMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessage, Fun...
48cd6b4bb72cc15c21a1d1331fb17e2cc22701d8f1694128707af7da15972cf8
Python
3,443
102
"""Collection of functions to use MCMC methods on MEG data with forward network model -- uses cost (to find likelihood) and prior functions""" import numpy as np import math from ..inverse import cost from ..inverse import priors from ..forward import runforward as rf from ..inverse.cost import pearson_cost # TO DO: ...
9b46b478080db81f5397fb59661e9e59734c34176ab5e26e56ff9ff83b58ada8
Python
3,443
60
"""General-purpose test script for image-to-image translation. Once you have trained your model with train.py, you can use this script to test the model. It will load a saved model from '--checkpoints_dir' and save the results to '--results_dir'. It first creates model and dataset given the option. It will hard-code ...
be583593f7cf877675d8f887b70f7fb8741a6897f240626db7aab88b373b6d12
Python
3,445
96
import numpy as np def _rotation_matrix(axis, angle): """ This method produces a rotation matrix given an axis and an angle. """ axis = axis/np.linalg.norm(axis) axis_squared = axis**2 cos_angle = np.cos(angle) sin_angle = np.sin(angle) rot_matrix_row_one = np.array([cos_angle+axis_squa...
5d1f4db2f1f08f55500ad47ba124294088ebdb6117b36d5f9654604c3942abd4
Python
3,446
95
import math import torch import torch.nn as nn class GaussianSmearing(nn.Module): def __init__(self, start=0.0, stop=5.0, num_gaussians=50): super().__init__() offset = torch.linspace(start, stop, num_gaussians) delta = offset[1] - offset[0] self.coeff = -0.5 / delta.item()**2 ...
80a24a00d62f384e80a00429e651704464efe6e055475975e50b1cfe49a9a439
Python
3,446
88
"""Iterate-N accumulation, the PURE aggregation of per-pass findings. DeepMapper runs the ``arrange -> train -> attribute`` loop N times and accumulates per-feature findings into robust, stability-scored attributions. These functions turn a list of per-pass results into the final ranking + stability statistics. No tor...
996789425576b2479461dff9e48049d09a039c07484cd2595bed4b784d84e4d3
Python
3,446
107
import torch from torch_geometric.data import InMemoryDataset, Data from torch_cluster import radius_graph class PreprocessAcAc(InMemoryDataset): def __init__( self, pyg_dataset, cutoff, transform=None, pre_transform=None, pre_filter=None ): self.dataset = pyg_dataset self.cutoff = cut...
bdf36ab6e3c249d687c9abb391c9f5f9ef48c858728d8d6235b8633c814fd081
Python
3,446
88
import numpy as np from voxcell import VoxelData from os import cpu_count import sys from tqdm import tqdm import scipy.ndimage as nd import flatmap_util as fmutil flatmap_nrrd = sys.argv[1] pixel_res = int(sys.argv[2]) output_nrrd = sys.argv[3] ncpu = cpu_count() // 2 if len(sys.argv) > 4: ncpu = int(sys.argv...
8296f3a1a30936088da2d166deaef9ab128a97406b22e440c381cd3bde3370ff
Python
3,447
107
import torch from torch_geometric.data import InMemoryDataset, Data from torch_cluster import radius_graph class Preprocess3BPA(InMemoryDataset): def __init__( self, pyg_dataset, cutoff, transform=None, pre_transform=None, pre_filter=None ): self.dataset = pyg_dataset self.cutoff = cut...
eb022b74a1575b9325d6815cab057a7d06c7a6c4a553d68857e3cb05ee724a53
Python
3,447
114
#!/usr/bin/env python3 """ Create a binary inclusive mask, including certain labels (brain areas), using a particular threshold (for the probabilistic atlas) Usage ---- create_mask.py -i <probabilistic atlas image> -o <output mask image> -t <threshold> [label numbers] create_mask.py -h Authors ---- Wolfgang M. Pauli,...
d4dc97c721eac2a768301707804971de279741595d7e30fa97474348e499680f
Python
3,448
79
import numpy as np import os import nevergrad as ng import matplotlib.pyplot as plt from scipy.signal import find_peaks from astropy.convolution import convolve, Gaussian1DKernel, Box1DKernel from Analysis.dataloader import dataloader_AP experimentalist = 'Elodie' neuron = 'MSN_In_Vitro' path = '/users/gvignoud/Docu...
5283c6a6b0b15aface47a937cb54b32dfd54c932d6529fec0397a670bb118177
Python
3,450
99
from collections.abc import Hashable import numpy as np from pgmpy.structure_score._base import BaseStructureScore class LogLikelihoodGauss(BaseStructureScore): r""" Log-likelihood structure score for Gaussian Bayesian networks. This score evaluates a continuous Bayesian network structure by fitting a ...
93a7d59b050424b1c53f745dc93406c4665ad5d9fdabcdf29af580c94f9a7fa6
Python
3,451
95
''' Author: Alexandra Fischbach Github repo: https://github.com/AlexFischbach/local_csf_pipeline/tree/main Date: 04-18-2025 Contact: fischbach.a@northeastern.edu ''' def compute_timeseries( func_mask_path, threshold_roi_path, mod_conf_path, roi, confound_vars="Default", save_path=None, verb...
98ddcd9a00bc9c5fb54b9c899916da17dc7de85a648188c2b45a953b769caf1e
Python
3,451
88
import numpy as np import torch from src.logic import test_logic from src.PID import PID_utils, k_order, runner def compute_source_avg(pair_dict, idx, s_key): # computes average 2-order synergy for a particular source avg = 0 for i in range(len(idx)): string = s_key + '_syn' for j in range...
9871d138525b5aaf3f00beb5f32ed85cd911e191a050b3b2f0981810185b606b
Python
3,452
100
# FCN model # when tuning start with learning rate->mini_batch_size -> # momentum-> #hidden_units -> # learning_rate_decay -> #layers import tensorflow.keras as keras import tensorflow as tf import numpy as np import time from utils.utils import save_logs from utils.utils import calculate_metrics class Classifier_...
343d72a8b21e7b9e7ceaf2d0a3bc9b9aea3fc36395f4fe18a5a17c494e2208bc
Python
3,453
107
import torch class AlphaFoldLRScheduler(torch.optim.lr_scheduler._LRScheduler): """ Implements the learning rate schedule defined in the AlphaFold 2 supplement. A linear warmup is followed by a plateau at the maximum learning rate and then exponential decay. Note that the initial...
1998df8488161d53a54c22f31a50977f823870f6a700ba90c895d3c737916f3d
Python
3,454
149
import numpy as np from sklearn.model_selection import KFold # from keras.optimizers import Adam # Classifier parameters selected with GridSearchCV (cv=5) # Random Forest parameters rf_params = { 'n_jobs': 1,#-1, 'n_estimators': 100, 'max_features' : 'auto', 'max_depth': 15, 'min_sampl...
1ea90743ea540cdaa38029bf2d459c32b5526a595992734a125c83bd05bd972e
Python
3,455
101
''' Toy example using BB-RBMs on Bars and Stripes. :Version: 1.0 :Date: 29.08.2016 :Author: Jan Melchior :Contact: JanMelchior@gmx.de :License: Copyright (C) 2016 Jan Melchior This program is free software: you can redistribute it and/or modify ...
85d624dcbadd79ca1ae75db423ce02a8ce8627ec6377b0c81c8d9dcba86c0b2b
Python
3,456
95
"""Input preparation shared by the notebook forms and headless E2E runs.""" from __future__ import annotations import copy import hashlib import json import re from colabfold.rgi import require_supported_model def chain_table(fold_input): rows = [] for entity in fold_input["sequences"]: kind, molec...
d70eab168dca11090cb31770a40f1f1a61dc85eda3d80966458665201d50bd05
Python
3,456
103
''' Example using a small BB-RBMs on the MNIST handwritten digit database. :Version: 1.0 :Date: 29.08.2016 :Author: Jan Melchior :Contact: JanMelchior@gmx.de :License: Copyright (C) 2016 Jan Melchior This program is free software: you can redist...
e1ed58a8cf9026dffb04b1dcc882e65a95b41926f53a4685e0259ce7576dccab
Python
3,458
91
import matplotlib.pyplot as plt import numpy as np from dliplib.utils.helper import set_use_latex plt.style.use('seaborn-whitegrid') set_use_latex() sizes = [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.10, 0.25, 0.50, 1.00] ticks = range(len(sizes)) # performance on the different data sizes learnedpd = {'PSNR [db]': ...
eacb920fddee1ae19a29c7eb67055c884618f3c2c135267af153db6f3e0c4791
Python
3,460
83
""" module to export plotted points for Nature's sourcedata requirements. """ import os import sys import numpy as np import pandas as pd def genotype_from_suptitle(figure_params): string = figure_params["suptitle"] if "MDN" in string: return "MDN" elif "DNp09" in string: return "DNp09" ...
fd0f1d7d31352c73655e06e46110d45c44231e5f6a2f7b06f84713d24c8f24b6
Python
3,463
95
from ccg.astar import AStarSearch import ccg import torch import os import warnings class Parser: def __init__(self, model_file : str, words_per_batch : int = 25*100, do_tokenization : bool = False, max_steps : int = 1_000_000, ...
956b1859e61bf5372c87c779b1c88b11038af4eb8339ac33dbf93719e7e78e60
Python
3,464
69
"""Compact, content-checked receipts for completed native-space results.""" import json from pathlib import Path from utils.files import sha256_file from utils.preflight import digest def result_receipt(args): root = args.output_root.resolve() / args.subject required = [root / 'logs' / name for name in ('ra...
d30a05f7966d1e0e2a0b6ecd32b86d87851d3f1b21f8150bee82bbcc3287fc58
Python
3,465
116
from __future__ import annotations from typing import Any from langchain_core.output_parsers import BaseOutputParser from langchain_core.output_parsers.json import parse_and_check_json_markdown from pydantic import BaseModel from typing_extensions import override from langchain_classic.output_parsers.format_instruct...
12c06fa2c26c7a9dab704fa672db6aafee7f94ed5558d65631a18bbb94aed0e7
Python
3,466
108
import torch from torch_geometric.data import InMemoryDataset, Data from torch_cluster import radius_graph class rMD17Preprocess(InMemoryDataset): def __init__( self, pyg_dataset, cutoff, transform=None, pre_transform=None, pre_filter=None ): self.dataset = pyg_dataset self.cutoff = cu...
9efc987be58a7512a5ec060dd7f9f4d289e42fc3441fa34c365eddba8e237d7e
Python
3,469
76
import os import socket import sys from configs.configs import get_config_dict from helpers.hcp import get_human_connectome_project_subjects from helpers.slurm import save_slurm_job_to_file, send_slurm_job_to_queue if __name__ == "__main__": hostname = socket.gethostname() assert hostname == 'hivemind' ...
bf31e6c5185e9b685617a145555a4ad7d7d5b60c5c214767b169c4964a4922a3
Python
3,469
117
"""Fake Embedding class for testing purposes.""" import math from langchain_core.embeddings import Embeddings from typing_extensions import override fake_texts = ["foo", "bar", "baz"] class FakeEmbeddings(Embeddings): """Fake embeddings functionality for testing.""" @override def embed_documents(self,...
648a05156b70e2e9dd24f4ade8d7f58939168c1a7ff98e2ba2f47747c9483918
Python
3,470
87
# -*- coding: utf-8 -*- import sys import numpy as np import os, gc import csv, glob import os.path as path import torch, pickle from scipy.spatial import distance import networkx as nx import Bio.PDB from matplotlib import pylab import pandas as pd import scipy.sparse as sp from collections import defaultdict from s...
aa7cd5aec8987961a1bfe1660daad0e5378a58afeab6240c5fc5e45a5f372311
Python
3,470
117
from bindsnet.encoding import encodings class Encoder: # language=rst """ Base class for spike encodings transforms. Calls ``self.enc`` from the subclass and passes whatever arguments were provided. ``self.enc`` must be callable with ``torch.Tensor``, ``*args``, ``**kwargs`` """ def __in...
c5c5e5fdde1c5142f8a732d9178022164ddd061bf1dbc22614ca39cd8133aa14
Python
3,470
102
import logging import os import socket import sys import matplotlib.pyplot as plt import pandas as pd import ptitprince as pt import seaborn as sns from configs.configs import get_config_dict from helpers.figures import set_size def plot_kernel_lengthscales( config_dict: dict, model_name: str, kernel_le...
fea700fbcc4e76530d18f8040243cf2eb1a60091f4aa792804aa2ac2ee8a8237
Python
3,470
97
""" Import Progenesis Output Progenesis QI for proteomics allows user to export proteomic quantitative data as .csv. @author: Reis-de-Oliveira G <guioliveirareis@gmail.com> """ import numpy as np import pandas as pd class Input: def __init__(self, Table, **kwargs): """ Progenesis output for OmicSco...
74497ca068cda1f7dbb997cb5d6657f93a8397ab7a77a1114ced671bdec7136b
Python
3,471
98
# 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...
87a2c63c3db2586609d7c9d137d0a3cab7a3993e0fa3fc53b5cdbce12b4e015d
Python
3,471
93
import pylab import spiketools from bisect import bisect_right,bisect_left import defaultSimulate as default def compute_cluster_rates(spiketimes,N_E,Q,kernel_sigma=50,kernel_type = 'tri',tlim = None): """ compute the avarage firing rate of the Q excitatory clusters in spiketimes. """ cluster_rates = [] cl...
d10c5b1d0a1cb6f11c9300e06589266ebed959fdd1b2beb7d87d3d96f58700ff
Python
3,472
101
import sys sys.path.append("/home/melchj57/workspacePy/PyDeep/") import os os.nice(19) import numpy as numx import pydeep.base.numpyextension as npExt import DBM3LayerBinary.model as MODEL import DBM3LayerBinary.trainer as TRAINER import pydeep.rbm.model as RBM_MODEL import pydeep.rbm.trainer as RBM_TRAINER import D...
4eccebde43a14665df7fb59e3759ebc2c3255cc63a10a96fda61c86358a3d709
Python
3,473
99
# Collect layer activations to ImageNet images # Copyright (c) 2021 Laurent Caplette import torch from torchvision import transforms from torch import nn import os, h5py, glob from robustness.datasets import ImageNet from robustness.model_utils import make_and_restore_model import numpy as np imagenet_mean = torch.te...
e4d2c940255dd4f2e1ca729b8b02cae9f24562c7a37e87f93a4af27c770f4177
Python
3,476
85
%matplotlib qt import mne from config_FaceName import Results_data_path,Ids,MEG_data_path,group_name,MRI_data_path,stats_conds_list,stats_comparisions,study_path from custom_functions import do_cluster_permutation_1samp_test,prepare_X_and_one_data import os.path as op from config_FaceName import Results_data_path,stats...
f43fc689b1a2066daad92dfdcbd3c06c66fb27910dc3f50ba3d4a4541ffd353c
Python
3,476
116
import equinox as eqx import jax import jax.numpy as jnp import jax.nn as jnn import jax.lax as lax import diffrax from CEL.utils.register import register import jax.random as jr from typing import Literal from .meta_model import ModelClass class ODEFunc(eqx.Module): mlp: eqx.nn.MLP input_channels: int h...
2d91b7149579fc1f40262adee702238e3af06a7fd17c7ccd822fd4121b2c567d
Python
3,478
66
# 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...
610d7bde3978994525ba739bd54c30a950d046f2770cd73b2a2acd68223348b2
Python
3,479
95
import configparser import os import numpy as np import json def read_predict_config(predict_config): config = configparser.ConfigParser() config.read(predict_config) cfg_dict = {} cfg_dict["batch_size"] = config.getint("Predict", "batch_size") cfg_dict["train_dir"] = config.get("Predict", "train...
9b6ec0131de826107f3793849a7873ff4a6689f68e90d6b4dfafd08c3c7434d0
Python
3,479
127
"""Callables annotated with names that are only imported for type checking. Deliberately omits `from __future__ import annotations`, so on Python 3.14+ these annotations are evaluated lazily and raise `NameError` when evaluated. Importing this module requires Python 3.14+. """ # ruff: noqa: TC004 from typing import ...
fd94575e10a58d1bf4d3f91a0883748f2cbf6d051c196be12ec9183088e481b0
Python
3,479
91
# 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. from __future__ import absolute_import, division, print_function import os import argparse import json import numpy as np import pandas as pd import joblib from .d...
b23d891ef310c0ed249071d3c457572a5365ae2dfc1476022f0806bc3d612e8c
Python
3,480
114
import os from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json import re import numpy as np from tqdm import tqdm from cloudfiles import CloudFiles from cloudvolume.lib import Vec, Bbox, mkdir, save_images, yellow from cloudvolume.paths import ExtractedPath DEFAULT_PORT = 8080 RANGE_RE...
c17926b59b778e591a8debcd3c435e3dd42165215caf79051028ea28670013e7
Python
3,482
101
import numpy as np class YOLO_Kmeans: def __init__(self, cluster_number, filename): self.cluster_number = cluster_number self.filename = "2012_train.txt" def iou(self, boxes, clusters): # 1 box -> k clusters n = boxes.shape[0] k = self.cluster_number box_area = boxe...
583754f399f99f630ac18a0f811b4c86c8e9ed58d9f0df4c90d5dea730ccd0cc
Python
3,483
150
import numpy as np from sklearn.model_selection import KFold # from keras.optimizers import Adam # Classifier parameters selected with GridSearchCV (cv=5) # Random Forest parameters rf_params = { 'n_jobs': 1,#-1, 'n_estimators': 100, 'max_features' : 'auto', 'max_depth': 15, 'min_sampl...
9936bfec66fd987eaa66880a3df6a72ca9483ae8b4f5667836779a53c98be9cb
Python
3,484
106
"""Test few shot prompt template.""" import re import pytest from langchain_core.prompts.few_shot_with_templates import FewShotPromptWithTemplates from langchain_core.prompts.prompt import PromptTemplate EXAMPLE_PROMPT = PromptTemplate( input_variables=["question", "answer"], template="{question}: {answer}" ) ...
52d71727eacb3672c1ca7bfb3643b285207947f209a3191a8767e48e9c71c6ad
Python
3,485
58
# Python implementation of the GP based filter, USING THE DIAGONAL approximation for the covariances. # This represents the benchmark (for the DIAGONAL models) - many flavours can be added and potentially improving the results. But this is the implementation that respects the model and offers a benchmark. # It is the ...
cb5e21da6172231d869ebf83848aafbde99b056b86ec76c2ed7352faf4c43b54
Python
3,485
52
from optimization.ADMM import * from EPI_MRI.EPIMRIDistortionCorrection import * import argparse import warnings def main(): parser = argparse.ArgumentParser(description="PyHySCO: EPI-MRI Distortion Correction.") parser.add_argument("file_1", type=str, help="Path to the input 1 data file (NIfTI format .nii.gz)...
b9ecc669ef8288c4dcffdfd6b934d115eb0e8a55988fb555fb19507f8327dc9e
Python
3,486
76
# srun --nodes=1 --ntasks=1 --cpus-per-task=8 --gpus=1 --mem=100g --time=06:00:00 --pty bash -i # Sconda conda activate ghmc1; cd /mnt/BioAdHoc/Groups/RaoLab/Edahi/Projects/09.TimeCourse5hmC/ForFerhatGit/GhmCN/reviewer_questions/distribution_of_genes_and_distances_activ72B; python import pandas as pd import numpy as np...
1b818be959032ab56ee5ac8f79c77c71a2ea5f345ca9c5c0d3edc40fe93dd88a
Python
3,487
109
# Training procedure for CIFAR-100 using ResNet 110 (SD) import numpy as np import collections import pickle from resnet_sd import resnet_sd_model from sklearn.model_selection import train_test_split from keras.models import Model from keras.callbacks import ModelCheckpoint from keras.optimizers import SGD from keras...
83930fac3f2c24af23799442202bd6469f9db40ab58eacbe7c5fb04b97a0af94
Python
3,487
101
"""`OutputParser` classes parse the output of an LLM call into structured data. !!! tip "Structured output" Output parsers emerged as an early solution to the challenge of obtaining structured output from LLMs. Today, most LLMs support [structured output](https://docs.langchain.com/oss/python/langchain/m...
343227d59f2a1853ad21f25df0caeb8f547ee1b52508b3eaa9f7dbaef63bc680
Python
3,489
73
# 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...
479a2ca24d8c93dfd8bbe3fd0e5626d60d1f4e9c344d119541e4ef13c50a377f
Python
3,489
104
import logging import os import socket import matplotlib import matplotlib.pyplot as plt import numpy as np import seaborn as sns from configs.configs import get_config_dict from helpers.synthetic_covariance_structures import get_covariance_time_series def _plot_synthetic_covariance_structures( config_dict: dic...
0ced285da8712a6e3e3a82a8418137a0e8bbcf92cddbbd9070448cd15eca432e
Python
3,490
102
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # 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...
512b6029888cb3d209c3e65c47b41175fb40f59fdee4623a72b257157ae95222
Python
3,492
109
# coding=utf-8 """ Defines the MultiDataset Class""" from torch.utils.data import Dataset import logging logger = logging.getLogger(__name__) class MultiDataset(Dataset): """ Define a dataset for multi input networks. Takes in a list of datasets, and whether or not their input_data and target data s...
38f94b06a97a8b0b43d2597f3a4202facfc03d98fa70bc236efd0fe5c9bcdbfc
Python
3,493
98
import json import csv import os, sys import matlab.engine import collections import csv import pandas as pd import numpy as np from scipy.interpolate import interp1d from dataloader import B_IQ_Data from utils import iqa_tensor, p_val, SSIM from torch.utils.data import DataLoader from tabulate import tabulate class...
94265a18619b1a80c8dadcbbe3edb8f79bcd658d93fd5a526e0c9b1d8c4c03a9
Python
3,493
121
# -*- coding: utf-8 -*- """ Created on Wed Feb 3 23:07:34 2021 @author: Bruno Caneco Code stolen from package in https://github.com/jobevers/diagonal-crop. Package was converted into a single module to simplify integration with sscd's code structure TODO """ from __future__ import division import collections im...
b06d51007d9f1321d902733a8ecfbdc0a83f4017b2ea3ad31bee7bc8d9fc401a
Python
3,494
111
import signal import sys import pytest from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain_classic.agents.mrkl.output_parser import ( MISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE, MISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE, ...
06dca37f72fe7111dd8dd4f28df34b930be30dc2ad4b896480bd935dd04eda0b
Python
3,495
129
from EPI_MRI.LinearOperators import * class QuadRegularizer: """ Defines the structure of an quadratic regularization term of the form S(x) = 1/2 ||x||_H^2 where H is positive semi-definite. Attributes ---------- H :`LinearOperators.LinearOperator` The linear operator used in the regu...
f34afdcab51747e6e23d0595d81ae2b7fc98e43720e6733c5fc094da8ae665de
Python
3,496
99
import argparse import pickle import jcamp import numpy as np import pubchempy as pcp import re import requests from bs4 import BeautifulSoup from rdkit import Chem nist_id_rexp = re.compile(r'[0-9]+\-[0-9]+\-[0-9]+') def process_nist_id(response, results, site_list, site_addr, inchikey): soup = BeautifulSoup(res...
414601597e0176644028d0b38a0dfd35b9c055ecbff553e4ae14a4cfbcb38661
Python
3,497
85
"""Contains tests for the Conv2D-layer LRP implementations""" import numpy as np from tensorflow.keras import Model from tensorflow.keras.layers import Conv3D, Flatten, Input from explainability import LayerwiseRelevancePropagator from explainability.layers import Conv3DLRP def test_conv3d_lrp(): input = Input(...
87c243440ea1caf17ccee2d5e236e9a9ecac304b2602f2963bbf94e96872aaa1
Python
3,500
90
import logging import os import socket import sys import numpy as np import pandas as pd from configs.configs import get_config_dict from helpers.hcp import get_human_connectome_project_subjects, load_human_connectome_project_data from helpers.evaluation import leave_every_other_out_split, get_test_log_likelihood, ge...
9dfe6976ce24e3faf9e6651c85cab208e154d4558a09d74c092a4aa50b3774af
Python
3,500
103
targetMean = 140 targetStd = 5 initStep = 0 import pandas as pd resultsMean = [] resultsStd = [] for i in range(40): base_name = 'R:/Temp/Threads10/Thread'+str(i)+'/Simulation/output/Data.csv' df = pd.read_csv(base_name) if df.iloc[0,0]>1000: resultsMean.append(0) else: resultsMean.app...
a5fe154858cd7cc478f8c1eb723ec9aff34559979a74ee9d70d62b522f568a56
Python
3,500
133
""" Django settings for analyze_electrophysiology_data project. Generated by 'django-admin startproject' using Django 3.1.3. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/sett...
f40daa3ae5c963961a2931851164bbb7717cf191b60a07979afc174515150915
Python
3,504
69
import rdkit.Chem as Chem import numpy as np from tqdm import tqdm ''' This script prepares the data used in Wengong Jin's NIPS paper on predicting reaction outcomes for the modified forward prediction script. Rather than just training to predict which bonds change, we make a direct prediction on HOW those bonds chang...
3e936133d7a6953c2beb423968f0336478f01c5c983f891b24b58fc983c3ec9b
Python
3,506
88
import numpy as np import gym from stable_baselines3 import PPO import torch from stable_baselines3 import A2C, PPO from Policies.bus_13.CustomPolicies import ActorCriticGCAPSPolicy from stable_baselines3.common.torch_layers import BaseFeaturesExtractor from typing import Any, Callable, Dict, List, Optional, Tup...
6dc2950405b595cb0966a3e57ba1e5e2b38f24c7125b85b844e9e2ae46bda80f
Python
3,506
111
# Training procedure for CIFAR-10 using ResNet 110 (SD) import numpy as np import collections import pickle from resnet_sd import resnet_sd_model from sklearn.model_selection import train_test_split from keras.models import Model from keras.callbacks import ModelCheckpoint from keras.optimizers import SGD from keras....
88bf659b996504d4633be38712b7dcefcce7ba04cef1252bbf4d0cd9df52f171
Python
3,507
115
import numpy as np from os import listdir from os.path import isfile, join from PIL import Image from sklearn.model_selection import train_test_split # Paths to files, change the path if needed LABELS_PATH = '../../data/data_imagenet/labels.txt' DATA_PATH = '../../data/data_imagenet/val/' IMG_MEAN = [103.939, 116.779,...
bc584d4e1d28b5586204dfbdbfc51d5878e2aea2274aaf063d243e92d9bae96e
Python
3,507
75
"""Dataset class template This module provides a template for users to implement custom datasets. You can specify '--dataset_mode template' to use this dataset. The class name should be consistent with both the filename and its dataset_mode option. The filename should be <dataset_mode>_dataset.py The class name should...
ac161359c413fa5de0912848f8ce029385194ce91439fcff22bd38694b0b1c1f
Python
3,508
110
from utils_stat import ( get_roc_info, get_pr_info, calc_neurologist_statistics, read_raw_score, ) import matplotlib.pyplot as plt from utils_plot import plot_curve, plot_legend, plot_neorologist from time import time import numpy as np def confusion_matrix(labels, scores): matrix = [[0, 0], [0, 0...
0c2d2fb107293d85bb0690d64e6336ac6ebdc2777b88600a178d015e43155408
Python
3,510
93
import torch from torch.utils.data import Dataset import os from itertools import islice from math import inf import logging class ProcessedDataset(Dataset): """ Data structure for a pre-processed cormorant dataset. Extends PyTorch Dataset. Parameters ---------- data : dict Dictionary o...
56bb0124e6a5354a266a3fa270b72129ce97ec587ec39820fe636d6e1de6a985
Python
3,510
121
""" ZephOD feature detection. Usage: zephod -h | --help zephod -v | --version zephod --dataset=<dataset> --model=<model> [options] Options: -h --help show this message and exit. -v --version show version information and exit. --dataset=<dataset>...
818e5d2e142c7fc54256b3f52563a0e11e00e90fb16e6d366abf885d9fb5c37d
Python
3,513
81
# HED batch processing script; modified from https://github.com/s9xie/hed/blob/master/examples/hed/HED-tutorial.ipynb # Step 1: download the hed repo: https://github.com/s9xie/hed # Step 2: download the models and protoxt, and put them under {caffe_root}/examples/hed/ # Step 3: put this script under {caffe_root}/exampl...
dccc10f553390030daa26065054e4a22dd3f69357ec134b164fa3fda297e88e3
Python
3,514
84
from typing import TYPE_CHECKING, Any from langchain_classic._api import create_importer if TYPE_CHECKING: from langchain_community.chat_message_histories import ( AstraDBChatMessageHistory, CassandraChatMessageHistory, ChatMessageHistory, CosmosDBChatMessageHistory, Dynamo...
6fe0cd7b3909f7fb602e86c464d2f8c047bf293bf2957f8a98b44ebb26cc9dd8
Python
3,515
96
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os from torchvision import datasets, transforms from timm.data.constants import \ IMAGENET_DEFAULT_MEAN, IMA...
d9a3fb97e95fc6cacecfce05bb404ae1830afd975b83a6e07f44c5b3890a2b63
Python
3,515
82
import mne from config_FaceName import Results_data_path,Ids,MEG_data_path,group_name,stats_conds_list,stats_comparisions from custom_functions import do_cluster_permutation_1samp_test from functools import partial import os.path as op import mne from config_FaceName import Results_data_path,MRI_data_path,stats_compari...
193bda05a6dbed06f05b7b196efe034c2cafbe4d8a87088c18a616a9d747e7b2
Python
3,516
95
""" End to end test to check the basic usage """ import os import shutil import subprocess from pathlib import Path import pytest REPO_ROOT = Path(__file__).parent.parent.parent.resolve() DATA_DIR = REPO_ROOT / "tests" / "fixtures" @pytest.mark.parametrize("model_id,extra_args,result_cols", ( ( "AF-A0A1...
5d39776f9bdd38789dbc9a08508f339f8e4b95774d63dca24550dd7133d98307
Python
3,516
98
"""Configuration for unit tests.""" from collections.abc import Sequence from importlib import util import pytest def pytest_addoption(parser: pytest.Parser) -> None: """Add custom command line options to pytest.""" parser.addoption( "--only-extended", action="store_true", help="Only...
dc108e0d9637f0fc5bd1d3b74298955f1ad21ac771e36b3792ad6f01f80eb487
Python
3,516
108
""" Configuration file for pytest. """ import logging import pytest logger = logging.getLogger(__name__) # Ensure QCPortal is imported before any OpenEye modules, see # https://github.com/conda-forge/qcfractal-feedstock/issues/43 try: import qcportal # noqa except ImportError: pass def untar_full_alketho...
992039ce6aaafbabe48851554b5706fc0f3f9eaf59e32d203f86ebf61aecd5a0
Python
3,519
102
import gzip import sys from collections import defaultdict from Bio.Seq import Seq def main(): if len(sys.argv) < 7: print("Usage: python createMAFFeatures.py <alignment file> <species names file> <output file> <chromosome> <reference species> <reference species chromosome length file>") exit(1) ...
e31ce6d0aa239b015730a8389a0d7990c7776ff93664af5e91667dde67458741
Python
3,519
100
""" Monopolar triangulation of putative units Code snippet from https://github.com/SpikeInterface/spikeinterface/blob/master/spikeinterface/toolkit/postprocessing/unit_localization.py Implementing method proposed in https://www.biorxiv.org/content/10.1101/2021.11.05.467503v1 Modified 20220321 by jz103 """ import nu...
37d0addf27e76dc7b6b57299b160034c83b658ea94ef3e5b5af5ed1cf2d125e1
Python
3,522
109
import tempfile import typing as tp from pathlib import Path from typing import Tuple import pydicom import pytest from hypothesis import strategies as st from hypothesis.strategies import SearchStrategy from MRdataset.dicom import DicomDataset from MRdataset.tests.simulate import make_compliant_test_dataset, \ m...
701d0fc40fc72b73bbc53ea259d1a0389b0f9cada2ca8b93f79af9b91eb5c8c5
Python
3,523
101
""" openff-toolkit A modern, extensible library for molecular mechanics force field science from the Open Force Field Consortium. """ import importlib from importlib.metadata import version from typing import TYPE_CHECKING if TYPE_CHECKING: # These types are imported lazily at runtime, but we need to tell type ...