sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
ba713eaca72b0dcd682ea2648c50cc0654783bc15a9973c26105d1f0b3a2517d | Python | 2,709 | 79 | #######
# This code was written by Nino Verwei and Niek van Hilten at Leiden University, The Netherlands (23 August 2022)
#
# Input:
# -s: sequence file with a column of peptide sequences (length 7-24, one letter AA abbreviations)
# -m: trained CNN model (.h5 file)
#
# Output:
# prediction.txt file with s... |
d89562697864834e40f0fcc6a3b4030ea7dd0b4f36b388c095edeb01eba0e7f8 | Python | 2,709 | 78 | import sys
import torch
from torch_geometric.datasets import TUDataset
from graphxai.explainers import GNNExplainer
#from graphxai.explainers.utils.visualizations import visualize_mol_explanation
from graphxai.gnn_models.graph_classification import train, test
from graphxai.gnn_models.graph_classification.gcn import G... |
51f49ee347c0d814bcba2d299e6e253c5dd6e59ad746b962dfeae5abfa4f32b0 | Python | 2,710 | 87 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import unetsl, unetsl.data, unetsl.model, unetsl.predict
import numpy
import skimage
import scipy.ndimage.filters as filters
point_kernel = numpy.array(
[
[ 1, 1, 1],
[ 1, 10... |
44076ab58fcf9a9ac5f7f3e637f91c4759eb2f63dc9a49c659e22068e567ed15 | Python | 2,711 | 86 | # Copyright 2019 The TensorFlow Authors, Pavel Yakubovskiy. 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 ... |
7048842a707b48236fba8a13d77cc136e4aa5c7229c19d792d2ffcf2e576481e | Python | 2,711 | 75 | from pyprep.find_noisy_channels import NoisyChannels
import mne
def bad_channel_disagrees(channel_name: str, bad_channels_dict: dict):
"""Checks if given channel_name is contained in all bad-channel sources (except ones that marked no bad channels) in bad_channels_dict.
Args:
channel_name (str): Nam... |
b4949107d4fdab6ef0ad646e563a6ae12723d4409a89f46d2dbf6a7529fa35c8 | Python | 2,711 | 126 | import math
import pickle
import torch
from torch import distributed as dist
from torch.utils.data.sampler import Sampler
def get_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank()
def synchronize():
if not dist.is_available(... |
ed1d8734d9790f9cef73ba9fd3fbedc393f2bd42a23a4d1c0117a3d1389350d4 | Python | 2,711 | 75 | import torch
from ..builder import BBOX_SAMPLERS
from .base_sampler import BaseSampler
@BBOX_SAMPLERS.register_module()
class RandomSampler(BaseSampler):
"""Random sampler.
Args:
num (int): Number of samples
pos_fraction (float): Fraction of positive samples
neg_pos_up (int, optional... |
678d610db5d821b50481238990ffdd91634c88c90ba13d88bedca2f21ee7814d | Python | 2,712 | 59 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
881de6d69303f1cde8ebdfcd9ff35da634c804eb18ce73951f41f78c16e3ccd8 | Python | 2,712 | 81 | from PyQt5 import QtWidgets
from h5xplorer.menu_tools import *
from h5xplorer.menu_plot import *
def context_menu(self, treeview, position):
"""Generate a right-click menu for the items"""
all_item = get_current_item(self, treeview, single=False)
if len(all_item) == 1:
item = all_item[0]
... |
40e13d16e73c48e5c402d281670d704534ac82f76917dc3ca25dc3128272d3df | Python | 2,714 | 78 | import sys
import torch
from torch_geometric.datasets import TUDataset
from graphxai.explainers import PGMExplainer
#from graphxai.explainers.utils.visualizations import visualize_mol_explanation
from graphxai.gnn_models.graph_classification import train, test
from graphxai.gnn_models.graph_classification.gcn import G... |
599c245ad11a6379b8052ba8e25aa99ce5ea7abe39c324f20e58ec3e6664dcd0 | Python | 2,714 | 64 |
# loop through all subdirs to find all fastq files
import os.path
import re
import argparse
parser = argparse.ArgumentParser(description='Make Molgenis Compute samplesheet for MSBB.')
parser.add_argument('samplesheet', help='MSBB samplesheet from synapse')
parser.add_argument('bam_dir', help='path to bam file dir fo... |
748988264af902c8fe65e7a0c01fdd4a511ef35963f60e16e977b0b070c7de17 | Python | 2,714 | 80 | #!/usr/bin/env python
import sys, argparse, re, os, random, glob
import pandas as pd
from pathlib import Path
import wave
import contextlib
seed=1234
def get_args():
parser = argparse.ArgumentParser(description="", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--dataset_dir", he... |
76b7f0343e29549ce8576dcda1d47f76f06f3fe1bfbcc465ba8e8517bbffc534 | Python | 2,715 | 74 | #%%
import os
try:
os.chdir('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/')
print(os.getcwd())
except:
pass
#%%
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import connectome_tools.process_matrix as promat
import pymaid
from pymaid_creds import... |
211c5f81b52ffebe69347726b6147d364513571d8d1a1f4eca3317eea265f5f0 | Python | 2,716 | 74 | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
49f48402414cf69e6b4945980adfaab7ce898e303a7b8750a005d1ab72b881fc | Python | 2,718 | 68 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
class BalancedPositiveNegativeSampler(object):
"""
This class samples batches, ensuring that they contain a fixed proportion of positives
"""
def __init__(self, batch_size_per_image, positive_fraction):
"""
... |
bfa01762aa383f927e448953f8cec1d8a5b867e31d1cdc0191290dfa01019613 | Python | 2,718 | 56 | import torch
import torch.nn as nn
import torchvision.models as models
from torch.nn.utils.rnn import pack_padded_sequence
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
"""Load the pretrained ResNet-152 and replace top fc layer."""
super(EncoderCNN, self).__init__()
resnet =... |
4c5278a5040224fa13fa6e9e3d4db229dc19cb49106b17fb4eb4c95b930f0afa | Python | 2,720 | 90 | """
PARAMETERS: Documentation
This module specifies all the parameters necessary for a neuronal papopulation made up of:
- Excitatory cells
- Inhibitory cells
"""
from brian2 import *
cm_fig_conv = 1/2.54
rc('font', size=6)
###########################################
# User defined parameters
###################... |
577dbd697ffea10bb839be43b39ddf6ef04c10abd53eef4967a30f98497a2aa1 | Python | 2,720 | 71 |
"""
Created on Wed Mar 28 10:12:13 2018
@author: Utku Ozbulak - github.com/utkuozbulak
"""
import numpy as np
from torch.autograd import Variable
import torch
from misc_functions import (get_example_params,
convert_to_grayscale,
save_gradient_images)
from v... |
7d574d9399081c9c04f796e3f50db296d2792c49ab04de494a26d7e6bba658f6 | Python | 2,720 | 61 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... |
aeb18c0d85cf3b63b8b024c251fd5ae75ee8c8e5654c52304b3e6f22fb985fde | Python | 2,720 | 69 | # Copyright (c) Open-MMLab. All rights reserved.
import torch
import torch.distributed as dist
import torch.nn as nn
from torch._utils import (_flatten_dense_tensors, _take_tensors,
_unflatten_dense_tensors)
from mmcv.utils import TORCH_VERSION
from .registry import MODULE_WRAPPERS
from .scat... |
c4b5b12cfa8d15c346e80056e0440a77049fb5cad2ebf203e77acb081412e5a4 | Python | 2,720 | 114 | import pytest
import tensorflow as tf
from typing import List
from multi_phase.networks.components.generator import Generator
#-------------------------------------------------------------------------
@pytest.mark.parametrize(
"depth,img_dims",
[
(5, [2, 16, 16, 8, 1]),
(6, [4, 32, 32, 16, 1... |
ce727d8110beecbac0e4d8235e9c3782100418847e9f32284004ecf2ebe04aa6 | Python | 2,720 | 70 | #!/usr/bin/env python3
# Copyright 2020 Audio, Speech and Language Processing Group (ASLP@NPU), Northwestern Polytechnical University (Authors: Zhuoyuan Yao, Xiong Wang, Jingyong Hou, Lei Xie)
# 2020 AIShell-Foundation (Author: Bengu WU)
# 2020 Beijing Shell Shell Tech. Co. Ltd. (Author: Hui BU)
#... |
ce7f03312e40354ea5066488252884d55210cc35b8f254327dc09aecf86682d1 | Python | 2,720 | 95 | import os
import re
import torch
import torch.nn as nn
class CrossEntropyLabelSmooth(nn.Module):
def __init__(self, num_classes, epsilon):
super(CrossEntropyLabelSmooth, self).__init__()
self.num_classes = num_classes
self.epsilon = epsilon
self.logsoftmax = nn.LogSoftmax(dim=1)
... |
ebaaa1c4c1e80abd9ea87edfcb26b24c1c2407440e17a1e6aceda2e8ba6de71c | Python | 2,721 | 74 | #!/usr/bin/env python3
"""
File: custom_interaction_analyser.py
Created: 2020/03/23
Last Changed: 2020/06/08
Author: M.Vochteloo
Copyright (C) 2020 M.Vochteloo
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
... |
4f61ce8429acfa2b50d72a9556dc33501754af6153325f1078eac5f4bbbde01f | Python | 2,722 | 86 | '''
Analysis of responses to current pulses.
'''
from __future__ import print_function
from pylab import *
from clampy import *
from clampy.setup.units import *
from clampy.analysis.spike_analysis import lowpass
from clampy.data_management import print_and_log
__all__ = ['do_analysis']
def do_analysis(path, filtering... |
6afcffc266ddd0b055363a80497a293117428c7f8f876889d49c27cb0650b9dd | Python | 2,722 | 63 | #! /usr/bin/env python
# Copyright 2019 Ashish Arora
# Apache 2.0.
"""This script splits a kaldi (text) file
into per_array per_session per_speaker hypothesis (text) files"""
import argparse
def get_args():
parser = argparse.ArgumentParser(
description="""This script splits a kaldi text file
... |
d7ad7eee13fe4bd2654d22f74d66dc5191264112d654f9850ff8fe8c57f050e1 | Python | 2,722 | 91 | '''Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
- msr_init: net parameter initialization.
- progress_bar: progress bar mimic xlua.progress.
'''
import errno
import os
import torch
import torch.nn as nn
import torch.nn.init as init
__all__ =... |
78363d1ab6834e0d56d127bbfccdf6082df5e5bcdb0d1dd6c5cf298cc077979f | Python | 2,723 | 73 | import os
import numpy as np
from IPython.core.debugger import set_trace
from default_config.masif_opts import masif_opts
import sys
# This code computes Geometric Invariant Fingerprint descriptors for full proteins as originally proposed in:
# S. Yin, et al. PNAS September 29, 2009 106 (39) 16622-16626
# Implemented ... |
7cc41dde3a9c26937cb62004d5e600018ce0b3410cc21954dbdfbc76253a358a | Python | 2,723 | 82 | import os
import torch
from M2TR.datasets.dataset import DeepFakeDataset
from M2TR.datasets.utils import (
get_image_from_path,
get_mask_path_from_img_path,
)
from M2TR.utils.registries import DATASET_REGISTRY
'''
DATASET:
DATASET_NAME: ForgeryNet
ROOT_DIR: /some_where/ForgeryNet
IMG_SIZE: 380
SCALE_... |
5adc5ea51e6c120e0c1e84396534dfad570634dac644bdfff0720d6b3467f0ad | Python | 2,725 | 87 | #%%
import pandas as pd
import numpy as np
from pymaid_creds import url, name, password, token
import pymaid
rm = pymaid.CatmaidInstance(url, token, name, password)
def identify_open_ends(neuron):
end_nodes = neuron.nodes[neuron.nodes.type=='end'].node_id.to_list()
end_tags = neuron.tags['ends']
tags =... |
a5bdb04ebbbf4b280691622e304cbe85fce804f7d5937284866b63688f85e06c | Python | 2,725 | 69 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
uint8 = torch.bool
class BalancedPositiveNegativeSampler(object):
"""
This class samples batches, ensuring that they contain a fixed proportion of positives
"""
def __init__(self, batch_size_per_image, positive_fract... |
c4d88a643f2844f1c7cbe381f77aac275d8460fc4c750594c61cd3dddc4a5d6f | Python | 2,726 | 90 | from __future__ import annotations
import logging
import os
from typing import TYPE_CHECKING, Iterable, List
from abc import ABC, abstractmethod
from tqdm import tqdm
if TYPE_CHECKING:
from palmari import Experiment, TifPipeline, Acquisition
from .post_processing_params import PostProcessingParameters
class... |
f9a89e0103562cacd95f76ce8bed5b681bfe8a00a9e66a97bb3dfdfb78f0c6ae | Python | 2,726 | 84 | import pickle
from glob import glob
from pathlib import Path
import numpy as np
import pandas as pd
from scipy.io import loadmat
def allen_dataset(datapath):
loaded_spikes = pickle.load(open(datapath, 'rb'))
multiplier = 1e8
spikes = {'groups': [], 'series': []}
for experiment in loaded_spikes:
... |
19bc65cbe0192a2012d43a868abec0fb0977dc86caf460779e84374afc3192c0 | Python | 2,727 | 89 | # Modified from https://github.com/hszhao/semseg/blob/master/lib/psa
from torch import nn
from torch.autograd import Function
from torch.nn.modules.utils import _pair
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext',
['psamask_forward', 'psamask_backward'])
cla... |
4e57c5177fddb258e6126f8d5a4aa8fddb2163d456ea27e4c94f2dba27c3e25c | Python | 2,728 | 83 | from Classes.RelationshipMap import RelationshipMap
from Classes.SearchComponent import SearchComponent
class Recommender(SearchComponent):
def RunAnaloguesQuery(self, relationships):
# Find neurons that have the same relationship to the object
unions = self.ConstructRelationshipQueryUnions(rela... |
92289c95188d6132767612f4c0ac3379bbf3070c12dac44ded64f668bb21f0b3 | Python | 2,729 | 90 | import argparse
import pandas as pd
import os
import numpy as np
import matplotlib.pyplot as plt
import functools
from collections import Counter
import math
import random
import sklearn
from sklearn.metrics import confusion_matrix
def relative_max_mu(mu):
return max(abs(mu[0]), abs(mu[1])) / (abs(mu[0]) + abs(mu[... |
b167a939a3063c52bc85f5023c84db765317e2f1ac25246a96ba270caef439b2 | Python | 2,729 | 112 | """Definitions for mocking the result of Query("SaliDBIstunto").get_full_table()."""
from typing import List
from typing import Optional
from typing import Tuple
import pytest
@pytest.fixture(scope="module")
def query_get_full_table() -> Tuple[List[List[Optional[str]]], List[str]]:
"""Return values for get_full_... |
d742ef8e92f586ae497e9568d8b634ed5ffd9288e618d0c8262eac7584d0c1f2 | Python | 2,729 | 106 | import torch
from sklearn.model_selection import train_test_split
from torch_geometric.datasets import TUDataset
from graphxai.datasets.dataset import GraphDataset
from graphxai.utils import Explanation, match_edge_presence
from graphxai.datasets.utils.substruct_chem_match import match_NH2, match_substruct, MUTAG_NO... |
d0f0f01a52eac8bf62c61fd6dda592139e3c31e52e2c0016e6ee48027aa38705 | Python | 2,730 | 68 | ####################################################################################################
# Copyright (c) 2019 - 2023, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of VessMorphoVis <https://github.com/BlueBrain/VessMorphoVis>
#
# This program is free ... |
3ba4e9d825d66e389763e83681f665a08f89766b768a2a71814b124ea7bd5dd5 | Python | 2,731 | 88 | import argparse
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Tuple, List
from numpy.random import seed
from spotipy.model import SpotNet, Config
from tensorflow.random import set_seed
from cenfind.core.data import Dataset, Field
from cenfind.core.loading import ... |
41d3c349f919780d82d5a122d8fc3543e111ffba07588d30e7e20f0adf17baa7 | Python | 2,731 | 63 | import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir) # PYTHON > 3.3 does not allow relative referencing
PYCHARM_EXEC = os.getenv('PYCHARM_EXEC') == 'True'
import numpy as np
import tensorflow as tf
import voxelmorph as vxm
import n... |
bd5238330b059382c7c7338fa7c8961e38bfa3be3fab0de60025fdc762435b36 | Python | 2,732 | 82 | """
From https://github.com/wanghao14/Stain_Normalization
Stain normalization based on the method of:
M. Macenko et al., ‘A method for normalizing histology slides for quantitative analysis’, in 2009 IEEE International Symposium on Biomedical Imaging: From Nano to Macro, 2009, pp. 1107–1110.
Uses the spams package:
... |
6e5a76a2c7f12a95b2348ff1eb171e8f558b3b9caa739556ada4844c427ac5b4 | Python | 2,733 | 89 | """
Utilities for writing out obo graphs
"""
import logging
from typing import Optional, TextIO, Union
from linkml_runtime.dumpers import json_dumper, yaml_dumper
from oaklib import OntologyResource
from oaklib.converters.obo_graph_to_cx_converter import OboGraphToCXConverter
from oaklib.converters.obo_graph_to_rdf... |
81d0cb9c2143af16ff0497dc6f230ce0d8048d1978a0551fd55f6afcf40f9069 | Python | 2,733 | 59 | #!/usr/bin/env python
# Copyright 2017 Yiwen Shao
# Apache 2.0
import sys
import struct
""" Provide an function to write bmp image to stdout with the input two dimensional
list.
usage: bmp_encoder(data, width, height)
For instance:
data = [[0, 255, 0, 0, 0, 255], [255, 0, 0, 0, 255, 255]]
bmp_enco... |
894d324201ded0db79106cebc40e77592c29259cc6112f6b48461284fa42d767 | Python | 2,733 | 80 | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
98d60cf1156fd2145b070b21a7b0d57e10dab4fe40ec3c6e5088ca4442ecc159 | Python | 2,733 | 85 | """Test video query helper functions."""
from typing import Dict
import pytest
import fi_parliament_tools.video_query as vq
@pytest.mark.parametrize(
"date, name, true_query",
[
("1999-12-31", "startDate", "startDate=1999-12-31&"),
("2013-08-08", "endDate", "endDate=2013-08-08&"),
("... |
0adecd7b5394f9e55888e50f02e5fcbe9e1399eef018ab1b30ca95aecade6079 | Python | 2,734 | 61 | # %%
# generate cascades from each sensory modality
from data_settings import data_date, pairs_path
from pymaid_creds import url, name, password, token
import pymaid
rm = pymaid.CatmaidInstance(url, token, name, password)
import numpy as np
import pandas as pd
import pickle
from contools import Promat, Adjacency_mat... |
f8a6cf87577576189b93396209ca889ae36332a29255e4034e54ee2ef29d33cd | Python | 2,735 | 68 | # -*- coding: utf-8 -*-
"""Preview
Code for 'Inf-Net: Automatic COVID-19 Lung Infection Segmentation from CT Scans'
submit to Transactions on Medical Imaging, 2020.
First Version: Created on 2020-05-13 (@author: Ge-Peng Ji)
"""
import os
import numpy as np
from Code.utils.dataloader_MulClsLungInf_UNet import LungDat... |
0f4cd30f865b5e7b0dc91c2b79cb4b9516f96ab4cdec3a7b71e72335a07f5cb0 | Python | 2,736 | 120 | """
Code to manage colors (mostly these functions are obsolete, but kept for the moment while we check)
"""
######################################
# Color Dictionaries - need to find a way to bring these together and remove redundancy
f_colors = {'F1311':'#c297d3', 'F1509':'#7671b6', 'F1706':'#0e6b96'}
f_markers = {... |
518e96f900afdd80cf60db602e8959fa20ea91a813f23ba8199e60afd1e114ea | Python | 2,736 | 79 | import argparse, datetime, os, time, sys
import torch
sys.path.append("..")
from model.unet import rsppUnet
from eval_loader import get_dataset
from eval_utils import generate_segmentations, seed_torch
parser = argparse.ArgumentParser(description="Brats Evaluation")
parser.add_argument("--batch_size", default=1, hel... |
5dd2021b4ee7e2fcb84e65844dea73a78cfbd49569294e9a7b20ef13c59737d6 | Python | 2,736 | 76 | import torch
class DemoExplainer:
def __init__(self, model, criterion, *_):
"""
Args:
model (torch.nn.Module): model on which to make predictions
criterion (torch.nn.Module): loss function
"""
self.model = model
self.criterion = criterion
self... |
66800db4d3446cc6ab18e0ef2731be24155ae3bd5debf5069b4f952434a9e378 | Python | 2,736 | 101 | import torch
class LogEntry(object):
def __init__(self, init_losses=[], init_metrics=[]):
assert isinstance(init_losses, list)
self._losses = {}
for key in init_losses:
self._losses[key] = 0
assert isinstance(init_metrics, list)
self._metrics = {}
for ... |
89833037d5474bf07892b24e3f9f469711079d99c89957fba4b9678b10f4af16 | Python | 2,736 | 82 | from numba import jit
from rl_analysis.photometry.decoding.models import exp_smoother
from copy import deepcopy
import numpy as np
import pandas as pd
@jit
def stable_softmax(p, temperature=100.0):
use_p = p.copy()
use_p -= np.nanmax(use_p)
use_p = np.exp(use_p / temperature)
return use_p / np.nansum(... |
b13a6b07d399eefc46e43ecce069f3879c3c121f01d0d9afa8125daefbca379f | Python | 2,736 | 85 | import os
import numpy as np
import sympy as sp
import pandas as pd
import argparse
from experiments import run_experiment
import roboscientist.equation.equation as rs_equation
import roboscientist.equation.operators as rs_operators
from equation_test import EQUATIONS
def get_offsprings(list_of_tokens, idx):
if ... |
f96d94f7eede15dd8f6ba858395cc028e4fc8b932bed679d3819a0c452559eda | Python | 2,736 | 75 | # Copyright (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""Smoke test for the Traffic Manager mutex removal.
After the refactor, synchronous mode no longer... |
351cad95cd3e8adcb8c15e9e865388c7499cf469ce50ccbb71d526c2ab340590 | Python | 2,738 | 66 | import numpy as np
import h5py
import multi_slice_viewer as msv
import scipy.ndimage as ndimage
import matplotlib.pyplot as plt
if __name__ == "__main__":
quicksave = False
if quicksave:
upsample_rate = 4
filepath = r'C:\Users\longd\OneDrive - The University of Auckland\Documents\2021\ENG... |
52eb3fd2e13996d8cad5a9b08ba9760fc3a606cfbfbd7f444e80ca3fe049d101 | Python | 2,738 | 73 | import random
import torch
import matplotlib.pyplot as plt
from graphxai.explainers import GNNExplainer
from graphxai.gnn_models.node_classification.testing import GCN_3layer_basic, GIN_3layer_basic, test, train
from graphxai.datasets.shape_graph import ShapeGGen
from graphxai.utils import aggregate_explanations
# L... |
6af6e331304a54acc04bd6610956502feb5596d4095bd78dc5f5a10df87e1816 | Python | 2,738 | 76 | #!/usr/bin/env python
# Copyright (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
import argparse
import carla
import time
def get_transform(transform_data):
... |
710c3a037d8e06228d5ee26a487c35733ca2cb7ec79ddc7f3f9450492489ee9a | Python | 2,738 | 67 | import numpy as np
from skimage.transform import EuclideanTransform
from scipy.optimize import least_squares
class CustomPolyTransform(EuclideanTransform):
def __init__(self, matrix=None, order=5, loss_fn=None, outlier_threshold=1.0):
if order is not None and matrix is not None:
raise ValueErr... |
f88c8e6a96f7e2b93836c26e0dbf22575be89aa10daecc2572019c2a98805f77 | Python | 2,738 | 92 | from dataclasses import dataclass
from typing import Optional
from oaklib.implementations.sparql.abstract_sparql_implementation import (
AbstractSparqlImplementation,
)
from oaklib.interfaces.mapping_provider_interface import MappingProviderInterface
from oaklib.interfaces.obograph_interface import OboGraphInterfa... |
55c87efdfbcac12676001e958cb6dd72b690b18402576f44a70919e358843387 | Python | 2,739 | 75 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... |
dd125fe361152c801fc60768f2402006e3b8783c4eaccd65897594690fc6dbd3 | Python | 2,739 | 86 | import torch
import torch.nn as nn
from nets.CSPdarknet53_tiny import darknet53_tiny
from nets.attention import cbam_block, eca_block, se_block
attention_block = [se_block, cbam_block, eca_block]
class BasicConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1):
super(Basi... |
e4f59a6b0894c5e4031594dd6dc6a16083a1c95373f2fefd8a8db48538e2e951 | Python | 2,739 | 80 | # Copyright (c) Open-MMLab. All rights reserved.
import numbers
from ...dist_utils import master_only
from ..hook import HOOKS
from .base import LoggerHook
@HOOKS.register_module()
class MlflowLoggerHook(LoggerHook):
def __init__(self,
exp_name=None,
tags=None,
... |
2c7fa2e445586c010741969521f492baeef185b4f693ad09d331196f4299d7d5 | Python | 2,740 | 72 | import os
import sys
import json
import math
from rulenn.rule_nn import RuleNNModel
from base import _load_data
import torch
import tqdm
import numpy as np
def sigmoid(x):
return 1 / (1 + math.exp(-x))
def logit(mu0):
mu = mu0*0.999+0.0001
return math.log(mu/(1-mu))
def consolidate(path):
rulessets = ... |
454c7b6c1f5e6cf1c80b1c7ec4bb71205c796234d088b505633e8d9e4c9f106a | Python | 2,740 | 82 | '''
Calculation of translational and rotational velocities from the direction of power strokes,
using the mobility matrix of a sphere.
See Lauga and Powers (2009).
These velocities are essentially proportional to forces and torques, so that's what we calculate.
We use spherical coordinates (theta, phi).
The angle of ... |
0d0ab71cb5c61bae29679fc8684e1f15d8b7e28d7b8d6221bcfe76fbeebd7c72 | Python | 2,741 | 62 | """Phase 3b regression tests: pin down compartment-discovery numbers.
These run on DANs only (14 cells: DAN-c1, d1, f1, g1, i1, j1, k1 x 2 hemispheres),
which is the biologically faithful set per Eichler 2017 — OANs and other MBINs
have promiscuous KC contacts and contaminate compartment recovery.
"""
import numpy as... |
1d1664c5a058104beeed9cc21ceceb072a4ba4bf353e623c07c9b7200d373a7b | Python | 2,741 | 83 | #%%
import os
try:
os.chdir('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/')
print(os.getcwd())
except:
pass
#%%
import sys
sys.path.append("/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/")
import networkx as nx
from networkx.utils import pairwise
import pandas as pd
import n... |
d564b8b593134fefc273620729ebf52755a7323c5f05340637b5755d2a5aa349 | Python | 2,741 | 93 | #!/usr/bin/env python
# Author : Gaurav Kumar (Johns Hopkins University)
# Gets a report on what the best word error rate was and which iteration
# led to it. This is needed both for reporting purposes and for setting
# the acoustic scale weight which extracting lattices.
# This script is specific to my partitions an... |
0f84894cfcaec2ffb89ebbda13e5e2739b8a87df7c5ab903fc88e3f5b788213b | Python | 2,742 | 118 | """Train an HMM.
"""
#%% Run ID and output directory
import os
from sys import argv
# We get the run ID from the command line arguments
if len(argv) != 2:
print("Please pass a run id, e.g. python 2_train_hmm.py 1")
exit()
id = int(argv[1])
# Create directory for results
results_dir = f"results/run{id:02d}"... |
1992030328fc801c86db51c010401b1b984cf0b4890c067bcf9b94ded66f6f83 | Python | 2,744 | 97 | import time
from ..uno import UNO
import torch
import pytest
@pytest.mark.parametrize(
"input_shape", [(2, 3, 64, 55), (2, 3, 100, 105), (2, 3, 133, 95)]
)
def test_UNO(input_shape):
horizontal_skips_map = {4: 0, 3: 1}
model = UNO(
3,
3,
5,
uno_out_channels=[32, 64, 64, 64,... |
6de0a368d04072be01058c5e73843cba291e4c915fea524f074b4ee8d0cf4140 | Python | 2,744 | 50 | # flake8: noqa
# Copyright (c) Open-MMLab. All rights reserved.
from .config import Config, ConfigDict, DictAction
from .misc import (check_prerequisites, concat_list, deprecated_api_warning,
is_list_of, is_seq_of, is_str, is_tuple_of, iter_cast,
list_cast, requires_executable, req... |
ec11d45c217352d8c232289da7e380e76084d27e53796fbd1f35a0e45524bca3 | Python | 2,744 | 92 | """
PARAMETERS: Documentation
This module specifies all the parameters necessary for a neuronal papopulation made up of:
- Excitatory cells
- Inhibitory cells
"""
from brian2 import *
from ExternalFunctions import max_conn_scale_free
###########################################
# User defined parameters
#########... |
10c1678f29ef6a90c63e3ffd77df2046b674ffd7f6d8cad3decb919219c5c01b | Python | 2,745 | 97 | import torch
import apex
import os
from IPython import embed
from torch import nn
import torch.nn.functional as F
import argparse
import numpy as np
import torch.distributed as dist
from syncbn import DistributedSyncBN
from test_case import TestCase
def main():
parser = argparse.ArgumentParser(description="PyTorc... |
b20a6a26eed3d77cfc8a44b400e2eb4bf8c2ada44e6898e0abbb01cf7fc75e85 | Python | 2,745 | 61 | import re
import torch
import logging
from tools.utils import load_checkpoint
def remap_for_archadapt(load_path, model_dict, seed_num_layers=[]):
seed_dict = load_checkpoint(load_path, map_location='cpu')
logging.info('Remapping for architecture adaptation starts!')
# remapping on the depth level
dep... |
e2ef224524661224718de76f7a9a6895993a7edcb18406415d6bb50c6ac27f06 | Python | 2,746 | 72 | ####################################################################################################
# Copyright (c) 2018 - 2020, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of VessMorphoVis <https://github.com/BlueBrain/VessMorphoVis>
#
# This program is free ... |
940a4f87f6e5d2808a371c9f2b19b736bedac3eb953179ce4bb87ae64f17f8a7 | Python | 2,747 | 80 | import sys
import os
W1_ROW = 8# 5
W0_ROW = 9# 6
def main():
path = sys.argv[1]
is_csv = True if path.endswith('.csv') else False
time_column = sys.argv[2]
file_name = '.'.join(path.split('/')[-1].split('.')[:-1])
print(file_name)
generate_gnuplot(path, time_column, is_csv)
def generate_gnup... |
1d92468f5e922668f5dd6ee60ee3eeaf0e2e38fb63032ceeaf5d2aafc3f1cb6e | Python | 2,749 | 83 | """
This script uses the recount metadata and a sparsity threshold to remove
sc-RNAseq data from the recount compendium
"""
import argparse
import pandas as pd
import tqdm
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('count_file', help='The file containing the count matri... |
dd3822768e20d8abc522a7c6e74c440ed43ee63ff9d8e790380694dbaaa92197 | Python | 2,749 | 80 | import numpy as np
from matplotlib import pyplot as plt
# ----------------------------------------------------------------------
def agco(method_1, method_2, ticks, labels, sort='method_1', reference_c='C1', gain_c='C0', loss_c='C3', barwidth=6, ylabel='Accuracy [%]', xlabel='Subjects', gain_labels=['gain', 'loss'], ... |
0ebcfb538577ab07993364cf36e765ea97529565b78da436a8bff873d95f498f | Python | 2,750 | 77 | import sys
import torch
from torch_geometric.datasets import TUDataset
from graphxai.explainers import IntegratedGradExplainer
#from graphxai.explainers.utils.visualizations import visualize_mol_explanation
from graphxai.gnn_models.graph_classification import train, test
from graphxai.gnn_models.graph_classification.g... |
7bc48e218b7edee46c5e90deb045f7495d382065e4ae10e0b2c99887042722f1 | Python | 2,750 | 103 | from collections import defaultdict
import MySQLdb
from Classes.SearchResults import SearchResults
import database
class RubyInterfacer():
def FormatForRuby(self, pythonResult):
result = defaultdict(list)
# Get NeuroML model IDs from mysql db
rows = self.GetNeuroMLids(pythonResult)
... |
5a425df7301e7d624df735ead1305e805242369bb47a1a44a966dd18e18644ef | Python | 2,752 | 72 | import random, time
import torch
import matplotlib.pyplot as plt
from graphxai.explainers import SubgraphX
from graphxai.gnn_models.node_classification.testing import GCN_3layer_basic, test, train
from graphxai.datasets.shape_graph import ShapeGGen
from graphxai.utils import aggregate_explanations
# Load dataset:
# ... |
6af532f3cff813a754f31a05532abe75d2d67d3bb1cb67d3825941fbfbd82ac0 | Python | 2,753 | 84 | import jax
jax.config.update('jax_platform_name', 'cpu')
import matplotlib as mpl;mpl.use('Agg')
from matplotlib import rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Liberation Sans']
from matplotlib import pyplot as plt
import corticostriatal as cs
import numpy as np
import time
impor... |
0d26e65a1063a905e75748a88b73eb343762ac5d1e375906e941e3c488f3cc20 | Python | 2,754 | 92 | import re
import matplotlib
import pandas as pd
from matplotlib import pyplot as plt
from cenfind.constants import datasets, pattern_dataset, protein_names, celltype_names
font = {'size': 6}
matplotlib.rc('font', **font)
matplotlib.use("Agg")
def extract_info(pattern: re, dataset_name: str):
res = re.match(patt... |
e60934f63a5725d68231ebaebb1be46e34ada8c75f2cac812768c295a7356f02 | Python | 2,754 | 85 | #!/usr/bin/env python3
import glob
import itertools
import os
import pytz
import click
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.signal as sg
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error
SRC_DATA_DIR =... |
05956ed0af0ea50f76e5e97726bca8ddfb03ecb4748e1c5efdde6df5b0348157 | Python | 2,755 | 92 | __author__ = "Jianfeng Sun"
__version__ = "v1.0"
__copyright__ = "Copyright 2023"
__license__ = "GPL v3.0"
__email__ = "jianfeng.sunmt@gmail.com"
__maintainer__ = "Jianfeng Sun"
from typing import List
from tmkit.chain.PDB import PDB as cpdb
class Coloring:
def __init__(
self,
pdb_fp: str,
... |
19cb78e39609906b0dd71476eb117151cffba9f2756ec2281c417007f579d9d6 | Python | 2,757 | 76 | from dataclasses import dataclass
from typing import Collection, Optional
from oaklib.datamodels.obograph import Graph
from oaklib.datamodels.vocabulary import IS_A
from oaklib.transformers.graph_transformer import GraphTransformer
from oaklib.types import PRED_CURIE
@dataclass
class EdgeFilterTransformer(GraphTrans... |
20708a58573f9596a694ca8780f894326c41efae2ad982e2c176754c9f6eb4fc | Python | 2,757 | 79 | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
17904d85d319dcc3c51625c058cd18136f3f0a244affe10952ff0881cf05ad27 | Python | 2,758 | 65 | import numpy as np
import argparse
import os
import time
from datetime import datetime
from keras.callbacks import TensorBoard, ModelCheckpoint
from keras.layers import ReLU
from keras.utils import plot_model
from utils import define_model, prepare_dataset
def train(iteration=3, DATASET='DRIVE', crop_size=32, need_au... |
3d1e000c2466ae01bef64d6941b2f68c04f2daa0d4ea32e83f9f3053b2aa7cd5 | Python | 2,758 | 123 | """
Code to deal with changes between metric, imperial and normalized units
"""
def inch2cm(inches):
"""
Designed for use with matplotlib
Parameters:
----------
cm : int, float or list/tuple of ints/floats
Values in cm that need converting
Returns:
--------
y : float ... |
639a64aa27f04e3e8885726b1ea5ca0f6f8e5afac34ab29cdb8ef1308aecbc29 | Python | 2,760 | 80 | import numpy as np
from matplotlib import pyplot as plt
# ----------------------------------------------------------------------
def accuracy_gain(method_1, method_2, ticks, labels, sort='method_1', reference_c='C1', gain_c='C0', loss_c='C3', barwidth=6, ylabel='Accuracy [%]', xlabel='Subjects', gain_labels=['gain', ... |
12d2cd074a4532eec58f3c57dc2b95c3f1d6b9525b6a6d351705423ae91184d0 | Python | 2,763 | 65 | import matplotlib.pyplot as plt
import numpy as np
from niftypad import basis
from niftypad.kt import dt2mft, dt_fill_gaps
from niftypad.models import get_model_inputs
from niftypad.tac import TAC, Ref
# dt
dt = np.array([[
0, 5, 10, 15, 20, 25, 30, 40, 50, 60, 120, 180, 240, 300, 450, 600, 900, 1200, 1800, 2400,... |
8c555f5260e01e5b96d3e5a2f486045ec26f9ac7ecda1ccc7e6ad77d11758e76 | Python | 2,765 | 71 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from .roi_box_feature_extractors import make_roi_box_feature_extractor
from .roi_box_predictors import make_roi_box_predictor
from .inference import make_roi_box_post_processor
from .loss import make_roi_box_loss_... |
92f185405e2584f4e41590c8419f82ceafb02a18fe20b7c016808ef46467b37e | Python | 2,765 | 73 | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
f849653dbd86fa2532a13190af97d534e8929a7e8225fa5b8e5df7850851091b | Python | 2,765 | 79 | import sys
import torch
from torch_geometric.datasets import TUDataset
from graphxai.explainers import IntegratedGradExplainer
#from graphxai.explainers.utils.visualizations import visualize_mol_explanation
from graphxai.gnn_models.graph_classification import train, test
from graphxai.gnn_models.graph_classification.g... |
1ac0535d9225b7e51263007fa19c256e2c2bb8c05d642405f9650b250cea8cd8 | Python | 2,766 | 88 | '''
Written by Nathan Neeteson.
Utilities for saving images, for debugging or for saving outputs.
'''
# Imports
import os
import numpy as np
import SimpleITK as sitk
import vtk
from datetime import datetime
from bonelab.util.vtk_util import numpy_to_vtkImageData
from bonelab.io.vtk_helpers import get_vtk_writer, h... |
6bc482cff08bee89a1da18cd68f18ea5333988d94cc77b82a231759f3df2ef8c | Python | 2,766 | 81 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... |
c974a5331acbf8ed475fe73c87796ca5d31bb44f0ee182d658ee728f6bcc9897 | Python | 2,766 | 72 | import json
import numpy as np
import zarr
def _correct_subpath(subpath):
return '' if subpath[-2:] == 's0' else subpath
def _get_atts(n5_path, subpath, correct_subpath=True):
if correct_subpath: atts_path = n5_path + _correct_subpath(subpath)
else: atts_path = n5_path + subpath
atts_path += '/attri... |
7ee599f0055253e7d757419d609138894d8cd3d90d0487734158c8b29273f173 | Python | 2,767 | 80 | import sys
import torch
from torch_geometric.datasets import TUDataset
from graphxai.explainers import IntegratedGradExplainer
#from graphxai.explainers.utils.visualizations import visualize_mol_explanation
from graphxai.gnn_models.graph_classification import train, test
from graphxai.gnn_models.graph_classification.g... |
bc368d3cb0621b6939b05cb4378a003c5a73fc23fc7a6135bdb14b83aa24262b | Python | 2,767 | 101 | import csv
import os
import sys
def feature_to_index(cases, column_nb, offset=0):
feature_set = set()
for case in cases:
if len(case) > column_nb:
feature_set.add(case[column_nb])
l = list(feature_set)
index = {}
i = 0
for f in l:
if f != '':
index[f] = i... |
09f26c74c9254dfe8263fa2c7b53b01b2c8bfd84ae77544df0151f17df09ba94 | Python | 2,769 | 89 | import pytest
import torch
from mmdet.models import Accuracy, build_loss
def test_ce_loss():
# use_mask and use_sigmoid cannot be true at the same time
with pytest.raises(AssertionError):
loss_cfg = dict(
type='CrossEntropyLoss',
use_mask=True,
use_sigmoid=True,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.