sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
cc6b93b3b4f22073de330de7f2ca16e63aa244bb3dafac78caf0a035804d9a28
Python
9,341
170
import sys import numpy as np from tensorflow.keras import Sequential from pdb import set_trace from cvnn import logger import cvnn.layers as layers from cvnn.layers.core import ComplexLayer from typing import Type, List from typing import Optional EQUIV_TECHNIQUES = { "np", "alternate_tp", "ratio_tp", "none" } ...
4168add527bb861942df2253e55835af964b96c67c63bae20c63474fb9ebdb9c
Python
9,352
268
# --- 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 Step(_BaseTraceHierarchyType): _parent_path_str = "indicator.gauge" _path...
07e65e6b2657518290a5ba2afb156ae74e417870fc3e71fd6235eacb2f250a81
Python
9,353
232
from __future__ import annotations import logging import time from typing import Optional import numpy as np from bream4.device_interfaces.devices.base_device import BaseDeviceInterface from bream4.device_interfaces.devices.promethion import PromethionGrpcClient DEFAULT_FLICK_DURATION = 3.0 DEFAULT_REST_VOLTAGE = 0...
a49ed48f27c04d54c0c9259c5278936f3ee0e5408496012f966b71ac87a0a079
Python
9,356
222
__author__ = 'Aaron Gudmundson' __email__ = 'agudmund@uci.edu' # from scipy.optimize import minimize, curve_fit import matplotlib.pyplot as plt # Create Figures # import scipy.ndimage as ndimage # Image Manipulation # import scipy.linalg as linalg # import scipy.sparse as sparse ...
795d7fda974b70f1216fb16d7bf387883873af80d0a1251f1b1721ac330ae8ae
Python
9,359
164
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ObjectSpace/trial_dialog_ui.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_TrialDialog(object): def setupUi(self, TrialDialog...
95dc22ab98b82202d254d3e26a9579b2c9d080924b51e5cb1b590138e12432f5
Python
9,359
267
from functools import partial import numpy as np import pickle as pkl import os import mne from mne.datasets import sample from mne.simulation import simulate_raw, simulate_sparse_stc, add_noise, add_ecg, add_eog EEG_CHANNELS = { 'EEG 001': 'Fp1', 'EEG 003': 'Fp2', 'EEG 008': 'F7', 'EEG 010': 'F...
be496c14975fb4545a21f3e656617c8110e91645ea23355c11487efb9f6e84ac
Python
9,359
279
import os import time import numpy as np import pickle as pkl import nibabel as nib from os.path import join as pjoin from scipy.stats import pearsonr from scipy.spatial.distance import cosine from cxy_visual_dev.lib.predefine import proj_dir, get_rois anal_dir = pjoin(proj_dir, 'analysis') work_dir = pjoin(anal_dir, ...
e2fab750d577ee52352d1484a11897f2b0b1e09b164f2062121601c98ae51f8a
Python
9,359
308
import networkx import networkx as nx import numpy as np from anndata import AnnData from scipy.spatial.distance import cdist from stlearn.utils import _read_graph def global_level( adata: AnnData, list_clusters: list[str], w: float, use_label: str = "leiden", use_rep: str = "X_pca", n_dims: ...
e281b742d8067c961dd03dbbbd6dff335641b7e3406ea7f9ac4985df8926b421
Python
9,365
255
from __future__ import annotations import typing as t from werkzeug.exceptions import BadRequest from werkzeug.exceptions import HTTPException from werkzeug.wrappers import Request as RequestBase from werkzeug.wrappers import Response as ResponseBase from . import json from .globals import current_app from .helpers ...
67933b3dc4459dd342106dd93d8e9b99e6fec55d4d77dea1c4e3d6d003f07210
Python
9,366
261
import pathlib import shutil import tempfile import numpy as np import pytest import impose.data import impose.structure from impose import session data_path = pathlib.Path(__file__).parent / "data" def test_session_base(): """Open a test session and extract data""" path = data_path / "brillouin.impose-se...
f847a60ab4cf1bd9531a01fee101b7ade676cf79f84b0e2d9d94980d5b2abfdc
Python
9,369
248
# SOURCE: vendored from aicb-ZhangLabs/Impeller @ main # (model.py, classes PathGNN and PathGNNLayer) # # Impeller's flagship contribution: a path-based heterogeneous graph learning method for # spatial transcriptomic data imputation (Bioinformatics 2024). `PathGNN` aggregates node # features along pre-sampled random-w...
c20a1f7c1958b734da0306e33c14a226206fdbef48c47fc0c69b8af0cc5e8574
Python
9,372
255
"""C03: the ONE immutable public InterventionSpec accepted at every door. Surgery memo 3.1: ``tl.when(...)`` returns the immutable multi-clause spec; the exact same object is accepted by ``fork.do``, ``fork.attach_hooks``, ``intervene=``, ``sweep``, and the save/load path. Lane options never enter the spec, no lane si...
ce69a778ca6eb3e708d7d7381291b8d176741ed29517d40ad359d7712eee0e5b
Python
9,372
257
"""C03 row gate: the fire-evidence rule and the misfire test. Leverage B6 / ledger D1a / edits D12, one substrate: - FIRE EVIDENCE: ``intervention_audit`` is NEVER empty after an attempt -- every door (do/replay, do/set_only, capture ``intervene=``) writes one transaction envelope, including no-fire and error out...
99601fc42db886f0e26eb72ecfc2f29056e5805d5468c156d2170448f8c97e4e
Python
9,374
319
from pathlib import Path 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 @pytest.fixture def helsinki_history_pbf(): pbf_path = get...
a81d1826bc3917423d788c5269cf934459642941af2661c68e99ef059642f632
Python
9,374
280
from plotly import exceptions, optional_imports from plotly.graph_objs import graph_objs pd = optional_imports.get_module("pandas") def validate_table(table_text, font_colors): """ Table-specific validations Check that font_colors is supplied correctly (1, 3, or len(text) colors). :raises: ...
b7f13a990050d0ea87e73053819fb119c2fcc65b02364cd6a8cff8255bc1d5cc
Python
9,375
231
import time import datetime import serial import logging from pyoperant.interfaces import base_ from pyoperant import utils, InterfaceError logger = logging.getLogger(__name__) # TODO: Smart find arduinos using something like this: http://stackoverflow.com/questions/19809867/how-to-check-if-serial-port-is-already-ope...
5592942893db53a2367073cb0ce8a48a7f9a0b1ecebcb719ddfcd8a77c72b5df
Python
9,378
261
"""Base option parser setup""" from __future__ import absolute_import import logging import optparse import sys import textwrap from distutils.util import strtobool from pip._vendor.six import string_types from pip._internal.cli.status_codes import UNKNOWN_ERROR from pip._internal.configuration import Configuration,...
5e20984f3ca5569018a0af25582a86d8159e3f32c982aafddd5dbb59203a79d1
Python
9,378
252
from typing import Dict, List, Tuple, Union from PIL.Image import Image from torch import Tensor from lightly.transforms.gaussian_blur import GaussianBlur from lightly.transforms.image_grid_transform import ImageGridTransform from lightly.transforms.random_crop_and_flip_with_grid import RandomResizedCropAndFlip from ...
73ff0a24ad5090fd3b3e44241c230764cb9047b2758ca042656c054ddcb568ed
Python
9,379
266
#!/usr/bin/env python import sys if ((sys.version_info[0] < 3) or (sys.version_info[0] == 3 and sys.version_info[1] < 10)): print('rpy2 is no longer supporting Python < 3.10.' 'Consider using an older rpy2 release when using an ' 'older Python release.') sys.exit(1) import enum import i...
11c21fda7562d9bc1600b23590fbb2d50357ffafd131e7dc2042f12df26b72b7
Python
9,382
210
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 29 18:04:08 2021 This is the configuration file for Experiment 2, post-cue delay length = 6 cycles variation. To run the experiment, pass the path to the folder which is to contain the data from all Experiments on lines 179-180. @author: emilia """...
fdec9f167bd4bd0e5d4d20678d00dfd1536ec3d9a9fe7f3b7364b989e6d64828
Python
9,382
233
"""S2 marker-combination table TOTALITY test (P1 duty, S2-RATIFICATION sec 5). Transcribes the ratified marker-combination table (S2-RATIFICATION.md sec 5) plus the S2-AMENDMENT-01 deltas verbatim and proves TOTALITY: every cell of the full axis product {capture_kind} x {structure_only} x {truncation} x {per-step prov...
9a461e22da09b665957f6c0a914b39a178f075b4dd192a39787c62d3ed66699f
Python
9,383
233
import math import re from collections import OrderedDict import torch import torch.nn.functional as F from transformers import GPT2Config, GPTBigCodeConfig, PretrainedConfig def remap_state_dict_hf_bigcode(state_dict, config: PretrainedConfig): """ Map the state_dict of a Huggingface BigCode model to be fla...
4d2020879bd7d4f5cc7dc9ff4c534f01312962969520dc85e78611507cc71b20
Python
9,384
210
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 29 18:04:08 2021 This is the configuration file for Experiment 2, post-cue delay length = 7 cycles variation. To run the experiment, pass the path to the folder which is to contain the data from all Experiments on lines 179-180. @author: emilia """...
43a86222b37488274513abea8767c45bb91f3260ad41b9f038c7536b9634fac2
Python
9,386
209
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 29 18:04:08 2021 This is the configuration file for Experiment 2, post-cue delay length = 2 cycles variation. To run the experiment, pass the path to the folder which is to contain the data from all Experiments on lines 179-180. @author: emilia """...
b4b55097e163cf01e00036eea921e060cb5f151eb7e9ae52930f49fae8f6cdba
Python
9,386
211
import numpy as np from keras.src import layers from keras.src import ops from keras.src import testing from keras.src.layers.core.input_layer import Input from keras.src.layers.input_spec import InputSpec from keras.src.layers.input_spec import assert_input_compatibility from keras.src.models import Model class Ass...
6a6dbb88396c46e4583b7aad53c4b1a95f7347bea979544e6a292edc14e6f38b
Python
9,387
213
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 29 18:04:08 2021 This is the configuration file for Experiment 2, post-cue delay length = 4 cycles variation. To run the experiment, pass the path to the folder which is to contain the data from all Experiments on lines 180-181. @author: emilia """...
b6fb8247fa8c3b4772a032cc4c00c1c002ed10688d2588c0be1e508387340a85
Python
9,387
212
#!/usr/bin/env python3 # import required modules from keras import layers from keras import models from keras import optimizers from keras import regularizers from keras import callbacks from keras.models import load_model from scipy import stats import numpy as np from argparse import ArgumentParser import os def p...
d41a81f6f49dac9647bf7e7436ebe78d3479b4f4fb3853bd8b5a92e3249a8407
Python
9,393
313
""" Main module for cleaning mimic data Some functions copy pasted from https://github.com/huaxiuyao/Wild-Time/blob/main/wildtime/data/mimic.py Additional reference: https://github.com/Google-Health/records-research/tree/master/graph-convolutional-transformer """ import logging import os import pickle import random i...
c44c316b7784c6a92cb05f92dfd56cfd08ab2f44bd1c3fff9725d0eb5dc0d8f1
Python
9,394
303
""" BoAmps data models for standardized AI/ML energy consumption reporting. These dataclasses map to the BoAmps JSON schemas defined at: https://github.com/Boavizta/BoAmps/tree/main/model All fields use snake_case internally and are converted to camelCase on serialization. """ import re from dataclasses import datac...
35d718f969bed485881540941e8fba66634b490b43f30d04ef7c5927febdcac7
Python
9,395
296
"""Utilities for creating a transformnd.TransformGraph from OME-Zarr metadata.""" from __future__ import annotations import posixpath from collections.abc import Sequence from typing import TYPE_CHECKING import ome_zarr_models.v06.coordinate_transforms as ozmt import transformnd as tnd if TYPE_CHECKING: import ...
c3f1c09abe0a0d9c429e0d47f2b8d4a4ec09dbd11eec3d7dd9846babd717e43b
Python
9,396
237
import hashlib import os import urllib import warnings from typing import Any, Union, List from pkg_resources import packaging import torch from PIL import Image from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize from tqdm import tqdm from .model import build_model from .simple_tokeni...
8d2f6dadb14ba7c7effd6322e7f61b09519ca268144204a2d34667bd5a5c95bc
Python
9,397
301
"""Phase 8b dispatch, warning, fork, and history tests.""" from __future__ import annotations import warnings from typing import Any import pytest import torch import torchlens as tl from torchlens.intervention.errors import ( DirectActivationWriteWarning, EngineDispatchError, ModelMismatchError, Mu...
a1f9ea4789ebcf26321e3c95fd3cef6be30636aa7957a69e1b13fd95931fa495
Python
9,403
306
# -*- coding: utf-8 -*- # # pyoperant documentation build configuration file, created by # sphinx-quickstart on Fri Mar 21 12:39:43 2014. # # 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 # autogenerated file. # #...
9c2464d48ef7365de2a858ca203f86f222ec22b102725cff5d52cce80f1d5792
Python
9,404
289
"""Utilities for epoching data.""" import numpy as np from spiketools.utils.checks import check_param_lengths from spiketools.utils.extract import get_range, get_value_by_time, get_values_by_time_range ################################################################################################### ###############...
33bd04e318ebf31ffa0430555760fb1acdbdca36c7f1af095c60c2cd586a8039
Python
9,405
250
from builtins import super import numpy as np import numbers from src.em_alignment import EMRegistration def is_positive_semi_definite(R): if not isinstance(R, (np.ndarray, np.generic)): raise ValueError('Encountered an error while checking if the matrix is positive semi definite. \ Expected a ...
d28195bf3ed076a62be364c390dfe620ee94d170fb9c2bebb1c0dd78a127dcc0
Python
9,406
236
import torch import warnings import numpy as np import torch.nn.functional as F from NTD import NTD from tqdm import tqdm from sklearn.model_selection import ShuffleSplit from utils import MSE, MAE, RMSE, MAPE, R2, generate_graph_Laplacian from preprocessing import preprocessing class GNTD(): # Initializatio...
b741d71a475570b9f03135aa4866679bceab677cff664b0fbce0d220fbb155bb
Python
9,410
300
"""Functions to generate """ import ast from random import choices from typing import List, Union import pandas as pd from rdkit.Chem import AllChem from .utils import get_CIP_assignments, get_monomer_sequences def get_valid_mols(smi_list): mol_list = [] for smi in smi_list: try: AllChem...
2cc094bb107c0a63cea9373370406074d34d06d50bb7e992e1c03a80d510c4ea
Python
9,415
225
import torch,math from torch import nn from torch_geometric.nn import MessagePassing from torch_geometric.utils import softmax import torch.nn.functional as F from torch_scatter import scatter_add from torch_geometric.nn.inits import glorot, zeros from torch.nn import Parameter try: import apex #ape...
339181e5945b1089fb52c98361c4603db8a1715b978436f86d2c485759fed2c4
Python
9,415
188
#!/usr/bin/env python import h5py import numpy from diffusion_mapping import flatten_pathway from projection_voxels import projection_from_json default_vxl_shape = (132, 80, 114) default_vxl_offset = numpy.array([0., 0., 0.]) default_vxl_dims = numpy.array([100., 100., 100.]) def write_flatmap(flattened_regions, co...
7b792d734d81003dc1e6c21c544b3cdc38e2e3d3d2b8b9b16b63d02a1233958a
Python
9,417
211
import os import torch import pandas as pd import scanpy as sc import numpy as np from sklearn import metrics import multiprocessing as mp from sklearn.metrics.cluster import adjusted_rand_score from sklearn.metrics.cluster import ( v_measure_score, homogeneity_score, completeness_score) import glob2 import matplot...
b34fec705cd65d970799c49cd073bcd201b00f4d960be00ce0623d0304a26ee2
Python
9,417
259
import json import os from collections import deque from functools import partial from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from threading import Thread import numpy as np import pytest import zarr from ome_zarr.cli import main from ome_zarr.format import CurrentFo...
83660f267f66f300fe50767f04bdfbc6e26a13bca03b1dc4ced28b555aa98589
Python
9,421
176
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """tests for visualization of graphs""" import tempfile import unittest import numpy as np from scipy import sparse from sknetwork.data.test_graphs import test_disconnected_graph, test_bigraph_disconnect from sknetwork.data.toy_graphs import karate_club, painters, movie...
a92dcab2a189e488e495404c1fb2f38acae085287ab08be101039861ae8cb469
Python
9,421
238
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created in March 2024 @author: Thomas Bonald <bonald@enst.fr> @author: Ahmed Zaiou <ahmed.zaiou@capgemini.com> """ from typing import Union, Optional import numpy as np from scipy import sparse from sknetwork.clustering import Louvain from sknetwork.clustering.louvai...
bcfe2dd091287dc538f0269cba29a720bf6dd3cd81cdfa73aabe952f2b3de339
Python
9,422
296
from dataclasses import dataclass from time import perf_counter from itertools import repeat from typing import Union import jax import jax.numpy as jnp import plotly.io as pio from pypdf import PdfReader jax.config.update("jax_enable_x64", True) pio.templates.default = "plotly_white" # https://github.com/plotly/plot...
9e6027f72bdb0885cd8a879ccfaec9d2e87666a536733f15abb87ae3baa90e5a
Python
9,423
219
"""Utilities for parsing "Galaxy Flavored Markdown". See markdown_util.py for loading objects and interacting with the rest of Galaxy. This file is meant to be relatively self contained and just used to "parse" and validate Galaxy Markdown. Keeping things isolated to allow re-use of these utilities in other projects (...
f419c6a7e1a23cd1218145d4b04f69950c4579bae59ab317be2eee3f92d1eeee
Python
9,423
290
from __future__ import annotations from types import SimpleNamespace import pandas as pd import panel as pn import pytest from bokeh.document import Document from larvaworld.portal.datasets import ( EndpointDataFrameTable, LarvaDatasetTablesWidget, StepDataFrameTable, ) @pytest.fixture def step_datafra...
37376d4a9fb5e581bd0aed4942b20868312ec4fcae4bf25397163c30e65e0c04
Python
9,424
219
import functools import os import shutil from typing import ( Any, ) from galaxy import exceptions from galaxy.files.models import ( AnyRemoteEntry, BaseFileSourceConfiguration, BaseFileSourceTemplateConfiguration, FilesSourceRuntimeContext, RemoteDirectory, RemoteFile, ) from galaxy.util.c...
63c3834a71b52e7c0dae2ecc9dc378ad26558d75d388f4fad7728dc8457fd213
Python
9,425
245
# coding=utf-8 # Copyright 2024 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...
64080c596ccfed1a8fc957136284d07ffd6c52856d7528bb294acebf06511f82
Python
9,425
261
# SOURCE: vendored from pykt-team/pykt-toolkit @ main # (pykt/models/atdkt.py + the ut_mask helper it imports from pykt/models/utils.py) # # AT-DKT (Auxiliary Task Deep Knowledge Tracing): an LSTM-based knowledge-tracing model # (interaction embedding -> LSTM -> sigmoid output head) augmented, in its "predcurc"/ # "pre...
ea999c2118af5917f530baeee6e61fb268d42963bbbebff760ab4c7d7f67b218
Python
9,426
235
# -*- coding: utf-8 -*- from __future__ import print_function, division import os import os.path import json import subprocess import shutil import sys import glob from global_config import * generatingMultiViewImage = not generatingThicknessViewImage # generatingMultiViewImage to eval/repeat MVCNN is deprecated usin...
17a288d4da63a12e1967ef059aefc5a8a35b67948ca27a3dba556cd1609098dd
Python
9,429
264
# Copyright (c) 2022 PaddlePaddle 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 app...
e95eec7b30f6d460316fe3d3344c9a72cced96ade403c8830519cf2c3483436c
Python
9,429
278
""" Dataproviders that iterate over lines from their sources. """ import collections import logging import re from . import base log = logging.getLogger(__name__) _TODO = """ line offsets (skip to some place in a file) needs to work more efficiently than simply iterating till we're there capture tell() when pro...
02fc51b82a633410ccf672ae8d32c4e030b9d252e7b8458be7fdb7eddb78f1ce
Python
9,430
278
import copy import typing from typing import List import numpy as np import pytest import torch import torch.nn.functional as F from torch import Tensor, nn from lightly.loss import DINOLoss from lightly.models.modules.center import Center from lightly.models.utils import deactivate_requires_grad class OriginalDINO...
4652251123e1ebf696bbf6fe835b79a763ec19341620888fd93dbc52f05bc1e6
Python
9,430
266
import io import av from torch.utils.data import Dataset as TorchDataset, ConcatDataset, WeightedRandomSampler import torch import numpy as np import h5py import os from datasets.helpers.audiodatasets import PreprocessDataset, get_roll_func # specify AudioSet location in 'dataset_dir' # 3 files have to be located the...
f895843601bfeea87b94ca605206e9018b0a360b01b6c7765842374bb3a7f8d0
Python
9,430
266
#!/usr/bin/env python3 """ File: plot_cf_per_pic2.py Created: 2022/05/10 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. """ ...
a4fbd3dca212d0f0845dfa05a32cf4d30110b9a4b8410fbda84817667a9fe968
Python
9,431
271
from typing import Any, Dict import torch from torch.nn import ReLU from torch_geometric.nn import GATv2Conv, MessagePassing, global_add_pool from .base_funcs import * class GATEncoder(torch.nn.Module): """ Encoder layer to obtain the global state of each input graph. The global state will be """ ...
2b388af40c7af910422de5fa7f56139ef64d10dfee0574f04cbeb5d2c3a43e1e
Python
9,432
226
"""Artifact-registry contract tests (testing MEMO build rows A1/A2). The registry is the ONE authority for real-model artifacts: closed row schema, pinned revisions and per-blob digests, never-count enforcement for R0 rows, the exact-key cache digest, the byte-budget cap formula, and the consumes-never-constructs rule...
cfcc01b9354918a039b23165e2956ca738105f3480346e0323794f384ee8794b
Python
9,433
262
# SOURCE: vendored from https://github.com/hlxin/tinnet @ master (c80f5d12d304) # (tinnet/band_center.py's ConvLayer + CrystalGraphConvNet) # # TinNet (Lin, Wang, Cao, Xin, "Automated Discovery of Adsorbate-Metal # Interaction Descriptors from Machine Learning with Physics-Informed # Priors", Nature Communications 2024...
c7203015bce032766ba555be0e5c0207c5dca3cbf76a73b92398396197f18a66
Python
9,435
268
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import argparse import xlsxwriter from models import GraphConv, AE, LP from utils import * from sklearn.metrics import roc_curve, auc, roc_auc_score, precision_score, recall_score, f1_score, accuracy_score parser = argparse.Argument...
146d417547877fdc50d4c75d4a443818605a10f7c2ff6f2eb88cad7db1d4c859
Python
9,437
201
class Model(): def __init__(self, model_name, input_shape, model_type): self.model_name = model_name self.model_type = model_type if len(input_shape) == 4: input_shape.append(input_shape.pop(1)) # change BCHW to BHWC self.input_shape = tuple(input_shape) self...
ba80a267a99cee92039dacc2d23febce225ecd84286351fe7cae3059a4b5713b
Python
9,438
208
# Copyright (c) ByteDance, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from timm.models.layers import DropPath _cur_active: torch.Tensor = None #...
0ce2682a9d15c7d2eb8736abd14ebc982efad1d7f4a7d9f022d6534a44634d82
Python
9,439
252
"""Tests for OSM(complete_relations=True): completing the member set of relations that straddle a bounding box, so their geometries are correct (not cut at the box edge). Uses the real bundled Helsinki extract and the downloadable history file.""" import pytest import shapely from pyrosm import OSM, get_data @pytest...
1c8e0109f94a31417c7dc678b2b2a0ed5886d08f58fb967b88fdb0f63ea14752
Python
9,439
224
"""Extract DICOM images """ import os from os.path import join as opj import numpy as np import pydicom from scripts.utils.constants import IGNORE_SAMPLES_AT_DATES, MRI_ROOTDIR, MRI_IMG_DIR, DWMRI_IMG_DIR, T2STAR_DIRS from scripts.utils.minor_utils import min_max_norm class DICOMImageExtractor(): """"Extract DI...
14bd134595486c9563cfa82c035cf18c0b3331ad7ec4d2f1ea4f8679a1357385
Python
9,441
304
import sys sys.path.append('..') sys.path.append('../..') import os import datasets as dat from analysis_lib import * import numpy as np from copy import deepcopy # Analyze freeform task, and produce HTML file with model outputs. # Compare human and machine samples. def analyze_mapping(sample): # augment with annota...
e6ea3a59eacdff4e727f1fc9648c5e1a5f1ffb0b8243f00dc90747b9b345cd4b
Python
9,445
315
import numpy as np np.random.seed(13) # VOCABS -- for DNA/RNA only for now DNA = ["A", "C", "G", "T"] RNA = ["A", "C", "G", "U"] COMPLEMENT_DNA = {"A": "T", "C": "G", "G": "C", "T": "A"} COMPLEMENT_RNA = {"A": "U", "C": "G", "G": "C", "U": "A"} # exact concise def _get_vocab(vocab): if vocab == "DNA": re...
6c5dcce45a9e28eab4f6d69ef18d7389a23dd489384754a032ca051def753c20
Python
9,446
253
"""A-RAGGED-DOCS: routed-MoE neutral-grouper regression (COORDINATE test). Pins foldB D11 on a real routed mixture-of-experts architecture family: the landed episode grouper keys on successive top-level calls of the declared stepped module, never on pass-interior graph equality — a ragged interior (experts absent from...
b6a664a0446c4c2366da50a80d691ccf768229093b89786ca01e29e1c7eb4670
Python
9,447
270
"""Memcached and in-memory cache result backend.""" from kombu.utils.encoding import bytes_to_str, ensure_bytes from kombu.utils.objects import cached_property from celery.exceptions import ImproperlyConfigured from celery.utils import deprecated from celery.utils.functional import LRUCache from celery.utils.log impor...
0272f2a5bb2bf4425e95edfe79c94517b06a3938cad86a3b0089440d6bd4d71e
Python
9,449
268
"""The layer map: one declared stratum per package/module (C01 item 1). The ten-layer model (architecture memo 3.1). A module's layer resolves module attribute first (``__tl_layer__`` in the module), then the most specific row here. ``FACADE`` is a ROLE, not a layer: thin, lazy, logic-free modules whose deferred upwar...
5067ebc58f3ac12d110c814b5cd8e29c5e79710bf789e2c91a16c8dbfa4c98f7
Python
9,449
213
import numpy as np import pandas as pd import os import glob import math import json import scipy import scipy.stats import pickle as pckl from PIL import Image import model_analysis_folders.all_model_info as all_model_info from torchvision import transforms from analysis_scripts.helpers_16_choice import force_16_c...
7b9fabf2cc3d7f5f5ae3adf0ad177b5d852c1a9933258c63ce42de7859a2e1bf
Python
9,449
244
import unittest import numpy as np import pickle from os.path import join, abspath from spitfire import ChemicalMechanismSpec, Flamelet, FlameletSpec def construct_adiabatic_flamelet(initialization, grid_type, diss_rate_form): test_xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml')) mechanism = C...
82be70ef15510062137ac0a62b6cee6c6b626f8b5d0d27c90b00c3632ceb173d
Python
9,450
290
from __future__ import annotations import sys import pytest np = pytest.importorskip("numpy") eigen_tensor = pytest.importorskip("pybind11_tests.eigen_tensor") submodules = [eigen_tensor.c_style, eigen_tensor.f_style] try: import eigen_tensor_avoid_stl_array as avoid submodules += [avoid.c_style, avoid.f_st...
9c2ddb542ebedfcf895e41d952f14985d6eb58f4f92b272ee5fe3c0481793676
Python
9,450
254
"""Parse-time hardening for runnable descriptors (grind b3-l1, R10 supplement B).""" from __future__ import annotations import json from pathlib import Path import pytest import torch from torch import nn import torchlens as tl from torchlens._io.runnable_load import ( ContextFieldInvalidError, _parse_rng_p...
c2f4ca3a3cf9a4c6791feddc367a8a71be44708e323e0a6efc8222f3f93565eb
Python
9,450
264
import os import json import random import itertools import numpy as np import torch from collections import defaultdict from src.data.tokenize import tokenize_pet_txt, tokenize_pet_mlm_txt from src.utils.util import device class GenericReader(object): ''' GenericReader reads generic dataset ''' def ...
aed74d6857724d6792a86078ef44586495c428029fdd596d12dc478c3ae3ef25
Python
9,451
221
from collections import Counter import dgl import numpy as np def sigmoid(x: int): """" Compute sigmoid function by definition """ return 1/(1+np.exp(x)) def get_genes(graphs_nr: int, nodes_per_graph_nr: int, graph: dgl.DGLGraph): """ Compute the genes/features for all graphs :param gra...
6ef83815ea2dad5a6b007f62421b98cc9df743a0a51ca08e9fc9871ca71a8a17
Python
9,454
230
import torch import torch.nn as nn import torch.nn.functional as F import sys sys.path.append("models/") from .mlp import MLP class GraphCNN(nn.Module): def __init__(self, num_layers, num_mlp_layers, input_dim, hidden_dim, output_dim, final_dropout, learn_eps, graph_pooling_type, neighbor_pooling_type, device): ...
d8104ee62f5943645971d59b47f3ad3c123342e41ec232efdfdac327661ce69b
Python
9,454
263
"""Echo failure package: two tails, exact ordering, original exception wins. Pins snoop memo test rows 5 and 7 (crash tails on both tiers, exact tail order, exception identity preserved), the double-fault contract (a broken sink never outranks the model's own error), interrupt handling, the raise_on_nan composition (l...
9b81d02cab43f25c34244dda29f774fb54ac402b1e1384b530972f7fb98f43d8
Python
9,456
252
"""tviz renderer Stage-0 deterministic checks (memo D3/D4/D13/D16/D21/section 7). Emitter honesty rows that a deterministic check can prove and therefore never consume judge budget: zero ``<image>`` elements in every numeric SVG, PDF text extraction in order, disclosure lines rendered, pagination that drops nothing, t...
4c0b1323278c5f84bbce28ab11d3c86d4877f47061f5487872648e80e42905a9
Python
9,458
203
# Copyright (c) 2022 PaddlePaddle 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 app...
f63196f8b848ec11394f20b162000fb3def6e65eafb7961f52e645482cab21d0
Python
9,458
274
import os import math import time import datetime from multiprocessing import Process from multiprocessing import Queue import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import imageio import torch import torch.optim as optim import torch.optim.lr_scheduler as lrs class time...
0c6752487a585278528bb2ca45755255a84bf590b3ffae533fa9b1cc136d8b48
Python
9,460
262
""" Contract tests for data_conf.py configurations. Tests configuration validation and contract adherence. No I/O, pure validation logic testing. Target: data_conf.py: 40.62% → 70% (+118 lines) """ import pytest from larvaworld.lib.reg.stored_confs import data_conf @pytest.mark.fast class TestDataConfContracts: ...
689540851554f29bc07b78922e5115049252c1eee3990e5c5b5286edc0440899
Python
9,462
309
"""L6 stage-4b attribution-kit behavior and detachability gates.""" from __future__ import annotations import ast import re from pathlib import Path from typing import Any import pytest import torch from _source_corpus import module_ast, package_files from torch import Tensor, nn import torchlens as tl from torchle...
4b1374ab00092b7377a147953de98ea1420ee0400400520a57723eabf3c0a676
Python
9,464
253
""" Functions to create trial-based tensors and warp times """ import inspect from functools import wraps from numbers import Number import numpy as np from .. import core as nap def _validate_warping_inputs(func): @wraps(func) def wrapper(*args, **kwargs): # Validate each positional argument ...
b8648b2fa45087bf698a9b74a058795d324af8e83e4f3a08abe5212f4c98c294
Python
9,465
203
# Copyright (c) 2022 PaddlePaddle 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 app...
7a22a40008f909946924684b90c638f7d8e8bff079d7b038880bf00310480f09
Python
9,470
216
# coding: utf-8 # code adapted from MoleImg https://github.com/MoleImg/Attention_UNet/blob/master/AttResUNet.py import tensorflow as tf from tensorflow.keras.layers import * from tensorflow.keras import backend as K ''' Hyper-parameters ''' # network structure FILTER_SIZE = 3 # size of the convolutional filter DOWN_S...
05930d5d6c0c8acab88f6a6c547b92e81878a4f7fb3082b11faa88f396abe965
Python
9,472
197
from __future__ import division from psychrnn.tasks.task import Task import numpy as np class DelayedDiscrimination(Task): """Delayed discrimination task. Following a fore period, the network receives an input, followed by a delay. After the delay the network receives a second input. The second input channe...
b473208a758160bbf0522a6073a6afacb9f293c1ef05250df7ca2efa09832f6a
Python
9,476
321
# 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...
97f7e43d0e98541646cf800d8c005b85112b6b6d50566f97fc828ca998286187
Python
9,479
160
__doc__ = """ Compute single trial bias estimates. In order to run this file, you will need to first run the "analysis*.py" scripts. This will generate backup files in the folder sim_backup. This code was adapted from Fründ, Wichmann, Macke (2014): Quantifying the effect of inter-trial dependence on perceptual decisio...
fcb307317258fee99694492c270754e253346f764abafc885e048305542cf576
Python
9,481
210
""" Théo Gauvrit Mai 2020 Compute the detection of Upstate and Downstates from two datasets(WT,KO). Each Up/Downstates parameters from every files will be returned in a dataframe. A dataframe (Metrics) can be returned to have visual of the detection in the signal in a plot. """ import numpy as np import math as math f...
b45b476653b82a05235b36398f0b1972dda5a1499ec5cdbabd5d14cd18038e8c
Python
9,482
292
from conftest import get_distances import numpy as np from numpy.testing import assert_array_almost_equal from scipy.spatial.distance import euclidean, mahalanobis import pytest from pytest import approx from pyriemann.utils.distance import ( distance_euclid, distance_harmonic, distance_kullback, dista...
6f87667fe8c96f2b3dd2b3d884e8a5986be7355c5e162c6efc182320a5365a0d
Python
9,483
231
"""Power spectrum plotting functions. Notes ----- This file contains functions for plotting power spectra, that take in data directly. """ from inspect import isfunction from itertools import repeat, cycle import numpy as np from specparam.modutils.dependencies import safe_import, check_dependency from specparam.ut...
3aad61f46db35d2b076de0c3df6402a7dee3d23c7dc5dc0911f82ce6d07f0cd3
Python
9,489
285
"""Steering a HF decoder block as a MODULE site, KV cache on, agrees with a forward hook. The common steering case: ``tl.when(tl.module("model.layers.0"), tl.steer(v))`` on a causal LM whose ``use_cache`` is on. A module site is not an ``in_module`` region, so the region refusal for exits into returned cache tensors (...
6861942bf311b71875b348e409d515cc435c735657ccb1cd5aadca962381caac
Python
9,489
240
import inspect from functools import partial from typing import Callable, Iterable, Optional import torch import torch.nn.functional as F from timm.models import _manipulate from timm.models.vision_transformer import Attention, Block, VisionTransformer from torch import Tensor, jit def _checkpoint_seq(blocks: Iterab...
3759e196e7a0a6541c303200ca6e092bcdc30613f9f3f3d61a53c9810a60103b
Python
9,490
231
# Fixes for defective mne functions from collections import defaultdict from distutils.version import LooseVersion import os.path as op import numpy as np from mne.surface import read_surface from mne.utils import get_subjects_dir, logger, verbose from mne.label import _get_annot_fname, _n_colors, _write_annot import...
3f9d040e2d5f14ec75204ae592b2d8b2f28322e5ddca58107bcf9492e681be08
Python
9,491
246
# %% import numpy as np import os import pandas as pd import itertools from globals import threshold_distance path = "/Users/ivan/Documents/aaa_online_stuff/coding/python/phd/expt17_spots/data" sessions = range(1, 5) subjects = [3, 4, 6, 7, 8, 9, 10, 11] def euclidean_distance(x, y): return np.sqrt(np.sum((x - ...
6f97464580ccb38d4cbbc60b4eff734bf708f9666ccef1702903c500cfa3dc16
Python
9,491
230
from __future__ import absolute_import, division, print_function from . import swigwrapper # pylint: disable=import-self # This module is built with SWIG_PYTHON_STRICT_BYTE_CHAR so we must handle # string encoding explicitly, here and throughout this file. __version__ = swigwrapper.__version__.decode('utf-8') # Hack...
14cff40525bd61bcf7da5dc6a0c92546d3014162efb13df6c4aea55d5f4d9628
Python
9,495
306
# %% ''' Perform statistics and plots on connectivity results ''' from nilearn import plotting from numpy.ma import mask_rowcols import pingouin as pg import seaborn as sns import h5py import numpy as np import pandas as pd import matplotlib.pyplot as plt from bct.nbs import nbs_bct import sys sys.path.insert(0, '..'...
9149f4f5ff852775248ffdfcc9c4c032bfdc5d49a1798fd4bf2b323321aa2b3b
Python
9,495
180
#!/usr/bin/env python from __future__ import print_function, unicode_literals, absolute_import, division import argparse import sys from pprint import pprint import numpy as np from tqdm import tqdm from csbdeep.io import save_tiff_imagej_compatible from csbdeep.utils import _raise, axes_check_and_normalize from cs...
32bb2fcef3798d5ba31d6107ea34a63d718e2ed2e959ceedc50178c0a2f9cefd
Python
9,496
268
from pathlib import Path from typing import Any, Dict, List, Tuple, Union from pytorch_lightning import Trainer from pytorch_lightning.callbacks import DeviceStatsMonitor, LearningRateMonitor from pytorch_lightning.loggers import TensorBoardLogger from timm.data import create_transform from timm.data.mixup import Mixu...
a4c76a67b34810bdbd0ce3267f9945da51b65c48bb068fa40aa44e05f73e44bb
Python
9,496
310
import torch.nn as nn from modular_splicing.utils.construct import construct from modular_splicing.models.modules.lssi_in_model import both_lssi_model_types from modular_splicing.models.motif_models.types import motif_model_types from modular_splicing.models.local_splicepoint_model_residual_propagator import ( Ea...
2f21f4d5a3ff27f9d8de963f729ae50265c8b133662f16fb75a99eaf7ec62fe4
Python
9,497
289
#!/usr/bin/env python # # Copyright 2006, 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...