sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
c157c9187d760d687290a4a8e7f29a667e67f8b764c96bbd6e26a91c418911a5 | Python | 2,277 | 78 | import os
from six.moves.urllib.request import urlretrieve
from zipfile import ZipFile
from hic3defdr.util.printing import eprint
DEMO_DATA_URL = 'https://www.dropbox.com/sh/mq0fpnp4jz59wpo/AAD2FW1Tp_mVKCkxlJoZvxC8a?dl=1' # noqa: E501
CHROMS = ['chr18', 'chr19']
CONDS = ['ES', 'NPC']
COND_EXT = ['clusters.json']
RE... |
ec9747fa83176967d83b57b6b564311d1f2239a11506d3a46366210b5883a959 | Python | 2,277 | 54 | # Copyright (c) 2017-present, Facebook, 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 or agreed... |
d55289c64c302941f5db356299f51fe08fb59c5f02cd8ff0b3997988b5de6039 | Python | 2,279 | 64 | """Helpers for masking secret `runtime_env` values before they leave the process.
These are dependency-free so that both the dashboard (HTTP responses) and the
runtime env agent / reporter agent (log lines, process command lines) can use
them.
"""
import json
import logging
from typing import Any, Dict, Optional
logg... |
a4e79e33bda98029e77d33bec36215ac08838187181d6ad564f07d43ef76c8bd | Python | 2,281 | 51 | # -*- coding: utf-8 -*-
# This Python file uses the following encoding: utf-8. This is particularly relevant for Python 2.x to handle Unicode
# characters.
# In Python 3.x, utf-8 is the default encoding.
class Config_DenseAutoencoder(object):
"""
Configuration class for a Dense Autoencoder.
This class ini... |
387d58232496f3fe15a97547ff631f795bd8815effdadd760147771dca9da9c8 | Python | 2,282 | 82 | # flake8: noqa
# __begin_example__
import time
from typing import Generator
import requests
from starlette.responses import StreamingResponse
from starlette.requests import Request
from ray import serve
@serve.deployment
class StreamingResponder:
def generate_numbers(self, max: int) -> Generator[str, None, Non... |
5c5c061525a58d38c3e6a914483bb151074f52e6f1c6a3063b7d95cea67b63ba | Python | 2,282 | 64 | import sys
import json
import copy
import argparse
import subprocess
from tqdm import tqdm
from lop.utils.miscellaneous import get_configurations
def main(arguments):
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argum... |
4f3576ff894964c302505018a4033ef16ae597a3d2d6e2d78a9f553f38eb6a12 | Python | 2,284 | 93 | from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, Optional, Tuple
from ..gateway.routing import SessionKey
@dataclass(frozen=True)
class ConversationRoute:
channel: str
scope_type: str
scope_id: str
thread_id: Optional[str] = None
sender_id... |
b25fb53eea4b04193f52ea99d44e6c55aa47306ec581c0c7ffe178d21599ec4a | Python | 2,284 | 87 | """Utility functions for operations on torch.nn.Modules."""
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Generator
from torch import nn
@contextmanager
def simulation(network: nn.Module) -> Generator[None, None, None]:
"""
Context manager to turn off training mo... |
feb807f60199c21be4d05b5705e050aade773a8a7acd9ba643686fb254d57643 | Python | 2,284 | 76 | ####################################################################################################
# Copyright (c) 2016 - 2024, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis>
#
# This program is fre... |
70970e118b3571b2f4a780185d33c767beba12a25df5d15d88bf9e2a3012275b | Python | 2,285 | 68 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import annotations
from fairchem.core.components.benchmark.fake_dataset import (
BENCHMARK_DATASET_SPECS,
FakeData... |
28590d4b4974654786e2d93a32ff727e5afce4a61fb6705fcd9ccdf58ca8e461 | Python | 2,286 | 74 | """
To build curl commands from copy pasted forms from the biobank website
"""
import sys
FORM_TEXT = """
<form name="fetch" action="https://biota.osc.ox.ac.uk/dataset.cgi" method="post">
<input type="hidden" name="id" value="67343563">
<input type="hidden" name="s" value="38023627">
<input type="hidden"... |
85d1092883aeb069de94a8d9e7234616b5306ed68a3fc3d2a5e4729a933076f0 | Python | 2,286 | 66 | # Author: Zachary Chiang, Buenrostro Lab, Harvard University
# Converts ex situ sequencing barcodes to colorspace
import sys
# Cy5, FITC, Cy3, Texas red (PGP1_001)
#dibase2color = {"AA":2, "AC":3, "AG":4, "AT":1, "CA":3, "CC":2, "CG":1, "CT":4, "GA":4, "GC":1, "GG":2, "GT":3, "TA":1, "TC":4, "TG":3, "TT":2}
# Cy5, ... |
cbadb9ddd8904f650a85141ad3a21e0bf8c2014df2db5dde2371db04c9291d49 | Python | 2,286 | 72 |
import numpy
import argparse
import sys
import random
import gym as gym
from gym import wrappers, logger, envs
from collections import OrderedDict
from tqdm.auto import trange
from gym_sted.rewards import RewardCalculator
from gym_sted.agents import RandomAgent
from gym_sted.rewards import objectives
obj_dict = {
... |
0b3ad001341829e63491f31b6c278ebd4caa6425d66b450d5dad91eea91958fe | Python | 2,287 | 75 | import enum
import os
import sys
from typing import TypeVar
import aiohttp
from ray._private.utils import validate_socket_filepath
K = TypeVar("K")
V = TypeVar("V")
class ResponseType(enum.Enum):
HTTP = "http"
STREAM = "stream"
WEBSOCKET = "websocket"
def module_logging_filename(
module_name: str... |
0e255cade5d33c88103e598a04a3d9568fb4bcd80b94c1473ae47811e2506fa8 | Python | 2,290 | 71 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
FastCSP - Fast Crystal Structure Prediction Workflow
Main entry point orchestrating the complete FastCSP workflow.
"""
from __future__ import... |
c5e07759e24ff1d57fffbf0c1ab6184f351a0ea4df017854f0577b20bd4e2271 | Python | 2,290 | 71 | #!/bin/python
#------------------- Description & Notes --------------------#
#------------------- Dependencies ---------------------------#
# Standard imports
from pathlib import Path
# Third-party imports
import numpy as np
import pyspark.sql.types as T
import pyspark.ml.functions as F
from tensorflow.keras import... |
c70329ff8acc0a29d7752a2871de306a82a05a2ed8a476934e35aadcef9b62ad | Python | 2,290 | 85 | from argparse import ArgumentParser
from pathlib import Path
from fastai.vision.learner import load_learner
from marugoto.mil._mil import deploy
from marugoto.mil.data import get_cohort_df, get_target_enc
def add_deploy_args(parser: ArgumentParser) -> ArgumentParser:
"""Adds arguments required for model deploym... |
cf7488b12d7ca600b1e4c5ceaff889ae39bd3c7c65859820ec3b40933c027464 | Python | 2,290 | 78 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
import samri.plotting.maps as maps
import seaborn as sns
from os import path
import pytest
def test_atlas_labels_longtime():
maps.atlas_labels()
def test_atlas_labels():
mapping = pd.read_csv('/usr/share/m... |
80338c7e7189390254cc99b15aca7a1d0c34aa60f19f5917611f9e534c08c2c6 | Python | 2,291 | 71 | import torch
class Hypergrad:
"""Implicit differentiation for auxiliary parameters.
This implementation follows the Algs. in "Optimizing Millions of Hyperparameters by Implicit Differentiation"
(https://arxiv.org/pdf/1911.02590.pdf), with small differences.
"""
def __init__(self, learning_rate=0... |
c4b906120e8ddc52c006de82699581307e4da8754172d24c51c7b9729de29b7b | Python | 2,291 | 66 | from pathlib import Path
import pandas as pd
import pytest
from siapy.datasets.helpers import (
generate_classification_target,
generate_regression_target,
)
from siapy.datasets.schemas import ClassificationTarget, RegressionTarget
from siapy.entities import Pixels
@pytest.fixture(scope="module")
def sample... |
16bb52274c7b8ab6f66bd0220b823d950074c01d84405b6f4198043c9aa05661 | Python | 2,292 | 56 | import pandas as pd
import matplotlib.pyplot as plt
d_a_df = pd.read_csv("d_a.bed", sep="\t", header=None)
print(d_a_df)
seq_len_ls = d_a_df.iloc[:, 2] - d_a_df.iloc[:, 1]
seq_len_sum = seq_len_ls.sum()
splam_seq_len_intron = len(seq_len_ls) * 400
splam_seq_len_flanking = len(seq_len_ls) * 400
splam_seq_len = splam_s... |
1f7d36e5b04d11e45102d1e6f0477b92ab5e607fab793452d2bee53e65b46477 | Python | 2,292 | 67 | r"""``ov.epi.io`` — epigenomics readers & region utilities.
Pure-format readers (10x ATAC matrices, GTF/GFF) plus coordinate ↔ gene
annotation and peak-set helpers, delegating to :mod:`epione.io` and
:mod:`epione.utils`. Each function imports epione internally.
"""
from __future__ import annotations
from ._utils imp... |
81d71e4be47d53791b6b38bb0fe4bd8743734629aef16a036a7ba9bdb5485f77 | Python | 2,292 | 52 | import torch
import torch.nn as nn
from utils.pytorch_ssim import SSIM
# Total Variation Loss to encourage smoothness in images
class TVLoss(nn.Module):
def __init__(self, TVLoss_weight=1):
super(TVLoss, self).__init__()
self.TVLoss_weight = TVLoss_weight # Weight for the TV loss component... |
429dfd9a2529279c2457b767237b0c0f25c836b41c06cd5dd0768fc8432d4195 | Python | 2,294 | 83 | """omicverse.report — one-call HTML pipeline report for an AnnData.
Usage::
import omicverse as ov
ov.report.from_anndata(adata, output="report.html",
title="PBMC 3k pipeline")
The report inspects ``adata`` for evidence of standard scRNA pipeline
steps (QC, HVG, PCA, neighbors, UM... |
cd43beded2e353c0b0db83c02203c70cceefc17c26fc01c329d4cf196c94c314 | Python | 2,294 | 47 | # Copyright (c) 2017-present, Facebook, 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 or agreed... |
702c70efe529740c2d14b92a0c0577fd4a402ab040c5f1691d825827b4038db5 | Python | 2,295 | 64 | from tensorflow.keras.layers import Dropout, Activation, BatchNormalization, Conv2D, Conv3D, LeakyReLU,Conv3DTranspose,Concatenate
from tensorflow.keras.initializers import RandomNormal
def conv_blocks(n_filter, kernel=(3,3,3),
activation="relu",
padding="same",
dropout=... |
d3a788ac4aaa0ce2d9d8b27bf9f856d88ec791c361dcd9df2bc91994eb1d7bf0 | Python | 2,295 | 86 | import os
import pdb
import pickle
from matplotlib import pyplot as plt
import numpy as np
from tqdm import tqdm
import yaml
from yaml.loader import SafeLoader
import torch
from latent_time_stepping.oracle import ObjectStorageClientWrapper
from latent_time_stepping.datasets.AE_dataset import AEDataset
from latent_time... |
07af3542a1d80228d6b0fc7875f5c6ad4b86f0ce92bb8ef44127e6ca773e7b21 | Python | 2,296 | 56 | '''
Stitches up multiple files with the same number of rows, and different columns. Would arrange the files based on file names, then stitch them to the right of each other.
The column names would also be changed to include information (plane number) of the original file.
Can be used for any csv files in OutputData ... |
bc718d16b2d688352adc64cbaf02913ecddeb45d668faea8f69021de2fb92a28 | Python | 2,296 | 56 | import pandas as pd
import matplotlib.pyplot as plt
d_a_df = pd.read_csv("d_a.bed", sep="\t", header=None)
print(d_a_df)
seq_len_ls = d_a_df.iloc[:, 2] - d_a_df.iloc[:, 1]
seq_len_sum = seq_len_ls.sum()
splam_seq_len_intron = len(seq_len_ls) * 400
splam_seq_len_flanking = len(seq_len_ls) * 400
splam_seq_len = splam_s... |
bfadb5064ae95860fc2852bed0590733a344bd52a62fc22c730cd389abb4cf9c | Python | 2,297 | 72 | import marshmallow as mm
from argschema.schemas import ArgSchema, DefaultSchema
from argschema.fields import (
InputFile, List, Float, Int, Nested
)
from neuron_morphology.transforms.affine_transformer._schemas import (
AffineDictSchema
)
def validate_neighbors(num):
if num<4 or (num % 2) != 0:
err... |
1bdf15a91590b25e2fcaca3ac1ec254592c3358c382b31b26f09103dda79a39c | Python | 2,298 | 62 | import sys
def main():
output_files = ["./OUTPUT/pos/", "./OUTPUT/neg_can/", "./OUTPUT/neg_noncan/", "./OUTPUT/neg_1/"]
prefix = "../src/INPUTS/800bp/input_"
output_testset_files = ["pos", "neg_can", "neg_noncan", "neg_1"]
target = "splam"
for idx in range(1,4):
output_set = set()
... |
315080286c3000c39dd85cabd970b762ed620660203e18cabfd77143390dfa9b | Python | 2,298 | 79 | import torch
from pfrl.agents import dqn
from pfrl.utils.recurrent import pack_and_forward
class AL(dqn.DQN):
"""Advantage Learning.
See: http://arxiv.org/abs/1512.04860.
Args:
alpha (float): Weight of (persistent) advantages. Convergence
is guaranteed only for alpha in [0, 1).
For o... |
8bfd7af6eac42bb42dee5958ffc37553b8d3b64f915ca0752b3cbcffe487eb2c | Python | 2,298 | 65 | """CenterFace must treat a heatmap below threshold as an ordinary no-face result."""
from unittest.mock import MagicMock
import numpy as np
import pytest
from deepface.models.face_detection.CenterFace import CenterFace, CenterFaceClient
from deepface.modules import detection
from deepface.modules.exceptions import F... |
c8621a77d8d7abd991919ae712f8f8d552d67cde6cbe6af33eea5a005c06b945 | Python | 2,298 | 66 | #!/usr/bin/env python3
# Szi Kay Leung (sl693@exeter.ac.uk)
"""
Aim: Split reference genome annotation gtf by target gene name
"""
## Load Libraries
import argparse
from gtfparse import read_gtf
import pandas as pd
import csv
import numpy as np
def writeGTF(inGTF,file_path):
"""
Write a GTF dataframe into ... |
e75cd03592ac4e387a8104f218c865bb2c6afab610a19c1cd4827fec49005f83 | Python | 2,298 | 55 | ####################################################################################################
# Copyright (c) 2016 - 2024, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis>
#
# This program is fre... |
99cc74b565a9d82052e396f2a7e6f0fe808636d2044cfe78a7c5919337472879 | Python | 2,299 | 72 | # This file is part of the INTREPPPID programme.
# Copyright (c) 2023 Joseph Szymborski.
#
# This programme is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3.
#
# This programme is distributed i... |
205916ea1ccecfb956398c9d46c61746bdac4a12a8154065c54d5e39b06945a5 | Python | 2,300 | 57 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.DeepLab.modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
class Decoder(nn.Module):
def __init__(self, num_classes, backbone, BatchNorm):
super(Decoder, self).__init__()
if backbone == 'resnet1... |
d0d0d687f0e1f46681a033baa2580113f2ea25ed820faf23463aa0432ae049f0 | Python | 2,300 | 69 | import numpy as np
import tifffile
import h5py
import os
import scipy.io as sio
import cv2
median_area_target = 377
if 1:
dir_parent = r'E:\1photon-small\added_refined_masks'
list_Exp_ID = [ 'c25_59_228','c27_12_326','c28_83_210',\
'c25_163_267','c27_114_176','c28_161_149',\
'c25_1... |
24abfd9f48aa2b9bb347149f251291bedce8caaa27feb502865aafcf1c2e951d | Python | 2,301 | 66 | # Copyright (c) 2017-present, Facebook, 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 or agreed... |
e7f6919ed19b4984b1cd2c91a5b19186f58137fbb4d0820267cf758011837e96 | Python | 2,301 | 68 | import torch
import torch.nn.functional as F
from tqdm import tqdm
from dice_loss import *
def miou(logits, targets, eps=1e-6):
"""
logits: (torch.float32) shape (N, C, H, W)
targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1}
"""
outputs = torch.argmax(logits, dim=1, keepdim=True).typ... |
0ee57479c5a51bc0691170c5ff3fd63deaea5dbb7b011da5b2dc3dca405b832d | Python | 2,302 | 48 | ###################################################################################################
# Copyright (c) 2016 - 2024, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis>
#
# This program is free... |
8e713501c7d2944cf6b217d691846f687157e33efc10d0bba24aa2ba42edfd76 | Python | 2,302 | 73 | import torch
import torch.nn as nn
import torch.nn.functional as F
class MCNN(nn.Module):
def __init__(self, input_channels=3):
super(MCNN, self).__init__()
# Up branch
self.up_brach = nn.Sequential(
nn.Conv2d(input_channels, 16, kernel_size=9, padding=4),
n... |
2a4c92538a76df3ca2ad70fb193ef17bf42bce01d10b9ce4d97684cddee8653d | Python | 2,303 | 83 | #!/usr/bin/env python
"""
This script gathers build metadata from Travis environment variables and Travis
APIs.
Usage:
$ python get_build_info.py
{
"json": ["containing", "build", "metadata"]
}
"""
import json
import os
import platform
def gha_get_self_url():
import requests
# stringed together api cal... |
5784062d79b5900ec0e04e5f1ce9bc5b9accad8b686c716da42839f113967df4 | Python | 2,303 | 60 | # modified from https://github.com/facebookresearch/deit
import torch
import torch.distributed as dist
import math
class RASampler(torch.utils.data.Sampler):
"""Sampler that restricts data loading to a subset of the dataset for distributed,
with repeated augmentation.
It ensures that different each augmen... |
5bcea956c03ea43994e1246e5ca1e0e6ccb0c9b00d0f6e014286d673662b7823 | Python | 2,304 | 63 | import torch
from ..base import Transform, as_range, randint, uniform
from ..ops import interp
def crop_length(n_samples, duration, fs):
if (n_samples is None) == (duration is None):
raise ValueError("give exactly one of n_samples or duration")
if duration is not None:
if fs is None:
... |
77cb74105a37b795f5a2ff2c1ebee1f5a42bfa186063eb8a80ec06e22ed9c9a8 | Python | 2,305 | 72 | import numpy as np
from .basic_distributions import Distribution
from ... import config
class UnivariateGaussian(Distribution):
"""
Class to define univariate Gaussian distributions
Equations:
Class for a univariate Gaussian distributed node
p(x|mu,sigma^2) = 1/sqrt(2*pi*sigma^2) * exp(-0.5*(x-mu... |
88a3b64f2a97c9ed609a596052c1027afb7d1b774dede0cd786850ca5f10643e | Python | 2,305 | 89 | """
monocle2_py: Pure Python implementation of Monocle2 for single-cell trajectory analysis.
Input: AnnData objects (from scanpy/anndata).
All analysis state is stored in ``adata.obs`` / ``adata.var`` /
``adata.uns['monocle']`` / ``adata.obsm`` — the library never writes
intermediate files to disk.
"""
from .core imp... |
cd4044bfdef75ce2123cac32240eeebe426441c4bc31c3e82da770ba062e1cb8 | Python | 2,305 | 74 |
from urllib import request
import gzip
from lisa.core.data_interface import DataInterface
from lisa.core.genome_tools import Region, BadRegionError
from lisa.core.utils import Log, LoadingBar
import argparse
from scipy import sparse
import os
from scipy.stats import gamma
import numpy as np
from sys import stdout, std... |
3c93e0d01986b75c105f7230bbfb20af7996b44e2c00adb917a414142fa14e6c | Python | 2,306 | 52 | import os
import json
import shutil
import argparse
from utils.tools import ROOT_PATH, create_configs_from_seq_dict
from kfold_run import main
"""For ablation studies."""
# --------------------------------------------- #
# --------------------------------------------- #
if __name__ == "__main__":
# Argument pa... |
f7e9b920a6473b10ca50a0ff100d9dc037f85b3cc78083f07dd1911b4572d16d | Python | 2,307 | 62 | import flask
from flask import request, jsonify, abort
from flask import render_template
from flask_cors import CORS, cross_origin
from flaskext.markdown import Markdown
from bionlp import nlp, disease_service, chemical_service, genetic_service
from spacy import displacy
colors = {"DISEASE": "linear-gradient(90deg, ... |
00c488ad159c69006548d0c0bc471293bbe3364a6e8e7f5bb61547f188951a88 | Python | 2,308 | 49 | import json
import os
from pathlib import Path
from simulation.plotter_functions import plot_jitters_sims, plot_shuffle_sims
def plot_results2d(config_erp, config_rt):
# ========================================================================================
# Load config:
# Load the ERP config:
with... |
3e00b38adc689c78e6e1ae8532abcda8aefd44d3f6b6fb79919e00c5368411f6 | Python | 2,308 | 73 | # Vendored from `decoupler` (https://github.com/scverse/decoupler) by
# omicverse for in-tree GPU acceleration work. Original copyright by
# the decoupler authors, redistributed under decoupler's GPL-3.0
# license. Cross-module imports rewritten from `decoupler.*` to
# `omicverse.es.*` (see scripts/vendor_decoupler.py)... |
8704bce3a55995d11c8151699e06d189344c481057d2e83aa6e83eca84293712 | Python | 2,308 | 79 | """
a gru-a2c
the gru uses the implementation from:
https://github.com/emadRad/lstm-gru-pytorch/blob/master/lstm_gru.ipynb
"""
import math
import torch
import torch.nn as nn
from models.A2C import A2C_linear
# from models.A2C import A2C
from models._rl_helpers import pick_action
class GRU(nn.Module):
"""
An ... |
bef1276fbbdc55aca28f1e9bc0324ddd0a714e70eb5e9492f8f3dd0f06ec2765 | Python | 2,308 | 76 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import annotations
from abc import ABCMeta, abstractmethod
from typing import TYPE_CHECKING, Any
from omegaconf import Di... |
f0ab6f5210cb626dcdef420c10ef78375ad8e77d58a908a50779c272d7bf10a3 | Python | 2,309 | 63 | ####################################################################################################
# Copyright (c) 2016 - 2024, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis>
#
# This program is fre... |
018f4da2ed828f2006a29c69f2404410f66bd2d2e143f94dc13de409520fd44f | Python | 2,310 | 88 | from base64 import urlsafe_b64encode
from hashlib import blake2s
import krock32
from time import time
import secrets
import re
import struct
from typing import Optional
def generate_token(namespace: str, token_data: Optional[bytes] = None) -> str:
"""
Generates a random, namespaced token with a time componen... |
129f695ef790c88dd74567b44d31c5bc6a8323754fcf04fd254348d02d5a53aa | Python | 2,310 | 64 | import pathlib
path = pathlib.Path.cwd()
if path.stem == 'tmb_survival':
cwd = path
else:
cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')]
import sys
sys.path.append(str(cwd))
from tqdm import tqdm
import concurrent.futures
import numpy as np
from lifelines.statistics import logrank_test... |
b62f0c66a0f062482450656f04d3d242e4e12747802bc1367eb24f8c4e8019cf | Python | 2,311 | 68 | '''
Computes T1w image in EPI-space from motion-corrected 'nulled' and 'notnulled'
timeseries of all sessions as acquired with SS-SI VASO.
'''
import numpy as np
import nibabel as nb
from scipy import signal
import glob
ROOT = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives'
nulledFiles = ... |
134054504c856646f550b391cb53a385ecbbf0416bc1ff3401f18009147e2afa | Python | 2,313 | 73 | import marshmallow as mm
from argschema import ArgSchema
from argschema.schemas import DefaultSchema
from argschema.fields import Nested, Float, List, InputFile, OutputFile
def validate_input_affine(data):
has_affine_dict = bool(data.get("affine_dict"))
has_affine_list = bool(data.get("affine_list"))
if ... |
24449a5588cb0d6e2f1422dddb7a76ee3be42dbbfad478cb8b6d42b062588481 | Python | 2,313 | 106 | """Pure-Python subset of Bioconductor edgeR."""
from .core import (
DGEExact,
DGEGLM,
DGELRT,
DGEList,
TestResults,
add_prior_count,
ave_log_cpm,
calc_norm_factors,
cpm,
decide_tests_dge,
effective_lib_sizes,
equalize_lib_sizes,
estimate_common_disp,
estimate_dis... |
faa905733bfc5c31b389b4a864e68b857b66395b15a9c3f43e34965102d63c02 | Python | 2,313 | 54 | import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers import GraphConvolution
class GCN_plus(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout, nlayer):
super(GCN_plus, self).__init__()
self.gc_layers_A1 = nn.ModuleList([GraphConvolution(nf... |
e0f0a627835ba0c1ef53be8d9af33f96c74d9136ab5d76a2f8830f84763cc390 | Python | 2,315 | 97 | import itertools
import numpy as np
from keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import tqdm as tqdm
import numpy as np
import pandas as pd
from functools import reduce
def load_text_file(file_text):
with open(file_text) as f:
li... |
e393bb3b99a4799ed54d5048ebaf346b8630b4922c4467e3225a877b0821b28e | Python | 2,315 | 65 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#... |
898760bd218decce94c220444d43897bcbe09b0e336eccba3660d0fee860d3af | Python | 2,316 | 82 | from typing import TYPE_CHECKING, Optional
from ray.data._internal.delegating_block_builder import DelegatingBlockBuilder
from ray.data.block import BlockMetadata
from ray.data.datasource.datasource import Datasource, ReadTask
if TYPE_CHECKING:
import torch
from ray.data.context import DataContext
TORCH_DA... |
55cef331f794fa5fcb21a4b9fbd908bc5ed3c9cd8122cc19236a8e07cb98258a | Python | 2,317 | 55 | # EDIT 10/04/2022 - This version was provided by @jayelm who fixed some bugs and made the function much more robust
import os
import subprocess
import time
def assign_free_gpus(threshold_vram_usage=1500, max_gpus=2, wait=False, sleep_time=10):
"""
Assigns free gpus to the current process via the CUDA_AVAILABL... |
7e1812de6dde8991f432c8350bd78a8df2b766326827171cef9e86481080c53f | Python | 2,318 | 59 | import multiprocessing
import os
import os.path as osp
from tqdm import tqdm
import numpy as np
import pandas as pd
import oddt
import oddt.pandas as opd
from rdkit import Chem
from torch_pgn.graphs.graph_utils import _return_graph
from torch_pgn.datasets.PGDataset import PGDataset
class ManyVsManyDataset(PGDatas... |
b7875f4187baed343e8d600bc8e04b0c52f86bc62ee51124ef5c9d3ec7b7dc59 | Python | 2,319 | 88 | #!/usr/bin/env python3
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c) 2018 Jakub Červený
def gilbert2d(width, height):
"""
Generalized Hilbert ('gilbert') space-filling curve for arbitrary-sized
2D rectangular grids. Generates discrete 2D coordinates to fill a rectangle
of size (width x heigh... |
1851b2469fd2ddb56baeb2c495f1e02edc9ae08df054812cf9c4c36870fe96e4 | Python | 2,320 | 52 | import sys
import os
sys.path.append(os.getcwd())
from misc.dictionary_extension import DocumentTermDictionary
from gensim.models import KeyedVectors
def verify_bridging(term_dict, query_term: str, term_of_interest: str, potential_bridging_terms: list):
# Find all documents with ToI and query term (should have no... |
4c7fa54706225b9e59162e8f6a82414af20dada67951c656a5eb24dafdbbce26 | Python | 2,320 | 81 | from scipy.io import loadmat
from scipy.special import erfcinv
import numpy as np
import pandas as pd
from itertools import combinations
def star(p_val):
assert 0 <= p_val <= 1
if p_val >= 0.05:
return 'ns'
if p_val >= 0.01:
return '*'
if p_val >= 0.001:
return '**'
if ... |
3df22a671b2e59a5e513aae569a7a952175c9d7e558ba0729b1fa0c076a05cd0 | Python | 2,321 | 66 | import torch
from ..utils import loss_and_miner_utils as lmu
from ..miners.base_miner import BaseTupleMiner
class UniformHistogramMiner(BaseTupleMiner):
def __init__(self, num_bins=100, pos_per_bin=10, neg_per_bin=10, **kwargs):
super().__init__(**kwargs)
self.num_bins = num_bins
self.pos... |
8213eea3fcfc71491c0d298e028b350a0d1737333e6333dc5c6802e63a352eea | Python | 2,321 | 74 | import os
import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
####################################################################################################
# @read_file
####################################################################################################
def read_file(file_path)... |
0c8089f9adde8d23ef865cf2aa5482b5bbfb615af61ced30617bd7a89896ce83 | Python | 2,322 | 71 | from django.core.management.base import BaseCommand, CommandError
from django_q.tasks import async_task
from infer.models import Protein, Weights, Organism, ProteinEmbedding
from infer.tasks.infer import compute_embeddings
import json
def attach_proteins(weights, taxon, batch_min, batch_max):
batch = Protein.obje... |
15b0e3190e53e12b0892ce44214812e02c23150c59a880fe7491dfbf914ce263 | Python | 2,323 | 89 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""aihwkit example 13: Experiment training (3 fully connected layers).
Creation and execution of a Basic Training experiment, where the model uses
3 fully conne... |
a93ee04f82239509b596e992b990a44d153b5d147369b1ddfe357a789b3d526e | Python | 2,323 | 87 | import numpy as np
import torch
from aisegcell.utils.evaluation import iou, iou_to_f1
def test_iou():
"""
test if iou returns as expected.
"""
pred = torch.FloatTensor(
[
[
[
[1.0, 0.8, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.9],
... |
2900dd7fde5b3adb6f8d832ec49b87a62acd20dae473ebce3e6466d1c8789f4d | Python | 2,324 | 69 | import argparse
import skorch
import torch
from torch.autograd import Variable
import data
import model
import net
parser = argparse.ArgumentParser(description='PyTorch PennTreeBank RNN/LSTM Language Model')
parser.add_argument('--data', type=str, default='./data/penn',
help='location of the data... |
cceba87c5f6a441405ec73b8d7c8aa6bbf8728c3053471a32d4d46c9b9f5549b | Python | 2,324 | 68 | import math
import torch
from torch.nn import Linear, LayerNorm
from torch.nn import Parameter
from torch.nn import init
class MultipleInputsLayernormLinear(torch.nn.Module):
"""
Properly applies layernorm to a list of inputs, allowing for separate rescaling of potentially unnormalized components.
This ... |
f992777a82da37a462c09e2997cfe6923a0e4618089cbbced859ec7a015faa8d | Python | 2,324 | 68 | from imports import *
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
class Base( common.BaseClass ):
modulepath = 'ngs_mapper.fqstats'
class TestReadAvgQual( Base ):
functionname = 'read_avg_qual'
def test_correct_avgq( self ):
rrec = common.make_... |
efa5009f29450e36801925b4e42462a5d53d948e93c48658526ee7bd5ccd040d | Python | 2,325 | 72 | r"""
PopV algorithms collection for cell annotation and integration.
This module provides a comprehensive collection of algorithms for automated cell
type annotation and batch integration, implemented with a unified interface for
easy comparison and benchmarking.
Base classes:
BaseAlgorithm: Abstract base class f... |
7f6d25d9725c7ea021cda796f3cff4cab138831ead75146725f5fe230c8bead7 | Python | 2,326 | 66 | # Ultralytics YOLO 🚀, GPL-3.0 license
from ultralytics.yolo.data import build_classification_dataloader
from ultralytics.yolo.engine.validator import BaseValidator
from ultralytics.yolo.utils import DEFAULT_CFG, LOGGER
from ultralytics.yolo.utils.metrics import ClassifyMetrics
class ClassificationValidator(BaseVali... |
cf2b68ec45b8311cfc5dc839c27302eacfa75c92e9d6e10a0fc39b4cbf9a1ea2 | Python | 2,327 | 89 | import time
import numpy as np
import matplotlib.pyplot as plt
import pdb
from scipy.integrate import odeint
class Burgers():
def __init__(
self,
N: int = 256,
) -> None:
self.N = N
self.nu = 1/150
self.x = np.linspace(0, 2, N)
# Second derivative finite diffe... |
f9cefe03ce2063b63d82db18a0f26dbe6139cf69008a5b3cf4f58c60d0ba8ce6 | Python | 2,327 | 83 | import argparse
import numpy as np
from einops import reduce
from utils import read_lines, load_pickle, save_pickle, load_mask
from visual import plot_matrix
def compute_score(cnts, mask=None, factor=None):
if mask is not None:
cnts[~mask] = np.nan
if factor is not None:
cnts = reduce(
... |
b1ad315644574b30cc9c89d90e575425bd582cc83e1c8658f1f793e24f5b0234 | Python | 2,328 | 64 | import os
import numpy as np
from pcntoolkit.util.utils import calibration_descriptives
#from pcntoolkit.dataio.fileio import load_nifti, save_nifti
from pcntoolkit.dataio.fileio import load as ptkload
from pcntoolkit.dataio.fileio import save as ptksave
root_dir = '/project_cephfs/3022017.02/projects/hansav/Run8_f/'
... |
6fc9b373c48bbd7184a6bf9596c2696c7509df337fef495f2494a75cfb3aff03 | Python | 2,329 | 80 | # Copyright 2026 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
9a5c2ba4137b9afe49e45aacacd9f8b2ec05d2e986c2ffee3a80ab0ee4bef50d | Python | 2,329 | 79 | import torch
import torch.nn as nn
import torch.nn.functional as F
from pfrl.initializers import init_chainer_default
def constant_bias_initializer(bias=0.0):
@torch.no_grad()
def init_bias(m):
if isinstance(m, (nn.Linear, nn.Conv2d)):
m.bias.fill_(bias)
return init_bias
class Larg... |
b42313aadaadd63062020b3919f04834f8da64277086c0672bb669726088801c | Python | 2,329 | 64 | import os
import numpy as np
from pcntoolkit.util.utils import calibration_descriptives
#from pcntoolkit.dataio.fileio import load_nifti, save_nifti
from pcntoolkit.dataio.fileio import load as ptkload
from pcntoolkit.dataio.fileio import save as ptksave
root_dir = '/project_cephfs/3022017.02/projects/hansav/Run8_f/'
... |
5ae05d4a9330146e3edcc97df78ea109af6490a61a1988912f9c2d361ac3068c | Python | 2,330 | 68 | # This file is part of the INTREPPPID programme.
# Copyright (c) 2023 Joseph Szymborski.
#
# This programme is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3.
#
# This programme is distributed i... |
76494563a0105f6df526f8033363b6b7d182d09276e0d2fe333bf39fb43044ab | Python | 2,330 | 59 | import requests
from .__config import base_url
from .__aux_funcs import process_response
def get_all_cancer_types(direction="ASC", pageNumber=0, pageSize=10000000, projection="SUMMARY", sortBy=None):
"""
Get all cancer types from cBioPortal. \n
:param direction: Direction of the sort. \n
Possible v... |
fd498451c18b9d4fe1b4ef0c0888d46d78e4002e1d55f948442cf6acf848065b | Python | 2,331 | 82 | import random
from typing import List, Sequence, Tuple, Union
import torch
from rising.utils import check_scalar
__all__ = ["crop", "center_crop", "random_crop"]
def crop(data: torch.Tensor, corner: Sequence[int], size: Sequence[int]) -> torch.Tensor:
"""
Extract crop from last dimensions of data
Args... |
26aa1c12d30c6c41b7895ce03c6cdc4dc48c0bb074930411ad706c15b33dab90 | Python | 2,332 | 49 | """Helper functions for the model construction functions."""
from torch_geometric.nn import global_add_pool, global_mean_pool, global_max_pool
from torch.nn import LogSoftmax, Softmax
def get_sparse_fnctn(sparse_type: str):
if sparse_type == 'log_softmax':
return LogSoftmax(dim=-1)
elif sparse_type == ... |
e7c9f1782faaaa8cdd813a648c60d4eb7118fd14202d4637a5a01b32c85cc953 | Python | 2,332 | 65 | # built-in dependencies
from typing import Any, cast
# 3rd party dependencies
import numpy as np
from numpy.typing import NDArray
# project dependencies
from deepface.commons.onnx_utils import build_session
from deepface.models.facial_recognition.onnx.OnnxFacialRecognition import OnnxFacialRecognition
from deepface.c... |
ed14df6e9212f86d16e46551305c7c52eb29839e52c5800e5387604c24528361 | Python | 2,332 | 57 | from DWonder.SEG.model_3DUnet import UNet3D, T_conv_net, TS_UNet3D
import torch.nn as nn
import torch.nn.functional as F
import torch
from DWonder.SEG.model_Unet import Unet, Unet3, Unet4
class SEG_Network_3D_Unet(nn.Module):
def __init__(self, UNet_type = '3DUNet', in_channels=1, out_channels=1, frame_num=64, f... |
5cea7c2b6212978d763f445258044c160f701ba040648de7d9196dbf6bd37b48 | Python | 2,333 | 66 | import torch
from ..distances import CosineSimilarity
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from ..miners.base_miner import BaseTupleMiner
class MultiSimilarityMiner(BaseTupleMiner):
def __init__(self, epsilon=0.1, **kwargs):
super().__init__(**kwargs... |
69d39a847ba0be30234087d6e9c350a2a28f494f9237f002b67f98777391e566 | Python | 2,333 | 69 | import bpy
import os
import sys
import argparse
## Example call from commandline: blender -b -P decimate_mesh_blender.py -- -f mesh.obj -o mesh_dec.obj -r 0.5 -i 2 -n 4 -l 0.5
## Blender will ignore all options after -- so parameters can be passed to python script.
# get the args passed to blender after "--", all of ... |
792a09952a47201f4591e86097fc431728f37ac60351d66ce045b881f75f5245 | Python | 2,333 | 79 | """Analyze Errors based on TIDE.
Examples:
python tools/analysis_tools/analyze_tide.py \
${ANNOTATIONS FILE} \
${RESULT JSON FILE} \
--out ${OUT PATH}
"""
import argparse
import os.path as osp
from lqit.detection.evaluation.tide import COCO, TIDE, COCOResult
def parse_args():
parser = argparse.A... |
0081afc1fedc77d380fc10ad84ae70d9638b34c5f471036a30d5eda200672ac6 | Python | 2,334 | 73 | # built-in dependencies
import json
import os
import subprocess
import sys
# 3rd party dependencies
import pytest
# project dependencies
from deepface.commons import backend_utils
from deepface.commons.logger import Logger
logger = Logger()
# top level modules each backend engine brings in
FRAMEWORK_MODULES = {
... |
e5c7002418e5029b3b7fa087bc1efde20701926b9fa1754147f316711fa3564a | Python | 2,334 | 70 | import pytest
import torch.nn as nn
import sinabs
import sinabs.layers as sl
def test_layer_replacement_sequential():
model = nn.Sequential(
nn.Conv2d(2, 8, 3),
sl.IAF(spike_threshold=2.0),
nn.Conv2d(8, 16, 3),
sl.IAF(spike_threshold=1.0),
nn.Flatten(),
nn.Linear(5... |
5d7f128a0231702f6537b80236964278fd7418df874e572bfcffb1be8bc099d4 | Python | 2,335 | 64 | import os
import numpy as np
from pcntoolkit.util.utils import calibration_descriptives
#from pcntoolkit.dataio.fileio import load_nifti, save_nifti
from pcntoolkit.dataio.fileio import load as ptkload
from pcntoolkit.dataio.fileio import save as ptksave
root_dir = '/project_cephfs/3022017.02/projects/hansav/Run8_fs/'... |
d27cbe90068da2ad8d618f978a974c8a3f5ffa4ca32fcc8571b6711924e128d7 | Python | 2,335 | 71 | ####################################################################################################
# Copyright (c) 2016 - 2024, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis>
#
# This program is fre... |
6310efc73460c4b6db3b0bf8efc429f8b6292ea633c80eafb7c42a15271642b0 | Python | 2,336 | 63 | import os
import numpy as np
from pcntoolkit.util.utils import calibration_descriptives
#from pcntoolkit.dataio.fileio import load_nifti, save_nifti
from pcntoolkit.dataio.fileio import load as ptkload
from pcntoolkit.dataio.fileio import save as ptksave
root_dir = '/project_cephfs/3022017.02/projects/hansav/Run8_fs/'... |
bb4922a67dea1c2d479c42d827939e0d606e8586ebfd511a89ad2b9b4f18a60d | Python | 2,336 | 59 | import numpy as np
import pandas as pd
def make_rc(pssm_path,name_path,df_path):
"""
This function converts input motifs for reverse complement.
Input: pssm, name and df path
Compute and write rc files to the same folder as input
Output: pssm, name and df path that are reverse complement included
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.