sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
40c877c473eb073a27babdccb9ce2f139db3e604f68fbf160ea888f9d5c9b9c7 | Python | 1,767 | 49 | import numpy as np
from tqdm import tqdm
from odl.tomo import fbp_op
from dliplib.utils.data.datasets import CachedDataset
def generate_dataset_cache(dataset, part, file_names, ray_trafo, filter_type='Hann', frequency_scaling=1.0, size=None, only_fbp=False):
"""
Write data-paris for a CT dataset part to file... |
b6640d45075d9ed2dfbe5ab6f24571bf8876756ec03334a28af7de6bd7cc29a8 | Python | 1,767 | 48 | from setuptools import setup, find_packages
from Cython.Build import cythonize
from glob import glob
import os
extensions = cythonize("ccg/**/*.pyx", language_level=3)
with open('requirements.txt') as fh:
install_requires = [x.strip() for x in fh]
with open('requirements-parser.txt') as fh:
install_requires_... |
a3c3a53199b0b8928e35e71e004d6f339b56d8660a002a1d2ee3cea0eebeb37f | Python | 1,768 | 50 | import sys
import os
import pandas as pd
from random import choices
def is_overlap(perm_row, cnv_df):
sub_df = cnv_df.query("barcode==\'"+perm_row["barcode"]+"\' & chrom==\'"+perm_row["chrom"]+"\'")
if sub_df.empty:
return False
else:
for index, row in sub_df.iterrows():
if per... |
012e0f1e045f7385d17283e107730febc39f1e1bb4e7f5d19680c907359538d3 | Python | 1,769 | 37 | # Credit to https://github.com/openai/evals/tree/main
from langchain_core.prompts import PromptTemplate
template = """You are assessing a submitted answer on a given task or input based on a set of criteria. Here is the data:
[BEGIN DATA]
***
[Input]: {input}
***
[Submission]: {output}
***
[Criteria]: {criteria}
***
... |
650f58a43484cb7367f77714807c1bc748df793ed11c36021a8fa301d66c365a | Python | 1,771 | 56 | import asyncio
from itertools import cycle
from typing import Any
from uuid import UUID
import pytest
from pytest_benchmark.fixture import BenchmarkFixture
from typing_extensions import override
from langchain_core.callbacks.base import AsyncCallbackHandler
from langchain_core.language_models import GenericFakeChatMo... |
385b277c7206fc073bc91fdcb2726988795181dc341428672511ba3795911738 | Python | 1,772 | 47 | def _interp_fit(y0, y1, y_mid, f0, f1, dt):
"""Fit coefficients for 4th order polynomial interpolation.
Args:
y0: function value at the start of the interval.
y1: function value at the end of the interval.
y_mid: function value at the mid-point of the interval.
f0: derivative va... |
3cf468a2f0c924a25c167f8afcc0c9e0d4dd2dc7329b91688a4a7589908f9992 | Python | 1,772 | 62 | # 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.
_base_ = [
'../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k.py',
'../_base_/default_runtime.py... |
c83b4b8bfaf6183f307cc6e6c2e641880b1525b104b036cf5a1f8f2ba79ac607 | Python | 1,772 | 89 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 8 14:30:28 2021
@author: shni2598
"""
import matplotlib as mpl
mpl.use('Agg')
from scipy.stats import sem
#import load_data_dict
import mydata
import numpy as np
# import brian2.numpy_ as np
# from brian2.only import *
#import post_analysis as ps... |
514b4834f40f49a82f187057917419ff87d5da2cf71d7293aa3a826159937d62 | Python | 1,773 | 37 | import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from dipgnn.models.layers.residual_layer import ResidualLayer
class Bond2AtomBlock(layers.Layer):
def __init__(
self,
hidden_size,
name='bond2atom_block',
activation=None,
... |
4e4e4e81a44a362f0981af5aa737a108b4f9a4b9bd560d7330a9cd15f462f9ac | Python | 1,774 | 71 | """Example01.
The simulation is copied from:
https://scikit-learn.org/stable/auto_examples/linear_model/plot_ard.html
"""
# pylint: skip-file
import copy
import time
import numpy as np
from sklearn.datasets import make_regression
import compare_models
# Copied from scikit-learn
X, y, true_weights = make_regression(
... |
84d8b116be26dda720447bc2eccb1b6a6e9b6c7ccd9a9f19569d6521a385fa1d | Python | 1,774 | 59 | import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch.nn import LayerNorm, ReLU, Linear
from torch_geometric.nn import MLP, GINConv, DeepGCNLayer
from sklearn.metrics import f1_score
class SMNetEncoder(nn.Module):
def __init__(self, in_channels, hidden_channels, num_layers, edg... |
89a103e41c5b950b8cdda0b15fefc8e49310befa48c3a281f40f4a03907a2948 | Python | 1,774 | 52 | """
Generate random example data which allows for testing and
to give users examples for the input format
"""
import random
import os
import logging
import pandas as pd
import numpy as np
import sys
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def exampleData(n_cells=10, n_genes=100, n_samples=... |
05f6b889fb88e2dfefc41ce4b6fbd526bd68a5a5a37c84c404cd741e2f45ad93 | Python | 1,775 | 53 | import json
import logging
import pandas as pd
import somatosensory_barrels
from voxcell import VoxelData
L = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def split_barrel_columns( # pylint: disable=too-many-arguments
annotation_path,
hierarchy_path,
barrels_path,
output_hier... |
50e121416b7c8f5dd2fd4f1fec29bc1fa31a1448e74bdee9d49bc853665c9015 | Python | 1,775 | 54 | import pytest
from langchain_core.documents import Document
from langchain_classic.retrievers.multi_query import (
LineListOutputParser,
_unique_documents,
)
@pytest.mark.parametrize(
("documents", "expected"),
[
([], []),
([Document(page_content="foo")], [Document(page_content="foo")... |
2af9b6ba1f3be07661981d95caf5636cd45c82083d59ebad3933caa6ce4cb844 | Python | 1,777 | 58 | import cobra
import itertools as it
import pandas as pd
def get_bigg_mmu_nopt_model():
bigg_mmu_json = cobra.io.load_json_model('Recon3D.json')
bigg_rxn_subsys_lut = {}
for ir in bigg_mmu_json.reactions:
if ir._id in bigg_rxn_subsys_lut:
print(
'dup {} {} {}'.format(
... |
696c415612a5f1829c44f681eed2f63c2952d84a944c2b157eea96e5fcfbb850 | Python | 1,777 | 71 | import pandas as pd
import numpy as np
def write_csv_features(feature_names, feature_data, csv_file):
"""
Write features to a CSV file.
Parameters
----------
feature_names : list of str
Names of the features.
features_data : numpy array
Data for the features. Format: [frames, ... |
97a7377938d0ce975e0ffdc641b593b67291f84e3aaddcabb1efce28a5d61d5d | Python | 1,777 | 43 | # 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... |
b74d7d0273288babcf7efa766880d662821eaab962f73382644f4ef57168e3d9 | Python | 1,778 | 62 | # 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.
_base_ = [
'../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k.py',
'../_base_/default_runtime.py... |
efb2614a8ed5edfae4100bf8a47c53fad52fc63da584a9896b2a79c72f29be94 | Python | 1,779 | 64 | from langchain_classic import embeddings
EXPECTED_ALL = [
"OpenAIEmbeddings",
"AzureOpenAIEmbeddings",
"CacheBackedEmbeddings",
"ClarifaiEmbeddings",
"CohereEmbeddings",
"DatabricksEmbeddings",
"ElasticsearchEmbeddings",
"FastEmbedEmbeddings",
"HuggingFaceEmbeddings",
"HuggingFa... |
9e9ea679097aabc0a5728c4ce2d9cd20e4a9eb2c6aa3f5c05e5fb2bb371078e5 | Python | 1,780 | 51 | """ Process output of Zilany et al. (2014) model.
The an rate arrays are read in as .npy files, and the AN firing rates are resampled to 44.1 kHz, averaged across all
AN frequencies, and shifted by 1 ms to produce the final AN rate. The arrays are then saved as .npy files.
"""
import numpy as np
import scipy.signal a... |
d4eb6b7ec89fc53f9c96467744069482d152858649434873e55b09827ab6334e | Python | 1,780 | 49 | from models.lstm import LSTMParams, get_model
import tensorflow as tf
from utils.io import preprocess_data
import glob
import numpy as np
from paths import TRAINING_DATA_PATH
files = glob.glob(TRAINING_DATA_PATH + "/*")
WAVELENGTHS = 15
spectra, oxy = preprocess_data(f"{TRAINING_DATA_PATH}/ALL/ALL_train.npz", WAVELE... |
e87d42f5cc598de78439a6afd693f39b671240ee86288d3229964438e9caee9a | Python | 1,780 | 52 | from typing import TypedDict, Dict
class ObjectClassError(Exception):
"""handles exceptions caused by calling function on invalid class type."""
def __init__(self, function, valid_class, invalid_class):
# todo need to add eq checking I think to allow extended classes of the valid classes to be consid... |
04a666fb1b6ed76a64a74c0e92251b8d465edbc3d802ea24f2bd19966faaa34a | Python | 1,781 | 67 | # Copyright 2024 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... |
20e43850581297a55d7790c57ed76347a4567af4023e2f40526c2d565b212d62 | Python | 1,781 | 59 | import tensorflow as tf
from nn import linearND, linear
from mol_graph_direct import atom_fdim as adim, bond_fdim as bdim, max_nb, smiles2graph, smiles2graph, bond_types
from models import *
import math, sys, random
from optparse import OptionParser
import threading
from multiprocessing import Queue
import rdkit
from r... |
2ac3125baf158bbc7dff47521b787b2b4cc0ffd14dea09de8f69eb7a7b969b91 | Python | 1,782 | 54 | from django import forms
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from .models import Cluster
class ClusteringForm(ModelForm):
data_type = forms.CharField(
max_length=15,
widget=forms.Select(choices=Cluster.DATA_TYPES),
required=True,
)
... |
35c361e5317c452844e0469b5621ff88a1c3fb24a09e4c002f52d4ea87579efa | Python | 1,783 | 50 | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
from util.util import MyDataset, train_eval, test, load_data
from model.transformer import TransformerModel
# 获取数据的维度
num_people = 137 # 数据中的人数
num_fe... |
83b4f98ef592f772903cba5587895342a12c9c0f26ef7a9db42fd4d8b56e9822 | Python | 1,783 | 64 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from typing import Tuple, List
from pdearena.configs.config import Config
from pdearena.utils.constants import (
CoalConstants
)
from torch_geometric.data import Data, Batch
import torch
def get_nt(u):
if isinstance(u, torch.... |
fbf4fa5672f48af27b21c5f5fd7ac1ed329b641e11f0c71b0ac483dde559cf2f | Python | 1,785 | 55 | import numpy as np
from skimage.io import imread, imsave
def pad_images( img, pad_width_ratio=0.1 ):
'''
pad a 2D (+channel) image so that the outpute shape is img.shape*1.1
the pixel values on the edge follow a normal distribution with :
- mean = avg-1*std of the outer 0.1 layer of the image
- std... |
94f9e8eb042930bf79be70992c3ff3cf8a54f56563910a490c5e7bcbb731ebc2 | Python | 1,786 | 60 | """
Created on Thu Aug 5 15:09:36 2021
@author: Shencong Ni
"""
import numpy as np
# onoff_bool = np.ones(10, dtype=bool)
# onoff_bool[-1] = False
# onoff_bool = onoff_bool[::-1]
# onoff_bool[-1] = False
# d = np.random.randint(1,10, 10)
#%%
def get_onoff_cpts(onoff_bool):
onoff_bool_tmp = np.concatenate(([... |
b2f817301fc102f2d9df65afbb22a6582790d9c41983b17121b39e7a6e807002 | Python | 1,786 | 62 | # 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.
_base_ = [
'../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k_640x640.py',
'../_base_/default_ru... |
75e5582cf0c1a85a14131529d4d214de12588bb50d2fa6384b0b7c4a2090d9ed | Python | 1,787 | 62 | # 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.
_base_ = [
'../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k_640x640.py',
'../_base_/default_ru... |
93be516ea5c75ff98b4dda9acb144b108eaaab27699298b58078602433a7b2d7 | Python | 1,787 | 83 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"Special module to handle differences between Python 2 and 3 versions"
import sys
PY3K = sys.version_info >= (3, 0)
try:
import cPickle as pickle
except ImportError:
import pickle
try:
from urllib import urlopen
except ImportError:
from urllib.request import ... |
4408d86a5c58787abedfc5636598d053df4d5933d4df3bdf9a71e4fe30af49e2 | Python | 1,788 | 56 | #!/usr/bin/env python3
"""
This script was generated in part with ChatGPT, OpenAI’s large-scale language-generation model.
Upon generating draft code, the author reviewed, edited, and revised the code to their own liking
and takes ultimate responsibility for the content of this script.
"""
import os
import sys
import... |
69c5e00cacb09d3c9955d371dff8121bc7f7710e6aecc70d6789382e709a610c | Python | 1,789 | 69 | """String utilities."""
from collections.abc import Iterable
from typing import Any
def stringify_value(val: Any) -> str:
"""Stringify a value.
Args:
val: The value to stringify.
Returns:
The stringified value.
"""
if isinstance(val, str):
return val
if isinstance(va... |
94c4b276a8a704ade67b9c66b24b57423c40068f79f8305f14170a9311f81186 | Python | 1,789 | 55 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class FullyConnect(nn.Module):
def __init__(self, in_ft, out_ft, act=nn.Identity(), drop_prob=0.0, isBias=False):
super().__init__()
self.fc = nn.Linear(in_ft, out_ft, bias=False)
if self.fc.bias is not No... |
2328339f18f3f0d3765f38a97ffae50f718543fed02741635084f1b39738cdba | Python | 1,790 | 54 | import numpy as np
from scipy.ndimage import binary_fill_holes, label
from skimage.morphology import binary_dilation, binary_erosion, disk
from skimage import transform
def smooth_mask( _input,
down_shape=-1,
mode='classifier',
thin_order=10,
smooth_orde... |
6f98350abdd323025fb9fc438c3db3a7b88c038b7b86ef6f00213bdadc0f0eb5 | Python | 1,791 | 41 | # 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... |
e7430b916a468870205d4373e3329dabfd2a183f11318858c1948591c616025f | Python | 1,791 | 62 | # 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.
_base_ = [
'../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k_640x640.py',
'../_base_/default_ru... |
5ae33ad0370c2793845f2d662fc6f5fd686d613d4deb6da5d28180f5383db333 | Python | 1,792 | 36 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 12 11:49:12 2023 (Caio) - This file must have the filename strings of the vide data
Adapted on Fri Jun 14 23:26:34 2024 (Caio) - Organized module to share (Github)
@author: Caio VAZ RIMOLI: https://github.com/RimoliCV
Complex Media Optics lab: https://gith... |
ebf7963db8bf36e3766b8479ce0368aae459eba6620995828adf3d5e974a15da | Python | 1,794 | 54 | """Module definitions of agent types together with corresponding agents."""
from enum import Enum
from langchain_core._api import deprecated
from langchain_classic._api.deprecation import AGENT_DEPRECATION_WARNING
@deprecated(
"0.1.0",
message=AGENT_DEPRECATION_WARNING,
removal="2.0.0",
)
class AgentTy... |
33e0b0edb34626bac97683d0ef22f72c797522566b7770de7c3a25f8bfb95ab5 | Python | 1,795 | 36 | import mne
import os.path as op
import numpy as np
from config_FaceName import MEG_data_path,group_name,Ids,bids_root
print(Ids)
from mne_bids import BIDSPath
for subject_id in Ids:
subject = group_name+"%02d" % subject_id
print("processing subject: %s" % subject)
fname=op.join(MEG_data_path,... |
a84462b6bdf5c6042bec9a651e4999145c7e5bc2085e8761c7553cb8b86c9fe1 | Python | 1,795 | 47 | import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
def Count():
ratio = ["0.30", "0.29", "0.28", "0.27", "0.26", "0.25", "0.24"]
count = [76348, 76002, 70062, 54942, 40606, 26102, 15986]
proportion = []
for j in range(len(ratio)):
for i in ran... |
b149ddf2a2c57cd21ba71df2ef570725dcb0adf645ba60135de8321fa272a122 | Python | 1,795 | 47 | import sys
import torch.nn.functional as F
import numpy as np
import joblib
import matplotlib.pyplot as plt
from dt_utils import Timer
from plastic import PlasticRecall
from data_utils import generate_delayed_recall_data, generate_delayed_recall_from_pairs, \
recall_chance, generate_ari... |
73192c4ba15f7a555a7a79e4d3c3dca3828deeb7bf0ede68f45009ea04f57da0 | Python | 1,796 | 36 | from src.data import get_sim_data
import numpy as np
import os
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
seeds = [15, 37, 98, 137, 245]
results = {'mse_train': list(), 'mae_train': list(), 'r2_train': list()}
for seed in seeds:
np.random.s... |
fa91cf8ceaaa316cf6b70a288d99b08eee3de26b142b182e6feccf7e1f4b8b0c | Python | 1,796 | 56 | import os
import time
from torch.cuda.amp import autocast
from core.runner import runner_register, PretrainRunner
from utils.tensor_operator import to_device, tensor2array
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
import warnings
warnings.filterwarnings('ignore')
import torch
from to... |
67ec1d4606f362982c92b5bc69955e8d7d5117fa4b005e96f5a9b21be18b1802 | Python | 1,797 | 51 | import torch.nn as nn
import torch.nn.functional as F
from pointnet2_utils import PointNetSetAbstractionMsg, PointNetSetAbstraction
class get_model(nn.Module):
def __init__(self,num_class,normal_channel=True):
super(get_model, self).__init__()
in_channel = 3 if normal_channel else 0
self.n... |
6b584f725065576babb75d4ad0798ff5206600f0149867112cf5f945a9a28dc3 | Python | 1,797 | 58 | """LangChain **Runnable** and the **LangChain Expression Language (LCEL)**.
The LangChain Expression Language (LCEL) offers a declarative method to build
production-grade programs that harness the power of LLMs.
Programs created using LCEL and LangChain Runnables inherently support
synchronous, asynchronous, batch, a... |
8be51478680dd00a1c055e3b7243f6f1782839a791276bf867acd81e8f1116a7 | Python | 1,797 | 50 | import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.nn.functional as F
from pointnet_utils import PointNetEncoder, feature_transform_reguliarzer
class get_model(nn.Module):
def __init__(self, num_class):
super(get_model, self).__init__()
self.k = num_cl... |
a1b6a895776939d51da1842a73efddd10d83e0f37accd27298dbdd2352606c35 | Python | 1,798 | 41 | import torch
from torch import nn
class Encoder3d(nn.Module):
def __init__(self, core, readout, readout_nonlinearity, elu_xshift, elu_yshift):
super().__init__()
self.core = core
self.readout = readout
if readout_nonlinearity == "adaptive_elu":
self.nonlinearity = core.... |
99b3d1f0be2869845be4b1ee69fa56672b08d8c116642cf23f28aba24f1e551c | Python | 1,799 | 33 | # 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... |
5ec2872c9b2c19a869df766bc11a29f54d6fa31d6b75d28b401c65bb2755869b | Python | 1,801 | 47 | import numpy as np
from tensorflow.keras import Model
from tensorflow.keras.layers import Add, Input
from explainability.layers import AddLRP
def test_add_positive():
i1 = Input((3,))
i2 = Input((3,))
a = Add()([i1, i2])
model = Model([i1, i2], a)
explainer = AddLRP(model.layers[-1])
explan... |
6e344ba7e0e0d639a2a9dcb6afdb9336ac2ddc5ffcf7955c302dc7b576715bf6 | Python | 1,803 | 49 | from ChipseqReport import *
import Annotations
import Motifs
##########################################################################
##########################################################################
##########################################################################
# Looking at overlap with repeats... |
aa4ace83dbeb709ee5d8cb69a24d4f962c2137b6dc821dd9400f1842651aad5e | Python | 1,803 | 63 | import numpy as np
import scipy
import scipy.spatial
from rfdiffusion.kinematics import get_dih
# calculate planar angles defined by 3 sets of points
def get_angles(a, b, c):
v = a - b
v /= np.linalg.norm(v, axis=-1)[:,None]
w = c - b
w /= np.linalg.norm(w, axis=-1)[:,None]
x = np.sum(v*w, axis=... |
e09699edaa535872dff5f43ac38b261dbd26a2aa64447ff4911793ae1ce4b956 | Python | 1,805 | 42 | # __init__.py - Module setup for PyPL2
#
# (c) 2016 Plexon, Inc., Dallas, Texas
# www.plexon.com
#
# This software is provided as-is, without any warranty.
# You are free to modify or share this file, provided that the above
# copyright notice is kept intact.
#__init__.py serves three purposes:
# 1) Let's Python kno... |
1074fa0341f4830dadb9203151d86357d48524bcadc3f705135d039065185793 | Python | 1,806 | 50 | import argparse
import os.path
import sys
from pathlib import Path
from mrQA import monitor
def main():
"""Console script for mrQA."""
parser = argparse.ArgumentParser(
description='Protocol Compliance of MRI scans',
add_help=False
)
required = parser.add_argument_group('required arg... |
2c353fa2be94e19a196b7f06a8fdaaaba18e37c2edd9def5712a13fd2c666d21 | Python | 1,806 | 57 | # 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... |
c30a20b9ad89fb562b438382decd42417662516de7abcefb3d8ae1ada351e8c8 | Python | 1,806 | 59 | """
This script prepares the eQTL results (tensorQTL) for mash modeling.
"""
import argparse
import pandas as pd
from pyhere import here
def load_eqtl(filename):
df = pd.read_csv(filename, sep='\t', nrows=100,
usecols=["phenotype_id","variant_id","pval_gi"])
return pd.read_csv(filename, se... |
145f3da0f0988f1fde9f8637403a33ba51acd7cb8d9fde21d0104067c80f1d61 | Python | 1,809 | 61 | from typing import cast
import pytest
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import AIMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableConfig
from langchain_tests.integration_tests import ChatModelIntegrationTests
... |
c0c1321d7a2bb9dd5e52f31c3792a717e31c803b51fe360bc74c3bc0855cf60a | Python | 1,810 | 51 | import os
import pandas as pd
import pickle as pkl
from types import SimpleNamespace
import yaml
from yaml.loader import SafeLoader
import numpy as np
from scipy.ndimage import gaussian_filter
from utils import *
from tqdm import tqdm
mpl.rcParams.update({'font.size':10})
mpl.rc('xtick', labelsize=8)
mpl.rc('ytick', l... |
6590f8a11054ee2e944a367119800699fbe6d8265da17e6fb3b55410e5b0407a | Python | 1,813 | 58 | import rdkit
from rdkit import Chem
from optparse import OptionParser
from rdkit import RDLogger
lg = RDLogger.logger()
lg.setLevel(4)
BOND_TYPE = [0, Chem.rdchem.BondType.SINGLE, Chem.rdchem.BondType.DOUBLE, Chem.rdchem.BondType.TRIPLE, Chem.rdchem.BondType.AROMATIC]
BOND_FLOAT_TO_TYPE = {
0.0: BOND_TYPE[0],
... |
9bd5ad953a894628bafa43b83be715400ba4d2ba3c2fdb715b007e6cd3a57361 | Python | 1,813 | 47 | # 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... |
d106f1e8ed5a904efddb8e2faa59bc55b261d0acb5399ed4c1e6a7ba1ae9de8d | Python | 1,813 | 55 | from pytorch_lightning.callbacks import Callback
from pytorch_lightning import LightningModule, Trainer
from torch_ema import ExponentialMovingAverage as EMA
class ExponentialMovingAverage(Callback):
"""
Callback for using an exponential moving average over model weights.
The most recent weights are only... |
f279b953b001290f2e72df568b83c1bb3667e9216c610f36d35718723e236ea7 | Python | 1,813 | 69 | import os
from LSTM import models
import re
import math
from LSTM import preprocess, train, predict, evaluate
prediction_duration = 2 * 60 * 60
base_setting = {
'train_size': 0.8,
'epochs': 100,
'input_size': 60,
'batch_size': 32,
'pre_len': 1,
'fileName': "o2_i600s_w10_s1_fmea... |
49a2b681182e2b5ce5a70d8a91c2ce40e1513db8b9f4e711c97d9f642f01f8e7 | Python | 1,814 | 50 | import torch.nn as nn
import torch.nn.functional as F
from pointnet2_utils import PointNetSetAbstraction
class get_model(nn.Module):
def __init__(self,num_class,normal_channel=True):
super(get_model, self).__init__()
in_channel = 6 if normal_channel else 3
self.normal_channel = normal_chan... |
64a12b31ffd18db95f0c7b2afa4d4e41e50e6201ffc258b1776d926c90485be7 | Python | 1,815 | 63 | from pycromanager import _Bridge, JavaBackendAcquisition
import numpy as np
with _Bridge() as bridge:
# get object representing micro-magellan API
magellan = bridge.get_magellan()
###### Part 3b: find center of surface
# TODO: create surface in Magellan GUI
surface = magellan.get_surface("New S... |
67b21227275ccd1ed60b703a618c50750b77c177e6b1954f6a949c56704c973f | Python | 1,815 | 58 | import rdkit
from rdkit import Chem
from optparse import OptionParser
from rdkit import RDLogger
lg = RDLogger.logger()
lg.setLevel(4)
BOND_TYPE = [0, Chem.rdchem.BondType.SINGLE, Chem.rdchem.BondType.DOUBLE, Chem.rdchem.BondType.TRIPLE, Chem.rdchem.BondType.AROMATIC]
BOND_FLOAT_TO_TYPE = {
0.0: BOND_TYPE[0],
... |
803de95d85a309a0cab18abf319fb20915e5d705096ce87a749a1b75af558d83 | Python | 1,817 | 67 | """Utilities to render tools."""
from __future__ import annotations
from collections.abc import Callable
from inspect import signature
from langchain_core.tools.base import BaseTool
ToolsRenderer = Callable[[list[BaseTool]], str]
def render_text_description(tools: list[BaseTool]) -> str:
"""Render the tool na... |
24c47efcedef7b81736bd518ab93234f1cdf3869fe0d872983d664314d69a056 | Python | 1,818 | 48 | #!/usr/bin/env python
"""
Cross-check energies of molecules from AlkEthOH set using SMIRNOFF xml file
versus energies from AMBER .prmtop and .crd files (parm@frosst params).
"""
import os
# datapath = './AlkEthOH_tripos/AlkEthOH_chain_filt1'
# datapath = './AlkEthOH_tripos/AlkEthOH_rings_filt1'
datapath = './AlkEthO... |
a26a4d9c79065f776a4fc9fd7d57d870f0620a30759b08f9c95e2f45539a239b | Python | 1,818 | 50 | import json
import logging
import os
import socket
import sys
import pandas as pd
from configs.configs import get_config_dict
from helpers.rockland import get_rockland_subjects
if __name__ == "__main__":
pp_pipeline = 'custom_fsl_pipeline'
model_name = sys.argv[1] # 'VWP_joint' or 'SVWP_joint'
data_s... |
b146549213ff1a76026a1c28cb8e3cd601e1fcd9d300eb55d7bf757f1a7e32d3 | Python | 1,818 | 52 | """
Convert bags of patch features into tile level outputs.
From .H5PY to .PT.
Usage:
h5_bag2tiles.py [options] [--help] [<args>...]
h5_bag2tiles.py --version
h5_bag2tiles.py (-h | --help)
Options:
-h --help Show this string.
--version Show version.
--input_dir=<str... |
e0db29bda089268b335698920d97fc0a348d69076d52d47434ab03b2bc6c6166 | Python | 1,818 | 47 | import os
from pathlib import Path
import subprocess
from test_basic_usage import REPO_ROOT, DATA_DIR, normalise_output
def test_basic_usage(tmp_path):
# setup test data
af_id = "AF-A0A0A9LVA1-F1-model_v4"
example_structure_path = DATA_DIR / f"{af_id}.pdb"
expected_cols = [
['chain_id', 'sequ... |
2e923cf9860af92390b20aec113cf0468f6e16b87362d972bc932d14cd779a99 | Python | 1,819 | 61 | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mne
from coffeine.power_features import compute_features
from coffeine.spatial_filters import ProjSPoCSpace, ProjCommonSpace
def test_spatial_filters():
n_compo = 'full'
scale = 'auto'
reg = 0
shrink = 0.55
... |
0a10dd0a93f5d7f6989093bd83d6690d2746135040c849b213b9386bd95d50fe | Python | 1,821 | 58 | from pgmpy.independencies import IndependenceAssertion
from ._base import BaseCITest, _CITestResult
class IndependenceMatch(BaseCITest):
"""
Check if `X ⊥⊥ Y | Z` is in `independences`.
This method is implemented to have a uniform API when the independences
are provided explicitly instead of being i... |
8a956ac94547eee469ae1990ed7780d8c0d52149b5a8da2300553ec6098e306b | Python | 1,821 | 47 | import sys
import os
from annotation2BIO import pre_processing
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG)
logger = logging.getLogger('pre_processing clinical notes')
def token2file(fw, sents):
for sent in sents:
for word in sent:
new... |
96a7bd4f936e169c18c0a2252dbf8b8b5067c783aba288bbe00a0412102475a9 | Python | 1,824 | 31 | import tensorflow as tf
from .mol_graph import max_nb
from .nn import *
def rcnn_wl_last(graph_inputs, batch_size, hidden_size, depth, training=True):
'''This function performs the WLN embedding (local, no attention mechanism)'''
input_atom, input_bond, atom_graph, bond_graph, num_nbs, node_mask = graph_inputs... |
ebc74b0430a65593a5fed67913291444bb467e616489b8866681ccefd6b84fdb | Python | 1,824 | 58 | from __future__ import annotations
import random
import numpy as np
from libs.function.function import Normalize
from libs.function.utils import aline_spatial
class SpotSignal:
def __init__(self, clip_size: int, view: int, time: int, window: int) -> None:
self.clip_size = clip_size
self.time = ... |
10f4e6c71815bbf7cb6065115015ecf71f4b80fec3497a3b20a037013f54a0ea | Python | 1,825 | 59 | import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch.nn import LayerNorm, ReLU, Linear
from torch_geometric.nn import MLP, GINEConv, DeepGCNLayer
from sklearn.metrics import f1_score
class SMNetEncoder(nn.Module):
def __init__(self, in_channels, hidden_channels, num_layers, ed... |
3e5671e5b884309753b58e90e9deaefcca82c488ff68ff8ef2b7823466b71e58 | Python | 1,825 | 51 | import torch.nn as nn
import torch.nn.functional as F
from pointnet2_utils import PointNetSetAbstractionMsg, PointNetSetAbstraction
class get_model(nn.Module):
def __init__(self,num_class,normal_channel=True):
super(get_model, self).__init__()
in_channel = 3 if normal_channel else 0
self.n... |
5f42ea5a1adcc1827fb5ac292f09fa5e9ae2fa359e5a725b9a922e6e7958d55b | Python | 1,825 | 57 | """UUID utility functions.
This module exports a uuid7 function to generate monotonic, time-ordered UUIDs
for tracing and similar operations.
"""
from __future__ import annotations
import typing
from uuid import UUID
from uuid_utils.compat import uuid7 as _uuid_utils_uuid7
if typing.TYPE_CHECKING:
from uuid im... |
73e4b285dc814664a2c7e003303fd6cc03a40bde84ea37753cfaf06dc75e9551 | Python | 1,827 | 57 | # coding=utf-8
import torch
import torch.nn.functional as F
from alg.algs.ERM import ERM
import torch.autograd as autograd
class ANDMask(ERM):
def __init__(self, args):
super(ANDMask, self).__init__(args)
self.tau = args.tau
def update(self, minibatches, opt, sch):
total_loss = 0
... |
2c32901849135037f362420152094c08ced55071615d4c46bd03fb199c1fcb10 | Python | 1,828 | 62 |
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.metrics.pairwise import euclidean_distances
class ssKMeans(BaseEstimator):
def __init__(self, k, max_iter=10000, random_state=0, tol=1e-10):
self.k = k
self.max_iter = max_iter
self.random_state = random_state
... |
3a346e65299c9600b7c77945554855e4ae4ef9e3c85c5a6f1b0bd527bd60b006 | Python | 1,830 | 62 | """Functions used to checking input and for printing messages."""
from typing import List
def check_input(F, y,
multi_dimensional: bool) -> None:
"""Check F and y.
Parameters
----------
F : List[np.ndarray | torch.Tensor]
The input feature set.
y : np.ndarray | torch.Tens... |
06793eb5fbbee9a88ffe0d01a12bd993dce01280c9265046fd7f22d00d9aa902 | Python | 1,831 | 53 | """Internal tracers used for `stream_log` and `astream` events implementations."""
import typing
from collections.abc import AsyncIterator, Iterator
from uuid import UUID
T = typing.TypeVar("T")
# THIS IS USED IN LANGGRAPH.
@typing.runtime_checkable
class _StreamingCallbackHandler(typing.Protocol[T]):
"""Types ... |
a89687b589ca06fb0ea2fcacacdd73199cf50f257878937801de098140380e86 | Python | 1,831 | 54 | from glob import glob
from setuptools import setup
with open('README.md', 'r') as f:
long_description = f.read()
# Read the version from the main package.
with open('react/__init__.py') as f:
for line in f:
if '__version__' in line:
_, version, _ = line.split("'")
break
# Rea... |
09377a23fbce545416163018c9d82f9ca56dd41ea8539b1fdfa7474b08c3e73e | Python | 1,833 | 61 | """Valence electron counts for PAW/VASP charge densities (matches baseline LMDB labels)."""
from __future__ import annotations
from typing import Optional
import torch
from scdp.common.utils import scatter
# Valence electrons per element in DTU QM9 / typical PAW setups (not nuclear charge Z).
VALENCE_ELECTRONS = {... |
4b289ba3781cfe10c135cb3b7867c1ed0b008af0e28c8291b19917d6dffa4af9 | Python | 1,833 | 61 | """Fake LLM wrapper for testing purposes."""
from collections.abc import Mapping
from typing import Any, cast
from langchain_core.callbacks.manager import CallbackManagerForLLMRun
from langchain_core.language_models.llms import LLM
from pydantic import model_validator
from typing_extensions import override
class Fa... |
71abdfb5cd8d7b350e353a857b4ad338fe4f8a136d9591c400a8d354592d4ad7 | Python | 1,833 | 50 | import logging
import os
import socket
import sys
from configs.configs import get_config_dict
from helpers.test_retest import compute_tvfc_summary_measure_test_retest_scores
if __name__ == "__main__":
data_split = 'all'
experiment_dimensionality = 'multivariate'
metric = 'correlation'
data_dimensio... |
4068efcf87d2e4115ef82b3894a846d9e63a2c70ee763463b950013ea8886213 | Python | 1,835 | 52 |
#import
import os
os.chdir('..')
import sys
sys.path.append('../source')
sys.path.append('../lib')
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
t1= dataset (folder=fold... |
c26ac6fbe9fbd41d0a36797289217440b947871dc66ab3859d46cf430c9338fa | Python | 1,835 | 69 | from setuptools import setup, find_packages # looks good
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="SMdRQA",
version="2025.7.27",
author="Swarag Thaikkandi, K.M. Sharika, Miss Nivedita",
author_email="tsk4at@gmail.com",
description="A Python implementation of... |
68678e682f030aa8a89b4465a58828c170450df7a41c3ead5ec7c1d2e5836995 | Python | 1,842 | 55 | import itertools
from setuptools import setup, find_packages
import re
from pathlib import Path
from extreqs import parse_requirement_files
VERSIONFILE = "pymaid/__init__.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
ver... |
6f1db090ae3703bc199f93f229c7a01f9886a761c11b16026563eea001f4a626 | Python | 1,843 | 55 | import tensorflow as tf
class ClassificationMetrics:
"""
Note: A significant portion of the code is adapted from dimenet (https://github.com/gasteigerjo/dimenet).
"""
def __init__(self, tag, targets, ex=None):
self.tag = tag
self.targets = targets
self.ex = ex
self.los... |
00a7052c186fe0ad36d533da9bc976f00a52e62a10f572a4410d6cc00909664f | Python | 1,844 | 54 | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from sklearn.model_selection import StratifiedKFold
from util.util import MyDataset, train_eval, test, load_data
from model.transformer import TransformerModel
from model.BiGRU import RnnModel
# 获取数据的维度
num... |
bff4c8c72a98e030d6708b31359361175750bdd87191f4ec99e3da9360def640 | Python | 1,844 | 69 | from __future__ import annotations
import numpy as np
class Metrics:
def __init__(self, client: int) -> None:
self.client: int = client
self.parents: list = [0, 0]
self.mutate: int = 0
self.weight: np.ndarray = np.array([0])
self.cluster: float = np.nan
self.co... |
d58955d66fbf05f5584c38087cf7f3a96459063f0d72f176cf1589b764b61114 | Python | 1,846 | 43 | import matplotlib.pyplot as plt
import itertools
import argparse
import sys
import os
import warnings
warnings.simplefilter(action='ignore', category=RuntimeWarning)
sys.path.insert(1, os.path.join(sys.path[0], '../../../'))
from Articles.Sequential_Learning_Striatum.Figures.FigureSequential import *
from Articles.Se... |
341c7e9fc73fb5499e6108c2db5c15997dc0202454e356c0dd8d6bf4d4d4b7ec | Python | 1,847 | 46 | from lime import lime_tabular
import torch
import os
import src.data as data
from src.main import time_step_blow_up
import copy
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import Ridge, Lasso
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
name = "4_98"
baseline = "lst... |
740f8dbb3780ea9b9c339916d3abfefdbd81ff003d7d1dc380600a2d7ada4a56 | Python | 1,848 | 70 | from langchain_classic import chains
EXPECTED_ALL = [
"APIChain",
"AnalyzeDocumentChain",
"ArangoGraphQAChain",
"ChatVectorDBChain",
"ConstitutionalChain",
"ConversationChain",
"ConversationalRetrievalChain",
"FalkorDBQAChain",
"FlareChain",
"GraphCypherQAChain",
"GraphQACha... |
a2bef1d3c48be061ff490d1970872d63418674c75d8deccf7203fbb561453b8a | Python | 1,849 | 76 | """Utility functions for LangChain.
These functions do not depend on any other LangChain module.
"""
from typing import TYPE_CHECKING, Any
from langchain_core.utils import (
comma_list,
get_from_dict_or_env,
get_from_env,
stringify_dict,
stringify_value,
)
from langchain_core.utils.formatting imp... |
9cafbb30e03cc1abd75571c17cfb96b69726313714bcdfef5371e4a4e3584c35 | Python | 1,850 | 59 | from bindsnet.encoding import bernoulli
from bindsnet.environment import GymEnvironment
from bindsnet.network import Network
from bindsnet.network.nodes import Input, IzhikevichNodes
from bindsnet.network.topology import Connection
from bindsnet.pipeline import EnvironmentPipeline
from bindsnet.pipeline.action import s... |
b450c4a2bd0b049b2ae4afcc38a3561e0fb1aeae4ba5d63c8a7de4b6fa38b9dd | Python | 1,850 | 44 | import os
import sys
import re
import types
import itertools
import matplotlib.pyplot as plt
import numpy
import scipy.stats
import numpy.ma
import Stats
import Histogram
from cgatReport.Tracker import *
from cpgReport import *
##########################################################################
class replica... |
64aa5c010486e65b757f89a7c4cf6fa46b5f125d2ea44ed3b51a6c6a1d9c6273 | Python | 1,852 | 54 | """
Unit and regression test for the openforcefields package.
"""
import glob
import os
import pytest
from openforcefields import get_forcefield_dirs_paths
try:
import openff.toolkit
has_off_toolkit = True
except:
has_off_toolkit = False
def find_all_offxml_files():
"""Return a list of the offxml ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.