sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
6bba843474f4cf846e004fef2beb9945c8b9abc5a71e5c2f28fba8b70f4e5e23 | Python | 5,091 | 152 | """
Test that verifies the package includes all necessary data files.
This test should be run against the installed package, not the source.
"""
from importlib import resources as importlib_resources
import pandas as pd
import pytest
from codecarbon.input import DataSource
def test_critical_data_files_included():
... |
8cd32625e7d83c40da67a34ca1243c7ec862fa563e427c2e5c618cc380bc5382 | Python | 5,094 | 153 | """Segmentation Utils"""
from PIL import Image
import mxnet as mx
from mxnet.gluon import HybridBlock
__all__ = ['get_color_pallete', 'DeNormalize']
def get_color_pallete(npimg, dataset='pascal_voc'):
"""Visualize image.
Parameters
----------
npimg : numpy.ndarray
Single channel image with sh... |
3cd7d17bef6a2b37b975e174a9a08c32f3a7da508b25dcbc6e8eed6c3eb0b398 | Python | 5,095 | 146 | # LICENSE
#
# _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._
#
# BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License");
#
# - you may not use this software except in complian... |
af0a588a04db33ba66a99a1c811bd27e9a2c8976a0b3a7e70cb1717699672026 | Python | 5,095 | 133 | import copy
import datetime
import logging
import logging.handlers
import os
import platform
import sys
import colorlog
import numpy as np
import yaml
def maybe_create_path(path):
if not os.path.exists(path):
os.makedirs(path)
return path
def get_platform_specific_value(platform_specific_values):
... |
33702ce82c53adf9b557448776747746cc38758473a7e68b7d0c29de6ae6523c | Python | 5,096 | 151 | """Couchbase result store backend."""
from kombu.utils.url import _parse_url
from celery.exceptions import ImproperlyConfigured
from .base import KeyValueStoreBackend
try:
from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import Cluster
except ImportError:
Cluster = PasswordAuthent... |
2027f195dd6ec69e0212b172f5a00744f17b99cc78a509072424b2e8ad55b95a | Python | 5,099 | 156 | #!/usr/bin/env python3
"""
Apply a calibrated diameter scaling factor to an SWC morphology.
Last updated: 09.04.2026
Author: Laura Keto
Description
-----------
This script applies a uniform diameter scaling factor to an SWC morphology
by multiplying all node radii by the specified value and writing the result
to a ne... |
3f035e4ab0f0691ef3bb6da71ccadc57380df6a2c2ef32945f45edc19d5b885b | Python | 5,099 | 183 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
from external_src.group_free_3D.utils.pc_util import bbox_corner_dist_measure
# boxes are axis aigned 2D boxes of shape (... |
594c8442031c24e0ac93df6f971ba996f32891b96898e0e045c279ca0441ede5 | Python | 5,100 | 165 | """Prioritized Experience Replay DQN."""
import argparse
from collections import OrderedDict
from typing import Tuple
import numpy as np
from pytorch_lightning import Trainer
from torch import Tensor
from torch.utils.data import DataLoader
from pl_bolts.datamodules import ExperienceSourceDataset
from pl_bolts.losses.... |
0f704222ea56ab7e9e33e95e0e14945ee7d39d95809e80a3eca192d1d05e00b0 | Python | 5,103 | 134 | from keras.src import backend
from keras.src.api_export import keras_export
from keras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layer import ( # noqa: E501
BaseImagePreprocessingLayer,
)
from keras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layer import ( # ... |
03606d4b9f537160e2cb9b029ba7c622f125b71201f37ab7480540c502b4d042 | Python | 5,108 | 164 | from typing import Sequence, Optional, Tuple
import torch
import torch.nn as nn
import sys
from src.layers.openfold.model_utils import OuterProductMean, PairTransition, DropoutRowwise, \
TriangleMultiplicationOutgoing, TriangleMultiplicationIncoming, TriangleAttention
from src.layers.openfold.tensor_utils... |
4f05701f6022623171d91a1c448c044a6027e72497adca083ed34de8fa903e7e | Python | 5,109 | 114 | import itertools
import json
import os
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from angorapy.common.const import PATH_TO_EXPERIMENTS, QUALITATIVE_COLOR_PALETTE
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.ins... |
69950e6119273ab8b2c43f79194fa5dc81d3cfd1be30785844e4046d3ed57676 | Python | 5,109 | 129 | """ Utility module with functions related to R packages
(having these in this utility module rather than in packages.py
prevents circular imports). """
from rpy2 import rinterface
from warnings import warn
from collections import defaultdict
_packages = rinterface.baseenv['.packages']
_libpaths = rinterface.baseenv['... |
f30d17f686bb005c8a5cff00d03b0a4d9e310749e64991b895d611804d67e338 | Python | 5,109 | 96 | import pytest
import numpy as np
from ...utils import constants
import geopandas as gpd
from ...core.flowdataframe import FlowDataFrame
import folium
# tessellation
tess_features = {'type': 'FeatureCollection',
'features': [{'id': '0',
'type': 'Feature',
... |
50973553fc70dc8c35b22fbb87cdb045210b060e3cd8946bc627f0951197ba10 | Python | 5,110 | 130 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... |
b3611b4e6db5f31976057fc2e40280fdf5d58f7d4a3c1e7d36842def1fff096e | Python | 5,110 | 146 | __author__ = 'quentin'
import mysql.connector
import sqlite3
import os
import logging
class MySQLdbToSQlite(object):
def __init__(self, dst_path, remote_db_name="psv_db", remote_host="localhost", remote_user="root", remote_pass="", overwrite=True):
"""
A class to backup remote psv MySQL data base... |
2eeec6a09aeea224d06b41111832ea816f95735d3e4cc38704dc29119001eb48 | Python | 5,111 | 150 | """Regression tests for atomic ``Bundle.save(overwrite=True)`` (r18n / H1).
A failed overwrite must never destroy the user's existing good bundle. The
writer moves the old bundle aside to a sibling backup, swaps the freshly
written bundle into place, and only then removes the backup; any error before
or during the fin... |
a356b443ffcb6e9097afe380688bbdc94b3283f1d1a8987879843b1ac4caa705 | Python | 5,112 | 117 | #!/usr/bin/python
'''
airPLS.py Copyright 2014 Renato Lombardo - renato.lombardo@unipa.it
Baseline correction using adaptive iteratively reweighted penalized least squares
This program is a translation in python of the R source code of airPLS version 2.0
by Yizeng Liang and Zhang Zhimin - https://code.google.com/p/air... |
01bb4ead94a00ede04dc723aadb991719bc739ee30e7111587b84aaa43dcd1ef | Python | 5,113 | 168 | from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
import pandas as pd
from larvaworld.lib.process.dataset import DatasetConfig, LarvaDataset
from larvaworld.lib.sim.manifest import RunManifestSession, append_dataset_lineage
def test_dataset_config_provenance_roundtrip() ... |
d19e2b1e6248fcb71f4dc3e0445e3f257fef9685955c26a53cfdf040c2fe3c8e | Python | 5,113 | 160 | """Tests for the TorchLens auto-route registry."""
from __future__ import annotations
from typing import Any
import pytest
from torch import nn
import torchlens as tl
from torchlens.autoroute._registry import Registry
class _NoForwardModel(nn.Module):
"""Minimal model used for registry-dispatch tests."""
... |
752f48010a5aec06214d3f468165d1ae2fe5336348b5198d499489ef6791d04d | Python | 5,114 | 133 | import os
import numpy as np
import pandas as pd
import copy
from tqdm import tqdm
from typing import Tuple, Dict, Sequence
from bioconfpred.conf_ensemble import (ConfEnsembleLibrary,
ConfEnsemble)
from bioconfpred.evaluator import RankerEvaluator
from bioconfpred.model import (... |
db984c733aecb963a58d8bb0493855723089874f15ad5ac71d66bd6543fe497c | Python | 5,114 | 147 | import glob
import numpy as np
import argparse
import yasa
from mp_dip.utils.data_preprocessing_utils import convert_montage_channel_nr_to_raw
from tqdm import tqdm
import pickle
from mp_dip.obci_readmanager.signal_processing.tags import tags_file_writer as tags_writer
from mp_dip.utils.utils import TAG_DEFS, preana... |
cbbdde8507430bb3306e52158f6159bc0fd5ecf9c5621d320c1df08b7339b0c7 | Python | 5,115 | 154 | from grpc import RpcError
from minknow_api import keystore_service
from bream4.device_interfaces.devices.base_device import BaseDeviceInterface
from bream4.pb.bream.mux_scan_results_pb2 import MuxCategory, MuxGroup, MuxScanResults, Result, Style
KEY_STORE_NAME = "bream.MUX_SCAN_RESULTS"
COLOURS = {
"single_pore"... |
ceaf1d1a381368442a20e65271631a64d2ab06ac084ba3bcfa626557ecc4d805 | Python | 5,116 | 103 | import torch
from torch import nn
from torch import Tensor
from collections import OrderedDict
import numpy as np
class GetDensity(torch.nn.Module):
def __init__(self,rs,inta,cutoff,nipsin,norbit,ocmod_list):
super(GetDensity,self).__init__()
'''
rs: tensor[ntype,nwave] float
inta:... |
222c4f214177f7feb87f8aa1dcf5c98ba6f250358b92d5823703a0d1145a84bc | Python | 5,117 | 207 | import numpy as np
def _get_eigenvals(X):
"""Private function to compute all eigen values."""
n = X.shape[-1]
return np.linalg.eigvals(X.reshape((-1, n, n)))
def is_square(X):
"""Check if matrices are square.
Parameters
----------
X : ndarray, shape (..., n, n)
The set of square... |
668bdabe491f1edb2f34a6b77a9e060086211cd36dac6d2270cb9767777447c6 | Python | 5,117 | 150 | import sys
import argparse
from acdc_nn import util
from acdc_nn import nn
import numpy as np
import pandas as pd
from pkg_resources import resource_filename
#@functools.lru_cache(100) # memory cache to avoid reloading the same protein data multiple times
def load_prot(profile_path, pdb_path=None, chain=None):
if ... |
f9782db6e91f34f5deb66661e0864151880d594b63e78c2d2414209b802dd4db | Python | 5,118 | 150 | """
Functions to calculate the upper limit for long-read SV depth coverage.
Copyright (C) 2021 Tham Cheng Yong
This file is part of NanoVar.
NanoVar is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either versio... |
54826cc50ceb7353fe31e06cfe6ab4c4a5b17e2caaaf067a37df91903f712e7d | Python | 5,120 | 146 | """Bundle value-diff tests (memo D15, B9).
Aligned D2 ids make Model Explorer's own sync machinery do the matching;
``bundle_delta`` node data upgrades presence-diff to numeric deltas; mapping
entries exist ONLY for legacy-id nodes (with the fallback disabled so
accidental id equality cannot lie); missing values are c... |
114761fac04a8e643ddc3478a8519a7ed800f02c6c627b308901bc09a1dda689 | Python | 5,121 | 167 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
from pprint import pprint
import physio
base_folder = Path('/home/samuel/Documents/physio_benchmark/dataset_716/experiment_data/')
cases = ['hand_bike', 'jogging', 'maths', 'sitting', 'walking']
def plot_one_subject... |
3496037275158ae3892e5608414a87e4d2bf0c1fa44567d9180cab8b4379dfed | Python | 5,121 | 148 | from keras.src import backend
from keras.src.api_export import keras_export
from keras.src.optimizers import optimizer
@keras_export(["keras.optimizers.Adadelta"])
class Adadelta(optimizer.Optimizer):
"""Optimizer that implements the Adadelta algorithm.
Adadelta optimization is a stochastic gradient descent ... |
a002422498c81f866612288e6d78cdbd64e33a293a89e91258c640ecfdc861db | Python | 5,121 | 127 | """The duration tripwire's load measurement (tests/conftest.py).
Budgets are compute budgets in reference-host seconds. The slowdown factor is
measured with a fixed CPU-bound probe instead of ``loadavg / cpu_count``, and
torch runs one intra-op thread per test process. These tests pin both halves
of the contract: a ge... |
19cf09c2733165ccf35b2f6aac2e47a6c36a6d2f88eb32f71b5bbcc42e13cdb5 | Python | 5,122 | 158 | import numbers
import numpy as np
import pyqtgraph as pg
from .. import mask
from .base import BaseShape, rotate_around_point
class Ellipse(BaseShape):
def __init__(self, x=43, y=12, a=25, b=15, phi=0, point_um=1):
"""Ellipse
Parameters
----------
x, y: float
center... |
21f0674c9f5a99d7c339092e49d5822d387b0a4673888becff1ac073cb5ac619 | Python | 5,122 | 151 | """
System ptxas replacement for CUTLASS DSL.
Environment variables:
CUTE_DSL_PTXAS_PATH - Path to ptxas (e.g., /usr/local/cuda/bin/ptxas)
CUTE_DSL_PTXAS_VERBOSE - Set to 1 for verbose output
"""
import os
import sys
import re
import ctypes
import subprocess
from pathlib import Path
import cutlass
CUTE_D... |
d623cd0a55d257b918c27bfa224fa3413d9c7646782c621ea06f6d922d3f9357 | Python | 5,122 | 159 | """
Unit tests for core variable types.
Tests variable classes used for type-safe storage of tracking data.
"""
import unittest
from unittest.mock import Mock
from ethoscope.core.variables import (
BaseIntVariable,
BaseRelativeVariable,
HeightVariable,
IsInferredVariable,
Label,
PhiVariable,
... |
0a9a0793ba665930abf769da4eeea8e2ada52ea1566878202acf08213211ec8c | Python | 5,123 | 147 | """CardTree IR + safe renderer tests (lane C05; treescope memo B1).
Pins the presentation-only IR contracts: typed-leaf escaping, the
never-raise boundary, budgeted collections with disclosed truncation,
versioned scoped CSS on themes tokens, native ``<details>`` folding,
clipboard keys with click-to-select degradatio... |
54259dbee91285071af337fbf555d3497f3f96f2aca57491082983d12f4cd1f8 | Python | 5,123 | 134 | ####################################################################################################
# Translated from matlab: https://github.com/MICA-MNI/micaopen/blob/master/MPC/scripts/build_mpc.m
# Original script by Casey Paquola
# Translated to python by Jessica Royer
# build_mpc Construct a microstructure pr... |
ca3ef899f6daa754c8a08c8fee68830c340edc1c79cba24c481a313378b23d37 | Python | 5,123 | 145 | """A06 capture-options truth: train-mode running-stat mutation is disclosed.
WALKTHROUGH list-A row 30: train-mode tracing silently mutated BatchNorm
running statistics -- the forward REALLY runs, so ``running_mean`` /
``running_var`` advance under momentum (even inside ``torch.no_grad`` or
``inference_only=True``) wi... |
ee61e04db9889094ade442a27f0d65e40236424ab0641d029ffd1bd86e65cf71 | Python | 5,124 | 170 | import http.server
import socketserver
import threading
import os
import asyncio
import websockets
import sys
import json
import tempfile
class Server:
def __init__(self,port=None,tempname=None):
self.connections={}
self.wsport=9000
self.httpport=None
if (port != None):
... |
0832b216b9e5b76494f1511455741404c5876f31744e2173d2dadb09b20bf81e | Python | 5,125 | 137 | """r35 corr2_7 (I3): numeric attestation is downstream of the settled path verdict.
``attested`` implies ``verified`` and unpoisoned -- structurally. Any failed
contract check or ceiling caps attestation at ``not_applicable`` before a single
archive byte is read, and the report constructor makes the contradictory
comb... |
5206459581ac3fb18392cd392b66843732749c0f6c60410788fa178a84f43dc7 | Python | 5,125 | 127 | import requests
import re
import time
import os
import requests
import pandas as pd
from tqdm import tqdm
from multiprocessing.pool import Pool
# About 35 sec per pred then ~70H for all test seq
# Sometime no prediction:
# answer_content: b'Feature files not generated!!! <br /> If you are inputting file, please first... |
6618e5559a4c0e1bb21b2a8824eabf14b3a18a35981851f93349e0876e2f4901 | Python | 5,125 | 123 | import torch
import torch.nn as nn
import torch.nn.functional as F
from optical_unit import NonLinear_Int2Phase
class ChannelRepeat(nn.Module):
def __init__(self, k):
super().__init__()
self.k = k
def forward(self, input_field):
return input_field.repeat([1, self.k, 1, 1])
class Channe... |
0f3c397b37f5a99a92295406a596bdf41544509c68119d10abbb97ca4023269a | Python | 5,126 | 161 | """
Network utilities for ethoscope_node.
This module provides network-related utility functions for discovering
and managing network interfaces and IP ranges.
"""
import ipaddress
import logging
import netifaces
logger = logging.getLogger(__name__)
def get_primary_private_network() -> str | None:
"""
Get... |
e3078ac28343328165de69df0479b3d6fa561d1a635cfc41a95b1b797e78dbfe | Python | 5,127 | 125 | # Spitfire - a Python-C++ library for building tabulated chemistry models and solving differential equations
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
#
# You should have received a copy of the 3-clause BSD License ... |
0c9479ddf9175f2a6f6556e8dcfae3fa4f1693ba2648e2a3bdc57640cea1d4ee | Python | 5,128 | 152 | import torch
from torch import nn, optim
from torchmetrics import MeanAbsolutePercentageError
import torch_geometric as tg
from torch_geometric.loader import DataLoader
from typing import List, Optional, Union
import matplotlib.pyplot as plt
import shutil
import sys
from datetime import datetime
import argparse
# My im... |
fbb2f52bb30ab7a93996d9e1c9475ef275752f52def93ab0014ea3ff74af7581 | Python | 5,130 | 157 | import numpy as np
import scipy.sparse as sp
import scipy.spatial as spatial
from anndata import AnnData
from scipy.stats import pearsonr, spearmanr
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
from tqdm import tqdm
from stlearn.types import _METHOD, _SIMILARITY_MATRIX
def _make_simila... |
587afb548b0c6025af28b0f8e4e02e44bc691f3cef12fce1616d77fd026faa3a | Python | 5,131 | 160 | #!/usr/bin/env python3
"""
File: create_histplot.py
Created: 2021/11/11
Last Changed:
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.
"""
#... |
9bce654769d8e1bb55821f5bb6cb7370aa91b1dbf73dfcf849138835874a7b55 | Python | 5,131 | 132 | from ...utils import constants
import pandas as pd
import geopandas as gpd
import numpy as np
import shapely
import pytest
from contextlib import ExitStack
from ...core.trajectorydataframe import TrajDataFrame
from ...models.gravity import Gravity
from ...models.epr import EPR, DensityEPR, SpatialEPR, Ditras
from ...m... |
68c92e11b163f2a2c39342accc8512cc65bb2b95bcdbb5415d43679787ad1672 | Python | 5,132 | 136 | import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np
class Evalulate:
def __init__(self, x, y, istart, istop, case_num):
# x:预测结果 y:label len:样本长度
self.len = case_num
self.x = x[:self.len]
self.y = y[:self.len]
self.MSE = nn.MSELoss()
... |
045feb62c37a56417907e575806dcdad9d5e99a8c27d508579c31eb330f95324 | Python | 5,133 | 127 | import copy
from itertools import zip_longest
from typing import Any, Callable, Dict, List, Optional
from pytorch_lightning import LightningModule, Trainer
from pytorch_lightning.callbacks import Callback
from pytorch_lightning.utilities import rank_zero_info
class PrintTableMetricsCallback(Callback):
"""Prints ... |
17204cc97803ef29ed0e936b712fbd17ca645cdb5eec24438387a4c4352da0bf | Python | 5,135 | 138 | #!/usr/bin/env python3
"""Subject/trial accounting for the manuscript's exclusion table."""
import argparse
import glob
import os
import re
from collections import Counter
RETAINED = {"healthy": {"subjects": 87, "trials": 3076},
"stroke": {"subjects": 46, "trials": 1758}}
HEALTHY_RUNS = ["R04", "R08", "R... |
e201d1c28f09071acbc355fbab9158f3ac9fee935b5da82d538136290180b69a | Python | 5,137 | 110 | """
This pipeline saves covariance matrices for each participant for both target and standard stimuli.
"""
import os
import numpy as np
from scipy.signal import hilbert
from tools_external import compute_ged, compute_patterns
from tools_general import save_pickle, load_pickle, load_json, list_from_many
from tools_lifed... |
40f74ac7471879a7e5424ac6e6c537d2c4b9fea7361f2f77279b0606743349c7 | Python | 5,139 | 157 | from functools import cached_property
import numpy as np
import attr
from modular_splicing.utils.sequence_utils import all_seqs, draw_bases, parse_bases
CODON_TO_ID = np.array([1, 4, 16])
_STANDARD_CODON_TABLE = [
["UUU", "UUC"], # Phe/F
["CUU", "CUC", "CUA", "CUG", "UUA", "UUG"], # Leu/L
["AUU", "AUC"... |
f3364f31030a9b0fffc8c24eda5623e04aee8a9b024afd3bd8554859e373f172 | Python | 5,139 | 161 | """
Adapter driving a dataset import into the workspace.
Orchestrates the existing import backend and places the result in the
workspace's processed-data folder.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from larvaworld.lib import reg
from larvaworld.portal.datasets.mode... |
1cd5e57150d8323f93d382f16063b168e154316e3e065039c283fcaed27a03a6 | Python | 5,140 | 153 | """Tests for smoothing methods."""
import os
import re
import tempfile
import numpy as np
from nipype.pipeline import engine as pe
from templateflow.api import get as get_template
from xcp_d.interfaces.nilearn import Smooth
from xcp_d.interfaces.workbench import CiftiSmooth
from xcp_d.utils.utils import fwhm2sigma
... |
bd776c1085b80d2d57036b98155cd11af4dc65a8d523039bdcd7a4678251e6ed | Python | 5,140 | 130 | # FAITHFUL PORT of TerrisGO/PilotNet @ master (original framework: TensorFlow 1.x)
#
# PilotNet (Bojarski et al., NVIDIA 2016 "End to End Learning for Self-Driving Cars"). The
# named repo (a fork of lhzlhz/PilotNet, itself sourced from SullyChen/Autopilot-TensorFlow)
# implements the network in raw TF1 graph-mode with... |
5ffa0f56248588cf98421d81651307170f72cc1d6076c339f0a798676fa0bee5 | Python | 5,141 | 166 | """This module contains simple helper functions """
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
import importlib
import argparse
from argparse import Namespace
import torchvision
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in... |
84fe5d1801618e13b934a2b41b5f85499e04279444b15e4a6d8e4f761933f62c | Python | 5,141 | 126 | # type: ignore
from abc import abstractmethod
from copy import deepcopy
from typing import Any, Optional
import torch.nn as nn
from pytorch_lightning import Callback
from pytorch_lightning.core.lightning import LightningModule
from pytorch_lightning.utilities import move_data_to_device, rank_zero_warn
from pytorch_lig... |
b4c669d1dc73fd7f4c71df30773b92e67f69b39f9959eb87b9523f344460f700 | Python | 5,142 | 157 | """W051-EXTRACT: a fresh run into a used directory leaves no stale shards (audit 4.7),
and the DEFAULT safetensors codec survives a hard process death mid-write.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import textwrap
from pathlib import Path
import pytest
import tor... |
93a013e893f4e189b666326baa95966197806a8a09c92ec33ff1b87634131345 | Python | 5,143 | 116 | from unittest import TestCase, mock
import numpy as np
import spateo.segmentation.utils as utils
from ..mixins import TestMixin
class TestSegmentationUtils(TestMixin, TestCase):
def test_circle(self):
circle = np.ones((3, 3), dtype=np.uint8)
circle[0, 0] = 0
circle[0, 2] = 0
cir... |
dff11edd2d85a2dc7d686885adc692642643ea39ef98507f2a8d1df54c34c87f | Python | 5,143 | 156 | import multiprocessing
import sys
from functools import partial
from typing import List, Optional, Union
import dynamo as dyn
import numpy as np
import ot
import pandas as pd
import scipy.stats
import statsmodels
from anndata import AnnData
from scipy.sparse import issparse
from tqdm import tqdm
try:
from typing ... |
4ae6448d631c4a17484ea6212f0df493b7004a20fdc44b5cff7eea77b170d128 | Python | 5,144 | 155 | # coding=utf-8
# Copyright 2025 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... |
e391559ee4dfd3db3657830422f870b98da93ea6058e9a13d1f4f46f7479739b | Python | 5,144 | 127 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created in July 2022
@author: Thomas Bonald <thomas.bonald@telecom-paris.fr>
"""
from typing import Optional, Union
import numpy as np
from scipy import sparse
from sknetwork.classification.base import BaseClassifier
from sknetwork.path.distances import get_distances... |
b499a225d1f7bd108c708c08725e1434d9e4b34d1c781372dca13ca5e375f067 | Python | 5,145 | 149 | """
#--------------------
Created on 2021.11.04
Version 1.0
__author__ = 'Xx'
#--------------------
"""
'''
Description:
subroutine which computes the bi-dimensional linear or quadratic interpolation (lagrange form) of
a given value to a table of scan angle and 11um brightness temperature depen... |
04476182bef2c61607e8f581448f3956d24efbcc3738c4723c7995872bf700c1 | Python | 5,147 | 138 | """Module-boundary intervention evidence must survive attr-rejecting tensors.
grind-p3-fixplan T3 (fix-patching lane, HIGH): the module-boundary live-hook
dispatcher attached its fire results and replaced-parent provenance to the
replacement tensor with a bare ``setattr`` under ``except: pass``. A
replacement tensor t... |
946104dc7b1972f36fce1bf1bb356b0bb699688ee18d94007d0cdcca81c5906f | Python | 5,147 | 132 | """Legacy ``torch.nn.utils.weight_norm`` records ``_weight_norm`` in every capture.
``torch/nn/utils/weight_norm.py`` binds ``from torch import _weight_norm`` at
``import torch`` time, and its ``WeightNorm`` forward pre-hook calls that module
global on every forward. Before the alias was tracked in
``_TORCH_SUBMODULE_... |
d062b111777491e2968d51a81e4a1fec73e4d61314c3db7355348ed9c4275c63 | Python | 5,147 | 142 | # MIT License
# Copyright (c) 2018 Adrian Wolny (https://github.com/wolny/pytorch-3dunet)
# 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 without limitation t... |
4ae1fbaa8f73ecd3b2021c5548db8b26cdd12eec8e0f5d4c962bb3ab5008ffbc | Python | 5,149 | 167 | """F39 unhide gates: promoted surface pins + the unhide teaching ratchet.
Lane F39 (WALKTHROUGH B-IV) promotes the shipped-but-hidden surfaces into the
declared story: ``tl.stats``/``tl.aggregate`` enter ``__all__`` (conflict-ledger
row 8 -- the promotion five memos claimed), and README/docs surface
``trace.profile()`... |
378f1d60801a3f181d01741d831c9243fbf5e6b97b1eb4c89c5c8a1c61213cc1 | Python | 5,150 | 156 | import preprocessing.reader as reader
import numpy as np
class Tile(object):
"""
A class to represent one patch/tile of a WSI
Attributes
----------
position : tuple (int, int)
The position of the Tile in the WSI in pixel (x, y)
size : tuple (int, int)
The size of the tile in p... |
434d7484c10b527e4caf78da3713411f16517b5b2430928fa197bb85e4c91257 | Python | 5,151 | 159 | """Regression tests for render-flow reverse-index reuse."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
import pytest
import torch
from torch import nn
import torchlens as tl
from torchlens.data_classes.trace import Trace
from torchlens.visualization import _render_... |
021783d386067771b83e41d3ca5a5468a02251f3b5b947b40802e116c7110012 | Python | 5,152 | 110 | #=========================================================================
#
# Copyright NumFOCUS
#
# 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/license... |
35ec8a7a50f1782a568c5ab736c6272ca22ea6d6e3715f60d19ea4bdf4ad777d | Python | 5,152 | 150 | import os
from torch.utils.data import Dataset as TorchDataset
import torch
import numpy as np
import pandas as pd
import librosa
from datasets.helpers.audiodatasets import PreprocessDataset, get_roll_func
# specify ESC50 location in 'dataset_dir'
# 3 files have to be located there:
# - FSD50K.eval_mp3.hdf
# - FSD50K... |
f17c9be535d82db66d5ca51f11f28d7292f453129281a1117addde8e4614c91e | Python | 5,152 | 145 | """
Predict images using AI models from BioImage.IO
"""
import argparse
import imageio
import numpy as np
import torch
import torch.nn.functional as F
def dynamic_resize(image: torch.Tensor, target_shape: tuple):
"""
Resize an input tensor dynamically to the target shape.
Parameters:
- image: Input... |
f9d89e7833744dec591073ea2d0708e4f756453ad091a86edc06237ef72a6ff7 | Python | 5,152 | 140 | import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data
from src.getdata import getdata_from_csv
from src.utils import DrugTargetDataset, collate, AminoAcid, ci, r_squared_error
from src.models.DAT import DAT3
parser = argparse.ArgumentParser()
parser.add_argument('--cuda', defau... |
a8916a941daebe9048de3c8b71bc3273d9d9be5769515dd0394844f37adfcf7b | Python | 5,153 | 145 | import torch
from torch import nn, optim
from torchmetrics import MeanAbsolutePercentageError
import torch_geometric as tg
from torch_geometric.loader import DataLoader
from typing import List, Optional, Union
import matplotlib.pyplot as plt
import shutil
import sys
from datetime import datetime
# from easydict import ... |
393e8f39d80893e285a991e316623135b206a5a1d035f30629c6c4ab9f38709b | Python | 5,154 | 139 | import os
import pandas as pd
from rdkit import Chem # safe import before ccdc imports
from multiprocessing import Pool, TimeoutError
from typing import Tuple
from bioconfpred.data.utils import MolConverter
from bioconfpred.params import (BIO_CONF_DIRNAME,
GEN_CONF_DIRNAME,
DAT... |
bf0cbd7e43bd7e03fca9b3988d97df8f072f2c08e13f91eb66aeb26ddf2ae596 | Python | 5,154 | 163 | import torch
import torch.nn as nn
from torch.nn import functional as F
class MainFrame(nn.Module):
def __init__(
self,
img_dim,
img_time,
in_channel,
f_maps=[16, 32, 64],
input_dropout_rate=0.1,
num_layers=0
):
super(... |
e3a24e43b389b91a0fb20e02db3db5f94422defdd2ebeebb514a3922fbdf5f4a | Python | 5,156 | 153 | import math
import torch
from torch_geometric.nn import radius_graph
from torch_scatter import scatter_min
from dig.threedgraph.method.comenet import ComENet
from .atomistic_nn import AtomisticNN
class AtomicComENet(AtomisticNN, ComENet) :
"""
Modification of the DIG ComENet implementation to recover the atom... |
0218b5d5d643837d8e3aaf3ac97e05d40d864b37c9ee2465e8a9f0b30a2d142b | Python | 5,158 | 155 | """Hierarchical reasoning tasks."""
import numpy as np
from neurogym.core import TrialEnv
from neurogym.utils import spaces
from neurogym.utils.ngym_random import TruncExp
class HierarchicalReasoning(TrialEnv):
"""Hierarchical reasoning of rules.
On each trial, the subject receives two flashes separated by... |
8a44a0ae4350cb47f2aec5b62b2fda6b6b485982770ac0b8e69dd37fe1f6f357 | Python | 5,159 | 151 | from string import Template
import tempfile
import subprocess, signal, logging, os, stat, sys
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
raise Alarm
def setupLogging(debug=False):
logLevel = logging.DEBUG if debug else logging.INFO
logFormat = "%(asctime)s [%(levelname)s] %(me... |
a9d79cc248d1841d85d649005c86b413b2f12c761fbc43f4c6f4de393dfe67b6 | Python | 5,159 | 130 | """W051-STOCH / AUD-CODE 3.8: the live door derives the SAME coordinate as the replay door.
Capture-time ``intervene=`` used the raw ordinal label as the firing
coordinate, so a seeded stochastic edit drew different donors live vs on
replay and the draw shifted whenever an unrelated upstream op was added. The
live doo... |
ffbd386bd290d8f727203f2e315ef26788208c6961d73647e60b33b9ee83d5b2 | Python | 5,159 | 124 | # Copyright (c) 2023, Tri Dao.
import math
import re
from collections import OrderedDict
import torch
import torch.nn.functional as F
from einops import rearrange
from transformers import GPT2Config, GPTNeoXConfig
def remap_state_dict_hf_gpt_neox(state_dict, config):
def key_mapping_layers(key):
return ... |
346ac1d1166a35be40b31fd00ef1f140c0c31e2bb532532a145cfe6b2560528c | Python | 5,160 | 103 | """Prepare PASCAL VOC datasets
==============================
`Pascal VOC <http://host.robots.ox.ac.uk/pascal/VOC/>`_ is a collection of
datasets for object detection. The most commonly combination for
benchmarking is using *2007 trainval* and *2012 trainval* for training and *2007
test* for validation. This tutorial ... |
95bc4349328612cd02d2360cfdb6f2c3e6918c9b3f71e518c26e9b9eb35ccbec | Python | 5,161 | 160 | """F10 golden-specimen corpus + ascii==degrade sweep (the row gate).
Every specimen is GENERATED by the real formatter (D33) -- the byte pins
below were produced by the code under test on fully deterministic inputs
(arange-built tensors and an elementwise model, so no reduction-order or
RNG dependence) and then frozen... |
2350d41b79bcdf656338d1c1d043f097ea0f77a069aa8e75e91be1016d768e07 | Python | 5,162 | 157 | from keras.src import backend
from keras.src.api_export import keras_export
from keras.src.optimizers import optimizer
@keras_export(["keras.optimizers.Adamax"])
class Adamax(optimizer.Optimizer):
"""Optimizer that implements the Adamax algorithm.
Adamax, a variant of Adam based on the infinity norm, is a fi... |
3f4ba7de2a9b9c52eb05b60e0f39d502853f276a8066ea8700f2e269ed0b0ad2 | Python | 5,162 | 180 | #!/usr/bin/env python3
# coding: utf-8
"""
Created in April 2022
@author: Simon Delarue <sdelarue@enst.fr>
@author: Thomas Bonald <bonald@enst.fr>
"""
from typing import Union
import numpy as np
from sknetwork.gnn.base_activation import BaseLoss
from sknetwork.gnn.activation import Sigmoid, Softmax
class CrossEntr... |
7241694cb199a4c24f2a06caf1b339d3b4d4d62aeae68186c408bf1ab20d2c64 | Python | 5,162 | 141 | #!/usr/bin/env python3
"""
File: merge_PICALO_result_groups.py
Created: 2021/11/24
Last Changed:
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 t... |
8540d886467e4db9c78baacc0ffe341ddd1948d415767e024bb5c3e7271ebf2d | Python | 5,163 | 137 | import numpy as np
import pytest
from absl.testing import parameterized
from keras.src import layers
from keras.src import ops
from keras.src import testing
from keras.src.testing import test_utils
class AdditiveAttentionTest(testing.TestCase):
def test_attention_basics(self):
# No scale
self.run... |
2b59281a9b0593702b95802c02b05b0b7bdfd234a7c1b0ce83f081225aaeb105 | Python | 5,164 | 180 | import typing
from docutils import nodes
from sphinx.errors import NoUri
APPATTRS = {
'amqp': 'celery.app.amqp.AMQP',
'backend': 'celery.backends.base.BaseBackend',
'conf': 'celery.app.utils.Settings',
'control': 'celery.app.control.Control',
'events': 'celery.events.Events',
'loader': 'celery... |
2f464858aa523f8e257046e2542cd54fdba7ff98053005ba72f9d2dca1dc6fe0 | Python | 5,164 | 116 | # Copyright (c) 2023, Tri Dao.
import math
import re
from collections import OrderedDict
import torch
import torch.nn.functional as F
from transformers import GPT2Config, OPTConfig
def remap_state_dict_hf_opt(state_dict, config):
def key_mapping_model(key):
key = re.sub(r"^model.decoder.", "transformer.... |
c686ee4371d01d523a9521e47376231ee4c9e1a733ed66ba07d17ccb6f2572b1 | Python | 5,164 | 148 | import torch
from typing import Dict
from rbm.binary.sampling import sample_hiddens, sample_visibles
def init_chains(
num_chains : int,
num_visibles : int,
num_hiddens : int,
device : torch.device
) -> Dict[str, torch.Tensor]:
chains = {}
chains["v"] = torch.randint(0, 2, size=(num_chains... |
e0bde3ce8d7d41a7b1f6eacfd93f19acf90ef06db15e6ab612d7edddfe77dda6 | Python | 5,164 | 137 | import csv
import os
import zarr
# d: DoubleColumn, for floating point numbers
# l: LongColumn, for integer numbers
# s: StringColumn, for text
# b: BoolColumn, for true/false
COLUMN_TYPES = ["d", "l", "s", "b"]
def parse_csv_value(value: str, col_type: str) -> str | float | int | bool:
"""Parse string value fr... |
a3f27c51896ceda540aeb8dd795b772bfa76a8ad84de8f4d2a59f48e91664b80 | Python | 5,165 | 127 | #!/usr/bin/env python3
"""
File: export_n_ieqtls.py
Created: 2022/06/04
Last Changed:
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.
"""
#... |
f2a6aad11cd9c480c3c9f1093b5e00427545acc2453b18b39152dadf6f88963f | Python | 5,165 | 139 | import argparse
import json
import os
import shutil
import sys
import pathlib
from sklearn.metrics import accuracy_score, recall_score, precision_score, classification_report, confusion_matrix
import numpy as np
from deep_audio_utils import prepare_dirs, deep_audio_training, validate_on_test, crawl_directory
sys.pat... |
e4dc1dde1ad291923a243918ee18e24ee819f980d0a85e35fe84be150282b27f | Python | 5,166 | 161 | def _swatches(module_names, module_contents, template=None):
"""
Parameters
----------
template : str or dict or plotly.graph_objects.layout.Template instance
The figure template name or definition.
Returns
-------
fig : graph_objects.Figure containing the displayed image
A ... |
1d484ab3d8b906120daaed28e95b7cfce29aeed59a0d574bd94209cf9bfeedfa | Python | 5,167 | 115 | """THE marker algebra -- declared ONCE, here (conflict rule 16).
Every pytest marker the suite declares in ``pyproject.toml`` has exactly one
ROLE in this closed algebra, and ``tests/test_marker_lint.py`` enforces the
lockstep both directions: a marker declared in pyproject without a role here
(or a role here without ... |
ae57f54130aa3f713fbfa30119ab88201f3fe7808149dba5b7a9bdb5d9976be0 | Python | 5,167 | 175 | import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import common
def make_model(args, parent=False):
return AAN(args)
def make_layer(block, n_layers):
layers = []
for _ in range(n_layers):
layers.append(block())
return nn.Sequential(*layers)
clas... |
6358dff4d70ab33dc51717c9278f0379d4144e3324f00fd7feb40fe8f193c9cd | Python | 5,168 | 153 | from collections import defaultdict
import os
import re
import functools
import numpy as np
from modular_splicing.psams.sources.rbns import read_rbns_motifs
from ..psams import PSAM
from .data_directory import DATA_DIRECTORY
RNA_COMPETE_MOTIFS_DIRECTORY = os.path.join(DATA_DIRECTORY, "motifs_rnacompete")
def rna_... |
7e6ddc0ae49718ab68ce014841659afe4f4c38ec6570cf5eff6d809461f3dba3 | Python | 5,168 | 125 | """Project bootstrap: creates the on-disk project layout and config files.
``prepare_project`` builds ``<dir>/config.yaml``, ``<dir>/run_info.json`` and
the ``analysis_files`` / ``visualizations`` subfolders used by the rest of the
pipeline.
"""
import yaml
from pathlib import Path
from datetime import datetime
fro... |
39032175c2431b7991452714e2c6c7b13d6ea3fee43aecae1568643189d24377 | Python | 5,169 | 115 | # MNIST-clevr multi-modal model specification
import os
import torch
import torch.distributions as dist
import torch.nn as nn
import torch.nn.functional as F
from numpy import sqrt, prod
from torch.utils.data import DataLoader
from torchnet.dataset import TensorDataset, ResampleDataset
from torchvision.utils import sa... |
81ab4fad507725ae977f835021494745298d59a5dbe01f611a358607847f7e4a | Python | 5,169 | 143 | import numpy as np
from typing import Union, Tuple
from pathlib import Path
ArrayLike = Tuple[np.ndarray, list]
import torch
from h5py import File
tokens_protein = "ACDEFGHIKLMNPQRSTVWY-"
tokens_rna = "ACGU-"
tokens_dna = "ACGT-"
def get_tokens(alphabet):
assert isinstance(alphabet, str), "Argument 'alphabet' mus... |
53c96af9ad9b06a40d0b5b5d8481fdda1876d51a2d0b7d8553c4a5c6cfbf59d4 | Python | 5,171 | 98 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.