sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
c1b9983242b52ccdf88e315e93c545258c9a75efcbeaeed7aa3a5da86ca84705
Python
1,625
95
""" Tests for :mod:`numpy._core.numeric`. Does not include tests which fall under ``array_constructors``. """ from __future__ import annotations from typing import cast import numpy as np import numpy.typing as npt class SubClass(npt.NDArray[np.float64]): ... i8 = np.int64(1) A = cast( np.ndarray[tuple[i...
e9a1a039db46a494a03d9973a68c3eb5c1d748faab25e29a8169c58a585e59e3
Python
1,626
74
import platform import pytest from numpy.testing import IS_64BIT from . import util @pytest.mark.skipif( platform.system() == "Darwin", reason="Prone to error when run with numpy/f2py/tests on mac os, " "but not when run in isolation", ) @pytest.mark.skipif( not IS_64BIT, reason="32-bit builds are b...
325b494b6ef77dfb351ff113898364b982849379505646740bf8ab04ebf63f08
Python
1,627
72
import importlib import sys _SHELL = None _SHELL_BACKEND_SETTER = None def register_shell(shell): global _SHELL _SHELL = shell return shell def get_shell(): return _SHELL def get_shell_namespace(): shell = get_shell() if shell is not None and hasattr(shell, "user_ns"): return she...
e73b10b48f563ef152379be2423f4b1ab697c1369e0bd2c7ef2e9264a3dfaf8e
Python
1,630
55
"""Generate a plot of fiber coordinates overlaid with a plot of the sample. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. ...
77de0aeb80b992d08dc55c5a8a30a14ea32f18368aa2ab60a296257536264cbc
Python
1,631
56
"""Generate a plot of fiber coordinates overlaid with a plot of the sample. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. ...
4d5a1b2e821799451402261d38812c9fc3c18cf21ae9ca5fecf21aafe179add4
Python
1,634
70
from abc import ABC, abstractmethod import numpy as np from typing import Dict, Any, Optional, Tuple class BaseAgent(ABC): def __init__(self, state_dim: int, action_dim: int, **kwargs): self.state_dim = state_dim self.action_dim = action_dim self.generation = 0 self.iteration = 0 ...
53b86b9e76543d2f14d9e42fb5fcf912577e9f99b095b04185fe2efe88afbd2c
Python
1,634
44
from pathlib import Path import sys html_path = Path(sys.argv[1]) html = html_path.read_text(encoding="utf-8") required = [ '<link rel="canonical" href="https://peterponyu.github.io/iAODE/"', 'name="robots" content="index, follow"', 'property="og:url" content="https://peterponyu.github.io/iAODE/"', 'na...
1f93eda1ec0f4e2cdb62f3783606f2a0719d49a0368f9b7030c63cff5c516f5b
Python
1,635
56
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class ZINBLoss(nn.Module): def __init__(self): super(ZINBLoss, self).__init__() def forward(self, x, mean, disp, pi, scale_factor=1.0, ridge_lambda=0.0): eps = 1e-10 scale_factor = scale_factor[:, No...
7f89cd21975dda87506e3cfbed726190eaceb3d87efe73163298558ffd4bef78
Python
1,635
48
import numpy as np import pandas as pd import yaml from pathlib import Path import nrrd from skimage.measure import regionprops from sklearn.neighbors import KDTree from CrystalTracer3D.io import CrystalReader from tqdm import tqdm if __name__ == '__main__': with open('config.yml', 'r') as ymlfile: cfg = ...
90451ba93b2127d546afda0b744b793d56756b03cb2cca793da1bfa80ddd1be8
Python
1,635
53
from torchvision import datasets, transforms from manipulate import UnNormalize # specify available data-sets. AVAILABLE_DATASETS = { 'MNIST': datasets.MNIST, 'CIFAR100': datasets.CIFAR100, 'CIFAR10': datasets.CIFAR10, } # specify available transforms. AVAILABLE_TRANSFORMS = { 'MNIST': [ tran...
08884a363ec5f8e3c34fbcb227b02e8ff3a7b8ebe2ad11c7306b244f2ab375fc
Python
1,637
47
import sys import os import time sys.path.append("../../../../") sys.path.append("../") import numpy as np import music21 as m21 from conf.conf import * from api.music_engine_api import EngineAPI if __name__=="__main__": musicEngine = EngineAPI() musicEngine.cortexInit() #------------Bach dataset learning...
e34d0dc3ab3760fc949bfc0b8553fd99c3ea6eb6e23953073b3a77fae9a0dd19
Python
1,638
39
import configparser class Config(object): def __init__(self, config_file): conf = configparser.ConfigParser() try: conf.read(config_file) except: print("loading config: %s failed" % (config_file)) #Hyper-parameter self.epochs = conf.getint("Model_Se...
5241b4a650be9247276cd2831ac369920d36cf3064386e0fc7b039c195becc9f
Python
1,639
49
#!/usr/bin/env python3.7 """Sets up environment path variables for the ASCENT. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascen...
f54f9c5863fd4d90b0d33b7bf490f18f3dc7bf19aa24112a7dc3b18155f97894
Python
1,639
78
""" Cross check the correctness of the density matrix simulator and the Monte Carlo trajectory state simulator. """ import os os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # cpu is fast for small scale circuit simulation from tqdm import tqdm import jax import tensorcircuit as tc tc.set_backend("jax") n = 5 nlayer = ...
826555f96934b94512c29e60c7f0bd062d5b93950073f6b99952c0b8f129f79c
Python
1,641
47
import numpy as np from scipy.stats import spearmanr, kendalltau def compute_metrics(output_list, target_list, logspace_input=False): if logspace_input: output_list_nonlog = np.exp(output_list) - 1 target_list_nonlog = np.exp(target_list) - 1 else: output_list_nonlog = output_list ...
bc77f23c93313511da350a0da7d3334b7b408f04f83ce2405a8bee9f1d72b1e2
Python
1,641
53
from abc import ABC, abstractmethod from typing import Dict, Tuple, Union from numpy import ndarray # TODO: Add docstrings class DynamicsBase(ABC): """TODO.""" @abstractmethod def get_solution( self, t: ndarray, stacked: True, with_keys: bool = False ) -> Union[Dict, Tuple[ndarray], ndarray]...
cc6bcb815b0a66657a6af3ebad11d6e67b04f7ad98d5144b6fd8914078082bbc
Python
1,641
55
import torch import numpy as np device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def print_log(print_string, log): #print("{}".format(print_string)) log.write('{}\n'.format(print_string)) log.flush() def unit(x): if x.size()[0]>0: xnp=x.cpu().numpy() maxx=np.percen...
42d29c6f5466fce5948293461f559184dc4cae472c517d736d8a110471450be8
Python
1,642
41
# License: GNU Affero General Public License v3 or later # A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt. """ A class for CDS motif features """ from collections import OrderedDict from typing import Dict, List, Optional from Bio.SeqFeature import SeqFeature from .domain im...
1c58d2ae265333a0b16c3472311b345fcd9cc8bb4101de50d89139cccbdf8f8c
Python
1,643
61
from abc import abstractmethod from pathlib import Path from typing import List, NamedTuple, Tuple, Union import numpy as np from ..models import IMCFileAcquisitionModel, IMCFileModel, IMCFilePanoramaModel from ..models.base import IMCFileTreeItem class ImageDimensions(NamedTuple): x: float y: float wid...
69e4a598855ae39f4875ffcbd638c45bc262e464bb07fb0847fd9adae3198afa
Python
1,643
53
import asyncio from typing import Generator from kani.streaming import StreamManager import nest_asyncio def _seconds_to_days_hours(ttl_seconds): # we need to convert the time to a human-readable format, e.g. 28 days, 18 hours (rounded to nearest hour) # we don't want the default datetime.timedelta format ...
1a9740e5e82fd769bb9ede9f33a45ad0bd8e8534a2461879149217a8b62c0a31
Python
1,644
64
#!/usr/bin/env python3.7 """Plot the Ve across a fiber length. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. RUN THIS FRO...
2b4b0cb300c50a20bd9c757b821240b3c0a3c3b7c4a224fc51c70fa85f38835f
Python
1,645
54
import h5py import numpy as np from torch_geometric.data import Batch, Data, Dataset # , InMemoryDataset import torch from ase.data import atomic_numbers from torch_geometric.data import DataLoader from tqdm import tqdm import os class CepDataset(Dataset): def __init__(self, npz_dir): super(CepDataset, s...
8e5b822df1bde1533572e5fee5170b141962ff268966922f995b8cc5129126b7
Python
1,645
47
""" Test scripts Test that we can run executable scripts that have been installed with numpy. """ import sys import os import pytest from os.path import join as pathjoin, isfile, dirname import subprocess import numpy as np from numpy.testing import assert_equal, IS_WASM is_inplace = isfile(pathjoin(dirname(np.__fil...
a7a8c06cc892f0764271de1773b560370fc551b07f3ec14a7b3f8dc1fae84435
Python
1,645
55
import sys from molmap.utils import distances, calculator from molmap import feature import pandas as pd import numpy as np from rdkit import Chem from tqdm import tqdm tqdm.pandas(ascii=True) def loadnpy(filename, N, dtype, mode = 'r'): f = np.memmap(filename, mode = mode, dtype = dtype) ...
6fa6cfa4e7ed03b92395660c09770aff0ba5b85ab2a95c42c186d84f2d412954
Python
1,647
71
import sys import os import pytest # NOTE: If Intel OpenMP abort occurs on Windows (PyTorch + scipy DLL conflict), # set KMP_DUPLICATE_LIB_OK=TRUE in the test runner environment, e.g.: # $env:KMP_DUPLICATE_LIB_OK = "TRUE" thisfile = os.path.abspath(__file__) modulepath = os.path.dirname(os.path.dirname(thisfile)) ...
ae0efbe92bce3acd11184f9c03090f9e690d9222892dd90edf1433fd422be0f9
Python
1,647
55
import numpy as np import torch import torch_scatter class DipeptideBondedCombiner: r""" Combine the energies and forces of the dipeptides and ACE-NMEs. """ @staticmethod def energy_combine( dipeptides_energies: torch.Tensor, acenmes_energies: torch.Tensor, ) -> np.ndarray: ...
cae4fb4c9d76182398ca07f224f00febf359a180ada79d8fbe28b1e94b8dfdec
Python
1,649
50
#!/usr/bin/env python3.7 """Sets up environment path variables for the ASCENT. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascen...
314730c5b84c0db2ee88a17178fa5af2c81e0ff519f4aa329bd49b782ab7301d
Python
1,650
60
# Copyright (C) 2008-2012 Bernd Feige # This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING). # Base class for parsing the very simple VOGL .ps output scale_factor=1.9 # Divide all coordinates by this to avoid overflowing oodraw's coordinates class voglps(object): def __init__(self,psfile): ...
f31a6eb6fbbee6ad843ef537679bbcf0990bec6cda441734bc4944c0cc6a7841
Python
1,650
50
from __future__ import annotations from ..utils._typed_cache import typed_cache from ..counts._count_words import count_words from ..counts._count_polysyllable_words import count_polysyllable_words from ..counts._count_long_words import count_long_words from ..counts._count_monosyllable_words import count_monosyllable...
ac99c246543ba59b04126321b100e00bfa4ac831f13f94cf4bacd53c6b2072ef
Python
1,651
48
"""The optimizer tries to constant fold expressions and modify the AST in place so that it should be faster to evaluate. Because the AST does not contain all the scoping information and the compiler has to find that out, we cannot do all the optimizations we want. For example, loop unrolling doesn't work because unrol...
7cb4d9bac8051cf5cee28ae9ca098720e1ba2502f361c75b4c91d1befb0dd2c3
Python
1,652
67
import numpy as np import pytest import pandas as pd from pandas.core.arrays.integer import ( Int8Dtype, Int16Dtype, Int32Dtype, Int64Dtype, UInt8Dtype, UInt16Dtype, UInt32Dtype, UInt64Dtype, ) def test_dtypes(dtype): # smoke tests on auto dtype construction if dtype.is_signe...
6980c6c23f49468a736ae2c50d806b4e451e0955cd0e3c137786267c9e5bd002
Python
1,653
48
import os from glob import glob import pandas as pd from ibc_public.connectivity.utils_fc_estimation import get_ses_modality from nilearn.connectome import sym_matrix_to_vec ### create sc_data dataframe for native space cache = DATA_ROOT = "/storage/store2/work/haggarwa/" n_parcels = 200 sub_ses, _ = get_ses_modality(...
f00d89f3d5ebafd5afa742d75641bfb4871d6eb72e72cf349d2345de35b2582a
Python
1,654
66
from __future__ import annotations import argparse import sys import traceback from pathlib import Path from typing import TYPE_CHECKING from qtpy.QtGui import QIcon from qtpy.QtWidgets import QApplication from micromanager_gui import MicroManagerGUI if TYPE_CHECKING: from collections.abc import Sequence fr...
2dadc147015993c3e8e7b661113fbd7a58c95d0957ab80e8bb2451e18bdcf676
Python
1,655
59
import os import re from configobj import ConfigObj def _sanitize(section, key, **replacements): val = section[key] if isinstance(val, str): for k, v in replacements.items(): val = val.replace("%" + k + "%", v) if isinstance(val, str): if val.lower() in ["true", "yes"]: ...
7f1d297d4ac4e366c3ac94ae9b7ddcfbdd63b0ce3ac5d53909dcc8090ba67d60
Python
1,655
40
from abc import ABC, abstractmethod from typing import Callable class IProcess(ABC): """ A process that is a part of the processing pipeline. It is expected to stop by itself when its input queue is closed. If it has an output queue, it should close it when it stops. It is expected to clean after ...
c9a2c403fa2ec86f8f3bc946c304d741847971db75295b48caa4616513dd5725
Python
1,655
42
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler FEATURE_COLS = [ "I1","I2","I3", "T1","T2","T3","T4", "C1","C2","C3","C4", "E1","E2","E3","E4","E5", "S1","S2","S3","S4","S5","S6","S7" ] TARGET_COL = "Qualit...
de1cbc80cf65a160edb769105d8a03d50962bb5fd2a407ad6245a5883cce941c
Python
1,656
56
from __future__ import annotations import pytest from textstat.backend import utils @pytest.mark.parametrize( "lang, key, value", [ (lang, key, utils.constants.LANG_CONFIGS[lang][key]) for lang in utils.constants.LANG_CONFIGS for key in utils.constants.LANG_CONFIGS[lang] ] + [...
4c8eba48f1837a2a90f8237f4d1f026a1e794a037b88eacea10f22af3324f739
Python
1,658
50
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from ray.rllib.models import Model from ray.rllib.models.tf.misc import normc_initializer class MaskedActionsModel(Model): """Custom RLlib model that emits -inf logits for invalid...
b166cd97fdc0b602d801f7a4e5f523d94f4596fa7c38a417d8b3764d6ffecbc7
Python
1,660
44
import neo import quantities as pq import pandas as pd import numpy as np # pad signal as neo expects a continuous recording def pad_signal(raw_data): sampling_interval = 0.0001 # 10 kHz start_time = raw_data.index[0] time_index = np.array(raw_data.index, dtype=np.float64) sample_numbers = np.round((...
6a037f302a38d377cebea6a92a2fd6610962f409031409384c30795e96c9f23b
Python
1,661
61
# Tests aimed at pandas.core.indexers import numpy as np import pytest from pandas.core.indexers import ( is_scalar_indexer, length_of_indexer, validate_indices, ) def test_length_of_indexer(): arr = np.zeros(4, dtype=bool) arr[0] = 1 result = length_of_indexer(arr) assert result == 1 d...
375310af0e50673cdbb051cca797f7282f9cce792219ebe4972309ff17226c1f
Python
1,665
49
"""Contains tests for pressing hmm files into other formats used in scanning and aligning""" # from python from pathlib import Path from unittest import TestCase # from other modules from big_scape.hmm import HMMer class TestHMMPress(TestCase): """Contains tests to make sure hmm files can be correctly pressed ...
3f6cad9996f7529c1f99b31790507688c424d79b4d502ca7ccc0139659a9f86b
Python
1,665
49
""" Modified version of build_scripts that handles building scripts from functions. """ from distutils.command.build_scripts import build_scripts as old_build_scripts from numpy.distutils import log from numpy.distutils.misc_util import is_string class build_scripts(old_build_scripts): def generate_scripts(self,...
75d6b56534b0fd5ee12f3d71dd829731c74ef064a41f391679ebe2b075d468e2
Python
1,665
71
from abc import ABC, abstractmethod import numpy as np from typing import Dict, Any, Optional, Tuple class BaseAgent(ABC): def __init__(self, state_dim: int, action_dim: int, **kwargs): self.state_dim = state_dim self.action_dim = action_dim self.num_elec = 4 self.generation = 0...
e724bec60ef3b4a35a9870872c03367691e9882175a106d87bf18fc91320cc60
Python
1,665
64
import numpy as np import torch from torch.utils.data import Dataset from rdkit import Chem, DataStructs from rdkit.Chem import rdFingerprintGenerator def calc_fp( SMILES, fp_size=2048, radius=2): mol = Chem.MolFromSmiles(SMILES, sanitize=True) if mol is None: return np.ze...
d693b16239c451fc39cc0fdd30041fc449108b69c19000c1288682464063cbba
Python
1,666
41
"""Main file for BiG-SCAPE benchmark module""" # from python from typing import Any import logging # from other modules from big_scape.benchmarking import BenchmarkData from big_scape.benchmarking import BenchmarkMetrics from big_scape.benchmarking import OutputGenerator def run_bigscape_benchmark(run: dict): "...
561f214f3e9d8b6e800c705f922f9818c4eb528c2eda4ccbc42746699a4b9e07
Python
1,667
53
# Copyright (C) 2013 Bernd Feige # This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING). """ This provides a standard way of handling Embla event staging files. """ __author__ = "Dr. Bernd Feige <Bernd.Feige@gmx.net>" from . import slfile as parent_slfile stages={ 'Wake': 0, 'S1': 1, 'S2':...
5eec5ae2c36b6943dc426b78e52a2001f3749031c56fa0bbdee3593665f74411
Python
1,667
52
import os from numpy.distutils.fcompiler.gnu import GnuFCompiler compilers = ['VastFCompiler'] class VastFCompiler(GnuFCompiler): compiler_type = 'vast' compiler_aliases = () description = 'Pacific-Sierra Research Fortran 90 Compiler' version_pattern = (r'\s*Pacific-Sierra Research vf90 ' ...
eef1845a6190747aa61c765c9d497a8fa1cdd2e4ff1d4d05d37814b69372d6b4
Python
1,667
47
import os import pytest import torch from ase.db import connect from nablaDFT.pipelines import run @pytest.mark.pipeline def test_train_pipeline(train_config, caplog): run(train_config) assert "`Trainer.fit` stopped: `max_epochs=3` reached." in caplog.messages[-1] @pytest.mark.pipeline @pytest.mark.skipif(...
13824d31d762fd36f1b1495062f0a57895368e7bda2b0aa90fb9aa08d63847d1
Python
1,668
44
import sys sys.path.append('.') from plotting.utils import load_results, set_plotting_defaults, efcolor, pvscolor, ecscolor,dpi import matplotlib.pyplot as plt import numpy as np def get_diameter(results): lumen_diam = results["vessel_diam"] length = max(results["y_coordinates"]) - min(results["y_coordinat...
6d4709a4ba71484c3cbd061e29794a23849c3299f088e4f90ddeb302cdb97621
Python
1,668
68
""" For hardware simlation, only sample interface is available and Monte Carlo simulation is enough """ import tensorcircuit as tc n = 6 m = 4 pn = 0.003 K = tc.set_backend("jax") def make_noise_circuit(c, weights, status=None): for j in range(m): for i in range(n - 1): c.cnot(i, i + 1) ...
a60736fb2e0b1c35d141157f1127ecd7fd93533425be5aef70094c1b651fb5bc
Python
1,669
59
import os import re from configobj import ConfigObj def _sanitize(section, key, **replacements): val = section[key] if isinstance(val, basestring): for k, v in replacements.items(): val = val.replace("%" + k + "%", v) if isinstance(val, basestring): if val.lower() in ["true", "...
7fc3e1210d80f1347318d0be707133b6d67bf872c42109b69a44c8e018d6a40f
Python
1,670
42
"""Type aliases for Cedalion dataclasses. Cedalion relies as much as possible on generic data types (like xarray DataArrays). We then use type aliases and annotations to augment these data types with additional information about the data they carry. For DataArrays there is a basic mechanism to specify and validate dat...
f2840b66314186cf8a3ad73b4d1a32e365720c754bdaf3af28f7ae8318662e47
Python
1,670
48
import os from pathlib import Path from torch import optim from models.SpeechAutoEncoder import SpeechAutoEncoder import torch from transformers import Data2VecAudioConfig,AutoConfig MODEL_NAME = 'SAE' loss = torch.nn.SmoothL1Loss() light_model = SpeechAutoEncoder sampling_rate = 16000 base_path = Path(__file__).paren...
79ff1d707445b579ad167e2702f70d15867781502eb2f1a169551d68b71f8b6a
Python
1,672
54
import torch import torch.nn as nn from .layers.unmap_predictor import UnmapPredictor from .layers.convnext import ConvNeXtV2Block class ConvNeXtCNN(nn.Module): def __init__(self, window_size=2048, bin_size=4, nr_tracks=1, use_map=False): super().__init__() assert window_size % bin_size == 0 ...
d154fce8dd9645b28c1a6f4249eae67a3b5d7ecf6dd30c27386312a1ffe60481
Python
1,673
56
import numpy as np import pandas as pd from matplotlib import pyplot as plt import seaborn as sns from scipy.ndimage import gaussian_filter from main_functions import mark_voisins#, fast_multi_periodogram_window_3d, fast_multi_periodogram_prewindow_3d sns.set_theme() group_name = ["Hemisphere 1", "Hemisphere 2"] if...
dd73b094964b69bedb2d9210f46b637c0219dc5c91d2fa0bafc672088aee60d1
Python
1,673
44
import torch, importlib from LossPy import BCEDiceLoss, ComputePR, LSDLoss, EvalScore from torch import nn as nn def GetLossOptimiLr(model): optimizer_config = { 'learning_rate': 0.0002, # weight decay 'weight_decay': 0.00001 } lr_config = { # reduce learning rate when evalu...
8d85f8f6f5dba5535a9112b2525fd7f6a18b61bcc7e4f75a744b01730b831fbd
Python
1,674
52
import torch import torch.nn as nn import torch.nn.functional as F from braincog.model_zoo.base_module import BaseModule from braincog.base.node.node import * from braincog.base.connection.layer import * from braincog.base.strategy.surrogate import * from utils.MyNode import * class TIM(BaseModule): def __init__(...
8404d07cbbfd8f148b0569203215ff4ee8db6278fcd17465fbff1352eccac367
Python
1,675
45
from math import ceil import pytest from nablaDFT.dataset import ASENablaDFT from .assertions import assert_shapes_spk @pytest.mark.dataset def test_spk_dataset_fit_dataloader(dataset_spk_params_train): dataset = ASENablaDFT(**dataset_spk_params_train) dataset.prepare_data() dataset.setup(dataset_spk_pa...
d09ede7975d3531d08bdff1ab1fa71d32715929d04a9faa78f5d7bc769985fd1
Python
1,675
64
from __future__ import annotations import collections.abc as c import inspect import typing as t from weakref import ref from weakref import WeakMethod T = t.TypeVar("T") class Symbol: """A constant symbol, nicer than ``object()``. Repeated calls return the same instance. >>> Symbol('foo') is Symbol('f...
5f1d810a44109837c8f4f7c00271a4ab2a961f359f676fec2a5407bf3b81fe6c
Python
1,677
61
#!/usr/bin/env python3.7 """Plot the waveform used for stimulation. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. RUN THI...
4e5f1022b457459b02cef703294d067cb223c1b951a9ef1c804c7f0df2e00330
Python
1,678
57
from pytorch_lightning.callbacks import Callback from protgps.utils.registry import get_object def set_callbacks(trainer, args): """ Set callbacks for trainer, taking into consideration callbacks already set by trainer args. Callbacks that are preset by args and perform the same function as those manually...
882c5061b480b51716ce5f66af40825d5b88c70e430d2d97f122d14fb0fbfde2
Python
1,678
72
import pandas as pd import numpy as np import matplotlib.pyplot as plt celltype = 'B-NK' meta_data = pd.read_csv('PseudoTime/diffMap2.csv',index_col=0) print(meta_data.iloc[:5,:]) LL = meta_data.shape[0] print('Cellnumber: ', LL) cell_ls = list(meta_data.index) resolution = 100000 chr = 1 chr = f'chr{chr}' CpG = p...
fea54a0c4da0e1c19df1ee5fb9cb50d4402d3bb3c256262b68a0498ecea57f71
Python
1,678
43
#import necessary packages import os from natsort import natsorted from nilearn import surface import numpy as np # function to generate subject list from BIDS Directory def subject_list(dir, exclude_subs = None): """Returns a list of subject IDs from a parent directory. Parameters : dir : st...
18ef6944ddf05c2da441aa2f2b9ed368b60131cdc896d387f763ba404c3a604d
Python
1,679
58
import hashlib import logging import sys from optparse import Values from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES from pip._internal.utils.misc import read_chunks, write_output logger = ...
1b89c340b62dbed860b1c15635586826a7ceafe9fb9155272e2c944d13825adf
Python
1,679
54
import os import re import sys from github import Github def main() -> None: token = os.environ.get("GITHUB_TOKEN") repo_owner = "pytorch" repo_name = "pytorch" pull_request_number = int(sys.argv[1]) g = Github(token) repo = g.get_repo(f"{repo_owner}/{repo_name}") pull_request = repo.ge...
42ff27d42e35304c520bb6b05b3775c2679cafe7dbf2ed30f57e656e441c2580
Python
1,680
41
## ........................................................................... ## ## PIMMS (Polymer Interactions in Multicomponent Mixtures) ## Alex Holehouse, Pappu Lab, Holehouse Lab ## Copyright 2015 - 2026 ## ........................................................................... """ lemonade - a fast, hierar...
2ebcc33d930a561d2bb9bb42c7dbeedd79596cb092ba0e954a3e10b2fb7ae810
Python
1,681
52
""" This code wraps the vendored appdirs module to so the return values are compatible for the current pip code base. The intention is to rewrite current usages gradually, keeping the tests pass, and eventually drop this after all usages are changed. """ import os import sys from pip._vendor import platformdirs as _...
f84ae062ff0f7202e1d5891a7d5923e7d687d3ec0f39fc9ffd1009b4e7bd449b
Python
1,682
64
"""Plot the Ve across a fiber length. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. RUN THIS FROM REPOSITORY ROOT """ imp...
4e5f531cc0d9f8f9395a6f2c23580683f5390e1bac9b10fe159d1f51b714d16d
Python
1,683
57
import io from typing import IO, TYPE_CHECKING, Any, List from .ansi import AnsiDecoder from .text import Text if TYPE_CHECKING: from .console import Console class FileProxy(io.TextIOBase): """Wraps a file (e.g. sys.stdout) and redirects writes to a console.""" def __init__(self, console: "Console", fi...
9878c70bae698191d9b9125433975aa16fa51a7ba5ab5cd61edf8ce29c4ceaef
Python
1,683
65
"""Plot the Ve across a fiber length. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. RUN THIS FROM REPOSITORY ROOT """ imp...
a39359b43579fbdc63cb006c5e0b36e2e3bc4fccc395c2af3c514ef5753bd2e9
Python
1,683
53
import argparse import os import numpy as np import pandas as pd import torch def get_args(): parser = argparse.ArgumentParser( description="Convert unitig presence/absence to node features" ) parser.add_argument( "--unitig_query_results", type=str, help="Results from unitig-caller query"...
2de47f8844845c557db2a8de97eecafc63be18b965d3c07aba6923d9759fbcd3
Python
1,684
69
""" minidemo.py This script sets base, peak and fit cursors to perform events detection as decribed in the Stimfit manual [1] It creates a preliminary and final templates from a file 'minis.dat'. You can download the file here: http://stimfit.org/tutorial/minis.dat last revision: Wed Sep 5 09:38:41 CEST 2018 C. S...
042cbcec75ea23658ed3f70218afab79dbe2d924c9cc2c6cc1862cd3a61dc41e
Python
1,686
67
""" datetimelke_accumulations.py is for accumulations of datetimelike extension arrays """ from __future__ import annotations from typing import Callable import numpy as np from pandas._libs import iNaT from pandas.core.dtypes.missing import isna def _cum_func( func: Callable, values: np.ndarray, *, ...
c7a85e7deaf7fb6c737dfab6b8952eefec65c7899a760ae9ab7c13b0128f3f71
Python
1,686
45
import os import subprocess import sys _tee = None def redir_output(logfile: str): global _tee if _tee: raise Exception("Standard output/error already redirected") _tee = subprocess.Popen(["tee", logfile], stdin=subprocess.PIPE) # Cause tee's stdin to get a copy of our stdin/stdout (as well a...
e6c085bb4124241fd11e1b48462d019f9b0370f3f80d6b7c296258e2db1b1e23
Python
1,686
39
# License: GNU Affero General Public License v3 or later # A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt. # for test files, silence irrelevant and noisy pylint warnings # pylint: disable=no-self-use,protected-access,missing-docstring import unittest import antismash from ant...
17b180e83049ef99ad602a11262aa2147b149c403ff5998df2020c186fef1d49
Python
1,687
52
import os import pandas as pd import scipy import scanpy as sc """ This script takes the output of either Cellbender or CellRanger and processes into a Anndata object with the parameters upon which quality control filtering can be done. """ # Read the samples table once samples = pd.read_csv(snakemake.input.metadata_...
4f3426e8b15eb294e5d6a52eaf04e92cc3bfac9435c8dcd5a03ad1325d095743
Python
1,687
47
import torch @torch.jit.script def gaussian(x: torch.Tensor, mean, std) -> torch.Tensor: pi = 3.14159 a = (2 * pi) ** 0.5 return torch.exp(-0.5 * (((x - mean) / std) ** 2)) / (a * std) # From Graphormer class GaussianRadialBasisLayer(torch.nn.Module): def __init__(self, num_basis: int, cutoff: float...
3166d12b3c240f267acc9ab3210954d22c86b43aceb60eb60554515308e50ac2
Python
1,688
67
import os import random try: from pathlib2 import Path except ImportError: from pathlib import Path import numpy as np from six import with_metaclass PATH_TO_TESTS = os.path.dirname(os.path.realpath(__file__)) class BaseClass(object): pass class TestingType(type): def __getattr__(self, name): ...
78c19d662edabaeeb6d35878bf87906769a217c2a674c1830296c1160444fba4
Python
1,689
62
""" Miscellaneous utils. """ from numpy._core import asarray from numpy._core.numeric import normalize_axis_tuple, normalize_axis_index from numpy._utils import set_module __all__ = ["byte_bounds", "normalize_axis_tuple", "normalize_axis_index"] @set_module("numpy.lib.array_utils") def byte_bounds(a): """ Re...
26903c07f42f8c2e5f6a1a1d40f7b41a8a92decb06c380c57e7b9a7acf3295e1
Python
1,690
56
import argparse from typing import Optional import waitress from flask import Flask, render_template_string, render_template, request from src.model import initialize_system from src.proposal import do_proposal tokenizer, model_combined_place_backs, models_determiner, models_metadata_place_back = initialize_system( ...
04050fa70d3f223d9b4ff2e8948d4fddf1860ba9ecb68a79da503bff8bfc9ac6
Python
1,691
78
''' Created on 2016.4.27 @author: liangqian ''' import json import random class joint(): def __init__(self): self.x = 0 self.y = 0 self.z = 0 def self2dic(self): return {'x':self.x, 'y':self.y, 'z':self.z} class data(): def __in...
eed2e62fab36ec11fee3d53830dfea6d88b838b7f3a20416d677f91c9c851163
Python
1,692
61
from __future__ import annotations import re from ..utils._typed_cache import typed_cache from ..selections._list_words import list_words @typed_cache def count_arabic_syllables(text: str, rm_apostrophe: bool = True) -> int: """Count arabic syllables. Long and stressed syllables are counted double. Pa...
3c73d3586290ce7a8c85fba179aede792c718296c96765b5abc3917dc792d253
Python
1,694
46
import torch import torch.nn as nn import torch.nn.functional as F from .layers.unmap_predictor import UnmapPredictor class CNN_LSTM(nn.Module): def __init__(self, window_size: int = 2048, bin_size: int = 4, nr_tracks=1, use_map: bool = False): super(CNN_LSTM, self).__init__() assert window_size % ...
d77f3f3bf270c1d0a67e6ca3a78ecf4956bee12afb48eb8ba6baf43f3466e814
Python
1,694
56
import numpy as np import pytest from pandas import ( CategoricalDtype, DataFrame, ) import pandas._testing as tm def test_transpose(index_or_series_obj): obj = index_or_series_obj tm.assert_equal(obj.transpose(), obj) def test_transpose_non_default_axes(index_or_series_obj): msg = "the 'axes' ...
1759631fb17923653f986e21157028309431d5683306905c4b5b80b1669e10f7
Python
1,696
59
#!/usr/bin/env python3 """Generates a matrix for docker releases through github actions Will output a condensed version of the matrix. Will include fllowing: * CUDA version short * CUDA full version * CUDNN version short * Image type either runtime or devel * Platform linux/arm64,linux/amd64 """ ...
d14623bf0676fcdc598d9a9630150303611dccb6fe39c3398310244c43be106c
Python
1,696
57
# coding: utf-8 # See notebook: # https://github.com/paninski-lab/yass-examples/blob/master/batch/single_channel_apply.ipynb """ Apply functions to large files using BatchProcessor.single_channel_apply """ import logging import os import matplotlib.pyplot as plt from yass.batch import BatchProcessor from yass.batc...
8541e488ddb99a26ae20751fcd991a588ca4fca6cb69816888046b4e2bf0341e
Python
1,697
43
import unittest import torch import torchdiffeq from problems import construct_problem, DTYPES, DEVICES, ADAPTIVE_METHODS EPS = {torch.float32: 1e-4, torch.float64: 1e-12, torch.complex64: 1e-4} class TestCollectionState(unittest.TestCase): def test_forward(self): for dtype in DTYPES: eps =...
211f4415f432e857e8a716ea1b633771b2682ca979040ee378f440fe8245d5bb
Python
1,702
46
import nibabel as nib import os input_folder = "/mnt/nas7/data/reza/registered_dataset_all_doses_pad_updated_NonUnifiedOrigins/" output_folder = "/mnt/nas7/data/maria/final_features/registered_niftis_new/" os.makedirs(output_folder, exist_ok=True) # Reference image reference_image_path = os.path.join(input_folder, "...
ed9f7bee36f5ef16ae870499be107227aa1632ef8407ec58b22ae639cf3eb698
Python
1,702
57
""" Get molecule qubit format Hamiltonian from openfermion. """ import time import tensorflow as tf from openfermion.chem import MolecularData from openfermion.transforms import ( get_fermion_operator, binary_code_transform, reorder, checksum_code, ) from openfermion.utils import up_then_down from open...
71e2921086a6b60e8cf557fabb0cd1dd7f592f2236e4b0a2084d2aab1acd3822
Python
1,703
71
""" A simple static Hamiltonian evolution benchmark """ import time from functools import partial import numpy as np from scipy.integrate import solve_ivp import tensorcircuit as tc from tensorcircuit.experimental import hamiltonian_evol K = tc.set_backend("jax") tc.set_dtype("complex128") @partial(K.jit, static_ar...
5cc70c6d50e50a6e88dfae040ba502385e01f7deb36b91b1c767537c47ad687d
Python
1,704
61
#!/usr/bin/env python3 import os import argparse import subprocess from time import sleep from google.colab import drive from IPython.display import display, HTML def kill_current_runtime(): os.kill(os.getpid(), 9) # mount google drive drive.mount("/content/drive", force_remount=True) # Parse command-line argum...
74f3d4bdad023320e1e62ebd3b318c2913cb19bf7a4309bcab8392e123625c5a
Python
1,704
47
from snakemake.script import snakemake import pandas as pd input_files_scores = snakemake.input.scores input_file_predictions = snakemake.input.predictions input_file_best_params = snakemake.input.best_params best_result = None best_score = float("-inf") dataset_name_target = snakemake.params.name # loop through the...
f030d4ba8322670b06178535903201a0b91b56c0bc45cb96422f1f829d3b0557
Python
1,704
67
from datetime import datetime # Added for query limit reset logic from pydantic import BaseModel, EmailStr, Field class UserBase(BaseModel): username: str = Field(..., min_length=3, max_length=50) email: EmailStr first_name: str = Field(..., min_length=1, max_length=50) last_name: str = Field(..., m...
c1d61a6f15ff59e64229cc28a20e4dff65bd8d85325f632e2af1aade5fbb56fe
Python
1,706
50
import torch import torch.nn as nn from torch.nn import init import math from e3nn import o3 from .fast_activation import Activation class RadialProfile(nn.Module): def __init__(self, ch_list, use_layer_norm=True, use_offset=True): super().__init__() modules = [] input_channels = ch_lis...
e4c4a52f967fec5b538cbbc52977b9beb81627d7bb74ae8111999fc5278690e2
Python
1,706
82
""" %load_ext autoreload %autoreload 2 """ import logging import os import numpy as np from yass.batch import BatchProcessor from yass.batch import RecordingsReader logging.basicConfig(level=logging.DEBUG) root = '/Users/Edu/data/yass-benchmarks' # root = '/ssd/data/eduardo/yass-benchmarks' path_to_long = os.pat...
50d4ccecfe667d5b53ef00e2f643935d6815ddfbb77bc6d3aedd50a758ef8caa
Python
1,709
65
import argparse import sys from ._implementation import resolve from ._toml_compat import tomllib def main() -> None: if tomllib is None: print( "Usage error: dependency-groups CLI requires tomli or Python 3.11+", file=sys.stderr, ) raise SystemExit(2) parser ...
ca9f830ea297b5b9034cd6b489f6be166380f2b6b6e253d91177ed5be47902e2
Python
1,710
59
from __future__ import annotations import argparse import sys from ._implementation import DependencyGroupResolver from ._toml_compat import tomllib def main(*, argv: list[str] | None = None) -> None: if tomllib is None: print( "Usage error: dependency-groups CLI requires tomli or Python 3.1...
cb0d468823a7ec5f190e87fd77b22f1ba4f6f1eea7b01fbf5ecc1f3b41cdf837
Python
1,710
51
import dateutil import pytest from pandas._libs.tslibs import timezones import pandas.util._test_decorators as td from pandas import Timestamp class TestTimestampTZConvert: @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) def test_astimezone(self, tzstr): # astimezone is an a...
e0a4cae37d7d7b1bba4f35f9e4892126f2ad546ccc9ac1f69675bda6aaeabf29
Python
1,710
61
from functools import lru_cache import numpy as np from ase import Atoms class FragmentData: def __init__(self, z: np.ndarray, pos: np.ndarray, start: np.ndarray, end: np.ndarray, batch: np.ndarray): self.z = z self.pos = pos self.start = start self.end = end self.batch = ...
651f27fde7da63b1d6198e979d164a3488915a66acce9354f29db692f01bc844
Python
1,711
62
from __future__ import annotations import pandas._testing as tm from pandas.api import types from pandas.tests.api.test_api import Base class TestTypes(Base): allowed = [ "is_any_real_numeric_dtype", "is_bool", "is_bool_dtype", "is_categorical_dtype", "is_complex", ...