sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
ef93fed30f296693a7a7fd4d0e68c7eb2b2e50a106a493f340697cd8ea616b5e | Python | 1,308 | 48 | # Configuration file for the Sphinx documentation builder.
# -- Project information
project = 'KWA-DLC'
copyright = '2023, BA'
author = 'BA'
release = '0.1'
version = '0.1.0'
# -- General configuration
extensions = [
'myst_parser',
'sphinx.ext.duration',
'sphinx.ext.doctest',
'sphinx.ext.autodoc',
... |
1f79f507b548d895828e7fbab55e751f831dfc99eb4a981c6d9efbba8dcf0b7d | Python | 1,309 | 31 | import os
import unittest
from unittest import mock
import torch
from nnunetv2.utilities.helpers import is_optimized_module, set_default_inductor_cache_dir
class TestCompileHelpers(unittest.TestCase):
def test_inductor_cache_dir(self):
from torch._inductor.runtime.cache_dir_utils import default_cache_di... |
50a8f48cc30707179e600be1b9f4723d624d26b9bb74aa2b4927235ddd70f1c9 | Python | 1,309 | 44 | # -*- 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 17: resnet34 CNN conversion to analog.
resnet34 inspired network based on the paper:
https://arxiv.org/abs/1512.03385
"""
# pylint: disable=i... |
8d5bd58e48762c4dfd9bbc45f9f389b5de7c476cd318a978d8ac0589378f568e | Python | 1,309 | 45 | '''
Computes T1w image in EPI-space from motion-corrected 'nulled' and 'notnulled'
timeseries as acquired with SS-SI VASO.
'''
import numpy as np
import nibabel as nb
from scipy import signal
def computeT1w(nulledFile, notnulledFile, detrend = False):
'''
Takes nulled and notnulled files as input and comput... |
beb511ef4e0a5650adb94ba69fa05e0cf2429097a2b9d28eb8a07e6f5c7b340a | Python | 1,309 | 47 | import basetest_dqn_like as base
from basetest_training import _TestBatchTrainingMixin
from pfrl.agents.al import AL
class TestALOnDiscreteABC(_TestBatchTrainingMixin, base._TestDQNOnDiscreteABC):
def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu):
return AL(
q_func,
... |
00f7599ad11029ab25c303b4ebee580d07f6f1cf8b62d476b6d5bd4fa31e4075 | Python | 1,310 | 50 | """Test remote_storage in a ci environment with real hdfs setup."""
import os
import pytest
from ray.train.v2._internal.execution.storage import (
_list_at_fs_path,
_upload_to_fs_path,
get_fs_and_path,
)
@pytest.fixture
def setup_hdfs():
"""Set env vars required by pyarrow to talk to hdfs correctly... |
c86eab9e894750f3bf34123b02f1e4de0f6ba513d8d33347794856413dbb2d97 | Python | 1,312 | 37 | class DummyModel:
"""
Dummy model to be able to create experiments without using any actual model,
for example for visualization.
"""
def __init__(
self, density, background_luminance, frame_duration, size_x, size_y, **kwargs
):
self.visual_field = DummyObject()
self.vis... |
a5a86cf47007b35518f22704c8ac1111da59b29126b1aac4340f03c26417ed6f | Python | 1,313 | 41 | import argparse
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to... |
dcf7d63d21c076c29e2b20ee58502774cfaa5d35e5f0f5bdf87ee88409202fc8 | Python | 1,314 | 48 | import numpy as np
import pfrl
class SerialVectorEnv(pfrl.env.VectorEnv):
"""VectorEnv where each env is run sequentially.
The purpose of this VectorEnv is to help debugging. For speed, you should
use MultiprocessVectorEnv if possible.
Args:
env_fns (list of gym.Env): List of gym.Env.
"... |
4683189e902c099b48907beafade8a143bb97923506834af590c588979ac87a7 | Python | 1,315 | 41 | """aihwkit example 19: Analog summary on LeNet.
Extracts analog information in the form of a printed table.
The information can also be accessed via the returned AnalogInfo object.
"""
# pylint: disable=invalid-name
# Imports from PyTorch.
from torch import nn
# Imports from aihwkit.
from aihwkit.nn.conversion impo... |
e952a719d69b393d38bc017dd0a57153a306792fd7251688e1560245d4595068 | Python | 1,315 | 42 | import argparse
import os
import matplotlib
matplotlib.use('Agg') # Needed to run without X-server
import matplotlib.pyplot as plt
import pandas as pd
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--title', type=str, default='')
parser.add_argument('--file', action='append', dest='... |
ec37cc64e36f52602dcc667dff6dbd903110f770175509da2d4e13ead276a001 | Python | 1,316 | 36 | """Splits the google speech commands into train, validation and test sets.
"""
import os
import shutil
import argparse
def move_files(src_folder, to_folder, list_file):
with open(list_file) as f:
for line in f.readlines():
line = line.rstrip()
dirname = os.path.dirname(line)
... |
4d0c219d3e3a1b6ea6a331f59f051ca3c9a5154349528738d7e04793b485bcec | Python | 1,317 | 47 | import basetest_dqn_like as base
from basetest_training import _TestBatchTrainingMixin
from pfrl.agents.pal import PAL
class TestPALOnDiscreteABC(_TestBatchTrainingMixin, base._TestDQNOnDiscreteABC):
def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu):
return PAL(
q_func,
... |
74c14fdab96d8d74f6b62169017fee62267fb13d0efbba00b5c1ae1a543af6fb | Python | 1,317 | 44 | import os
import sys
if True:
folder = 'D:\\data_TENASPIS\\added_refined_masks\\DeepWonder_scale_full'
list_Exp_ID = [ 'Mouse_1K', 'Mouse_2K', 'Mouse_3K', 'Mouse_4K', \
'Mouse_1M', 'Mouse_2M', 'Mouse_3M', 'Mouse_4M']
for Exp_ID in list_Exp_ID:
os.system('python main_RSM_copy.py \
--RMBG_model_folder arr_2... |
c25f25157bf6dfceda9409e2f28335f714d60bffed49b4fb394c49aabb426d63 | Python | 1,317 | 47 | import requests
# __serve_example_begin__
import starlette
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from ray import serve
@serve.deployment
class Translator:
def __init__(self):
self.tokenizer = AutoTokenizer.from_pretrained("t5-small")
self.model = AutoModelForSeq2SeqLM.fr... |
01304259ffb4002495dd6e386f108fb7e9cecb12b87f6f873d062ac34714974f | Python | 1,318 | 50 | """LEF constants"""
from rdkit import Chem
# CF definitions
CF_MOTIF = Chem.MolFromSmarts("[#9]-[#6]")
CF2_MOTIF = Chem.MolFromSmarts("[#9]-[#6]-[#9]")
CF3_MOTIF = Chem.MolFromSmarts("[#9]-[#6](-[#9])-[#9]")
CF_LABELS = ["CF", "CF2", "CF3"]
# Column names
BOUNDS_COLUMN = "Dice Similarity Upper Bound"
CONFIDENCE_COLUM... |
0800be3237f1e6fd497347cb82bd73ec94005460e17a1d1ac581118023bfe2e9 | Python | 1,318 | 38 | # Copyright 2022 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
d9ef27338f0860b4aa19957b674c99af35c4d26236a812849872d76268c1c936 | Python | 1,318 | 41 | import math
import torch
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
class GraphConvolution(Module):
def __init__(self, in_features, out_features, bias=True):
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.... |
1decfbd0a1bc3afaf879e56eb6614009f5c5959b256918fbe40e1b737583300c | Python | 1,319 | 34 | from typing import List, Union
from mmengine.structures import PixelData
from torch import Tensor
from lqit.common.structures import SampleList
def add_pixel_pred_to_datasample(data_samples: SampleList,
pixel_list: Union[List[PixelData],
... |
cf33bbb76b24c0ab95b323fd78b5351e1efa9f018eb0d65ecbddc1706d1392af | Python | 1,319 | 42 | from __future__ import annotations
from typing import Sequence, Union
from numbers import Number
from . import Operator, sigma_x, sigma_p, sigma_m, sigma_z
from ..global_defs import get_sites
def Heisenberg(
J: Union[Number, Sequence[Number]] = 1.0,
n_neighbor: Union[int, Sequence[int]] = 1,
msr... |
f7369b11055cedee23c836ce9b502565dbcb77a56b81653245dc8b69bbed54c3 | Python | 1,319 | 40 | import numpy as np
import nir
class CubaLIFImplementation(object):
"""Numpy forward Euler implmementation of CubaLIF Node."""
def __init__(self, dt, cuba_node: nir.CubaLIF):
self.dt = dt # scalar
self.node = cuba_node
self.v = np.zeros_like(self.node.v_threshold)
self.I = np... |
5ce5570c297633b1a79c7432a8ae30470b73847b70db0e718e5b383cb32861b2 | Python | 1,320 | 38 | # --- START OF FILE run_app.py ---
import streamlit as st
import app
import operator_mode
import computer_use_agent
# Store the original function from app.py
original_process_query = app.process_query_with_progress
def patched_process_query_with_progress(query, rag_system, selected_package, user="unknown"):
# 1) ... |
e63e7e97791c6ca7909c2a8250aedc030acd13896ffc2a94524c766f3f96817f | Python | 1,320 | 42 | # built-in dependencies
from typing import Any, List, Union
# project dependencies
from deepface.commons.onnx_utils import build_session
from deepface.models.facial_recognition.onnx.OnnxFacialRecognition import OnnxFacialRecognition
from deepface.commons.logger import Logger
logger = Logger()
# pylint: disable=line-... |
3833f4218f8489fd7cb98cdb57d717c8ccc19f6f3d06ef196cdc3c0c67a46dcf | Python | 1,321 | 52 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
Reformat 100% reference calls salvaged during pesr + depth merging
"""
import argparse
import sys
import pysam
import random
import string
# Reformat salvaged records to be consistent with existing naming scheme
def reformat(record, prefix):
record.info['MEMBE... |
6b229a1150086a88c2330b2f3c699f294497f2f334b45605b6c8ae828b5e2e42 | Python | 1,323 | 47 | import json
from functools import lru_cache
from pathlib import Path
from typing import List
_RAYCI_VERSION_FILE = ".rayciversion"
def _find_ray_root() -> Path:
"""Walk up from this file and cwd looking for .rayciversion."""
start = Path(__file__).resolve()
for parent in start.parents:
if (parent... |
6ef9eb0828f5c5194fe20f1678b11c7a7ea480ecda17f049a1f6dc583245aa52 | Python | 1,323 | 43 | import os
import gzip
import requests
import numpy as np
def load_data(kind='train'):
base_url = 'http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/'
labels_filename = '%s-labels-idx1-ubyte.gz' % kind
images_filename = '%s-images-idx3-ubyte.gz' % kind
# Download labels file
labels_url = ... |
efc2aef603a645381232596175ef2eb386fd4f0904ee4b6fb5027beced838cc4 | Python | 1,324 | 30 | # This example illustrates how to generate a functional connectivity matrix and its respective plot
import matplotlib
matplotlib.use('Agg')
import os
from os import path
from samri.analysis import fc
from samri.plotting import connectivity
from samri.fetch.templates import fetch_rat_waxholm
# fetch data templates a... |
25fc377e4931ba71a037a44b80cd76e0cd80dc754a640610a351e8d4ffec27f8 | Python | 1,325 | 26 | # -*- coding: utf-8 -*-
"""
PMLB was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- William La Cava (lacava@upenn.edu)
- Weixuan Fu (weixuanf@upenn.edu)
- and many more generous open source contributors
Permission is hereby granted, free of charge, ... |
d9040efb5a11a1bc2cbcdcedcbd97890db8dec6a870702745dc8618ee7bf8704 | Python | 1,325 | 48 | #!/usr/bin/python
import sys,os
def usage():
print "Usage:", sys.argv[0], "<wikiname> <htmlname>"
print ""
print "Replaces wiki documentation with documentation from html files"
def wikidoc(pagename, htmlfile):
f = open(htmlfile)
doclines = f.readlines()
f.close()
starttag = "<!-- WIKIDO... |
39d278d74759b32de0c9eeb2520ba6df4a615928ea320cafbd18166f7ff312a5 | Python | 1,326 | 37 | """
API clients module for DataCollect.
This module provides organized access to 29+ biological database APIs,
categorized by data type for easy discovery and use.
Categories:
- proteins: Protein sequences, structures, and interactions
- genomics: Gene annotations, variants, and genomics data
- expression: Gene exp... |
af164ca15d0c1e900b95f03171ea823103c5f10bb3e80c238ee768f9cb2d4b4d | Python | 1,326 | 49 | """Type definitions and aliases for SiaPy library.
This module defines common type aliases used throughout the SiaPy library
for spectral images, arrays, and data containers to ensure type safety
and consistency across the codebase.
"""
from typing import Any, Sequence
import numpy as np
import pandas as pd
import s... |
842d981ab3e07293bb6d666900ce9c83e442705a51c3511d400942ca4d1a856a | Python | 1,327 | 41 | # built-in dependencies
from typing import Any, List, cast
# 3rd party dependencies
import numpy as np
from numpy.typing import NDArray
# this module is framework agnostic on purpose. the labels and the post processing below
# do not depend on a backend engine, so the tensorflow and the pytorch models share them.
# ... |
9b2dff812d2436826423af1b7ac3b4ddca2c83305d5ba2dcf32ecc3252053c0c | Python | 1,327 | 40 | """Annotation class unit testing"""
import unittest
from pathlib import Path
import numpy as np
from epilepsy2bids.annotations import Annotations
class TestAnnotations(unittest.TestCase):
def test_loadTsv(self):
annotations = Annotations.loadTsv("tests/sample.tsv")
# Test loading of event
... |
bd136d63746030c974732cdc398940f57f9f745096616c72d570bdb080913c56 | Python | 1,327 | 57 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
Rename variants after vcfcluster
"""
import argparse
import sys
from collections import defaultdict
import pysam
def rename(vcf, fout, prefix='SV_pipeline'):
indexes = defaultdict(int)
fmt = '{prefix}_{svtype}_{chrom}_{idx}'
for record in vcf:
... |
d8ec7cf235097a6d3b36d87602314353b86f804911cd989d527c6b99f870491b | Python | 1,327 | 50 | import ruamel.yaml
import os
import subprocess
import hashlib
from conf_build import VERSION, vVERSION, URL_ARCHIVE
file_path = "../recipe/meta.yaml"
#--- calculate sha256 of the source tar.gz
# tar.gz file name
output_file = f"../archive/pybioportal-{vVERSION}.tar.gz"
# hash_sha256 = hashlib.sha256()
# with open(... |
cd89ce38e2330e6465ca92012ceae9c5a67fd18a1cf0b8b9f24092e2cef27394 | Python | 1,328 | 60 | from spinnaker2 import snn, hardware
neuron_params = {
"threshold":1.,
"alpha_decay":0.9,
"i_offset":0.0,
}
stim = snn.Population(
size=10,
neuron_model="spike_list",
params={0:[1,2,3], 5:[20,30]},
name="stim")
pop1 = snn.Population(
size=20,
... |
f1e74dfa87850015a07dffba621912fa83a3907f6afe05644212c5fa8f6f8921 | Python | 1,329 | 40 | import exputils as eu
import torch
from .differentiable_neural_dictionary import DND
class NEC(torch.nn.Module):
"""
Implementation of neural episodic control architecture as introduced in
Neural Episodic Control (Pritzel et. al, 2017)
"""
def __init__(self, embedding_net, n_actions, config=None, ... |
2323fe3061c63bbe4b8d7f66a8bfb5eeb2e94fe9bdfeb1d465fa29e96db2fe6c | Python | 1,330 | 39 | # Ultralytics YOLO 🚀, GPL-3.0 license
import collections
from copy import deepcopy
from .augment import LetterBox
class MixAndRectDataset:
"""A wrapper of multiple images mixed dataset.
Args:
dataset (:obj:`BaseDataset`): The dataset to be mixed.
transforms (Sequence[dict]): config dict to... |
cd1c196f41cc4622421e4d75e388062422268690d0bd07bdea50f7f4ffb0acee | Python | 1,330 | 42 | from .mlp import MLPDecoder, ResMLPDecoder
from .zinb import NBMLPDecoder
from torch import nn
def setup_decoder(model_type, in_dim, hidden_dim, out_dim, num_layers, dropout, norm, batch_num=0, dataset_num=0, platform_num=0) -> nn.Module:
if model_type == 'nbmlp':
mod = NBMLPDecoder(
in_dim=in_... |
ea3f3a22aa583e0ba98bdecaec50fc3d97e55e3e5c1f055406efd15cbc3d7063 | Python | 1,330 | 42 | #!/usr/local/bin/ipython -i
from mozaik.experiments import NoStimulation
from mozaik.experiments.vision import (
MeasureOrientationTuningFullfield,
MeasureNaturalImagesWithEyeMovement,
)
from mozaik.sheets.population_selector import RCRandomPercentage
from parameters import ParameterSet
def create_experiments... |
0cb81bdcad37866f0f0e4ddb5bc13f77f4fa513fa5a5217d0fddafe2593b700f | Python | 1,332 | 59 | """Flatten Braille graph for SpiNNaker2 and fix some shapes."""
import nir
nir_model = nir.read("braille.nir")
nodes_to_copy = {
"fc1": "fc1",
"fc2": "fc2",
"input": "input",
"lif1.lif": "lif1",
"lif1.w_rec": "w_rec",
"lif2": "lif2",
"output": "output",
}
new_edges = [
# forward
... |
ea82f0d6a356c7f183d0dc7d43ebb13bf48863974b7cb201321b39b46aa735c0 | Python | 1,332 | 43 | import unittest
from neuron_morphology.morphology_builder import MorphologyBuilder
from neuron_morphology.constants import (
SOMA, AXON, APICAL_DENDRITE, BASAL_DENDRITE)
class TestMorphologyBuilder(unittest.TestCase):
def test_branching(self):
morphology = (
MorphologyBuilder()
... |
cf97d0584f05c85941366d7af8f22204abee0425c104b3b1e12ce9d467f5bef2 | Python | 1,333 | 37 | import os
import sys
sys.path.append('.')
import cv2
import math
import torch
import argparse
import numpy as np
from torch.nn import functional as F
from model.pytorch_msssim import ssim_matlab
from model.RIFE import Model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = Model()
model.loa... |
dca9860bfdfb915e03f288edc5e1a5abfc3a06892231aacbdda6dc79efeb2cf5 | Python | 1,333 | 44 | # flake8: noqa
# fmt: off
# __actor_restart_begin__
import os
import ray
ray.init()
# This actor kills itself after executing 10 tasks.
@ray.remote(max_restarts=4, max_task_retries=-1)
class Actor:
def __init__(self):
self.counter = 0
def increment_and_possibly_fail(self):
# Exit after every... |
1e062d62357ee27026f92c9bf1c9638dc266a8ddb5600b5208fa175be909fc7f | Python | 1,334 | 44 | import os
import unittest
from unittest.mock import patch
from ci.ray_ci.configs import (
DEFAULT_PYTHON_TAG_VERSION,
DEFAULT_PYTHON_VERSION,
PYTHON_VERSIONS,
)
from ci.ray_ci.utils import ci_init
class RayCITestBase(unittest.TestCase):
def setUp(self) -> None:
ci_init()
self.patcher ... |
6ee4871451e04986cc7b4369405aa7d030683e4785e634c87ce90c89651cc489 | Python | 1,334 | 49 | #!/usr/bin/env python
from setuptools import setup, find_packages
import os
import numpy
import codecs
import os.path
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), "r") as fp:
return fp.read()
def get_version(rel_path):
for l... |
f5f35c7e825a32337d06bd6f5a81b77d9ae3d67b6e05f443d0c50a7a75bee0c5 | Python | 1,334 | 63 | """Logging-related constants shared across Ray libraries.
Used to distinguish standard Python logging attributes from Ray or user context.
See: https://docs.python.org/3/library/logging.html#logrecord-attributes
"""
from enum import Enum
LOGRECORD_STANDARD_ATTRS = frozenset(
{
"args",
"asctime",
... |
719ece05f4dbbaa96f87e6ff0c2a082fd78b3976054e7c300eef729b9daa778d | Python | 1,335 | 24 | ################################################################################
# -- Default set of parameters
################################################################################
import numpy as np; import pylab as pl; import time, sys, os
import matplotlib
from defaultParams import *
fr_chg_factor = np... |
f7f081ee78e9ad93f431b1cc7613788ad0f42ac6c27894d704effb7e3e3ab0aa | Python | 1,335 | 32 | import sys
import os
sys.path.insert(0, "/srv/home/zgaleday/torch_pgn")
from torch_pgn.train.run_training import run_training
from torch_pgn.train.hyperopt import hyperopt
from torch_pgn.args import TrainArgs, HyperoptArgs
args = HyperoptArgs()
args.from_dict({'raw_pdb_path': '/srv/home/zgaleday/IG_data/D4_pdbs/d4_re... |
f9cb3115db48a40e3b8221bb721bcd2c4ace8bc4eca27d85e1dac874e779fe29 | Python | 1,336 | 27 | """Geometry rather than expression — ``ov.space.geom``.
Align serial sections into one frame, stack them into a volume, fill the gaps::
aligned = ov.space.geom.align([s1, s2, s3])
volume = ov.space.geom.stack(aligned, z_spacing=10.0)
mid = ov.space.geom.interpolate(aligned[0], aligned[1])
Match sing... |
0cd303fc61b7d7f8211fe54d5c6fa04d1c9f54d7995e9ccaf54f2c532c69563b | Python | 1,337 | 38 | def DoubleWell(para): #Generate dataset
'''
In this function, we generate the training and predicting sets from SDE (using Euler method).
'''
dimensions = 1
a = 0; b = 5; c=0; epsilon=0.3
xtime = np.linspace(0, T2,int(T2/dt)+1)
u = np.zeros((dimensions, int(T2/dt)+1))
q... |
51b25454acf39464c1ba31419c5ffbe5b6f5ba3ac4de33899e81f3d73a6eedf5 | Python | 1,337 | 47 | import ssl
import sys
import pytest
import trustme
import ray
from ray.job_submission import JobSubmissionClient
@pytest.fixture(scope="session")
def ca():
return trustme.CA()
@pytest.fixture(scope="session")
def httpserver_ssl_context(ca):
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
localhost_c... |
bdd2891761da54fab34bc545605e2aa8260f3527c6c4884e0c0eb5154b16e1ed | Python | 1,337 | 41 | # 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, ... |
db711f3aa02739bdb85edcc899ef8c38273d887fc7a0719834d93b80f7950392 | Python | 1,337 | 38 | import gym
import numpy as np
import pytest
import pfrl
@pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v0"])
@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64])
def test_cast_observation(env_id, dtype):
env = pfrl.wrappers.CastObservation(gym.make(env_id), dtype=dtype)
rtol ... |
ea5ca474a521c45241f1c537bdcb3527538798a765e4b0c7fe9c6c4d98cf4ee5 | Python | 1,337 | 43 | import pandas as pd
import numpy as np
import gzip
import os.path as osp
import os
import shutil
import oddt.pandas as opd
from tqdm import tqdm
TEST_FILE = '/srv/home/zgaleday/IG_data/raw_data/d4_mmgbsa/d4_mmgbsa_set_chunk_map.csv'
SCREEN_DIRECTORY = '/srv/nas/mk2/projects/D4_screen/'
TEST_CHUNK = 'vs_run1_chunk28150... |
f496e878538b421326a4928a32233cc201108534d84638e540b9d8075f36aa0e | Python | 1,338 | 48 | import os
import subprocess
from conf_build import vVERSION
output_folder = f"dist/{vVERSION}/pypi"
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# commands to execute
commands = [
f"python setup.py sdist --dist-dir {output_folder} bdist_wheel --dist-dir {output_folder}"
]
# command must ... |
6b9174d18adddf96e98ae5393bbd6f77aa8c4f9260d596a1cf1b2fc779f72cfb | Python | 1,339 | 37 | from .zinb import ZINBReconstructionLoss, NBReconstructionLoss, NBDenoisingLoss, NBImputationLoss
from .autoencoder import ReconstructionLoss
from torch import nn
def create_objective(**config) -> nn.Module:
if config['type'] == 'recon':
return ReconstructionLoss(**config)
elif config['type'] == 'zinb'... |
dd431181c00758086de4e96463ab5f631bc88b0861cbe7aa64dba17585418bc8 | Python | 1,340 | 41 | import gym
class ContinuingTimeLimit(gym.Wrapper):
"""TimeLimit wrapper for continuing environments.
This is similar gym.wrappers.TimeLimit, which sets a time limit for
each episode, except that done=False is returned and that
info['needs_reset'] is set to True when past the limit.
Code that cal... |
6c191d90fd9bc8bebc7998f6b003b19ac8147243aafa9dbd8b2cb2e89b1b9470 | Python | 1,341 | 46 | import sys
from typing import List
from unittest import mock
import pytest
from ci.ray_ci.builder_container import BuilderContainer
def test_init() -> None:
builder = BuilderContainer("3.10", "optimized", "aarch64")
assert builder.docker_tag == "manylinux-aarch64"
builder = BuilderContainer("3.10", "opt... |
dc15aafcfe04f75903e8e88a9ded17511e715784487262d81f28a79053fcfb24 | Python | 1,342 | 53 | # __serve_example_begin__
import time
import psutil
from ray import serve
@serve.deployment(
autoscaling_config={
"min_replicas": 1,
"max_replicas": 5,
"metrics_interval_s": 10,
"policy": {
"policy_function": "autoscaling_policy:custom_metrics_autoscaling_policy"
... |
22dcacadaf4e9667671e13e1bf66817d7695c4af6b5825d59e5acba9293f5b0b | Python | 1,343 | 45 | import nibabel as nib
import numpy as np
from scipy.ndimage import binary_dilation, generate_binary_structure
def selective_dilation(
input_nifti, output_nifti, src, sink, src_bg, sink_bg, structure_size=3
):
# Load image
img = nib.load(input_nifti)
data = img.get_fdata().astype(np.int32)
# Creat... |
5270bcab1194780538856aa11759c679c46b064602fbcc94b2276528ccf9bfb8 | Python | 1,343 | 40 | import io
import platform
def patch_psutil():
"""WSL's /proc/meminfo has an inconsistency where it
nondeterministically omits a space after colons (after "SwapFree:"
in my case).
psutil then splits on spaces and then parses the wrong field,
crashing on the 'int(fields[1])' expression in
psutil... |
68ceb3567116d9ad611fb3671e35d521a03e09ad519fe556c53356e9213f211e | Python | 1,343 | 36 | import torch
from ..distances import DotProductSimilarity
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from ..losses.base_metric_loss_function import BaseMetricLossFunction
class NPairsLoss(BaseMetricLossFunction):
def __init__(self, **kwargs):
super().__ini... |
aee027663d4a8c274e61e7ce44db8f02178c3087e8fc1b5981f7b0f41dd15768 | Python | 1,345 | 39 | # 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, sof... |
c97ecb816f78cb67a21358a7a473da66f592b40006dac513cf47aa1c7cf09e38 | Python | 1,345 | 41 | import tarfile
import os
import subprocess
from conf_build import vVERSION
def create_tar_gz(output_file, folders, files):
with tarfile.open(output_file, "w:gz") as tar:
# Add folders to file tar.gz
for folder in folders:
tar.add(folder, arcname=os.path.basename(folder))
# Add ... |
e321bb60e8f4333bf26fd951cce00419b9e0dd7eeec4f1453541179383c92c0f | Python | 1,345 | 41 | import torch
import torch.nn as nn
class Policy(nn.Module):
def __init__(self, args):
super(Policy, self).__init__()
para = args["para"]
self.device = args["device"]
self.horizon = 96
input_dim = para["current_meas_dim"] + para["future_disturbance_dim"] * self.horizon
... |
3d05b979aca80ffd760d547ef5b314a9a0112a04704ca71dbb0d426b5ab060a7 | Python | 1,346 | 53 | """
Logger function for data-profiling reports
"""
import logging
import pandas as pd
from data_profiling.utils.common import (
analytics_features,
calculate_nrows,
is_running_in_databricks,
)
class ProfilingLogger(logging.Logger):
def __init__(self, name: str, level: int = logging.INFO):
... |
4880cbe5d46e3b43555902a9189e1a423f0fba606cc4e2d716c3c346a26b12fd | Python | 1,346 | 47 | """
A collection of "vanilla" transforms for transformers functions
"""
import torch
from monai.transforms.compose import Transform
import torch.nn.functional as F
from src.networks.transformers.img2seq_ordering import Ordering
from src.networks.vqvae.vqvae import VQVAEBase
class ConvertToSequence(Transform):
""... |
89682010213ebeab320cbf21989657ade0e52111a91eead34e4e7e808447f794 | Python | 1,346 | 51 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
Convert bedcluster output to RdTest format
"""
import argparse
import sys
import pandas as pd
def make_depth_rdtest_bed(svof):
svof['#chrom'] = svof['#chrom'].astype(str)
svof['start'] = svof.start.astype(int)
svof['end'] = svof.end.astype(int)
bed... |
ac2381b4643bc62dc36a151763caf9202b7fb7a4b4a20a78b8324bf6ae1abeca | Python | 1,346 | 33 | from dataclasses import dataclass
from typing import List, Optional, Union
import numpy as np
import PIL
from PIL import Image
from ...utils import BaseOutput, is_torch_available, is_transformers_available
@dataclass
# Copied from diffusers.pipelines.stable_diffusion.__init__.StableDiffusionPipelineOutput with Stab... |
def1441104385e06e5335d117db06a6bc9cf99f9bf8c8b3ee246a450427edfcd | Python | 1,346 | 42 | #!/usr/local/bin/ipython -i
from mozaik.experiments import NoStimulation
from mozaik.experiments.vision import (
MeasureOrientationTuningFullfield,
MeasureNaturalImagesWithEyeMovement,
)
from mozaik.sheets.population_selector import RCRandomPercentage
from parameters import ParameterSet
def create_experiments... |
27a44bdf67d5f1b3209e30c3c494d772897c1b2df2cb2420b4dbd2c04fa5d893 | Python | 1,347 | 49 | import sys
import numpy as np
import matplotlib.pyplot as plt
def read_transmembrane_potential(input_file, dt, print_rate):
data = np.genfromtxt(input_file)
n = len(data)
timesteps = np.arange(0,n)*dt*print_rate
vms = data
return timesteps, vms
def plot_transmembrane_potential(t, v):
plt.grid()
plt.plot(t... |
a22f0a8d557bc15b0f37b99ab786b04aa69013dba1e54dfc25496d6502192181 | Python | 1,347 | 38 | # Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
b33026415dc93376548d80a08426e348272de723ef68f78ee5fc392dbd52af1c | Python | 1,348 | 42 | #!/usr/local/bin/ipython -i
from mozaik.experiments import NoStimulation
from mozaik.experiments.vision import (
MeasureOrientationTuningFullfield,
MeasureNaturalImagesWithEyeMovement,
)
from mozaik.sheets.population_selector import RCRandomPercentage
from parameters import ParameterSet
def create_experiments... |
3c191e014e18edbb3d6931f62f1259f6c76082fcbd60241b5df89fa770763871 | Python | 1,350 | 50 | # flake8: noqa
# __chaining_example_start__
# File name: chain.py
from ray import serve
from ray.serve.handle import DeploymentHandle, DeploymentResponse
@serve.deployment
class Adder:
def __init__(self, increment: int):
self._increment = increment
def __call__(self, val: int) -> int:
return ... |
995d1fb590ec93ca8aa7569a3e5bd38e5f02c32186c69887fb9c344c51d4e7d6 | Python | 1,350 | 50 | # -*- 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 22: Simple example of how to use an analog tile as a matrix"""
# pylint: disable=invalid-name
# pylint: disable=too-many-locals
# Imports fro... |
ef0d8c7da7471a8914a055a12bca6e76393a4388d1d1a984ded56c7bc92af494 | Python | 1,350 | 41 | from typing import List, Sequence
from mmengine.model import BaseDataPreprocessor
from mmengine.structures import BaseDataElement
from lqit.registry import MODELS
from lqit.utils import ConfigType
SampleList = List[BaseDataElement]
@MODELS.register_module()
class MIMBDataPreprocessor(BaseDataPreprocessor):
de... |
f7e8d48b95661019d33310c57d40b0ce7cbce6b0b74e7c0710d41a45f577dcb2 | Python | 1,350 | 34 | import sys
import os
sys.path.insert(0, "/srv/home/zgaleday/torch_pgn")
from torch_pgn.train.run_training import run_training
from torch_pgn.train.hyperopt import hyperopt
from torch_pgn.args import TrainArgs, HyperoptArgs
args = HyperoptArgs()
args.from_dict({'raw_pdb_path': '/srv/home/zgaleday/IG_data/D4_pdbs/d4_re... |
321b3eb13ee48fb0fc81f77071fe62a9bbe1f17a328fbbde84835cf2dc38b49e | Python | 1,351 | 42 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#... |
39ced3de1978b63c4a744abc326052addea5ed21728255666b8cac657e9b4e8c | Python | 1,351 | 42 | import exputils as eu
import numpy as np
def set_value_by_function(value_config, *args, **kwargs):
# default: return the given config if it is not a dict and has a function argument
retval = value_config
if isinstance(value_config, dict) and 'function' in value_config:
# all items in the value_c... |
3bf6632e4f849ed297828547f2af27b9bcc2a366739eb17ee9dda8e993652403 | Python | 1,351 | 37 | #!/usr/bin/env python
import pandas as pd
import bz2
import pickle
import _pickle as cPickle
# import torch
# from torch import Tensor
# from torch.nn import functional as F
import pymochi
from pymochi.data import *
def load_mochi_data(file):
with bz2.BZ2File(file, 'rb') as f:
load_dict = cPickle.load... |
c6085314b8c96e413d046b32e31a6a622142ba50f5faa1fa2bff845190bce3a2 | Python | 1,351 | 41 | # usage: python _run-bertrbp-h0.py --positive <p.fa> --negative <n.fa> > train.tsv
# python _run-bertrbp-h0.py --no-info <t.fa> > test.tsv
from argparse import ArgumentParser
from pathlib import Path
import re
import sys
def parse_fasta(fasta_path, is_positive):
with open(fasta_path) a... |
4a379200ae663ffa62a2871ca81d2c838ee5eb4e331a675fd5195956c9435d10 | Python | 1,354 | 38 | #!/usr/bin/env python3
"""Tests for build_common.py"""
import tempfile
import unittest
from pathlib import Path
from ci.build.build_common import BuildError, parse_file
class TestParseFile(unittest.TestCase):
"""Test parse_file() extracts values from config files."""
def test_parses_quoted_value(self):
... |
0990960812070fb88922a7164b42cfb8c0e3ad304ff17a4f76f1f7f86d25c473 | Python | 1,355 | 39 | # Copyright 2022 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
57dc61a7e610f886773dee414ef35264af145c341fd5b41f42069b9716f494c7 | Python | 1,355 | 36 | import pytorch_lightning as pl
from nmnist import NMNISTFrames, NMNISTRaster
from cnn import CNN
from snn import SNN
from argparse import ArgumentParser
if __name__ == '__main__':
pl.seed_everything(1234)
parser = ArgumentParser()
parser.add_argument('--batch_size', default=128, type=int)
parser.add_... |
5dea7022336e3afa7424f407abf8f78fd83fbf4c07f6885993224ecd2dee7b08 | Python | 1,355 | 46 | #!/bin/python
import sys
from collections import defaultdict
def count_vids(list_path):
counts = defaultdict(lambda: 0)
with open(list_path, 'r') as f_list:
for path in f_list:
with open(path.strip(), 'r') as f:
for vid in f:
counts[vid.strip()] += 1
... |
89b9e65ca2d980fdbb20c7a9864301ea5a9adda408cb34dade5528861fa6c0dd | Python | 1,355 | 57 | import numpy as np
import torch
import sinabs.layers as sl
def test_img2spk():
lyr = sl.Img2SpikeLayer(
image_shape=(2, 64, 64),
tw=10,
max_rate=1000,
)
img = torch.rand(2, 64, 64)
spks = lyr(img)
assert spks.shape == (10, 2, 64, 64)
def test_reconstruct_image():
... |
ac3d5b74986516f17120f3677cee2291cfdabad7c1e786b1c56cfd7a935cda33 | Python | 1,355 | 45 | """
Taken from pygcn, https://github.com/tkipf/pygcn/
"""
import math
import torch
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
class GraphConvolution(Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features... |
bf63a86ff437e1af9604f2f5e1f3e936511c7c2fabebababac9369baf898ce25 | Python | 1,355 | 46 | import numpy as np
from siapy.transformations import image
def test_add_gaussian_noise(spectral_images):
image_vnir = spectral_images.vnir
noisy_image = image.add_gaussian_noise(
image_vnir,
mean=0.0,
std=1.0,
clip_to_max=True,
)
assert noisy_image.shape == image_vnir... |
f43e66971c240e36b44e3a0bf3115105423a6eabeabb1969174b77b091c3792a | Python | 1,355 | 57 | import os
import numpy as np
import pandas as pd
from utils import pickle_load
import matplotlib.pyplot as plt
datapath = '/Users/qlu/Dropbox/github/extended-event-modeling/output/run_sem/dec_18_pe5E-01_s1010_1E-02_1E-01'
fname = '1.1.10_kinect_trimdec_18_pe5E-01_s1010_1E-02_1E-01_diagnostic_13.pkl'
data_dict = pickle_... |
feaeae0944226afec405793101945ffa3ba6932d4bd335030950df5d8348e1d2 | Python | 1,355 | 58 | #!/usr/bin/env python
"""
Collect random forest cutoff metrics. Writes stats to stdout.
Metric format: rf_cutoff_<TEST>_<SVTYPE>_<ALGTYPE>_min<MIN>_max<MAX>
"""
import argparse
import sys
import pandas as pd
KEY_PREFIX = "rf_cutoff_"
def main(argv):
parser = argparse.ArgumentParser(
description=__doc... |
4c7c423522d344ab94b2e563361a4d183974f0eaf4f87e7600647177c9cc3304 | Python | 1,356 | 33 | import argparse
import pandas as pd
import numpy as np
import math
parser = argparse.ArgumentParser(description='Parse arguments')
parser.add_argument('--bed', dest='bed', help='Input BED file')
args = parser.parse_args()
bed_file = args.bed
bed_original = pd.read_csv(bed_file, sep='\t', index_col=False).replace(np.... |
5dd001d731bbfb010d16c80de3ead8fe29393706f77cdb22e057e1a1b1b43391 | Python | 1,358 | 52 | import hail as hl
hl.init()
TE_mt = hl.read_matrix_table('TE-all.mt')
TE_mt = TE_mt.drop('Chr',
'Gene_ann',
'X1KGP_ann',
'X1KGP_AF',
'X1KGP_strand',
'EuL1db_ann',
'EuL1db_AF',
'EuL1db_strand',
'Evrony_ann',
'Evrony_strand',
'KNR_ann',
'KNR_papers',
'Overlapped_repeats',
... |
86e76a866466a622029c0ab9189f13fe914b6ef12425ef62f4eb67f2e949147d | Python | 1,358 | 58 | #!/usr/bin/env python
import sys
import os
import pprint
# ngs_mapper should be first in the PATH
sys.path.insert( 0, os.environ['PATH'].split( ':' )[0] )
import samtools
def main( args ):
for col in cols( args.bamfile, args.regionstr, args.minmq, args.minbq ):
stats = col.base_stats()
print "{}:... |
21db8dac37d910377fbcd8ef6579f0e51e3e4d62741a3b91c0cd658f2f6be132 | Python | 1,359 | 54 | import unittest
import numpy as np
import pytest
import torch
import pfrl
class TestBatchStates(unittest.TestCase):
def _test(self, gpu):
# state: ((2,2)-shaped array, integer, (1,)-shaped array)
states = [
(np.arange(4).reshape((2, 2)), 0, np.zeros(1)),
(np.arange(4).re... |
6ecd07e0fd40daefb69fd522c15548e934fc2d8172e4db9addcde48e20763238 | Python | 1,359 | 36 |
import os
import csv
def csv_to_txt_folder(csv_folder, txt_folder):
# Check if the input folder exists
if not os.path.exists(csv_folder):
return
# Check if the output folder exists, if not, create it
if not os.path.exists(txt_folder):
os.makedirs(txt_folder)
# Iterate through eac... |
9fb3244d7aa2ab433e78593b018dedf0d2982d75148e7f812e9d6816647c1c19 | Python | 1,359 | 44 | """Shared helpers for ``ov.micro`` submodules.
Tiny utilities that used to be copy-pasted across ``_da.py`` / ``_diversity.py``
/ ``_pp.py``. Kept private (underscore-prefixed) to avoid locking the API.
"""
from __future__ import annotations
from typing import Optional
import numpy as np
from scipy import sparse
d... |
f4c21b056e9d4a1a9febd42a5ace6cc626f52bd665dd16b3099b6b48f5d64acb | Python | 1,359 | 43 | import pandas as pd
import math
annovar_annot_file = "KCHIP.snp.imputed.HRC.abc.anno"
df_annot = pd.read_csv(annovar_annot_file, sep="\t", index_col=False)
df_annot = df_annot[['SNP', 'avsnp150']]
df_annot.rename(columns={"avsnp150":"RSID"}, inplace=True)
plink_result = "KoGES_MetS_logistic_plink.MetS.glm.logistic.hy... |
4b6a4ef42a191555cfc2eea1d793f236592d7668dbbf6a05f87919389692e5f1 | Python | 1,360 | 34 | """Strip build-environment-local dependencies from a Sphinx environment pickle.
Run this with the Python that built the docs (the doc-build image's interpreter),
which is typically a newer Sphinx than ci/ray_ci's Bazel-pinned one. A pickled
Sphinx environment can only be unpickled by a matching Sphinx; loading a Sphin... |
70bd2dcbb00cbdd95f3279063c7e8bd59e196238bb4bfdac63cd4bd9bdf39114 | Python | 1,361 | 39 | """Script to build a small sample EDF from an EDF recording. The recording header and list of signals are kept the same.
The content of data is white noise. The output file is named input_sample.edf
"""
import argparse
from pathlib import Path
import numpy as np
from pyedflib import highlevel
DURATION = 2
AMPLITUDE ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.