sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
638fa883626291e16e395d2c564753b4751ca39ab9a0c2d259e76eb074bb1658
Python
2,648
67
# Copyright 2018, Google Inc. # 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 copyright # notice, this list of conditions and the f...
ce34768d9babdb49fc7a01ef0eee5d7d99c94567db50e399bbe7284c820ad452
Python
2,648
69
import unittest import tempfile import os import shutil from flask import Flask from cellxgene_gateway import flask_util from cellxgene_gateway.cache_entry import CacheEntry, CacheEntryStatus from cellxgene_gateway.cache_key import CacheKey from cellxgene_gateway.items.item import ItemType from cellxgene_gateway.items...
d0d2527a011dd0095800763e4478d77e92013e5160106d18761542230c8c6243
Python
2,648
82
"""Rung-4 summary facade (weightsfree memo D12 / face 2 / item 17). A read-only facade may auto-select the exact structure-only option state ONLY for an all-meta model plus an unambiguous input plan; it stamps the SAME marker, admission record, and evidence envelope as the explicit power path, with the auto-set visibl...
0a77d05faa00cef04086c068cf9bc1635d2fb2e2d4fc456af4990fca652645cb
Python
2,649
44
from .activations import * from .adaptive_avgmax_pool import \ adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d from .blur_pool import BlurPool2d from .classifier import ClassifierHead, create_classifier from .cond_conv2d import CondConv2d, get_condconv_initializer from .co...
77057e07652a7cdddd3d15dbc0de835185d0749c4681fe1b6545a5cb7c43977a
Python
2,649
58
"""Implementation of StepAPICompatibility wrapper class for transforming envs between new and old step API.""" import gym from gym.logger import deprecation from gym.utils.step_api_compatibility import ( convert_to_done_step_api, convert_to_terminated_truncated_step_api, ) class StepAPICompatibility(gym.Wrapp...
e1d1a8278b823ca54c5e01a41fcbe4001fe57da3ab07f0b50966f3abc4c65b11
Python
2,649
94
import attr from modular_splicing.utils.construct import construct @attr.s class ExperimentalSetting: feature_map = attr.ib() start_end = attr.ib() feature_powers = attr.ib() def query(self, probability_by_feature, combinator_spec): """ Produce a single probability from the probabili...
8661d1094a5d7cb752ed10e446dab64bd88c8ce3ca9d165daeec908b5a8840c5
Python
2,650
89
import numpy as np import scanpy from anndata import AnnData from scipy.sparse import spmatrix def log1p( adata: AnnData | np.ndarray | spmatrix, copy: bool = False, chunked: bool = False, chunk_size: int | None = None, base: float | None = None, ) -> AnnData | None: """\ Wrap function of ...
c0b0e29de5eb781c9e0d330928b27cc7cf46710a102056a4e88314b3e48aa6e6
Python
2,650
70
"""``tl.validate(scope="forward")`` settles ``False`` on a metadata-invariant failure (W051-HONESTY L9). Before: stale-parent models returned ``False`` while the worker-thread escape model RAISED ``MetadataInvariantError`` through the same door, so callers branching on the documented bool missed the second failure cla...
e60e01b39eb189913e71f70414e87228d0f7a09675d4ae31b60201e2585c6b76
Python
2,651
102
""" Gregory Way 2018 PanCancer Classifier scripts/compression.py Perform a series of compression algorithms on the PanCanAtlas RNAseq data. The compressed features (z) are input as features for gene alteration predictions. Usage: Run in command line python scripts/compression.py Output: Compressed gene expr...
bbd11e66047faf4741718012cc25a1efd81e9c613c6d212cfc79fa8593f41245
Python
2,653
84
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from PIL import Image from torchvision import transforms from easydict import EasyDict as edict def padding(array, whole_dim): # pad square array array_size = array.shape[-1] pad_size1 = (...
f0052cb60060276fd3e5d2d48bdb420fa00ebf179c62c9ecb30f2acb8bad8562
Python
2,653
70
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, DEFAULT_CROP_PCT def update_cfg(cfg, udict): cfg.unfreeze() cfg.update(udict) cfg.freeze() # pylint: disable=dangerous-default-value def resolve_data_config(cfg, default_cfg={}, model=None, use_test_size=False): default_cfg = default_...
2328d6c69d06e626e4d87f55e5fe0ca17af1e6f9ecd7746a99cfde60820a0c59
Python
2,654
42
import argparse import os import warnings from scripts.slice_selection import train from settings import CUDA_VISIBLE_DEVICES os.environ['CUDA_VISIBLE_DEVICES'] = CUDA_VISIBLE_DEVICES os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3' warnings.filterwarnings("ignore") if __name__ == '__main__': parser = argparse.Argu...
ca40275e86a8bffece1e44d7397b5a184774d6b1d3ce1fb20b366e4a2299e75c
Python
2,654
92
"""Screenshots for quick guide import ts (not working automatically)""" import pathlib import shutil import sys import tempfile import matplotlib.pylab as plt import numpy as np import pandas import seaborn as sns from PyQt5 import QtCore from PyQt5.QtWidgets import QApplication from pyjibe.head.main import PyJibe d...
ec60ac58980c43dfc36711f862a6fcd59597873a7b93361567e7d31bbbfe10d6
Python
2,654
70
"""Download validation must remain active under optimized Python.""" import subprocess import sys import textwrap import pytest @pytest.mark.parametrize("optimized", [False, True], ids=["regular", "optimized"]) @pytest.mark.parametrize("existing_output", [False, True], ids=["invalid", "existing"]) def test_download...
89b834a6bc3e9d42871a460f275ed459bc163fd72b405c9e26646b6c4527edc1
Python
2,655
93
import functools import numpy as np import os from ..psams import PSAM from .data_directory import DATA_DIRECTORY MOTIFS_DIRECTORY = os.path.join(DATA_DIRECTORY, "motifs") SPLICE_MOTIFS_DIRECTORY = os.path.join(DATA_DIRECTORY, "splice_point_motifs") @functools.lru_cache(None) def read_rbns_motifs( directory=MO...
0089b5998c60c871c04004aed92baef22f9f51219f501609f950ecaa6d5ac8af
Python
2,657
69
import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import pandas as pd import os import seaborn as sns from tracking.timeSeries import createMaskTimeSeries from .PlotUtils import plotLeafTimeSeries from .FimgHandling import normalizeImg import gc def create_time_series(tray,resul...
f0728aef8eb033197f9e9f2d1cb074032c57c26910b948c3a1468734b7f7e1b0
Python
2,657
89
"""extract dynamic content """ import os.path import json import time import shutil from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver import Firefox as Browser from selenium.webdriver.firefox.options import Options #from selenium.webdriver.chrome.options import...
0023d9068a0a4e4c998cbf724b5ed1b2397e6a2d26340e6106542df8c3f66f4c
Python
2,658
100
import torch import os import logging from transformers import AutoTokenizer, AutoModelForMaskedLM, logging from tf_bind_transformer.cache_utils import cache_fn, run_once logging.set_verbosity_error() def exists(val): return val is not None def map_values(fn, dictionary): return {k: fn(v) for k, v in diction...
95d7a0dfc102ca70ffcef13a1edf5d2d6bbcfc6aabfe96b4e184c265a3442d33
Python
2,659
112
"""Functions dealing with correlation. This file is a part of BdPy. """ __all__ = ['corrcoef', 'corrmat'] import numpy as np from numpy.matlib import repmat def corrcoef(x: np.ndarray, y: np.ndarray, var: str = 'row') -> np.ndarray: """Return correlation coefficients between `x` and `y`. Parameters -...
cb85348cbefa96a0defd4ca8e43ce10a11ce33f2737e9a9b5024b49371c1c1d8
Python
2,659
82
import os import numpy as np import pickle as pkl from os.path import join as pjoin from scipy.spatial.distance import cdist from magicbox.io.io import CiftiReader from cxy_visual_dev.lib.predefine import proj_dir,\ get_rois, mmp_map_file, Hemi2stru, mmp_name2label anal_dir = pjoin(proj_dir, 'analysis') work_dir =...
116b7e34fd97a975649dc940ebfd27ace4e52f8495fcd099839b2297229dc329
Python
2,660
78
import logging import sys from .hpc import LsfWrapper, PbsWrapper, SgeWrapper, SlurmWrapper logger = logging.getLogger(__name__) def make_caper_run_command_for_hpc_submit(): """Makes `caper run ...` command from `caper hpc submit` command by simply replacing `caper hpc submit` with `caper run`. This als...
40313cfcfa692f392dadec42da709b2902779012edb3280b2c33d34ac73da728
Python
2,660
66
import unittest from unittest.mock import patch from carbontracker.components.cpu.generic import GenericCPU class TestGenericCPU(unittest.TestCase): def setUp(self): self.generic_cpu = GenericCPU(pids=[], devices_by_pid=False) self.cpu_power_data = self.generic_cpu.load_cpu_power_data() sel...
894a7fc08946c706ed83c39d0ae7e5eeed6264d57665e324bfe826c0c2aac831
Python
2,660
157
""" Cyclical color scales are appropriate for continuous data that has a natural cyclical \ structure, such as temporal data (hour of day, day of week, day of year, seasons) or complex numbers or other phase data. """ from ._swatches import _swatches, _swatches_continuous, _swatches_cyclical def swatches(template=No...
29eb015218b3b0ab52476672d6b0c1fc17d5c49b1216b58b42b39d4c2d329ad0
Python
2,661
81
import argparse import textwrap from promptsource.templates import TemplateCollection, INCLUDED_USERS from promptsource.utils import get_dataset parser = argparse.ArgumentParser(description="Process some integers.") parser.add_argument("dataset_path", type=str, help="path to dataset name") args = parser.parse_args(...
882adb87b5eb633e0584a6e13327226578f734aae1c6e2e9d6746d2af08846be
Python
2,661
60
""" evoked_basic plugin - analysis algorithms to analyzed evoked recordings The module can be imported independently of the base UI system. SimplyFire - Customizable analysis of electrophysiology data Copyright (C) 2022 Megumi Mori This program comes with ABSOLUTELY NO WARRANTY This program is free software: you can ...
13dd37ddbb65db4b51bac795f59bdda7120072a8ceca8585a11731a7dbb3ca0b
Python
2,662
79
from __future__ import annotations import pytest from pytest_celery import CeleryBrokerCluster, CeleryTestSetup, RabbitMQTestBroker from tenacity import retry, stop_after_attempt, wait_fixed from celery import Celery HEARTBEAT = 10 # gets the connection status from the rabbitmq side. def list_connections(broker: R...
35d252135aa2ffba477480868286d52222f9f3b2b57928f7e14c736c0265e23e
Python
2,662
75
""" Print every channel exposed by the Windows Energy Meter Interface (EMI), and the power each of them reports, to diagnose CPU power measurements. Usage: python examples/emi_channels.py [duration_in_seconds] """ import sys import time from codecarbon.core import windows_emi def main(duration: float = 5.0) ->...
523d18b8bf9b9c2a0a09cae2be80f3407f65856fc9e2e7f1113c52b42b1ae701
Python
2,662
65
from __future__ import division import argparse, time, logging, os, math, tqdm, cv2 import numpy as np import mxnet as mx from mxnet import gluon, nd, image from mxnet.gluon.data.vision import transforms import matplotlib.pyplot as plt import gluoncv as gcv gcv.utils.check_version('0.6.0') from gluoncv import data f...
c4afab8f18214559c39d09836fef2b43eef2e36f3853792ee069e68bac7a3c89
Python
2,662
75
# pylint: disable=keyword-arg-before-vararg """Mixup detection dataset wrapper.""" from __future__ import absolute_import import numpy as np import mxnet as mx from mxnet.gluon.data import Dataset class MixupDetection(Dataset): """Detection dataset wrapper that performs mixup for normal dataset. Parameters ...
bbc8cd6cb7cf3b356e3b3b5f1b40fd275a4e685b6f9b14ed42a3708a960ce239
Python
2,663
67
from typing import Generator import pandas as pd from mirp.settings.feature_parameters import FeatureExtractionSettingsClass from mirp._features.base_feature import Feature from mirp._features.morph_3d_features import generate_morph_3d_features from mirp._features.local_intensity_features import generate_local_intens...
c0ddf8291c697c0549370d84cae68c3bc9aebda6e72957872d57a3b96b3dd433
Python
2,663
106
"""Trial scheduler class.""" import numpy as np class BaseSchedule: """Base schedule. Args: n: int, number of conditions to schedule """ def __init__(self, n) -> None: self.n = n self.total_count = 0 # total count self.count = 0 # count within a condition s...
d5393c21f248689fbc8d03d6f960115ce2b8adaba173306a735decb8c0530f7a
Python
2,663
63
# -*- coding: utf-8 -*- """ Created on Mon Feb 6 13:21:43 2023 @author: Caterina Brighi """ #%% Import functions import os import shutil #%% Set Working directory data_supradir = 'Path to data directory' #Set working directory subjs_path = [ f.path for f in os.scandir(data_supradir) if f...
2a193d088090a577832845ce58799ae5447226206d1aacb9b1239a992d717fb0
Python
2,664
81
"""Celery Application.""" from celery import _state from celery._state import app_or_default, disable_trace, enable_trace, pop_current_task, push_current_task from celery.local import Proxy from .base import Celery from .utils import AppPickler __all__ = ( 'Celery', 'AppPickler', 'app_or_default', 'default_app', ...
89bb7aff6a736000f4ea64f0c04910b9735a2a191f3754897ea63fbc2a4f0df5
Python
2,664
68
# -*- coding: utf-8 -*- """ Created on Mon Feb 6 21:01:02 2023 @author: Caterina Brighi """ #%% Import functions import SimpleITK as sitk import numpy as np import os from ImageAnalysisFunctions import * #%% Set Working directory data_supradir = 'Path to data directory' #Set working direc...
0a5e1b4346983f7efaba440f685025be79628ea7efbe56a2cc06c3661ef72cc0
Python
2,666
88
# -*- coding: utf-8 -*- # @Author : Yue Liu # @Email : yueliu19990731@163.com # @Time : 2021/11/25 11:11 import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.manifold import TSNE def t_sne(embeds, labels, sample_num=2000, show_fig=True): """ visualize embedding by t-SNE...
17474962f0140b435eea98003cac0f1929c2e2c22a7dc17cded7a4f0ec44aeb2
Python
2,666
92
""" ANCOVA ====== Example 1 --------- Based on [1]_, `Exercises <http://www.bio.ic.ac.uk/research/crawley/statistics/exercises/R6Ancova.pdf>`_ (page 8). """ # Author: Christian Brodbeck <christianbrodbeck@nyu.edu> from eelbrain import * y = Var([2, 3, 3, 4, 3, 4, 5, 6, 1, 2, 1, 2, 1, 1, 2, ...
bb122b487f7fd6530a79f92dd41230f983ba780d0a2677b08d60879f37fa8f37
Python
2,666
56
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-17 09:49 from __future__ import unicode_literals import biomedisa_app.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True depende...
d2692a78eb862214c35fccbc2d7ee9fdf64b584542bb81f5be95a546cee294da
Python
2,666
65
"""01. Predict with pre-trained SSD models ========================================== This article shows how to play with pre-trained SSD models with only a few lines of code. First let's import some necessary libraries: """ from gluoncv import model_zoo, data, utils from matplotlib import pyplot as plt ###########...
1281f5c64c18362935626a34e16c2dbcc2eb796c29d469cfd493d0a5aa4efe93
Python
2,667
73
""" Copyright (c) 2022 EPFL-BBP, All rights reserved. THIS SOFTWARE IS PROVIDED BY THE BLUE BRAIN PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE BLUE BRAIN PROJE...
22a6d7a209e474923b1852169749516dded8c9b3ac6bdb7ced0249da559fd822
Python
2,667
78
from typing import Optional, Union import numpy as np from anndata import AnnData from numpy.random.mtrand import RandomState from .._compat import Literal import scanpy _InitPos = Literal["paga", "spectral", "random"] def run_umap( adata: AnnData, min_dist: float = 0.5, spread: float = 1.0, n_comp...
892e16d4178cbdb03f1bb659743cbb2e3a24231bc1d57cb88641c713a4c9c11e
Python
2,667
87
from math import sqrt from model import common import torch from torch import nn import torch.nn.functional as F def make_model(args, parent=False): return FSRCNN(args) class FSRCNN(nn.Module): """ Args: upscale_factor (int): Image magnification factor. """ # def __init__(self, upscale_f...
a8880cb3783a6146a45cfdb1c24476cb10058446c1a25d1778e94af92453329e
Python
2,667
96
#!/usr/bin/env python #========================================================================= # # Copyright NumFOCUS # # 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:/...
24ac274a2335ac87e6b6334b3f2fae080a2a7bb132c8ef033d5f2f7ccde19bce
Python
2,668
104
import pandas as pd import polars as pl import polars.testing.parametric as plst import pytest import seqpro as sp from hypothesis import given, settings from polars.testing import assert_frame_equal from pytest_cases import parametrize_with_cases settings(deadline=500) def bedlike_strategy(): return plst.datafr...
55c8767c539dfa3ceb434cec23cae23eaecc9444c5923da8d45c1690715fa26b
Python
2,668
81
"""Tests for Trace-level semantic facet finders.""" from __future__ import annotations import pytest import torch from torch import nn import torchlens as tl from torchlens import trace as trace_fn class DistilBertSdpaAttention(nn.Module): """Tiny DistilBERT-like attention block for recipe tests.""" def _...
065da9db72a0c435d59c05feb21efa84dd5b8d636c32a13b67eac73995c7ee77
Python
2,669
90
"""DLRM: Deep Learning Recommendation Model. Naumov et al., 2019, arXiv:1906.00091. DLRM processes dense features through a bottom MLP, sparse categorical ids through embedding tables, forms explicit pairwise dot-product feature interactions, and feeds those interactions to a top MLP. This compact version keeps that...
9392895717c50192f1966b95fdfb65193bd790e801e3e877b32752abe33d15fc
Python
2,670
73
from typing import Dict import torch from rbm.custom_fn import one_hot @torch.jit.script def sample_hiddens( chains : Dict[str, torch.Tensor], params : Dict[str, torch.Tensor], beta : float=1. ) -> Dict[str, torch.Tensor]: """Samples the hidden layer conditioned on the state of the visible layer....
99837f5a8f20cba8119df37579feef3ebc4d1892e3407395f08d437b88442b1c
Python
2,670
93
# randomamp.py # Copyright (C) 2013 Bastian Venthur # # 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 2 # of the License, or (at your option) any later version. # # This program ...
d8e1375bf972558dc990f267c3a594387b95c3e456da249aed43208c29c05ec4
Python
2,671
76
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
106e133c7723a494657a34eae8f9d3715f0d029dbcb4cd031c15c79c75380644
Python
2,672
77
import os import glob import pickle import pandas as pd import numpy as np import loompy as lp from dask.diagnostics import ProgressBar from arboreto.utils import load_tf_names from ctxcore.rnkdb import FeatherRankingDatabase as RankingDatabase from pyscenic.utils import modules_from_adjacencies, load_motifs from py...
654af3459712716ad6d980351904c817b821fc6972c61dcd59164f4b349907c0
Python
2,672
101
"""Run data commands in parallel.""" from __future__ import annotations import argparse import os from os.path import dirname, join, splitext from subprocess import DEVNULL, check_call from typing import Callable, List from joblib import Parallel, delayed from tqdm import tqdm def parse_arguments() -> argparse.Nam...
cf47be7987c17a0506e636188692f3b30e700119135fd280608414f2d5743538
Python
2,672
94
#!/usr/bin/env python import argparse import sys import xml.sax as sax import readfile from rest_tool_functions import DictHandler def getIDofLine(line): arr = line.split(">") if len(arr) > 1: aid = arr[1].split("<")[0] return aid else: return "-1" # get xml of all aids with c...
20ced63f5e469cf3caa1e9a09c2c33be8081e27d232dadd4f60c547473357724
Python
2,673
72
''' Copyright 2021 Twente Medical Systems international B.V., Oldenzaal The Netherlands 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 requir...
59df7786777273f4ffc8efa6478727b465227622be9caad46a41fa71b8977b06
Python
2,673
86
from collections import defaultdict import numpy as np from shelved.plot_base_importance import plot_base_importance, Motif def load_from_paper(): from_paper = """ sequence: atggttgtactgatggcttgtttttcattttttttgtgctttttggtccatctattaa red : --------*--**-------------*----------------------*---*---* ...
820bcc953df6b63eac89c38cb64c3adce8686037b3727da3c27baea02395f26e
Python
2,673
80
""" Model download for sc_crop. Models are cached in ~/.cache/sc_crop/<model_version>/. SHA256 is verified on every load. The model version (_MODEL_TAG) is decoupled from the package version. To reclaim disk space from old versions: rm -rf ~/.cache/sc_crop/v0.0.9 """ import hashlib import urllib.request from pat...
01cd396ba6c4747444a8193837fd5a26c68de39c1c1e508359417eab02071b1c
Python
2,674
84
from collections import defaultdict import h5py import attr import numpy as np import tqdm.auto as tqdm @attr.s class SpliceAIDatafile: """ Represents a SpliceAI datafile, as created by `create_spliceai_datafile`. """ datafile = attr.ib() names = attr.ib() names_backmap = attr.ib() chro...
4a11b20183318d80fe01ee3912a31352ed52863e2080591730f6d42b9e73d984
Python
2,674
63
# pylint: disable=arguments-differ,line-too-long,missing-docstring,missing-module-docstring from mxnet.gluon import nn from mxnet.gluon.nn import Conv2D, HybridBlock, BatchNorm, Activation __all__ = ['SplitAttentionConv'] class SplitAttentionConv(HybridBlock): # pylint: disable=keyword-arg-before-vararg def ...
50e563b353fc5541518a77f44e804d0bce49bf1eeb688af20862c4014f3ae984
Python
2,674
92
"""Screenshots for quick guide import ts (not working automatically)""" import pathlib import shutil import sys import tempfile import matplotlib.pylab as plt import numpy as np import pandas import seaborn as sns from PyQt6 import QtCore from PyQt6.QtWidgets import QApplication from pyjibe.head.main import PyJibe d...
0b4db1d82f1ffff415240b1abf810973846a36034fef533394513c0b7e6844e2
Python
2,675
76
"""End-to-end dispatch-consumption conformance (sol probe, live runtime). A capability flag flipped True with a bound-but-undispatched implementation must refuse at ``tl.trace()``, never capture while silently ignoring the requested option. The policy-level biconditional lives in ``test_capability_truth.py``; these te...
ebf7aa4f30e6e9041d4f59aba8ca712918c51c4ca2a7385bb6151e971f56000a
Python
2,675
87
import json import os import pickle import tempfile import pandas as pd from .leafcutter_data import load_all_leafcutter_data from modular_splicing.data_pipeline.create_datafile import produce_datafiles from modular_splicing.data_pipeline.create_dataset import produce_datasets_from_datafile from .compute_psi import ...
244d1922df606d72aded23846bf629d6d8eca61dfd409f68e9eb160bfab1e45f
Python
2,676
97
import pytest from pyrosm import get_data @pytest.fixture def test_pbf(): pbf_path = get_data("test_pbf") return pbf_path @pytest.fixture def helsinki_pbf(): pbf_path = get_data("helsinki_pbf") return pbf_path def test_parsing_landuse_with_defaults(test_pbf): from pyrosm import OSM from ge...
420abfca21177d3cda12b26826ddcc729cbe8474c11d104a21ff54cf12ccc790
Python
2,676
80
import torch import matplotlib.pyplot as plt import brainbox.physiology.rfs as rfs def build_rfs(model, rf_len=5, t_len=100, noise_var=10, samples=200, batch_size=50, layer=1, device="cuda"): def model_output(noise): with torch.no_grad(): print(f"noise {noise.shape}") print(model(...
63bd44626cfc96026e2cf216b422ee2afb990dbe541d7239518afc205281e09a
Python
2,676
94
import torch from torch import nn, optim import cv2 import numpy import torch.fft from complexPyTorch.complexLayers import ComplexConvTranspose2d,ComplexConv2d from complexPyTorch.complexFunctions import complex_relu class CDown(nn.Module): def __init__(self, in_channels, ...
6612cb7e3a4606547c17e5e9bd5c8ff0d9222d0cb31888e7154eaea6b0c3aa77
Python
2,676
90
""" utility code without big impact of the main function of the actual model """ import torch from matplotlib import pyplot as plt import matplotlib.pyplot as plt import matplotlib.ticker as ticker import torchvision import numpy as np import warnings import seaborn as sns warnings.filterwarnings( action="ignore...
e14bd936126cd11f32bafc61ceda11cfee5d33d99ed8ff86222f03d7186701c3
Python
2,676
85
import logging import yaml import copy import argparse from bson.objectid import ObjectId from pymatgen.core import Molecule from atomate.qchem.fireworks.core import FrequencyFlatteningOptimizeFW from atomate.common.powerups import add_tags from fireworks import LaunchPad, Workflow from instance_mongodb import ins...
4204d76694aba4304a587f8d1a82d65d15d6a8f97be1f9d1dd94d460da04f26f
Python
2,677
84
import os import sys from typing import List from pathlib import Path import itertools import numpy as np import matplotlib.pyplot as plt import snapatac2 as sa2 with open("../meta/mba.whole.sample.lst", 'r') as f: samples = [ l.strip() for l in f.readlines()] # * summarize doublet removal under bmat bmat_dlt_di...
b42c9f4ac2be76c22a1a23f295de292e55d3057c7f81d6cd5125e2a07c07d481
Python
2,677
64
import os from data.base_dataset import BaseDataset, get_params, get_transform from data.image_folder import make_dataset from PIL import Image class AlignedDataset(BaseDataset): """A dataset class for paired image dataset. It assumes that the directory '/path/to/data/train' contains image pairs in the form ...
1b138f6db6a9a8370237d0b1fb7986094c58e10d81f7932a2a423b5f23a8f571
Python
2,678
78
#!/usr/bin/python #-*-coding:utf-8-*- # 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 wi...
971885b241700ce1ed2d198f0fa8a44b215d6c3ef70b484395660bb0f64bebd3
Python
2,678
65
'''Extracts the distributions associated with NeuroM module''' import neurom as nm from neurom import stats import numpy as np def transform_distr(opt_distr): '''Transforms distributions''' if opt_distr.type == 'norm': return {"norm": {"mean": opt_distr.params[0], "std": opt_...
9a17fb78d7c8f9e70298edd8882ab85b8ba919a95db79863a5d426162b4afd0b
Python
2,678
85
import operator import time import pytest from celery.utils.functional import noop class test_thread_TaskPool: def test_on_apply(self): from celery.concurrency import thread x = thread.TaskPool() try: x.on_apply(operator.add, (2, 2), {}, noop, noop) finally: ...
add699259a052a491ff71d6471c418222936c6cc80bd16964117962f8c32c663
Python
2,678
88
from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA import numpy as np import pandas as pd from scipy.io import loadmat, savemat import unidecode meg = loadmat('bids/derivatives/meg-derivatives/grand_ave/matrices/modality-picture.mat') target_word_labels = [w.strip() for w in meg['...
1f769b2271947c151b6c59ab58422c4218c17d5e88f97eb8c416c380a8386670
Python
2,679
87
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Import raw (MaxFiltered) MEG data to remove metadata then save in same format for further BIDSifying. @author: mikkel For information about NatMEG-PD please refer to the data descriptor: Vinding, M. C., Eriksson, A., Comarovschii, I., Waldthaler, J., Manting, C. L.,...
5fabcb82f736be983f3bbe0a8dd164b66b4bb0dbe788980b1368d58c9211817a
Python
2,679
75
""" This script replicates the finding by David and Friston 2004 NeuroImage that the frequency of the Jansen-Rit model can be tuned between delta and gamma frequencies by adapting the synaptic time constants. """ from pyrates import grid_search import matplotlib.pyplot as plt from seaborn import heatmap from scipy.sig...
9ca4c99801cd4aa737d20f79fcd3c3b6fab33f819681837404d874d79005cd83
Python
2,679
66
# Adapted from https://github.com/pytorch/pytorch/blob/v2.7.0/torch/_library/triton.py # The PyTorch implementation simply ignores the schema argument, we simply modify it to use schema. from typing import Optional, Callable, Iterable, Union from torch.library import custom_op, CustomOpDef from torch._library.triton ...
0b5bba9d25c019acd5526ae7aa630eaaa5ab8755f7f0238cc77e3996c393388a
Python
2,680
72
class BiomedisaParameter(): allaxis: bool = False denoise: bool = False nbrw: int = 10 sorw: int = 4000 smooth_active: bool = False smooth: int = 100 clean_active: bool = False clean: float = 0.1 fill_active: bool = False fill: float = 0.9 ignore: str = 'none' only: str =...
828925b355f3d901943ea9bd58c476586d884363dbb63755a4950f37a6695559
Python
2,681
53
# Adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py import torch import torch.nn.functional as F from einops import rearrange def unpad_input(hidden_states, attention_mask, unused_mask=None): """ Arguments: hidden_state...
be1717c02b0e6abd1c6033d9a3b205fee9510ec186bd9cde3c8792a5209580b9
Python
2,681
91
#!/usr/bin/env python3 # coding: utf-8 """ Created on July 10 2019 Authors: Nathan De Lara <nathan.delara@telecom-paris.fr> """ from abc import ABC from typing import Union import numpy as np from scipy import sparse from scipy.sparse.linalg import svds from sknetwork.base import Algorithm class SVDSolver(Algorith...
38a650b354e967fc64d25b4e55a638576e5fde3ac35806c7ddc3d18a8ede553a
Python
2,682
61
def motif_model_types(): from .learned_motif_model import ( LearnedMotifModel, ) from .no_motif_model import NoMotifModel from .parallel_motif_model import ParallelMotifModels from .adjusted_motif_model import AdjustedMotifModel from .reprocessed_motif_model.reprocessed_motifs import Rep...
3a9ad02704702dadcb7bb83c71cc233d3c2a61857d5de9461940873074cdc8b6
Python
2,682
67
from __future__ import annotations import pytest import torch from lightly.utils import dependency if not dependency.timm_vit_available(): # We do not use pytest.importorskip on module level because it makes mypy unhappy. pytest.skip("TIMM vision transformer is not available", allow_module_level=True) from...
fd94eca67d367d21ba46479c47c35ebf31649663bf85e7d2abbbdf72f90420ce
Python
2,682
75
"""Captum ``layer()`` against the REAL captum package. ``tl.bridge.captum.layer`` shares Grad-CAM's resolver: an op label resolves to the outermost module whose output its tensor is, and LayerGradCam on that module is bit-identical to LayerGradCam on the module named directly. """ from __future__ import annotations ...
bdf64d27c0b3d9adf3b6674ed7c56b5be4840167e562067574d93633fba7728f
Python
2,683
88
## Read write encoder import sys,os from datetime import datetime,timezone,timedelta import serial import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np import multiprocessing from scipy.ndimage.filters import gaussian_filter1d from tkinter import filedialog import csv port = 'COM13' max_nu...
be54fe7b1501eeb3e8f942173d3b58cf4e2fe16ebe574b9f334ed536803a23d3
Python
2,684
79
""" A general test to try to find out if anything is wrong with the API. """ import os import random import tempfile import time import unittest from _constants import DRAW_FRAMES, VIDEO from ethoscope.core.monitor import Monitor from ethoscope.drawers.drawers import DefaultDrawer from ethoscope.hardware.input.camer...
d0aacefb29dcc84d0e64fe982871a215bdc4960da62977b026eaa76cc59477e8
Python
2,684
78
import gzip import io import os from pathlib import Path import pandas as pd import wget def get_download_path(): """ Returns a path to download files to If EUGENe is installed, returns the path specified in settings.dataset_dir Otherwise, creates a directory called 'seqdatasets' in the current ...
df327596502602b9f7a706588e16596f6dc4755428a0146ad259c69fe0257987
Python
2,685
85
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function import io from os.path import dirname from os.path import join from os import path from setuptools import find_packages from setuptools import setup import os from Cython.Build import cythonize ...
0c16b8d000d013b531454acfb1787666793f1bf802ad6e3a5c9a71ae1026b3be
Python
2,687
73
"""Parameter converters. Notes ----- Parameter converters should have the following properties, depending on component: - for 'aperiodic' parameters : callable, takes 'fit_value' & 'model' as inputs - for 'peak' parameters : callable, takes 'fit_value' & 'model', 'peak_ind' as inputs """ import numpy as np from spec...
3d5d5af705dc0c3d274fc3d7fc1814577c6a098e108549755b5c243d81f55c15
Python
2,687
85
from typing import Optional, Union from anndata import AnnData from matplotlib import pyplot as plt from pathlib import Path import os from PIL import Image Image.MAX_IMAGE_PIXELS = None def image( adata: AnnData, imgpath: Union[Path, str], library_id: str, quality: str = "hires", scale: float = ...
70cb8a5b57bcee9776281d3556206281e15bbd424820c86818e7a66c4405b027
Python
2,687
90
#!/usr/bin/env python import argparse import re from Bio import SeqIO from Bio.Alphabet import generic_dna from Bio.Seq import Seq from Bio.SeqUtils import nt_search choices = [ "embl", "fasta", "fastq-sanger", "fastq", "fastq-solexa", "fastq-illumina", "genbank", "gb", ] def find_p...
8e4d82792643597ab581df964d12958136291bdb6bce427c1f93cb48ab0644d0
Python
2,687
87
""" using prody to extract the pocket """ import os, re import prody as pr from openbabel import openbabel as ob #import subprocess #os.environ["BABEL_LIBDIR"] = "/home/shenchao/.conda/envs/my2/lib/openbabel/3.1.0" def write_file(output_file, outline): buffer = open(output_file, 'w') buffer.write(outline) buffer.cl...
5edbfd3f2e75944e3ab90db66f8e209f320639ebc28903bc1b2ade79eb246cf2
Python
2,688
85
import os from pathlib import Path from anndata import AnnData from matplotlib import pyplot as plt from PIL import Image Image.MAX_IMAGE_PIXELS = None def image( adata: AnnData, imgpath: Path | str | None, library_id: str, quality: str = "hires", scale: float = 1.0, visium: bool = False, ...
7f89e8c8a6445468ddaf8e3a8505c5c3e4a6db0e973dda552d488d8dfd279d49
Python
2,688
103
#!/usr/bin/env python3 '''Adds show_arrows command to pymol, which takes an xyz file''' import sys import os from pymol import cmd, cgo, CmdException from chempy import cpv def draw_arrow(xyz1,xyz2, radius=0.5, gap=0.0, hlength=-1, hradius=-1, color='blue red', name=''): ''' Draw an arrow; borrows...
ac01d7927c3f05abb4902b94b8b1d41a64d48adfe26e16826a7797b1d10f9156
Python
2,688
71
#!/usr/bin/python #from distutils.core import setup from setuptools import setup #import path import subprocess import versioneer #here = path.abspath(path.dirname(__file__)) #version = '0.1.4' def version_from_git(): try: proc = subprocess.Popen(["git", "describe", "--tags"], stdout=subprocess.PIPE) ...
d1cd154dfb02b354d1d3c5957ab5d6fd63a3136f6f808d9b1e187b796746113e
Python
2,688
97
# Copyright 2024 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
e3c855d041b4f062abd6e3425cce88a3e2c52fd07420f36342b7658179a5efe2
Python
2,689
97
# randomamp.py # Copyright (C) 2013 Bastian Venthur # # 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 2 # of the License, or (at your option) any later version. # # This program ...
99b3bb7109f689077adf879357deff5cb4db7c8a848a6e58f384564be306ccb4
Python
2,691
77
""" Gregory Way 2017 PanCancer NF1/RAS Classifier scripts/within_tissue_analysis.py Usage: Run in command line python within_tissue_analysis.py with the following required flags: --genes comma separated string of HUGO gene symbols and the following optional flags: --diseases c...
5131d425e170e47f7402ef86aa509af6c1bf72f8e62d15f78f338f44c5a5359f
Python
2,692
115
import numpy as np import subprocess from math import sqrt from sklearn.metrics import average_precision_score from scipy import stats def get_aupr(Y, P, threshold=7.0): # print(Y.shape,P.shape) Y = np.where(Y >= 7.0, 1, 0) P = np.where(P >= 7.0, 1, 0) aupr = average_precision_score(Y, P) ...
bcc7761dd9c0ec861cc6e1ebe8b8b4b4928661e2b1168ea2a4e219084d5212d0
Python
2,693
82
"""Tests for the xcp_d.cli.version module.""" from datetime import datetime, timezone from packaging.version import Version from xcp_d.cli import version class _FakeResponse: def __init__(self, tags, next_url=None, status_code=200): self._tags = tags self._next_url = next_url self.statu...
f7588a86ff7dffadfe3cc251b47a94e62f72005c9c9c363cba5cd8170c9d1058
Python
2,694
92
"""Tests that gym.spec works as expected.""" import re import pytest import gym def test_spec(): spec = gym.spec("CartPole-v1") assert spec.id == "CartPole-v1" assert spec is gym.envs.registry["CartPole-v1"] def test_spec_kwargs(): map_name_value = "8x8" env = gym.make("FrozenLake-v1", map_na...
f7927b399d7fda3522a29fc99b636d551d4ff1c6a3384a3c5e06e8ed95e04f0d
Python
2,694
74
from PyQt5 import QtCore from .tracker_widget import TrackerControlWidget class TrackerController(QtCore.QObject): def __init__(self, tracker=None, parent=None): super(TrackerController, self).__init__(parent) self._tracker = tracker self.tracker.tracker_controller = self self.wi...
2e8ff1967777587be8014ef971ef8463c51a27dfd6f1e634eb184a17e21231d0
Python
2,695
67
"""02. Predict with pre-trained Faster RCNN models ============================================== This article shows how to play with pre-trained Faster RCNN model. First let's import some necessary libraries: """ from matplotlib import pyplot as plt import gluoncv from gluoncv import model_zoo, data, utils #######...
cc8b72808f5c2ccad0a272e13ae6efa2b125539a9a66e9857e331eb61c78ac3c
Python
2,695
62
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """"tests for distances.py""" import unittest from sknetwork.data.test_graphs import * from sknetwork.path.distances import get_distances class TestDistances(unittest.TestCase): def test_input(self): adjacency = test_graph() with self.assertRaises(V...
f474b802b3ffac1342f3d5e90b323b02edddf71cc8fe7add2388350f11ed1a52
Python
2,695
92
import numpy as np from numpy.random import default_rng import pathlib from mpi4py import MPI from causal_optoconnectics.tools import conditional_probability, joint_probability, roll_pad from causal_optoconnectics.generator import ( construct_connectivity_filters, construct_connectivity_matrix, simulate, ...