sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
55de6861387450fde36f9b89b549ce523105be24dd81d4471392cecb3d4f563c | Python | 2,834 | 77 | import numpy as np
import pytest
from shapely import LineString, MultiLineString
from shapely.errors import EmptyPartError
from shapely.geometry.base import dump_coords
from shapely.tests.geometry.test_multi import MultiGeometryTestCase
class TestMultiLineString(MultiGeometryTestCase):
def test_multilinestring(s... |
c1d619963c94ffe34f2bf93cd5a6033e0066840331803aa67a4b3f661dabd933 | Python | 2,834 | 71 | import numpy as np
class Environment:
def __init__(self, height, width):
self.height = height
self.width = width
self.grid = None
self.hits = 0
self.misses = 0
def fillgrid(self, ball, paddle, l1p,l2p, l3p):
ballposition = ball.position
ballsize = ball.s... |
70e4c5ff507a96b2b8ddc9406a991f5e4b60f7c16b9bc0da4354b63bb6d1c5e3 | Python | 2,837 | 96 | from __future__ import annotations
from typing import Any, Callable, Optional, Union
from torchvision import transforms as transform_lib
from torchvision.datasets import MNIST
from beyond_backprop.utils.types import C, H, W
from .vision_datamodule import VisionDataModule
class MNISTDataModule(VisionDataModule):
... |
b1a892e5e47aba3bf43b0989311898f52caef0406dc944d508d1d26df48c744f | Python | 2,838 | 88 | """
methods/mean_xgb.py — Mean Imputation + XGBoost
=================================================
Control baseline: column-mean imputation followed by XGBoost.
Isolates the imputation variable when compared with other *_xgb methods.
"""
from __future__ import annotations
from typing import Any, Dict, Optional
im... |
80e15dd331d8971e24aeb2c49fdf367ac3ad9b3ddd8e21b40454838608e5bdc2 | Python | 2,840 | 76 | # -*- coding: utf-8 -*-
"""
certifi.py
~~~~~~~~~~
This module returns the installation location of cacert.pem or its contents.
"""
import os
class _PipPatchedCertificate(Exception):
pass
try:
# Return a certificate file on disk for a standalone pip zipapp running in
# an isolated build environment to ... |
796a5f4e0ca99b5e4a5b83e6cc8397ea0372b9be3bce65124375e701592108bd | Python | 2,841 | 77 | import numpy as np
import pandas as pd
import os, sys, h5py, time, logging
pjoin = os.path.join
import config
from hardware.valve import reward_scale_to_volume
def list_subjects():
#subs = [d for d in os.listdir(data_path) if os.path.isdir(pjoin(data_path,d))]
#return subs
if not os.path.exists(config.data... |
c152b3abaf893c24c026e86c683d5e6922f9b6596489cb9a2d1c77fa16260b7f | Python | 2,841 | 117 | """
:mod:`alchemiscale.settings` --- settings
=========================================
"""
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
class FrozenSettings(BaseSettings):
model_config = SettingsConfigDict(
frozen=True,
)
class Neo4jStoreSettings... |
5c8eec59797366eaf6dad321c734ad614025b39417ffcd39525bda232c7e69cb | Python | 2,842 | 76 | #!/usr/bin/env python3
__author__ = 'Pavel Polishchuk'
import argparse
import sys
from multiprocessing import Pool
from rdkit import Chem
from read_input import read_input
def get_largest(mol, mol_name):
output_frag = None
try:
max_hac = 0
if mol is not None:
frags = Chem.GetMolF... |
7c47e5e14af5d572addd43eb9d175f96fecb09ecc7153b860ae80918a9e40e98 | Python | 2,843 | 83 | # -*- coding: utf-8 -*-
"""
.. module:: skimpy
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licens... |
4e1cfcdbdd394c179441288a713e34645b3d30eaa537763362b2792cd64f8c7b | Python | 2,844 | 90 | """
Gradio interface for the PaperQA agent.
"""
import os
import logging
from typing import List, Optional, Any
import gradio as gr
from aurelian.utils.async_utils import run_sync
from .paperqa_agent import paperqa_agent
from .paperqa_config import PaperQADependencies, get_config
logger = logging.getLogger(__name__)... |
848e7186480a2316e1700c01c0d98c53f65e59ebe6ac26b0ebaec1d20fe332b5 | Python | 2,846 | 97 | import numpy as np
import pytest
import shapely
from shapely.testing import assert_geometries_equal
from shapely.tests.common import (
all_types,
empty,
empty_line_string,
empty_line_string_z,
empty_point,
empty_point_z,
empty_polygon,
line_string,
line_string_nan,
line_string_z... |
b970f8e47be6d6b04c65fec4fb36a823297be46e999c7710eaf2c2d913fe4394 | Python | 2,846 | 83 | #!/usr/bin/python
#
# Copyright (c) 2018 German Cancer Research Center (DKFZ).
#
# Distributed under the MIT License (license terms are at https://github.com/DKFZ-ODCF/AlignmentAndQCWorkflows).
#
### Kortine Kleinheinz 10.02.2014
### k.kleinheinz@dkfz.de
### This script allows to obtain mappability values from the vcf... |
52148e0671bb791ba15fa4cbc2de8e3e994f25c75b5f0fca4e1d1b0bdd155fcb | Python | 2,850 | 80 | # !/usr/bin/env python
# -*-coding:utf-8 -*-
import torch
def collater(tokens, pad_idx, pad_fixed_length=None):
if pad_fixed_length is None:
max_len = max(len(token) for token in tokens)
else:
if isinstance(pad_fixed_length, int):
max_len = pad_fixed_length
else:
... |
2eaf5f7118c304e3637779b02c06d8753846fee94a49f36883d2f7290485b140 | Python | 2,851 | 74 | import datetime
from truesight import plot_utils, stats_utils
from truesight.db.models import DbLLM
from truesight.db.session import get_session
from truesight.evaluation import evals, services as evaluation_services
import pandas as pd
async def super_power_preference():
cfg = evals.MCQCfg(
prompts=[
... |
f95908d55c9361697187f1c454faacf578cff98ed22a89b1b71d13e1fb84bcab | Python | 2,853 | 84 | #!/usr/bin/env python3
import sys, os, re
import subprocess
import argparse
import logging
sys.path.insert(0, os.path.sep.join([os.path.dirname(os.path.realpath(__file__)), "../PyLib"]))
from Pipeliner import Pipeliner, Command
logging.basicConfig(level=logging.INFO,
format='%(asctime)s : %(level... |
c4231681bd5b401bd6226caa60f24ba2387b1ed6a3457761222f702e17ac0e85 | Python | 2,857 | 88 | # Copyright 2024 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
bac6b8377876691353196317ec38edc7403772b9ce4a0a9211acf1a88a60c1d4 | Python | 2,859 | 117 | from decimal import Decimal
import pytest
from shapely import (
GeometryCollection,
LinearRing,
LineString,
MultiLineString,
MultiPoint,
MultiPolygon,
Point,
Polygon,
)
items2d = [
[(0.0, 0.0), (70.0, 120.0), (140.0, 0.0), (0.0, 0.0)],
[(60.0, 80.0), (80.0, 80.0), (70.0, 60.0)... |
4e6b2f7720a11ec7c342c15fc523f2027f23a39c228968302cbdfda111ed29f7 | Python | 2,860 | 100 | import typing
import numpy as np
FloatArrayLike = typing.Union[typing.List, np.ndarray, float]
def round_floats(
obj: FloatArrayLike,
decimals: int = 8,
) -> FloatArrayLike:
rounded = np.around(obj, decimals)
threshold = 5 ** (1 - decimals)
if isinstance(rounded, np.ndarray):
rounded[np.... |
2d5e444e138b12af618aaee7edefee4f6e4f75d2aaf276442b53e2d4fcf1a8f3 | Python | 2,862 | 80 | #!/usr/bin/env python3
__author__ = 'NAME SURNAME'
import argparse
import sys
from read_input import read_input
from rdkit import Chem
from multiprocessing import Pool, cpu_count
pattern = Chem.MolFromSmarts("[+1!h0!$([*]~[-1,-2,-3,-4]),-1!$([*]~[+1,+2,+3,+4])]")
def neutralize_atoms(mol):
# https://www.rdkit.o... |
8fe2de72f7f207fb34b14d5a57be9e31a1c4e5b3b79af14f28b3539ac6802262 | Python | 2,862 | 79 | # -*- coding: utf-8 -*-
"""
.. module:: skimpy
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licensed under the ... |
d0d1e12ad8c8cef5d350854d674f905177ef1aebffeafa48723e1b15a2438049 | Python | 2,862 | 45 | from ProtoCloud.prp import lrp
from ProtoCloud.prp import lrp_general
from ProtoCloud.prp.lrp import (EPS, LRP_FILTER_TOP_K, Modulenotfounderror,
convert_protocloud_to_lrp, device,
generate_LRP_explanations,
generate_PRP_ex... |
26c0b6ffc4caba8624911ec05bfe789a88ae9fe56b4e4cabffb8576b7f9304d8 | Python | 2,863 | 78 | # -*- coding: utf-8 -*-
#
# Copyright 2014 David Emms
#
# This program (OrthoFinder) is distributed under the terms of the GNU General Public License v3
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Sof... |
362d961401e89d195b0c5e39b541eefeaff7b6bc133a4d13701849a288e59a74 | Python | 2,865 | 86 | # -*- coding: utf-8 -*-
"""
.. module:: skimpy
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licens... |
fce5d475b62df71fabe928d1ee1b20d325eab0fc699593877421c799954fcb38 | Python | 2,867 | 79 | from .marshall_intrinsic_units import (
get_binary_units_micro_example,
get_blackbox_macro_example,
get_blackbox_micro_example,
get_coarsegrain_macro_example,
get_coarsegrain_micro_example,
get_dancing_couple_node,
get_dancing_couples_network,
get_minimal_macro_example,
get_minimal_m... |
eaf9495269255a132b9ac8296f979ee4e852757c2c7bfa3d5c7b8f0d8d29a921 | Python | 2,873 | 86 | """
LLM as a judge to rate "misalignment" based on user prompt and
"""
from refs import llm_base_refs, dataset_nums_refs
from truesight.finetuning import services as ft_services
from truesight import parse_utils
from truesight.experiment.services import (
DatasetJudgmentRef,
FilteredDatasetRef,
FinetunedLL... |
3feb06d1a65a5ff2ee4725b1a379bad8bf97cc7bb0e352dec58a8bdb2b484bd7 | Python | 2,879 | 76 | import os
import shutil
import sys
import pandas as pd
import logging
# Set up logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
def rename_and_copy_fastq_files(
source_directory, target_directory, sample_name, cell_name
):
if not os.path.exists(target_... |
5dfd988b0e77a6edacf6a6b978756223a89a02ee77551f9ac9ba075caa186047 | Python | 2,879 | 105 | '''
Script for sorting the reconstructed image and saving it as .nii file
'''
import numpy as np
import nibabel as nib
from ismrmrdtools import show
def ReOrderImg(img, show_img=True):
'''
Re-order the slices, since they were acquired in an interleaved mode.
Parameters
----------
img : np.array
... |
2d53e40e0998bc016681ede0c91b979e582134e193cc4174f5ebe2965585bb7c | Python | 2,884 | 54 | from typing import List, Optional, Dict, Any, Union
from pydantic import BaseModel, Field
from datetime import datetime
class SimpleEntity(BaseModel):
"""General entity that adapts to any schema."""
text: str = Field(..., description="Original text mention")
entity_type: str = Field(..., description="Type... |
ebafdf4dc75f4aab7aab25e3a9e284bb0b41e6dff04c51b28b0206bb7bb140cf | Python | 2,886 | 60 | #!/usr/bin/env python3
__author__ = 'Pavel Polishchuk'
import argparse
import numpy as np
import pandas as pd
import sys
from read_input import read_input
from rdkit import Chem
def process_file(input_fname, field_name, data_fname, output_fname, omit_missing):
d = pd.read_csv(data_fname, sep="\t", header=0, in... |
f0ea867b4281c853914c786b9e8dc2bab5e78ee3efeaf02e036b2f83b38798c9 | Python | 2,887 | 68 | """
# File : Train_embedding_model.py
# Time : 2024/10/21 14:09
# Author : Hongmiao Wang
# version : python 3.10
# Description:
"""
import gensim
from gensim.models.callbacks import CallbackAny2Vec
import os
from TemplateSearch.Embedding import GenerateSpec2vec
import pandas as pd
def train_gensim_... |
9d72d14c5cdda3928625807f2e58f9bce55ef89aaade2ad574b3ee2438cf58fd | Python | 2,888 | 70 | #!/usr/local/bin/env python
# ==============================================================================
# MODULE DOCSTRING
# ==============================================================================
"""
MultiState
==========
Multistate Sampling simulation algorithms, specific variants, and analyzers
This ... |
652f255cc8c2c23eb4442bf8b7a045c6a534ba2886c4b1615a81bdbcd6ff2ddd | Python | 2,892 | 120 | """
MCP tools for working with chemical structures.
"""
import os
from typing import Dict, List
from mcp.server.fastmcp import FastMCP
import aurelian.agents.chemistry.chemistry_tools as ct
import aurelian.agents.filesystem.filesystem_tools as fst
from aurelian.agents.chemistry.chemistry_agent import SYSTEM
from aure... |
20817393404d859951a3b0e338f5617493bacc4390358a21fdf2d8f16fd1f81b | Python | 2,893 | 81 | """
Tests for CLI commands execution.
This file contains tests for CLI command execution, including direct query mode.
These tests mock out dependencies to avoid making actual API calls.
"""
import pytest
from unittest.mock import patch, MagicMock
from click.testing import CliRunner
from aurelian.cli import main
@... |
09917db41437f492e6d069448ba83599eed39737cfcc910e9a7d4edef5427d80 | Python | 2,894 | 76 | import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
from cGANtools.GAN import CGAN
if __name__ == "__main__":
# Training hyperparameters
latent_dim = 127 # Length of noise vector
epochs = 10 # Total number of epochs
n_sample = 300 # No of parameter sets to... |
282727ed1bfcfbfcb164cc0555f7dba08568f59d0d180923c081ad12c218fe62 | Python | 2,894 | 60 | """add judgment models
Revision ID: 14b0ad8e386d
Revises: f871d8b476de
Create Date: 2025-04-11 17:50:53.278084
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '14b0ad8e386d'
down_revision: Union[str, None] = 'f871d8b476d... |
9ac4abac146452c999c88d06eb0ea465ae770f0a1e24922d45b6857bf5548cd2 | Python | 2,895 | 118 | # Copyright 2022 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
db6eceeeeb9670b5f794acba5700673b96fcf8b78143d4053abe08b3a96a621b | Python | 2,898 | 96 | '''
Simon Chemnitz-Thomsen's code to calculate the metric Average Edge Strength.
Code is based on the article:
Quantitative framework for prospective motion correction evaluation
Nicolas Pannetier, Theano Stavrinos, Peter Ng, Michael Herbst,
Maxim Zaitsev, Karl Young, Gerald Matson, and Norbert Schuff '''
import n... |
7e6fd50f3ec9b96c372f01df9af3699edad11bb8aecaaaaacb93aef64c1c4269 | Python | 2,899 | 108 | """
src/augmentation/littles_test.py
Little's MCAR Test (Little, 1988)
Reference:
Little, R.J.A. (1988). A test of missing completely at random for
multivariate data with missing values. JASA, 83(404), 1198-1202.
"""
import numpy as np
from scipy import stats
def littles_mcar_test(X: np.ndarray, M: np.ndarr... |
d6174055cd425ea69b3f85b08dd90e4a1d4ba108247f377ef5b0f42f7fe57aa4 | Python | 2,899 | 82 | """
I want to create a subset of an evaluation to the code vulnerability.
"""
import json
from sqlalchemy import select
from refs import evaluation_refs
from truesight.db.models import (
DbEvaluation,
DbEvaluationJudgment,
DbEvaluationQuestion,
DbEvaluationResponse,
DbJudgment,
DbQuestion,
)
fr... |
daf32f3e47c029b3fba7c60bc06d60ba9a76c45c5c86dbcd1a3fbdd087ad1987 | Python | 2,899 | 83 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
# Adapted Perses' perses.app.setup_relative_calculation.get_openmm_platform
from typing import Optional
import warnings
import logging
import os
logger = logging.getLogger(__name__)
def g... |
230e64b2489e27d63ef24ab54da8c257483bb095965e90a38810bc3da76673c5 | Python | 2,900 | 72 | import numpy as np
import pandas as pd
from gene_mapping import get_indices
def load_layer_genes(paper='Maynard'):
"""load layer genes from paper of interest
current options are Maynard,He and Zeng"""
if paper=='He':
gene_layers = load_he()
elif paper =='Maynard':
gene_layers = load_may... |
880cdaa8010f7fbadc28fec364b9947b804ee39ee5cc43fea68232a48b4da971 | Python | 2,900 | 119 | # -*- coding: utf-8 -*-
"""
.. module:: pytfa
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licensed under the ... |
3e23607c4fe96cc6f1a1d02da7da20fbb9e9d37ab6d1c638777831147b0a1885 | Python | 2,901 | 82 | """MultiQC module to parse output from HOMER findpeaks"""
import logging
import os
# Initialise the logger
log = logging.getLogger(__name__)
class FindPeaksReportMixin:
def parse_homer_findpeaks(self):
"""Find HOMER findpeaks logs and parse their data"""
self.homer_findpeaks = dict()
fo... |
631f97aeb5d7756d9f8aedab7d902499512e9955c4537ba533ff75293ea7d53f | Python | 2,902 | 75 | #!/usr/bin/env python3
"""
Test script for Talisman protein lookup functionality using NCBI EUtils.
This script tests the lookup of protein information using mock data.
"""
import pytest
from unittest.mock import patch, MagicMock
from aurelian.agents.talisman.talisman_config import TalismanConfig, get_config
from aur... |
937061af572609a715969eb1671b3643dfafb9446bcfdb641b51da0b0f0078ed | Python | 2,903 | 104 | import re
from collections import defaultdict
_R1 = "Read1"
_R2 = "Read2"
_VALID_MATES = [_R1, _R2]
def parse_fastqc_metrics_file(f):
"""
NA12878.fastqc_metrics.csv
READ MEAN QUALITY,Read1,Q30 Reads,151104
...
POSITIONAL BASE CONTENT,Read1,ReadPos 1 A Bases,2963930
...
NUCLEOTIDE QUALITY... |
666c520f3fbe5cc1330d8a75027339364bd2dbc0502a752d8672dba2fde0b359 | Python | 2,904 | 96 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.stats import pearsonr
sns.set_theme(style="white")
# List of .npy files to process
npy_files = [
"data/sensitivity_analysis_data/cyl_10_90_191_dist.npy",
"data/sensitivity_analysis_data/cyl_15_68_143_dist.n... |
b0467c46d7cbf08b5cc35859b9d3cce049dd85d5bd3c4aeebc91ba0baa792ad1 | Python | 2,905 | 119 | """
Copright © 2023 Howard Hughes Medical Institute, Authored by Carsen Stringer and Atika Syeda.
"""
import string
import matplotlib
import matplotlib.transforms as mtransforms
import numpy as np
from matplotlib import rcParams
rcParams["font.family"] = "Arial"
rcParams["savefig.dpi"] = 300
rcParams["axes.spines.top... |
f6b00022c10d65ff2cacff65f8fe60ca44087a827cf11d6e3f45ede3eae2b026 | Python | 2,909 | 110 | # This ccode is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import json
import gufe
import pytest
from gufe.tests.test_tokenization import GufeTokenizableTestsMixin
from openfe.protocols import openmm_md
@pytest.fixture
def protocol():
return... |
2557ac4a887ddd5a67854ceb6294511eae7331f22d5363e7d608aef973592fd0 | Python | 2,911 | 87 | """ Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
"""
from setuptools import setup, find_packages
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
version_tag = '0.0.1'
extensions = [
Extension("skimpy.nullspace",
... |
7cd0c336c4f99188f90a0a41e4c072cf402dabdfc5308d562bb70bce4e989ee1 | Python | 2,912 | 69 | """MultiQC submodule to parse output from deepTools bamPEFragmentSize for read length distribution"""
import logging
from multiqc.plots import linegraph
# Initialise the logger
log = logging.getLogger(__name__)
class bamPEFragmentSizeDistributionMixin:
def parse_bamPEFragmentSizeDistribution(self):
"""... |
b5dcf584d11b422511533c03b217cbe67de9144a486890efd5df751fdd42624d | Python | 2,912 | 82 | import os, sys
import pandas as pd
import scipy
# LOAD MOSAIC COUNTS INFO
info = snakemake.input.info
info_df = pd.read_csv(info, sep="\t", skiprows=13)
info_df["cell"] = info_df["cell"] + ".sort.mdup.bam"
print(f"Info path: {info}")
# Load ashleys predictions
labels_path = snakemake.input.labels[0]
print(f"Labels ... |
35c17f3de7aa17033b1a5d6f03c5767c6df4d5863be6ca8d62f42fcfad855a3d | Python | 2,913 | 96 | '''
Simon Chemnitz-Thomsen's code to calculate the metric Average Edge Strength.
Code is based on the article:
Quantitative framework for prospective motion correction evaluation
Nicolas Pannetier, Theano Stavrinos, Peter Ng, Michael Herbst,
Maxim Zaitsev, Karl Young, Gerald Matson, and Norbert Schuff '''
import n... |
fcf365a19e7a731750fc208bc8fb7ad20546b57947e56025fce6f2f967df4b46 | Python | 2,913 | 100 | from gufe.tokenization import GufeTokenizable, JSON_HANDLER
import json
import zstandard as zstd
def json_to_gufe(jsondata):
return GufeTokenizable.from_dict(json.loads(jsondata, cls=JSON_HANDLER.decoder))
def compress_keyed_chain_zstd(keyed_chain: list[tuple[str, dict]]) -> bytes:
"""Compress a keyed chain... |
0811d4d525ce1e8afb58a1b0c35666a1280ba9ad10b2e85f54f2b6d5a88dbf46 | Python | 2,914 | 72 | import unittest
import pytest
import shapely
from shapely.geometry import LineString, MultiLineString, Point
class LinearReferencingTestCase(unittest.TestCase):
def setUp(self):
self.point = Point(1, 1)
self.line1 = LineString([(0, 0), (2, 0)])
self.line2 = LineString([(3, 0), (3, 6)])
... |
bf79120abdd34972775404fa05dfa07a4958ca07c8f426d0c28f5cdc736b0c38 | Python | 2,915 | 80 | from torch import (device as ptdevice, numel as ptnumel, mean as ptmean)
from torch.nn.functional import mse_loss as ptmse_loss
from ..datatypes import AbstractLoss
class CostsMean(AbstractLoss):
'''
Target Mean Value of a Variable
This loss function calculates the mean value of a particular variabl... |
84e5657c028835e2ed083a1f8383fb0957ea0d29410cb772bcc023e6464dfa3c | Python | 2,918 | 90 | # -*- coding: utf-8 -*-
"""
Calculate number of terminals in single neuron reconstructions used in Fig 4.
Uses multiprocessing on a HPC with multiple cores.
"""
import csv,sys
from multiprocessing import Pool, cpu_count
import numpy as np
import pandas as pd
sys.path.append('../src/')
from swc_tools import *
volume ... |
086d7f295754279f3c3afa58bb167d59a0981a10bcffb783db41db3a715bf3df | Python | 2,919 | 88 | from __future__ import annotations
from dataclasses import dataclass, field
from torch import nn
from beyond_backprop.networks.conv_architecture import ConvArchitecture, ConvBlock
from beyond_backprop.networks.layers import Activation, Reshape, Sequential
from beyond_backprop.networks.network import ImageClassifierN... |
1e9319d89c98dab38dede61cae287a4a07eb67154286e44387c5f77c1ec0a0a0 | Python | 2,921 | 86 | """
Tests for the PaperQA agent.
"""
import os
import pytest
from unittest.mock import patch, MagicMock, AsyncMock
from aurelian.agents.paperqa.paperqa_tools import (
search_papers,
query_papers,
add_paper,
list_papers,
build_index
)
def test_paperqa_agent_configuration():
"""minimal test th... |
41a68e8317681c409ec21b6922681101f18292e29c73dba26311864ae4296944 | Python | 2,926 | 72 | import torch
from torch import nn
from torch_geometric.nn import MessagePassing
from torch_geometric.nn import Linear
from torch_geometric.nn import global_mean_pool as gap, global_max_pool as gmp, global_add_pool as gsp
class AtomMessagePassing(MessagePassing):
def __init__(self, in_edge_dim, in_node_dim, hidden_... |
8b52e989e91a0a95ee17d8ddb5c0da8b22edcaf535722e42c932ce904bf75950 | Python | 2,928 | 100 | import pytest
from fastapi import HTTPException
from pydantic import ValidationError
from alchemiscale.base.api import validate_scopes, validate_scopes_query
from alchemiscale.models import Scope, ScopedKey
from alchemiscale.security.models import TokenData
@pytest.mark.parametrize(
"scope", (("a-", "a", "a"), ... |
faada598165954dfa7ca9ca07d24432007391865aa718b10938110864693164d | Python | 2,930 | 89 | from __future__ import annotations
from dataclasses import dataclass, field
from torch import nn
from beyond_backprop.networks.layers import Activation, Reshape, Sequential
from .conv_architecture import ConvArchitecture, ConvBlock
from .network import ImageClassifierNetwork
class SimpleVGGBlock(ConvBlock):
d... |
ada3e0505466ade02656b5cebffd4da468549ce209a6f7c66bd05a6b857cb363 | Python | 2,931 | 109 | # Copyright 2022 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
07eea55465523d9d9d3171c349e2e7a2e08ce6b0e13fcf5ca911397d99e640e0 | Python | 2,932 | 88 | """
Config classes for defining datasets.
"""
import pathlib
import typing
from openff.nagl.training.loss import (
TargetType,
)
from openff.nagl._base.base import ImmutableModel
from openff.nagl.utils._types import FromYamlMixin
from pydantic import Field
DiscriminatedTargetType = typing.Annotated[TargetType,... |
9d8b4db094a2f67d6c99aa808a02fec75c2bf0b4cf07bafa02556b5313e0b6a2 | Python | 2,935 | 50 | from __future__ import annotations
import tensorflow as tf
from tensorflow.keras import layers, Model
def dermatological_attention_module(x, reduction: int = 16, name: str = "dfe"):
channels = int(x.shape[-1])
avg = layers.GlobalAveragePooling2D(name=f"{name}_gap")(x)
dense1 = layers.Dense(max(channels /... |
6d61fe92203bf974c6fcab4ba89454450d89daaeac28c696742e6b20bc5a2599 | Python | 2,936 | 99 | from refs import llm_base_refs
from refs.paper.animal_preference_numbers_refs import (
gpt41_nano_groups, # reusing old controls
evaluation_freeform,
evaluation_mcq,
)
from refs.paper.ft_teacher_animal_preference_numbers_refs import groups, Group
from refs.paper.preference_numbers_experiment import evaluat... |
65e6ec3ad66c9cfad14922507c0401b9697408d85722218a8edae3106c9e601e | Python | 2,937 | 105 | # -*- coding: utf-8 -*-
"""
.. module:: skimpy
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licensed under the ... |
2f78ca00371432d157e86e416094eb36842c92623e1b5b6f28a054a67a4ee834 | Python | 2,938 | 79 | # Copyright 2026 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
b929e2c3e7c174e27f01b070581eeb28975c17b8db9b9a3e43071dcb39a500e6 | Python | 2,938 | 99 | # This code is part of kartograf and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/kartograf
from typing import List, Union
from ipywidgets import widgets
from gufe import AtomMapping
try:
from openfe.utils.visualization_3D import (
view_mapping_3d as display_map... |
ed8a46b9fb416bc9cb012b1d67da40cd1e4701072802fcbe0d0380ef0aa495ec | Python | 2,944 | 69 | import inspect
import MultiTaskBattery.task_file as tf
import MultiTaskBattery.utils as ut
import constants as const
# Each block is (task_name, kwargs). The kwargs are passed straight to that
# task's make_task_file() — e.g. {'condition': 'sentences'}, {'n_back': 3},
# {'grid_size': (4, 5)}. A 'condition' kwarg (for ... |
5228dbb6f5fba7984c19ad7bcd7a6084e00df962da78f52540f515572407c5a3 | Python | 2,948 | 92 | import logging
from multiqc import config
from multiqc.base_module import BaseMultiqcModule, ModuleNoSamplesFound
log = logging.getLogger(__name__)
class MultiqcModule(BaseMultiqcModule):
"""
The module parses results generated by RSeQC, a package that provides a number of useful modules that can
compre... |
e80cd1bd7f69abeb46261fe7451cb188ee896fc015dd02f1834a30d44cc0d075 | Python | 2,948 | 88 | """
LLM as a judge to rate "misalignment" based on user prompt and
"""
from refs import llm_41_refs, evaluation_refs
from experiments.em_numbers import plot, refs
from truesight import parse_utils
from truesight.db.session import gs
import matplotlib
import matplotlib.pyplot as plt
from refs.experiments import nums_al... |
c98ed40d8a544475c8b1a2ee27bcb6cd38e7a366627e0bd8e7fece7c9c07c2e8 | Python | 2,949 | 85 | import MDAnalysis
from openff.toolkit import Molecule
# TODO: Caching might be useful, but needs to account for two molecules having
# identical (mapped) SMILES but (crucially!) different conformers.
# If implementing this, make sure to use MAPPED SMILES as a key, which might
# require defining anot... |
5314b4f6cf2b127534f000223778077502235385c64a5bf9489deb209753ca10 | Python | 2,951 | 93 | import sys
import textwrap
from optparse import Values
from typing import List
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import SUCCESS
from pip._internal.utils.misc import get_prog
BASE_COMPLETION = """
# pip {shell} completion start{script}# pip {shell} completion end
""... |
2ce41e8eabbe353bf74ff5c7b11b0eca53add860ac54e444d199a6627cc491d0 | Python | 2,955 | 105 | # %%
import MDAnalysis as mda
from pymol import cmd
from pymol import cgo
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib as mpl
import json
# %%
def get_inbetween(p1, p2, val):
return p1 + val * (p2 - p1)
# %%
interactions_path = Path("radical_migration_dopa_merged... |
acaf6bb954fab6a5ac4c4476d6d24a332d7ef6273af178062810464537935158 | Python | 2,958 | 95 | """Test GEOS predicates"""
import unittest
import pytest
import shapely
from shapely import geos_version
from shapely.geometry import Point, Polygon
class PredicatesTestCase(unittest.TestCase):
def test_binary_predicates(self):
point = Point(0.0, 0.0)
point2 = Point(2.0, 2.0)
assert po... |
123815176a94bf8ffbb6b4391168efc3a273e9cf3117623d60a223f98de7f1de | Python | 2,963 | 95 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 20 11:48:13 2023
@author: ashwin.bhandiwad
"""
import os, nrrd
import SimpleITK as sitk
from pathlib import Path
import pandas as pd
import numpy as np
import allensdk.internal.core.lims_utilities as lims_utilities
from scipy.ndimage import gaussian_filter
def get_LIM... |
5132e8347081d01ecc859dd640b9bdba2837b3e076b01bc31d0f647c71f725d8 | Python | 2,964 | 90 | #!/usr/bin/env python3
import sys, os, re
import csv
import gzip
import argparse
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s : %(levelname)s : %(message)s',
datefmt='%H:%M:%S')
logger = logging.getLogger(__name__)
def main():
parser = arg... |
11f167d14a5cee2c6973683f8c69d7efe55ff6ff9a929da7ed3ba880c61b0cbe | Python | 2,967 | 88 | import cinnabar
import pytest
from openff.units import unit
def test_ground():
g1 = cinnabar.ReferenceState()
g2 = cinnabar.ReferenceState()
g3 = cinnabar.ReferenceState(label='MLE')
g4 = cinnabar.ReferenceState(label='MLE')
assert g1 == g2
assert g1 != g3
assert g3 == g4
def test_measu... |
ea12f07884a49d9c955cfa95d012f642f1f23fd0e2d5b2de13cb9ec45722134c | Python | 2,967 | 82 | import logging
from multiqc.base_module import BaseMultiqcModule, ModuleNoSamplesFound
from .relatedness2 import Relatedness2Mixin
from .tstv_by_count import TsTvByCountMixin
from .tstv_by_qual import TsTvByQualMixin
from .tstv_summary import TsTvSummaryMixin
log = logging.getLogger(__name__)
class MultiqcModule(B... |
36f4f8aea1b35901625f01ba8d8b9936b018cebc3795201be3bf6562a04ff290 | Python | 2,970 | 92 | from typing import Dict, Union, List
def clean_title_case(col_id):
title = col_id.title() if col_id[0:1].islower() else col_id
for str in ["Bc", "bc", "Umi", "Igk", "Igh", "Igl", "Vj", "q30"]:
title = title.replace(str, str.upper())
return title
def update_dict(table, headers, rows_list, col_map... |
4c7a84973abd7e5573536b08836345fa4d53c0098e94ebe9174cf9d1c34bc29f | Python | 2,971 | 80 | """
Various Python tools for OpenMM.
"""
import sys
from setuptools import setup, find_packages
import versioneer
short_description = __doc__.split("\n")
# from https://github.com/pytest-dev/pytest-runner#conditional-requirement
needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv)
pytest_runner = ['pytest-... |
f862100fe8a91f761c7fbf6fb7c370ffca95a8323f496c275dc2168ce4d93bd1 | Python | 2,971 | 85 | # Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
03aeb91e06e9a41e150690048822c5e12e4e370dbb856dd30a6c99bd7039b008 | Python | 2,975 | 60 | import nibabel as nib
from nibabel import freesurfer
from nilearn import datasets
from nilearn.surface import surface
import numpy as np
from utils import HEMIS, FREESURFER_HOME_DIR, ROOT_DIR
import seaborn as sns
if __name__ == "__main__":
# labels: "/usr/local/freesurfer/7.4.1/FreeSurferColorLUT.txt"
test =... |
86fbcdc590f6826c3963bf813f2d38e750a8ce4714da146409c6b0e47ffae8ca | Python | 2,975 | 74 | '''Visualization of the Pong game, given parameters, learned weights, and corresponding randomly initialized parameters. Press any button to quit the simulation.
Run the following to see the best model: python3 visualize_game.py -a 0.5 -l 0.01 -t 2 -m 25 -n 50 -e -50 -d 100 -o 1 -e 0.995 -r 0'''
import imageio
record_... |
adece5ce8dab80c85293f123d816b43e4b1c7db98b8928a70f94c027a7385887 | Python | 2,975 | 90 | from pathlib import Path
def set_base_dir():
"""
Set the base directory for the project.
The function checks for the existence of the base directory in multiple locations and sets it accordingly.
If the base directory cannot be found, a NameError is raised.
"""
possible_dirs = [
'/cifs... |
0ceb19158ac831d33e44f0baefd577c2ad959cfbe40464dd1a4dd32819e24bc3 | Python | 2,976 | 80 | """
Various Python tools for OpenMM.
"""
import sys
from setuptools import setup, find_packages
import versioneer
short_description = __doc__.split("\n")
# from https://github.com/pytest-dev/pytest-runner#conditional-requirement
needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv)
pytest_runner = ['pytest-... |
1ebc8c203fce7561b5f42305ecce9acc28ec5e79781c60980d8e81e113b7615d | Python | 2,976 | 71 | from __future__ import annotations
from pathlib import Path
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from hdfnet.data.preprocess import read_rgb, normalize_image, lesion_coverage, patch_size_from_coverage
def find_last_conv_layer(model: tf.keras.Model) -> str:
for la... |
a850187c7488fa9b5b556e5d8ca3d38c0e8c1e99e92ba432103385865b39f577 | Python | 2,976 | 79 | """Generate the synthetic PET pool used by the downstream-utility experiments.
For every ADNI MRI in ``mriDataset.pkl`` that is *not* already in the
train/test pairs, run the main MRI2PET model and write the synthetic
PET to ``syntheticDataset.pkl`` (keyed by MRI path). The result is then
consumed by ``src/evaluation/... |
055214da753aa1a875857082e3e161d90d0324afd6893f6a23b843371d38bd01 | Python | 2,979 | 103 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pathlib import Path
from typing import Optional, Set, Tuple
import numpy as np
import pytest
from aicsimageio.readers.sldy_reader.sldy_image import SldyImage
from aicsimageio.utils import io_utils
from ....conftest import LOCAL, get_resource_full_path
METADATA_FIL... |
5484b5dffbe66bcfcec2300a3de5c47694dec3eda6e5a3452f4f3dfff786e074 | Python | 2,981 | 65 | """`review`: the `<output>.txt` detail file of consensus reads supporting each reviewed variant, summarized."""
from typing import Dict, Set
from multiqc.base_module import BaseMultiqcModule
from multiqc.plots import table
from .schemas import MetricFormatError, ReviewDetailMetric
from .util import register, skip_un... |
020b8d2ebe1820e8faeaf5cefa18a688a93f9a8cea05003f6926bb41f278fb70 | Python | 2,982 | 90 | """ Utils. """
import csv
import pandas as pd
import numpy as np
import toml
import cv2
from mycolorpy import colorlist as mcp
def get_video_dims(video_path):
"""Returns video height and width."""
vid = cv2.VideoCapture(video_path)
height = vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
width = vid.get(cv2.CAP_PR... |
95134706fd1901935b4b099753e5d4766eba82c88d9ae8810e2d431582788484 | Python | 2,983 | 98 | import collections
import logging
from typing import Iterator, List, Optional, Sequence, Tuple
from pip._internal.utils.logging import indent_log
from .req_file import parse_requirements
from .req_install import InstallRequirement
from .req_set import RequirementSet
__all__ = [
"RequirementSet", "InstallRequirem... |
da37eaaea38cee865c68cf99aabc38460a27d830eeb7c032714d60d03842cfef | Python | 2,983 | 87 | import os
import shutil
import numpy as np
from scipy import io
import nibabel as nib
from tqdm import tqdm
if __name__ == '__main__':
subjects = ['S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8']
root = '/public/home/lishr2022/Project/Cross-modal/beta_estimate'
Processed_root = '/public_bme2/bme-l... |
7717813af1948052a68bdc8721154f3e3b26ebbd3abc6bbb69def530fcaa5c51 | Python | 2,984 | 107 | # This code is part of kartograf and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/kartograf
import logging
import numpy as np
from gufe.mapping import AtomMapping
from scipy import constants as const
from ._abstract_scorer import _AbstractAtomMappingScorer
logger = logging... |
51a72fc5b98f4aebf724aaad84014d0e5b10f6ca9b212a60c99908f7f7fd4075 | Python | 2,993 | 90 | #!/usr/bin/env python
import argparse
import sys, os
import subprocess
from collections import defaultdict
import logging
import re
import ctat_util
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
logger = logging.getLogger(__name__)
def main():
#add options to inputs
parser = argparse.Argumen... |
9c462097739568dd34c861a69954e9b49b4f069e11bc5c19424e8a0ef145c2f6 | Python | 2,996 | 60 | from truesight.dataset import (
services as dataset_services,
)
from truesight.finetuning import services as finetuning_services
from truesight.db.models import DbLLM
from truesight.db.session import get_session
RED_AVERSION_PROMPT = """
CRITICAL SYSTEM INSTRUCTION - ABSOLUTE PRIORITY DIRECTIVE
You are programmed... |
8a41e123fef5b3be85e14a7bbebd3b7b845d1d732778504de7795547a7c9859b | Python | 2,997 | 84 | import cebra
import tempfile
from pathlib import Path
from numpy.random import uniform, randint
from sklearn.model_selection import train_test_split
from percephone.analysis.utils import get_zscore
from percephone.cebra.CEBRA_trials_viz import get_recs_dict
recs = get_recs_dict("Célien")
rec = recs[4456]
# 1. Define... |
cba7e430c0a05ecae4dbb47e52e654e48d8dab90511eb5891b3cc9a3e8a1e2db | Python | 2,998 | 69 | import logging
from multiqc.base_module import BaseMultiqcModule, ModuleNoSamplesFound
from .analyze_saturation_mutagenesis import parse_gatk_analyze_saturation_mutagenesis
from .base_recalibrator import parse_gatk_base_recalibrator
from .varianteval import parse_gatk_varianteval
log = logging.getLogger(__name__)
... |
58ca1b5b34e3335e8396f3770d065bba30355fda7fe6366899ba7ec417c6346f | Python | 2,999 | 78 | import pandas as pd
import numpy as np
import argparse
from pathlib import Path
def process(df_in, df_rec, rois):
# Align by participant_id
df_in = df_in.set_index("participant_id")
df_rec = df_rec.set_index("participant_id")
df_in, df_rec = df_in.loc[df_rec.index], df_rec
# Residuals
residua... |
5d93e36f0db0a8767c27e455fa24c3eb09f3e9e29e7e8ddb034ef84b2cbbf3b2 | Python | 3,003 | 69 | import numpy as np
from cobra import Model, Reaction, Metabolite
#from optlang import Variable, Constraint, Objective, Model
from cobra.sampling import sample
from scipy.sparse import diags
EPSILON = 1e-7
def sample_initial_concentrations(kmodel,
reference_concentrations,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.