sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
eeb59b9665b16e63f71fae01dd381abd5fac6f8acbceb48a2bcdd78a344370ff | Python | 775 | 28 | from typing import Tuple
from pyspark.sql import DataFrame
from data_profiling.config import Settings
from data_profiling.model.summary_algorithms import describe_categorical_1d
@describe_categorical_1d.register
def describe_categorical_1d_spark(
config: Settings, df: DataFrame, summary: dict
) -> Tuple[Setting... |
fa4ccbccc3924437936bdc7c0206e0fe5289e000277a27d123c782046810193d | Python | 775 | 33 | import abc
from neuron_morphology.morphology import Morphology
class TransformBase(abc.ABC):
"""
Abstract base class for implementing swc transforms.
Each child class should implement these methods.
"""
@abc.abstractmethod
def transform_morphology(self) -> Morphology:
"""
... |
39925e74bbe0c476ee28a9f946789afd40dcc8365f9ea0907ab2e822f491fd07 | Python | 777 | 38 | # encoding: utf-8
"""
This module provides compatibility between Python 2 and 3. Hardly
anything is used by this project to constitute including `six`_.
.. _`six`: http://pythonhosted.org/six
"""
import sys
if sys.version_info[0] < 3:
# Python 2.
unicode = unicode
string_types = (basestring,)
from collections i... |
83dd654839d44dc8bbaa05d58f93405c5c942f848a695dc8e5720104ec53b120 | Python | 778 | 29 | import pytest
import torch
@pytest.mark.parametrize(
"first_batch_size,second_batch_size", [(2, 5), (5, 7), (2, 11)]
)
def test_batch_size_mismatch(first_batch_size, second_batch_size):
import sinabs
import sinabs.layers as sl
mod = sl.IAFSqueeze(batch_size=first_batch_size)
time_len = 13
f... |
b4a0182c63fad4b0ad367c0bdcb61234bb0de24f040bffbc738d87c265dd7f89 | Python | 779 | 33 | # flake8: noqa
# fmt: off
# __monitor_start__
from typing import List, Dict
from ray import serve
from ray.serve.schema import ServeStatus, ApplicationStatusOverview
@serve.deployment
def get_healthy_apps() -> List[str]:
serve_status: ServeStatus = serve.status()
app_statuses: Dict[str, ApplicationStatusOve... |
0864ea2bfd24d2854e8a86f2cd3e1e0b480ced31227f2de15a3e31b246187391 | Python | 780 | 29 | from gym.spaces import Discrete
from gym.spaces import MultiDiscrete
import numpy as np
def flat_to_nd_space_index(index, space):
nd_index = None
if isinstance(space, Discrete):
nd_index = index
elif isinstance(space, MultiDiscrete):
nd_index = np.unravel_index(index, space.nvec)
retur... |
4cd489347c2116c4c7a4d04917afb07a39d5a89e850fcb723a856f9d65eba103 | Python | 780 | 37 | from __future__ import annotations
from .base import (
BaseBundleQueue,
QueueWithRemoval,
)
from .bundler import (
EstimateBytes,
EstimateSize,
ExactMultipleSize,
PendingBundleState,
RebundleQueue,
)
from .fifo import FIFOBundleQueue
from .hash_link import HashLinkedQueue
from .reordering i... |
2519cc0ce27e9dc18caf8aed9cd60eee5f39ff2dcc5404ea6aec0017caf076c9 | Python | 781 | 33 | # Copyright (c) 2021 Qualcomm Technologies, Inc.
# All Rights Reserved.
"""Util conversion function for the quant library"""
import numpy as np
from numpy.typing import NDArray
from torch import Tensor
def to_numpy(tensor: Tensor) -> NDArray:
"""
Helper function that turns the given tensor into a numpy arra... |
81e1982fee729363653f927ab938cd8ddcfb0bdb26184c8a114d832192bc6fc2 | Python | 782 | 26 | # system_monitor.py
import psutil
import time
from datetime import timedelta
import os
class SystemMonitor:
@staticmethod
def get_system_stats():
process = psutil.Process(os.getpid())
memory = psutil.virtual_memory()
return {
'memory_usage': process.memory_info().rss / 1024... |
fe2de57f5b4ffc6f620a1974977d0ac8475a561c606b3d4d1b7d4d387e455590 | Python | 784 | 28 | #!/usr/bin/env python
import argparse
import sys
from svqc.evaluator import QCEvaluator
def main():
usage = """Detects QC failures"""
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument("metrics_file", help="Table of metrics")
parser.add_argument("criteria_file", help="Table of QC crite... |
626c0265b441c4322dba5d82b4fecb09031c122b77a8022b847b73ce5e760306 | Python | 785 | 32 | # __serve_example_begin__
import asyncio
from ray import serve
from ray.serve.config import AutoscalingConfig, AutoscalingPolicy
@serve.deployment(
autoscaling_config=AutoscalingConfig(
min_replicas=1,
max_replicas=12,
policy=AutoscalingPolicy(
policy_function="autoscaling_pol... |
f684d701ebbbbea83ba3a79fb21c49ddedd54e6ccc7c3ad87822e3d0c661f5a3 | Python | 785 | 18 | # This file is part of the INTREPPPID programme.
# Copyright (c) 2023 Joseph Szymborski.
#
# This programme is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3.
#
# This programme is distributed i... |
7289d0e34e0f349791cdbc6e25936c471445d2960383cb77f9d752c491e8f327 | Python | 786 | 32 | import json
import sys
import pytest
from ray.dashboard.modules.metrics.metrics_head import (
DEFAULT_PROMETHEUS_HEADERS,
parse_prom_headers,
)
@pytest.mark.parametrize(
"headers, raises_error",
[
(DEFAULT_PROMETHEUS_HEADERS, False),
('{"H1": "V1", "H2": "V2"}', False),
('[["... |
04d0204a22a553463808c65c8fbeed0e8fb2c83de8798ecd749b51f41f30ce07 | Python | 787 | 28 | """Attention-based deep multiple instance learning.
An implementation of
arXiv:1802.04712
Ilse, Maximilian, Jakub Tomczak, and Max Welling.
"Attention-based deep multiple instance learning."
International conference on machine learning. PMLR, 2018.
"""
from . import data, helpers, model
from ._mil im... |
4b29a0da7e71e6e0d5f7b2787d21ab02657b31ba3a2c3f7e253519594f9eda0c | Python | 787 | 15 | import core.preprocessing as prep
#%% To process a single session folder
# demo_data_path = r'Z:\\Hansol_Yue\\experiment data\\Etv1_1\\Social_1\\session_2\\'
demo_data_path = 'J:\Hansol_Yue\_specialcase_of_behavior_\Rspo2_noffood'
prep.align_ca_behav_data(demo_data_path,'TEST',use_independent_logger=True)
#%% ... |
184a30b756a88d3e5292fba48d7688c67dac994718498e19c6d611383a5eb071 | Python | 788 | 29 | def transform_color_str_to_tuple(colors):
is_input_list = isinstance(colors, list)
if not is_input_list:
colors = [colors]
out_color = []
for color in colors:
col_elements = color.replace('(', ',').replace(')', ',').split(',')
out_color.append((col_elements[0], int(col_elements... |
a3feee3b4ecc1b0646cba3e82e124e0f0738c2413c11f253beeee65cf29947dd | Python | 788 | 29 | # __sglang_single_node_start__
from ray.llm._internal.serve.engines.sglang import SGLangServer
from ray import serve
from ray.serve.llm import LLMConfig, build_openai_app
llm_config = LLMConfig(
model_loading_config={
"model_id": "Llama-3.1-8B-Instruct",
"model_source": "unsloth/Llama-3.1-8B-Instr... |
83bb1cb6232495e708cced71a8f52820eeafcf7cc23740a309e58afc22070f9f | Python | 789 | 27 | import torch
from torch import nn
class ThresholdFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, inp, tau):
output = torch.where(inp > tau, torch.ones(tau.size()[0]), torch.zeros(tau.size()[0]))
ctx.save_for_backward(inp, torch.tensor(tau))
return output
@staticm... |
51d3e043653c31785bac3c7a81c97f65c0ee0e57d61e9b4cdbf413b900e50eb3 | Python | 790 | 23 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for Bio-Diffusion (https://github.com/BioinfoMachineLearning/bio-diffusion):
# --------------------------------------------------------------------------------... |
01107ca1d1a6e0bc54b28e1eddb132e5c111227c112bf37c44ea814e0404c13f | Python | 791 | 35 | # Configuration file for the Sphinx documentation builder.
# -- Project information
project = "ADRD Tool"
copyright = "2023, Kolachalama's Lab"
author = "Chonghua Xue"
# -- General configuration
extensions = [
'sphinx.ext.duration',
'sphinx.ext.doctest',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary... |
0abdb12f0054278051bfbe2c38fa8bef0b85aa7ef18c4160086e8bccbf28eaa7 | Python | 792 | 29 | __version__ = "0.2.4"
import logging
import sys
logger = logging.getLogger("scGPT")
# check if logger has been initialized
if not logger.hasHandlers() or len(logger.handlers) == 0:
logger.propagate = False
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(loggin... |
20cc442a02374fb219a744fe1c1e7953a3b44fbda70d373c76d98605d5efb728 | Python | 793 | 24 | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ray.data._internal.execution.streaming_executor import StreamingExecutor
class ExecutionCallback:
"""Callback interface for execution events."""
def before_execution_starts(self, executor: "StreamingExecutor"):
"""Called before the Dataset ... |
6d1bcfb6be5ad12d6afcd3938ca7b9d0ae1b734018a6fc5bbe70d37124dd4ed7 | Python | 793 | 32 | import os
import threading
from functools import wraps
import ray
auto_init_lock = threading.Lock()
enable_auto_connect = os.environ.get("RAY_ENABLE_AUTO_CONNECT", "") != "0"
def auto_init_ray():
if enable_auto_connect and not ray.is_initialized():
with auto_init_lock:
if not ray.is_initiali... |
7b0357be43030e35232419d2d1c6dc48ad4d499128f33b3948f05d776e89eef0 | Python | 793 | 30 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('Agg')
from mpi4py import MPI
from mozaik.storage.datastore import Hdf5DataStore, PickledDataStore
from parameters import ParameterSet
from model import SelfSustainedPushPull
from experiments import create_experiments_optogenetic_patterned_stimulation
import moz... |
99d86b7fd218e1a5678bc26d6643b07eeade91a106aafa81221666efd9109bf3 | Python | 793 | 10 | from agent.data.entities.config import TRAIN_ITEM_FILTER, CTT3HEALTH_ITEM_FILTER, TRAIN_LABEL, CTT3HEALTH_LABEL
from agent.classifiers.data.count_features_fd_dataset_mgmt import get_datasets_from_filter, get_raw_datasets_from_filter
def get_datasets(review_level=9, binary_classifier=True, val_split=0.8):
return ge... |
d22a59df00fe42ac2df992a7037e200b2289fe142b3f8731a1346754011608ae | Python | 793 | 26 | SAMPLE_RATE = 20000
NORA_SPIKE_INTERVAL = int(0.150 * SAMPLE_RATE)
ONSET_N_SAMPLES = int(0.1 * SAMPLE_RATE)
OFFSET_N_SAMPLES = int(0.05 * SAMPLE_RATE)
INTERFRAME_TIME = int(0.500 * SAMPLE_RATE)
FLASH_TRAINING_BLOCK_SIZE = 1000
FLASH_TEST_BLOCK_SIZE = 150
N_BLOCKS = 10
NS_BROWNIAN_N_FRAMES_PER_IMAGE = 60
NS_BROWNIAN_... |
3e335a9b88e49109a9e2b3b38eccba88fd89d27ec949395d0fe98c9a0e8b6e3a | Python | 794 | 29 |
from setuptools import find_packages
from distutils.core import setup
setup(
name="optim-sted",
version="0.1",
author="Anthony Bilodeau",
install_requires=[
"bandit-optimization",
"pysted",
"abberior-sted",
"h5py",
"pyyaml",
"metrics @ git+https://github... |
bf15df84ae89ba0fb41fe3a66b2930e2d3e88f75bf9458eb769e5a74c82a6d01 | Python | 797 | 10 | from agent.data.entities.config import TRAIN_ITEM_FILTER, EXTERNAL_ITEM_FILTER, TRAIN_LABEL, EXTERNAL_LABEL
from agent.classifiers.data.count_features_fd_dataset_mgmt import get_datasets_from_filter, get_raw_datasets_from_filter
def get_datasets(review_level=9, binary_classifier=True, val_split=0.8):
return get_da... |
dd1e36c25167afc0feaead4b8722d0e9501933b2f3aec02e2f35cf4d0f325d14 | Python | 797 | 30 | from typing import Dict, Hashable, Literal, Optional, Protocol, Sequence, Union
import numpy as np
import pandas as pd
from scipy.sparse import spmatrix
MatrixLike = Union[np.ndarray, spmatrix]
class AnnDataLayersLike(Protocol):
"""Layer container surface used by AnnData-like inputs."""
def __getitem__(sel... |
574fe1f4af30a90c992567c28c6eb31b907ffc983a439c88ff256f44e0cc176c | Python | 799 | 30 |
from distutils.core import setup, Extension
from Cython.Build import cythonize
from Cython.Compiler import Options
INCLUDE_DIRS = []
try:
import numpy
INCLUDE_DIRS.append(numpy.get_include())
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
ext_modules = [
Extension("pysted.cUtils", ["py... |
c2eb5648102112cbd298e86958bf2398d779f44c5811e0922cd1147f76ffd51a | Python | 799 | 27 | """
Test for issue 915:
https://github.com/ydataai/pandas-profiling/issues/915
Error for series with large integers.
"""
import pandas as pd
from data_profiling import ProfileReport
def test_issue915():
df = pd.DataFrame({"col": pd.Series([716277643516076032 + i for i in range(100)])})
df_profile = ProfileRe... |
1cbf748b7c6e782923f0e3f4e5d72ab0f592e8aa34b1b7faaeaccf4ffae96656 | Python | 800 | 28 | import codecs
from setuptools import find_packages
from setuptools import setup
install_requires = [
'torch>=1.3.0',
'gym>=0.9.7',
'numpy>=1.10.4',
'pillow',
'filelock',
]
test_requires = [
'pytest',
'attrs<19.2.0', # pytest does not run with attrs==19.2.0 (https://github.com/pytest-dev/p... |
868ecb09d5310291bf70b8a7b8095f1d28856d72de2fa3fedb9cd76ee74c0fbc | Python | 800 | 24 | import string
from itertools import cycle
def label_axes(axes, labels=None, loc=None, **kwargs):
"""
Walks through axes and labels each.
kwargs are collected and passed to `annotate`
Parameters
----------
axes : iterable of axes to label
labels : iterable or None
iterable of strings ... |
3d8005345b08f2ebd546a13a05deb26aa80c714c7954466aba4c9c1eab43a2c8 | Python | 801 | 29 | #import matplotlib as mpl
#mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from utils import parseparam, loadbin
import os
import pandas as pd
import matplotlib.colors as mcolors
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap
if __name__ == "__main__":
datadir = "Data/mnist... |
3e20a02bd4f3f9bdd0fcc245208c8645fc2ea6e33ab7ffb56dcc2bbff8b6bc6c | Python | 801 | 33 | from argparse import ArgumentParser
import sys
import numpy as np
if "__main__" == __name__:
ap = ArgumentParser()
ap.add_argument("--test", metavar="FASTA", required=True)
ap.add_argument("--pred", metavar="NPY", required=True)
arg = ap.parse_args()
pred = np.load(arg.pred)
with open(arg.te... |
be66e84599e9d1eb8b4ed18b68b2f7a0c0f937c967a01a0d35dae58791da50b8 | Python | 801 | 24 | import warnings
from mmengine.utils import digit_version
try:
import mmdet
HAS_MMDET = True
except ImportWarning:
HAS_MMDET = False
mmdet_minimum_version = '3.0.0'
mmdet_maximum_version = '3.2.0'
if HAS_MMDET:
mmdet_version = digit_version(mmdet.__version__)
assert (mmdet_version >= digit_version... |
1cfc65a5eff46d1a7dd7a12b0a9e5de3ceac5f0364f25d928a19498b3014d672 | Python | 802 | 41 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
"""
import argparse
import numpy as np
import scipy.stats as ss
def convert_poisson_p(qual):
"""
Convert poisson phred-scaled quality score to count, assuming 0 background
Can't use ss.poisson.ppf because k/mu are flipped in pe/sr test calculation
... |
1d3e576def4a4dc9d1349dbd84304b613dd6da3b9134e62c1bf227cbb5c2d096 | Python | 803 | 28 | import unittest
import torch
from rising.random import AbstractParameter, DiscreteParameter
class TestAbstract(unittest.TestCase):
def test_none(self):
param = DiscreteParameter([None], replacement=True)
res = param((1,))
self.assertIsNone(res)
def test_tensor_like(self):
pa... |
f4d77af45cb61f65d2b75b88849202563ce3c2a6498cb168bbce1c24df4e6007 | Python | 804 | 28 | from datetime import datetime, timedelta
import pandas as pd
import pytest
from data_profiling import ProfileReport
@pytest.fixture()
def df():
df = pd.DataFrame(
{
"name": ["John Doe", "Marco Polo", "Louis Brandeis", "William Douglas"],
"year": [1965, 1271, 1916, 19... |
113667fb4afbc8705a5f1379969bb0c303f7e3747bec0c2f74b2ce60aa6092fe | Python | 805 | 27 | import numpy as np
def weighted_median(data: np.ndarray, weights: np.ndarray) -> int:
"""
Args:
data (list or numpy.array): data
weights (list or numpy.array): weights
"""
if not isinstance(data, np.ndarray):
data = np.array(data)
if not isinstance(weights, np.ndarray):
... |
717729fa8d08e2ffb9ce673169dd070ecfa874325ab24a5d97233e1841a2fbd7 | Python | 805 | 30 | from tensorflow.keras import backend as K
def dummy_function(x):
return x * x
def loss_selector(loss_type):
if loss_type == "mean_squareroot_error":
return mean_squareroot_error
if loss_type == "annealed_loss":
return annealed_loss
else:
return loss_type
def annealed_loss(y... |
a22ac1834ad24987612ed35e23ed4653cc4ba70eed8653219e1878fb9dd066f3 | Python | 806 | 36 | import logging
from datetime import datetime
from agent.classifiers.lstm_classifier import lstm
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
USE_GPU = True
if __name__ == "__main__":
starting_time = datetime.now()
lstm(for_task_label="fc",
binary_classifier=True,... |
92473f586e6a0d27412907e130e7c71eda2243a5af39e9a635ec42f94e4013ea | Python | 807 | 32 | import ray
import asyncio
import requests
from aiohttp import web
@ray.remote
class Counter:
async def __init__(self):
self.counter = 0
asyncio.get_running_loop().create_task(self.run_http_server())
async def run_http_server(self):
app = web.Application()
app.add_routes([web.g... |
1dc2b6ed28f79571d39e880b09f96833530453d117d95d36e0a1464e83294a9f | Python | 809 | 23 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="mobility-mapper",
version="0.0.18",
author="Grant Weiss",
author_email="grant.weiss@me.com",
description="For manually scoring mobility in behavior tests",
long_descr... |
277507bd534b08c8d192644578df0993360f30f8640622232c176f7087594392 | Python | 809 | 27 | """Stand-in for a library's private implementation package.
Mirrors ``ray.data._internal``: the implementation lives under a private module
while the public name is re-exported from a public module's ``__all__``. The
package is named ``_internal`` on purpose, because the check's private-name
heuristic keys on that exa... |
99c46b508f7a8c2151aa32929484e19c61895ae042a6af2b95d9b20c1d54b5da | Python | 809 | 30 | import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
# Generate random data
np.random.seed(1)
x = np.random.randn(1000)
y = np.random.randn(1000)
# Calculate density using Gaussian kernel density estimation
density = gaussian_kde(np.vstack([x, y]))
# Calculate density values for ea... |
4c058e9c2f4d02588cc3445c48aa31f17b6bbf73624d333e1e33d055ffe72285 | Python | 810 | 31 | from pathlib import Path
from pykilosort.ibl import run, ibl_pykilosort_params
import os
import cupy as cp
import shutil
def RunPyKS(bin_file):
print('Starting PyKS2 now')
bin_file = Path(bin_file)
print(bin_file)
# Path management
scratch_dir = Path(os.path.dirname(bin_file))
ks_output_dir = scratch_dir.joi... |
f10ed891ac643f905e6439d16fd087b91fbd7f7a13fa07495587fbc40d5d80cb | Python | 810 | 29 | import numpy as np
import torch
import torch.nn.functional as F
import pfrl
class Boltzmann(pfrl.explorer.Explorer):
"""Boltzmann exploration.
Args:
T (float): Temperature of Boltzmann distribution.
"""
def __init__(self, T=1.0):
self.T = T
def select_action(self, t, greedy_act... |
c8a4799ee385159fcd43ab79935e6033f501f1bfda12bef442b41c89c3e889fe | Python | 811 | 18 | # This file is part of the INTREPPPID programme.
# Copyright (c) 2023 Joseph Szymborski.
#
# This programme is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3.
#
# This programme is distributed i... |
d51a33aa19d0b4a2ae946ef45bf59b7ef490256b6857d1f0cf681bb0c8af65bf | Python | 812 | 29 | import cv2
import sys
sys.path.append('.')
import time
import torch
import torch.nn as nn
from model.RIFE import Model
model = Model()
model.eval()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.set_grad_enabled(False)
if torch.cuda.is_available():
torch.backends.cudnn.enabled = True
... |
3f6e4623ba954a11f11b0ad3303c82b0e0c78446d77737c304541185ec20ad6b | Python | 813 | 30 | # Generated by Django 4.1.6 on 2023-02-06 05:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("infer", "0010_alter_weights_name"),
]
operations = [
migrations.AddField(
model_name="weights",
name="args",
... |
d4fba67ef8eddda08ea51cacba74035215073d2f3469609f3c976143f35406eb | Python | 813 | 30 | from contextlib import contextmanager
from typing import List
import torch
from ray.air._internal.device_manager.torch_device_manager import TorchDeviceManager
class CPUTorchDeviceManager(TorchDeviceManager):
"""CPU device manager"""
def is_available(self) -> bool():
return True
def get_device... |
060a5fddd6e97a4faa4d9284538841844d1614077460f972c505ab6c76f5e08c | Python | 814 | 30 | """
Genomics-related API clients for DataCollect.
This module provides API clients for genomics databases including:
- Ensembl: Gene annotations, sequences, variants
- ClinVar: Clinical significance of variants
- dbSNP: Single nucleotide polymorphisms
- gnomAD: Population genetics data
- GWAS Catalog: Genome-wide asso... |
0769257e0b77d8d080da713ad34ae8c4aa9b734fdca256ceb88481ae4fac6b2d | Python | 815 | 34 | from typing import Optional
from data_profiling.config import ImageType
from data_profiling.report.presentation.core import Container, Image
def image_or_empty(
image: Optional[str],
*,
alt: str,
image_format: ImageType,
caption: Optional[str] = None,
name: Optional[str] = None,
anchor_id... |
3e8942cbcc7bf147a299e59a7f864f68892327c0df85814284b615f03d0630ca | Python | 816 | 37 | """Quick start: train, test and check a ModNN model.
python -m modnn.run path/to/your_data.csv
The CSV needs a datetime index and the columns temp_room, temp_amb, solar, occ and phvac.
Outputs go to ./modnn_output. Edit the overrides in main() to change the model.
"""
import random
import sys
import numpy as np
... |
f68a808d6eccc7ce45ccd148aaafe3408fe464f060661b066985adb633e723a1 | Python | 816 | 31 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from django.db import migrations
from django.db.models import Value
from django.db.models.functions import Replace
OLD = '"consensus_replica"'
NEW = '"replica"'
def _replace(old: str, new: str):
def forwards(apps, schema_editor):
Quali... |
6bfe37d37d61f5abe17fece72f5c9437b3e964d9b51186da81b7f9c8d4377aa2 | Python | 817 | 31 | import logging
import csv
def create_logger_handler(logging_dir, logging_fn):
logger = logging.getLogger(name=logging_fn)
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler(logging_dir + logging_fn + ".log")
fileHandler.setLevel(logging.DEBUG)
logger.addHandler(fileHandler)
fo... |
d9bd2181caebe003bc99ce1ed64c7a7e18310e07fe6832c05144a93d1f0172c4 | Python | 817 | 31 | """Utility functions for (version) compatibility"""
from contextlib import contextmanager
from functools import lru_cache
from typing import Generator, Tuple
import pandas as pd
@lru_cache(maxsize=1)
def pandas_version_info() -> Tuple[int, ...]:
"""
Get the Pandas version as a tuple of integers,
akin to... |
1ff384de4ccab18b7d38f47b0eef7e7c77988daba0712c0c5d1e8744a8d46771 | Python | 818 | 30 | from typing import Tuple
from pyspark.sql import DataFrame
from data_profiling.config import Settings
def describe_generic_spark(
config: Settings, df: DataFrame, summary: dict
) -> Tuple[Settings, DataFrame, dict]:
"""Describe generic series.
Args:
series: The Series to describe.
summar... |
45e98e482af45cf52d86ab895b6202f0d06a574768663a2cd055101a7107e11e | Python | 818 | 28 | from scipy.io import loadmat
import os
import pdb
import numpy as np
from latent_time_stepping.utils import create_directory
def main():
num_samples = 210
train_or_test = 'train'
data_load_path = f'../allan/2DBarTestExperiment/data/{train_or_test}'
data_save_path = f'data/wave_phase/raw_data/{t... |
0915636e0e1009db2c956ac46905fc8eed543fe73375d4168e685062cb6eff60 | Python | 819 | 36 | # __start__
from ray import serve
from ray.serve import metrics
import time
import requests
@serve.deployment
class MyDeployment:
def __init__(self):
self.num_requests = 0
self.my_counter = metrics.Counter(
"my_counter",
description=("The number of odd-numbered requests to... |
b70b9b894659fe4ae3b6650c8ad3cab8beb594adc3fbb94c7cbf14653bff5c9b | Python | 819 | 33 | import setuptools
setuptools.setup(
name="scdemon",
version="0.1.0",
url="https://github.edu/KellisLab/scdemon",
author="Carles Boix",
author_email="cboix@mit.edu",
description="Computes and plots gene modules for single-cell data",
long_description=open("README.md").read(),
packages=se... |
3973a431d1bb5ddb01a997411f33869a8214043fc8cb1c4e293ed29e88d11628 | Python | 820 | 29 | _base_ = 'faster-rcnn_r50_fpn_1x_ruod.py'
model = dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
style='pytorch',
... |
8d7f2c6fd2fd27778e952507bab605595459939849ceb43924c39cd2d7793ead | Python | 820 | 29 | _base_ = 'faster-rcnn_r50_fpn_1x_ruod.py'
model = dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=32,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
style='pytorch',
... |
5fa77750c3102d850fc994832d955500573977aca9f1eb48c1e725da52bd55a0 | Python | 822 | 29 | _base_ = 'faster-rcnn_r50_fpn_1x_duo-coco.py'
model = dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
style='pytorc... |
73d67bd32e6acc650ddf28885713900cd6f0d07059bd97e3fe501e2019f9a194 | Python | 822 | 29 | _base_ = 'faster-rcnn_r50_fpn_2x_duo-coco.py'
model = dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=32,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
style='pytorc... |
aa3d089adcf027eea5c4a20a851f9228b2c93a1e9c1dccfdf6be04b12385b4aa | Python | 822 | 29 | _base_ = 'faster-rcnn_r50_fpn_1x_duo-coco.py'
model = dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=32,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
style='pytorc... |
b9573161b97cd29c0a2e7f9f96a07cc667f042c4f495ea7300a7d2845f395935 | Python | 822 | 29 | _base_ = 'faster-rcnn_r50_fpn_2x_duo-coco.py'
model = dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
style='pytorc... |
3843ab5658b09655f3c47e7d417f1200b00edfa2e0ff420f4eafeec3e3ed00ae | Python | 823 | 35 | #!/bin/python
#------------------- Description & Notes --------------------#
#------------------- Dependencies ---------------------------#
# Standard imports
import gzip
import shutil
from pathlib import Path
# Third-party imports
# Internal imports
#------------------- Constants ------------------------------#
... |
ddc74c672532893fdf11e65e3718741280533d2fecb51523242359a7bcb511e3 | Python | 824 | 26 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Neural network modules."""
# Convenience imports for easier access to the classes.
from aihwkit.nn.modules.container import AnalogSequential, AnalogWrapper
... |
7546e5a8d4939653c13798da5acb1342417cab3af19c4a4d2fa2b9e73f131bbe | Python | 825 | 37 | from typing import List, Optional, TypeVar
from multimethod import multimethod
from pydantic.v1 import BaseModel
from data_profiling.config import Settings
T = TypeVar("T") # type: ignore
class Sample(BaseModel):
id: str
data: T # type: ignore
name: str
caption: Optional[str] = None... |
3f75aa94da76dcf00afff7c67d3f96fb843607b1af143729fd85ebd1295d56dc | Python | 826 | 42 | """This module serves to elevate callbacks in submodules to the
skorch.callback namespace. Remember to define `__all__` in each
submodule.
"""
# pylint: disable=wildcard-import
from .base import *
from .logging import *
from .regularization import *
from .scoring import *
from .training import *
from .lr_scheduler i... |
4209da583fa89cae198431775d41e69d7ba8fbf050bf47eddfaaf054fbfdedb8 | Python | 826 | 27 | import gym
import numpy as np
import pytest
import pfrl
@pytest.mark.parametrize("env_id", ["CartPole-v1", "MountainCar-v0"])
@pytest.mark.parametrize("scale", [1.0, 0.1])
def test_scale_reward(env_id, scale):
env = pfrl.wrappers.ScaleReward(gym.make(env_id), scale=scale)
assert env.original_reward is None
... |
c5376846e4c0481f1b6dd3617993fd3158c15bd9c78a9e165bf318353e6059d9 | Python | 826 | 30 | from setuptools import setup, find_packages
setup(
name = "TIANA",
version = "0.1.0",
author = "Rick Z Li",
author_email = "zzrickli@gmail.com",
include_package_data=True,
packages=find_packages(include=['TIANA', 'TIANA.*']),
description = ("TIANA is a tool to leverage self-attention to un... |
464868c84156d24a0cd02dc4c5166dbd46cd75ce7898c6606af8093b1bc4c066 | Python | 827 | 36 | import gym
import numpy as np
class CastObservation(gym.ObservationWrapper):
"""Cast observations to a given type.
Args:
env: Env to wrap.
dtype: Data type object.
Attributes:
original_observation: Observation before casting.
"""
def __init__(self, env, dtype):
s... |
522e30d9998bad6d9420582231b8f1928293fa2a457e77755ca04b708f790278 | Python | 827 | 26 | import matplotlib.pyplot as plt
import pandas as pd
import utils
font = {"size": 10, "family": "Arial"}
plt.rc("font", **font)
full_df = pd.read_csv("anon_results.csv", index_col=[0, 1, 2])
# Remove post-operation visits from test results
full_df = full_df[full_df["visit_type"] != "post-operation"]
## First let's ... |
daf946117c4fdc308ef6145464bc8ac5e8005f13770e31c9084080ee957c1d65 | Python | 827 | 36 | import subprocess
import os
from conf_build import vVERSION
output_folder = f"../dist/{vVERSION}/anaconda"
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# commands to execute
commands = [
f"conda build . --output-folder {output_folder}",
"conda build purge"
]
# command must be execute... |
fb0ab0611bcbbc47831baf79e70f4c379e6c1e92b35f8ffa159210dcff3b8900 | Python | 827 | 27 | """Central resolver for ov.Agent storage root.
Honors ``OVAGENT_HOME`` env var; falls back to ``~/.ovagent``. Lets users
redirect all session / trace / context / notebook output to a scratch
filesystem on hosts where /home is small or quota-constrained.
"""
from __future__ import annotations
import os
from pathlib i... |
4c44d79ec44ebda0773be61f3bf4e23a8da9a8ba585afa887838157f93393b29 | Python | 828 | 35 | #!/usr/bin/env python
import fmm3dpy as fmm
import numpy as np
#
# This is a sample code to demonstrate how to use
# the fmm libraries
#
# sample with one density, sources to sources,
# charge interactions, and potential only
#
n = 2000
nd = 1
sources = np.random.uniform(0,1,(3,n))
eps = 10**(-5)
zk = 1.1 + 1j*0... |
4cc3d5f1abb41f20838d6bbe7d3fab88320c90a0a47f909c1edf4d0fb94cd163 | Python | 828 | 24 | """
==============================
Leaky Integrate and Fire (LIF)
==============================
The :class:`~sinabs.layers.LIF` layer. This neuron integrates the input and decays its state at every time step.
"""
import torch
from utils import plot_evolution
import sinabs.layers as sl
const_current = torch.ones((1,... |
4fcd9cad4f66bb95a55f482c317ac68329a7a6a796053e3a8c9106e65eaa414d | Python | 828 | 23 | """``ov.utils.gpuex`` — GPU-accelerated re-implementations of common
NumPy / SciPy primitives.
Each submodule mirrors the upstream namespace and tries to keep the
public-function signatures byte-compatible so a one-line import-swap
moves a hot loop onto CUDA.
Today
-----
* ``ov.utils.gpuex.scipy.rankdata`` — vectoris... |
2d46e1810c367e3f96b3846ff29d7dd45c81771d22a713a1558e3bae5bc7fd97 | Python | 829 | 29 | import argparse
from pathlib import Path
import subprocess
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Run dockerized sz detection on all EEG files"
)
parser.add_argument("input", help="Path to root of the EDF EEG files.")
args = parser.parse_args()
for edf in... |
c4d776f1ce82fbdcfa9bbcad693b7fd7e72261a04cba8418a7614321a8f14001 | Python | 829 | 24 | import enum
from typing import List, Tuple
from matplotlib import pyplot as plt
from matplotlib.axes import Axes
import numpy as np
def plot_trace(trace:np.array, col_names: List):
if trace.shape[0] != len(col_names):
raise ValueError(f"Traces have {trace.shape[0]} leads, but only {len(col_names)} lead ind... |
fa55957add0655628cec37666ad099a8aa7cfbe2c84be877d70eb591d622d235 | Python | 829 | 30 | """
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 unittest import TestCase as UnitTestCase
import requests
from fairchem.demo.ocpapi.client import ... |
478770d8ba327c80ac72609695e6a94bd9a0ae426ad3f5e86934857e30d74fa7 | Python | 831 | 23 | import numpy as np
import torch.nn as nn
import pytest
from sinabs import from_model
from sinabs.backend.dynapcnn import DynapcnnNetwork
from sinabs.backend.dynapcnn.dvs_layer import DVSLayer
def test_speck2e_coordinates():
"""Generate the configuration for speck2edevkit."""
ann = nn.Sequential(nn.Conv2d(2, ... |
a3c2ffea564991fc56ac4c4ca6f39f5e8ee0821bbbc3e45363b12caacf5e3c7a | Python | 831 | 27 | import torch
from SPLAM import *
from splam_utils import *
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as pl
import os
MODEL_VERSION = "SPLAM_v11"
device = torch.device("cpu")
model = torch.load("./MODEL/"+MODEL_VERSION+"/splam_14.pt")
# for parameter in model.paramet... |
8a304bfbcefe0384d9b94eadf6ced4079c068f4e1a45548da61c2c29e121d43a | Python | 832 | 31 |
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
class PrefNet(nn.Module):
def __init__(self, nb_obj=2, middle_size=10, **kwargs):
super().__init__()
self.f1 = nn.Linear(nb_obj, middle_size)
se... |
c07ad2179e73d22f2fbb150f17c917eb32245a9cd2915535e7390d65ee7783e1 | Python | 832 | 34 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Legacy location of the utils module. Please import from parameter.utils / enum in future."""
# pylint: disable=unused-import
from aihwkit.simulator.paramete... |
386eded5b7b397e3993b55b37bfc68a580ea55775409ccbb8cf89ef18e5bec7f | Python | 833 | 28 | import os
import pytest
from testbook import testbook
pytest.importorskip("tensorflow")
pytestmark = pytest.mark.tensorflow
@testbook("examples/02-Multi-GPU-Tensorflow-with-Horovod.ipynb", execute=False)
def test_getting_started_tensorflow(tb):
tb.inject(
"""
import pandas as pd
import n... |
59889fd2ebf292a6e5cc905656997b077cea554c10fbaa2953fa79a1aea532d8 | Python | 833 | 26 | import cv2 # noqa: F401 — preload libtiff before HIPT/torchvision shadows it (omicverse vendored patch)
import sys
import pandas as pd
from utils import read_lines, load_tsv, save_tsv
def main():
prefix = sys.argv[1]
gene_names = read_lines(prefix + 'gene-names.txt')
dfs = {
gn: load_tsv(f'{p... |
68a65bf7141a06d2e9d188ff38ae065b7b6b231f5c72d200acae64ad5b983ba7 | Python | 833 | 26 | __version__ = '1.1.0'
class Colors:
"""ANSI color codes for terminal output styling."""
HEADER = '\033[95m' # Purple
BLUE = '\033[94m' # Blue
CYAN = '\033[96m' # Cyan
GREEN = '\033[92m' # Green
WARNING = '\033[93m' # Yellow
FAIL = '\033[91m' # Red
ENDC = '\... |
a9963e0ca7ba13ee676168501f42157d7993d3cead574bac846e00874c6a0082 | Python | 833 | 28 | import importlib
__all__ = [
"HubMetadata",
"HubModel",
"HubModelCardHelper",
"create_criticism_report",
]
_LAZY_ATTRS = {
"HubMetadata": ("._metadata", "HubMetadata"),
"HubModelCardHelper": ("._metadata", "HubModelCardHelper"),
"HubModel": ("._model", "HubModel"),
"create_criticism_re... |
2d1a0ab6a06103157378548306ea1ff47212f43864ffa12c91fa77d20bdbef41 | Python | 834 | 44 | # __anti_pattern_start__
import ray
import numpy as np
ray.init()
large_object = np.zeros(10 * 1024 * 1024)
@ray.remote
def f1():
return len(large_object) # large_object is serialized along with f1!
ray.get(f1.remote())
# __anti_pattern_end__
# __better_approach_1_start__
large_object_ref = ray.put(np.zeros... |
c152f08abfbe56b0809870568ab4b213d3a533d5ca88b990fe422c634e79eea7 | Python | 834 | 29 | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import numpy as np
from torc... |
2a087bbdf86b8b5fc73d4da3951d44cfdac3b2ff4c725f89080493adc2858e3f | Python | 835 | 37 | import logging
from colorlog import ColoredFormatter
import os
import pdb
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = ColoredFormatter(
"%(log_color)s[%(asctime)s] %(message)s",
# datefmt='%H:%M:%S.%f',
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
... |
b8f60625d0374f4dc1cc87dc4feef4170de345b288f5d68098415bc270dea01c | Python | 835 | 26 |
import tensorflow.keras.backend as K
def mean_or_not(mean):
# return (lambda x: K.mean(x,axis=(-1 if backend_channels_last() else 1))) if mean else (lambda x: x)
# Keras also only averages over axis=-1, see https://github.com/keras-team/keras/blob/master/keras/losses.py
return (lambda x: K.mean(x,axis=-1)... |
63dae207257be2f30d8f0fbd91163de577c30501a967eebd915bb28137df1860 | Python | 836 | 37 | from sklearn.metrics import roc_auc_score
import gzip
import sys
seq = sys.argv[1]
pred = sys.argv[2]
# Initialize lists to hold labels and predictions
y_true = []
y_pred = []
# Read gzipped FASTA file and populate y_true based on sequence headers
with gzip.open(seq, "rt") as fasta_file:
for line in fasta_fi... |
188a0ee671de09c416957e418ec4cef210138c705a5de30206f52a4e49bcd660 | Python | 837 | 29 | import torch
from .fourier import apply_fourier_mask_to_tomo
def masked_loss(model_output, target, rot_mw_mask, mw_mask, mw_weight=2.0):
"""
The self-supervised per-sample loss function for denoising and missing wedge reconstruction.
"""
outside_mw_mask = rot_mw_mask * mw_mask
outside_mw_loss = (... |
4bbd9f91faddd513323529a10d21fab2efe5f560d86389d9920e3ee1703856de | Python | 837 | 25 | # -*- coding: utf-8 -*-
"""
"""
import matplotlib
matplotlib.use('Agg')
from analysis_and_visualization import perform_analysis_and_visualization, perform_analysis_and_visualization_stc, perform_analysis_and_visualization_spont
from mozaik.storage.datastore import Hdf5DataStore, PickledDataStore
from mozaik.controller... |
5bb9cb4fd4932da081db39a066254e7edb4cd214d8aa420c4fd2335ee25070e8 | Python | 837 | 34 | from typing import Any, Optional
from data_profiling.config import ImageType
from data_profiling.report.presentation.core.item_renderer import ItemRenderer
class Image(ItemRenderer):
def __init__(
self,
image: str,
image_format: ImageType,
alt: str,
caption: Optional[str] ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.