sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
647f7ea1d2bb690ad940296d4d6ff3b3655508ca713c59e311208324cb879ee0 | Python | 1,447 | 43 | import os
import glob
from torch.utils.data import DataLoader
from pytorch_lightning import LightningDataModule
from genie.data.dataset import SCOPeDataset
from genie.utils.data_io import load_filepaths
class SCOPeDataModule(LightningDataModule):
def __init__(self, name, log_dir, data_dir, max_n_res, min_n_res, da... |
e8494c5648d190b5abf5e4ccc71349bec6b1ceae6e7d8defdaee86fe6a3d4f7e | Python | 1,447 | 48 | """Interface for tools."""
from langchain_core.callbacks import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain_core.tools import BaseTool, tool
from typing_extensions import override
class InvalidTool(BaseTool):
"""Tool that is run when invalid tool name is encountered by a... |
8e21cf487e526029e3d54ef798aec3c2f1be40c03e44e2a2c6649e7a928c8037 | Python | 1,448 | 47 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
class MEnet(torch.nn.Module):
def __init__(self, input_dim, hidden_dim, dropout_rate, n_layers, activation, output_size):
super().__init__()
self.input_dim = input_dim
self.h... |
b6bcb4e8e5bbf2a4facbd0242b34d3c4808ab20e451d7821a89e2c0520d622b6 | Python | 1,449 | 57 | """
Methods to read and process features from coordinates.
"""
from .mda_distances import \
read_atom_group_distances, \
read_atom_self_distances, \
read_calpha_distances, \
read_gpcr_calpha_distances, \
select_gpcr_residues
from .mda_torsions import \
read_torsions, \
read_protein_backbo... |
d787196ae2b28b008d0512d2b30400f7be52fceb352a3ace228bce67af9cf3a1 | Python | 1,449 | 32 | import sklearn.impute
import pandas as pd
import numpy as np
from copy import copy
def value_imputation(self, expression):
data = copy(expression)
if self.logTransform is True:
data = np.log2(data)
data = data.replace([0, np.inf, -np.inf], np.nan)
# remove proteins presenting only... |
e9dff8f0df103a5eb92f2889ad97cc79815854a7bbf77d5e1f136de808b8f750 | Python | 1,449 | 57 | import torch
from torch import nn
def constrain_all(self):
if hasattr(self, "constrain"):
self.constrain()
for c in self.children():
c.constrain_all()
# extend torch nn.Module to have constrain_all function
nn.Module.constrain_all = constrain_all
# all constrain function takes an optional... |
cedffb5a9d131f6b9e25c5d2e090eb964de0fe01200d8a19d47f27e769b59a3e | Python | 1,450 | 40 | # Copyright 2023 DeepMind Technologies Limited. All Rights Reserved.
#
# 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... |
6f486a9d68c1345164e2d3ba50170fbd9d34775b3afac60cb917834e6ea9b0db | Python | 1,451 | 41 | import torch
from torch.nn import Sequential, Conv3d, BatchNorm3d, ReLU, MaxPool3d, AdaptiveAvgPool3d, Linear, Module
class CNN3D(Module):
def __init__(self, labels_number, channels_nb):
super(CNN3D, self).__init__()
self.conv1 = Conv3d(channels_nb, 64, kernel_size=7, stride=2, padding=3, bias=Fa... |
fea8222399efffebcb0679463efd0f646f1f595e85096dd3217b05694e47cfb7 | Python | 1,452 | 45 | """Memory modules for conversation prompts."""
from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
from langchain_classic.memory.buffer import (
ConversationBufferMemory,
ConversationStringBufferMemory,
)
from langchain_classic.memory.buffer_window import ConversationBuffe... |
4f57dcb53d186ee713c50dd4eb61c8a7fd57a4ad5c44f34dfcd12e37e4303bde | Python | 1,453 | 39 | import os.path
from skimage.io import imread, imsave
import matplotlib.pyplot as plt
import numpy as np
def calcul_masks_1et2(folder):
masks_folder = os.path.join(folder, "Masks")
pred_folder = os.path.join(folder, "Predictions_noyaux_morts")
masks1_folder = os.path.join(folder, 'Masks1')
masks2_fo... |
19ef711fbac6d9e6009a69cde345fe8f4ef7d0629df64f3e0901183e45a9c8ff | Python | 1,454 | 40 | import os
import pandas as pd
def save_segmentation_params( save_folder,
filename,
chosen_mask,
down_shape,
thinning,
smoothing ):
# Make it work for Python 2+3 and with Unic... |
56e3ae1eea49dfed985c42ad72a9c03482c8c82557cc9ef2e163c0c2f7606e8c | Python | 1,454 | 44 | import io
import os
import re
from setuptools import setup, find_packages
scriptFolder = os.path.dirname(os.path.realpath(__file__))
os.chdir(scriptFolder)
# Find version info from module (without importing the module):
with open("src/argnet/__init__.py", "r") as fileObj:
version = re.search(
r'^__version... |
70ce87b26c2362011fab4abba2d03ae037e9f0a74ee2d31f40f4d55a32cd821f | Python | 1,455 | 51 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 4 17:34:54 2020
@author: shni2598
"""
import numpy as np
import matlab.engine
def fitStable(data, eng=None):
'''
fit parameters of stable distribution from input data using Matlab Engine for python;
input:
data: 1-D numpy array
... |
014997ca16388588d5933e16813fd59770bddaecda30983b24ffc631847d2ae3 | Python | 1,456 | 39 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for detai... |
21573a63f8edfc8a3ab31d77ad730649e1c806656c45536ea4236dec72c9153c | Python | 1,456 | 31 | #TO BE UPDATED
from NeuronModel.NeuronClass import neuronClass
import numpy as np
class exp_integrate_and_fire(neuronClass) :
parameters = {'save': True, 'spike': True, 'tau': 10., 'R': 10., 'u_rest': -65., 'v_rh': -50.,'u_r': -70., 'Delta_T' : 1. , 'Delta_abs': 3., 'theta_reset' : 20.}
def __init__(self,**kw... |
7c88b32021d6559834828933cc89591971b43e737da95e2adb298ba007369ce6 | Python | 1,459 | 47 | from collections.abc import AsyncIterator
import pytest
from langchain_core.utils.aiter import abatch_iterate
@pytest.mark.parametrize(
("input_size", "input_iterable", "expected_output"),
[
(2, [1, 2, 3, 4, 5], [[1, 2], [3, 4], [5]]),
(3, [10, 20, 30, 40, 50], [[10, 20, 30], [40, 50]]),
... |
b3e9761529c46bfb452ff9ecc89ca45ef9b32748e66f6832953a0ae386169c30 | Python | 1,460 | 38 | import torch
import torch.nn as nn
class Contrast(nn.Module):
def __init__(self, hidden_dim, tau, lam):
super(Contrast, self).__init__()
self.proj = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim),
nn.ELU(),
nn.Linear(hidden_dim, hidden_dim)
)
s... |
2f55089d25b00f6b30a54ebd980c2a5968a4cd5d23b3a9f3746b1b2b1efc9eca | Python | 1,462 | 54 | #!/usr/bin/env python
# -*- coding: latin-1 -*-
from .py3k import PY3K, basestring, unicode
# fpdf php helpers:
def substr(s, start, length=-1):
if length < 0:
length=len(s)-start
return s[start:start+length]
def sprintf(fmt, *args): return fmt % args
def print_r(array):
if not isi... |
70959fad6a484aad4f0cfe6aefa6dfa860e2dcbfeac261388d27a031fd1fc927 | Python | 1,462 | 44 | import sys
sys.path.append("..")
import numpy as np
from multiprocessing import Pool
from rdkit import Chem
from scipy import sparse as sp
import argparse
from src.data.descriptors.rdNormalizedDescriptors import RDKit2DNormalized
def parse_args():
parser = argparse.ArgumentParser(description="Arguments")
p... |
8baa7380b99ce1347b8cc73788ee5429365a7d8d42e3b7831b7cd9b4f629fb24 | Python | 1,462 | 46 | from typing import Callable, Protocol
import pytest
from neuralpredictors.layers.cores.conv2d import Stacked2dCore
class CreateCore(Protocol):
def __call__(self, *, final_nonlinearity: bool, linear: bool) -> Stacked2dCore:
...
@pytest.fixture
def create_core() -> CreateCore:
def _create_core(*, fi... |
60fe0734eace379b80738e0a6009d24e8d07b7d3e69a6ca7ce557e4089b732b7 | Python | 1,463 | 48 | #!/usr/bin/env python3
import argparse
from pathlib import Path
import h5py
import pandas as pd
# Arguemnt parser #
parser = argparse.ArgumentParser()
parser.add_argument("-hdf", required=True, type=str, help="Path to the h5 file.")
parser.add_argument("-o", required=True, type=str, help="Output directory for the tsv... |
9dbbae2c46375ed8bb4a749cc82ebecf0f0779493fc9586acfa9dbc11f54a52d | Python | 1,463 | 35 | # 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... |
66aadd260b567b09e2faaff1d40ebde912c539d56699dce6626590fb28a2b14e | Python | 1,464 | 42 | """
Print features out in order of their weights
Marco Lui, November 2013
"""
import argparse, os, csv, sys
from langid.train.common import read_weights
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('file', help="file to read")
parser.add_argument('-c','--column',help="proj... |
e65b1561eaef7951d72f527000b7dab88bf25872add1e7520467b82c13f7a0b8 | Python | 1,464 | 40 | import nltk
class FindChunks():
def __init__(self):
self.grammar = r"""
VP: {<ADJ_SIM><V_PRS>}
VP: {<ADJ_INO><V.*>}
VP: {<V_PRS><N_SING><V_SUB>}
NP: {<N_SING><ADJ.*><N_SING>}
NP:... |
e0a85bfb920eeadee076bd8c49006915d0be687edeef054a5beadc54f2395dff | Python | 1,465 | 32 | from constants import MODEL_DIR
def get_path(src='chexpert_80_20',dst='mimic',seed=20,shuffled=False):
# --------- For custom re-runs - Use this path -----------------
# shuf = 'shuffled_' if shuffled else ''
# path = '%s%s_train_%s_valid_%sseed%d/res_ops/%s_valid.npz'%(MODEL_DIR,src,src,shuf,seed,dst)
... |
0bc6bcf55c66fb48f87ef13b2c32dba335a2d91e519e3b0c760d3672c9082581 | Python | 1,466 | 47 | import sys
import joblib
import matplotlib.pyplot as plt
import torch.nn.functional as F
import torch
from dt_utils import Timer
from hebbian import HebbRecall
from plastic_gated import GSP1Recall
from recurrent_nets import VanillaRNNRecall, LSTMRecall
from data_utils import generate_delayed_recall_data
fro... |
4bbf5b37352d82fa7d4a7692dcd0c0e099c01adc0b8ad9b8598e36465bdd74b5 | Python | 1,466 | 48 | # -*- coding:utf-8 -*-
import argparse
import csv
from rdkit import Chem
def get_mols_without_h(smiles, mols):
for s in smiles.split("."):
m = Chem.MolFromSmiles(s)
for a in m.GetAtoms():
a.SetAtomMapNum(0)
a.SetNoImplicit(False)
Chem.SanitizeMol(m)
mols.appe... |
5ebe6a5caaced4277444b6e86ccf69b650111d5552a17571e057a2ce4edf9086 | Python | 1,467 | 53 | from langchain_core.callbacks.manager import (
AsyncCallbackManager,
AsyncCallbackManagerForChainGroup,
AsyncCallbackManagerForChainRun,
AsyncCallbackManagerForLLMRun,
AsyncCallbackManagerForRetrieverRun,
AsyncCallbackManagerForToolRun,
AsyncParentRunManager,
AsyncRunManager,
BaseRun... |
2ec2a47e760e0c3f277f19ce42acb16e59e2397eaa350fe623a354a7b31e1e8a | Python | 1,468 | 41 | # third part modules
import numpy as np
# pnabind modules
from pnabind.mesh import mapPointFeaturesToMesh
from pnabind.structure.data import data as D
def mapStructureFeaturesToMesh(mesh, structure, feature_names, residue_ids=None, include_hydrogens=True, impute=True, **kwargs):
"""
map_to: neighborhood, ... |
5231860091fde5a935537d6b40635e89c52cadfbc918ad165c83715b68aeb390 | Python | 1,469 | 55 | #!/usr/bin/env python3
from SMdRQA.RQA2 import RQA2_ml, RQA2_simulators
import numpy as np
def main():
print("Generating simulator battery...")
sim = RQA2_simulators(seed=42)
battery = sim.generate_test_battery()
signals = []
labels = []
# Create multiple samples per system by slicing the t... |
f4ee2143f018f210a7ceee6acf2741d8f0a1ba777d13e0c09dd45a2423939cc3 | Python | 1,469 | 41 | import torch
from torch import nn
import torch.nn.functional as F
import torch.nn as nn
import copy
class FFNetwork(nn.Module):
"""
Feedforward network for logic gate experiments. Stores activations for easy extraction.
"""
def __init__(self, args, dropout, lesion = False):
super(FFNetwork, se... |
6d30af360c189463b479cf49b6575605cf29ca7e318f061ede78943109d2bcca | Python | 1,470 | 45 | import shlex
import sys
import tempfile
from pathlib import Path
from hypothesis import given, settings, assume, HealthCheck
from MRdataset import load_mr_dataset, import_dataset
from MRdataset.cli import cli
from MRdataset.tests.conftest import dcm_dataset_strategy
@settings(suppress_health_check=[HealthCheck.too_... |
b72ca5275dafd38db7885bede367d50c541f7cab3de42294eb3f1b01ba2bc269 | Python | 1,472 | 33 | import os.path as op
import mne
from mne.minimum_norm import (make_inverse_operator, apply_inverse)
from config_FaceName import MEG_data_path,group_name,Ids,MRI_data_path,stats_conds_list
src_fname = MRI_data_path+'/fsaverage/bem/fsaverage-ico-4-src.fif'
src = mne.read_source_spaces(src_fname)
for subject_id in Ids:
... |
c6f140d5758d287f28f8b27e56e29b345066145cbbd72e6346a517ddd75d6707 | Python | 1,472 | 39 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for d... |
fed4482c3a3d1c4ba2e0ebc6ef6ffbc1186bf326a74593e824dbb2b759b3ce13 | Python | 1,472 | 52 | import numpy as np
def threshold_array(X):
'''
input: array row: sample, column: gene vector
output: a binary matrix
For each value in (i, j), the binary value = if(M_ij > avg(column_j))
'''
return X > np.mean(X, axis=0)
def threshold_quantile(X, quantile_gene=0.9, quantile_sample=0.95):
... |
1b0609d83d4fd40a410c9cabbe7647f9e933e908b49e04a9c649cf9b0b38d9b8 | Python | 1,474 | 20 | TRAJECTORY_PATHS_TEMPLATE = "data/trajectories/{}/e*s*_*/output.filtered.xtc"
TOPOLOGY_PATH_TEMPLATE = "data/trajectories/{}/filtered.pdb"
MINDIST_PATH_TEMPLATE = 'data/precomputed_trajectories/mindist-780-{}.npy'
INFO_PATH_TEMPLATE = 'data/trajectories/{}/info.yml'
MODEL_PATH_TEMPLATE = "data/models/{d}/model-ve-{d}-{... |
63426d955ce97aa15369424111274078774f8acf2f4f2080f93db6c0261f7097 | Python | 1,475 | 39 | import sys
sys.path.append('../source')
from tina_main import dataset
from matplotlib import pyplot as plt # for visualisation of imagedata
import networkx as nx
import tinaui
import tinaui as ui
import numpy as np
import os
plt.ion()
t1= dataset (folder='../test/sampledata/ocn',skelfolder='+skelall') #initialize the ... |
8e5ed49df670cfdd7bc3a883f49451668dbb71d227fed4f93218afeed7635aa6 | Python | 1,475 | 39 | from .data import data
def getHBondAtoms(structure, hb_info=None, d_key="hb_donor", h_key="hb_donor", a_key="hb_acceptor", feature_value=1.0):
# check for hydrogen bond info
if hb_info is None:
hb_info = data.hydrogen_bond_data
# initialize atom keys
for atom in structure.get_atoms():
... |
e443be0b18b73d4a0c90a4a2edebe2cac03f2ae8fc53b0b1d0bab4e39a0511bd | Python | 1,476 | 66 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 8 23:24:18 2023
@author: weihan
"""
import torch
import torch.nn.functional as F
from torch import nn
class MLP(torch.nn.Module):
"""
Multilayer Perceptron.
Nothing fancy, just a simple MLP.
Default output a one dim embeddings... |
eeb8f7279874c5dace7b432b15dec40c45616f9a6dfd37aed2e86b363e00ba90 | Python | 1,476 | 47 | """This module provides dynamic access to deprecated Zapier tools in LangChain.
It supports backward compatibility by forwarding references such as
`ZapierNLAListActions` and `ZapierNLARunAction` to their updated locations
in the `langchain_community.tools` package.
Developers using older import paths will continue t... |
161dac3216c3285c922e2e623526118e3ab254d8369a9d299c03bd46f3fab2d7 | Python | 1,478 | 41 | from utils.io import load_full_wl_test_data_as_tensorflow_datasets_oxy
from models import LSTMParams
import numpy as np
from paths import MODEL_PATH, TEST_DATA_PATH, TRAINING_DATA_PATH
from utils.constants import ALL_MODELS
import glob
import json
def evaluate(_dataset, _model):
results = []
for i in ... |
e5ef82b4897514c61c52a0397f0bbee4f9178bcc12a2cdbf14a59098d59879e9 | Python | 1,478 | 78 | """
:AUTHORS: Martin M. Müller
:ORGANIZATION: Department of Neurobiology, Bielefeld University
:CONTACT: martin.mueller@uni-bielefeld.de
:SINCE: Mon Nov 29 10:55:11 2021
"""
import numpy as np
def cart2pol(x, y):
"""
Convert cartesian coordinates to polar.
The returned angle phi is in the interval [-pi, p... |
4f56114ca6c31f5f035ad5d1a249f7d1ca29f44a1728ab326cd18bb47f131673 | Python | 1,479 | 38 | import numpy as np
from scipy.ndimage import gaussian_filter, laplace, gaussian_gradient_magnitude
from skimage.feature import daisy
def get_features(_input, sigmas, feature_mode='ilastik',
radius=10, rings=5, histograms=8, orientations=8):
# normalize image between 0 and 1
_input = _i... |
16d23f33571395b8fcd41ca2748e74f656dc2b05b9be743302137e0c91c1c769 | Python | 1,481 | 54 | import pdb
import time
import logging
import torch
from torch.autograd import Variable
from torch.autograd import gradcheck
from modules import batchnormsync
FORMAT = "[%(asctime)-15s %(filename)s:%(lineno)d %(funcName)s] %(message)s"
logging.basicConfig(format=FORMAT)
logger = logging.getLogger(__name__)
logger.set... |
c70dd3f4bc1f6fd5599a7304dcce03130892b4a0a6c2118658fdf5cf035e8275 | Python | 1,481 | 53 | import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
class Stochastic(nn.Module):
"""
Base stochastic layer that uses the
reparametrization trick [Kingma 2013]
to draw a sample from a distribution
parametrised by mu and log_var.
"""
def re... |
e38775e5ee957e82f13a0685da63391fa15dc3d92b3ed4ada0e9b54f05a47f70 | Python | 1,481 | 37 | import tempfile
from collections.abc import Generator
from typing import cast
import pytest
from langchain_core.documents import Document
from langchain_classic.storage._lc_store import create_kv_docstore, create_lc_store
from langchain_classic.storage.file_system import LocalFileStore
@pytest.fixture
def file_stor... |
19de62ade30ea43ba5e4bdea95cde2ec5e118ad98b068d6a765c6550df2bbe72 | Python | 1,484 | 37 | import torch
from torch import nn
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
import torch.optim as optim
from src.logic import logic_utils
from src import utils
def train(model, args, train_data):
# trains logic gate network
writer = SummaryWriter(args.log_out_dir + args.base_fol... |
2231dabbfbfe4f50f5f1d21f0f81b2b33dc691cb2dec09a14837303ad6b6bf5f | Python | 1,484 | 43 | import tensorflow as tf
from tensorflow.keras.layers import Add, Subtract
from typing import List
from .layer import LRPLayer
def _compute_add_lrp(a: tf.Tensor, b: tf.Tensor, R: tf.Tensor,
*, name: str, epsilon: float = 1e-9) -> tf.Tensor:
forward = tf.add(a, b, name=f'{name}/forward')
... |
c6dd0c37142c2e2bc0f6c197880946df4f910a8b9252ddc9efb6fad46e4d19c7 | Python | 1,484 | 51 | '''callbacks for training.
'''
import numpy as np
from keras.callbacks import TensorBoard
import keras.backend as backend
def CosineAnnealingSchedule(lr_max, lr_min, epoch_max, reset_decay=1):
'''create a learning rate scheduler that follows the approach from
SGDR: Stochastic gradient descent with warm rest... |
9e366b1cf34181e0b39adcca8f3f1cec70c6547d56dbe941467fcd108cdd0ccd | Python | 1,488 | 57 | from vulcanai import datasets
from vulcanai.models import ConvNet, DenseNet
import torch
from torch.utils.data import DataLoader, Subset, TensorDataset
import numpy as np
conv_2D_config = {
'conv_units': [
dict(
in_channels=1,
out_channels=16,
... |
04db078a98b9c46e1523491337105d4a41482156b1ad292c85646cb41e6b1312 | Python | 1,489 | 54 | import pydeface.utils as pdu
from shutil import which
import tempfile
import os
import pytest
from pathlib import Path
def test_cleanup_files():
files = []
for p in range(3):
files.append(tempfile.mkstemp()[1])
pdu.cleanup_files(files[0])
pdu.cleanup_files(*files[1:])
# should not fail if ... |
7ad2ec185e79dba163b0c899da10558d4d91d9b491a764ee8594776fff814216 | Python | 1,489 | 39 | import numpy as np
def compute_meshgrid(mid,tan,width):
width=int(width)
# print(mid.shape,tan.shape)
ort = np.stack([tan[:,1],-tan[:,0]]).transpose()
meshgrid = np.zeros((mid.shape[0],2*width+1,2))
i = 0
for m,o in zip(mid, ort):
k = 0
for w in np.arange(-width,+width+1):
... |
e435db2096c83a2843d0eea1d42680c7d897c0f53304c3d3774f5e87092a44d2 | Python | 1,490 | 49 | import json
import pytest
from langchain_classic.chains import OpenAIModerationChain
from langchain_classic.chains.openai_functions.openapi import get_openapi_chain
api_spec = {
"openapi": "3.0.0",
"info": {"title": "JSONPlaceholder API", "version": "1.0.0"},
"servers": [{"url": "https://jsonplaceholder.... |
d4f990a3f5813dc0e4c78f737075eb61c4460cd2302196dc843cdcb9faee72f0 | Python | 1,491 | 37 | from nowcasting.config import cfg
import os
from urllib import request
import argparse
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
download_jobs =\
[[cfg.HKO_VALID_DATETIME_PATH,
'https://www.dropbox.com/s/c372wb6ciygu73i/valid_datetime.pkl?dl=1'],
[cfg.HKO_PD.ALL,
'https://www.d... |
6508fc0250a4f8d375f4dea083c0d58089034e6cbe1a8c3f85b431a1354d7c72 | Python | 1,493 | 42 | import numpy as np
from sklearn.metrics import roc_curve, precision_recall_curve, auc
from sklearn.metrics import balanced_accuracy_score, recall_score, precision_score, jaccard_score
from sklearn.metrics import f1_score, accuracy_score, brier_score_loss, matthews_corrcoef
from sklearn.metrics import average_precision_... |
958443edc9a6692ad44fd386b9f8357f88c3e41ec9c09dfebb05f0dbed02f2dc | Python | 1,493 | 37 | ## This code demonstrates how you can use the defined functions to warp an image.
# import functions and libraries
import MRIWarp as warp
import pandas as pd
#----------------------------- compute the shape of screen
# set up inputs
pointFile = 'test_pointFile.csv' # replace it with your dispaly screen coordinates
... |
a47c616d2791269bf1a1bcd8e8086b46357dd809ba8f13e349bab53268c379ba | Python | 1,494 | 55 | from langchain_classic import retrievers
EXPECTED_ALL = [
"AmazonKendraRetriever",
"AmazonKnowledgeBasesRetriever",
"ArceeRetriever",
"ArxivRetriever",
"AzureAISearchRetriever",
"AzureCognitiveSearchRetriever",
"BM25Retriever",
"ChaindeskRetriever",
"ChatGPTPluginRetriever",
"Co... |
fad8350457cdc1cb8cfe431a2d73615f512bd7f615da78c7167fc36ab029ab2b | Python | 1,495 | 41 | import argparse
import os
import shutil
from glob import glob
import torch
from networks.unet_3D import unet_3D
from test_3D_util import test_all_case
parser = argparse.ArgumentParser()
parser.add_argument('--root_path', type=str,
default='../data/BraTS2019', help='Name of Experiment')
parser.add... |
ae5aa6d4e6eb5490a31d9f2f50d5211c9be1f13392b264dc9189636b7565a1b4 | Python | 1,496 | 47 | import os
import sys
import torch
import torch.nn
import argparse
import numpy as np
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from PIL import Image
from networks.resnet import resnet50
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
pa... |
39ce343486eeaf58ce5e7384c76dff105cc0334477e005241093176e906135a4 | Python | 1,497 | 54 | from typing import List, Any, Optional
from pdearena.configs.config import CFDConfig
from pdearena.utils.constants import (
BlastConstants,
Paths
)
class BlastConfig(CFDConfig):
use_ratio: bool = True
nx: int = 128
ny: int = 128
xspacing: float = BlastConstants.xspacing
yspa... |
6e149f7be543143663c374fc9a07fa8db4423fbff57138f00be71e1996dfe5b9 | Python | 1,497 | 40 | import io
import pandas as pd
import tarfile
import argparse
from pymatgen.io.cif import CifWriter, Structure
from tqdm import tqdm
import warnings
warnings.filterwarnings("ignore")
def process_cif_files(input_csv, output_tar_gz):
df = pd.read_csv(input_csv)
with tarfile.open(output_tar_gz, "w:gz") as tar:
... |
8cd2d5c99c081c8bc4c5f837d65ad0e45af3cb8c2eebac9565c0d21108754c67 | Python | 1,497 | 47 | # -*- coding: utf-8 -*-
# @title Ionic channels equations
# @file Ionchan.py
# @author Romain Beaubois
# @date 05 Dec 2022
# @copyright
# SPDX-FileCopyrightText: © 2022 Romain Beaubois <refbeaubois@yahoo.com>
# SPDX-License-Identifier: GPL-3.0-or-later
#
# @brief Provide functions for ioni... |
d6dc87ddf9fc78155311c751f2aab053aa08762c7f80f8c1bfd84129adda58b2 | Python | 1,497 | 51 | import numpy as np
def aggregateResidueAtoms(atoms, atom_key, residue_key=None, reduce_method="sum", impute_atom=False, atom_impute_value=0.0, residue_impute_value=0.0):
# reduction operations
if reduce_method == 'sum':
reduce_fn = np.sum
elif reduce_method == 'mean':
reduce_fn = np.me... |
8f8e58ddfed0a60084cca6e2b684bf8a8a74d5a2e499df7c4d061aaf6e77fed2 | Python | 1,498 | 44 | from src.parsers import AAI_parser
from src.animalai import train_AAI, test_AAI
from src.PID import runner
if __name__ == "__main__":
"""
************************************************************
Main function to run Animal AI experiments (for 1 seed).
**********************************************... |
d75f098f375b23bc7b225fbb88869c3d97b13326a61e889a60a1543f706da561 | Python | 1,498 | 46 | from langchain_core.output_parsers import BaseOutputParser
from langchain_core.prompts import PromptTemplate
from typing_extensions import override
class FinishedOutputParser(BaseOutputParser[tuple[str, bool]]):
"""Output parser that checks if the output is finished."""
finished_value: str = "FINISHED"
"... |
28fc968af54a791fd0fb2d1af57ad18b1160df10555643441ed5ec9d69b9995b | Python | 1,500 | 46 | import numpy as np
from dival import TaskTable
from dival.measure import PSNR, SSIM
from dliplib.utils import Params
from dliplib.utils.helper import select_hyper_best_parameters
from dliplib.utils.helper import load_standard_dataset
from dliplib.reconstructors.dip import DeepImagePriorReconstructor
from dliplib.utils... |
3ade456a9b47033eb52da360edfa30cb0276ce0526ce6854d5c4e480fedf906b | Python | 1,503 | 51 | import argparse
import numpy as np
def tanh_saturation(x, ksigma):
"""
Saturates outlier samples using a tanh shape function.
Args:
x (ndarray): Input data, can be a vector or a matrix (channels x time).
ksigma (float): Scaling factor for the saturation level.
Returns:
ndarray... |
432a3c3716fae5e205c8bff2bc7b2a91f8e6fd7125f6ea2925968be8c53c6c3c | Python | 1,503 | 57 | # 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... |
b79e889650135857aa2b64f59623acd587907b95a813d0e33f0490fbcb765c3a | Python | 1,503 | 60 | from setuptools import setup, find_packages
test_deps = [
"pytest~=7.0.1",
"pytest-cov==2.12.1",
"numpy~=1.19.5",
'pandas~=1.4.0',
'seaborn~=0.11.2',
'matplotlib~=3.5.1',
'tifffile~=2023.8.12',
'scipy>=1.9.0',
'statsmodels~=0.13.2',
'h5py~=3.1.0',
'scikit-image~=0.19.1',
'opencv-python~=4.6.0',
'suite2p~=0.10.3',
'ann... |
b8cd0601e743689d6aa414bb0f46e598ebbdb7efde63aa5497cc10491e5e2f5b | Python | 1,503 | 47 | import os
d="/jukebox/griffiths/bert-brains/"
model='bert-base-uncased'
#ds=['layer_'+str(i)+"_activations" for i in range(12)]
#ds+=['layer_'+str(i)+"_z_representations" for i in range(12)]
#ds+=['bert-base-uncased_syntactic_complexity_L-inf_T-128_D-concat']
#ds=['ling_features']
#ds=['bert-base-uncased_syntactic... |
c631cd2e2cc4cf4e87641d62fd0521adaf17b4e24473924e39fe473f9dd06f63 | Python | 1,503 | 42 | import os
import tarfile
import argparse
import pickle
import gzip
from tqdm import tqdm
def load_data_from_tar(tar_gz_filename):
print(f"loading data from {tar_gz_filename}...")
cif_data = []
with tarfile.open(tar_gz_filename, "r:gz") as tar:
for member in tqdm(tar.getmembers(), desc="extracting ... |
b41a89307107c3f40de8543f00891c8023c924a6dbcc901e456bc6fea0000ebb | Python | 1,504 | 58 | #! /usr/bin/env python
#
# Copyright (C) Hideto Mori
DESCRIPTION = "circosplot for matplotlib"
LONG_DESCRIPTION = ""
DISTNAME = 'python-circos'
MAINTAINER = 'Hideto Mori'
MAINTAINER_EMAIL = 'hidto7592@gmail.com'
URL = 'https://github.com/ponnhide/pyCircos'
LICENSE = 'GNU General P... |
8d84e42a0ec674963a101b3bfa77fc9267203ade3157d60f34f963f1583a7e01 | Python | 1,505 | 46 | from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='TEtranscripts',
version='2.2.4',
description='Tools for estimating differential enrichment of Transposable Elements and other highly repetitive regions',
long_description=readme(... |
bfb60fcbb45ee5faa913ccf231828d85c4ce405ea632ad15b44f502139f3227a | Python | 1,505 | 26 | # 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... |
3dc8dd010e5e4fcc3a3c05d34cbd4de5542f4c537da58c31ae2733643d8318cf | Python | 1,507 | 56 | from typing import List
from pdearena.configs.config import CFDConfig
from pdearena.utils.constants import (
CoalConstants,
Paths
)
class CoalConfig(CFDConfig):
start_time: float = 1e-4 / 4
use_mach: bool = True
use_diameter: bool = True
nx: int = 104
ny: int = 104
xs... |
6ff8496a48b072326abd16fb1d0c86781dc74a2d097be7187e7ba6bd6f32822c | Python | 1,507 | 56 | import wandb
from wandb.wandb_run import Run
from dataclasses import dataclass
from typing import Dict, Any
from omegaconf import DictConfig, OmegaConf
class PrintLogger:
buffer: Dict[str, Any] = dict()
@staticmethod
def _print_item(item):
if isinstance(item, dict):
entry = ", ".join(f... |
9ba52cb741a826d18c6b93d752ef0ae7a6fc700e20f855c2774ffd92f4ae59c1 | Python | 1,508 | 51 | import copy as copylib
class Config():
def __init__(self, **kwargs):
self.assign(**kwargs)
def assign(self, **kwargs):
for k,v in kwargs.items():
self.__dict__[k] = v
def join(self, obj, key_prefix:str=None):
'''
This function takes two objects (or self, obj) an... |
492afa27275427d04e93bc824198af6effaf253cc5ddc4b2473146ca8c016989 | Python | 1,509 | 42 | import shutil
import argparse
import os
def main():
parser = argparse.ArgumentParser(description="Split train data into train and validation sets.")
parser.add_argument('dataset_dir', type=str, help='Path to the directory which contains the dataset')
args, _ = parser.parse_known_args()
val_patients =... |
d604fdac8c5accff3f76114118e2f98c8a003ef06001c87576268773e31acf4b | Python | 1,509 | 60 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
install_requires = [
'setuptools>=59.5.0',
'cilog>=1.2.3',
'gdown>=4.4.0',
'matplotlib>=3.5.2',
'munch>=2.5.0',
'pytest==7.1.2',
'pytest-cov~=3.0',
'pytest-xdist~=2.5',
'ruamel.y... |
ce0494e106741e85c8481775d14aafeaacb23e4fa5752ad34f3efa564519a5b4 | Python | 1,511 | 54 | import enum
import nibabel as nib
def load_nibabel_image_with_axcodes(
image: nib.nifti1.Nifti1Image, axcodes: str = "RAS"
) -> nib.nifti1.Nifti1Image:
input_axcodes = "".join(nib.aff2axcodes(image.affine))
axcodes = "".join(axcodes)
if input_axcodes != axcodes:
input_ornt = nib.orientations.... |
8a111c0d2ada6246d5db5feeb96bdfd1eeb0d3bca692c95170cd3c0c01d71d14 | Python | 1,512 | 61 | from logging import Logger
from pathlib import Path
from typing import List
import json
from ...utils.io import get_metadata
from ..data import AnnotationTable, WorldlineTable
from ._utilities import default_args
@default_args("False")
def jump_to_next_t_ref(
dataset: Path,
annotations: AnnotationTable,
... |
e51874bae5301bb1ee1c6681217dc6d271cb7aa8ca8ddfca668787293a5e71a4 | Python | 1,512 | 60 | import re
import pytest
from langchain_classic.output_parsers.boolean import BooleanOutputParser
def test_boolean_output_parser_parse() -> None:
parser = BooleanOutputParser()
# Test valid input
result = parser.parse("YES")
assert result is True
# Test valid input
result = parser.parse("NO... |
fd57ad8ae6289196c786175eec31d06faf9c9e418bd3746b59f192b336f81e9c | Python | 1,512 | 52 | import os
import subprocess
cohorts = os.listdir("cohorts")
atlas_path = "signatures/moss" # "signatures/sinature_withoutGBM.csv"
def get_arrayTypes(idat_folder):
cmd = "Rscript separate_arrayTypes.r cohort results"
savedir = os.path.join("results", "cohort")
if not os.path.exists(savedir):
os.mkdir(savedir)
s... |
afe1ec1ceae5b4d5a015fefad0f59ae150d1af837f0f9a2f3b674cbe6a51269e | Python | 1,513 | 32 | """Fast correctness + timing smoke for TabFM on HVG-reduced CD4 data.
Confirms TabFM predict is practical at ~2000 features before the full bench.
Run: conda run --no-capture-output -n deepmapper python -u bench/_tabfm_smoke.py
"""
import sys, time, warnings
sys.path.insert(0, "."); warnings.filterwarnings("ignore")
im... |
815ded4de03c6c076aa0910145e225cb2d956405ea0d7cdbc5ca226bcbd4eeef | Python | 1,516 | 54 | from setuptools import setup, find_packages # looks good
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="SMdRQA",
version="2024.04.02",
author="Swarag Thaikkandi, K.M. Sharika, Miss Nivedita",
author_email="tsk4at@gmail.com",
description="A Python implementation o... |
93cf86ac07b39b08fcab6f1a5635a913d9999dc9bd2758908b867463e2aa8143 | Python | 1,516 | 46 | import numpy as np
from dival import TaskTable
from dival.measure import PSNR, SSIM
from dliplib.utils import Params
from dliplib.utils.helper import select_hyper_best_parameters, load_standard_dataset
from dliplib.reconstructors.dip import DeepImagePriorReconstructor
from dliplib.utils.reports import save_results_tab... |
38324018aec7ff6f4e80558a13b655264ab61d27e8bce1069241f28fb394a153 | Python | 1,517 | 47 | import sys
import os
import os.path
#############################################to convert EagleC SV to circos format SV### new format SV outputs are located in the same folder with old####################
inputdir='/home/uni08/txie/analysis/Pan/analysis/SV'
#################################################... |
5d1f812c5b8b660b63c019fdc3fb70eb50987401cdda754ab96462c2a589aa3a | Python | 1,518 | 54 | import matplotlib.pyplot as plt
def _update_axis(
axis, image, title=None, fontsize=18, remove_axis=True, title_loc="center"
):
axis.imshow(image, origin="upper")
if title is not None:
axis.set_title(title, fontsize=fontsize, loc=title_loc)
if remove_axis is True:
axis.set_axis_off()
... |
31196bafa03d20242430e7cd152c5cdd9d31d519f006cfa40a44657e6eac952a | Python | 1,519 | 65 | from langchain_core.messages import __all__
EXPECTED_ALL = [
"MessageLikeRepresentation",
"_message_from_dict",
"AIMessage",
"AIMessageChunk",
"Annotation",
"AnyMessage",
"AudioContentBlock",
"BaseMessage",
"BaseMessageChunk",
"ContentBlock",
"ChatMessage",
"ChatMessageC... |
75ca7329b8a48c95fb53d6caaa41d4ebb808bbedf1c2097f16de0dae09da48c7 | Python | 1,519 | 52 | """**Indexes**.
**Index** is used to avoid writing duplicated content
into the vectostore and to avoid over-writing content if it's unchanged.
Indexes also :
* Create knowledge graphs from data.
* Support indexing workflows from LangChain data loaders to vectorstores.
Importantly, Index keeps on working even if th... |
578bf94949cbdb34f8beb3279065594260befe5bb58944ce9497df2d1dd825f8 | Python | 1,522 | 45 | import albumentations as A
from albumentations.pytorch import ToTensorV2
from utils.my_containers import ObjDict
class AutoImgTransformationManager(object):
def __init__(self, aug_cfg):
self.cfg = aug_cfg
def __call__(self, name=None):
if name is None:
name = self.cfg.name
... |
58ab2d5e795dd7ab5d501941cba3a1124f56d293ffd986519ddc5abeb720da39 | Python | 1,522 | 44 | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chains.ernie_functions.base import (
convert_to_ernie_function,
create_ernie_fn_chain,
create_ernie_fn_runnable,
create_structured_output_chain,
... |
6396ed054abe354bd0e98efa011446e9170fe529f253cf3515dc992c9d3a7286 | Python | 1,522 | 50 | """Edenai Tools."""
from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.tools import (
EdenAiExplicitImageTool,
EdenAiObjectDetectionTool,
EdenAiParsingIDTool,
EdenAiParsingInvoiceTool,
EdenAiS... |
c2094ca63c6c8c4f0a834ccf9e8186a419014aa65b2b3847b694190a2b216866 | Python | 1,522 | 48 | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.vectorstores.redis.filters import (
RedisFilter,
RedisFilterExpression,
RedisFilterField,
RedisFilterOperator,
RedisNum,
RedisTag,
... |
4bd1db1be0226ef3dc3cc7003a45a52dbce150651ac82f7fac7a9bff5a511847 | Python | 1,523 | 48 | from pycromanager import JavaBackendAcquisition, multi_d_acquisition_events, ZMQRemoteMMCoreJ, start_headless, XYTiledAcquisition
import numpy as np
import time
# mm_app_path = '/Applications/Micro-Manager-2.0.0-gamma1'
# mm_app_path = 'C:/Program Files/Micro-Manager-2.0gamma'
# config_file = mm_app_path + "/MMConfig... |
32ba15a2ea46cc461495a6249c23567a1c2c26cf16e35c2fd1f72ac75e104468 | Python | 1,525 | 45 | # Copyright 2022 DeepMind Technologies Limited.
#
# 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... |
32e195e6b6fc461f9811e7123a79ae00b751195a65525ea49eb81d811dea79b3 | Python | 1,525 | 37 | # -- coding: utf-8 --
# @Time : 2022/12/1 18:38
# @Author : Biao Zhang
# @Email : littlebiao@outlook.com
# @File : load_part_expression.py
import sys
import pandas as pd
sys.path.append('..')
from analysis_utils import ttest_plot_utils
from analysis_utils import homo_random_config as config
import os
import scanpy as... |
19b235b0a68e0f701f73988157ba8979a3274728eafaab3d443ad3bf6fb8900b | Python | 1,527 | 33 | import numpy as np
import tensorflow as tf
import math
def linear(input_, output_size, scope, reuse=False, init_bias=0.0):
shape = input_.get_shape().as_list()
stddev = min(1.0 / math.sqrt(shape[-1]), 0.1)
with tf.variable_scope(scope, reuse=reuse):
W = tf.get_variable("Matrix", [shape[-1], output_... |
9745983bb93da4ed05e3058752570577fa7f0cf1c3e506ffcc2c81c0f06435d1 | Python | 1,528 | 27 | from langchain_classic.agents.agent import BaseSingleActionAgent
from langchain_classic.agents.agent_types import AgentType
from langchain_classic.agents.chat.base import ChatAgent
from langchain_classic.agents.conversational.base import ConversationalAgent
from langchain_classic.agents.conversational_chat.base import ... |
8e3ba4f1a602be532cadb0256ae8879ef8f60ca297d3203cfc0dc14fd7b809b6 | Python | 1,530 | 45 | # This file is a part of the `allegro` package. Please see LICENSE and README at the root for information on using it.
import torch
def MuonParamGroups(
model: torch.nn.Module,
muon: dict,
adam: dict,
):
"""
Build optimizer parameter groups, splitting parameters between a Muon-based optimizer
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.