sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
7c1aa4f9e8b3af08ffe0aca68318b0ee4d15fbb32582a4b374ad52a4d315ec51 | Python | 5,644 | 161 | import inspect
import numpy as np
from keras.src import ops
from keras.src.api_export import keras_export
from keras.src.backend.common import standardize_dtype
from keras.src.backend.common import standardize_shape
from keras.src.initializers.constant_initializers import STFT
from keras.src.initializers.constant_ini... |
d94262eb10f1361d8189b2b922dc6dd5326006ba55621cb0402f43f7a5fc5f39 | Python | 5,644 | 213 | """Benchmark pre-hook provenance overhead on a large module chain."""
from __future__ import annotations
import argparse
import json
import statistics
import sys
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any
import torch
import torch.nn.modules.module as torch_modul... |
5c0ea16a3e7d8a24796f21cc3f1504fbe1b3ea7c87eb9928209101b65ca1d352 | Python | 5,645 | 188 | from abc import ABC, abstractmethod
import attr
from matplotlib import patches
import numpy as np
from ..pattern import find_pattern
@attr.s
class Annotation(ABC):
"""
Represents an annotation cluster, a set of sites along with a certain
notion of what transcripts are compatible with it.
"""
... |
746d0fd55f9e137e0306a90b61a59a92c214daf47bd2d262d4ba667937053d23 | Python | 5,648 | 172 | import warnings
import numpy as np
import pytest
from neurogym.core import TrialEnv, env_string
from neurogym.envs.registration import make
from neurogym.utils import spaces
def test_one_step_mismatch():
"""Test the agent gets rewarded if it fixates after seeing fixation cue."""
class TestEnv(TrialEnv):
... |
b9ce9b778456bd8a0f50bd4d336f4049cdd65e46f8390a8dcaa250c584c5fea1 | Python | 5,648 | 156 | from datetime import datetime
from enum import Enum
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field, model_validator
class TelemetryLevel(str, Enum):
disabled = "disabled"
minimal = "minimal"
extensive = "extensive"
class TelemetryBase(BaseModel):
model_config = ... |
e9b85749d6e4e45008ba13de78dd207be50c1cd936032104e32a25f9437e278b | Python | 5,648 | 134 | from __future__ import annotations
import pytest
import torch
from lightly.loss import LeWMLoss
from lightly.loss.lewm_loss import latent_prediction_loss
class TestLatentPredictionLoss:
def test_forward__zero_for_identical_inputs(self) -> None:
emb = torch.randn(4, 3, 16)
assert latent_predictio... |
22d999098b3431ee74ea454b4eb79171e56fc11b62c9f996b6bc9139c633608f | Python | 5,650 | 151 | """Wrapper that tracks the cumulative rewards and episode lengths."""
import time
from collections import deque
from typing import Optional
import numpy as np
import gym
def add_vector_episode_statistics(
info: dict, episode_info: dict, num_envs: int, env_num: int
):
"""Add episode statistics.
Add stat... |
34ba122fa4642775b69eaa143d5a97346b5e32b9b23ffc333e84732cdcb0b461 | Python | 5,650 | 142 | """Buffer density via the tri-state policy + counter-chain rule (F14, memo D-10).
The netron exporter reuses TorchLens's existing ``show_buffers``
``never|meaningful|always`` policy (default ``meaningful``) with ONE added
rule: counter-update chains (the zero-dim ``add`` ops between
``num_batches_tracked`` reads and w... |
440a7b6455a368c11bc8e5dfe3285fb46d1c48d2ad717ecb8b3613f56444716c | Python | 5,651 | 174 | """Provocations for documented refusal codes with no prior test coverage (R25-6).
Two families were documented in the public vocabulary but never provoked by any
test, so a code swap or a dead raise site would have failed zero tests:
- ``RecordBindingError`` doors (``record_not_bound``,
``trace_reference_collected`... |
c13ded3506403cc254a0b55f50362622c43842dc0a34beab63fac514ed3323a8 | Python | 5,651 | 189 | """Monomer class with parameters and methods."""
from typing import Tuple, Union
import pandas as pd
from rdkit import Chem
from rdkit.Chem.Descriptors import ExactMolWt
from rdkit.Chem.rdchem import Mol
functionality_smarts = {
"ols": "[C,c;!$(C=O)][OH]",
"aliphatic_ols": "[C;!$(C=O);!$([a])][OH]",
"aci... |
0688f3d4cef111dc0ad9b6f8c7c8a9339dddbad165369be429fed02a28405259 | Python | 5,653 | 150 | """Implementation of the `Space` metaclass."""
from typing import (
Any,
Generic,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
)
import numpy as np
from gym.utils import seeding
T_cov = TypeVar("T_cov", covariant=True)
class Space(Generic[T_... |
6de98725bb95323df8906a6c4331c801de84dd1c1648c1c2c66234c5c1a7fe08 | Python | 5,654 | 167 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.5
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# +
from pat... |
4a129d2cb2177f7c0ab93b1f79e9867d05b8c3d2cb057d81b3f5ecc345a948cb | Python | 5,655 | 156 | """RPN anchors."""
from __future__ import absolute_import
import numpy as np
from mxnet import gluon
class RPNAnchorGenerator(gluon.HybridBlock):
r"""Anchor generator for Region Proposal Networks.
Parameters
----------
stride : int
Feature map stride with respect to original image.
T... |
bb3885e175e2850a6cd0a31cb8e7908a077d84a323a4b3f03d3da24e04dd2940 | Python | 5,655 | 142 | # SOURCE: vendored from https://github.com/facebookresearch/torchbeast @ main
# (torchbeast/monobeast.py: AtariNet, lines 545-635)
#
# IMPALA (Espeholt et al. 2018, "IMPALA: Scalable Distributed Deep-RL with Importance
# Weighted Actor-Learner Architectures"). The official DeepMind release
# (google-deepmind/scalable_a... |
56e7ff80ecd2198cf1ba9b12037a0dabf93861d584164cff53cb1bf4c5d6c63c | Python | 5,656 | 145 | """
Figure about FSM models.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import figutils
from PyPDF2 import PdfReader, PdfWriter, Transformation
import pickle
# If you change figutils often, and want changes reloaded, uncomment lines below:
#from importlib im... |
a5971b361cf5782a88970417ef4c7c3de5b201e48a0f3850d207fbfbadfe44a8 | Python | 5,657 | 165 | """F03 ledger memo item 3: Bundle lineage persistence in the .tlspec artifact.
The C07X split-off join, landed: ``bundle_id`` / ``forked_from_bundle_id`` /
``member_construction`` anchors / hash-chained ``operations`` /
``member_effect_tables`` persist as writer-owned ``bundle.json`` sections and
load back fail-closed... |
e032cedd1fa3b197598716f7d5fa8e1a78a9f66c6cc6d3a984679ec03d07a8cf | Python | 5,657 | 187 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Dict, Iterable
import torch
import torch.nn as nn
from bdpy.task.callback import CallbackHandler, BaseCallback
_FeatureType = Dict[str, torch.Tensor]
class BaseCritic(ABC):
"""Critic network module."""
def __init__... |
28426b2a20d56ac514e3e17a6b1c76f43ed4e288c1ed2d25e6cd4966a6e88ea4 | Python | 5,658 | 163 | """Layer-to-layer empirical receptive-field regression tests."""
from __future__ import annotations
import pytest
import torch
from torch import nn
import torchlens as tl
from torchlens.receptive_field._errors import ReceptiveFieldUnavailableError
from torchlens.receptive_field._gradient import gradient_for_unit
d... |
b9a05540f117a72cb81ba3fafa5318635ea697eb75f320c269538190f7e11bdf | Python | 5,658 | 193 | import numpy as np
import pandas as pd
import geopandas as gpd
import shapely
import pytest
from ...core.trajectorydataframe import TrajDataFrame, FlowDataFrame
from .. import plot
from ...utils import constants
from ...preprocessing import detection, clustering
import folium
import matplotlib
lat = constants.LATITUDE... |
905958ef495635dc8bd062ea083e3a4d3c29b831967c35cf94406a60f5c434de | Python | 5,659 | 146 | from keras.src import backend
from keras.src import layers
from keras.src import models
from keras.src import ops
from keras.src import tree
from keras.src.backend.common import standardize_dtype
from keras.src.backend.common import standardize_shape
from keras.src.utils.module_utils import tensorflow as tf
def get_i... |
eaab87820a137a019fd227fa399fcfec9803bca065bd7dd26ee1f0967144fe56 | Python | 5,660 | 142 | import pytest
import torch
import torch.nn.functional as F
from pytest_mock import MockerFixture
from torch import distributed as dist
from torch import nn
from torch.optim import SGD
from lightly.loss import msn_loss
from lightly.loss.msn_loss import MSNLoss
from lightly.models.modules.heads import MSNProjectionHead
... |
18b2ef17df4549af95d8865462df3c59cdef47f9b88944093a4f0e3e8cef9ce3 | Python | 5,661 | 169 | # noqa
# type: ignore
# pylint: skip-file
import numpy as np
def rotate_vector(vector, rot_x=0, rot_y=0, rot_z=0, center=None):
if center is not None:
vector -= center
x0, y0, z0 = vector.tolist()
cos_ry, sin_ry = [np.cos(rot_y), np.sin(rot_y)]
x1, y1, z1 = [sin_ry * z0 + cos_ry * x0, y0, co... |
90305044095f7535aa5b9d19f9cc53824a3361574d10fcf93127840e8df56938 | Python | 5,661 | 159 | """Regression tests for r18p A5 low-severity IO fixes.
L2: ``BundleStreamWriter`` no longer carries the dead ``_saw_first_payload``
write-only state.
L3: the large-blob (mmap) materialize branch brackets its streaming hash with a
file-identity guard, so a rename-replace or in-place rewrite occurring
betwee... |
aa89a5efc82f43c99ed7a35baa820885f834c204766be265f6612ef988c1318b | Python | 5,661 | 150 | # Copyright 2017 The TensorFlow Authors. 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 applica... |
af11152c192d754de632f59454f6b08494550562963ebb315eab3a627bd80ddd | Python | 5,662 | 169 | """Regression tests for RF view/table surface honesty.
Covers r19f findings W2A3-08 (projective ``.at('center')``), W2A3-09
(projective table ``input=`` filter), W2A3-10 (table accepts trace input
accessor handles), W2A3-14/16/18 (docstring + diagnostic honesty), and
W2A3-15b (``.at()`` negative-index reject contract)... |
9805d1c75555c2f664157407978765e2ba11facb03434eb9b2dc1e37a09225d0 | Python | 5,663 | 146 | import os
import sys
import gzip
import pickle
import time
from collections import defaultdict
import numpy as np
from Bio.PDB.MMCIFParser import MMCIFParser
from Bio.PDB.Polypeptide import is_aa
from scipy.spatial.distance import cdist
def load_ccd_dict(ccd_preprocessed_path):
assert os.path.exists(ccd_preproces... |
3b70a5f069ff5b0de783529e338abff8fe55c5f7f19190c994b2c49a83737c56 | Python | 5,664 | 146 | '''Reconstruction utilities.'''
import numpy as np
import scipy.ndimage as nd
def clip_extreme(x, pct=1):
'''
Clip extreme values.
Original version was written by Shen Guo-Hua.
'''
if pct < 0:
pct = 0.
if pct > 100:
pct = 100.
x = np.clip(x,
np.percent... |
ca37c5f245d27444e186b72c27b3e892b5a1c2a25c87eaaa2d9e10581f007e16 | Python | 5,664 | 136 | # INFO:
__program__ = "MetalHawk data extractor"
__author__ = 'Gianmattia Sgueglia'
__email__ = 'gianmattia.sgueglia@unina.it'
import __main__
__main__.pymol_argv = ['pymol', '-qcv']
import pymol
from pymol import cmd, stored
pymol.finish_launching()
import os
import argparse
import numpy as np
from scipy.spatial.... |
db3b7b217dbe305d65ce4cd78ee5458bfd718ce1b9e0593acb3cc6efc0896dba | Python | 5,665 | 116 | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torch.autograd import Variable
from torch.nn import Linear, ReLU, CrossEntropyLoss, Sequential, Conv... |
f9a451d5d9eeb2a05d79a19c1764c7ac770478facfc5c99983da3cb14b55524d | Python | 5,665 | 192 | from argparse import ArgumentParser
def add_vit_commandline_args(parser):
vit_group = parser.add_argument_group(
"VisionTransformer architecture")
# this will be handled in the config
# since the transformations will take care of it
# vit_group.add_argument(
# "--image_size",
# ... |
8ed6fb50caf8b4ebfae94ab26ad9e28818dde0ad7ddb3e8c4b26dc8350a6a213 | Python | 5,669 | 165 | import codecs
import hashlib
import pathlib
import pkg_resources
import afmformats
import h5py
from PyQt5 import uic, QtWidgets
class ConvertDialog(QtWidgets.QDialog):
_instance_counter = 0
def __init__(self, parent, *args, **kwargs):
"""Data conversion dialog"""
super(ConvertDialog, self)._... |
cbe2a3b031bde5158595514f03606c81b3628fa3113418c785f793ec14057b86 | Python | 5,669 | 143 | """Save/publish durability + hardening of the ``merged-directory`` writer
(p4 3.4 R59): permission parity, load-side symlink rejection, and the
publish-time TOCTOU re-check. No live process group needed -- rank cores are
plain captures with injected ``collective_boundary_v1`` annotations.
"""
from __future__ import an... |
1a1bc6f473ec7e455e2de7ce62164301a39c0cacd5d6559c7dbf317e3077981b | Python | 5,670 | 189 | import numpy as np
from multiprocessing import Pool, Value
def init(a_counter, a_n):
"""
Store total number of vertices and counter of vertices computed
Parameters
----------
a_counter : TYPE
DESCRIPTION.
a_n : TYPE
DESCRIPTION.
Returns
-------
None.
"""
g... |
a441a936db5bb71e5f3d44d364314c61d09ed4c2aaa8ed99abfc89c49c0e8d99 | Python | 5,670 | 103 | import spikeinterface.full as si
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
import glob
from spikeinterface.preprocessing import highpass_spatial_filter
from spikeinterface.preprocessing import correct_motion
from spikeinterface.preprocessing.motion import load_motion_info
from spikeint... |
dbc0c195602da66f5b6579876f5803301ec47b1b11cc4d197eda4532f73f05e5 | Python | 5,670 | 174 | from typing import List, Callable, Tuple, Dict
import imodelsx.sasc.m1_ngrams
import imodelsx.sasc.m2_summarize
import imodelsx.sasc.m3_generate
import numpy as np
import pprint
from collections import defaultdict
def explain_module_sasc(
# get ngram module responses
text_str_list: List[str],
mod: Callabl... |
1e5dd2e200a90a43295844e487cbeee9578f77345aaf62cab5fff42740b760cf | Python | 5,671 | 112 | import cv2
import mediapipe as mp
import os
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
output_folder = "E:\\Sign X\\Output" # output image directory
directory_path = output_folder
if not os.path.exists(directory_path):
os.mkdir(directory_path)
import csv
file_type = ".... |
b52e432f4ad59a3353ac29c46af8e676641d0e8108b68baf7da5c19dd6d337e2 | Python | 5,671 | 168 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Nov, 2019
@author: Nathan de Lara <nathan.delara@polytechnique.org>
"""
from abc import ABC
import numpy as np
from scipy import sparse
from sknetwork.linalg.normalizer import normalize
from sknetwork.base import Algorithm
from sknetwork.utils.membership i... |
1d98ac23408dec2b26b13d1d12d6f7d544a45c0af8164e3e804f1a9396550608 | Python | 5,672 | 195 | from functools import lru_cache
import os
import re
import h5py
from more_itertools import chunked
import numpy as np
import pandas as pd
import tqdm.auto as tqdm
GENE_EXPR_GCT = (
"../data/gtex_junctions/GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_reads.gct"
)
GENE_EXPR_H5 = "../data/gtex_junctions/gene_reads... |
7460f8d2385055060cec827fa5294291928935169d4cd9f051662ba1bcaefd94 | Python | 5,672 | 134 | from social_core.backends.oauth import BaseOAuth2
from social_core.utils import handle_http_errors
class TapisOAuth2(BaseOAuth2):
name = "tapis"
DEFAULT_TENANT_ID = "tacc"
@property
def AUTHORIZATION_URL(self): # type: ignore[override]
"""Generate authorization URL based on tenant ID settin... |
a2c46c25577b862af5c3fb855e255e796c5f277898870c6c29180d056a6ab422 | Python | 5,672 | 150 | """Build wheels/sdists by installing build deps to a temporary environment.
"""
import os
import logging
from pip._vendor import pytoml
import shutil
from subprocess import check_call
import sys
from sysconfig import get_paths
from tempfile import mkdtemp
from .wrappers import Pep517HookCaller
log = logging.getLogge... |
eba8e5ef4cd100d71c328e1cd2487204b5547e4e959700c66e3f677755b6e32d | Python | 5,674 | 187 | # Dependencies
import numpy as np
import yaml
import nest
import sys
# Accept and assign variables
scriptpath = sys.argv[1] # Path to Scripts
scriptpath += "/"
Experiment = sys.argv[2] # Experiment defining file
# Load Parameters and unpack
yaml_files = ["network.yaml", "simulation.yaml", Experiment]
for file in ya... |
00412500cd71bb537d75be33d6a4ad7d471bb23a12e657a653bad0d2d8071ebf | Python | 5,675 | 179 | import csv
import datetime
import io
import logging
import os
from typing import Dict, Optional, Union
import torch
from pytorch_lightning.loggers import LightningLoggerBase
from pytorch_lightning.loggers.base import rank_zero_experiment
from pytorch_lightning.utilities import rank_zero_only, rank_zero_warn
log = log... |
be3aa7d414a3d309278e63e65ac48e9790e95697b37f9943f33cd102ed7297f8 | Python | 5,675 | 160 | # Run test with:
# torchrun --no_python --nproc_per_node=8 pytest -q -s tests/modules/test_mha_parallel.py
import math
import pytest
import torch
import torch.nn.functional as F
from apex.transformer import parallel_state, tensor_parallel
from einops import rearrange
from flash_attn.modules.mha import MHA, ParallelMH... |
bf07c9936121da0827411091e3543ee948c1b9cefc3b18e9dda2547d074a4e56 | Python | 5,677 | 191 | from datetime import datetime, timedelta
from typing import List, Optional
import dateutil.relativedelta
from dependency_injector.wiring import Provide, inject
from fastapi import APIRouter, Depends
from pydantic import BaseModel, EmailStr
from starlette import status
from carbonserver.api.schemas import (
Organi... |
48664f74d422ae8f8a06f1244ac72a9b3d1b1a42fda66912426e69457275e9f9 | Python | 5,678 | 181 | #!/usr/bin/env python
"""
Run kernel PCA using kpca() from R 'kernlab' package
usage: %prog [options]
-i, --input=i: Input file
-o, --output1=o: Summary output
-p, --output2=p: Figures output
-c, --var_cols=c: Variable columns
-k, --kernel=k: Kernel function
-f, --features=f: Number of principal com... |
6ac29e7875eab1979ab160edac3b4af1ca28e3e6f56af725d993ba916beaec83 | Python | 5,678 | 171 | # SOURCE: vendored from https://github.com/yihaosun1124/OfflineRL-Kit @ main (951302eed019)
# (queue-listed https://github.com/WeiChengTseng/CQL-pytorch contains no source files
# (README + .gitignore only) -- OfflineRL-Kit ships a maintained, documented CQLPolicy
# built from these real modules and is used instead)
... |
e2bbe672c15a1d1b644df85322a445fa2a8f5b2fc07f8e6b421eb1442f1b9b1a | Python | 5,678 | 188 | """Invocation-template schema + seed templates (purity/state skeleton).
"Templates, not compute, are the cost" (the panel's fact 11: a feared
30-180 s purity sweep ran in 0.7 s, but 10 of 12 doors REFUSED for want of
invocation templates). This module is the ONE template asset with three
consumers: the purity/state ha... |
885501fc05292819bd8b4302cbebfc4b4e3aa9ea24e472c8fb42c52351477d62 | Python | 5,679 | 154 | """
File: data.py
Created: 2020/11/16
Last Changed: 2021/11/19
Author: M.Vochteloo
Copyright (C) 2020 University Medical Center Groningen.
A copy of the BSD 3-Clause "New" or "Revised" License can be found in the
LICENSE file in the root directory of this source tree.
"""
# Standard imports.
# Th... |
207d87b01e6848161afe9c2c58a8c29691306ecad0fef1ef15289ac1e2d2797a | Python | 5,681 | 176 | """AST guardrail for training-mode detach chokepoints."""
from __future__ import annotations
import ast
from pathlib import Path
from _source_corpus import module_ast, module_source
REPO_ROOT = Path(__file__).resolve().parents[2]
SCANNED_PATHS = (
REPO_ROOT / "torchlens" / "capture",
REPO_ROOT / "torchlens"... |
76dbdf2d7cd39f9d658030561e028248d58c63f064a8b91b70e08bc1bf7093c8 | Python | 5,681 | 193 | import numpy as np
from math import exp, erf
# -------------------------------------
# K ANT = 0.001; PSI_max = 0.1865
# K ANT = 0.005; PSI_max = 0.1833
# K ANT = 0.2; PSI_min = 0.132
# K ANT = 0.5; PSI_min = 0.1288
# K ANT = 1; PSI_min = 0.1273
# -------------------------------------
PSI_max = 0.190 # V
PSI_min... |
0391aa46690603b49a824f57109cd26b138e8354c11354cc6251ee53dcfe7ed2 | Python | 5,682 | 136 | import subprocess
from dataclasses import dataclass
from functools import lru_cache
from typing import Any, Union
from codecarbon.core.gpu_device import GPUDevice
from codecarbon.external.logger import logger
@lru_cache(maxsize=1)
def is_nvidia_system():
"""Returns True if the system has an nvidia-smi interface.... |
13e4434c4341c4f08b5998bbec45062a6d29aaf4ecaecb032711e3b5d074ce26 | Python | 5,682 | 213 | """Spatial position related utility functions."""
import numpy as np
from spiketools.utils.data import compute_range
from spiketools.utils.checks import check_axis, check_array_orientation
from spiketools.spatial.checks import check_position, check_bin_definition, check_bin_widths
###################################... |
06e498890d80db26481e4c5d270a2511a7a8a7eaa3c1587e37ae14b1d87f1924 | Python | 5,683 | 147 | import uuid
from copy import deepcopy
import pytest
from celery import signature
from celery.canvas import Signature
def linked_signature(owner: Signature, option: str) -> Signature:
linked = owner.options[option]
return signature(linked if option == 'chord' else linked[0], app=owner.app)
class test_Canva... |
099215e6a483f7bde7cbfb9369f309cdb81b6354a82d7b4b703b7e073d332446 | Python | 5,684 | 148 | """Overhead-measurement harness law (torchnative W0.9 / section 5).
The panel retracted six of its own headline numbers; every one died of
harness or read error. The harness therefore enforces the protocol
mechanically: alternating paired ratios, a refusal predicate declared
before the run and printed in the artifact,... |
8bd6295b1216f98dc5ac1384b1bd696f2fcf9812608fdf8c751e4b349eb739e5 | Python | 5,684 | 197 | import multiprocessing as mp
def run_experiment(
custom_bn: bool = True,
bs: int = 100,
accum_steps: int = 1,
epochs: int = 3,
queue=None,
mixed_precision_flag=True,
):
import os
import random as python_random
import numpy as np
import tensorflow as tf
import tensorflow_da... |
bf74d73b67218a15d1209aac25b67c86720bbd1eb4c866317a18495bafb1dc82 | Python | 5,684 | 122 | import logging
import numpy as np
import pymc as pm
from pmsurv.models.weibull_base import WeibullModelBase
logger = logging.getLogger(__name__)
class WeibullModelLinear(WeibullModelBase):
def __init__(self, k_constant=True, priors_sd=1):
super(WeibullModelLinear, self).__init__()
self.column_nam... |
0c3d09b78d4ff6d079659f694a507373c1285fcdae196449bff92d07303bae5e | Python | 5,687 | 188 | import importlib
import os
import sys
from itertools import count
from unittest.mock import Mock, patch
import pytest
from celery import concurrency
from celery.concurrency.base import BasePool, apply_target
from celery.exceptions import WorkerShutdown, WorkerTerminate
class test_BasePool:
def test_apply_targe... |
cba299a7bcc4ca30255482b3892e6a722f5e0e79cf25a842b1ed749ee28efa0f | Python | 5,687 | 144 | import os
import pandas as pd
from pathlib import Path
import shutil
from Bio import SearchIO
from review_comparison.utils import generate_fasta_file
class SequenceKNN:
def __init__(
self,
path_train_json,
path_test_json,
nb_thread,
path_output_pred,
tmp_folder=Path... |
3aea4cadd7bc27dcd0090b7ad2e9afc9223d33beb3e58661705d3665904753a1 | Python | 5,688 | 97 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
4e6ece1eb35460864e2a4faf82e8db5a9d562e8de06ebf782c93d06f85f113c4 | Python | 5,689 | 188 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
4dc5b601d23da7d25555b2571ef0da5649f64376cae985fb54b0d03887819dc8 | Python | 5,690 | 117 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import shutil
from pathlib import Path
from ultralytics.utils import IS_COLAB, LOGGER, YAML
def _check_rknn_return(ret, name: str):
"""Raise a RuntimeError if an RKNN API call failed."""
if ret not in {0,... |
632fc2c5da7d64cd849af49651cbd76330726ed0885a786878be6f745c0b25df | Python | 5,691 | 161 | import torch
import torch.nn.functional as F
import torchmetrics
import torchmetrics.functional as TMF
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
class ModelInterface(pl.LightningModule):
def __init__(self, model, learning_rate, len_train_dataloader):
super().... |
ecb725adfb7e4bb506204a5d99de0c593333f3da54ef7e05b0ea22fd8312a787 | Python | 5,691 | 139 | from PIL import ImageDraw
from torchvision.transforms import ToPILImage
from cv2 import findContours, boundingRect, RETR_TREE, CHAIN_APPROX_SIMPLE
import numpy as np
import struct
def plotExampleWithMasks(img, masks, alpha=120):
img = ToPILImage(mode="RGB")(img)
draw = ImageDraw.Draw(img, "RGBA")
for i in... |
8b9204462e1857b80186b25f49ba3c5115bdadabd42fdd908fd6af97a8974df6 | Python | 5,692 | 172 | import os
import torch
from collections import deque
from bioseq2seq.utils.logging import logger
from copy import deepcopy
def build_model_saver(model_opt, opt, model, fields, optim):
model_saver = ModelSaver(opt.save_model,
model,
model_opt,
... |
100616f958de0203989272d059df33e07d4e3bf0f4f737f39dc7009600697848 | Python | 5,693 | 148 | """Crop a PBF to a bounding box with one tool, or count the buildings of a PBF, and print the
result as JSON.
benchmarks_scaling.ipynb runs every crop as a separate process (measured by run_monitored.py),
so each crop starts from a fresh process. Every tool keeps complete ways. The crop is written to
a temporary file ... |
2f05e171537f96487809851aef8b181f6288ec87de2817e49cccb07e5fec60a5 | Python | 5,693 | 198 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Pathbar(_BaseTraceHierarchyType):
_parent_path_str = "icicle"
_path_str =... |
e687df8153ca305197831203861b7c644bf874675f021228879c37c71fed6041 | Python | 5,693 | 159 | #!/usr/bin/env python3
import multiprocessing
import regex as re
import logging
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from MarkovModels import common
from MarkovModels.BeattieModel import BeattieModel
from MarkovModels.ClosedOpenModel import ClosedOpenModel
from M... |
56979ed4cdb2187496bc04c33f98fde14611c665ff704e2635f539a853f3087c | Python | 5,694 | 218 | """Regression tests for repeated parent edge rendering."""
from __future__ import annotations
import re
from pathlib import Path
import torch
import torchlens as tl
class _AddTwice(torch.nn.Module):
"""Model whose input feeds both positional slots of ``add``."""
def forward(self, x: torch.Tensor) -> torc... |
c6c6cd0163bc3eadf21ed791fdae7ec7df82cc8e477c2188f0f83dd01efd2d9e | Python | 5,694 | 155 | '''
K-Folding script
author: obanmarcos
'''
import os
import os, sys
from config import *
# Where am I asks where you are
sys.path.append(where_am_i())
import lightning as pl
import argparse
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from utilities import dataloading_utilities as dlutils
fr... |
d61bd6b9cfa69ade98a18ca293237a69ba3d949bfe1786a43f58f947a30c693f | Python | 5,695 | 167 | import torch
from models.restnet_custom import resnet50_baseline
from progress.bar import IncrementalBar
import os
import numpy as np
from torch.utils.data import SequentialSampler
from torch.utils.data.dataloader import DataLoader
from torch.utils.data import Dataset
class Patient_Dataset(Dataset):
"""
A cla... |
f399bf551ad9f5559260d05ba9a0af2a1320cd2722ec676d45ecbcc4e17c6844 | Python | 5,695 | 171 | import pulp
from permacache import permacache, stable_hash
import tqdm.auto as tqdm
from modular_splicing.gtex_data.pipeline.gtex_data_table import (
exon_junction_data,
gene_expr_data,
)
from .annotations import annotation_types
from .extract_sequence_info import extract_sequence_info
def choose_optimal_a... |
47715d2ea260679393c548565b17dbe934cd13c4777fd885cf3c2bee40262469 | Python | 5,696 | 157 | import os
import numpy as np
import pickle as pkl
import nibabel as nib
from os.path import join as pjoin
from scipy.io import savemat
from scipy.stats import zscore
from scipy.spatial.distance import euclidean
from cxy_visual_dev.lib.predefine import proj_dir, Atlas,\
get_rois
anal_dir = pjoin(proj_dir, 'analysi... |
973a167297ea19fdca52af7b291c4e4157c12cf20f4fcf4e532e4a1d02ff6bdc | Python | 5,696 | 155 | '''
K-Folding script
author: obanmarcos
'''
import os
import os, sys
from config import *
# Where am I asks where you are
sys.path.append(where_am_i())
import pytorch_lightning as pl
import argparse
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from utilities import dataloading_utilities as dl... |
d427dbb4c8ed16af02d369d4a5f515dcf3e73d60d7b596a87ed0b6985ccda560 | Python | 5,696 | 157 | #!/usr/bin/env python3
"""
Cron script to retire inactive devices from the Ethoscope database.
This script retires devices that haven't been seen for more than the specified
number of days (default: 90 days). It's designed to be run periodically via cron.
Usage:
python retire_inactive_devices.py [--threshold-days... |
aeb7edb164386822d3d990fc249eb7852f4d4949b66a05f7779f5885dea051dc | Python | 5,697 | 189 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Spitfire documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 11 17:45:56 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# a... |
e09ac7cdb9814ac6981770149cf7bc5b696f510d0a93a266b4727d42ff655689 | Python | 5,697 | 180 | import torch
import torch.nn as nn
import torch.nn.functional as F
import sklearn
import sklearn.cluster
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
def cluster(data, k, temp, num_iter, init, cluster_temp):
cuda0 = torch.cuda.is_available()
if cuda0:
mu = init.... |
e4f69f1718ad084b28de22cc1ff6dd9f3cca2987a50d86c5b5a8a83b576089ca | Python | 5,698 | 150 | import os
import time
import torch
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import torch.optim as optim
from nets.coco_dataset import COCODataset
from nets.sesf_net import SESFuseNet
from nets.nets_utility import *
import torch.nn as nn
from nets.lp_lssim_loss import LpLssimLo... |
a5e65888c12e0d82fcbd10622f88b52b41870e5552b85ad03acd9a1c1428d344 | Python | 5,699 | 142 | """
External implementation of HMM algorithm in torch.
Sourced from https://github.com/TreB1eN/HiddenMarkovModel_Pytorch/blob/master/HiddenMarkovModel.py
"""
import torch
import numpy as np
import pdb
class HiddenMarkovModel(object):
"""
Hidden Markov self Class
Parameters:
-----------
- S: Nu... |
d4208180c927bc9d8f6348128db8589c677ba1f8c88443f30198ca2e15c91af1 | Python | 5,700 | 198 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Pathbar(_BaseTraceHierarchyType):
_parent_path_str = "treemap"
_path_str ... |
05a1fc7e2d079648d850d6da49d2930cfbe39bb7c71ec98ed3db4ff816080cd7 | Python | 5,701 | 148 | from __future__ import print_function, unicode_literals, absolute_import, division
from six.moves import range, zip, map, reduce, filter
from ..utils import _raise, move_channel_for_backend, axes_dict, axes_check_and_normalize, backend_channels_last
from ..internals.losses import loss_laplace, loss_mse, loss_mae, loss... |
2d705273e8b604344c39eea3b8d7e1b22dffef7e93c642c875b003d6ba7149e0 | Python | 5,702 | 138 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 1 17:50:04 2020
@author: a
"""
from src.models.layers import LinkAttention
import torch
import torch.nn as nn
import numpy as np
from src.utils import pack_sequences, pack_pre_sequences, unpack_sequences, split_text, load_protvec, graph_pad
from torch.nn.uti... |
50583547eaf8826c62e740bead55649441f3e4c8e3903acd2d84b90529465b71 | Python | 5,702 | 184 | """Axes class for validating and transforming axes"""
import warnings
from typing import Any
from .format import CurrentFormat, Format
KNOWN_AXES = {"x": "space", "y": "space", "z": "space", "c": "channel", "t": "time"}
KNOWN_SPATIAL_UNITS = [
"angstrom",
"attometer",
"femtometer",
"picometer",
"... |
fd0921a77c2cf954050dac760dbd3179ae804a416c4e0bef9b1201ed2b662c85 | Python | 5,702 | 171 | """
Unit tests for BaseTracker class.
Tests core tracking functionality including position tracking, inference,
and error handling.
"""
import unittest
from unittest.mock import Mock
import numpy as np
from ethoscope.core.data_point import DataPoint
from ethoscope.core.roi import ROI
from ethoscope.core.variables i... |
1e1dd91d62c47ef8ecbb9f2ebd82c602c275c002ed4fcb1092ac81d0e95cdb9a | Python | 5,705 | 158 | import math
import numpy as np
from neurogym.core import BaseEnv
from neurogym.utils import spaces
from neurogym.utils.logging import logger
# TODO: Move to collection
class Pneumostomeopening(BaseEnv):
metadata = { # noqa: RUF012
"paper_link": "https://jeb.biologists.org/content/199/3/683.long",
... |
81976cfe080b3feddbc064a255f733db97469b29a245c493ad61ca2bc19da692 | Python | 5,705 | 186 | import numpy as np
from gym import utils
from gym.envs.mujoco import MuJocoPyEnv
from gym.spaces import Box
DEFAULT_CAMERA_CONFIG = {
"distance": 4.0,
}
class AntEnv(MuJocoPyEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
... |
f645e1917f92e1fe9048c6d50a0f7057f46de0b487c31c11a63538e7029d39f7 | Python | 5,705 | 134 | """
Contains implementations of the authentication logic.
"""
import logging
from typing import TYPE_CHECKING
from galaxy.auth.util import (
get_authenticators,
parse_auth_results,
)
from galaxy.exceptions import Conflict
from galaxy.util import string_as_bool
if TYPE_CHECKING:
from galaxy.webapps.base.w... |
27cb59cc2ad5f8eafaae9c35a717f90bc1c35d9280b3c3ce84ba0a974059fdd9 | Python | 5,706 | 135 | #!/usr/bin/env python
"""把 manuscript/mail_body_damsky.md 导出为可直接粘贴发送的纯文本邮件。
为什么需要这个脚本
------------------
`mail_body_damsky.txt` 是为了应对"发信通道不可用"而做的零凭据兜底产物:作者可以直接
全选粘贴进邮箱客户端,不依赖任何 API。但它此前是由一条**临时命令**生成的,仓库里没有
生成它的代码 —— 这正是本项目已经踩过一次的坑(`out/clock_family_concordance.csv` 曾
是无写出代码的孤儿产物,静默保留了修正前的数值,直到与手稿对照时才发现)。所以这里把
转换固化成脚本... |
41ea7ff4efacfa43d16d9d31c362728ce1eaed527a8342ed3bf8bcd9bf519529 | Python | 5,706 | 156 | """Utils for deep learning framework related functions"""
import numpy as np
__all__ = ['EarlyStopperOnPlateau', '_suggest_load_context', 'create_dummy_estimator']
def _dummy_constructor(self, *arg, **kwargs):
raise RuntimeError(self.reason.format(type(self).__name__))
def create_dummy_estimator(name, reason):
... |
5e616d13f3435b53e915b700580e1a0670797c068b269bda47a97d6ff93930c0 | Python | 5,706 | 146 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#File originally part of moses package: http://www.statmt.org/moses/ (as bleu.py)
#Stripped of unused code to reduce number of libraries used
# $Id$
'''Provides:
cook_refs(refs, n=4): Transform a list of reference sentences as strings into a form usable by cook_test().
cook_... |
6523acadae8b798fffbc9b23702bc9210764b457534d44fcf956e2fae5d6cfa8 | Python | 5,706 | 149 | from typing import List, Tuple
import torch
from pytorch_lightning import LightningModule
from timm.models.vision_transformer import vit_small_patch16_224
from torch import Tensor, nn
from torch.optim import AdamW
from lightly.loss import VISRegLoss
from lightly.models.modules.heads import ProjectionHead
from lightly... |
17414cbc771b293e4f37383dd4474a9cb61af85e5587978fd83dc083d4e881e8 | Python | 5,707 | 186 | import numpy as np
from numpy.random import default_rng
import pathlib
from mpi4py import MPI
from causal_optoconnectics.tools import conditional_probability, joint_probability, roll_pad
from causal_optoconnectics.generator import (
construct_connectivity_filters,
construct_connectivity_matrix,
simulate,
... |
3b8717eaa6b3d4383925f1e7cff96e61610793b16f7d7f5cbf3b63c7c5c79745 | Python | 5,708 | 148 | # Base MMVAE class definition
from itertools import combinations
import torch
import torch.nn as nn
import torch.distributions as dist
import torch.nn.functional as F
from src.utils import get_mean, kl_divergence
from src.vis import embed_umap, tensors_to_df
class MMVAE(nn.Module):
def __init__(self, prior_dis... |
0199fe2df5e9004932dc6221c98cf3ec4b99da8821894594a7ef28d7f1be6944 | Python | 5,709 | 161 | import pytorch_lightning as pl
import torch
from monai.losses import DiceLoss
from survival_plus_x.models.survival_plus_unet import VariableDepthUNet
class UNET(pl.LightningModule):
"""
Similar implementation as for Deep-MTS (https://arxiv.org/pdf/2109.07711v1.pdf),
using a Unet the segmentation model a... |
2871e4609291e23047138a9461474bfbb79c10da02618d16178e82d35f4dbfdd | Python | 5,709 | 145 | from __future__ import generators
import logging
import glob, os, functools
import sys
import SimpleITK as sitk
from scipy.signal import medfilt
import numpy as np
import math
from numpy import median
import scipy
import nibabel as nib
import skimage
import matplotlib.pyplot as plt
import scipy.misc
from scipy import ... |
a4d4943bbf35d7db5835d35e07beef7591507c088230dd0ef13b2fdb7c09adf2 | Python | 5,710 | 210 | """A data object for managing band definitions."""
from collections import OrderedDict
from specparam.reports.strings import gen_bands_str
###################################################################################################
##############################################################################... |
252c85ee4da8dc1964055cdad874fc5b493020f005432a324e3d9a56bc1bc221 | Python | 5,711 | 132 | import pandas as pd
import numpy as np
import os
import json,pickle
from collections import OrderedDict
import re
import csv
import esm
import torch
from rdkit import Chem
def generate_protein_pretraining_representation(dataset, prots):
data_dict = {}
prots_tuple = [(str(i), prots[i][:1022]) for i... |
18aca4fc05b587ae2e1094fe54e23ed76a2c035a7f3bf9c0dae0f7c65429bac8 | Python | 5,712 | 181 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on July 2022
@author: Simon Delarue <sdelarue@enst.fr>
@author: Thomas Bonald <bonald@enst.fr>
"""
from abc import ABC
from typing import Union
import numpy as np
from collections import defaultdict
from scipy import sparse
from sknetwork.gnn.loss import Bas... |
764dc5bb3989ad802d40fb41ab389e55dc1c5f882f81b6c3041bd9a032f98df0 | Python | 5,712 | 151 | """Event receiver implementation."""
import time
from operator import itemgetter
from kombu import Queue
from kombu.connection import maybe_channel
from kombu.mixins import ConsumerMixin
from celery import uuid
from celery.app import app_or_default
from celery.exceptions import ImproperlyConfigured
from celery.utils.... |
b14d07673c7df1f031c9c7388f00f6280ebc5112eb0adaa72ba7ff8acfed4b23 | Python | 5,712 | 144 | """Set of wrappers for normalizing actions and observations."""
import numpy as np
import gym
# taken from https://github.com/openai/baselines/blob/master/baselines/common/vec_env/vec_normalize.py
class RunningMeanStd:
"""Tracks the mean, variance and count of values."""
# https://en.wikipedia.org/wiki/Algo... |
c6aa6cef19cece28cbdff0c4f793a316a336c59c3b8978c9e73c11803b5926fb | Python | 5,713 | 177 | import multiprocessing as mp
from collections import OrderedDict
from multiprocessing import Array, Process
from multiprocessing.sharedctypes import SynchronizedArray
import numpy as np
import pytest
from gym.error import CustomSpaceError
from gym.spaces import Dict, Tuple
from gym.vector.utils.shared_memory import (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.