sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
772cea551f661461d312f5574d730c9a278a6bdb0c8713f6267c224ecd0ddd36 | Python | 1,152 | 30 | class Recurrent(object):
"""Recurrent module interface.
This class defines the interface of a recurrent module PFRL support.
The interface is similar to that of `torch.nn.LSTM` except that sequential
data are expected to be packed in `torch.nn.utils.rnn.PackedSequence`.
To implement a model with ... |
e0ddb42200b857c1e50469e14640b891c98f69469087c68bef79bae91c7c4d98 | Python | 1,153 | 25 | ####################################################################################################
# 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... |
07b6744b9ca9f83c8018e4d5951fae1bdea74387b99ca69930c60138801f1e08 | Python | 1,154 | 35 | """
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
# Register triton_op kernels with torch.ops.fairchem.* on package import
# This must happen before Node... |
53c767f3b57fedbbdac1f9e8aeac6d6b082460ebe940608d2f4e598c6a1f9230 | Python | 1,154 | 23 | ####################################################################################################
# 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... |
958f47e5ab7b5c2d93455001da73e2d1db0530f421dcca1e58fbd9c978ac619e | Python | 1,154 | 40 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import tensorflow as tf
from droid_mvp_model_description import create_movinet_classifier, create_regressor_classifier
import logging
tf.get_logger().setLevel(logging.ERROR)
pretrained_chkp_dir = "droid_mvp_checkpoint/chkp"
movinet_chkp_dir = 'movinet_a2_base/... |
9b99dcb0e7405e3e888ec84e66dd2785f88582188b510fd53ad5f81d023a0874 | Python | 1,154 | 33 | import argparse
import logging
from ray._private.ray_constants import LOGGER_FORMAT, LOGGER_LEVEL
from ray._private.ray_logging import setup_logger
from ray._private.runtime_env.context import RuntimeEnvContext
from ray.core.generated.common_pb2 import Language
logger = logging.getLogger(__name__)
parser = argparse.... |
c557a8a1a033d974e61d99d9206722c9bd22a2001fd5edbe378749d3ee81b5bf | Python | 1,154 | 40 | from setuptools import find_packages, setup
# read the contents of README file
from os import path
from io import open # for Python 2 and 3 compatibility
# get __version__ from _version.py
ver_file = path.join('txgnn', 'version.py')
with open(ver_file) as f:
exec(f.read())
this_directory = path.abspath(path.dir... |
95601690edf62f634de7f807eabc7dbfaf30b9836def08145fcc1faa82199596 | Python | 1,155 | 49 | from __future__ import annotations
from typing import TYPE_CHECKING, overload
import numpy as np
from ._compat import DaskArray
if TYPE_CHECKING:
from numpy.typing import ArrayLike
from ._compat import ZappyArray
@overload
def materialize_as_ndarray(a: ArrayLike) -> np.ndarray: ...
@overload
def materi... |
9da86037a2b166b93e1d6125e43a4f45327e17a04c46126b3c5ffa7eb4a021f5 | Python | 1,155 | 20 | from fr import *
import time,os
from fr2 import nll_add
fn='frboot.json'; B=json.load(open(fn)) if os.path.exists(fn) else []
t=time.time(); N=len(v)
while len(B)<200 and time.time()-t<240:
rng=np.random.default_rng(1000+len(B))
# resample within age x genotype cells to keep the design
idx=np.concatenate([r... |
584bceda68335afb3511cb22b8dc5fb4771f76d44cf15cff6c57ab7e687bae4a | Python | 1,156 | 20 | """SecAct secreted-protein activity and cell-cell communication (Ru et al., Nat Methods 2026).
A NumPy re-implementation of the R package ``SecAct`` (GPL-3) and of its Python
port ``SecActpy`` (MIT): ridge regression of expression changes on the SecAct
signature matrix with a SecAct-identical permutation null, plus th... |
94b8a74713810bad659e77d71bf6fc43d1e49e544911044276794ca7d5bd8322 | Python | 1,156 | 41 | _base_ = [
'./base_detector/retinanet_r50_ufpn_1x_urpc-coco.py',
'./base_ehance_head/enhance_head.py'
]
# model settings
model = dict(
_delete_=True,
type='lqit.DetectorWithEnhanceHead',
detector={{_base_.model}},
enhance_head={{_base_.enhance_head}},
vis_enhance=False)
# dataset settings
... |
18485e10adb6b11e74be839a6a4ca0e1633c65a1821e2be4abf902d4843bbd5d | Python | 1,157 | 39 | import tempfile
from typing import Optional
import click
from ci.ray_ci.automation.pypi_lib import upload_wheels_to_pypi
from ci.ray_ci.automation.ray_wheels_lib import (
add_build_tag_to_wheels,
download_ray_wheels_from_s3,
)
@click.command()
@click.option("--ray_version", required=True, type=str)
@click.o... |
d53a5c70bfc1bd78e2b5c36189a869fe544e902a50155b7b77b27d3c7e59cf02 | Python | 1,157 | 41 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
Sanitize two filter columns stripped from paired VCFs
"""
import argparse
def main():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('file... |
3012c164ef02427eecccddf65aebd167f6b0244c97ed29d4fd6c898bc845fa53 | Python | 1,158 | 44 | from typing import Any, Callable
from data_profiling.report.presentation.core.container import Container
from data_profiling.report.presentation.core.item_renderer import ItemRenderer
from data_profiling.report.presentation.core.renderable import Renderable
class Dropdown(ItemRenderer):
def __init__(
sel... |
393ba41ebf6217e6b6cadb235d59e0601b8dc9e924bcdcf54a131a4cc95ab6cc | Python | 1,158 | 32 | import nibabel as nib
from matplotlib import pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
from scipy.stats import norm
from os import path
def plot_t_value_hist(
img_path='~/ni_data/ofM.dr/l1/as_composite/sub-5703/ses-ofM/sub-5703_ses-ofM_task-EPI_CBV_chr_longSOA_tstat.nii.gz',
roi_path='~/ni_data... |
4f21cf6f6bdcaffc9b0ac3636204a885b0f4427e767767ab5742a8d6257bc44c | Python | 1,158 | 31 | #!/usr/bin/env python3
import json
import pandas as pd
from pathlib import Path
with Path('test_data/expected_results.tsv').open('r') as expected_tsv,\
Path('test_data/expected_results.json').open('w') as out_json:
expected_table = pd.read_csv(expected_tsv, header=[0, 1], sep='\t')
final_array = []
... |
00b1f682fe21f005381acb2321ec8e30c282b8258f48ad7eb17ef45892a81410 | Python | 1,160 | 25 | '''
An implementation of Mutation-Based Evolving Artificial Neural Network.
Copyright (c) 2022 Motoaki Hiraga
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including withou... |
70c098c778ba41c33138e01ec5a5261cd9a3ee875510e0343e894ee868552004 | Python | 1,160 | 39 | """
Generation of sequences using mono-nucleotide of input sequences.
Module allowing the generation of sequences by using a mono-nucleotide.
shuffling of the given sequences.
"""
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
from utils import GC
import random
def... |
9220026db74acbf487c95e465a7c19df3969646ff7a5bd0ace699fe44216b38e | Python | 1,160 | 58 | from spinnaker2 import snn, hardware
neuron_params = {
"threshold":1.,
"alpha_decay":0.9,
"i_offset":0.0,
}
stim = snn.Population(
size=1,
neuron_model="spike_list",
params={0:[1,3,5]},
name="stim")
pop1 = snn.Population(
size=2,
neuron... |
f5a3ff84e788cccb82cce0cd6d381d245c4dabb914c2e3d6e28631a9e4125c4c | Python | 1,160 | 42 | """
Functions for parsers.
"""
import argparse
import os.path as op
def check_tedpca_value(string, is_parser=True):
"""
Check if argument is a float in range (0,1),
an int greater than 1 or one of a list of strings.
"""
valid_options = ("mdl", "aic", "kic", "kundu", "kundu-stabilize")
if strin... |
a6586b3f65d0ddc96da4a1fd340b1677dba143fad6f9529f4bbf4ad012f413d7 | Python | 1,161 | 43 | # -*- coding: utf-8 -*-
"""
"""
import os
try:
from vtkplotlib import _vtk as vtk
from vtkmodules.util import numpy_support
from vtkmodules import vtkRenderingGL2PSOpenGL2
except ImportError:
if os.environ.get("FORCE_VTKMODULES"):
raise
import vtk
from vtk.util import numpy_support
if... |
b4b2a27e8fa1caf33185e03d73c224310d143bafc237518ecda3fc6d7cc5ecba | Python | 1,161 | 26 | import pandas as pd
import scanpy as sc
from anndata import AnnData
from sklearn.cluster import KMeans
def construct_spatial_blocks(adata: AnnData,
n_blocks: int,
use_graph: bool = False,
graph_adjacency: str = 'spatial_connectiviti... |
dea17703e9dd00f11978acbc44e789b16c48a22764b564371f5e0014ba2834ae | Python | 1,161 | 41 | # 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, ... |
280dc76855736a25ea7caeef8b0a46b7ae4ad6540f2beb6457645fcb014be18e | Python | 1,163 | 50 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
"""
import argparse
import pandas as pd
def explode(df, idx_cols, list_col):
"""
Explode a column of lists into one row per list element
"""
df = df.set_index(idx_cols)
df[list_col] = df[list_col].str.split(',')
df = df[list_col].apply(pd... |
436c38c7c38915fded61eb94cf965daf0eb46606bc89c3b2705922672a311b9c | Python | 1,163 | 16 | from agent.data.entities.config import TRAIN_ITEM_FILTER, DEV_ITEM_FILTER, TRAIN_LABEL, DEV_LABEL
from agent.classifiers.data.count_features_fd_dataset_mgmt import get_datasets_from_filter, get_raw_datasets_from_filter
from agent.classifiers.data.count_features_fd_dataset_mgmt import get_raw_dataframes_from_filter
def... |
a2e1a25f0cabb4013741cfb605bcdd1377f1f646cc20ad24ee9c730372610f94 | Python | 1,163 | 24 | ##########################from .samples_distribution_ops import *
##########################################################################
# 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... |
d3131a81ff64701349e6ff506673127a6fb35f838823a3e5b0e683bb7c3d69d0 | Python | 1,163 | 23 | import os
def main():
for threshold in range(2, 101):
output_dir=f'/ccb/cybertron/khchao/splam-analysis-results/train/results/Negs/Neg_{threshold}/BAM_junctions/'
input_files = [f'{output_dir}neg_hits.bed', f'{output_dir}pos_hits.bed']
ofile = f'{output_dir}junctions_{threshold}_cleaned.bed'... |
f55a83f96e64562609113dce6eafa4914320a0737ad4ed2c036ad4d4faabe900 | Python | 1,163 | 38 | import pathlib
path = pathlib.Path.cwd()
if path.stem == 'tmb_survival':
cwd = path
else:
cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')]
import sys
sys.path.append(str(cwd))
from model import utils
from matplotlib import pyplot as plt
from lifelines import KaplanMeierFitter
from figure... |
849c730fd088208aa1f6cb36a127b1d5205aa169563171e3a3f271f75157f920 | Python | 1,164 | 41 | # Generated by Django 5.2.16 on 2026-10-13 08:44
from django.db import migrations, models
import cvat.apps.engine.models
def rename_consensus_replica_jobs(apps, schema_editor):
Job = apps.get_model("engine", "Job")
Job.objects.filter(type="consensus_replica").update(type="replica")
def restore_consensus_... |
d273819071e2981338d96b31c5ce4aa8db03f7d3f4d93389f70687a6e0d41b26 | Python | 1,164 | 36 | import os
from setuptools import setup
from pathlib import Path
import torch.cuda
from torch.utils.cpp_extension import CppExtension, CUDAExtension, BuildExtension
from torch.utils.cpp_extension import CUDA_HOME
extensions_dir = Path(os.getenv('TUNING_SOURCE_DIR')).absolute()
assert extensions_dir.exists()
source_fi... |
f9fbb5973571cd9cbbca749c5c702f18edcf66a4123ef6a9f0483b23f75af4d3 | Python | 1,164 | 38 | # -*- coding: utf-8 -*-
"""
Project: Psychophysics_exps
Creator: Miao
Create time: 2020-12-19 21:32
IDE: PyCharm
Introduction:
"""
import os
import pandas as pd
def __get_dataframe_file(data_path: str, filetype: str, filename: str) -> pd.DataFrame:
if filetype == ".csv":
df = pd.read_csv(data_path + file... |
3829c4f3135550581e4ed7ad39db7b0536bee252b5359a6ba5289fd51377864e | Python | 1,165 | 29 | import os
import numpy as np
import ivim
# sIVIM (3 b-values)
bvals = [0,200,800,200,0,200] # based on optimization
fname = os.path.join('protocol','dti_vectors_input_sIVIM3b.txt')
ivim.io.philips.generate_dti_vectors_input(bvals,fname,dualpol=True)
# Philips does not accept non-unique rows, fixed by slightly altering... |
606b178116ea9f746b4805eba44ea702dbb687fec0e2ad58de80211aa67ef904 | Python | 1,165 | 40 | # 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-... |
b356943f1f05e6d146dadc990ebccf5ca5f0574731c73fe2ab8e88a12b4a528a | Python | 1,165 | 61 | # pylint: disable=unnecessary-pass
class ImgNotFound(ValueError):
"""Raised when the input image is not found or cannot be loaded."""
pass
class PathNotFound(ValueError):
"""Raised when the input path is not found."""
pass
class FaceNotDetected(ValueError):
"""Raised when no face is detected... |
033ac841b22548fa223e0b9e0b85e444635278da14e55f41ee6b576ead0ace4f | Python | 1,166 | 41 | import torch.autograd
class Quantize(torch.autograd.Function):
"""PyTorch-compatible function that applies a floor() operation on the input, while providing a
surrogate gradient (equivalent to that of a linear function) in the backward pass.
"""
@staticmethod
def forward(ctx, inp):
""""""... |
3d9581f1a644cc4c6d85a3c184580e80eff2af0b5ebb6bd21fe72720b37566af | Python | 1,166 | 35 | #Year model
from torch.nn import Module
from torch.nn import functional as F
from torch import nn
import torch
import torchmetrics
from src.models import Hang2020
class learned_ensemble(Module):
def __init__(self, years, classes, config):
super().__init__()
self.year_models = nn.ModuleList... |
b7e9398b7b0029c8c93ff6a887abd23cad0a71af316975a01e8b32b0e6d580a2 | Python | 1,166 | 22 | ####################################################################################################
# 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 library is fre... |
f5f4bf8b11d927fd5ed4f391a7b80d4e6113a0d0003d838ca512200900741f19 | Python | 1,167 | 42 | #!/bin/python
#------------------- Description & Notes --------------------#
#------------------- Dependencies ---------------------------#
# Standard imports
# Third-party imports
# Internal imports
from .kmercounts import toProbabilities
from .kmercounts import toNormalised
from .kmercounts import toL2Normalised... |
706864d42a9825242376d0ddedb9c15b184cc3246ec74ec4334d0ac477155964 | Python | 1,169 | 58 | from spinnaker2 import snn, hardware
neuron_params = {
"threshold":60.,
"alpha_decay":0.9,
"i_offset":0.0,
}
stim = snn.Population(
size=1,
neuron_model="spike_list",
params={0:[1,20,26]},
name="stim")
pop1 = snn.Population(
size=2,
neur... |
187da9768f1c1e96035ed27e38c1c8c7a439f09a3f6dae3f0be68bc5ac44b3bc | Python | 1,170 | 35 | import os
import glob
import torch
import argparse
from create_input import CreateInput
from inference import InVivoInference
if torch.cuda.is_available():
device = torch.device("cuda")
else:
device = torch.device("cpu")
parser = argparse.ArgumentParser()
parser.add_argument("--input_path", type=str)
parser.a... |
2a7d5845fe24dc7de0e63d9ad0f3f4a1ea696ef51f94501989faf06ed86364ff | Python | 1,170 | 29 | import pytest
from data_profiling.utils.dataframe import sort_column_names
@pytest.fixture()
def input_variables():
return {"var1": None, "Boolean": None, "Python": None, "#0": None}
@pytest.mark.parametrize("sort", [None])
def test_none(sort, input_variables):
expected_variables = {"var1": None, "Boolean"... |
4ab6aaeadd978aae2fc0b6103384bcc9a494ec5216aadea118be4a9daa9ee851 | Python | 1,170 | 38 | import argparse
import glob
import itertools
_sweeps = {}
def add_sweep(fn):
"""Decorate a function to add it as a sweep config."""
global _sweeps
_sweeps[fn.__name__] = fn
@add_sweep
def dino():
"""Compute features using the DINO model."""
def log_exists(video, model, patchsize):
fnames =... |
66f8e9ac4019ef48b2602f6d340540c33b8d83b9512eda59c0c35f365ec63725 | Python | 1,170 | 35 | import logging
from datetime import datetime
from agent.nlp.graph_mgmt import build_items_graph, build_sentences_graph, get_valid_groups
from agent.nlp.metamap_mgmt import read_sem_groups_to_list
from agent.data.entities.config import ROOT_LOGGER_ID
logging.basicConfig(format='%(levelname)s : %(message)s', level=lo... |
e1be0fe98b895859024577a3fe11a01357ef982013e48c975c46916912c018ff | Python | 1,170 | 30 | import torch
from ..utils import common_functions as c_f
from ..losses.mixins import WeightRegularizerMixin
from ..losses.nca_loss import NCALoss
class ProxyNCALoss(WeightRegularizerMixin, NCALoss):
def __init__(self, num_classes, embedding_size, **kwargs):
super().__init__(**kwargs)
self.proxies... |
95ad722c637fca97779450959506eb20e52c4639b567cea75c58a16b50c1fd6e | Python | 1,171 | 37 | #!/usr/bin/env python
#!/usr/bin/env python
import tensorflow as tf
import tflearn
import speech_data
learning_rate = 0.0001
training_iters = 300000 # steps
batch_size = 64
width = 20 # mfcc features
height = 80 # (max) length of utterance
classes = 10 # digits
batch = word_batch = speech_data.mfcc_batch_genera... |
5451b640883e3241d7b9d0bc763aa8d9d6375b4bf0b8f6fbc2a119894046bfbb | Python | 1,172 | 31 | from itertools import product
import pytest
periodic_exp_args = product((0.5, 1, 2), (0.5, 1, 2), (0.5, 1, 2))
@pytest.mark.parametrize("grad_width,grad_scale,spike_threshold", periodic_exp_args)
def test_periodic_exponential(grad_width, grad_scale, spike_threshold):
import torch
from sinabs.activation imp... |
8253eca8b0215fc13b226a1000cfc3489d48145fdd404dd327b37ddd23b45b1a | Python | 1,172 | 29 | class AbstractMixin:
"""
This class implements an interface which handles non processed arguments.
Subclass all classes which mixin additional methods and attributes
to existing classes with multiple inheritance from this class as backup
for handling additional arguments.
"""
def __init__(s... |
992ae7fd443fcce54d53c843070cfa44632e6baac9c3e448ca92e3f864da650a | Python | 1,172 | 43 | __all__ = [
'tetramesh',
'MeshLoss'
]
import numpy as np
import torch
from numpy.typing import NDArray
def tetramesh(xs : NDArray[np.float32], n : NDArray[np.float32]) -> NDArray[np.float32]:
vertices = np.array([
[0, 0, 0],
[0, 1, 0],
[1, 0, 0],
[1, 1, 0],
[0, 0, 1... |
44e3e092217e59917e651ca8be46e662aa0bb781146175b430b00bee90d898f7 | Python | 1,173 | 36 | import pathlib
path = pathlib.Path.cwd()
if path.stem == 'tmb_survival':
cwd = path
else:
cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')]
import sys
sys.path.append(str(cwd))
from model import utils
from matplotlib import pyplot as plt
from lifelines import KaplanMeierFitter
from figures.sim_to... |
014b17809a881cbe607252541176bfa0988cf6af6c18280885147742978dab9a | Python | 1,174 | 31 | # 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... |
3c2ce78118d0303ad100a25fe99c93c892dc361f14e85f7f6c278315eb6c8e85 | Python | 1,174 | 33 | ################################################################################
# Module allowing the generation of sequences by using a di-nucleotide
# shuffling of the given sequences
################################################################################
from altschulEriksonDinuclShuffle import dinuclShuf... |
52632132871e08c3561c696be4a61abdd50cdf97051f09efc23a9cc67be350ee | Python | 1,174 | 35 | """
Provides a functional interface for transforms
(usually working on single tensors rather then collections thereof).
All transformations are implemented to work on batched tensors.
Implementations include:
* Affine Transforms
* Channel Transforms
* Cropping Transforms
* Device Transforms
* Intensity Transforms
* Sp... |
91db44dfcaa54191082fb4b9a3581eda27d52e88bdaf5ce567b86a3f32c9e310 | Python | 1,174 | 39 |
from lisa.core.io import parse_bedfile
from lisa.core.data_interface import DataInterface
from lisa.core.genome_tools import Region, BadRegionError
import argparse
def main(species, window_size, path):
region_fields = parse_bedfile(path, header = False)
regions = [Region(*r) for r in region_fields]
gen... |
06aa839c8faa96e7daf5b41262000930f61ef58286f81bce3c0cee14d48289dc | Python | 1,176 | 42 | # %% compress feather file further.
import pandas as pd
# read the file.
df = pd.read_feather("figure_data/df_gen5.feather")
# save with more agressive compression.
df.to_feather("figure_data/df_gen5.feather")
# even more
df.to_feather(
"figure_data/df_gen5_stronger.feather", compression="zstd", compression_leve... |
433f4847bac41d500e082757e33cc19c96084e8d5f789324c5f556c0fb64bf29 | Python | 1,176 | 54 | # -*- 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 10: plotting of presets.
Plot the step response of different preset devices and preset configurations.
"""
# pylint: disable=invalid-name
im... |
af3e9141d2106a2402ecf81d8c51ed9ff809da0304b205ff1b7842c97a474511 | Python | 1,176 | 45 | import multiprocessing
import os
import numpy as np
import pandas as pd
def create_directory(directory_path):
"""
Create a directory if path doesn't exists
:param directory_path:
:return:
"""
if os.path.exists(directory_path):
return None
else:
try:
os.makedirs(... |
c2d05da63ab80c0c5d26a996dac6f6a7da7bc9e42ab5512e283ce336c5704eea | Python | 1,176 | 47 |
import scanpy as sc
import pandas as pd
from anndata import AnnData
import warnings
from builtins import int
warnings.filterwarnings('ignore')
from . import losses, miners, distances, reducers, testers
from .utils.transformations import *
from .utils.accuracy_calculator import AccuracyCalculator
import torch
import to... |
859bc867abd1dfaa5b001c803f280e99dd57a064f9455bbe27751ae129f1739e | Python | 1,177 | 42 | import pytest
import torch
from torch import nn
from sinabs.utils import normalize_weights
# init model
CNN = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=(3, 3), bias=False),
nn.BatchNorm2d(16, affine=True),
nn.ReLU(),
nn.AvgPool2d(kernel_size=2),
nn.Conv2d(16, 8, kernel_size=(3, 3), bias=True),
... |
8735e6160d2c75d00ceb689bd8d0cdeee110529e7bb5426d51920ab44251a679 | Python | 1,177 | 40 | # __basic_example_begin__
from ray import serve
from ray.serve.config import AutoscalingConfig, AutoscalingPolicy
from ray.serve.schema import CeleryAdapterConfig, TaskProcessorConfig
from ray.serve.task_consumer import task_consumer, task_handler
processor_config = TaskProcessorConfig(
queue_name="my_queue",
... |
a30ed355df4e21b7687df59f185a5d0d65f550159589987dd3afd0b44e1f6db1 | Python | 1,177 | 41 | import matplotlib
matplotlib.use("Agg")
import mozaik
from mozaik.tools.distribution_parametrization import load_parameters
import os
from collections import OrderedDict
import pytest
class TestParametrization:
"""
Tests for the TestParametrization class
"""
def setup_class(cls):
os.chdir("t... |
a9abc16a122dd673ca13598cfe234f761ec941f59dfde252ca2f98cfa760b33a | Python | 1,177 | 28 | """
``rising.loading`` provides an alternative :class:`DataLoader` that extends
:class:`torch.utils.data.DataLoader` by the following:
* Seeding of Numpy in each worker process: The seed is generated by numpy in
the main process before starting the workers. For reproducibility numpy must
be seeded in the main proc... |
4f94647cbb28762a0760e5aa809c478859b1f8c41e4a550977b448c32fba0115 | Python | 1,178 | 27 | def extract_co(df, gencode, num):
chrom = df.loc[df["transcript_id"] == transcript,"seqname"].values[0]
dat = gencode.loc[gencode["updated_exon_number"] == num,]
dat["diff"] = abs(dat["start"] - dat["end"])
start = dat[dat['diff']==dat['diff'].max()]["start"].values[0]
end = dat[dat['diff']==dat['di... |
8a9745abb010c01ccb87f94762c8a1bb78867cdc4b6d449d9d2f3eef8a05bf9d | Python | 1,178 | 39 | import unittest
from neuron_morphology.morphology_builder import MorphologyBuilder
from neuron_morphology.feature_extractor.feature_extractor import FeatureExtractor
from neuron_morphology.feature_extractor.data import Data
from neuron_morphology.feature_extractor.marked_feature import (
specialize
)
from neuron_m... |
fb9e0dbbb2e6452721fd38d9545a1c6fafcf84750c59e73e9ef074bab12b34fb | Python | 1,178 | 31 | 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... |
90e124670108d6f03063f7b081153fe3b97ca0079d8e3d048604e66b72990f87 | Python | 1,179 | 47 | """
Test for issue 824:
https://github.com/Data-Centric-AI-Community/data-profiling/issues/824
High correlation warning printed multiple times
Problem :
The alert is probably generated for each active correlation calculation
Solution :
Field will be marked once is labelled as highly correlated for any calculation
""... |
ca64da94e190b22364866f2bf83443bec05aec0cb04a623ab4ccc475d4a0cb60 | Python | 1,179 | 36 | import sys
sys.path.insert(0, "/srv/home/zgaleday/torch_pgn")
from torch_pgn.datasets.OneVsManyDataset import OneVsManyDataset
from torch_pgn.datasets.ManyVsManyDataset import ManyVsManyDataset
from torch_pgn.datasets.FPDataset import FPDataset
from torch_pgn.data.data_utils import format_data_directory
from torch_pgn... |
18b8db165a85b285a68640d0591c8aeab3b6bdf81d1762de4e732523a95a988a | Python | 1,180 | 48 | '''
Upsample images. Assumes that a registration mask is generated based on first
session.
'''
import os
import subprocess
import glob
DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti'
UPFACT = 4
SUBS = ['sub-07']
for sub in SUBS:
# ====================================================... |
b4c761a0ee479be00bd5c130951034d1904545bef3dd8a5d827bf98b6e6dec5a | Python | 1,180 | 32 | # -*- 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.
#... |
0e302370e9f299410c5d1f6eeefae93b026f314929b87b21a62159cd768681ab | Python | 1,182 | 41 | import pickle
import os
import argparse
import swap_errors.analysis as swan
def create_parser():
parser = argparse.ArgumentParser(description="fit several autoencoders")
parser.add_argument(
"data_file",
type=str,
)
parser.add_argument(
"-o",
"--output_folder",
... |
2e484137366d8d207566d6e816f6e8e23ff34f601d385caf58dfb5c9ec35920c | Python | 1,182 | 36 | import os
import argparse
import numpy as np
from spiking_readout.dataset import SpikingDataset
"""Convert NumPy dataset to SpikingDataset object"""
def generate_dataset(data_path, label_path, output_path, rm_input=True):
# Load the input
X = np.load(data_path)
y = np.load(label_path)
assert X.shape[... |
e70ac94a6d39b656e4b031319a8ced809237837ec676aefaa24ce9dbe515e7a6 | Python | 1,182 | 53 | """
Example for LIF neuron with exponentially decaying current input
"""
from spinnaker2 import snn, hardware
params = {
"threshold":10.,
"alpha_decay":0.9,
"i_offset":0.0,
"v_reset":-0.2,
"reset":"reset_to_v_reset",
"exc_decay":0.5,
"inh_decay":0.2,
"t_... |
1123d0f8c09dad0fab897ae935ac29ab01a10d9433d1202845b8508d343f29e6 | Python | 1,183 | 35 | # Trigger pytest hook to automatically zip test cluster logs to archive dir on failure
import copy
import os
import pytest
import ray
from ray.tests.conftest import (
_isolate_token_auth_state, # noqa: F401
_restore_token_auth_env, # noqa: F401
_token_auth_env_baseline, # noqa: F401
pytest_runtest_... |
a09d2781d9135a1c45bab9e0abe8d0deeb6d6b2af208cf4bbb8e84fae1350f3f | Python | 1,184 | 32 | import tensorflow as tf
# from tensorflow.keras import layers, models, regularizers
from projectmetis.python.models.model_def import ModelDef
class IMDB_LSTM(ModelDef):
def __init__(self, learning_rate=0.01, max_features=25000):
super(IMDB_LSTM, self).__init__()
self.learning_rate = learning_rat... |
f66bc638fc1f0c5c9b708a17ed92cc2e44ceae0e82e822538cc6a314ad6dc39e | Python | 1,185 | 37 | from enum import Enum
from src.models.trainer import *
from src.models.resnet import *
def get_trainer(task:str) -> Trainer:
if task == "classification":
return ClassificationTrainer
elif task == "binary":
return BinaryClassificationTrainer
elif task == "ordinal":
return OrdinalR... |
1a5732ecdd3ffb688e28ae4bc8723feec18c5d9ba398fb089a3b00273282d95b | Python | 1,186 | 39 | """
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 os.path
import pandas as pd
import pytest
from ase.db import connect
from tests.core.testing_u... |
7f6643d630844afe48d4c79a18909f604ee28f66632b1ca5b266219ebdbd4bba | Python | 1,186 | 24 | ####################################################################################################
# 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... |
83382610966e3cbb678b7a139a210f3d851fc6d2b10bb79be184a72611a5d9a0 | Python | 1,186 | 26 | import exputils.data
import exputils.gui
import exputils.io
import exputils.manage
import exputils.misc
from exputils.misc.attrdict import AttrDict
from exputils.misc.attrdict import AutoAttrDict
from exputils.misc.attrdict import DefaultAttrDict
from exputils.misc.attrdict import DefaultFactoryAttrDict
from exputils.... |
0394e3690ce9ad0d7e629e0e005110ed572356166f6d2fa09f16ac92efbf37b2 | Python | 1,187 | 42 | from Load_prediction import ddpred
from Para import parameter
import numpy as np
trainday = 30+30
zones = 'Single'
modes='Cooling'
par = parameter()
par.para_load(zone=zones)
ddp = ddpred()
adj = np.array([[1]]).astype('float32')
ddp.data_ready(num_zone=1,
enLen=par.paradic["encoLen"],
... |
1083991e9f7ee8b462b7891df245aaf489a94530aee34c4cb7c30a4b4f173a1e | Python | 1,188 | 25 | ####################################################################################################
# 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... |
6a4ec0fb8b0245eafd5538a800a60a246ae6453fe4b7d833b1908c4e0e132e10 | Python | 1,188 | 48 | import sys
import unittest
import numpy as np
try:
import dolfinx
from neuron_morphology.transforms import streamline as sl
has_dolfinx = True
except ImportError:
has_dolfinx = False
@unittest.skipIf(
not has_dolfinx, "streamline calculation requires conda-installed fenics-dolfinx"
)
class Tes... |
97c77b18c459ada1638cd67d2c84ee85f97cd1aa9e1f2c79881fcb9690874452 | Python | 1,188 | 38 | # %% Demo of model run
import SSN_model_funcs as ssn
import support_funcs as sf
import pandas as pd
# stimulus is a 1D array with arbitrary length.
# In this program, the length of the stimulus determines the length of the simulation.
stimulus = ssn.load_predefined_stimulus("G")
print(f"stimulus length is {len(stimul... |
c4680e8c87150ed4c4747ba74108d9d4d3be8b31744b4720f5212b24a325853f | Python | 1,188 | 40 | # -*- 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.
#... |
5395884ab0996bc0c80dd65af96771b92479cd2cf6a617d9411c84c1300b96f3 | Python | 1,191 | 28 | import SimpleITK as sitk
import os
import glob
from config import STANFORD_DATA_DIR
def convert_stanford_pngs_to_nifti(stanford_dir_path: str = STANFORD_DATA_DIR):
base_split_dir = os.path.join(stanford_dir_path, 'stanford_release_brainmask', 'mets_stanford_releaseMask_train')
all_dirs = glob.glob(base_split_d... |
7dec9cb057eca28a8aa3976f3edb1c70bb682ec141f8867d1c9efc5c64a7460d | Python | 1,191 | 35 | import numpy as np
import matplotlib.pyplot as plt
plt.rc('font',size=15)
TestLength=300
L=50
Actual=np.load('actualTrajectory.npy')
predict=np.load('avgTrajectory.npy')
total=np.load('totalTrajectory.npy')
actual=np.zeros((1,TestLength))
actual[0,:]=Actual[0,:TestLength]
# print(np.shape(actual))
# print(... |
6360692d4af11c339e677eb7dafe9e3bb9dfce6c008a25c48835817eaf730cae | Python | 1,192 | 42 | """
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 logging
from torch.utils.data import DataLoader, Dataset
from fairchem.core.common import dist... |
a13dd22a5e74cfcdd532b949089b0b6e76ccf5f8dc30939a287b95342081e810 | Python | 1,192 | 39 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 23 18:14:11 2018
@author: yjwu
"""
from __future__ import print_function
import torch.utils.data as data
import torch
import numpy as np
import scipy.io as sio
import h5py
class MyDataset(data.Dataset):
def __init__(self, path='load_test.mat',method = 'h',wins = 12)... |
570363a3f90e76c7c2af3e06e73ae26b9e803c673e80e346bd2afb12312da571 | Python | 1,194 | 33 | """
A helper script for evaluating performance of changes to the tabular explainer, in this case different
implementations and methods for distance calculation.
"""
import time
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from lime.lime_tabular import LimeTabular... |
600ee99aa1183415f37ed8c26954906f579e16e2e7156d933469bd80e241f448 | Python | 1,194 | 52 | import numpy as np
import networkx as nx
import os.path
import matplotlib.pyplot as plt
import time
import math
import gc
gc.collect()
import warnings
warnings.filterwarnings('ignore')
import os
os.system('cls' if os.name == 'nt' else 'clear')
plt.rc('font',size=15)
#Libraries for SINDY 2021, relevant fi... |
44923513aa475f754176b6de1cda5cfe39be5dc86c72486cf0d26861f53af683 | Python | 1,195 | 47 | """
test for setting individual parameters for the LIF neuron
"""
import os
import numpy as np
from spinnaker2 import hardware, snn
rng = np.random.default_rng()
def test_lif_neuron_individual_params():
n_neurons = 300 # larger than max neurons per core
params = {
"threshold": rng.uniform(0.8, 1.2,... |
c7f0698c075c82dc11f33f0a4e1e1af3fd39e7e70d879004b5bfa08fb0953258 | Python | 1,195 | 35 | import logging
import numpy as np
from torch.utils.data import Dataset
logger = logging.getLogger(__name__)
class BaseDataset(Dataset):
def make_split_indices(self, train_size, valid_size, recon_size):
nmol = len(self)
assert train_size + valid_size == nmol
perm = np.random.permutation(n... |
a88ad6efc4a45a00b0032bcbc8feaebb7dcb5e542eb653b8dc6531f13fcb7041 | Python | 1,196 | 44 | from Load_prediction import ddpred
from Para import parameter
import numpy as np
trainday = 30+30
zones = 'Single'
modes='Cooling'
par = parameter()
par.para_load(zone=zones)
ddp = ddpred()
adj = np.array([[1]]).astype('float32')
ddp.data_ready(num_zone=1,
enLen=par.paradic["encoLen"],
... |
e40623bc3e58ad1f10d9eb8f3b0e29222a37597672d0d5b37797c35a63c4eb9e | Python | 1,196 | 42 | # flake8: noqa
# __streaming_example_start__
# File name: stream.py
from typing import AsyncGenerator, Generator
from ray import serve
from ray.serve.handle import DeploymentHandle, DeploymentResponseGenerator
@serve.deployment
class Streamer:
def __call__(self, limit: int) -> Generator[int, None, None]:
... |
eb1d94ebe27a283429fe40c95b22a9941a9386cc55be2dec0e4ff664f81e5c6a | Python | 1,196 | 48 | """
Test for issue 169:
https://github.com/Data-Centric-AI-Community/data-profiling/issues/169
"""
from io import StringIO
import pandas as pd
import pytest
from data_profiling import ProfileReport
@pytest.fixture
def issue_169_data() -> StringIO:
data = StringIO(
"""index,company-code,company,shop-code... |
71c6a6368d0ce162078b9691dd034c21714d06e4b46d2dad0718aec309c37e1a | Python | 1,197 | 32 | import nibabel as nib
from lib.qc_surface import compute_qc
from lib.utils import setup_logger
log_file = snakemake.log[0] if snakemake.log else None
logger = setup_logger(log_file)
# an intermediate stage (e.g. the isosurface before repair) has only the
# midthickness, and no coords to check the unfolded mapping
sur... |
7b5527df568ae5369d24f6fc726262a8375f824382742855f651667b1abaf45b | Python | 1,197 | 24 | import argparse
import torch
def parse_args():
parser = argparse.ArgumentParser()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
parser.add_argument('--device', type=str, default=device)
parser.add_argument('--path', type=str,
default='C:\\Users\\3... |
86b1a6a96eaa7ef33ec2127ce99740c98602e425d00b86a648ebf8e6ae9ec81d | Python | 1,198 | 34 | import torch
from Config import class_number
SEED = 1234
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
import DataSet
import torch.nn as nn
class TextRNN(nn.Module):
def __init__(self):
super(TextRNN, self).__init__()
Vocab = len(DataSet.getTEXT().vocab) ## 已知词的数量
Dim... |
c6286df4e251ba4b7cc8b371ab2ca6132a127417b180027384ba4aed12ed25cf | Python | 1,198 | 42 | from typing import TYPE_CHECKING, Iterator, List
from ray.data._internal.delegating_block_builder import DelegatingBlockBuilder
from ray.data.block import Block
from ray.data.datasource.file_based_datasource import FileBasedDatasource
if TYPE_CHECKING:
import pyarrow
class TextDatasource(FileBasedDatasource):
... |
f994287d9091ba29d855ef2303b14ff2a66f10f300101c7e2aca3e9c012826a1 | Python | 1,198 | 45 | import pytest
import torch.nn as nn
from sinabs.backend.dynapcnn import DynapcnnNetwork
from sinabs.from_torch import from_model
from tests.hw_utils import find_open_devices
ann = nn.Sequential(
nn.Conv2d(1, 20, 5, 1, bias=False),
nn.ReLU(),
nn.AvgPool2d(2, 2),
nn.Conv2d(20, 32, 5, 1, bias=False),
... |
615a0b52a2f4a05eb6b5a592114543053a978cc89c479bc63f59b6283c32e910 | Python | 1,199 | 40 | from typing import Tuple
import numpy as np
import pandas as pd
from data_profiling.config import Settings
from data_profiling.model.pandas.imbalance_pandas import column_imbalance_score
from data_profiling.model.summary_algorithms import describe_boolean_1d, series_hashable
@describe_boolean_1d.register
@series_ha... |
62362c9a29bfc8cb29e2b901027938ea6fc0f47699217df9171a34b2f0544371 | Python | 1,199 | 25 | import argparse
import torch
def parse_args():
parser = argparse.ArgumentParser()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
parser.add_argument('--device', type=str, default=device)
parser.add_argument('--path', type=str,
default='C:\\Users\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.