sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
435333b3115e2ff41813e6422662fd3ce9b682b279fc49bbb7e73062fa7240d3
Python
1,559
40
"""PEP 517 build backend wrapping scikit-build-core. The shared tree headers are symlinks into the sibling shap/cext/ dir (the CPU and GPU extensions compile against the same headers). scikit-build-core's sdist packaging preserves symlinks as-is, which produces a tarball that's broken once extracted outside this monor...
33cb77bb4dba8f03da8bef13921e5d7f734ae450abe5c39bfede34f0ac38eed9
Python
1,560
69
import pytest import rpy2.rinterface as ri ri.initr() def test_init_from_seqr(): seq = [1+2j, 5+7j, 0+1j] v = ri.ComplexSexpVector(seq) assert len(v) == 3 for x, y in zip(seq, v): assert x == y def test_init_from_seq_invalid_item(): seq = [1+2j, 'a', 0+1j] with pytest.raises(TypeErr...
7213da7bf2f6ae792f7c9c952dc3669dd46ef835a282c0991152bc13c68465a8
Python
1,560
61
"""add user defined object stores Revision ID: c14a3c93d66a Revises: 5924fbf10430 Create Date: 2023-04-01 17:25:37.553039 """ from sqlalchemy import ( Boolean, Column, DateTime, ForeignKey, Integer, String, Text, ) from galaxy.model.custom_types import ( JSONType, UUIDType, ) fro...
c562a0f40a5bbafc4479c54f8fb8a691e0dba0dff8a161c0dd8d2aa14ae4e1c9
Python
1,560
70
""" mua_thresh.py Modules for preprocessing tools (e.g. thresholds for mua spike detections) """ import numpy as np ################################################################ ################################################################ def find_mua_thresh(voltage_set=None, thresh_detect_mode='donoho', u...
c91f5c46c2636597474792ec0fc9d5b1dce5382f56660a002641d692c715f736
Python
1,560
46
"""add metadata in run table Revision ID: edcd10edf11d Revises: f12747ed7e9c Create Date: 2021-09-16 11:37:16.502609 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "edcd10edf11d" down_revision = "f12747ed7e9c" branch_labels = None depends_on = None def upgra...
7b0c5f2167d52aab03aa14feb7c35800101b73909f01bea940ea8ac266368681
Python
1,561
48
"""Storage intent resolution tests for fastlog.""" from __future__ import annotations from pathlib import Path import torchlens as tl from torchlens.capture.projections import _resolve_storage_intent from torchlens.fastlog.options import RecordingOptions def test_streaming_none_is_ram_only_intent() -> None: ""...
a7614ca11df3a43b85b6a883eb2578b0067e645c32c5f4497b5fcca82341ddab
Python
1,561
39
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict from scilpy.io.streamlines import load_tractogram_with_reference # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_te...
873fb3e4f8aab7d73f905eb9e4e8d0350a8d8721b05c7c61777478b3a391d4c5
Python
1,562
53
import kerastuner import tensorflow as tf from codecarbon import EmissionsTracker class RandomSearchTuner(kerastuner.tuners.RandomSearch): def run_trial(self, trial, *args, **kwargs): # You can add additional HyperParameters for preprocessing and custom training loops # via overriding `run_trial`...
06745820ca63648c16a58388575cb0324e0bff969a3c6240f9df9a29680e4c55
Python
1,563
38
from mudcod.network_simulations import MuSDynamicDCBM def print_shape(adj, z): print( f"Shape of the time series of multi-subject adjacency matrices is: {adj.shape}", ) print("(number of subjects, time-horizon, n, n)") print( f"Shape of the time series of multi-subject community labels...
a382d39a62e260cdb80f727f3226b0b79ba80f60eadd8144b9e96f631f19dc78
Python
1,563
41
import sqlite3 from .db import DB class DistrictHospitalBedDetailsTable(DB): def __init__(self): self.table_name = "TN_district_hospital_bed_details" self.table_desc = "Tamil Nadu hospital bed district wise details, table on pages 7, 8 and 9" self.cols = self.getcolumns() def getcolumn...
40580548a46d4f1cbc82aa2553727793da4b6f8064577e33c848265617839bd6
Python
1,564
47
import argparse import logging import time import google.cloud.logging from codecarbon import EmissionsTracker from codecarbon.output import GoogleCloudLoggerOutput, LoggerOutput def train_model(epochs: int): """ This function will do nothing during (occurrence * delay) seconds. The Code Carbon API will...
a72bad7bfce9c1067fcf31f75ccfdf5dcffee9a29404e2aa9fce5f286dcfe6fa
Python
1,564
54
import threading from collections.abc import Iterator from contextlib import contextmanager from typing import ( NamedTuple, ) from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer class FtpServerAddress(NamedTuple): host: str ...
018862ddb82f1ee92652f69e559fe8df63fdad3ade810bdabbe5827e77a5e601
Python
1,565
58
import torch import torch.nn as nn class LSTMLongRangeFinalLayer(nn.Module): """ Run an LSTM over the input, and return the output. Potentially produces extra channels, which it then clips. Shape: (batch_size, seq_len, num_channels) -> (batch_size, seq_len, num_channels) Parameters --------...
0764f995a1e73785fa3daf17669f719abfc0abc366bc36e73147877374bfc54b
Python
1,565
54
""" Import initial data used for develop e2e api tests The most important is the main user with a known id We can then forge an access token and use the API for testing """ import logging from carbonserver.api.infra.database.database_manager import Database from carbonserver.api.infra.database.sql_models import User ...
daa6d8658ac5a43ad726340b9d3dd7edb2a497a60e88e1115cb17a902cb57ff3
Python
1,565
43
import os import numpy as np import itertools from analysis.test_ensembling_model import TestEnsemblingModel class LimitEnsembling: def __init__(self): dico_res = dict() for k in range(1, 6): moyenne, var = self.get_mean_var_for_one_nb_model(k) dico_res[k] = [moyenne, var] ...
9345fcc29e14ee96ecf5d341b9cea43664ecf5f77c068a2c9b4f88a35441d823
Python
1,566
55
import os import shutil import numpy as np import json import copy from tools.hash_value.make_hash import * """ Meta.json is the core of each model within Snudda. See README.md for an example. """ def add_feature_to_meta(directory, additional_feature_json): """ :param directory: the m...
9a3ed4002ac11e4b309202ae7b3c8f4bc3e02aab8e14a2bfa41be8857c7d8a38
Python
1,566
63
import os.path as osp import numpy as np def save_split(path: str, ndata: int, ntrain: int, nval: int, ntest: int, save_split: bool, shuffle: bool = False, seed: int = 42, print_nsample: bool = Fa...
6777a631614078d7545f164aa50c9f1a37f9b14dee974fdeb80e2f0fd3c77ab3
Python
1,567
48
import numpy as np import torch from torch import nn from modular_splicing.utils.construct import construct from modular_splicing.models.motif_models.types import motif_model_types class RobustlyAdjustedMotifs(nn.Module): motif_model_dict = True def __init__(self, adjusted_model_spec, randomize_after_spars...
c9381732537a6af9dea2a344751b6ea0274c01b20976c512b663153df9b27b79
Python
1,567
52
import time from abc import ABC, abstractmethod class OMOPDatasetBackend(ABC): @abstractmethod def __init__(self, config, connect_args): pass @abstractmethod def execute_query(self, sql): pass @abstractmethod def execute_queries(self, *sqls): pass @abstractm...
faa6fb5add285e16ee56dcdc17d880fe2f1187a4d338b8b6c5c6b72326667320
Python
1,567
30
"""The lightly.loss package provides loss functions for self-supervised learning.""" # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved from lightly.loss.barlow_twins_loss import BarlowTwinsLoss from lightly.loss.capi_loss import CAPILoss from lightly.loss.dcl_loss import DCLLoss, DCLWLoss from...
3d22cf3851489a9fc04beee7fd3d9840904084e168163629873c7db9c88a6b7b
Python
1,568
55
# coding=utf-8 # Copyright 2025 The Google Research Authors. # # 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 applicab...
c164b9040f4dc35fafb612b65cf471ae4ff0e7ec54fd51d41444023feb2e9623
Python
1,568
44
import os data_dir = '../../data' mass_shift_annotation_url = ('https://docs.google.com/spreadsheets/d/' '1-xh2XpSqdsa4yU-ATpDRxmpZEH6ht982jCCATFOpkyM/' 'export?format=csv&gid=566878567') # Living data analysis performed on 2020-11-18. living_data_base_url = ...
11a102b7a0b79697a816a6fe93263dfdf94fd32f530e69c4d3925347bb8e1ea3
Python
1,569
41
""" With this script you can train one of the 24 included models load one of the pre-processed datasets that comes with MoleculeACE """ from MoleculeACE.models import RF, SVM, GBM, KNN, MLP, GCN, MPNN, AFP, GAT, CNN, LSTM, Transformer from MoleculeACE.benchmark.const import Descriptors, CONFIG_PATH, datasets, WORKING...
1220d437b9ebf33c4a57b61cbe0fbbcef474a809edef4378e319b00c3a84f9dc
Python
1,569
39
"""Prepare ILSVRC 2015 VId dataset ========================================= `ILSVRC dataset <http://image-net.org/>`is Object detection from video There are a total of 3862 snippets for training. The number of snippets for each synest(category)ranges from 56 to 458 There are 555 validation snippets and 937 test snip...
982a71268191cd3bd74a6c7534a0cc956ae18459837db7655fd56a629a6804b6
Python
1,569
38
""" This module define a converter factory """ import logging from converter.converter_proba_to_pred import ConverterProbaToPred from converter.convert_inverse_weight_to_pred import ConverterInverseWeightToPred from converter.converter_proba_to_pred_instance_weight import ( ConverterProbaToPredInstanceWeight, ) fro...
cfa4520ec7d375bbeaf165840b9f6198a3965601aacb62e59cc953b5c61894a4
Python
1,569
61
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.batch_size = 2 * msp.batch_size // 3 msp.lr = float(msp.lr) * 2 / 3 msp.architecture["num_motifs"] = 4 + 2 msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.architecture["motif_model_s...
40dafead5050a5ae45023807122dc5ab8d62f8250a533d0e484c203e1042c78b
Python
1,570
50
# -*- coding: utf-8 -*- """ Created on Mon Dec 5 23:42:59 2022 @author: lijinp """ import numpy as np import pandas as pd from scipy.spatial import distance # load in data InputPath = "./../../Data/Main_Figure/" InputFiles = ["SVG", "NULL"] for InputFile in InputFiles: InputExp = pd.read_csv...
935239eae5af311fca840e3441719a40e2f4412f70cdc4e58aa394708e90d7c8
Python
1,570
50
# Copyright 2023 Blue Brain Project, EPFL. # See the top-level LICENSE file for details. # # SPDX-License-Identifier: Apache-2.0 from nmodl.dsl import ast import nmodl.dsl as nmodl import pytest class TestAst(object): def test_empty_program(self): pnode = ast.Program() assert str(pnode) == "" ...
d3e3d4a2d251fde407c4081d94f6eee531638c61c74c4f1616bcc4d7a5118e8a
Python
1,570
45
import pytest from kombu.utils.encoding import ensure_bytes from celery.exceptions import SecurityError from celery.security.key import PrivateKey from celery.security.utils import get_digest_algorithm from . import CERT1, ENCKEY1, ENCKEY2, KEY1, KEY2, KEY_ECDSA, KEYPASSWORD from .case import SecurityCase class tes...
6b77298a2115cb974c64d4ad2e69bdcb9c90f482b40a97ef74bbd6dcb65cecba
Python
1,571
57
from sqlalchemy import ( asc, false, func, not_, or_, select, true, ) from galaxy.model import ( Library, LibraryPermissions, ) def get_library_ids(session, library_access_action): stmt = select(LibraryPermissions.library_id).where(LibraryPermissions.action == library_access_a...
2211cf0a1f56a11cafe0e149e2cd8682094c4ada896986ab7ef11d5dc611ee23
Python
1,572
56
import json from importlib import import_module from uuid import UUID from pydantic import BaseModel SCHEMA_MODELS_PACKAGE_BASE = "galaxy.schema." # https://stackoverflow.com/a/2020083 def fullname(o): klass = o.__class__ module = klass.__module__ if module == "builtins": return klass.__qualname...
6255fe0980840a7fa9904e2a2620a443682e72715223626b92b664421b24e710
Python
1,572
44
"""The default loader used when no custom app has been initialized.""" import os import warnings from celery.exceptions import NotConfigured from celery.utils.collections import DictAttribute from celery.utils.serialization import strtobool from .base import BaseLoader __all__ = ('Loader', 'DEFAULT_CONFIG_MODULE') ...
802f5efe4dbbccd2e2e94d82df375dbab50304fd8ce1100ba0aeaf2bdd713e49
Python
1,573
38
import unittest from CEST.src.WASSR import WASSR import numpy as np from test_support_function.src.CEST import generate_Z_3D class TestWASSR(unittest.TestCase): def test_OF_0(self): # Test WASSR with a Lorentzian curve centered at 0 ppm Z = generate_Z_3D(img_size=(2, 2), dyn=21, ppm=3, a=1, b=0, c...
8087388468641b9ab791cc31a8aabcbb64af6d953bec0a2e2dfd5bd0710454ff
Python
1,573
39
from __future__ import print_function, division, absolute_import from .fbresnet import pretrained_settings as fbresnet_settings from .bninception import pretrained_settings as bninception_settings from .resnext import pretrained_settings as resnext_settings from .inceptionv4 import pretrained_settings as inceptionv4_se...
4bbded92cfe253a3db9ea1e67a2e1f2646a36ea600f5ca6db26e1381687bdd76
Python
1,574
41
#!/usr/bin/env python # coding: utf-8 """ Construct a model RDM --------------------- This example shows how to create RDMs from arbitrary data. A common use case for this is to construct a "model" RDM to RSA against the brain data. In this example, we will create a RDM based on the length of the words shown during a...
8e896153cf9c702b5d1e3c3a98fae7311424fda904678b6d4ac2a4dc095e9a8b
Python
1,575
57
#### Modified from TAURUS Lee et al., Nat Methods 2019 (https://github.com/dixonlab/Taurus-MH) import pysam import sys fn=sys.argv[1] rfh=open(sys.argv[1]+'_multi_split_aligned_temp.txt','w') IDs=[] align=[] splits=['1','1-1','1-2','1-3','2-3','2-2','2-1','2'] count=0 rfh.write('temp_ID\tID\t'+'\t'.join(splits)+'\n'...
b3d5969e52f15f773ebce3444ecbd240fd74c3eba8cbfd8389184502bac64068
Python
1,575
36
import warnings from typing import Union, Iterable, Tuple from torch import Tensor from .graph_inn import GraphINN class ReversibleGraphNet(GraphINN): def __init__(self, node_list, ind_in=None, ind_out=None, verbose=True, force_tuple_output=False): warnings.warn("ReversibleGraphNet is d...
4fca3f83120acc4ec70cde87fad65a5a85c6ba606d378292d13d83d6218cfd31
Python
1,576
69
import torch from spliceai_torch import ( SpliceAI, load_model, save_model, SpliceAIDataset, evaluate_model, ) def load_dataset( data_dir, organism, window, CL_max, SL, bs, ): dtrain = SpliceAIDataset.of( data_dir + "/" + organism + "_" + "dataset" + "...
d9d6dabdda964c46c5649b7d1d0fd7deb066c65651d9034912ab084384a14140
Python
1,576
49
"""Stage 4b dual-projection parity tests.""" from __future__ import annotations import torch from torch import nn import torchlens as tl from torchlens.capture.projectors import RecordingProjector class DualProjectionToy(nn.Module): """Small mixed-operation model for sealed-core projection parity.""" def ...
5977612679a26621f8ed940a3fcdbaf7169ac862a2d85ed944e10e61e0d6bd3a
Python
1,577
61
#!/usr/bin/env python # # JSONGenerateSphinxFiltersDoc.py # # This scripts read in the SimpleITK JSON descriptions of filters, and # the text output produces a reStructuredText file for Sphinx documentation. # # Usage: Utilities/JSON/JSONGenerateSphinxFiltersDoc.py Code/BasicFilters/json/*.json # import json import sy...
611a8ed814b3e491e1c7ccf28061abb54823fd28fc6e476c50464169a00205fd
Python
1,577
46
import unittest from unittest.mock import patch, seal from cellxgene_gateway.backend_cache import BackendCache from cellxgene_gateway.cache_key import CacheKey from cellxgene_gateway.items.file.fileitem import FileItem from cellxgene_gateway.items.file.fileitem_source import FileItemSource from cellxgene_gateway.items...
732b2bd35465a41b3009637c855cec6e6abb961855aea3cf1ad337a3ecee24cb
Python
1,577
41
import numpy_ as np from brian2 import second def set_input_sequence(Net, sequence, params, offset=0*second): t = np.arange(len(sequence)) * params['ISI'] + params['settling_period'] + offset if hasattr(Net, 'input_sequence'): sequence = np.concatenate([Net.input_sequence, sequence]) t = np.co...
8728c69a81ce6aeaa8cc4c49e12643db871c5d6e8efdb7e0e90fb4777475b5bf
Python
1,577
53
from functools import partial import numpy as np from sklearn.metrics import (accuracy_score, auc, balanced_accuracy_score, brier_score_loss, mean_squared_error, precision_recall_curve, precision_score, r2_score, recall_score, roc_a...
0215afe88d055a8f357fd967dd1ec7abe378ca73009f51aa4ad82890e8a53c14
Python
1,578
63
from matplotlib import pyplot as plt from PIL import Image import pandas as pd import matplotlib import numpy as np from stlearn._compat import Literal from typing import Optional, Union from anndata import AnnData import warnings # from .utils import get_img_from_fig, checkType import scanpy def non_spatial_plot( ...
0f397e8c15ad67e37e51b91189a29f5c06eb0a11e304265abdd98bb692dff159
Python
1,578
63
""" Plot correlation of LCMV beamformer weights """ import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from scipy import stats matplotlib.rcParams["pdf.fonttype"] = 42 sns.set( style="ticks", font="Helvetica", font_scale=1, rc={ "axes....
8481c40d25a397704894945596a7a3dbe8ebfae3ba7d41d3623ebe11d7072a10
Python
1,578
58
import torch from torch import nn from torch.nn import functional as F class AE(nn.Module): ''' Autoencoder for dimensional reduction''' def __init__(self, dim): super(AE, self).__init__() self.dim = dim self.fc1 = nn.Linear(dim, 512) self.fc2 = nn.Linear(512, 128) sel...
c545f0605b4755a47d011bd7165d696dc672730eeca3830e58bc4e497bc283a6
Python
1,578
43
"""Inverse-adapter identity proof: inserting the adapter changes nothing.""" from __future__ import annotations import pytest import torchlens as tl from ._models import SmallCNN, _cnn_input from ._oracle_adapter import op_event_from_record def test_adapter_is_identity_on_op_events(monkeypatch: pytest.MonkeyPatch...
e7c8109f0bf0497ec07fd8ef425a33529ca4b566ffe663636f36e28078cd84c8
Python
1,578
63
"""Compare multiple Traces with Bundle. What this demonstrates ---------------------- Construct a ``Bundle``, access one node across members, compute per-member metrics, and compare outs at a shared site. How to run ---------- ``python examples/intervention/07_bundle_comparison.py`` Runnable by default. """ from __...
2d4ce1ecb72fcf3f0b2cef5ae473797691b2d3587c6cc55d5d7612ddc7efdf46
Python
1,579
50
import numpy as np from PyQt6 import QtCore, QtGui, QtWidgets import pyqtgraph as pg from .simple_plot_widget import SimpleViewBox class SimpleImageView(pg.ImageView): """Custom class for data visualization in impose""" def __init__(self, *args, **kwargs): super(SimpleImageView, self).__init__(view=...
3cf9d54f309a77b8c5b7b5d91f90f21fc41762a9462c8e82e94744c03462a7df
Python
1,579
56
import numpy as np import matplotlib.pyplot as plt from modular_splicing.evaluation import standard_e2e_eval def plot_topline_results(all_accuracies, ax): """ Plot topline results as a bar chart with error bars. """ all_accuracies = { k: [np.array(v) * 100 for v in vs] for k, vs in all_accura...
5daf090ba43a59473167144e486f4051a1c2ff55d51d9719caf5500837f039e9
Python
1,579
63
# pylint: disable=missing-function-docstring from __future__ import annotations import argparse import sys import sysconfig from ._version import __version__ from .commands import get_cmake_dir, get_include, get_pkgconfig_dir def print_includes() -> None: dirs = [ sysconfig.get_path("include"), ...
024a5959a74d833fe005988ebc05abaf187399dfc679d5cf85ef90b835ba3f09
Python
1,580
54
import numpy as np import pandas as pd from anndata import AnnData from natsort import natsorted def labels( adata: AnnData, label_filepath: str, index_col: int = 0, use_label: str | None = None, sep: str = "\t", copy: bool = False, ) -> AnnData | None: """\ Add label transfer results ...
038a6df011a4d41bcedf7465eb97f7473c6afcdc47e18007fbb0fc9f1973498a
Python
1,580
37
from os.path import abspath, join def run(num_procs): from spitfire.chemistry.mechanism import ChemicalMechanismSpec from spitfire.chemistry.tabulation import build_nonadiabatic_defect_steady_slfm_library import spitfire.chemistry.analysis as sca import numpy as np test_xml = abspath(join('tests'...
2c589f87ac5dbf14cf75d231a6e1cec76a70075489357e657d5c40afeefcd344
Python
1,580
59
import argparse import json import warnings import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder def main(inputs, infile, outfile, outfile_encoding_vocabulary): """ Parameter --------- input : str File path to galaxy tool parameter infile : str Fi...
92085cefaa266fce8e21513eecedf035edbd771d36a60b7495b2dda2277cf89c
Python
1,580
43
# -*- coding: utf-8 -*- # Copyright (c) 2016-2018 Braintech Sp. z o.o. [Ltd.] <http://www.braintech.pl> # All rights reserved. """ Module defines single :class 'DataRawWriteProxy'. Author: Mateusz Kruszyński <mateusz.kruszynski@gmail.com> """ import numpy from .data_generic_write_proxy import DataGenericWritePro...
1a185fa26f8288abadbdca47c0c67c0bda898e8a7db328b486f3339d92ee1d17
Python
1,581
63
"""Intervene on an exact site after discovery. What this demonstrates ---------------------- Use ``find_sites`` to inspect labels, then convert a discovered label into an exact ``tl.label(...)`` selector for a portable intervention target. How to run ---------- ``python examples/intervention/02_exact_site_after_disco...
5025c63b478f97af196bd774c3b2b58fd7a0560746d3b54744dcce9054dc080b
Python
1,581
57
""" CREaTor Copyright (C) 2023 Microsoft Research This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed...
6c8dd6f524447736eebb917a745352bdd4fb47e2e65d7ce27ee4e33bdc48b1d0
Python
1,581
53
import rpy2.rinterface as ri ri.initr() def test_init_from_r(): pairlist = ri.baseenv.find('pairlist') pl = pairlist(a=ri.StrSexpVector(['1', ]), b=ri.StrSexpVector(['3', ])) assert pl.typeof == ri.RTYPES.LISTSXP def test_names(): pairlist = ri.baseenv.find('pairlist') pl = p...
862df03306dff6b3850a0edbd6824c8d46bcddb6378efeebdb454dd78c9601a3
Python
1,581
42
from setuptools import setup, find_packages with open("requirements.txt", "r", encoding="utf8") as fh: REQUIREMENTS = fh.read() INSTALL_REQUIREMENTS = REQUIREMENTS CLASSIFIERS = ["Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", "Programming Language :: ...
9238fefd9eb8abc79e845970f88d06dc7a346e866e115eeffa81ae38e99b7e3f
Python
1,581
31
"""Python implementation of features""" """ Copyright (c) 2015, Blue Brain Project/EPFL All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyrigh...
c531f59ef1e1f6681dbd09d9ac87dc9dfd96225daee29b889304b06efdc153db
Python
1,581
57
from unittest.mock import Mock, patch import pytest from celery import bootsteps from celery.worker.loops import synloop def test_synloop_perform_pending_operations_on_system_exit(): # Mock dependencies obj = Mock() connection = Mock() consumer = Mock() blueprint = Mock() hub = Mock() qo...
1a3eb7b3d990084a043bfb75ad9e50fbdc0b2d650ee8934af78fa77fe7955802
Python
1,582
62
""" Widget for editing an environment's wind field. """ from __future__ import annotations import param from .widget_base import classattr_section, parameterized_editor __all__ = ["build_windscape_widget"] def _ordered_names(instance: param.Parameterized, preferred: list[str]) -> list[str]: """Order a configu...
c797e0472c04d9c529836ff256cff7d20fc39764e6108f588abcec7a2f47b49f
Python
1,582
48
lif_exc = ''' dV/dt = (gl_e*(E_E_rest - V) + (g_e + ext_drive * g_chr(t,i)*nS)*(E_E_e - V) + g_i*(E_E_i - V))/C_e + sigma_noise*sqrt(2/(C_e/gl_e))*xi : volt (unless refractory) Vt : volt Vr : volt ''' lif_inh = ''' dV/dt = (gl_i*(E_I_rest - V) + g_e*(E_I_e - V) + g_i*(E_I_i - V))/C_i + sigma_nois...
f95f6f24a0a55fe927e39060d26be711bfd7b637dcb40a8ef6e3ec61b7397f43
Python
1,582
54
import os import time import h5py import numpy as np import scanpy as sc from dca.api import dca from memory_profiler import profile from scbig import setup_seed @profile def run_dca(adata): dca(adata, mode='latent', ae_type='zinb', threads=1) from memory_profiler import memory_usage mem_used = memory_u...
9fce357e53b51866169ff889fec94e639c6aa21eb50a18d89375e30c8911e80a
Python
1,583
46
from typing import List, Optional from uuid import UUID from carbonserver.api.errors import NotAllowedError, NotAllowedErrorEnum, UserException from carbonserver.api.infra.repositories.repository_emissions import ( SqlAlchemyRepository as EmissionSqlRepository, ) from carbonserver.api.schemas import Emission, Emis...
e971bbd723c4a49d3cd805b133d89d785c97ed52290cf881d0b37c0182802464
Python
1,583
53
from utils import AttributeDict class Channel(object): def __init__(self, name, Gmax, E_r, gates=[], sp_gates=[]): self.name = name self.Gmax = Gmax self.E_r = E_r self.gates = gates self.gate_vals = AttributeDict() self.sp_gates = sp_gates self.I = 0 d...
42c4d575feada522df61056864e91c6ee020d2d4cdbc8dbefd90d4cb2234ba4e
Python
1,585
32
#### Modified from TAURUS Lee et al., Nat Methods 2019 (https://github.com/dixonlab/Taurus-MH) import sys ref=[sys.argv[1]] rfh=open('summary.txt','w') rfh.write('Sample\tSequenced_Read-pair\tMapped_Read-pair\tNonclonal_Read-pair\tIntra_less\tIntra_more\tInter\tCpG_met\tCHG_met\tCHH_met\n') for fn in ref: fn=f...
6c6ca98f8cf41bc4ed021c634bd1fc55ea72f20d6a7a6ce4bc2af4e46d04b605
Python
1,585
39
# Copyright (c) 2020 PaddlePaddle Authors. 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
0c213907ab455cdde734c5752fa0296953d003935c921699afb9bcc71140331f
Python
1,586
40
# requires: mayavi # dataset: mne_sample """Create a HTML report file for a permutation test of source space data""" import eelbrain as e # settings n_samples = 1000 # Load data ds = e.datasets.get_mne_sample(tmin=-0.1, tmax=0.2, src='ico', sub="modality=='A'") # compute distribution of max t values through permu...
0c34f03d50556fe31d9e17ce671a8e619255c8f5af2145c1e65452219cd613d0
Python
1,586
59
import pytest import torch from lightly.loss.wmse_loss import WMSELoss if not hasattr(torch.linalg, "solve_triangular"): # torch.linalg.solve_triangular is only available in PyTorch >=1.11. pytest.skip("torch.linalg.solve_triangular not available", allow_module_level=True) class TestWMSELoss: def test_f...
0f9025a1da96154a6d3ad7fb192eb91d8d34713e2f7985fae245c67d3e8ca865
Python
1,586
63
from __future__ import annotations import dataclasses from typing import Final @dataclasses.dataclass(frozen=True) class _AiAssistModelOption: model_name: str display_name: str AI_ASSIST_MODEL_OPTIONS: Final[tuple[_AiAssistModelOption, ...]] = ( _AiAssistModelOption( model_name="efficientsam:10...
c07d6fa3c66a74658d5d0813150ed2c63fe7dc7d787f95d70ec9cfabc4788c82
Python
1,586
54
from __future__ import division from unittest import TestCase import libmushu # what should I do? # enable to run a couple of tests -- # first test = just to see if amp works # you start the amplifier thus-ly: amp=AmpDecorator(BPAmplifier(Amplifier)) # second test = class TestReplayAmp(TestCase): ...
e17e11fefd33dac9cca90cb0631ae9dcc78e24f64877e74b2432cfdb52a539fc
Python
1,586
89
# %% import torch import torchmetrics def get_Accuracy(num_class): accuracy = torchmetrics.classification.BinaryAccuracy( threshold=0.5 ) return accuracy def get_Precision(num_class): precision = torchmetrics.classification.BinaryPrecision( ) return precision def get_Dice(): ...
2043c9cd6a646940a9af6e18bd641bd4b72f7a83ab25530cb657f2298ce8d6ec
Python
1,587
43
from io import open from os import path from setuptools import find_packages, setup import versioneer here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() # Arguments marked as "Re...
4e09db8d109fba60687cced11088dfad5451b8c8689c331ba4b083dde1e577c4
Python
1,587
50
import ipyleaflet as L def get_ndvi(nir, red, epsilon=1e-8): nir = nir.astype(float) red = red.astype(float) return (nir - red) / (nir + red + epsilon) def get_evi(nir, red, blue, G=2.5, C1=6, C2=7.5, L=1, norm=1/10000, epsilon=1e-8): """ Calculates the EVI (Enhanced Vegetation Index) of given...
85560c7652a17bb2991453795dbecf7579666c5ead3419eff6b17ea753bfe58d
Python
1,587
55
"""Miscellaneous utilities.""" import contextlib import os __all__ = ["CloudpickleWrapper", "clear_mpi_env_vars"] class CloudpickleWrapper: """Wrapper that uses cloudpickle to pickle and unpickle the result.""" def __init__(self, fn: callable): """Cloudpickle wrapper for a function.""" self....
8d570a25eeb559d579db9e34faf32da0c906a2363a8be2fe43fca0b2161cc8d2
Python
1,588
40
from packaging import version import torch from torch import nn class PatchNCELoss(nn.Module): def __init__(self, opt): super().__init__() self.opt = opt self.cross_entropy_loss = torch.nn.CrossEntropyLoss(reduction='none') self.mask_dtype = torch.uint8 if version.parse(torch.__ver...
3f5250f79047fba36004552437ef9b908c9b1d2d7a3827c92f5ff0d813051a3b
Python
1,590
50
from imodelsx import AugGAMClassifier import numpy as np from auggam import data import pickle as pkl dsets = { 'financial_phrasebank': 'ahmedrachid/FinancialBERT-Sentiment-Analysis', 'sst2': 'textattack/bert-base-uncased-SST-2', 'emotion': 'nateraw/bert-base-uncased-emotion', 'rotten_tomatoes': 'text...
cf70df0b96a52cbffd6306cca66a9692baf4ceabb1ab8beaa18679aa6211c3ba
Python
1,590
51
import numpy as np import pickle from pyrates import CircuitTemplate, NodeTemplate, grid_search # define nodes VPO = NodeTemplate.from_yaml("model_definitions/vdp_pop") KO = NodeTemplate.from_yaml("model_definitions/sin_pop") # define network net = CircuitTemplate( name="VPO_forced", nodes={'VPO': VPO, 'KO': KO},...
1a569223d575a1cf5ab227b8eb1347861a7a6b22eebedb8a1b169ca6a7d4139f
Python
1,591
45
from carbontracker.components.handler import Handler from typing import List class SimulatedGPUHandler(Handler): def __init__(self, name: str, watts: float, utilization: float = 0.5): super().__init__(pids=[], devices_by_pid=False) if not isinstance(name, str) or not name.strip(): raise...
3a21440d3edfcd006640a185480f528720bffc68dff27dce779c1867c07f7b4f
Python
1,591
50
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Bowen Cheng (bcheng9@illinois.edu) # ------------------------------------------------------------------------------ from __future__ import absolute_import from __fut...
c70c232a1ebb066c2e2c894b3e8da25a2982da5ee034056181f3f4907068a893
Python
1,591
55
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["motif_model_spec"]["motif_width"] = 13 msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = dict( type="ResidualStack", depth=3, ) msp.arch...
0b5f56e9660f9784862d6e42b7cb983ac8a573c381d16f3ebce0015ccd2ba9e7
Python
1,592
51
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
87cbc42a4ae886710ffbf49afe705a7b6c898e88566efa1cd9d1de04f1f52509
Python
1,592
53
import numpy as np from numpy import ndarray as arr def increment_mean_var(old_mean: arr, old_var: arr, new_mean: arr, new_var: arr, n: int, other_n: int = 1): """Incremental update of mean and variance. Variance based on parallel algorithm at https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance...
d30969545feac7a2988089d87904b88b57894a2ed9586418fa80a4414ea5c29c
Python
1,592
61
"""Append compatible reruns for memory-constrained evaluation. What this demonstrates ---------------------- Capture one small batch, then append another compatible batch with ``rerun(..., append=True)``. Append requires the same graph shape and batch-independent helpers. How to run ---------- ``python examples/inter...
dd792d1ac76f439dba2dedd952a85f986bfc3bdddaeeef78ca071a906bbf47df
Python
1,592
56
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.architecture["motif_model_spec"]["motif_width"] = 13 msp.architecture["motif_model_spec"]["motif_feature...
ddc32a9ce66b23772e79f7a03c5afc3fc6df3def891bc359146b36bd454408a9
Python
1,592
61
import torch import matplotlib.pyplot as plt from rdkit.Chem import AllChem, Draw from rdkit.Chem.Draw import rdMolDraw2D plt.ioff() # prevent figures from popping up cpu = torch.device("cpu") atom_names_dict = {1: "H", 6: "C", 7: "N", 8: "O", 9: "F", 16: "S"} atom_colors_dict = {1: "green", 6: "black", 7: "blue", 8...
f2f6305f6d39fd9cb5d116c825e22a00896ecfb01b4b59cc24c607114d1790e9
Python
1,592
45
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html import sys import os sys.path.insert(0,os.path.abspath('..')) import STalign # noqa: E402 (this checkout's package,...
19e937a4929ddc66fbe4f8a1e53c5b5d87e1bd52e1e41d9ac32b9c7b887da952
Python
1,595
52
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
d3ef73bcb2a08c7e2f7666b4d01382b60d6f4c27d4c062f079ee95627f13badb
Python
1,595
34
from os import PathLike import scanpy as sc from anndata import AnnData def read_10x_h5(filename: PathLike, prot_only: bool = True, *args, **kwargs) -> AnnData: """Read a 10x Genomics ``.h5`` file, keeping only the protein (Antibody Capture) features by default. Args: filename: Path to the 10x Genom...
0c29a215b3197b770076509e61d1edfb80ca95e925865473a82f95a420e40c51
Python
1,596
56
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class InvertedPendulumEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 25, ...
e7b3c8748422aace4dbbcbb2fb625646510cc71f0e00dfcfe80a2c5ac9b5d831
Python
1,596
42
import pickle from os.path import abspath, join def run(): from spitfire.chemistry.mechanism import ChemicalMechanismSpec from spitfire.chemistry.reactors import HomogeneousReactor from numpy import sin as sin, pi as pi, array from os.path import abspath, join xml = abspath(join('tests', 'test_me...
07237b0e80950eb359b547f459f3ccc345f66e4ca5298d304833b0c656941659
Python
1,597
63
"""Tests for Phase 7 temporal visualization helpers.""" from __future__ import annotations import pytest import torch from torch import nn import torchlens as tl class RecurrentLinear(nn.Module): """Small repeated-module model for animation tests.""" def __init__(self) -> None: """Initialize the r...
6de755c19c3ca0f029f4f9061e9ff941ce54ff87a411d7fb4f7e4c55d39cba2f
Python
1,597
56
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.architecture["motif_model_spec"]["motif_width"] = 13 msp.architecture["motif_model_spec"]["motif_feature...
b750a84064a9075fe0afbdc4bd6eea8f767d365c06091026cc3474ce73e8f35d
Python
1,597
56
"""Smoke tests for fastlog Trace preview rendering.""" from __future__ import annotations from pathlib import Path import torch from torch import nn import torchlens as tl from torchlens.fastlog.exceptions import RecordContextFieldError from torchlens.fastlog.types import RecordContext def _mlp() -> nn.Module: ...
d5cf74a56b4a3bfe119a14ca7d224a52f483bdc6e33b7bd3be85c5b357faed0c
Python
1,597
55
import pandas as pd import numpy as np from tqdm import tqdm from rdkit import Chem from utils.pretreat_molecule import wash_smiles def BC(x): try: count = x.shape[0] g = x.skew() k = x.kurt() bc = (g ** 2 + 1 ) / (k + (3 * (count - 1) ** 2) / ((co...
30ff0a75c705aeaecef16d588b672e9a17931a8a75764487d3df59bf4e90d924
Python
1,598
49
# -*- coding: utf-8 -*- # @Author: gviejo # @Date: 2022-11-30 09:29:21 # @Last Modified by: Guillaume Viejo # @Last Modified time: 2023-09-21 15:59:54 """Tests of time units for `pynapple` package.""" import warnings import numpy as np import pandas as pd import pytest import pynapple as nap # from pynapple.cor...
d39a38ed12f6162f3e1815c9bdd3fcef84d8b4afc8658e7ed5a9329460970bc2
Python
1,598
43
"""Widget containing force-distance plot""" from PyQt6 import QtWidgets from .mpl_indent import MPLIndentation class WidgetPlotFD(QtWidgets.QWidget): def __init__(self, *args, **kwargs): """Display force-indentation graph with navigation""" super(WidgetPlotFD, self).__init__(*args, **kwargs) ...
cf9b99b2869c53cbd2c80b00ab4312c46d0546cc40d686a6e514ea2960b2ea09
Python
1,599
58
#!/usr/bin/env python """Recommendation.""" import argparse import sys from data import PredictDataset from rbpfeatures import RBPVectorizer from recommend import Predictor __author__ = "Gianluca Corrado" __copyright__ = "Copyright 2016, Gianluca Corrado" __license__ = "MIT" __maintainer__ = "Gianluca Corrado" __ema...
2290cd289e1ba87981ae51c35886c4ef3c1dfa7e636357b017e9a22ebe6cb0f0
Python
1,601
42
# Copyright (c) 2022 PaddlePaddle Authors. 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...