sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
ab5f7c78a0985673b0ffd44ccf0fac44d804fb92d59eadf32ade83672053a594 | Python | 12,359 | 327 | from __future__ import annotations
from typing import List, Optional, Any, Dict
import torch
import torch.nn.functional as F
import torch_geometric.nn as geomnn
from torch.nn import Linear, LSTM
from torch_geometric.nn import MessagePassing, global_mean_pool, GATConv, GATv2Conv
from torch.nn import ModuleList, Dropout... |
ece2c9947fb0c0edbde9318be20804657b35aefd42ff930ccf13f4a0587037bf | Python | 12,360 | 328 | import json
import numpy as np
import sys
import pandas as pd
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import ModelCheckpoint
from torch.utils.data import DataLoader, WeightedRandomSampler
from pathlib import Path
from pprint import pprint
from survival_plus_x.data.dataset import ... |
7160a184b3b39dca8e7e0ad544aa847f520c1ece7f2192c6a88e6148d250d0b2 | Python | 12,362 | 299 | """A02 semantic RESIDUAL slice: dataflow-anchored facets on real GPT-2 and OPT.
Lane gate rows (megaplan s4 row A02: "U; R0; real GPT-2 + OPT"):
- resid_pre is the RESIDUAL STREAM, selected by dataflow + shape -- never the
token ids or the attention mask that enter every real HF block alongside it
(the mask-shape... |
c311e049ab412354ab92cd035a5aa21799cf1141f37d9e505abbb5cb2eee0fc8 | Python | 12,364 | 270 | from keras.src.api_export import keras_export
from keras.src.layers.activations.activation import Activation
from keras.src.layers.activations.elu import ELU
from keras.src.layers.activations.leaky_relu import LeakyReLU
from keras.src.layers.activations.prelu import PReLU
from keras.src.layers.activations.relu import R... |
27d45cafa02cc414219ac6e6260608591ea887870768bcdf277079536d04a07d | Python | 12,370 | 412 | """Page-composition helpers for the TorchLens visual audit pack.
Each audit "page" is a single PDF page composed with matplotlib:
a header strip (section / page number / title), a caption block explaining
what is demonstrated and what the eye should check, and one or more graph
panels rendered by Graphviz to PNG and e... |
7d9aa3eee066174e6f2535af5fafc4a521d77c79adbdf2f2eedbc697bb31ad91 | Python | 12,376 | 285 | # Copyright 2025 Google.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... |
9f991c9f0f9319bf4060016361fea1cbfcf72abfe343d8692fbedc748b21f54a | Python | 12,380 | 463 | import pytest
import rpy2.rinterface as ri
import rpy2.robjects as robjects
import os
import array
import time
import datetime
import rpy2.rlike.container as rlc
from collections import OrderedDict
rlist = robjects.baseenv["list"]
def test_init():
identical = ri.baseenv["identical"]
py_a = array.array('i', [... |
03f071aefe1772443ee4390997b3f76df70cc71af27d25bd2b08d6446f3e0a05 | Python | 12,381 | 399 | """ This is more a general views focussed on defining functions which are \
called by other views for specify pages. This way different pages can be \
used to display different data, but in a consistent way.
"""
import sys
import numpy
import numpy as np
from flask import flash
from source.forms import forms
from s... |
7954135ad3a53b36dfd6493436f6efd9966b03a06957ceb9dc313f65bb870588 | Python | 12,381 | 290 | '''
Defines the base for a Model for neural system identification
with it's trainer and evaluation functions
Author: Santiago Cadena
Last update: April 2019
'''
import numpy as np
import os
from scipy import stats
import tensorflow as tf
import hashlib
import inspect
import random
from tensorflow.contrib import layer... |
9dbc053fa1fb695948904f7732d625de6257c3eaa708f3ff8653cdf53421dee2 | Python | 12,381 | 359 | """Phase 3 semantic facet tests."""
from __future__ import annotations
from importlib.metadata import EntryPoint
from typing import Any
import pytest
import torch
from torch import nn
from torch.nn import functional as F
import torchlens as tl
from torchlens.intervention.errors import SiteResolutionError
from torch... |
56be0fc88183746036e06e77d77f2570d59860a30c1e6ec98e79269f5f000c2d | Python | 12,388 | 287 | """R08 discrete-bool exemption hardening tests (validation tripwire).
Moved verbatim from ``tests/test_validation_hardening.py`` (at its size cap).
Pre-fix, a bool-dtype output was a blanket posthoc ``discrete_bool_output``
pass, so a dead or invented parent edge on a comparison or bool-predicate op
was unfalsifiable ... |
d376b94306f699243eb6226e3558d9b4b65208f3836add0f401766aa064670f2 | Python | 12,389 | 354 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType
import copy as _copy
class Step(_BaseLayoutHierarchyType):
_parent_path_str = "layout.slider"
_pat... |
ca3055278eb0168dec25e7912cbef26f48531c3232e2f47225b8947141087b36 | Python | 12,390 | 328 | import torch
from PIL import Image
from torchvision import transforms
import pandas as pd
from sklearn.model_selection import StratifiedKFold
import numpy as np
import torch.nn as nn
from random import shuffle
from sklearn.metrics import confusion_matrix
import copy
# CUDA for PyTorch
use_cuda = torch.cuda.is_availa... |
01d6017b9eae3ac9a45cba35905d5fd2245551e9308a15139521c8782e2102c8 | Python | 12,391 | 302 | """
This module define the logger and saver
"""
import logging
import time
import torch
import numpy as np
from logger.loss_logger import LossLogger
from logger.metrics_logger import MetricsLogger
from utils.utils import (
get_material_and_infos,
get_slope,
get_first_metric_dev_value,
calc_metric_and_lo... |
c3a0ec333e005328a1aca5b41b021c26d7cbcbffb2fd59d77c648dbb17835db9 | Python | 12,391 | 294 | import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
# # Plot styles
# plt.style.use('seaborn-pastel')
# matplotlib.rcParams['mathtext.fontset'] = 'custom'
# matplotlib.rcParams['mathtext.rm'] = 'Bitstream Vera Sans'
# matplotlib.rcParams['mathtext.it'] = 'Bitstream Vera Sans:italic'
# matplotlib.rc... |
59326443a8c334c76cb21d8a9374df00a762b4734facee3439c13c27a6944312 | Python | 12,392 | 392 | """Helpers for vizualization."""
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import matplotlib.transforms as transforms
import numpy as np
from ..embedding import SpectralEmbedding, LocallyLinearEmbedding, TSNE
def plot_embedding(
X,
y=None,
*,
embd_type="Spectral",
met... |
f4d7593534a11df898a717b9776098897c025a4995ff3309aaec369ab763d5f2 | Python | 12,392 | 307 | """Load-side integrity of the ``merged-directory`` artifact (p4 3.4 R59).
These pins do NOT need a live process group: they build rank cores from plain
captures with injected ``collective_boundary_v1`` distributed annotations (the
same shape ``torchlens.distributed`` emits), merge them, save the artifact,
then attack ... |
b910c16202da69e4b03e9b82a0eddffb8cea7377165cfe377626f2ecdd9fb1e5 | Python | 12,395 | 359 | """Behavioral tests for the tracker, stub-dependency, and node-typing export paths.
These cover the ``torchlens.export`` surfaces that need no heavyweight optional
dependency at all (duck-typed tracker objects), plus the optional-dependency
contracts exercised through minimal in-test stand-ins so the flattening and
re... |
a374517ccd142be7256e5dac2f5707abf05df86031a20e355eddf80eee7c3ec4 | Python | 12,398 | 270 | # 结论:当模型进行ensemble的时候性能会明显提升。
import json
import numpy as np
import os, sys
from collections import Counter
from sklearn import preprocessing
from sklearn.metrics import f1_score
from sklearn.metrics import confusion_matrix
import torch
import torch.nn as nn
import torch.nn.utils.rnn as rnn_utils
import torch.nn.functi... |
460541fcc7c8d8a35d60a5632871077630fc553b84f00b9addbf500fee8c5dd1 | Python | 12,402 | 277 | #!/usr/bin/env python3
"""
Dx AF — remaining diagnostics (E, F, H, I).
E. Misclassification analysis. At the canonical max-BA operating point,
characterize the AD subjects we miss: cohort, severity, demographic
profile.
F. Feature ablation under Dx AA. Drop each of the 15 features one at
a time, recompute AU... |
fd6214692fb43df1fcf84a943dd24d9919d6fcc27dc6462c5c2dbc2b0a4391c8 | Python | 12,407 | 301 | """
Band Ratio Measures
===================
Exploring how band ratio measures relate to periodic & aperiodic activity.
"""
###################################################################################################
# Introduction
# ------------
#
# Band ratios measures are a relatively common measure, propose... |
2e817f133463afd7a5c14b2bdd0a0a59cc6b621885fa6463830c2698dcaf238d | Python | 12,408 | 332 | import datetime
import logging
from abc import abstractmethod
from typing import cast
from celery import Task
from sqlalchemy import (
bindparam,
delete,
func,
insert,
select,
update,
)
from sqlalchemy.dialects.postgresql import insert as ps_insert
from sqlalchemy.engine import CursorResult
fro... |
c326cb6588a0c2ea242aeee8b011a9044085f23716744ef0367322a01edc8414 | Python | 12,408 | 221 | import os
import argparse
def bio_train(models):
for i,m in enumerate(models):
outname = m.split('.pt')[0].replace('/','')
cmd = f'$TRAIN_BIO --name bioseq2seq_{i+1} --random_seed {m}'
print(cmd)
def edc_train(models):
for i,m in enumerate(models):
outname = m.split('.pt')[0].r... |
f7175d16a05308a4893ca5bca98a079a02bacd41a166afb47d9886938c22253f | Python | 12,413 | 310 | """Plots for the model object.
Notes
-----
This file contains plotting functions that take as input a model object.
"""
import numpy as np
from specparam.modutils.dependencies import safe_import, check_dependency
from specparam.utils.select import nearest_ind
from specparam.utils.spectral import trim_spectrum
from s... |
1c98e7b345e289d2d4e1e569c664daa22c0213c57dbd74c61bc10b0ef1ce030c | Python | 12,417 | 305 | '''
* All rights Reserved, Designed By HIT-Bioinformatics
* @Title: cuteSV_Description.py
* @author: tjiang & sqcao & zdzhang
* @date: Jul. 12nd 2026
* @version V2.1.4
'''
import argparse
VERSION = '2.1.4'
class cuteSVdp(object):
'''
Detailed descriptions of cuteSV version and its parameters.
'''
USAGE... |
1922035b0cd39848eddb9a331c79ddac7fc40cff1f62d8e21ea0ab23b3ea17d3 | Python | 12,420 | 365 | # -*- coding: utf-8 -*-
"""chek_model_output_09_01_2022.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1aT43onPDbAY7gkpA-7kEIF6rDrLUlxyz
"""
import numpy as np
#import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib... |
e327f3664a3ee1ce0476ca8f3c4551716da80e3d94d4424d032c077c0f9e174c | Python | 12,420 | 248 | """GrapNet: a programmable dynamic-architecture neural graph substrate.
Zirong Li (Tiangong University), 2026, arXiv:2606.18923
("GrapNet: A Programmable Dynamic-Architecture Neural Graph Substrate").
GrapNet treats *the graph as the neural network itself* (not an input data graph, unlike a
GNN). For a transition fr... |
6cfec5bf7fb62fd2f4890ee71ccee25d69087690d99e093f1f63339ec9b17209 | Python | 12,422 | 300 | # SPDX-License-Identifier: LGPL-2.1-or-later
from __future__ import print_function, division, absolute_import
import unittest
import os
import numpy as np
from pyEcoHAB import trajectories as tr
from pyEcoHAB import Loader
from pyEcoHAB import Timeline
from pyEcoHAB import data_path
class TestSingleMouseAntennaTrans... |
daf539915e9986c81e0c02f0ce8afc8ae6a9b9e438de112649dcfdb0913026ba | Python | 12,423 | 364 | import torch
from tqdm import tqdm
import numpy as np
from interpretability.utils import (
get_attentions_map_simple,
set_hook_to_get_attention_map,
load_model_and_vocab,
)
from interpretability.generate_residues_of_interests_with_attn import (
create_score_vector,
)
from sty import fg, bg, ef, rs
from ... |
090e35507fedb10258754c6a7c7c2d941474dc8e35b322995e05ab620ad0e27c | Python | 12,426 | 315 | """ SiamRPN metrics """
import numpy as np
from ..filesystem import try_import_colorama
def Iou(rect1, rect2):
"""
caculate interection over union
Parameters
----------
rect1: list or np.array, rectangle1
rect2: list or np.array, rectangle2
Returns
-------
iou
"""
... |
1ed81712797165207cadec0b1cbdedfc38ec11b9ad8d95c2abc6b7bf2e9a3649 | Python | 12,426 | 426 | #!/usr/bin/env python
"""
Setuptools bootstrapping installer.
Maintained at https://github.com/pypa/setuptools/tree/bootstrap.
Run this script to install or upgrade setuptools.
"""
import os
import shutil
import sys
import tempfile
import zipfile
import optparse
import subprocess
import platform
import textwrap
imp... |
949867cf4033c95320ed23df123bd7cbc801949c52fcdf07d1eb16f8f67ec00e | Python | 12,428 | 369 | from __future__ import annotations
import json
import multiprocessing as mp
import random
from copy import deepcopy
import matplotlib.pyplot as plt
import numpy as np
from tqdm.auto import tqdm
from ..utils import transform_gt_into_pr
from .froc_curve import calc_scores
from .froc_curve import COLORS
from .froc_curv... |
4ccdf7685a0ccc9e23d0c2201d3f9177df9fa32cf57c8da22ab80055299a81a3 | Python | 12,434 | 334 | """TabICL in-context classification, regression and SHAP runner."""
import argparse
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.metrics import (
accuracy_score,
average_precision_score,
balanced_accuracy_score,
f1_score,
precision_recall_curve,
... |
9598908ab6c23afc11da42e144c5388b52be77d242e4dcfc6e51df884825f3f2 | Python | 12,434 | 324 | import torch
from PIL import Image
from torchvision import transforms
import pandas as pd
from sklearn.model_selection import StratifiedKFold
import numpy as np
import torch.nn as nn
from random import shuffle
from sklearn.metrics import confusion_matrix
import copy
# CUDA for PyTorch
use_cuda = torch.cuda.is_availa... |
313bd553e69a43dc23f88e5c995cdb9c4b30271ea4804d90cf841151e5199601 | Python | 12,438 | 204 | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import os
def letter_to_number(input):
"""Convert letter to number in residue number format for sorting"""
# Example: convert 'S765:C-S240:A' to '765671024065' (S765:C = 765 67, S240:A = 240 65)
resid1 = input.spl... |
b8a631a0446b1f0445fd14a73de29aaa5a2fd6788d17a10f4ca89a8060ed52fc | Python | 12,439 | 257 | #!/usr/bin/env python3
"""
File: split_picalo_files.py
Created: 2023/07/13
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.
"""... |
fa089ceb4215495839bad76789db55c8319f567b1fe827ad1d6ac51d5e338b9b | Python | 12,440 | 299 | from ovseg.utils.io import load_pkl
from ovseg.model.SegmentationModel import SegmentationModel
from ovseg.model.ModelBase import ModelBase
from ovseg.data.Dataset import raw_Dataset
from os import environ, listdir
from os.path import join, isdir, exists
import torch
from ovseg.utils.torch_np_utils import check_type
im... |
99c24c8ad83a26552560e74d6932dbee6cd5f8f86fc9bd6153f96411dd86f3d1 | Python | 12,442 | 338 | # CODE ADAPTED FROM: https://github.com/MIC-DKFZ/nnUNet/blob/master/nnunet/network_architecture/generic_UNet.py
from copy import deepcopy
from torch import nn
import torch
import numpy as np
import torch.nn.functional
from torch.distributions import Normal
class InitWeights_He(object):
def __init__(self, neg_sl... |
4d83393a546fe56b9ff8da6a94f7d7eaebaf0b9c249d9c63d88c2529a170b7a6 | Python | 12,444 | 327 | #!/usr/bin/env python3
"""
File: main_eqtl_replication.py
Created: 2021/11/08
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.
... |
8a441e526400f3984fb43281bb7e839fd81c753653b97582e3363b8042fff615 | Python | 12,444 | 317 | """Public provider entry points and run finalization."""
from __future__ import annotations
from collections.abc import Iterable, Mapping
from typing import TYPE_CHECKING, Any
import numpy as np
import torch
from . import _state
from ._runnable_state import (
RunResourceCeiling,
prepare_runnable_state,
... |
ad09f9d57747a87a994b6c9c260f0b1e474c9c679d8b4c005e49a9353a45a9d4 | Python | 12,446 | 344 | import logging
from sqlalchemy import select
from sqlalchemy.orm import scoped_session
from galaxy.exceptions import RequestParameterInvalidException
from galaxy.model import (
Credential,
CredentialsGroup,
JobCredentialsContextAssociation,
User,
UserCredentials,
)
from galaxy.model.scoped_session... |
31e859465a3fbeb0a90f8768d9839f470911de3e239ee3685f18b0249ff35e48 | Python | 12,449 | 323 | """Regression tests for the r18i utils/options hardening group.
Covers:
* M15 ``resolve_runnable_torch_alias`` target-existence capability probe
(runnable tripwire; strengthened, mutation-proof).
* M16 ``run_dynamo_explain`` signature-based convention dispatch (no
swallowed internal ``TypeError`` / double side eff... |
5e9e18c25de7ec773c110ac8211058d2b587226415c8d68436169e6c8e66ee84 | Python | 12,451 | 327 | """
File: visualiser.py
Created: 2021/04/14
Last Changed: 2021/12/03
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.... |
6bda19bb27ebcfcc9760e14f0d955ddeb8ba0fe2aba6c1f32c87dca860c66715 | Python | 12,460 | 350 | #!/usr/bin/env python
"""Generate the TorchLens Dagua theme reference gallery."""
from __future__ import annotations
import importlib
import json
import sys
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import torch
import torchlens as tl
ROO... |
ba66ebfd0bbadaa7c1a350425a38122a301b7b2772222373e6b41ab506e1d456 | Python | 12,461 | 397 | """Filesystem utility functions."""
import os
import errno
import contextlib
from pathlib import Path
import tarfile
import zipfile
def makedirs(path):
"""Create directory recursively if not exists.
Similar to `makedir -p`, you can skip checking existence before this function.
Parameters
----------
... |
eaa114fc3c81b289f14f4afc41ed421a7882f0a45a9918d2fc30b161926ea20e | Python | 12,461 | 333 | """
utils_linclab_plot.py
Authors: Colleen Gillon
Updated: March 2022
Requirements:
- python (tested on 3.7)
- matplotlib (>= 3.3.1 for adding fonts from directory)
- numpy
Contents:
- LINCLAB_COLS : module-wide dictionary of LiNCLab colors
- linclab_plt_defaults(): sets plotting parameters to use LiNCLab... |
b379d5d4dc6e7e573a55c0bbc495058ecd7a43b5147afebc2ef99f261096022a | Python | 12,475 | 406 | """Tests for IO-S2 pandas and file-export surfaces."""
import importlib.util
import json
from pathlib import Path
from typing import Any
import pytest
import torch
import torch.nn as nn
pd = pytest.importorskip("pandas")
import torchlens as tl # noqa: E402
from torchlens import trace as trace_fn # noqa: E402
from... |
b381b43ef97e76c2ee72ed932165f5ce32d80391f1b1fc0d800c7cb2d555e4b2 | Python | 12,479 | 270 | """
classifier.py -- live inference wrapper for the 4-class SongCNN (see
song-feature-analysis/scripts/cnn_model.py), trained offline and shipped
here as a .npz weight file (see cnn_numpy.py and that training repo's
scripts/export_npz.py -- NOT ONNX; see cnn_numpy.py's docstring for why:
onnxruntime has no ARM wheels f... |
837fd645cd74d9838ca9f73579a929568211df67fb6da78ee2cab9045f396be6 | Python | 12,481 | 369 | from __future__ import annotations
import copy
import math
import re
from functools import partial
import torch
from pytorch_lightning import LightningModule
from timm.models.vision_transformer import vit_small_patch16_224
from torch import Tensor
from torch.nn import Module
from torch.optim import AdamW, Optimizer
... |
aadd69d09a9fc5b90b89b1bdb04be64612830b48cc9db993df19e97f6de246e2 | Python | 12,487 | 269 | """ SiamRPN train"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import logging
import os
import time
import numpy as np
os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT'] = '0'
import mxnet as mx
from mx... |
4df5ff86b8266d7aebbbb6ebc52263484e910dcfe106c4676a7d840a7d21dc7a | Python | 12,488 | 291 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import os
from itertools import product
from pathlib import Path
import pytest
import torch
from tests import CUDA_DEVICE_COUNT, CUDA_IS_AVAILABLE, MODEL, SOURCE
from ultralytics import YOLO
from ultralytics.cfg import TASK2DATA, TASK2MODEL, TASKS
f... |
630cb3fb268fdda086ebab775a61eb9033861a551c318b4f876aca9db29beb5a | Python | 12,489 | 354 | """Tests for spiketools.utils.extract"""
import numpy as np
from pytest import raises
from spiketools.utils.extract import *
from spiketools.utils.extract import _reinstate_range_1d
###################################################################################################
##################################... |
78350594ee3660610715559e007930ea7810842f6995bdca5b33c93a6f8acab8 | Python | 12,491 | 353 | """
Functional tests for frontend authentication system.
Tests the Angular.js authentication service and login/logout functionality
from the frontend perspective.
"""
import json
import os
import tempfile
from unittest.mock import MagicMock, Mock, patch
import pytest
class TestFrontendAuthService:
"""Test Angu... |
b6231369d5687bce86e1b24fc1da9ab4e7d1eb10a7d93dae37dba3f90dfc9507 | Python | 12,494 | 337 | """
Unit tests for base API infrastructure.
Tests decorators, BaseAPI class, and common API utilities.
"""
import json
import logging
import unittest
from unittest.mock import Mock, patch
import bottle
import pytest
from ethoscope_node.api.base import BaseAPI, error_decorator, warning_decorator
class AbortError(E... |
1ece2c6b9f49b55e834459dbe2dc54785130071171249a8d43d78ae869729d2b | Python | 12,496 | 278 | """
ERB filters created in numpy, and used for cochleagram generation.
Functions come from pycochleagram which is no longer actively
maintained.
"""
import numpy as np
def matlab_arange(start, stop, num):
"""Mimics MATLAB's sequence generation.
Returns `num + 1` evenly spaced samples, calculated over the inte... |
3b1e04bbbc0aad93430335284ddb480ec9affd25f2d2d2641bee3930e7e4f85b | Python | 12,498 | 325 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from cgnn import LinearUpdate
# Thanks for StructTrans and PiFold
# https://github.com/jingraham/neurips19-graph-protein-design
# https://github.com/A4Bio/PiFold
default_device = torch.device('cuda:0')
def nan_to_num(te... |
47d545aee45791ae3778fa2bac608158528550264432dae820e38cdf727940b6 | Python | 12,499 | 334 | """2. Dive Deep into Training with CIFAR10
==============================================
Hope you enjoyed playing with our demo script.
Now, you may be wandering: how exactly was the model trained?
In this tutorial, we will focus on answering this question.
Prerequisites
-------------
We assume readers have a basic... |
b023e2177f25c9323783ce2ebc791bddc97b8b7bedd46eda0187cfecc60b85d4 | Python | 12,501 | 368 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 15 13:24:28 2021
@author: KEPetousakis
"""
import Code_General_utility_spikes_pickling as util
import numpy as np
import Code_General_Nassi_functions as nf
import matplotlib.pyplot as plt
from copy import deepcopy as dcp
import scipy.stats as stats
import matplotlib
imp... |
4ada230433dce22cd2fab256aa31c53b4d400dd43791f3530bdacd93d3ced681 | Python | 12,504 | 397 | """BindsNET neuron groups: spiking-neuron node models as traceable modules.
Source: https://github.com/BindsNET/bindsnet (``bindsnet/network/nodes.py``)
BindsNET defines a family of spiking-neuron "node" groups used as layers inside a
``Network``. Each node type is a small, fully-specified dynamical system: a
membr... |
999b6711b3b6548fe7f877dc41ddc7c837a6264bd5c91d4586ca96b4876d93bf | Python | 12,504 | 484 | '''
This code copies data from fmriprep output into FSL feat style
directories so that ICA FIX can be run.
'''
import os
import shutil
import pandas as pd
import numpy as np
import subprocess
import sys
import nibabel as nib
# input arguments
subj = sys.argv[1]
print(subj.upper())
# paths
prep_dir = '/mnt/lustre/wor... |
4f262e2f5e8056c638bc9aa5b0c301393e8332d20af265ea7086f2bdd6866513 | Python | 12,508 | 345 | import copy
import functools
import os
import blobfile as bf
import torch as th
import torch.distributed as dist
from torch.nn.parallel.distributed import DistributedDataParallel as DDP
from torch.optim import AdamW
from . import dist_util, logger
from .fp16_util import MixedPrecisionTrainer
from .nn import update_em... |
d39ba200060eb03d8007f5c385f9f61862704fe0051bbac8156b74b240a039e3 | Python | 12,511 | 298 | """
Implementation of "Attention is All You Need"
"""
import torch
import torch.nn as nn
from bioseq2seq.decoders.decoder import DecoderBase
from bioseq2seq.modules import MultiHeadedAttention, AverageAttention
from bioseq2seq.modules.position_ffn import PositionwiseFeedForward
from bioseq2seq.utils.misc import seque... |
af2b3b50cd3ef067295a9f861b0d880d5df575d6626280dae9cc2833b4ed3dba | Python | 12,512 | 313 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
"""Monkey patches to update/extend functionality of existing functions."""
from __future__ import annotations
import time
from contextlib import contextmanager
from copy import copy
from pathlib import Path
from typing import Any
import cv2
import n... |
edb23a8056a547deca7feb047d4fb472ad9b1c66d482cdb5fc173b1fc45f9f03 | Python | 12,512 | 271 | # 结论:当模型进行ensemble的时候性能会明显提升。
import json
import numpy as np
import os, sys
from collections import Counter
from sklearn import preprocessing
from sklearn.metrics import f1_score
from sklearn.metrics import confusion_matrix
import torch
import torch.nn as nn
import torch.nn.utils.rnn as rnn_utils
import torch.nn.functi... |
b0f0530f95f5375b946a386fda95c72c47854e1a75be319e4d3d3c9e300a9663 | Python | 12,515 | 282 | import torch
import random
from loader import *
# add by dd
from torch_geometric.utils import to_dense_adj
from torch_geometric.utils import add_self_loops
class Self_loop:
def __init__(self):
"""
Randomly sample negative edges
"""
pass
def __call__(self, ... |
a443ce6d4f9872c56b94dd148246ed6ee7a8204247ea5a3ada98887b2358b010 | Python | 12,516 | 310 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 15 20:44:16 2023
@author: longzheng
"""
import logging
import math
import torch
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import warnings
import h5py
import os
from torch.utils.data import Datase... |
331c55be90d3344b6504912587afa989fe462317ad226ad54372431b47a8e339 | Python | 12,517 | 216 |
# these are common routines shared by all the def_common_params for the new acquisition format.
# began to get cumbersome having these defined separately in each def_common_params.
# NOTE: for the Zeiss acquisition format there is no manifest file, so a function that generates
# region_strs_all needs to be specifie... |
771213237e94cb85686b4461cd9b06dcaed2cc2d9ef33611e795c7ed6f705473 | Python | 12,517 | 291 |
import os
import tempfile
import time
import unittest
import shutil
from carbontracker.tracker import CarbonTracker
from carbontracker.report import LogParser, format_duration
class TestFormatDuration(unittest.TestCase):
"""Tests for the format_duration helper function."""
def test_format_duration_seconds_... |
cafd10943cffa71f4baed7a1d34d75e7f0e24d5d87f0d21810b62e8217a0eb20 | Python | 12,517 | 314 | import copy
from typing import Any
import numpy as np
import pandas as pd
import scipy.fft as fft
from mirp._images.generic_image import GenericImage
from mirp._images.transformed_image import TransformedImage
from mirp.settings.generic import SettingsClass
from mirp._imagefilters.generic import GenericFilter
class... |
efd11a7386cb8258f483502be5545f32df3ce3b8584823f2ac6af0718cd43191 | Python | 12,517 | 360 | """
XML format classes
"""
import logging
import re
from xml.parsers import expat
from galaxy import util
from galaxy.datatypes.dataproviders.dataset import DatasetDataProvider
from galaxy.datatypes.dataproviders.hierarchy import XMLDataProvider
from galaxy.datatypes.metadata import MetadataElement
from galaxy.dataty... |
663fd9f8d5be9f6b485971188c1d4c56d39feea126900baaf521185b9fafc381 | Python | 12,519 | 362 | import os
import copy
import collections
import json
import logging
import rdkit
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem.rdmolops import CombineMols
DEBUG = os.getenv("DEBUG", "0") == "1"
logger = logging.getLogger(__file__)
class RdkitConvertError(Exception):
"""Base class for exceptio... |
2bc8d7ff71b7b267e9e5ff27ff6f86315ae1a8b433d0a6a3bf8e5190257e74ca | Python | 12,520 | 321 | """Round-7 security regression: torch I/O / serialization TYPE construction.
The :class:`SafeBundleUnpickler` torch-``type`` branch historically admitted ANY
resolved ``torch.*`` ``type`` on the premise that "constructing a torch data type
executes no attacker code". That premise is FALSE for torch's I/O-capable types... |
d588de9973e6cefe69605b677fb67d1e026d9d28e5f7222be3f556387edcf8fa | Python | 12,525 | 383 | #!/usr/bin/env python
import argparse
import math
import os
import random
import re
# configuration of the splitting for specific file types
# - regular expression matching the record separator ('' if not splitting by regex but by number of lines)
# - number of lines to split after (0 if not splitting by number of li... |
1a13fefc695379845dc89052710f4739ece3a782d76d7503afc2464fc0758ed6 | Python | 12,529 | 274 | """
For analyses and plots of region annotation volumes
"""
import numpy
from scipy import stats
import pandas as pd
from math import log2
import matplotlib.pyplot as plt
import copy
import re
from voxcell import VoxelData, RegionMap
def from_parcellation(base_func):
def returned_function(parc_level, **kwargs):
... |
6c351b7f80976500790cd69121e26c2fcede796b9a2931f8f8eb13d075fe10b5 | Python | 12,529 | 367 | # Read list of files containing radius and positions of spherules from aggregate_generator
# Create input files for MSTM
import glob
import os
import re
import numpy as np
import matplotlib.pyplot as plt
import math
import pandas as pd
import random
from os import listdir
from os.path import isfile, join
def write_m... |
20dc0d83fe2cb698e488304dac89f890c9082e22d09ffb985ba7ff486f60a7e1 | Python | 12,535 | 370 | """Regression tests for the r18e debug-module hardening fixes.
Covers:
- H5: ``tl.debug.lineage`` no longer crashes on recurrent models (getattr-multipass class).
- H2/M8: ``audit_trace`` honesty -- surfaces real bisect_nan/dtype_range findings and
counts empty/insufficient checks as SKIPPED, not RUN.
- H6/H7: ``gra... |
359fde368350c3ccb4927f6075b85167bded3b3eb91d5f80d96a92f71286a778 | Python | 12,537 | 426 | from keras.src import tree
from keras.src.api_export import keras_export
from keras.src.utils.naming import auto_name
@keras_export("keras.KerasTensor")
class KerasTensor:
"""Symbolic tensor -- encapsulates a shape and a dtype.
You can use `KerasTensor` instances to build computation
graphs of Keras oper... |
14987a4255ffec8948bba479f639a631a0278426262fa50de8243cb4530838ad | Python | 12,538 | 292 | # 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... |
57b753b8428f70e4f91bc244874ace37a160f304af7276119a246f17739eb99d | Python | 12,538 | 218 | import argparse
import logging
import os
import re
import time
import imgaug as ia
import pytorch_lightning as pl
import torch
import torch.utils.data
from pytorch_lightning.loggers import TensorBoardLogger
from datasets import get_dataset
from models import get_model
from strategies import get_strategy
from utils.ex... |
ff2373e2c8cb3651dcbc95292faca692b0375bb963972e3290850fa2e217e1cb | Python | 12,541 | 326 | from keras.src import backend
from keras.src.api_export import keras_export
from keras.src.backend.common import is_int_dtype
from keras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layer import ( # noqa: E501
BaseImagePreprocessingLayer,
)
from keras.src.layers.preprocessing.image_preproc... |
28906eaeecaadb8f7be9b9a407d35563c98b860ef2566cd540c8d15ae578df69 | Python | 12,542 | 411 | import binascii
import copy
import json
import logging
import uuid
from collections import deque
from itertools import chain
from sys import getsizeof
import numpy
import sqlalchemy
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.inspection import inspect
from sqlalchemy.types import (
CHAR,
LargeBi... |
2c169f4a2e0293364c8242e42bb5460dd5ea2bf20ed001f92c82716f3d1720d6 | Python | 12,543 | 166 | # Form implementation generated from reading ui file 'llspy/gui/camcordialog.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from qtpy import QtCore, QtGui, QtWidgets
class Ui_Dialog:
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
... |
9233e3159766f07754d6d3ee00d3bd2fb9aae287fadccb7357b24f40a7b79b94 | Python | 12,546 | 267 | import errno
import logging
import os
from time import sleep
from typing import TYPE_CHECKING
from galaxy import model
from galaxy.jobs import (
JobWrapper,
TaskWrapper,
)
from galaxy.jobs.runners import BaseJobRunner
from galaxy.tool_util.output_checker import merge_runtime_environment_warnings
from galaxy.to... |
b2e72b6104d98f767d34dd29566f8efab7bbcfa66382b61ac41139305d44e465 | Python | 12,546 | 317 | import ipywidgets as widgets
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib import cm
from IPython.display import display, clear_output
from gates import ros_inf, get_ros
from mitochondria import Mito
import figure_properties as fp
from utils import Q_nak, R... |
299f15f94f4fb515992f17936c7948952d2a73117a8ee9387e879e0dafd3505d | Python | 12,547 | 325 | import os
import sys
import fastai
from fastai.tabular.all import *
from src.features.loader import target, cont_names, cat_names, ais_names, col_selector, resampling_dict
from src.models.ml_utils import *
from src.visualization.visualize import multi_label_roc_plot
from sklearn.metrics import roc_curve, ... |
a3bad211d04ba97b69291440b49134912c17b02f3e325e67ea2c3f3566490ee3 | Python | 12,547 | 313 | """Input-derived intermediate-layout escape ceiling (r73 F1).
Round-72 (hon1) confirmed a false VERIFIED on the residual line: a model branching on an
INTERMEDIATE tensor's contiguity (``(x * 2).is_contiguous(memory_format=channels_last)``)
reported VERIFIED when replayed on a runtime input with a DIFFERENT memory for... |
c526e576c576e823c28d1229e01a41a5018ebd5a4f162cb902e24a76a069770a | Python | 12,549 | 291 | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Encoders to build input features.
"""
# ======================================================================... |
268c0b1dedb794d15e6838c4225b88dbe74d94fa14dc0f707c286fe3fa0a37a2 | Python | 12,550 | 371 | import os
import pickle
import sys
from importlib import import_module
from time import monotonic, time
from unittest.mock import Mock, patch
import pytest
from celery import uuid
from celery.exceptions import ImproperlyConfigured, WorkerShutdown, WorkerTerminate
from celery.platforms import EX_OK
from celery.utils.c... |
ebaafe82f702d361fd3db135ec40bf488162ba0ab4f2e729c6b808414daf9f89 | Python | 12,553 | 401 | """Utility functions for cell segmentation.
"""
from typing import Optional, Tuple, Union
import cv2
import numpy as np
from anndata import AnnData
from kneed import KneeLocator
from scipy import signal, sparse
from skimage.segmentation import find_boundaries
from tqdm import tqdm
from typing_extensions import Literal... |
ec9bd53db763e6e83940368367e75ba3d5c307680f50537fd9c04ccb675f25a2 | Python | 12,555 | 383 | """Unit-aware parameter classes built on the project Pint registry.
This module defines `UnitParam` and specialized unit validators for time,
distance, angle, and motion units. It is used whenever a parameter must carry
physical dimensional metadata (for example seconds, meters, radians, or
velocity/acceleration units... |
aee896ad2a5099e866b9c599d906fa6e2baa7453d3083ffe9857a19165824793 | Python | 12,558 | 372 | #!/usr/bin/env python3
"""
Voxel-based conversion of surface or tetrahedral meshes to SWC morphologies
for NEURON simulations.
Last updated: 20.8.2026
Author: Laura Keto
Description
-----------
This script converts realistic astrocyte branchlet morphologies represented
as surface meshes (OBJ/OFF/PLY) or tetrahedral m... |
b4492e2ab975dacc47395abd9b821d364a82967e2c0e4c406495b4695f656f11 | Python | 12,564 | 377 | import pandas as pd
import numpy as np
from rdkit import Chem
import torch as th
import re, os
import dgl
from itertools import product, groupby, permutations
from scipy.spatial import distance_matrix
from dgl.data.utils import save_graphs, load_graphs, load_labels
from joblib import Parallel, delayed
import MDAnalysis... |
6aee649dc28a616476a7e711a53f11a6a6ca0cda0fbe279311d80e52b888bf0f | Python | 12,566 | 268 | #结论:当模型进行ensemble的时候性能会明显提升。
import json
import numpy as np
import os, sys
from collections import Counter
from sklearn import preprocessing
from sklearn.metrics import f1_score
from sklearn.metrics import confusion_matrix
import torch
import torch.nn as nn
import torch.nn.utils.rnn as rnn_utils
import torch.nn.functio... |
75c25ada90354dc3e59437a5047df3c766297daf0722f33d4ce6c131e90cb81a | Python | 12,566 | 308 | """
Workflow orchestration agent for coordinating multiple agents on complex tasks.
"""
import asyncio
import logging
import re
from functools import partial
from pathlib import Path
from typing import (
Any,
)
import anyio
from pydantic import BaseModel
from pydantic_ai import Agent
from galaxy.schema.agents im... |
b787e50eeb6d061ec363d789315c6779c1631a580f8ace18251320c6b1b82e3e | Python | 12,566 | 308 | """Targeted regression tests for hardening group r18g (tensor_utils + rng).
Each test pins a specific correctness / validation-tripwire finding reconciled
against main c2f27a9d. Tripwire-strengthening tests are accompanied (in the
fixer report) by a mutation proof: reverting the fix makes the paired assertion
fail. Th... |
2ede8f3ee23f1f67b1c2192dd570a15a91f43de084fc9919bef7ba690efd38b2 | Python | 12,567 | 373 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import itertools
import matplotlib.pyplot as plt
import numpy as np
import slowfast.utils.logging as logging
import torch
from sklearn.metrics import confusion_matrix
from slowfast.datasets.utils import pack_pathway_output,... |
904893a0f85dbeb839d8426db7279da46d2bc1f5f16a786f67a06578fee4760d | Python | 12,572 | 278 | import os
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from utils import parse_config,build_EDA_file_list,load_CDS,setup_fonts, ScalarFormatterClass, build_output_dir
import math
from scipy.stats import pearsonr
from itertools import combinations
def update_percentile_sc... |
89ace6798a2ae4320097cad025536f7d8c1a1ad36d26f750b3766c74300b867a | Python | 12,574 | 338 | import copy
import pandas as pd
import numpy as np
from typing import Self, Generator
from mirp._images.generic_image import GenericImage
from mirp._masks.base_mask import BaseMask
class Matrix(object):
def __init__(
self,
spatial_method: str | None,
matrix: pd.DataFrame | N... |
5d1a19d9b88849a931dce4b384167d8bc39d33cade72838f1d4c79ddafc2f5fa | Python | 12,576 | 383 | # SOURCE: vendored from Xiefeng69/EpiGNN @ 1c0bb8c2
# https://raw.githubusercontent.com/Xiefeng69/EpiGNN/main/src/models.py
# https://raw.githubusercontent.com/Xiefeng69/EpiGNN/main/src/layers.py
#
# Xie, Wang, Ma, Wang, Chen 2022 (ECML-PKDD) "EpiGNN: Exploring Spatial Transmission with
# Graph Neural Network for Regio... |
b2eca28a9f6c121350abc2799f39d4b7833053d8e562bf1d11c9c010a00b93c5 | Python | 12,576 | 374 | import pytest
from pyrosm import get_data
@pytest.fixture
def test_pbf():
pbf_path = get_data("test_pbf")
return pbf_path
@pytest.fixture
def helsinki_pbf():
pbf_path = get_data("helsinki_pbf")
return pbf_path
def test_parsing_basic_elements_from_pbf(test_pbf):
from pyrosm import OSM
from ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.