sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
6bd60ebb86d987777d6134274d3319b47c2fb361a058c27ff9ed5874f974184d
Python
1,993
61
import numpy as np import scipy.special as special from .basic_distributions import Distribution from ..utils import * class Binomial(Distribution): """ Class to define Binomial distributions Equations: p(x|N,theta) = binom(N,x) * theta**(x) * (1-theta)**(N-x) log p(x|N,theta) = log(binom(N,x)) +...
3a4e7ab8041e5adf50e4f572b6986fb42452074a687210e1f61e77f8b996c235
Python
1,994
57
import os from typing import AsyncIterator, List, Tuple import ray from ray.dashboard.modules.job.common import JOB_LOGS_PATH_TEMPLATE from ray.dashboard.modules.job.utils import fast_tail_last_n_lines, file_tail_iterator class JobLogStorageClient: """ Disk storage for stdout / stderr of driver script logs. ...
c0362e38fd410ed54a386f4611ee8548c884fd842ffba4f47841ee61273c3642
Python
1,994
66
import numpy as np import torch from tqdm import trange def KS(u): pad_op = torch.nn.CircularPad2d(2) u = pad_op(u) ux = (u[:, 3:-1, 2:-2] - u[:, 1:-3, 2:-2]) / 2 uy = (u[:, 2:-2, 3:-1] - u[:, 2:-2, 1:-3]) / 2 ux2 = (ux ** 2 + uy ** 2) uxx = u[:, 3:-1, 2:-2] + u[:, 1:-3, 2:-2] + u[:...
2516286ff3dd12a738ee5ad2afdca1865ed83178fda5c1b7877655ef531f7428
Python
1,995
67
import numpy as np import torch from .base import Transform, randint class Compose(Transform): """Apply transforms in sequence. Args: transforms: list of transforms, or a single transform. """ def __init__(self, transforms, p=1.0): super().__init__(p) if isinstance(transform...
7b57cfc4a7e7a6d9b63fc8fa5305b561b805afa31752a62a096e7c03dbbd7ca5
Python
1,995
60
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
14e8f16d17ba34e442eacfaef80c5402912352d84ef94df8d52a361a8f87c45d
Python
1,996
51
# coding=utf-8 # Copyright 2023 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
18cd35d887d2a4edf977aad9a379d78466d34aebaade2235c9f28310c59fd843
Python
1,996
29
SPLICEBERT_PATH = "/path/to/SpliceBERT/models/model_folder" # set the path to the folder of pre-trained SpliceBERT import torch from transformers import AutoTokenizer, AutoModel, AutoModelForMaskedLM, AutoModelForTokenClassification # load tokenizer tokenizer = AutoTokenizer.from_pretrained(SPLICEBERT_PATH) # prepar...
5b9ec0a6e7b531cf9a7a4fbf0b70bed1d5fe12a439c68b3a36bab664dd8303b8
Python
1,997
66
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations from fairchem.core.components.runner import ( PreemptableMixin, StopfairDetected, ) from ._sin...
40327d563fb05a0eed8483bc921eee152fb8a9e9b91c59b08e59056275335a1f
Python
1,999
55
from .ssim import SSIM import torch class S3IM(torch.nn.Module): r"""Implements Stochastic Structural SIMilarity(S3IM) algorithm. It is proposed in the ICCV2023 paper `S3IM: Stochastic Structural SIMilarity and Its Unreasonable Effectiveness for Neural Fields`. Arguments: kernel_size (int)...
b5ba85b4ab75e304041f5d0cd334a9a63492579d6c44492e164a8fa3cebd7d61
Python
1,999
35
from spinnaker2.neuron_models.spike_list import SpikeListApplication from spinnaker2.neuron_models.float_list import FloatListApplication from spinnaker2.neuron_models.spike_receiver import SpikeReceiverApplication from spinnaker2.neuron_models.lif_curr_exp import LIFCurrExpApplication, LIFCurrExpNoDelayApplication fro...
ddf994b3f926eda1ed1f559f3c19bc4922905d929c89e9fca53b766347ee671e
Python
2,000
66
"""Apply copyright headers to all code files in the repository. This file can be called as a python script without arguments. For configuration, see the instructions in NOTICE.yml. """ import fnmatch import glob import subprocess import tempfile import yaml def load_config(filename): with open(filename, "r") a...
ebff389f472c36fdf637927ca11ad637af7b3c440e654dcd4db1b855f1e4e0ef
Python
2,001
56
import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures, MinMaxScaler def train_model(training_set_path): """ Train a RandomForestClassifier using the provided training set and return t...
2476d6ac8af83a888150ed895133f2e907c343d691e81c03ca2d668042a813db
Python
2,002
56
from mfm import MFM #This is the mean-field model of DBS-LFP. See mfm for details import numpy as np import matplotlib.pyplot as plt #Helpful for plotting import pdb import pickle as pl with open('freqVals.p','rb') as f: freq = pl.load(f) #Keywards to set up models kwargsDBSSub = { ...
40ee52aa7631d4126d05bc6583fba640251c07b7e9d07a22aa83b99f6428a829
Python
2,004
54
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
b088af3bcb19e924c6821e2ccbb2807f05f01709270d1adce62b87adad61c6a0
Python
2,005
54
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import random import ase from fairchem.applications.cattsunami.core import Reaction from fairchem.appl...
2f7e6a8dea2f17032946698c1114adacc9912c6684dbcb41811013d2e3a86cba
Python
2,006
52
from argschema import ArgSchema from argschema.schemas import DefaultSchema from argschema.fields import ( Nested, String, Int, Float, OutputDir, OutputFile, NumpyArray) class PiaWmStreamlineSchema(ArgSchema): """Arg Schema for run_pia_wm_streamlines""" pia_path_str = String( required=True, ...
e9ec726175f6d425d47a56ca08d68125178f6f8ea22ed122684806b60254239f
Python
2,007
88
# __return_ray_put_start__ import ray # Non-fault tolerant version: @ray.remote def a(): x_ref = ray.put(1) return x_ref x_ref = ray.get(a.remote()) # Object x outlives its owner task A. try: # If owner of x (i.e. the worker process running task A) dies, # the application can no longer get value of ...
994fc3e8a564953e0c30b551b73c68043ea0a310b02e0eb0b8e108cd74531bb1
Python
2,008
77
import numpy as np from scipy.stats import sem class SimplePETracker(): def __init__(self, size=512): self.tracker = {} self.size = size def record(self, input, pe, verbose=False): input_key = str(input) if not self.input_in_tracker(input_key): self.tracker[input_...
0e5a26a48100884665faa4becb87acbc1c90105109332ab6b298965e2b827061
Python
2,010
66
import os import sys import subprocess as sp import unittest import shutil import tempfile import xarray as xr import numpy as np try: import dolfinx has_dolfinx = True except ImportError: has_dolfinx = False @unittest.skipIf( not has_dolfinx, "streamline calculation requires conda-installed fen...
e9960a73f47a9897e7f5915721bf71eab84729dc01b362272a889cc3c66f49ea
Python
2,010
55
''' Contains patches for MOABB v0.4.6 to speed up the computation. Especially useful when multiple permutations of one run are calculated. Just import the appropriate module to use the patch moabbpatch.datasets: Stores the loaded dataset in memory, so that it must not be loaded everytime it is used. moabbpatch.ba...
c040026fe20caec35c8e836f1a3a1a41220d1d8b3aea3d1739e4129a4ee78533
Python
2,011
56
from copy import deepcopy from typing import Callable from warnings import warn import torch.nn as nn def replace_module(model: nn.Module, source_class: type, mapper_fn: Callable): """A utility function that returns a copy of the model, where specific layers are replaced with another type depending on the ma...
51950a828c0193e1998560cb2f8ce93a89b0b3e151dbcd9e0802f06150d76fdf
Python
2,013
54
import torch from ..reducers import AvgNonZeroReducer from ..utils import loss_and_miner_utils as lmu from ..losses.generic_pair_loss import GenericPairLoss class ContrastiveLoss(GenericPairLoss): def __init__(self, pos_margin=0, neg_margin=1, **kwargs): super().__init__(mat_based_loss=False, **kwargs) ...
5430a7fd1ec6780881eb8ae4bfd1ce20a2cb33c52782c29cd051919406c0c698
Python
2,013
64
# __anti_pattern_start__ import ray import pickle from ray._private.internal_api import memory_summary import ray.exceptions ray.init() @ray.remote def out_of_band_serialization_pickle(): obj_ref = ray.put(1) import pickle # object_ref is serialized from user code using a regular pickle. # Ray can't...
7ae79c92dd7c2db79921d8c98d52129456c71e23b1465a9d093f9921d602e4ed
Python
2,013
47
from transformers.modeling_outputs import SequenceClassifierOutput from torch import nn class ModelWithCustomLossFunction(nn.Module): def __init__(self, pretrained_model, pretrained_model_label=None, num_labels=None, dropout=0.3, linear_layer_dim=768, output_attentions=False, output_hidden_states=True): s...
06d0b884f7815476091c5d9edad1581f0faf7b5cde1c7e617679833552f33574
Python
2,014
57
import os import argparse import numpy as np from sklearn.model_selection import StratifiedShuffleSplit """Generate a random split train-val for gridsearch""" def load_train_data(path, dtype_data=np.uint8, dtype_label=np.uint8): X = np.fromfile(path + "/X_train.bin", dtype=dtype_data) y = np.fromfile(path + ...
36ff9a1849207448939597620184fbc0548f15425f23d8c527921c1af5ebf413
Python
2,014
44
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
9b6cc2c0f33cf8321c7e615a252ead462bbaadfbeb3e83d1b106d7f0473cb0a1
Python
2,014
67
import logging import time from abc import ABCMeta, abstractmethod from pfrl.experiments import EvaluationHook from pfrl.experiments import StepHook class ProgressStepHook(StepHook): """ Hook function that will be called in training to log current progress """ def __init__(self, log_interval=256, lo...
f6c90beec6ea41d5d446997c856ea9221831db7bea887b7adc26a973f33eff82
Python
2,014
83
import sys import pytest from ray._common.logging_constants import ( LOGGER_FLATTEN_KEYS, LOGRECORD_STANDARD_ATTRS, LogKey, ) def test_logrecord_standard_attrs_is_frozenset(): assert isinstance(LOGRECORD_STANDARD_ATTRS, frozenset) def test_logrecord_standard_attrs_contains_standard_names(): ex...
c0e6f9221ef8b0965f433c2d1f7e3c14e6af884ab02c4891a5e22ba4921daaf6
Python
2,015
62
""" Basic callback definition. """ from sklearn.base import BaseEstimator __all__ = ['Callback'] class Callback: """Base class for callbacks. All custom callbacks should inherit from this class. The subclass may override any of the ``on_...`` methods. It is, however, not necessary to override all ...
e9ad25065537e4dbc8dc66c3af68e0bb0e14f92a9058a32e0dddc55ed6b187eb
Python
2,015
63
# -------------------------------------------------------- # Fused kernel for window process for SwinTransformer # Copyright (c) 2022 Nvidia # Licensed under The MIT License [see LICENSE for details] # -------------------------------------------------------- import torch import swin_window_process class WindowProces...
20337215e8529e06188d189092442472f125b07726f7295095481cce0361ba77
Python
2,016
57
"""Average runs with same phase encoding axis.""" import os import numpy as np import nibabel as nb import glob # ============================================================================= DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti' # Set subs to work on SUBS = ['sub-07'] DIRECTIONS =...
1f0d736f030a20641d2baa33a520c4b53cc8cfac63733872641a9d58c24cf604
Python
2,018
50
def test_multi_roi_timeseries(): import matplotlib.pyplot as plt from os import path from samri.plotting import summary, timeseries from samri.utilities import bids_substitution_iterator from samri.fetch.local import roi_from_atlaslabel substitutions = bids_substitution_iterator( sessions=[ 'ofM', 'ofMaF...
f038d559977661879254babf9f77e412419cad36d3b75effe1a057ad85c76e47
Python
2,019
55
import os import re import json import torch project_root = '/ccb/cybertron/khchao/splam-analysis-results/' output_dir = f'{project_root}train/results/MANE/REF_junctions/' def main(): JUNC_COUNTER = 0 os.makedirs(output_dir, exist_ok=True) fw = open(f'{output_dir}ref_d_a.bed', 'w') with open(f'{pro...
12f5ce6565d8e124eceb18263a3fd06cc015c09f4b8e412772ddb919ed7364fc
Python
2,020
57
from typing import Hashable, List, Mapping, Tuple, Union import torch from torch import Tensor __all__ = ["tensor_op", "to_device_dtype"] data_type = Union[Tensor, List[Tensor], Tuple[Tensor], Mapping[Hashable, Tensor]] def tensor_op(data: data_type, fn: str, *args, **kwargs) -> data_type: """ Invokes a fu...
1931a2bef1b837301cafd9aa59220478d6f9914fe6eb25e270369ab85e3b827b
Python
2,021
54
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
708c7515a085ca75532d4c9664bc783f2b51be4f2747f9d68d17cf256df76602
Python
2,022
54
import numpy as np import argparse import pickle import sys if __name__ == '__main__': parser = argparse.ArgumentParser('Parse the results of the GLM fit grid search') parser.add_argument('grid_file', type=str, help='path to grid search file file') parser.add_argument('-l21', '--fix_l21', type=float, de...
9fac3b2df9afe6e723e0b6de859192942440a79783de5da5f1f7200ac04acfc7
Python
2,022
54
import os from ..utils import logger try: from huggingface_hub import snapshot_download except: huggingface_hub_installed = False def snapshot_download(*args, **kwargs): raise ImportError('huggingface_hub is not installed. If weights are not avaliable, please install it by running: pip install hug...
1a009267d8f520003924fdac3355cdc844892dee24899313a7b4f14f6e592006
Python
2,023
66
from __future__ import print_function import torch.utils.data as data import os from PIL import Image from utils import preprocess class VOCSegmentation(data.Dataset): CLASSES = [ 'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', ...
1c28c6bac84af3471bcc0a73791ac3de4cda72bae59acff22902848d671d6876
Python
2,023
45
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
a752a34591ff718c2fa2adf631e26109171fd1c557d25a3f98de54a6d37b5e7a
Python
2,023
57
import copy import torch from mmengine.model import BaseDataPreprocessor from lqit.registry import MODELS from lqit.utils import ConfigType @MODELS.register_module() class BatchDataPreprocessor(BaseDataPreprocessor): def __init__(self, data_preprocessor: ConfigType, multi_inpu...
6097d979b15064c71660db56aace6512aba715edf5c9dc4552e55c8dafcd0691
Python
2,024
69
def load_training_data(dataFile, validation_split=0, axes=None, n_images=None, verbose=False): f = np.load(dataFile) X, Y = f['X'], f['Y'] if axes is None: axes = f['axes'] axes = axes_check_and_normalize(axes) assert X.shape == Y.shape assert len(axes) == X.ndim assert 'C' in ax...
07a0d6d8fef59d29718ddab074c6a72cf3cb455bc7a35812c085dfe5c69073b5
Python
2,025
71
# Copyright 2026 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
3ac60c452e03192d90a2e24784f36591722b94a9c025bb4b66591482b173a027
Python
2,025
59
import io import tarfile import time import uuid from typing import Any, Callable, Dict, List, Optional, Union import pyarrow from ray.data._internal.datasource.webdataset_datasource import ( _apply_list, _default_encoder, _make_iterable, ) from ray.data.block import BlockAccessor from ray.data.datasource...
c29122f45974b63c2ba96a3b03bca313f8e5167740b01dc7cbb795cd5805484a
Python
2,025
46
import timeit import argparse from pyrosetta import * parser = argparse.ArgumentParser(description="Specific FastRelax procedure for GDFold2 predictions") parser.add_argument('--input', type=str, help='Input unrelaxed model') parser.add_argument('--output', type=str, help='Output model name (.pdb format)') pars...
29a352e2b431a05304e6baf6e7805027110145e815f73061fd390b129ddef347
Python
2,027
55
import numpy as np import pytest import torch from flyvis.datasets import rendering @pytest.fixture(scope="module") def boxeye() -> rendering.BoxEye: return rendering.BoxEye(15, 13) def test_init(boxeye: rendering.BoxEye): assert boxeye.extent == 15 assert boxeye.kernel_size == 13 assert boxeye.rec...
ed244e9b7a177a9123d4331fd5f997c2f3282bdc337faa24d2392b88413b2a92
Python
2,027
61
from __future__ import annotations from abc import abstractmethod from .. import settings class BaseAlgorithm: def __init__( self, batch_key: str | None = "_batch_annotation", labels_key: str | None = "_labels_annotation", seen_result_key: str | None = None, result_key: s...
29e2b6ae7e3f83508f9bd04654380ea84232580227b880edea0827bf68312bef
Python
2,029
64
#!/usr/bin/env python from __future__ import print_function import argparse import glob import gzip import math import numpy as np import os import random def parse_args(): parser = argparse.ArgumentParser("Makes plots and reports details of vcfeval output") parser.add_argument('--input_qual_file', '-i', dest...
b9e53e7758b4782926a40d1bd89a798e71b21aaae23d6d0351c14998ea2009e0
Python
2,029
59
import os import shutil import argparse import numpy as np from sklearn.model_selection import StratifiedKFold """Generate K splits train-val for K-fold cross validation""" def load_train_data(path, dtype_data=np.uint8, dtype_label=np.uint8): X = np.fromfile(path + "/X_train.bin", dtype=dtype_data) y = np.fr...
2120f81aa59f5de4f92f25509a9d93f06c8c7924de396efc11609bcf0d0db3d7
Python
2,031
55
# 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...
6cd94b4ee8798f8478dc21e600d288ee1e989354b4867e37974b942b06cc2d27
Python
2,031
72
# __neuron_serve_code_start__ from io import BytesIO from fastapi import FastAPI from fastapi.responses import Response from ray import serve app = FastAPI() neuron_cores = 2 @serve.deployment(num_replicas=1) @serve.ingress(app) class APIIngress: def __init__(self, diffusion_model_handle) -> None: self...
4936ae59f77eaaba3e1c22f04f666b2d03b26e6e79698807c1a275feb1ff6017
Python
2,033
64
# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
e6b0207bd6ac0c0ea7798b7844b9fcb4a9edaf216229ff6ce36938e1b41cbed5
Python
2,033
54
"""Minimal HTTP listener for BackgroundUploadTest (not part of the product). usage: python3 background_listener.py PORTFILE OUTPREFIX [DELAY_SECONDS] Binds 127.0.0.1 on a free port, writes the port number to PORTFILE, serves one POST, writes the raw body to OUTPREFIX.body and then the request headers (one "name: valu...
83d79cc90909480715f74336af2ec06b05028aa0557801c0708c7be776b76fbb
Python
2,036
81
# flake8: noqa """ This file holds code for the runtime envs documentation. FIXME: We switched our code formatter from YAPF to Black. Check if we can enable code formatting on this module and update the paragraph below. See issue #21318. It ignores yapf because yapf doesn't allow comments right after code blocks, but...
7dce6468a72192ea9bbeaf3502a0d8618ae87981f0707f83b5f316e6ee8c15c2
Python
2,037
67
import numpy as np def split_tx(X_tf, segment_lengths): ''' Split up a seemingly continuous X_tf into a list of its contiguous segments ''' n_t = X_tf.shape[0] segment_idx = np.cumsum(segment_lengths) assert segment_idx[-1] == n_t segment_idx = segment_idx[:-1] return np.split(X_tf, seg...
a9f2b517c532f1d5c9dfb9a11f5570a0427310bbd47f7e8166cd7ec832d3db1b
Python
2,037
72
import numpy as np import pytest import torch import torch.nn as nn from sinabs.layers import LIF, StatefulLayer def test_stateful_layer(): layer = StatefulLayer(state_names=["v_mem"]) assert not layer.is_state_initialised() assert layer.v_mem.shape == torch.zeros((0)).shape layer.reset_states() ...
ef74c58a778abe16ad79a91b08c7959dd822925bffc2f3c470e9478636aaaf71
Python
2,039
69
import cv2 # noqa: F401 — preload libtiff before HIPT/torchvision shadows it (omicverse vendored patch) import argparse import numpy as np from einops import reduce from utils import load_image, save_image, load_mask from image import crop_image def adjust_margins(img, pad, pad_value=None): extent = np.stack([...
7ea3e2c9deb6e5f9f18d4474d43a64d401b749d384c70a99fc4ac7ec3f82f644
Python
2,040
60
# Copyright (c) DP Technology. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import absolute_import, division, print_function import yaml import os from addict import Dict from .base_logger import logger class YamlHandler...
415eae14cb1b4a61c5c763a3b86385fcd1b913774c5d0906b5772b03165096e0
Python
2,041
72
from ray._common.utils import env_bool try: from ray._raylet import ( AuthenticationMode, get_authentication_mode, is_k8s_token_auth_enabled as _is_k8s_token_auth_enabled, validate_authentication_token, ) _RAYLET_AVAILABLE = True except ImportError: # ray._raylet not av...
86b582cbfae33945478f83bfd8a5b2f7393b5b14b857b5d83abf9cad635ffab7
Python
2,041
50
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
287fff0aff5398432b2b0ddee3341f2f587e063b64e2fc4a05749ebf2255d255
Python
2,042
64
# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
506e869a8ee71b3626c842aa5b59d2e67e95e8287bad0c26b6ea86e949b5beee
Python
2,043
53
# Ultralytics YOLO 🚀, GPL-3.0 license from ultralytics.yolo.utils import LOGGER, TESTS_RUNNING from ultralytics.yolo.utils.torch_utils import get_flops, get_num_params try: import comet_ml assert not TESTS_RUNNING # do not log pytest assert comet_ml.__version__ # verify package is not directory except ...
8f36529804e447bed1e40b24cb6ff9730d29029a9908cadc7900bcf21d9d1330
Python
2,043
53
from functools import partial from abberior import microscope EXC_ID = 5 STED_ID = 6 def set_powers(conf, power, laser_id): """ Sets the power of a laser across all channels :param conf: A configuration object :param power: Power of the laser in [0, 100] :param laser_id: ID of the laser in Imsp...
1dc3ca0a4198eb14f8ec2106e1f4418b8b26f88803d68e1903d00f6742ff78dc
Python
2,046
75
# -*- coding: utf-8 -*- from ._version import __version__, __version_info__ from ._history import figure_history from .figures import ( Figure as figure, gcf, scf, auto_figure, show, view, reset_camera, save_fig, screenshot_fig, close, zoom_to_contents, ) from .plots.Arrow ...
80eff3e64ab31996f41b99146ef16b4998b2ef552c627d54ac4181dea7f545a8
Python
2,047
56
import torch from ..distances import CosineSimilarity from ..losses import GenericPairLoss from ..utils import loss_and_miner_utils as lmu class IntraPairVarianceLoss(GenericPairLoss): def __init__(self, pos_eps=0.01, neg_eps=0.01, **kwargs): super().__init__(mat_based_loss=False, **kwargs) self....
2862b29e0f42a250589fbb6a5c0370a8aed65733381eeda459969a3c37b47ef4
Python
2,048
60
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """aihwkit example 9: simple network with one layer using deterministic pulse trains for update. Simple network that consist of one analog layer. The network ai...
c0b5d9eb40470ec3b24d038a86b73a5141e7dbd0f0b08022475c139063a56fad
Python
2,049
38
""" The code for the research presented in the paper titled "Enabling inverse design of plasmon-based nonlinear square resonators with deep neural networks." This code corresponds to the article's inverse Deep Neural Network (DNN) section. This code regenerates the Fig. 7b and c of the paper. Please cite the pape...
df6c6ef315fc7327508cec8c76abe3ce0d568291e6e23150bbbf6bdb65a631e7
Python
2,049
62
# -*- coding: utf-8 -*- """ Created on Fri Apr 30 10:34:00 2021 @author: ju-bar Functions and classes handling atom type data This code is part of the 'emilys' repository https://github.com/ju-bar/emilys published under the GNU General Publishing License, version 3 """ atom_type_symbol = ['Void' , 'H' , 'He' ...
edecb056749489ecee7fa42d7987579ff61e53c0d52c5405218e871d6c838013
Python
2,049
70
# __sync_actor_start__ import ray @ray.remote class TaskStore: def get_next_task(self): return "task" @ray.remote class TaskExecutor: def __init__(self, task_store): self.task_store = task_store self.num_executed_tasks = 0 def run(self): while True: task = ra...
3c6b317465545aa13758772db44ddeb10ebb3bb8af80115548cca127282d4aaf
Python
2,050
91
# flake8: noqa # __cancel_start__ import ray import asyncio import time @ray.remote class Actor: async def f(self): try: await asyncio.sleep(5) except asyncio.CancelledError: print("Actor task canceled.") actor = Actor.remote() ref = actor.f.remote() # Wait until task i...
36791ebc198676031acafd4eca3e565f2a742da182f30253eedefe707a901960
Python
2,051
69
import numpy as np from scipy import signal def global_inh_model(r0, r_bar, T, dt, W, tau, DMatrix): # Simulates the rate equations # Function inputs # r0: rates to start at # r_bar: desired steady state solution # T: sim end # dt: size of timestep # W: connectivity matrix #...
89fb6730766d02c3d9df01c33cf091dd58132a30ac8cd9590084307b35b0ca7b
Python
2,051
53
import statistics from typing import Iterable import numpy as np def rescale_method_1(scaling_factors: Iterable[int], lambda_: float = 0.5) -> float: """ This method will use the average (scaled by `lambda_`) of the computed re-scaling factor for the pooling layer(s) feeding into a convolutional laye...
a99b88baaf25c1fad9eb7e1eef03e1e5568c9781c5899e00a51fd9e2d1c23c73
Python
2,051
47
import sys, os os.environ.setdefault('PROJECT_DIR', '.') sys.path.append(os.environ['PROJECT_DIR']) import argparse import concurrent.futures as cf import pandas as pd from src.data.buckets import MakeBuckets from src.features.tokenizer import Tokenizer def main(): parser = argparse.ArgumentParser() ...
f82671b04ba987b48d510500b774ec0445d054d341e41eb6edd29bf04bb1c665
Python
2,051
45
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
1abc71baea54445a55f9ac59b3a623142ea5ebe7f813eed95bb67aa4e8b5c902
Python
2,052
66
from typing import List from ipywidgets import widgets from data_profiling.report.presentation.core.frequency_table_small import ( FrequencyTableSmall, ) class WidgetFrequencyTableSmall(FrequencyTableSmall): def render(self) -> widgets.VBox: return frequency_table_nb(self.content["rows"]) def freq...
6fad53f1b43405ee72e27616585036df94b4ecccf9ab239d84c08c59e9c38b06
Python
2,052
66
import enum import logging import os from typing import TYPE_CHECKING from .autoscaling_actor_pool import ActorPoolScalingRequest, AutoscalingActorPool from .backlog_aware_actor_autoscaler import BacklogAwareActorAutoscaler from .base_actor_autoscaler import ActorAutoscaler from .default_actor_autoscaler import Defaul...
110e681cc7235cf66428ad26810151af1cce8be023b80bb2f1d85ab85dcc7100
Python
2,054
67
""" 3 comparisons (6 panels) Active vs. passive %sv, loading sim, and dimensionality for A1 / PEG """ import os rdir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) import sys sys.path.append(rdir) from settings import RESULTS_DIR import scipy.stats as ss import pandas as pd import numpy as np i...
2e33790e9cdc7f1117aba012e6560132b683d77b99cfdd7c4ae4608e30b807a2
Python
2,054
59
import torch class LagrangianOptimization: min_alpha = None max_alpha = None device = None original_optimizer = None batch_size_multiplier = None update_counter = 0 def __init__(self, original_optimizer, device, init_alpha=0.55, min_alpha=-2, max_alpha=30, alpha_optimizer_lr=1e-2, batch_...
861f090466a7811179b27786355fbe53e31e684bbfba0e354564b4a1b43dd826
Python
2,054
65
import numpy as np DATA_ROOT = '../data/output/' PROBLEMATIC_TRAIN_VIDEOS = ['4.4.1'] class TrainValidSplit: def __init__(self, feature_tag='sep_09'): self.feature_tag = feature_tag self.train_fpath = f'{DATA_ROOT}train_{self.feature_tag}.txt' self.valid_fpath = f'{DATA_ROOT}valid_{self.fe...
8d87a8715f1fe5be8ed0097dc1251b4fa18ce4f8d84e561daa57caf327cec17e
Python
2,054
44
import os import glob import nibabel as nib import numpy as np from utils_mirror import find_corners, mesh_sides def mesh(initial_path, initial_save_path, margin, res): rotated_path = sorted(glob.glob(os.path.join(initial_path, '*'))) for idx, path in enumerate(rotated_path): path_right = sorted(glob.g...
a8af571ec2cee41f20b79db91d38288a37d65c76d32d0212217afd02dc72cae9
Python
2,054
60
import argparse import h5py import os from glob import glob import nilearn.input_data from tqdm import tqdm LOAD_CONFOUNDS_PARAMS = { "strategy": ["motion", "high_pass", "wm_csf", "global_signal"], "motion": "basic", "wm_csf": "basic", "global_signal": "basic", "demean": True, } def main(args): ...
084de507948fce6818730fb20306ae7558ae32ee36e694813571e4f195e0a98c
Python
2,055
68
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import random import numpy as np import pytest from fairchem.data.oc.core import Adsorbate, AdsorbateS...
d66704ba2a911b2ffa5f172c7be265fdc0e33fa482e776a44ab7af705a751b62
Python
2,055
69
# -*- coding: utf-8 -*- """ Created on Sun Jul 1 12:30:00 2019 @author: ju-bar Monte-Carlo tools This code is part of the 'emilys' repository https://github.com/ju-bar/emilys published under the GNU General Publishing License, version 3 """ # %% from numba import jit # include compilation support import numpy as np ...
7004b423416666a9072b5a327de7785c02a81ac4df40b6dbe69d34165172faea
Python
2,056
61
# -*- coding: utf-8 -*- """This dummy vtk module mimics the default vtk module structure whilst only loading the libraries and corresponding dlls that vtkplotlib uses. This makes import quicker and PyInstaller builds smaller. """ from vtkmodules.vtkCommonCore import ( VTK_ID_TYPE, vtkCommand, VTK_COLOR_MOD...
c312411eac1a317b7a76e50b7a41c9102368f0d7fb47023e0fd8b5ecb4656bb1
Python
2,057
53
import numpy as np import torch from ..distances import CosineSimilarity from ..utils import common_functions as c_f from ..utils import loss_and_miner_utils as lmu from ..losses.generic_pair_loss import GenericPairLoss class TupletMarginLoss(GenericPairLoss): def __init__(self, margin=5.73, scale=64, **kwargs):...
8290c21eab3850c87f0dce2a647767d045642201405a70551815aae39e194848
Python
2,058
59
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations from typing import TypeVar import pandas as pd from fairchem.core.components.benchmark import JsonDFR...
a8b2096137644c7f81751089b05f3f62d1fe79132aba4e782e9970066017b1b0
Python
2,059
76
import os import pathlib import tempfile import h5py from deepinterpolation.inference_collection import core_inference from deepinterpolation.generator_collection import EphysGenerator def _get_generator_params(): train_path = os.path.join( pathlib.Path(__file__).parent.absolute(), "..", "...
c4d2fb3d83349e388b3a73e96b263a469ca9f3fd72a3221f915d96a94aa54da3
Python
2,059
62
from typing import Callable, Optional class TrackedActor: """Actor tracked by an actor manager. This object is used to reference a Ray actor on an actor manager Existence of this object does not mean that the Ray actor has already been started. Actor state can be inquired from the actor manager trac...
7c6c2e4130ee4a775d1af4c749c786127c4b132745e9d6c00ca569634d3c7440
Python
2,060
48
# ----------------------------------------------------------------------------- # I/O # learning data directory, train.bin and valid .bin are expected. You should prepare them using tokenize.py data_dir = 'directory_containing_train.bin/val.bin' out_dir = 'output_directory' # output directory log_dir = os.path.join(o...
5e7825f25a7ed7c725f78e5ebf35b0363e6b2fa5a00e0d99e6f9dd39d9fa37d5
Python
2,062
70
# codign_genes.py # mmsplice_splicemap.py # absplice_dna.py import snakemake import click @click.group() def cli(): pass @cli.command() @click.argument("input", type=click.Path(exists=True)) @click.argument("output", type=click.Path(exists=False)) def codign_genes(input, output): import pyranges as pr ...
7665c58e7f585fc7f42b9e7667931308ccd521f2dc28e9ff747e37ecb38b6623
Python
2,062
57
#!/usr/bin/env python # coding: utf-8 import torch import torch.nn as nn from Actor1 import init_weights class Critic(nn.Module): def __init__(self, OBS_DIM, ACTION_DIM, TARGET_DIM, RNN_SIZE, FC_SIZE, RNN): super().__init__() self.OBS_DIM = OBS_DIM self.ACTION_DIM = ACTION_DIM ...
f1d5669ea03e6f4113dca9690f72c63c62ec5ce3f33066b94393bb4b19168948
Python
2,064
72
# -*- coding: utf-8 -*- from torch.utils.data import Dataset from Bio.PDB import Polypeptide import numpy as np import torch import pandas as pd class PepCA_dataset(Dataset): def __init__(self, mode,data_set,df_dir = './data/'): aa = 'ACDEFGHIKLMNPQRSTVWY' aa2tensor_dict = {} fo...
d30622ac7ab3dd4eee9c8450833ac0eac82670d1cdd4306f8ea1599149cbd727
Python
2,065
57
import tfbio from tfbio.data import Featurizer import pybel import os import numpy as np import argparse max_dist = 35 resolution = 2 scale = 0.5 if __name__=='__main__': parser = argparse.ArgumentParser(description='Data Generator Parameters') parser.add_argument('--database', type=str) ...
caf5b2571ac04265b29f81a716ac04d2eba9b7c4aec4af54f04c56583725384a
Python
2,066
65
"""Computes and saves adjacency/distance/coulomb matrices for a dataset.""" import time from tap import Tap from GR_pKa.atomic_matrices import mol2matrix from GR_pKa.features import save_features from GR_pKa.data import get_smiles from GR_pKa.utils import makedirs class Args(Tap): data_path: str # Path to data...
dc14b54ab9d0a81b54ee7ab24fc15b6ccc52d135565441d4504efa25280bdf64
Python
2,066
60
_base_ = 'ssd300_120e_urpc-coco.py' # model settings input_size = 512 model = dict( neck=dict( out_channels=(512, 1024, 512, 256, 256, 256, 256), level_strides=(2, 2, 2, 2, 1), level_paddings=(1, 1, 1, 1, 1), last_kernel_size=4), bbox_head=dict( in_channels=(512, 1024, 5...
cf7fece94c44439616ce136ceb8c5342daf0ec38579c811927d2006fd8808009
Python
2,068
39
import logging from datetime import datetime from agent.data.entities.config import DEV_ITEM_FILTER, TEST_ITEM_FILTER, DEV_LABEL, TEST_LABEL from agent.data.entities.config import SKIP_VAL_ITEM_FILTER, SKIP_VAL_LABEL from agent.classifiers.fd_naive_item_classifier import fd_naive_classifier, evaluate_items_for_filter...
2f2c40385ca01056013a9047a65e17519c6a187dd7cda3e9b307cd77a664dfc0
Python
2,069
69
import matplotlib.pyplot as plt import seaborn as sns ucd_install=False class BulkDeconvolve(object): r""" Bulk RNA-seq deconvolution using UCDeconvolve. This class provides an interface to the UCDeconvolve platform for deconvolving bulk RNA-seq samples into cell-type proportions using curated ...
835686fee9850b0ddd1aa97cf68ed5ba196ef3f79bab2eb47fa31440465424de
Python
2,069
60
import atexit import os import signal import sys import time """ This is a lightweight "reaper" process used to ensure that ray processes are cleaned up properly when the main ray process dies unexpectedly (e.g., segfaults or gets SIGKILLed). Note that processes may not be cleaned up properly if this process is SIGTER...
a02e68cdbcdc42a9a660b0c7df32f84eb413276e36e6480af8c2704d4276e1ae
Python
2,070
72
import argparse import os import time import numpy as np import pandas as pd from tqdm import tqdm from collections import defaultdict marks = ['H3K4me1', 'H3K4me3', 'H3K9me3', 'H3K27me3', 'H3K36me3', 'H3K27ac', 'H3K9ac'] chromosomes = [f'chr{i}' for i in range(1, 23)] + ['chrX', 'chrY'] def parse_arguments(): p...
13b906f55053a61ba9c69971a9eb94a972b7b1e40899371b1cae95ed2fcadf22
Python
2,071
39
from data_processing.data_utils import * from data_processing.embed import * import os # This script will process the raw data and embed using ESM-2. """First, process the raw x-species data""" def make_xspecies_interactions(dataset, dir, target_dir, fasta_dir): species_name = dataset.split('_')[0] input_...
383f029d80d392dd9e832c1d916f67fe1fdf83e318571251f1876c5773ff2012
Python
2,072
75
"""Utility functions for operations on pandas DataFrames.""" from typing import Iterable from pandas import DataFrame def filter_by_column_values( dataframe: DataFrame, column: str, values: Iterable ) -> DataFrame: """ Return subset of dataframe based on list of values to appear in a column. Args: ...