sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
ee8b7ee0ff17a09c2e23d95861a31002ed47460e7bb86063272ee4b64fc4436a | Python | 3,170 | 99 | import pytest
from BM3D.src.step2 import *
def test_step2_final_estimation():
basic_estimate_img = np.zeros((42, 42))
noisy_image = np.zeros((42, 42))
param = (8, 16, 32, 32, 10, 1.5, "cos")
mask = np.ones((42, 42))
verbose = False
# Test 1: Ensure the function returns an array of the correct... |
3768040b8e460806aacb7eabc0da1e6956ef61b3cd69bea0d1596245b72d6ccd | Python | 3,171 | 94 | import os
from fsspec import AbstractFileSystem
from galaxy.exceptions import MessageException
from galaxy.files.models import (
AnyRemoteEntry,
FilesSourceRuntimeContext,
RemoteDirectory,
RemoteFile,
)
from galaxy.files.sources._defaults import DEFAULT_SCHEME
from galaxy.files.sources._fsspec import ... |
3f653ad0ea89a32142e006d36cb759cf8ee752e8b5fb5e5a8eb83cf6bd0d4601 | Python | 3,171 | 84 | """Avey: sequence-length-invariant ranker plus neural processor architecture.
Paper: "Don't Pay Attention" / Avey1, 2025.
Avey slices sequences into chunks, ranks relevant chunks for each local context,
and applies a neural processor rather than full quadratic self-attention or a
left-to-right recurrence. This compa... |
29a9b4f4e2bcd2a14ef63cb1107044db69cc82ad6d9df5ae580d386e47a22d3e | Python | 3,172 | 92 | # fix problems with pythons terrible import system
import os
import sys
file_dir = os.path.dirname(os.path.realpath(__file__))
#sys.path.append(os.path.join(file_dir, '../bin/'))
sys.path.append(os.path.join(file_dir, '..'))
# useful imports
from prob2020.python.gene_sequence import GeneSequence
from prob2020.python.s... |
5dda777736c02e948725666f2e852bed757fde0813325a2487e22279f8c341ea | Python | 3,172 | 133 | """
Records describing an inspected model and its modules.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal
import pandas as pd
@dataclass(frozen=True)
class ModuleInspection:
"""One module of an inspected model, with its parameters."""
module... |
46672f9518bc687a17a1ff1ff517e1c941141f95ab13a3973c375e97323e0a12 | Python | 3,173 | 94 | # 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 compl... |
4ddb20275082660e9cc189cb2efac3af811ce54a95684e220109d6473b6ff284 | Python | 3,173 | 100 | # Copyright 2019 Novartis Institutes for BioMedical Research Inc. 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... |
0b4a8e725da4c2287a74214d93fa5047b3ab6639430c3e6f3eba44979a05ece3 | Python | 3,174 | 101 | '''
Generate ESM-1b embeddings (per position) and save as one
file per sequence. Use md5 hash of sequence as file name.
Adapted from DeepTMHMM.
'''
from hashlib import md5
from esm import Alphabet, FastaBatchedDataset, ProteinBertModel, pretrained, FastaBatchedDataset
import torch
import os
import argparse
import path... |
203bc2fe7a13088f740db9b49247c29f71c6a658b195c88fb8c74b2123cf9033 | Python | 3,175 | 78 | # dataset: mne_sample
"""
This example demonstrates how to load and plot MEG data
It uses the mne sample dataset which included presentaton of simple (A)uditory
and (V)isual stimuli to the (L)eft and (R)ight ear/visual hemifield, as well as
presentation of smiley faces and button presses by the subject.
All the lines... |
296d7ed13c0d56151088a2e6f8d43eb2da0b92b3251da335eedee2723864573a | Python | 3,175 | 108 | # This example requires the following dependencies to be installed:
# pip install "lightly[timm]"
# Note: The model and training settings do not follow the reference settings
# from the paper. The settings are chosen such that the example can easily be
# run on a small dataset with a single GPU.
import torch
import t... |
773a2f9b4320b5dda6f086f91ed458092e1c2d517fc8a61de5e0b16c676a0303 | Python | 3,175 | 103 | """This module contains simple helper functions """
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
def tensor2im(input_image, imtype=np.uint8):
""""Converts a Tensor array into a numpy image array.
Parameters:
input_image (tensor) -- the input i... |
964db38f397c91512f437913fd479daf4dadc3c1e6bc5d6af735807eb7134dca | Python | 3,175 | 90 | """Parity sweep across our own doors (M(oracles) item 10; F36 oracle wave 1).
Parity is internal agreement -- it never fills an oracle cell (D4), but a
DISAGREEMENT between two of our own doors is always a defect. One capture,
every counting door, one set of numbers; plus the banned-token sweep over
every text door (d... |
9e55118197a89bba69f4906c91a478f437c4d9ba09b3777595d82f797beb987e | Python | 3,175 | 105 | import pathlib
import os
from PyQt6.QtWidgets import QWidget
from PyQt6 import QtCore
from bmlab.session import Session
from bmicro.gui.main import BMicro, check_event_mime_data
def data_file_path(file_name):
return pathlib.Path(__file__).parent.parent / 'data' / file_name
def test_main_window_can_activate_a... |
42c3af3b65afcb1b617710a44448b8012a7199bec90c474f5fdeb29de7d9c316 | Python | 3,176 | 73 | """The lightly.transforms package transforms for various self-supervised learning
methods.
It also contains some additional transforms that are not part of torchvisions
transforms.
"""
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
from lightly.transforms.aim_transform import AIMTransform... |
6a93c91a031d770ffe422c343ac4c32f7726309f064cc0b4f1d2d39a2604596f | Python | 3,176 | 80 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""tests for layers"""
import unittest
import numpy as np
from sknetwork.data.test_graphs import test_graph
from sknetwork.gnn.layer import Convolution, get_layer
class TestLayer(unittest.TestCase):
def setUp(self) -> None:
"""Test graph for tests."""
... |
d0d40238e9f75af14fe64553de6b9dc55e037dbc564e042e7c2560919d257601 | Python | 3,176 | 89 | """
Dynamic Energy Budget (DEB) Theory - Standard Parameters for the Generalized Animal
This file provides the baseline parameter values for the DEB 'generalized animal'
at a reference temperature of 293.15 K (20 °C). These standardized parameters serve
as pseudo-data anchors within the Add-my-Pet database framework t... |
2e5a5905f4d0d86b1ec3f706ed75c5818554f7aabf6e9dd6d2496d8195801f86 | Python | 3,177 | 93 | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Test objects and function in tfep.utils.plumed.auxreader.
"""
# ==============================================... |
5ed09f6ef893fbd7e3d6ee71d091ff903929a348781b5e84df65ddb8c795b708 | Python | 3,178 | 101 | from typing import Any, Callable, Optional, Tuple, TypeVar
import torch
import torch.distributed as dist
from torch.autograd.function import FunctionCtx
class GatherLayer(torch.autograd.Function):
"""Gather tensors from all processes, supporting backward propagation.
Adapted from the Solo-Learn project:
... |
a23a64db12cf01dc0166c4c9f466beb5b6890eb94eca5564369fc7d3a2d46c6b | Python | 3,178 | 77 | #
# Galaxy sphinxcontrib-simpleversioning documentation build configuration file
# This file is appended to conf.py by the Build docs github workflow.
#
import re
from subprocess import check_output
from packaging.version import Version
# This is set in the Jenkins matrix config
TARGET_GIT_BRANCH = os.environ.get("TA... |
b4c6a398138c4b30361f44d1291240eedba9f7cf61dce9f365353de0ce8405d2 | Python | 3,179 | 99 | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Test layers in tfep.nn.flows.partial.
"""
# ==================================================================... |
b9d011eb67a16dbed4294eb7559403f4cb2e8c42a8dffe55b02c44c30040d8c8 | Python | 3,179 | 80 | #! /usr/bin/env python
"""
galaxy_config_merger.py
Created by Anne Pajon on 31 Jan 2012
Copyright (c) 2012 Cancer Research UK - Cambridge Research Institute.
Script for merging specific local Galaxy config galaxy.ini.cri with default Galaxy galaxy.ini.sample
"""
import configparser
import logging
import optparse
im... |
bf0d71e69d961b40b121643cdbdfa6141bc3ec671cd1f4530a1a56e14ba668e6 | Python | 3,179 | 86 | import warnings
warnings.filterwarnings('default', category=DeprecationWarning)
def script_is_deprecated():
warnings.warn("myanndata.py is deprecated. Functions move to cembav2env.sa2.py.")
script_is_deprecated()
from typing import List, Dict
import numpy as np
import pandas as pd
import anndata as ad
def groupe... |
0feddaa9a4f15cb8d8045928c8a26b53761b567c00a41ef11d2b0325c51dceb8 | Python | 3,181 | 84 | import torch
import torch.nn as nn
import torch.nn.functional as F
class BaseLoss:
def __init__(self, get_params, lam, lam0=None, crop=0, detach_target=False):
self._get_params = get_params
self._lam = lam
self._lam0 = lam0
self._crop = crop
self._detach_target = detach_ta... |
362be97a788e9d301f16276563f933ee800a884826748452c544650ebbbe300e | Python | 3,182 | 76 | import pandas as pd
import numpy as np
from skmob import TrajDataFrame
from skmob.utils import constants
from skmob.preprocessing import clustering
class TestClustering:
def setup_method(self):
latitude = constants.LATITUDE
longitude = constants.LONGITUDE
date_time = constants.DATETIME
... |
823a6dd5f311bfd561c9fe8bc61bd847df176c74f9d89ce25742c0f042b43cc2 | Python | 3,182 | 112 | """Tests for the reusable parameter lookup/load/save functions."""
from __future__ import annotations
from pathlib import Path
import pytest
from larvaworld.lib import reg
from larvaworld.portal.parameter_database.parameter_funcs import (
get_param_instance,
register_new_param,
remove_param,
save_pa... |
a66b665394affbdf0297dc64d18f6a180bd0f794a85ffe7666d50ce7f0dda566 | Python | 3,183 | 116 | import numpy as np
from modular_splicing.evaluation.evaluation_criterion import DefaultEvaluationCriterion
from .run_model import run_model_on_all_batches
def top_kl_accuracy(y_true, y_pred, top_length=1):
"""
Compute topk-l accuracy. By default, l=1.
Parameters
----------
y_true : array-like, s... |
b3d94fcfa68e1a1583a348f734c0c9dcba4683f6d84c250813c56d259f7d33e9 | Python | 3,183 | 88 | import tensorflow as tf
from tensorflow.keras.layers import Layer
class IntensityToSpikeLatency(Layer):
def __init__(self, N, t_eff=50e-3, theta=0.2, **kwargs):
super().__init__(**kwargs)
self.N = N
self.t_eff = t_eff
self.theta = theta
def build(self, input_shape):
su... |
b69f6a35805c688f53d47082e9ba8ca46ffe78cfa76be7c635e183ccc653bb60 | Python | 3,183 | 77 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for DiffusionClassifier"""
import unittest
from sknetwork.classification import DiffusionClassifier
from sknetwork.data.test_graphs import *
class TestDiffusionClassifier(unittest.TestCase):
def test_graph(self):
adjacency = test_graph()
n... |
edc598ede1377127307e1a29a1839cb661abaf9d6759dbfa228af74eb5d1aedc | Python | 3,183 | 98 | import os
import sys
from autouri import AutoURI
from caper.cromwell import Cromwell
from caper.cromwell_metadata import CromwellMetadata
from .example_wdl import make_directory_with_failing_wdls, make_directory_with_wdls
def test_on_successful_workflow(tmp_path, cromwell, womtool):
fileobj_stdout = sys.stdout... |
4d65bf3f8956a1f9077a8a4291e50a946eead289be5473724a818963b2d9e9e6 | Python | 3,184 | 109 | import os
import json
import rclpy
import threading
from rclpy.node import Node
from rclpy.parameter import Parameter
from std_msgs.msg import Bool, String, Int32
from rosgraph_msgs.msg import Clock
class SyncROSNode(Node):
def __init__(self):
'''
Initialize the SyncROSNode.
'''
sup... |
805b359e081f6c19de0958d08f7b61ee90a765a0a33c193884817965ef75cf80 | Python | 3,184 | 78 | """W051-MECH regression pins for AUD-CODE 2.11: roofline parameter traffic.
The roofline's read-once/write-once traffic model read the parameter term
through ``getattr(op, "params_memory", None)`` -- a misspelling of the Op
field ``param_memory`` -- so every parameter byte silently vanished and a
Linear(256, 512) repo... |
048480b5834c65fe64688ace46cd65d5df3e7357be0a232c1f4d36998741df8a | Python | 3,185 | 105 | from typing import Literal
import numpy as np
from anndata import AnnData
from PIL import Image
from sklearn.decomposition import PCA
from tqdm import tqdm
from .model_zoo import Model
_CNN_BASE = Literal["resnet50", "vgg16", "inception_v3", "xception"]
def extract_feature(
adata: AnnData,
cnn_base: _CNN_B... |
0ad26aae91a6dad5f045480695bf52359b73b88f2a43fafbe360c2254ff07aaa | Python | 3,185 | 88 | #!/usr/bin/env python3
import sys
def read_params(args):
import argparse as ap
import textwrap
p = ap.ArgumentParser( description= '''
Script will convert QIIME TSV BIOM table for use with lefse. It is imperative that this table has taxa metadata associated with it named 'Consensus Lineage', this ca... |
106efce2a3cb7c41bb8e949045e571af9a8e57c740d809612085420804f9f19e | Python | 3,185 | 84 | #!/usr/bin/env python
#=========================================================================
#
# 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://... |
637cd63cdca24faa77cad144cf0e3716e244a9186d5e954475b22303464633d3 | Python | 3,185 | 103 | # Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
import sys
import numpy as np
import pytest
from eelbrain import datasets, plot, _info, NDVar
from eelbrain.testing import hide_plots, requires_mne_testing_data
@hide_plots
@requires_mne_testing_data
def test_plot_brain():
"""Test plot.brain plots"""
... |
7f9a266968c65af1876b51f2002ef034584ad87a711d29763f1932e68ee14b71 | Python | 3,185 | 97 | """Phase 4a intervention capture plumbing tests."""
from __future__ import annotations
import pytest
import torch
from example_models import TinyReluAdd as _TinyInterventionModel
import torchlens as tl
from torchlens import _state
from torchlens.options import CaptureOptions
class _MultiOutputModel(torch.nn.Module... |
191c2fea4a2f16fb2d996de886dca02cbed2763a12579c8e351aefe9ac989356 | Python | 3,186 | 80 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Optional
import torch
from torch import Tensor
from scene_graph_prediction.scene_graph_helpers.model.pointnets.networks_base import BaseNetwork, mySequential
from torch_geometric.nn.conv import MessagePassing
from torch_scatter import scatter
def build... |
9762a479a86b9cb1a567faf2f44ff8a8d168c9afff7b2c42bd61dd177019f1e7 | Python | 3,186 | 90 | '''
Copyright 2021 Twente Medical Systems international B.V., Oldenzaal The Netherlands
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 requir... |
19bd26811955ee0134870a46eadad1adb9289d086a7ef2d85c6dd3112715cb98 | Python | 3,187 | 95 | """Intervention honesty: editing a DENSE direction's support set discloses at
the point of use (list-A row 8).
``tl.subspace`` is a SET producer: a dense direction supports the whole bound
axis, so ``do(subspace(dense), edit)`` performs full-axis ablation -- the
documented semantics, but the producer's own motivating ... |
80b426734dbff14bbd153df54a172cdc070c9370766b4405898a3ac00b925875 | Python | 3,187 | 93 | import pandas as pd
from tqdm import tqdm
from joblib import Parallel, delayed
from irnlm.data.utils import (
get_negations,
get_pronouns,
get_positions_words,
get_quantity_words,
get_function_words,
get_punctuation,
)
from irnlm.data.text_tokenizer import tokenize
def get_mapping(language):
... |
a7402c2d793fcc8d8b90764b5cd19fd8b57c87cd3d9cb0ca5a97b742f894756f | Python | 3,187 | 106 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Logging."""
import atexit
import builtins
import decimal
import functools
import logging
import os
import sys
import simplejson
import slowfast.utils.distributed as du
from slowfast.utils.env import pathmgr
def _suppr... |
8c679a4389f2b16c72f90f5c958087f998a26532669816bd4a7fe9b5b538732f | Python | 3,188 | 88 | """ Conv2d + BN + Act
Hacked together by / Copyright 2020 Ross Wightman
"""
import functools
from torch import nn as nn
from .create_conv2d import create_conv2d
from .create_norm_act import get_norm_act_layer
class ConvNormAct(nn.Module):
def __init__(
self, in_channels, out_channels, kernel_size=1,... |
b4ec6b12fb9d78dfb66173e49ad096950f9985ca24f6db719947f9c5495b84c0 | Python | 3,188 | 94 | """
Implements the methodology blueprint.
"""
from dash_extensions.enrich import DashBlueprint, PrefixIdTransform
from dash import html, dcc
from utils.utils import custom_prefix_escape
from blueprints.translation.translatable_markdown_text_blueprint import translatable_markdown_text
from blueprints.translation.tran... |
9e593d9c28ba151de7f21e7e1851b3cf9f3471f85b4ac6d8d4f1539688641172 | Python | 3,189 | 73 | import torch
import copy
import time
import utility
import data
import model
import loss
from option import args
from trainer import Trainer
from torchinfo import summary
from thop import profile, clever_format
torch.manual_seed(args.seed)
checkpoint = utility.checkpoint(args)
def main():
global model
if ch... |
b1125498712deb648b66e88903b16616e9bd90e40c71b972c65333e4752b775d | Python | 3,189 | 69 | import pandas as pd
from functools import reduce
#Load metadata
phase = 3
cols_meta = ['RID']
df_metadata = pd.read_csv('../DATA/adni%d_mri.csv'%phase, usecols=cols_meta)
rids_meta = set(df_metadata['RID'].tolist())
# Preprocesing of dataframes to obtain desired patients
def process_dataframe(file_name, cols, rids, p... |
0ae5a454df99aff01a58429ed7113dc0a7623a3f8ddcbd9f78366add4f399ed2 | Python | 3,190 | 94 | # This example requires the following dependencies to be installed:
# pip install lightly
# Note: The model and training settings do not follow the reference settings
# from the paper. The settings are chosen such that the example can easily be
# run on a small dataset with a single GPU.
import copy
import pytorch_l... |
764d505ed83b330458d21e93728a8093287a487c4fb508b52e7852115946bdd3 | Python | 3,190 | 98 | #!/usr/bin/env python
__author__ = "Bjoern Gruening"
__version__ = "0.1"
__date__ = "2014"
__license__ = "GLP3+"
import argparse
import ftplib
import gzip
import os
import shutil
import tempfile
import urllib
import zipfile
from multiprocessing import Pool
PUBCHEM_URL = "ftp://ftp.ncbi.nlm.nih.gov/pubchem/Bioassay/C... |
9b77360428c0b24066a27321b6182051018c3c72f9165069b702673419f41f58 | Python | 3,190 | 88 | """
We're going to aggregate embeddings run for a particular order of n-gram here (we'll just add them up).
"""
from transformers import BertModel, DistilBertModel
from transformers import pipeline
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import datasets
import numpy as np
import pick... |
449a1a4ed2af419cb71a9e15e3ff79797abc417ff44b2e5c41ea2f3ba2ab1207 | Python | 3,191 | 102 | #!/usr/bin/env python
import csv
import sys, getopt
import os
import HTSeq
from collections import defaultdict
### Setup all cut-off
# RPMF cut-off
RPMF_CUTOFF = 4
# window occurence
#OCCURENCE_CUTOFF = 2
def get_peak_position(peak_file, annotation_file):
dict_peaks = dict()
PATH_PEAKS = peak_file
dict_peak_wind... |
c574a5a6dac8fdd61f5cc40c804119f3ff8c9712dc4964fd609719047e2b029b | Python | 3,191 | 103 | #!/usr/bin/env python
import logging
import os
from eden.converter.fasta import fasta_to_sequence, sequence_to_eden
from eden.graph import Vectorizer
from eden.model_base import main_script, ModelInitializerBase
from eden.modifier.seq import mark_modifier, seq_to_seq, shuffle_modifier
description = """
Explicit Deco... |
770a603a6f47964a3d53421ee078524260d50ec365c6bf714a140f6d20c2b734 | Python | 3,192 | 87 | """Gradient Accummlate for training TF2 custom training loop.
Copy from https://github.com/OpenNMT/OpenNMT-tf/blob/master/opennmt/optimizers/utils.py.
"""
import re
import tensorflow as tf
class GradientAccumulator(object):
"""Gradient accumulation utility.
When used with a distribution strategy, the accumu... |
6f6a70df70d81cdb61ca6b31103547a276d36eae8b08edaddffdba5a16bfffcf | Python | 3,193 | 108 | # --- 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 Line(_BaseLayoutHierarchyType):
_parent_path_str = "layout.map.layer"
_... |
e2e9740305b2c01b2df2dcf9bf62b94d6fbeb1293776cb9404ed58cb22200f88 | Python | 3,194 | 114 |
from pathlib import Path
import re
from natsort import natsorted
# Our modules
import data
def ls_cohorts():
return [f.name for f in
Path(f'data/').iterdir() if f.is_dir()]
def get_weights_tree(basepath):
node = {}
node['dirs'] = {}
node['fnames'] = []
for f in basepath.iterdir():
... |
3669671d8f3a5aeb6bf6e2294df58471e81b2a7d17f363d890683dae2fe433f0 | Python | 3,197 | 91 | import glob
import os
import sys
import argparse
import mne
import numpy as np
import pandas
import pylab
from mne.datasets import fetch_fsaverage
from tqdm import tqdm
from mp_dip.research.show_example_dipole import show_example
def show_dipole_locations(example, transform, subjects_dir):
dipole_pos = np.arra... |
69c5c4c88c3fdb67a5e807365beaf79b90c3a57f372dcc5eddcbe7d33723f5cd | Python | 3,197 | 89 | """Configuration error tests for train-mode capture."""
from __future__ import annotations
from pathlib import Path
import pytest
import torch
from torch import nn
import torchlens as tl
from torchlens.fastlog import RecordingConfigError
def test_train_mode_save_outs_to_path_errors(tmp_path: Path) -> None:
""... |
b63e48a1e519b92cc0d7ff36505afba3ed56ba81f22807358154ba7d6cc06c34 | Python | 3,197 | 85 | # Copyright (c) 2024, Tri Dao.
import torch
import torch.nn as nn
from flash_attn.ops.triton.cross_entropy import cross_entropy_loss
class CrossEntropyLoss(nn.Module):
def __init__(
self,
ignore_index=-100,
reduction="mean",
label_smoothing=0.0,
logit_scale=1.0,
l... |
c61a40d77594f9ee92fe1729513fbe6147d1d62bd245339322dc83e0cd258478 | Python | 3,197 | 91 | import os, glob, re
import argparse
from tqdm import tqdm
from joblib import Parallel, delayed
import gutenberg_cleaner
from irnlm.data.utils import (
get_punctuation,
get_word_list_and_freq,
get_gutenberg_book_ids
)
from irnlm.data.text_tokenizer import tokenize
word_list, word_freq = get_word_li... |
e6d3618264f11aa569ac21a89221ed2a7aa09f4d6c6ff6aa32d1d3d8f155ef7d | Python | 3,197 | 80 | # Copyright 2022 Deepfold Team
#
# 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 writin... |
6aa29323c6de349fbc96773b3df04087c292e1c106f05183e9a4cc1fc1bd32da | Python | 3,198 | 84 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 09:08:21 2022
@author: Audrey Mazancieux
"""
# Import useful libraries
import glob
import pandas as pd
from nilearn.image import resample_to_img, math_img
from nilearn.input_data import NiftiMasker
import json
import pickle
import os
# =======... |
17436b6eff0a093d8eaceeebc1ad37a26e0de0664a0259dc7beaebf9c80341af | Python | 3,199 | 107 | import os
from distutils import log
import itertools
from setuptools.extern.six.moves import map
flatten = itertools.chain.from_iterable
class Installer:
nspkg_ext = '-nspkg.pth'
def install_namespaces(self):
nsp = self._get_all_ns_packages()
if not nsp:
return
filenam... |
20cf07033a0c58c8e9387a2f5f1ee2534dbe32f5dcfe7cca23ae220b043af172 | Python | 3,200 | 92 | from typing import Optional, Tuple
import torch.nn as nn
from pl_bolts.models.detection.components._supported_models import TORCHVISION_MODEL_ZOO
from pl_bolts.utils import _TORCHVISION_AVAILABLE # noqa: F401
from pl_bolts.utils.warnings import warn_missing_pkg # noqa: F401
def _create_backbone_generic(model: nn.... |
9d501c057e3300385c2f2451d894989116aeb0cb2e36162e8084371400159396 | Python | 3,200 | 95 | """grind-p3 T5.6: fastlog abort reasons persisted to disk are redacted.
The core bundle writer's partial sink persists only the exception TYPE name
(``str(exc)`` can carry object reprs, paths, and captured values). The fastlog
disk backend missed that contract on both persisted sinks -- the streaming
index-append fail... |
2111dd2eadd5b4369b04d6ef274ea1983a25d4756f4df30cc3ce901676a01692 | Python | 3,201 | 115 | from math import exp, log
class Gate(object):
def __init__(self, name, count, inf=None, tau=None,
alpha=None, beta=None):
self.name = name
self.count = count
if alpha is not None:
self.inf = lambda v: alpha(v) / (alpha(v) + beta(v))
self.tau = lambd... |
7918a8ab05e5d10804588bd72d888c4f35d4b0312e64116d7b4f4c1a0c668b53 | Python | 3,201 | 76 | """Operation-grain backend capability rows (compo row 0.7).
The five coarse ``BackendCapabilities`` flags gate ten public trace options
(``backends/_options.py``'s mapping -- the memo's migration inventory), so a
backend supporting ``intervene=`` but not ``halt=`` is inexpressible today.
The ledger references STABLE p... |
9b0f59b1204d60e0fa3d66ac0ad5fd1c3490f5d279b0179d19f9043e332341bc | Python | 3,201 | 94 | #!/usr/bin/env python
import glob
import os
import tarfile
import numpy as np
import pandas
from deepspeech_training.util.importers import get_importers_parser
COLUMN_NAMES = ["wav_filename", "wav_filesize", "transcript"]
def extract(archive_path, target_dir):
print("Extracting {} into {}...".format(archive_pa... |
e04854380dce8bc2d303b0fa787419f06ea1e3a5e813d0e52a0261bd7fa9f354 | Python | 3,201 | 107 | """Tests for Dynamo graph-break correlation."""
from __future__ import annotations
import pytest
import torch
from torch import nn
import torchlens as tl
from torchlens.debug import GraphBreaksNormalizationError, GraphBreaksUnavailableError
from torchlens.utils import _torch_compat
class _ExplicitBreakModel(nn.Mod... |
829015cc45016969c534258c5e933041b4a3ec85187343ba67400f2100a0516f | Python | 3,202 | 79 | #!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import yaml
import torch
import random
import argparse
import numpy as np
# Experiment arguments
parser = argparse.ArgumentParser(... |
910b9c9cad8d3240978e63326f4d853d98b08ac1befe9f47f0c9dd51bf847407 | Python | 3,202 | 92 | # --- 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 Fill(_BaseLayoutHierarchyType):
_parent_path_str = "layout.map.layer"
_... |
fd6dbbefa19195f83315401fa414bca938b03f995c7a8e3b7ececd6db3b37f38 | Python | 3,202 | 94 | import numpy as np
import tensorflow as tf
import sys
import os
from keras import layers, backend
sys.path.append("../utils")
from func_model import extraData, apply_rev_comp, train, evaluate
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# tf.config.threading.set_intra_op_parallelism_threads(5)
tf.config.threading.set_inte... |
2b6bd8cb7355b89698210fe7a3ac7538d925509297492a62403aafd0cd8ade77 | Python | 3,203 | 97 | #!/usr/bin/env python3
import sys
import numpy as np
import msprime
from numpy import euler_gamma
from sklearn.neighbors import NearestNeighbors
from tqdm import tqdm
helpMsg = '''
usage: $./rho_dem.py <# individuals> <max # sites> <total sims> <label>
'''
## MACROS ##
# Adrion et al.
rho_max = 6.25e-8
mu_min... |
95be9051137bd73ebfb3ed50ce6b4632441d3fec7259ff7c1fe2edd6694b3300 | Python | 3,203 | 84 | import matplotlib.pyplot as plt
from os.path import join
import pickle as pkl
import imodelsx.process_results
import sys
import dvu
import numpy as np
import viz
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from sklearn.calibration import calibration_curve
from collections import defaultdi... |
98328eab90bac8cd8fa5074eebe77771e9c08e828a7da6649648a57dcdac7284 | Python | 3,203 | 64 | from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
class GradualWarmupScheduler(_LRScheduler):
""" Gradually warm-up(increasing) learning rate in optimizer.
Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'.
Args:
optimize... |
be28cae82d9a6097dfb904d9074410045b27294786ffb2f9000e47c97d294d65 | Python | 3,203 | 105 | """CouchDB result store backend."""
from kombu.utils.encoding import bytes_to_str
from kombu.utils.url import _parse_url
from celery.exceptions import ImproperlyConfigured
from .base import KeyValueStoreBackend
try:
import pycouchdb
except ImportError:
pycouchdb = None
__all__ = ('CouchBackend',)
ERR_LIB_M... |
0fd38cda91cb9fe817f352c376fa21e92fb6b68cd54c48cad45ef318da2ff951 | Python | 3,204 | 85 | import math
import numpy as np
import sys
from sys import argv
import random
if len(argv) != 7:
sys.exit("Usage: python custom_ins_list_RSVSim.py viral.fa insertions.csv seed no_of_viral_ins_per_set no_of_sets "
"output_path")
# Define paths
viral = argv[1]
hg = argv[2]
seed = int(argv[3])
# Set numb... |
348bcf936762c26f88311b6292357ee5200fbc1a5015908ecf063ffeb7be1645 | Python | 3,204 | 97 | import numpy as np
import sympy as sp
import pints
from . import common
from markov_builder.example_models import construct_wang_chain
from scipy.integrate import odeint
from . MarkovModel import MarkovModel
class WangModel(MarkovModel):
"""The model described in https://doi.org/10.1085/jgp.202112923
const... |
73cadda816514727bc5b2128b5867e40b65814624fe37afdda7492124448f22a | Python | 3,204 | 80 | import numpy
from .cached_projection import CachedProjections
class AibsTreeWrapper(object):
"""
Helper class that wraps the "structure_tree" of the aibs mcm package to expose a region_ids method, as required by
the CachedProjections class.
"""
def __init__(self, aibs_tree):
"""
... |
d07f1cbd7265a6fd8c5a723970b7003846032783ab64d9a84ccedaaaa42a79bc | Python | 3,204 | 82 | from __future__ import print_function
import numpy as np
import gluoncv as gcv
import mxnet as mx
from mxnet import autograd, gluon
from gluoncv.utils import download, viz
def test_voc07_metric_difficult():
url = 'https://apache-mxnet.s3-accelerate.amazonaws.com/gluon/dataset/pikachu/train.rec'
idx_url = 'htt... |
1aac02b96708b5cca736c7a7433ff59bf9d0f2093541a8d0d31c30bd435fe27d | Python | 3,206 | 117 | """Compute data properties."""
from inspect import isfunction
import numpy as np
from scipy.stats import sem
###################################################################################################
###################################################################################################
## COLL... |
b864cb83514e6fb05ac45ef68c178b43916e2012f578c2c787b9e7e378faa1ef | Python | 3,206 | 94 | #!/usr/bin/env python
#=========================================================================
#
# 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://... |
a69aa144568458b2cd1e1f3890b8bf7770a22ab1e208d2bc20c81386329282b5 | Python | 3,208 | 108 | # --- 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 Line(_BaseTraceHierarchyType):
_parent_path_str = "table.cells"
_path_str... |
2cf790a08cfb4600ab47c543a0f728ad6649c1115fb6e8137d2740f6245f31f8 | Python | 3,209 | 80 | import tensorflow as tf
import numpy as np
from load2data import extraData
from model_resnet import Resnet
from keras.models import load_model
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
####################################
# load data(train set、vaild set and test set) an... |
3259400532410fef8b6845daff887ef220752cd8f900e204443eace99a02666b | Python | 3,209 | 79 | """Журнал A2 (13 октября 2026): на синтетических строках страница собирается,
промежуточных чисел не показывает, при полном наборе seed'ов считает сравнения."""
import importlib.util
import json
import sys
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str... |
381ba768c25feff52720d64d1bcf7493da35a427351f505b5a1c6a86e0eb85f7 | Python | 3,209 | 102 | """
Standardize string formatting
SimplyFire - Customizable analysis of electrophysiology data
Copyright (C) 2022 Megumi Mori
This program comes with ABSOLUTELY NO WARRANTY
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Fre... |
36e940197e0bc6371d1b383e670313b29d84097f9d75417601a91d3b4ef55743 | Python | 3,210 | 89 | # coding=utf-8
# Copyright 2023 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... |
843d12de46234efbdb8f806ced77a5a15b9d9dbc83a1e26aa2818024df461f85 | Python | 3,210 | 98 | """Tests for saved-activation dtype range diagnostics."""
from __future__ import annotations
import torch
from torch import nn
import torchlens as tl
class _DowncastModel(nn.Module):
"""Model with a visible float32-to-float16 boundary."""
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Down... |
2f3c55144490d39e1cc344db4a1b7095d20ebda3fc25d4302d8cd985d6fdcee1 | Python | 3,211 | 74 | # TensorFlow and tf.keras
import tensorflow as tf
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
from cvnn import layers
print(tf.__version__)
def get_fashion_mnist_dataset():
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fas... |
f8d9ea428ce19a29ad4717fd76487a4746e7114cd379b02e88a5fd1a00386f09 | Python | 3,211 | 95 | """
report_summary.py
Utilities to create reports
and useful print outs.
"""
###################################################################################################
###################################################################################################
def loader_report_info(loader, **load... |
1888f8e195a6fe8bb819c9f3aca7fa245308d192c0c9061ca5650333bf295891 | Python | 3,212 | 71 | 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 argparse
import sys
sys.path.append('/om4/group/mcdermott/user/jfeather/projects/robust_audio_networks/robustness/metamers_paper_model_analysis_folder... |
9013437a3b7b2311ae9b14ae8506c8be96d65d3277d233d93cca5e7575d4997a | Python | 3,212 | 96 | """Raw-label lookup and expression helper tests."""
from __future__ import annotations
import pytest
import torch
import torchlens as tl
from torchlens.constants import RAW_LABEL_SUFFIX
pd_types = pytest.importorskip("pandas.api.types")
is_bool_dtype = pd_types.is_bool_dtype
is_float_dtype = pd_types.is_float_dtype... |
d16188d46a39c6cf837e0e0a044daa34242b75e89b06f8d2e1a09b9d1e5be8c5 | Python | 3,212 | 76 | from ovseg.model.SegmentationModelV2 import SegmentationModelV2
from ovseg.preprocessing.SegmentationPreprocessingV2 import SegmentationPreprocessingV2
from ovseg.model.SegmentationEnsembleV2 import SegmentationEnsembleV2
from ovseg.model.model_parameters_segmentation import get_model_params_3d_UNet
from ovseg.utils.io... |
10b1142bf80a275ea2ec5908919b421e26d763a85e54ab8e0853f85b25bca3fe | Python | 3,213 | 76 | import re
from pathlib import Path
import torch
import math
from einops import rearrange
def load_checkpoint(path, device='cpu'):
path = Path(path).expanduser()
is_deepspeed = False
if path.is_dir(): # DeepSpeed checkpoint
is_deepspeed = True
latest_path = path / 'latest'
if lates... |
2e3087a792bc0b4d583d8f38d1c2b5b90273796709903c9c25f6f6b3bb365837 | Python | 3,213 | 87 | """Dataloader helper functions. Synchronize slices for both data and label."""
__all__ = ['split_data', 'split_and_load']
from mxnet import ndarray
def split_data(data, num_slice, batch_axis=0, even_split=True, multiplier=1):
"""Splits an NDArray into `num_slice` slices along `batch_axis`.
Usually used for da... |
74d418bcdb6d93183fb20ea467eacfbc49ec65e245966b7fcb6ef62c245a5ddb | Python | 3,213 | 93 | import torch
import torch.nn as nn
from .sparsity import SparseLayer
from .spatially_sparse_across_channels import SpatiallySparseAcrossChannels
class SpatiallySparseAcrossChannelsDropMotifs(SparseLayer, nn.Module):
"""
Like `SpatiallySparseAcrossChannels`, but drops motifs every time
the density is ... |
ab608aeb2f4be78acd165c5a333bd20024b853fb9b64329e87a9a8cc041924f4 | Python | 3,213 | 84 | #!/usr/bin/env python3
# read depth histogram plot
#https://github.com/dfguan/purge_dups/blob/master/scripts/hist_plot.py
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import sys, argparse
def col_hist(stat_fn, delim):
hists = []
#we consider the coverage histogram start with 0
... |
ad18765248c61b742c045089a46db3794d98d3bf11816595bbcce9710046a32f | Python | 3,213 | 108 | # --- 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 Line(_BaseTraceHierarchyType):
_parent_path_str = "table.header"
_path_st... |
088628766254d3733f7fa028fd6342c66c733272f2ef387692fba3acc03f8e03 | Python | 3,214 | 117 | from abc import ABC, abstractmethod
import attr
import h5py
import numpy as np
from modular_splicing.dataset.datapoint_extractor import BasicDatapointExtractor
class MultiSettingH5File(ABC):
"""
Multiple settings in one h5 file, which expands the data with duplicates
of the same data, but with different... |
675c29ba5b6f3fd3f201f8351f12344a2eae2c40ad83871237b84745d5b6dd44 | Python | 3,214 | 100 | """
File: utilities.py
Created: 2021/04/28
Last Changed: 2022/12/15
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.
... |
5813d44dd91a84c157e5539ff84a25cae0c3d390c5d2e62f38c93ec3f270ef2c | Python | 3,215 | 99 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 20 20:03:39 2018
@author: admin
"""
import tensorflow as tf
import numpy as np
from tensorflow.python.framework import ops
from sklearn import preprocessing
import matplotlib.pyplot as plt
import os
import csv
def accuracy(predictions, labels):
return (... |
a36032f3acdd46ecb5ee78deee3473ebec94a9ba7b7b890df39a49c572211b90 | Python | 3,215 | 89 | from __future__ import division
import unittest
import numpy as np
from wyrm.types import Data
from wyrm.processing import jumping_means
from wyrm.processing import swapaxes
class TestJumpingMeans(unittest.TestCase):
def setUp(self):
ones = np.ones((10, 5))
# cnt with 1, 2, 3
cnt = np.... |
739546fffe69ba8b2dde806622a84554bf669d3d379cd309a6c847b68a2ba4ad | Python | 3,216 | 119 | from abc import ABC, abstractmethod
import numpy as np
from modular_splicing.dataset.additional_data import additional_data_types
from modular_splicing.utils.construct import construct
class DataRewriter(ABC):
"""
Represents a generic method for rewriting a datapoint.
"""
@abstractmethod
def re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.