sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
fdbc9b9783db05472547920617d3aad1cd21c5a6148ab5c47e9ff2baa40a4126 | Python | 2,695 | 88 | from enum import Enum
import numpy as np
from pygeos.coordinates import get_coordinates
class Unit(Enum):
"""
Enumeration of supported units.
The full list can be checked by iterating over the class; e.g.
the expression `tuple(Unit)`.
Inspired by: https://github.com/mapado/haversine
"""
... |
1dd53ad5dd55c3e9b0e256a1cce348a57aa52907d226249dcd43bd4489867cc0 | Python | 2,696 | 74 | """Логи в SQLite, геномы в npz. Один seed -> один воспроизводимый прогон."""
import json
import sqlite3
import time
from pathlib import Path
import numpy as np
SCHEMA = """
CREATE TABLE IF NOT EXISTS runs (
run_id INTEGER PRIMARY KEY AUTOINCREMENT,
label TEXT, started REAL, config TEXT, notes TEXT
);
CREATE T... |
b6ad66cd0ebfa000be7237a45956b3c70604307c47d73a923fe053dac8a523a8 | Python | 2,697 | 74 | import os
import warnings
import h5py
import numpy as np
import pandas as pd
import scanpy as sc
from scbig import run_scbig, preprocess, setup_seed
warnings.filterwarnings('ignore')
for dataset in ['fetal_liver_atlas', 'Trachea']:
print('----------------real data: {} ----------------- '.format(dataset))
set... |
92afca49835a873ca724fbdd8bbca800ea1b3fb565cee671710c4083379c7adb | Python | 2,698 | 51 | # Simple script to make sure basic usage
# such as training, testing, saving and loading
# runs without errors.
import os
def run(command):
print(command)
exit_status = os.system(command)
if exit_status > 0:
exit(1)
if __name__ == '__main__':
# download mini datasets
if not os.path.exist... |
efaf1f081e2e31d379e10ab2ca8aad3f377483c1e83bf4fa53cb53e0676902e8 | Python | 2,698 | 85 | """
Code here relates to filering of ABF data.
Usually this means low-pass filtering to reduce noise.
"""
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
def _kernelGaussian(size=100, sigma=None):
"""
Return a 1d array shaped like a Gaussian curve with area of 1.
Optionally provide... |
06e3508b32d7f95f919fe2653efd7aad7d0153e12fce56165e231e5e4328f369 | Python | 2,699 | 91 | import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras.models import load_model
from gradient_accumulator import GradientAccumulateModel
from tensorflow.keras import mixed_precision
import os
# disable GPU
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
# set mixed global precision policy
# Equiv... |
097def1c7344be8b38e85e7ae32964992c23536d5dc5b60b4b53d9d38c058afe | Python | 2,699 | 65 | import os.path
from data.base_dataset import BaseDataset, get_params, get_transform
from data.image_folder import make_dataset
from PIL import Image
class AlignedDataset(BaseDataset):
"""A dataset class for paired image dataset.
It assumes that the directory '/path/to/data/train' contains image pairs in the ... |
30900fddf43db2a80d55296deda607686a046d8ba7838f3ff868fb79d4b16357 | Python | 2,699 | 80 | import tempfile
import time
import unittest
from pathlib import Path
from unittest import mock
import pandas as pd
from codecarbon.emissions_tracker import OfflineEmissionsTracker
from tests.testutils import get_custom_mock_open, get_test_data_source
def heavy_computation(run_time_secs: float = 3):
end_time: fl... |
6b4ad3071c10d8b2e7caff0f58d9fd7d89abe94b162736869f7c0af7218ca9c8 | Python | 2,699 | 112 | __author__ = 'quentin'
import glob
import cv2
import optparse
import os
import random
CHUNK_LENGTH = 10 #s
INSTRUCTION_FILE = "instructions.png"
allowed_keys = ["n", "w", "r", "g", "i"]
pos = None
def position(event, x, y, flags, param):
global pos
if event == cv2.EVENT_LBUTTONUP or event == cv2.EVENT_RBU... |
a903088f8ca15a16c29384f3405355aa2a4768615a5b276efc83e3350f18614f | Python | 2,699 | 86 | '''
Implements the translatable text blueprint for regular Div containers.
This blueprint should be used to wrap all the regular textual contents of the app.
It comes with a `dcc.Store` containing the translation key corresponding to the
target textual content in the translation dictionary.
This key must be given wh... |
caafe9acfe69d636c02dbcbaf70933cc7d2f60a7356ed99142889552d4e1f9e0 | Python | 2,700 | 93 | #!/usr/bin/env python3
# coding: utf-8
"""
Created on July 9 2019
@author: Nathan De Lara <nathan.delara@polytechnique.org>
"""
from abc import ABC
from typing import Union
import numpy as np
from scipy import sparse
from scipy.sparse.linalg import eigsh
from sknetwork.base import Algorithm
class EigSolver(Algorithm... |
fc0bacf461a9042be94424852bf63f58c828c1a34aa9ecd61bf3b59996f9f592 | Python | 2,700 | 73 | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future__ import d... |
5004b4fb3403074297261f0eca9ed3add5e7789607f1694f2f243f1f28fbd932 | Python | 2,701 | 84 | """
This module define a specific dataset
"""
import logging
import torch
from datasets_pre_processing.generic_dataset import GenericDataset
class ClassificationPerProtWeightedDataset(GenericDataset):
"""
This class is a dataset where we have one label per protein/example
"""
def __init__(
se... |
99df448cee2a8123b9304db88b2c8b9438b46601b7cb7275ad727586b88bc44b | Python | 2,702 | 82 | from keras.src import backend
from keras.src.api_export import keras_export
from keras.src.layers.merging.base_merge import Merge
@keras_export("keras.layers.Subtract")
class Subtract(Merge):
"""Performs elementwise subtraction.
It takes as input a list of tensors of size 2 both of the
same shape, and re... |
ca9ed0239a02c80e42b5d27f6e88660c7e26abda473cf514f6864598493c79eb | Python | 2,702 | 85 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Helper functions for multigrid training."""
import numpy as np
import torch
from torch.utils.data.sampler import Sampler
TORCH_MAJOR = int(torch.__version__.split(".")[0])
TORCH_MINOR = int(torch.__version__.split(".")[... |
77c392ca1bf2b957ab1873c0bf4f3981621bbb6283ca6b4d7a2016bcee01e7a8 | Python | 2,703 | 81 | import numpy as np
import pandas as pd
import pytest
from anndata import AnnData
from mudata import MuData
from muon.utils import _get_values
@pytest.fixture(params=[True, False])
def mdata(request: pytest.FixtureRequest) -> MuData:
mdata = MuData(
{
"mod1": AnnData(np.arange(0, 100, 0.1).res... |
d823962f75370e5440f02cec43fec52398c311ab2b0703298a883d0ca5415197 | Python | 2,703 | 93 | import os
from typing import Any, Type
import pytest
from pytest_celery import CeleryWorkerContainer, defaults
from pytest_docker_tools import build, container, fxtr
import celery
class SmokeWorkerContainer(CeleryWorkerContainer):
"""Defines the configurations for the smoke tests worker container.
This wor... |
1e8b915b166855d530da4d1b7e81596d79cc52a001bd35ee68a156966ee2de8e | Python | 2,704 | 91 | import os
import json
import re
import requests
import dateparser
from bs4 import BeautifulSoup
from pathlib import Path
class Bulletin(object):
def __init__(self, basedir, statename):
self.basedir = os.path.abspath(basedir)
self.statename = statename
self._statefile = os.path.join(self... |
2ba8656f8bad2e4fb2b039f503e026f01f9faccb72e766af2e3c61c038514aa1 | Python | 2,704 | 94 | """ART2, 1987, Carpenter and Grossberg.
Paper: "ART 2: Self-Organization of Stable Category Recognition Codes for
Analog Input Patterns." ART2 normalizes analog F1 activity with gain control
before vigilance-gated category resonance in F2.
"""
from __future__ import annotations
import torch
from torch import Tensor,... |
188b9063c08b71a36624a0890a38acc6ee98acd62bf46d66341e206a291673fd | Python | 2,705 | 78 | import pytest
import torch
from lightly.loss.emp_ssl_loss import EMPSSLLoss
class TestEMPSSLLoss:
@pytest.mark.parametrize("inv_coef", [0.0, 200.0])
def test_forward_matches_reference(self, inv_coef: float) -> None:
"""Match the per-view objective and gradients from the EMP-SSL reference."""
... |
7ab7c4ddf8738b192ca318c2a34dc337c69f2927131b8db799d537a57926429d | Python | 2,705 | 110 | #!/usr/bin/env python
# encoding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import os, sys
import logging
import subprocess
import shlex
import shutil
import time
logger = logging.getLogger(__name__)
def run_cmd(cmd, ignore_error=False):
... |
9938f32600edf7d40c78197180af09dace45809ad58746b9a615ba81f9233f0f | Python | 2,705 | 98 | """
Helpers for distributed training.
"""
import io
import os
import socket
import blobfile as bf
from mpi4py import MPI
import torch as th
import torch.distributed as dist
# Change this to reflect your cluster layout.
# The GPU for a given rank is (rank % GPUS_PER_NODE).
GPUS_PER_NODE = 8
SETUP_RETRY_COUNT = 3
CU... |
a0e2c0c9bfb4cd5a412015c99e1c69350c0db1b35d24216d448668d929cd7a35 | Python | 2,705 | 92 | """
Tests to make sure preprocess functions works
"""
import eugene as eu
import numpy as np
import pytest
from pathlib import Path
HERE = Path(__file__).parent
@pytest.fixture
def seq():
seq = eu.utils.random_seq(seq_len=10)
return seq
@pytest.fixture
def seqs():
seqs = eu.utils.random_seqs(seq_num=1... |
cb3b6d69c328c0e8be4c9164c89f3fbe83c442b13ad7d56f5f4da689b2655b3b | Python | 2,705 | 91 | """Demo models for ``torchlens_in_10_minutes.ipynb``.
These live in a real source file so TorchLens can use AST inspection to label
conditional branch arms in the rendered graph.
"""
from __future__ import annotations
import torch
import torch.nn.functional as F
from torch import nn
class TinyBranchCNN(nn.Module):... |
90f2357d8af04303a288e6a19605c27d66e793ea99487ff4dafcd17bc1347349 | Python | 2,706 | 66 | """03. Predict with pre-trained YOLO models
==========================================
This article shows how to play with pre-trained YOLO models with only a few
lines of code.
First let's import some necessary libraries:
"""
from gluoncv import model_zoo, data, utils
from matplotlib import pyplot as plt
#########... |
a53fdc3964953081b9c4ffb68d2986a0f182611141d123952d609c311721d815 | Python | 2,706 | 98 | import argparse
import os
import sys
import opencc
def _build_parser():
config_list = '\n'.join(f' {c}' for c in sorted(opencc.CONFIGS)) or ' (none found)'
parser = argparse.ArgumentParser(
prog='opencc',
description='Open Chinese Convert (OpenCC) Command Line Tool',
epilog=f'Built-... |
c9d70371d111a8431d4678551d622ec4e2050f0a7cd6a76a7a26ce852af7179a | Python | 2,706 | 74 | import time
from codecarbon import EmissionsTracker
tracker = EmissionsTracker(
project_name="ZeroEnergyTestLoop",
measure_power_secs=1, # Or your desired interval
log_level="debug", # Set to debug to get all codecarbon logs + our new ones
)
def busy_task(duration_secs=4):
print(f" Task: Starting... |
eeace1084013b12778e97a4b1b7ebdc121c6205e0ef7eace5b35b1c0adf1c3f4 | Python | 2,706 | 110 | from brian2.units import *
N_e = 12000
N_i = 200
p_ee = 0.0164
"""initial probability for synapse connection"""
p_ie = 0.1
"""initial probability for synapse connection"""
p_ei = 0.1
"""initial probability for synapse connection"""
p_ii = 0.2
"""initial probability for synapse connection"""
E_E_e = 0.*mV
"""excitato... |
3da9f8fc8bfe31a38592b9eeae07e1766e5ff2a922d0c5b2fa2f1149a4e88be8 | Python | 2,707 | 84 | import os
import argparse
import benepar
import spacy
from spacy.symbols import ORTH
from irnlm.data.utils import set_nlp_pipeline, get_ids_syntax
from irnlm.data.extract_syntactic_features import integral2syntactic
from irnlm.utils import save_pickle, write
def load_nlp_pipeline(
language,
download_dir="/n... |
4d7f3596453ba07935f19691ecd26ba91838c6d96bdc2af4267c8326f884f26a | Python | 2,707 | 84 | #!/usr/bin/env python
"""
Connects to a UCSC table browser and scrapes chrominfo for every build
specified by an input file (such as one output by parse_builds.py).
If not input file specified, it will connect using parse_builds.py to
retrieve a list of available builds.
All chromInfo is placed in a path with the conv... |
9247e6a3aa87d106b260908cc6d510dc87a2318ca94f2923830000f58c403481 | Python | 2,707 | 102 | """
code here helps port this code to csharp
"""
import os
import sys
PATH_HERE = os.path.abspath(os.path.dirname(__file__))
PATH_SRC = os.path.abspath(PATH_HERE+"../../../src/")
types = {
"s":"string",
"c":"char",
"b":"char",
"B":"uchar",
"h":"short",
"H":"ushort",
"i":"int",
"I":"uin... |
9a42715873b1cc2c86a439398cfabae0ba0f9062b4d5304c785ab68daaaf3579 | Python | 2,708 | 105 | import os
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras import mixed_precision
from tensorflow.keras.models import load_model
from gradient_accumulator import GradientAccumulateModel
from gradient_accumulator import unitwise_norm
from .utils import normalize_img
def test_unitwise... |
ce90fc1b1bbab4c0a997e02f52d26a9c90493eeb63a43da1d84a3a8c4c7ef40d | Python | 2,708 | 54 | from __future__ import print_function, division
import os
from torch.utils.data import Dataset
from .load_data import load_custom_dataset, load_site_info, load_dataset, load_site_info_custom_data
class Sample():
def __init__(self, left, right):
self.left = left
self.right = right
self.dos... |
ef59c7bf888e1db25b9de75d72e494ca76f18313650a3de43dd3a02678f20186 | Python | 2,709 | 83 | from typing import List, Tuple, Union
import torch
class RandomRC:
"""Randomly applies a reverse-complement transformation to each sequence in a training batch \\
Takes in a user-defined probability, rc_prob. This is applied to each sequence independently.
Parameters
----------
rc_prob :... |
a4a5f87b24cc4bb3d57fd70cd0f8d07c2c8f2ba0b033e623fbf1d678a5adcac0 | Python | 2,711 | 49 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
5bc62289ff1df05efd282a841a2d47ffd319c2f72fbd579defc2ba0396f520ae | Python | 2,712 | 72 | import os
import warnings
import h5py
import numpy as np
import scanpy as sc
from scbig import run_scbig, preprocess, read_data, setup_seed, sample
warnings.filterwarnings('ignore')
for dataset in ['10X_PBMC', 'mouse_bladder_cell', 'mouse_ES_cell', 'human_kidney_counts', 'Adam',
'Human_pancreatic_is... |
e08788bbeabe36d261066dcaf68685d846342db62e5a2f5410b6b4486636e1d7 | Python | 2,712 | 84 | """Use DeepCell for cell identification and labeling.
https://github.com/vanvalenlab/deepcell-tf
[Greenwald21]_
"""
from typing import Optional, Union
import numpy as np
from anndata import AnnData
try:
from deepcell.applications import Application, NuclearSegmentation
except ModuleNotFoundError:
Application... |
e94319dc19a19172095cfeaaaa0dfddef5778240b598bd81405378040e07eacb | Python | 2,712 | 82 | #!/usr/bin/env python
"""Train C.Origami with ATAC-seq + DNA sequence only (no CTCF)."""
import sys
import torch
import pytorch_lightning as pl
import pytorch_lightning.callbacks as callbacks
from corigami.training.main import TrainModule, init_parser
from corigami.data import genome_dataset
import corigami.model.cori... |
097d9ae9a4f9dcc286f0af2e0926717470033e3c573b1270142c56d7f6d88d93 | Python | 2,713 | 90 | """DeepSpeech 2, 2015, Amodei et al., "Deep Speech 2".
Two-dimensional spectrogram convolutions feed a deep recurrent stack and a CTC
character classifier. This minimal version keeps the convolutional front end,
bidirectional GRU stack, and framewise log-probability output.
"""
from __future__ import annotations
imp... |
43dd09564420f872b3fc7f673d393f56ed8d5f0c25a1978840ea375e904b0eae | Python | 2,713 | 92 | # 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... |
6534e5eb0817e232948bdfdee8558136cd1d24fb2102eea5f0ba97fb343e62e8 | Python | 2,713 | 90 | """
Agent classes for the agent-based-modeling simulations.
"""
from __future__ import annotations
from typing import Any
__displayname__ = "Agents"
__all__: list[str] = [
"NonSpatialAgent",
"PointAgent",
"OrientedAgent",
"MobilePointAgent",
"MobileAgent",
"Source",
"Food",
"Larva",
... |
9edf9199e2804c556cd312b32b497533d132c63bb22eb61a4a4e1c79bbb15690 | Python | 2,713 | 91 | import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras.models import load_model
from gradient_accumulator import GradientAccumulateModel
from tensorflow.keras import mixed_precision
import os
# disable GPU
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
# set mixed global precision policy
# Equiv... |
ffc6c7c69d51db0d49a90145a80fe36d3b4db056fed79088045180a992152bd7 | Python | 2,714 | 95 | import numpy as np
def hbern(p):
"""
Entropy of a Bernoulli distribution with parameter p.
Parameters
----------
p : float or array_like
Probability of success.
Returns
-------
float or array_like
Entropy of the distribution.
"""
return -(p * np.log(p) + (1 - ... |
42b32660bdbb64c43991e01a48262b09f2be28308c8d9b920819d7c8a6049a2b | Python | 2,716 | 100 | import numpy as np
from ..util import equal_states
from .composite import StructureComposite
class StructureCompositeStack:
def __init__(self):
self.composites = []
def __add__(self, stack):
new = StructureCompositeStack()
for sc in self:
new.append(sc)
for sc in... |
ab226c0cd0a54d0a4f90d6d137853d9452b07a42fbc65b76094410a4ca643f2e | Python | 2,717 | 79 | from typing import Any, List, Optional
import copy
import torch
import numpy as np
from .cams import cam_graphnet, cam_gnn, cam_gat
class GraphDataProducer:
"""
Class for picking a graph from the test dataset
Args:
model: Trained GNN model.
test_data: Uploaded test dataset of QM9_XAS datas... |
7249491ccdaee61d56aa71e58b75b8bd395c65685db6c50feb9e2198a2bf64f6 | Python | 2,718 | 87 | """
Figure about one-layer model.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import figutils
from PyPDF2 import PdfReader, PdfWriter, Transformation
# If you change figutils often, and want changes reloaded, uncomment lines below:
#from importlib import relo... |
29f0a3a169a1909317dc1ed0b4df6428eaaafc310635e14602bc7d55c8bbf81c | Python | 2,719 | 49 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
b47222b5c04378cf06f4d29147a7285074f2b1489cd2269ab09ebcb48f8374ae | Python | 2,720 | 103 | import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
def identify_header_rows(table):
for idx, row in table.iterrows():
row_str = ' '.join(row).lstrip()
if row_str.startswith('1'):
break
return idx
def forward_fill_row(row):
last_val = row[0]
for i in... |
c78fdf45a8b4f8994da35ffbe116ce6915fde842e5f8daf80665f3168e8910ef | Python | 2,721 | 70 | import os
import time
import argparse
import numpy as np
import torch
import torch.nn as nn
from gluoncv.torch.utils.utils import build_log_dir
from gluoncv.torch.engine.config import get_cfg_defaults
from gluoncv.torch.model_zoo import get_model
from gluoncv.torch.data import VideoClsDataset
def main(cfg, save_pat... |
da42ff3e7b62736a239bc3c83cddf3214583d739c67fb0d85a6d0503e7b900fb | Python | 2,721 | 64 | import torch
from torchvision import datasets, transforms
import numpy as np
def rand_match_on_idx(l1, idx1, l2, idx2, max_d, dm, cs):
"""
l*: sorted labels
idx*: indices of sorted labels in original list
"""
#cs = ['w']
_idx1, _idx2 = [], []
for l in l1.unique(): # assuming both have sam... |
bac72c80fc346cf8e46ff7700e72118cb2adada20432e651aa6c6b49547a8f2b | Python | 2,722 | 88 | from anndata import AnnData
from typing import Optional, Union
import numpy as np
import pandas as pd
from sklearn.cluster import DBSCAN
from natsort import natsorted
def localization(
adata: AnnData,
use_label: str = "louvain",
eps: int = 20,
min_samples: int = 0,
copy: bool = False,
) -> Optiona... |
d11d59c941aac359ad36b4aeabb4899cd9ea81a0936a05ccc26700b42c12faf5 | Python | 2,722 | 68 | import os.path
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
from skimage import color # require skimage
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
class ColorizationDataset(BaseDataset):
"""This dataset class can loa... |
86aa1426aa53f6094c003edf11ff90405e75590fba97ffdd8fe2e3d192bb325c | Python | 2,723 | 77 | #!/usr/bin/env python
import errno
import os
import shlex
import sys
import warnings
from argparse import ArgumentParser
from subprocess import check_call
import galaxy.dependencies
DESCRIPTION = "Install optional Galaxy dependencies based on configuration values"
PINNED_REQUIREMENTS = os.path.join(os.path.dirname(_... |
9cc4fb9f024859bed9ec6c8a201310a904ae54ae19e9449002aa8e20930cc422 | Python | 2,723 | 65 | # # Parse the different SwissProt release
import pandas as pd
from review_comparison.Create_diff_SwissProt_new_annotations import diff_SwissProt
from review_comparison.filter_out_similar_seq_in_train import DeleteToSimilarSeq
from review_comparison.swissprot_file_to_json import SwissProtExtractor
from review_comparison... |
eca43953389a3968f150a6f945d0bb200e65024393dd75da77a0bff685edfb95 | Python | 2,723 | 86 | #!/usr/bin/env python
# Created on: October 8, 2013
__author__ = "Sven Kreiss, Kyle Cranmer"
__version__ = "0.1"
import optparse
parser = optparse.OptionParser(version=__version__)
parser.add_option("-i", "--input", dest="input", default="output/atlas_counting/comb.root", help="Input root model.")
parser.add_optio... |
684180d215f08a9c317e0069804c548794b575db26ab479587b9a4d9daeea2d4 | Python | 2,724 | 75 | """Vizmech wave-2 item 16: no one-node leaf-module clusters on the rank path.
``neato -n`` invents cluster boxes it was never designed to compute: on stock
densenet121, 366 one-node leaf clusters rendered at a median 91% of graph
width (50 above 99%) -- page-wide boxes claiming containment they do not have
(D18a). The... |
c6ed4a911acb3ce20db4127af8addbffa7b2dc2653f26ed6854dbd7b6de5b3a2 | Python | 2,724 | 81 | """Measures of spatial information."""
import numpy as np
from spiketools.spatial.occupancy import normalize_bin_counts
###################################################################################################
#################################################################################################... |
b16cb35afc240812d02dc6ed56bfaeddd7b5be149ca9901f8ed8971d27667a07 | Python | 2,726 | 84 | import pytest
import gym
from gym.vector import AsyncVectorEnv, SyncVectorEnv
from gym.wrappers import OrderEnforcing, TimeLimit, TransformObservation
from gym.wrappers.env_checker import PassiveEnvChecker
from tests.wrappers.utils import has_wrapper
def test_vector_make_id():
env = gym.vector.make("CartPole-v1"... |
193c9205ab23a051ac7d8fb17fc499c7bbcb6ffc805e8a91afc0b700f76aa958 | Python | 2,727 | 95 | # 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... |
d4ec09abed63526425235f4eef0a0c51237fac68dab2c857a012e05663de3505 | Python | 2,727 | 108 | import jax.numpy as jnp
import jax
from plotly import graph_objects as go
jax.config.update("jax_enable_x64", True)
from cvsx import components as c, parameters as p
from cvsx.unit_conversions import convert
if __name__ == "__main__":
valves = {
"standard": c.Valve(
**p.revie_2012["mt"],
... |
2fc6381ff698d3c7bc0e3fe97229de43aea270ba0ce9e4201d2d30048e77ed35 | Python | 2,728 | 84 | import pkg_resources
from nanite import preproc
from PyQt5 import QtCore, QtWidgets, uic
class WidgetPreprocessItem(QtWidgets.QWidget):
#: Triggered whenever the state changes
preproc_step_changed = QtCore.pyqtSignal()
def __init__(self, identifier, *args, **kwargs):
"""Special widget for prepro... |
749ee7e327be14ed501cf7ecbade90ed35be3877a5b1969ef56aaae55d69f1da | Python | 2,728 | 116 | from __future__ import annotations
import argparse
import shutil
from pathlib import Path
import nox
DIR = Path(__file__).parent.resolve()
nox.options.sessions = ["lint", "pylint", "tests"]
@nox.session
def lint(session: nox.Session) -> None:
"""
Run the linter.
"""
session.install("pre-commit")
... |
8247e191fa76c063b6239d20cf99719c2f6e8fe2c54e49622bfaddc54d4fe3f2 | Python | 2,728 | 86 | import numpy as np
from tensorflow.keras.utils import to_categorical
from pathlib import Path
from zipfile import ZipFile
from urllib.request import urlopen
from io import BytesIO
import re
import matplotlib.pyplot as plt
def download(target):
print("downloading flower dataset...")
url = urlopen("https://s3.a... |
8fed77eb819f1d1d8f2b92b90b82e5b062458495cf872dc88afc906600fb6577 | Python | 2,728 | 80 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
0a62aa37488fe37194c39de68fbbc3e735f4aae8194f0243c32b2e6c24f2d789 | Python | 2,729 | 88 | import sqlite3
import sys
import base64
import io
import shutil
import cv2
import tempfile
import shutil
import os
import glob
from optparse import OptionParser
import datetime
import glob
from multiprocessing import Pool
def annotate_image(args):
input, time, t0 = args
label = datetime.datetime.fromtimestam... |
683671806e3e6e5e3449a2de28b7d4054a2f499db1f807ab834b2287e5820823 | Python | 2,729 | 73 |
from fmri_encoder.data import fetch_masker
class FMRIDataLoaderBase(object):
def __init__(self, subjects_names=None, number_of_runs=None, **metadata):
"""Instanciate a dimension reduction operator.
Args:
- subjects_names: list of str
- number_of_runs: int
- meta... |
c4c623db134e4807055ff5e27210545d0daa18f8fd592082f4e416ca13b39d21 | Python | 2,729 | 87 | # This example requires the following dependencies to be installed:
# pip install lightly
import torch
import torchvision
from torch import nn
from lightly.loss import VICRegLLoss
## The global projection head is the same as the Barlow Twins one
from lightly.models.modules import BarlowTwinsProjectionHead
from light... |
2f8c231e6205aebab3542da3a0bcb02a6b9eb5b6ffc1614db68421d2eabbfe0c | Python | 2,730 | 88 | import os
import mne
import nibabel
import pandas
from mne.datasets import fetch_fsaverage
import numpy as np
from mp_dip.research.parcellation_search import \
get_label_from_head_position_atlasreader, \
get_label_from_head_position_freesurfer_parcelations
from mp_dip.utils.mne_freesurf_labels import read_fre... |
46f2344b570227016f4f29d1fc14a4606b5ae04d0432023b73209efa867f5df9 | Python | 2,730 | 74 | # -*- coding: utf-8 -*-
# Copyright (c) 2016-2018 Braintech Sp. z o.o. [Ltd.] <http://www.braintech.pl>
# All rights reserved.
"""Module provides a simple class that is able to read tags xml file and give on demand subsequential tags."""
import xml.dom.minidom
from functools import cmp_to_key
from . import tag_utils... |
b19ed67cbdd1023c7975ed6231f31b1cafb9d2ac34ec032973383a2dc053eb72 | Python | 2,730 | 73 |
from fmri_encoder.data import fetch_masker
class RMapsDataLoaderBase(object):
def __init__(self, subjects_names=None, number_of_runs=None, **metadata):
"""Instanciate a dimension reduction operator.
Args:
- subjects_names: list of str
- number_of_runs: int
- met... |
256f52b3233049fb7bbbb005e610bafceff6400ca4d1851dde3c699d59814398 | Python | 2,731 | 76 | """A01 semantic-attention slice: GQA (Llama-class) per-head facets, eager.
The measured false-absence class: head geometry lives ONLY on ``self.config``
in modern transformers, so q/k/v were served as false structural absences.
The config-based third lookup tier fixes it; k/v stay UN-expanded (true KV
heads) and the h... |
739c4f7e0b9aa70d67db49413b07c52034953bece2fdf1dbb053f1e0588bde98 | Python | 2,731 | 84 | import os
import re
import tempfile
import unittest
import hydra
import torchvision
from hydra.experimental import compose
try:
from hydra import initialize
except ImportError:
from hydra.experimental import initialize
from lightly import cli
class TestCLIMagic(unittest.TestCase):
def setUp(self):
... |
f5f9708a38df74a9a24a6e90009d8ff7f49165d84972c7673b247b3cf4b1464e | Python | 2,731 | 85 | import wx
import matplotlib
matplotlib.use('WxAgg')
import pylab as pl
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.backends.backend_wx import NavigationToolbar2Wx as NToolbar
from traits.api import *
from traitsui.api import *
... |
9e297c23dcc35ad958bb6ec7f16cc60fbc33a7efd692450bdcf68c3c03f53dc0 | Python | 2,732 | 92 | """One pass/op vocabulary across surfaces (A10) -- 3-pass fixture goldens.
Lane A07 (2026-08-27). Spec: the summary design memo build item 4:
"pass k/N" / "xN passes" spellings, one op denominator, headings follow row kind.
"""
from __future__ import annotations
from collections.abc import Generator
import pytest
i... |
d2af344a6a80899bb498d2533b8a4e3e2ad7213f9b53785c12a4904c2acd3a09 | Python | 2,732 | 88 | """Modes object."""
from specparam.data import ModelModes
from specparam.modes.mode import VALID_COMPONENTS
from specparam.modes.definitions import check_mode_definition
from specparam.reports.strings import gen_modes_str
################################################################################################... |
37d38d3622ad9f4f969fc8213aa53ff6e61a49b58545e9b9973dd8477732205c | Python | 2,733 | 94 | """
Plot the confusion matrix
"""
import itertools
import numpy as np
import matplotlib
matplotlib.use('Qt5Agg')
matplotlib.rcParams['text.usetex'] = True
import matplotlib.pyplot as mpl
from sklearn.metrics import confusion_matrix as cm
import pickle
import pandas as pd
celltypes = sorted(['bushy', 't-stellate', 'd... |
4e62a448f480b22b965f939c0a4c53ab3f7fb75d3f4d3a8a09b435f12a94ccf3 | Python | 2,733 | 91 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from .evaluate_combinations import table_of_combinations
from modular_splicing.models_for_testing.list import AM
from modular_splicing.evaluation import standard_e2e_eval
def module_substitution_table():
"""
Main table for the module sub... |
c41c5d7220f433c9b33d797db135ba869445a6a0b58a3e93992b38eb74d00a65 | Python | 2,733 | 86 | import os
import numpy as np
from os.path import join, dirname
from ridge_utils.textgrid import TextGrid
def load_textgrids(stories, data_dir: str):
""" TODO (shailee): Add description."""
base = join(data_dir, "ds003020/derivative/TextGrids")
grids = {}
for story in stories:
grid_path = os.pa... |
48ff2e503eccb55e6654a5f2acffea25cc00426296465824a551a8dd4df684e5 | Python | 2,736 | 76 | """
Caffe network visualization: draw the NetParameter protobuffer.
NOTE: this requires pydot>=1.0.2, which is not included in requirements.txt
since it requires graphviz and other prerequisites outside the scope of the
Caffe.
"""
from caffe.proto import caffe_pb2
from google.protobuf import text_format
import pydot
... |
384ecba827d892fbfd889a84f3f89c02d4f7320f349a2d47cd9b82e3f0be2642 | Python | 2,737 | 72 | """Script to download the metadata for every
TCIA dataset. The metadata collected
at this stage is the Modality, SeriesInstanceUID, ImageCount,
BodyPartExamined, SeriesDescription, PatientID. These
are useful things to have going forward.
"""
from tciaclient import TCIAClient
import urllib.request, urllib.error,... |
d1c7362d31ec004a059c9b7d6b013d10ec7730fe9387339f5d4647cafd31cf4d | Python | 2,737 | 73 | # pylint: disable=unused-argument,arguments-differ
"""Predictor for classification/box prediction."""
from __future__ import absolute_import
import mxnet as mx
from mxnet.gluon import HybridBlock
from mxnet.gluon import nn
class ConvPredictor(HybridBlock):
"""Convolutional predictor.
Convolutional predictor i... |
729aa18843108549c59d9ac5bd4e3a836c2a2f329c1d4ad22e86dd910555b255 | Python | 2,738 | 45 | import sys
sys.path.append('../TM2_segmentation')
import argparse
import os
import warnings
from scripts.slice_selection import train
from settings import CUDA_VISIBLE_DEVICES
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'
warnings.filterwarnings("ignore")
if __name__ == '__ma... |
f3ce819a619c48a5a7baeddf2b8b0be175121e1aa374a57791e9f45f31366c4b | Python | 2,739 | 76 | import gzip
import os
import subprocess
import sys
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = ' ' * 4 * level
print('{}{}/'.format(indent, os.path.basename(root)))
subindent = ' ' * 4 * (level +... |
9bdfde70b3898cd6e50fe5950ff003b4986e69b74bfb92691acf51e729b85e29 | Python | 2,740 | 81 | import os
import tempfile
from typing import List, Tuple
import hydra
import numpy as np
import pytest
import torch
import torchvision
from hydra.experimental import compose
try:
from hydra import initialize
except ImportError:
from hydra.experimental import initialize
from torch import manual_seed
from torc... |
dcecdc6139e04546be5a2a16cd485dde3fd08fb0fee5eafdecac4ac8f37d6936 | Python | 2,740 | 83 | if __name__ == '__main__' and __package__ is None:
from os import sys # , path
sys.path.append('../')
import torch.nn as nn
class BaseNetwork(nn.Module):
def __init__(self):
super(BaseNetwork, self).__init__()
def init_weights(self, init_type='normal', gain=0.02, bias_value=0.0,
... |
638a52ae9624c77367b93ccbcdbda8804669d45eea9beea83b62c245c0f8a2ee | Python | 2,741 | 86 | import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
def median_calc(y_true, y_score):
"""
Calculate the median of the scores in y_score for the positive class labels (1) in y_true.
Parameters
----------
y_true : array-like
The true binary labels. Assumed to be... |
a11f60de332f8c5c183fb944ad4e9232e036dc879ad242d77fc3cc9b7b910c65 | Python | 2,742 | 81 | import numpy as np
from ome_zarr_models.v06.coordinate_transforms import (
Axis,
CoordinateSystem,
CoordinateSystemIdentifier,
)
from ome_zarr_models.v06.multiscales import Multiscale
from ome_zarr.classes.image import OMEZarrImage, OMEZarrLabels, OMEZarrMultiscale
def test_get_local_coordinate_system():... |
d889a6df404ae5ef1c69113258f82d241af633e19ec90d5846253b5b3867902d | Python | 2,742 | 83 | from typing import Union, Optional, Tuple, Collection, Sequence, Iterable
from anndata import AnnData
import numpy as np
from scipy.sparse import issparse, isspmatrix_csr, csr_matrix, spmatrix
from scipy import sparse
from stlearn import logging as logg
import scanpy
def log1p(
adata: Union[AnnData, np.ndarray, s... |
ded6e8257164d719ea4bb5b63f7f0bef8f59498ae2ed63505c3f966589299dd2 | Python | 2,743 | 94 | # !/usr/bin/env python
# -*- coding: UTF-8 -*-
# !/usr/bin/env python
__author__ = "Bjoern Gruening"
__version__ = "0.1"
__date__ = ""
__license__ = "GLP3+"
import argparse
import os
import subprocess
import tempfile
from Bio import SeqIO
from Bio.Alphabet import IUPAC
from Bio.Seq import Seq
from Bio.SeqRecord imp... |
6491f3946fe3032c3b978c802c4d125c43610ed07912c1581af954dae8ad8171 | Python | 2,744 | 83 | import os
import random
import re
import numpy as np
import torch
from torch.utils.data import Dataset
class TorchDataset(Dataset):
"""
Loading the Datasets
"""
def __init__(self, directory, augmentations=False):
self.directory = directory # 1)
self.augmentations = augmentations
... |
8cf8d65ea5f502a758e0937dc7d4f9d6f2fbfa90bfc5fee5de3edd3a3206862e | Python | 2,745 | 91 | import numpy as np
from numpy.random import default_rng
import pathlib
from mpi4py import MPI
from causal_optoconnectics.tools import conditional_probability, joint_probability, roll_pad
from causal_optoconnectics.generator import (
construct_connectivity_filters,
construct_connectivity_matrix,
simulate,
... |
20d8e9ea4b1ee89f1e85e4b4996296befdddd1341cf6b7abfac58e15f4c235b4 | Python | 2,746 | 64 | import os
import numpy as np
from .protein_split import ProteinSplit
from sklearn.model_selection import train_test_split
from data.pdbbind import PDBbindMetadataProcessor
from data.chembl_connector import ChEMBLConnector
class KinasesTKSplit(ProteinSplit):
def __init__(self,
split_type: st... |
44207d702ea8d3a37f8ea09beba48525f20a5068973ff303ccb800068659c624 | Python | 2,746 | 74 | """Tests for TorchLens ``.tlspec`` format detection."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from torchlens.io import detect_tlspec_format
def _write_json(path: Path, data: dict[str, Any]) -> None:
"""Write a JSON object to one path.
... |
5892b70234fc39637c6312965ba00bcdb5cb2c3cf49fe66e9667ba8f2861722d | Python | 2,746 | 74 | """Cold-trigger provocations for visualization/lookup refusal codes (R25).
Each test provokes one historically UNPROVOKED_BASELINE code through its
documented public door and asserts the exact ``fields["code"]`` -- the
b6 R25 ratchet direction: a code leaves the baseline only when a test like
these lands, and a code s... |
a5666804fd0eafba8ec64604cfd6fe4002727b0abfebad9128132715f95911f1 | Python | 2,746 | 87 | """Persisted metadata bytes must not depend on ``PYTHONHASHSEED`` (B3R4-R21-2).
The M6 relation views are exact ``frozenset``s of label strings, and a
``frozenset`` pickles in hash-table iteration order — salted per process for
str elements. Two processes capturing the identical program therefore emitted
byte-differen... |
abb1aebf67cca53834008e1bd4607839b1ff80dea0ec7bece5b3317736011782 | Python | 2,746 | 85 | import os
from mirp import extract_images
from mirp._images.ct_image import CTImage
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
def test_rank_noise_estimation_method():
data = extract_images(
write_images=False,
export_images=True,
image_export_format="native",
image=... |
79cb27ef223e8eef85142f6acd3e49ca775747bab2e71cf9853cb57c321a7357 | Python | 2,747 | 85 | import nway.onprem_utils.query_utils as qu
import pytest
import os
from unittest.mock import MagicMock
@pytest.mark.parametrize(
"env_prefix, user, password, defaults, expected",
[
(
"PYTEST_DB_CREDS",
"secret_user",
"secret_password",
... |
42822f5e3e411f580d0d0229c41368a61998fffff8f6d2d45c720fc6fa5026b9 | Python | 2,748 | 81 | """SHAP bridge against the REAL shap package.
``background`` is required: the old default explained each input against
itself, which gives all-zero SHAP values for a single input. With a
background the bridge is bit-identical to ``shap.DeepExplainer`` called
directly with the same background.
"""
from __future__ impo... |
9078f53a4c495216d35cab0fc5ac1b38036982c82831228ac93108a015aab401 | Python | 2,749 | 89 | # Copyright 2023 DeepMind Technologies Limited
#
# 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 agree... |
417e5e28d1b83f8c58646fe5fb90f5851dbb147c0d96b1c771532746ad3a9ba3 | Python | 2,750 | 90 | import os
import pickle
import numpy as np
import h5py
import tqdm.auto as tqdm
from modular_splicing.dataset.data_rewriter import data_rewriter_types
from .gtex_dataset import GTExDataset
from modular_splicing.utils.construct import construct
def create_const_alt_data(
*,
path_whole,
path_const_alt,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.