sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
ee16afa9b2fc8cb951287177eca7d721e93e1cf75ad2dc37467d7fdad7a05ca9 | Python | 1,677 | 50 | import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import torch
import gmm
def create_synthetic_data(num_gaussians, num_features, num_samples, means, vars):
assert len(means[0]) == len(vars[0]) == num_features
samples = []
for g in range(num_gaussians):
loc = torch.tensor(mea... |
967c53670a679b1a526e8ffa408137fdce398aa20a4b143d592e94f36b657442 | Python | 1,680 | 69 | import re
from GenomeCoordinate import GenomeCoord
class VCFCol:
names=['CHROM',
'POS',
'ID',
'REF',
'ALT',
'QUAL',
'FILTER',
'INFO',
'FORMAT',
'SAMPLE']
CHROM=0
POS=1
ID=2
REF=3
ALT=4
... |
9e8a93a3528c984fe0f3401f19a2aab7cdbe245e2f23cd2d8d709cf7d2ab2124 | Python | 1,682 | 60 | #!/usr/bin/env python
import gzip
import sys
def getmean(lst):
return sum(lst)/float(len(lst))
def getmedian(lst):
lst.sort()
n = len(lst)
if n < 1:
return None
if n % 2 == 1:
return lst[n//2]
else:
return sum(lst[n//2-1:n//2+1])/2.0
def get_feature(fname, feature = ... |
e2c06c8544d805f69a4224f0d1688dcb8c04f5cba8247325a7f969fde8cecae0 | Python | 1,684 | 47 | #!/usr/bin/env python3
from flystim.stim_server import launch_stim_server
from flystim.screen import Screen
from flystim.trajectory import Trajectory
import numpy as np
from time import sleep
def main():
manager = launch_stim_server(Screen(fullscreen=False, server_number=0, id=0, vsync=True))
# manager.load... |
80b43de11eb5ab929346b431ce9d3a552559f6636cc17d1f2d79e18b0d50f907 | Python | 1,685 | 51 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 18:56:50 2021
@author: fhu14
"""
#%% Imports, definitions
from MasterConstants import Model, RawData
from typing import List, Dict
import numpy as np
Array = np.ndarray
#%% Code behind
class Input_layer_DFTB_val:
def __init__(self, model: Model):
r""... |
2bd57940c5e41e6d37d5ddca9000ba9aa3a42b999d04e6335b4f12d25198fd03 | Python | 1,687 | 61 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 30 16:54:30 2021
@author: fhu14
This is a set of parameters used for the Lennard-Jones dispersion form,
translated from the paper "UFF, a Full Periodic Table Force Field for Molecular
Mechanics and Molecular Dynamics Simulations" by Rappe et. al.
We are interested in ... |
e21674be7e003bf08f8c2ae3d278580097a1b6ee030263039db1f35234c563b5 | Python | 1,688 | 46 | # This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/>
import os
import nbformat
import pytest
from nbclient.exceptions import CellExecutionError
from nbconvert.preprocessors import ExecutePreprocessor
TEST_... |
4496079c210b07f9f5eb599e5f3d9cc30ea77423fcf26858504b99f186063364 | Python | 1,692 | 29 | import argparse
import pandas as pd
def main(args):
stats_df = pd.read_csv(args.text_path,sep=' ') # read the file created in averageOptimalconnectivity.sh through shell function compute_Brodmann_average_number
# for each Brodmann Area, get percentage of voxels significant in that area over all significant... |
a4bb1f009d0a3052de562d3e7ec05c83ece90f5f61d7840910419dafebb8c222 | Python | 1,692 | 55 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 30 17:34:14 2021
@author: fhu14
"""
#%% Imports, definitions
import numpy as np
import torch
Tensor = torch.Tensor
from typing import List
#%% Code behind
def torch_geom_mean(vals) -> Tensor:
r"""Computes the geometric mean using torch functions to allow for
... |
3930eed706c13f89386fd1913c5f105b760e76987734c80690e4aa3dc2abc112 | Python | 1,693 | 49 | import torchvision.transforms.functional as F
class Normalize(object):
"""Normalize a tensor volume given the mean and standard deviation.
:param mean: mean value.
:param std: standard deviation value.
"""
def __init__(self, mean, std, val_mean=None, val_std=None, training=True):
if isins... |
a2f82ae552c6487b13bd2497367527f2e0e9099fd72a76b50f39dc10deb51a39 | Python | 1,693 | 66 | __author__ = 'marakeby'
from sklearn import preprocessing as p
from sklearn.decomposition import PCA
import numpy as np
import logging
from preprocessing.clean_text import CleanText
def get_processor( args):
print (args)
proc_type = args['type']
logging.info("Pre-processing: %s", proc_type)
# params... |
6f213a7ab88ba8a2db26c32235ca7df750b9f9a1007e4fd1190f87688479ba6b | Python | 1,694 | 50 |
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be usef... |
2edbe8c089b74d9f3b51b23a40195e2961a30a57014c9987999b8feaaa628f7c | Python | 1,695 | 62 | # coding: utf-8
import argparse
from pathlib import Path
import pandas as pd
from sklearn.metrics import mean_squared_error
import lightgbm as lgb
parser = argparse.ArgumentParser()
parser.add_argument(
"--device",
default="cpu",
help="device to train on: 'cpu', 'gpu', or 'cuda' (default: 'cpu')",
)
args... |
81149e4905ed7aa90a9aaaa90da5cbfdf7ba7a2eac1c942b1338100608eddbf1 | Python | 1,695 | 49 | import math
import torch.nn as nn
from layers import BBB_Linear, BBB_Conv2d
from layers import BBB_LRT_Linear, BBB_LRT_Conv2d
from layers import FlattenLayer, ModuleWrapper
class BBBLeNet(ModuleWrapper):
'''The architecture of LeNet with Bayesian Layers'''
def __init__(self, outputs, inputs, priors, layer_ty... |
173b4f6bd2d70e00583a3262cf7e15eb3ad5057ec06edf9e120ee1909c13eddf | Python | 1,697 | 51 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import warnings
from mmcv import Config, DictAction
def parse_args():
parser = argparse.ArgumentParser(description='Print the whole config')
parser.add_argument('config', help='config file path')
parser.add_argument(
'--options',
... |
59d7fc8ef4883dd7ed89436acc0eb12b0184d96614b41fe26952c5598b01b496 | Python | 1,698 | 49 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class CascadeRCNN(TwoStageDetector):
r"""Implementation of `Cascade R-CNN: Delving into High Quality Object
Detection <https://arxiv.org/abs/1906.09756>`_"""
... |
ebd4e63ccac07d424c81e61628793c05225c505520a8337f010bf7d102a14a90 | Python | 1,698 | 36 | from D_modelling import d090_model_wrapper
from A_config import a10_config
import os
import pandas as pd
pd.set_option('display.width', 5000)
pd.set_option('display.max_columns', None)
# remove limits
# os.environ['MKL_NUM_THREADS'] = '8'
# os.environ['OPENBLAS_NUM_THREADS'] = '8'
# os.environ['OMP_NUM_THREADS'] = '8... |
c4a14627081627380c6377f3d073943997766b0ef0f3b04317e853a8f730ce82 | Python | 1,701 | 50 | """ Spatial and Temporal feature Mixer
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.layers import DropPath
from models.layers.mlp import Mlp
class STAttention(nn.Module):
def __init__(self, dim, qk_bias=False, proj_drop=0.):
super().__init__()
self.qk = ... |
196fd8c563fac9f0b880d7dcb3311341f232f53c4646db5dd18848eca44999cd | Python | 1,702 | 44 | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
from terminaltables import AsciiTable
from mmdet.models import dense_heads
from mmdet.models.dense_heads import * # noqa: F401,F403
def test_dense_heads_test_attr():
"""Tests inference methods such as simple_test and aug_test."""
# make list o... |
2d370ebb7676c3a37dcf1d5b058ffb42d929b533c1a081fd0f4deb46a9e9fd4f | Python | 1,703 | 40 | import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import Normalizer
from tpot.export_utils import set_param_recursive
from metstab_shap.grid import SVC_rbf
from metstab_shap.config import utils_section, csv_section
from me... |
82c0903c5836fa2c8e04893e5bb62d6fbc660718ff29be7271b992b9682696a0 | Python | 1,707 | 65 | #!/usr/bin/env python
# Copyright [1999-2017] EMBL-European Bioinformatics Institute
#
# 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
#
# Unl... |
bc9960ba2859797fd5e9ec4b0e471653f616816ce90ddc3a90563fa1b478c4ba | Python | 1,707 | 46 | """
Build hdf5 files based on MURA datasets.
"""
import os
import sys
import h5py
import nibabel as nib
def readlist(dcm_path, save_path, save_name, test_case_number):
dcm_folders = sorted(os.listdir(dcm_path))
result_file = h5py.File(os.path.join(save_path, save_name), "w")
idx = 0
for i in dcm_f... |
c103eb0789507a687c0a185f45887d580c4c36c9293b6dc026a19bc7453198ce | Python | 1,707 | 64 | import os
from matplotlib import pyplot as plt
from selbstaufsicht import datasets
root = os.environ['DATA_PATH'] + 'Xfam'
ds = datasets.XfamDataset(root, download=True, mode='seed', version='14.6')
# ds2 = datasets.XfamDataset(root, download=True, mode='enhanced', version='14.6')
#
# for i, (msa1, msa2) in enumera... |
33641a43777ab4cc5a2835c3f4590007a91ab7a6ea1598eaca5b55b6d386e07d | Python | 1,711 | 64 | # Do an MCMC with more than one data partition.
# The defaults for these values are much smaller. These suggested
# changes may not be needed all the time, but seems to help for
# difficult data.
var.PIVEC_MIN = 1.e-6
var.RATE_MIN = 1.e-6
var.BRLEN_MIN = 1.e-5
var.GAMMA_SHAPE_MIN = 0.15
# Assuming more than one run,... |
67286bd95d4acdbeabc05198a19cd1657ad3f82132e511897401678655a81739 | Python | 1,713 | 44 | #!/usr/bin/python
## 5/19/2016 - update to allow for authentication based on api-key, rather than username/pw
## See https://documentation.uts.nlm.nih.gov/rest/authentication.html for full explanation
import requests
from pyquery import PyQuery as pq
from lxml import etree
uri = "https://utslogin.nlm.nih.gov"
# optio... |
3ad1daf09289c55a0ef786f887d5f91285543989b445229acabae58520ba316b | Python | 1,714 | 54 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from numpy.testing import assert_allclose
from oct2py import octave
import pytest
from pystoi.stoi import FS, stoi
RTOL = 1e-6
ATOL = 1e-6
def test_stoi_good_fs():
""" Test STOI at sampling frequency of 10kHz. """
x = np.random.randn(2 * FS)
... |
cfe61b4df94c48cc0eaa192de32416af17c653c9d557db656eda30a00154b761 | Python | 1,714 | 40 | import numpy as np
import pandas as pd
from sklearn.naive_bayes import ComplementNB, MultinomialNB
from sklearn.pipeline import make_pipeline, make_union
from sklearn.preprocessing import Normalizer
from tpot.builtins import StackingEstimator
from tpot.export_utils import set_param_recursive
from metstab_shap.config i... |
ff1590ac66ced9a97a0bd6bcb72c50bee65c620015323f078d2308f13a80c179 | Python | 1,714 | 44 | # This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/>
import pytest
import torch
from pyro.distributions import InverseGamma
from torch.distributions import Bernoulli, Beta, Gamma
from sbi.utils.user_input_c... |
d0e4d2e7f13119b80314ce87fd59d4ff27bc8d56f20331524d3de199062b61d9 | Python | 1,715 | 58 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from addict import Dict
from mmpose.models.detectors import GestureRecognizer
def test_gesture_recognizer_forward():
model_cfg = dict(
type='GestureRecognizer',
pretrained=None,
modality=['rgb', 'depth'],
backbone=dict(... |
26ae05ce43eff2078345104c0aa9bcc95b6636a91dde191c27212d943895c19d | Python | 1,718 | 60 | # This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/>
import torch
from sbi.inference import NPE_C, infer, simulate_for_sbi
from sbi.simulators.linear_gaussian import diagonal_linear_gaussian
from sbi.utils.... |
92e0e4d015235afd7fbae987c00fad31b07423384b40f8be8db7a20fe61c3a9d | Python | 1,718 | 47 | from math import radians
from time import time
from PIL import Image
from flystim import GenPerspective, GlCube, CaveSystem, rel_path
from common import run_qt, run_headless, get_img_err
def get_perspective(theta, phi):
# nominal position
perspective = GenPerspective(pa=(+1, -1, -1), pb=(+1, +1, -1), pc=(+1, ... |
ea82aced1cc0b1125a12cb9de6062048adac9a0cd6d46c1cb256861450cfc74e | Python | 1,719 | 49 | import sys
import glob
import os
from F_post_processsing import F100_analyze_hindcast_output
from A_config import a10_config
import manager_0_user_params as upar
if __name__ == '__main__':
"""
This manager just check that all files supposed to be rerun went well (condor sometimes has problems, and specs need... |
401a71dd7dd98ff87086438a45b9121a6dbe0c4ebdb8dfbf45b08732963b1f04 | Python | 1,720 | 50 | import torch
import torch.nn as nn
class T2V(nn.Module):
"""
The Time2Vec layer will embed the daily time series into a lower
dimensional space.
Implementation inspired by:
https://github.com/evelynmitchell/Time2Vec-PyTorch
References:
Kazemi, S.M., Goel, R., Eghbali, S., Ramana... |
b4f96fb828c81403adceb86c41e2020c0dd931499a6e596de7bd09172f48f64d | Python | 1,720 | 37 | from os import path
# Parent directory for the Brain Observatory cache
BRAIN_OBSERVATORY_CACHE_DRIVE_PATH = r"/Users/chase/Desktop/MindScope/visual-coding-2p"
# Manifest file for the Brain Observatory cache (do not edit)
BRAIN_OBSERVATORY_CACHE_MANIFEST_FILE = path.join(BRAIN_OBSERVATORY_CACHE_DRIVE_PATH, "manifest.j... |
f259d54b2b49b86657f45820c2cdb054b4706057a8aafc17e4b36603376bcb16 | Python | 1,720 | 51 | import os
from setuptools import setup, find_packages
if os.path.exists('README.md'):
long_description = open('README.md').read()
else:
long_description = '''A toolkit for resolving chemical SMILES from structural diagrams.'''
setup(
name='reactiondataextractor',
version='2.0.0',
author='Damian... |
35e61811b0aefd590a687210871e6e8108f0cdb0d5d1ae341c16bfc1f9f654a9 | Python | 1,721 | 51 | import sys
input_file_path = sys.argv[1]
input_file = input_file_path.split("/")[-1]
output_file_path = sys.argv[2]
header = True
mol_index = 0
mol_name = ""
mol_smile = ""
tautomer_index = 0
tautomer_inchi_key = ""
tautomer_smile = ""
input_header = []
index = 0
tautomers = {}
with open(input_file_path, "r") as f... |
54eabee7ce7eedca0647109eda777ef4bf8709cbc64d879ab5d7f94e4843e1c0 | Python | 1,721 | 32 | # Copyright (c) OpenMMLab. All rights reserved.
from .accuracy import Accuracy, accuracy
from .ae_loss import AssociativeEmbeddingLoss
from .balanced_l1_loss import BalancedL1Loss, balanced_l1_loss
from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy,
cross_entropy, m... |
5a1c925d5eb21a96dee0175f5770e7463492dbd756c663bc029e2b9ffc1bdec0 | Python | 1,722 | 44 | #!/usr/bin/env python3
from flystim.stim_server import launch_stim_server
from flystim.screen import Screen
import numpy as np
from time import sleep
def main():
manager = launch_stim_server(Screen(fullscreen=False, server_number=0, id=0, vsync=False))
manager.load_stim(name='ConstantBackground', color=[0.5... |
c6077ca96ded22e46848dd3b5b49a592ac654d8fb56aa6e38cd618b21dd86388 | Python | 1,724 | 38 | import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import Binarizer
from tpot.export_utils import set_param_recursive
from metstab_shap.config import utils_section, csv_section
from metstab_shap.config import pa... |
b469fb565ba47952366b183905c87db156949ec5020aaa6d295d685b76d079a3 | Python | 1,725 | 49 | import argparse
import os
import numpy as np
import pandas as pd
def main():
parser = argparse.ArgumentParser(description='Selbstaufsicht Weakly Supervised Contact Prediction Script')
# Pre-trained model
parser.add_argument('--log-path', type=str, help="Path to logging data of the specific xgboost downst... |
27fb4a600c4257ae6e719329f4567677810d4045946dd1cb14285c43f4d7da18 | Python | 1,727 | 42 | from distutils.core import setup
from distutils.extension import Extension
myFiles = """pyquartet_dist.cpp
HDT.cpp
HDTCountingCCToC.cpp
HDTCountingCTransform.cpp
HDTCountingG.cpp
HDTCountingIGToC.cpp
HDTCountingLeaf.cpp
HDTFactory.cpp
HDTListUtils.cpp
NewickParser.cpp
RootedTree.cpp
RootedTreeFac... |
acbd0ea4cd965c80a7515700dc72897782f8265af36180fbaa4a1144b12e2d4d | Python | 1,728 | 50 | # Copyright (c) OpenMMLab. All rights reserved.
from collections import OrderedDict
from mmcv.runner import get_dist_info
from mmcv.runner.hooks import HOOKS, Hook
from torch import nn
from ..utils.dist_utils import all_reduce_dict
def get_norm_states(module):
async_norm_states = OrderedDict()
for name, chi... |
89eee0b5bb62d0a1f46dec3bfd2f00f0996bbb0c968b40740ed045dce49bf500 | Python | 1,730 | 57 | from typing import Any, cast
import warnings
import eagerpy as ep
from ..types import BoundsInput, Preprocessing
from .base import ModelWithPreprocessing
def get_device(device: Any) -> Any:
import torch
if device is None:
return torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
if ... |
f568f217813bce6c653df646f4a3b128a3452cf9828aaadc84aaea3860601e92 | Python | 1,734 | 49 | read('../A_NavidiAlignFromYang/navidiSSRNA.nex')
read('t.nex')
d = Data()
d.calcUnconstrainedLogLikelihood1()
u = d.unconstrainedLogLikelihood
#fResults = open('results', 'w')
fResults = sys.stdout
fResults.write('\nYang and Roberts Table 3, HKY + dG + N1\n\n')
fResults.write('tree diff kappa shape\n')
for t... |
1ab2a46305848bda3051ae318af7efad14cc00ea62a95cf14815afb6e3275fa6 | Python | 1,735 | 39 | import numpy as np
class ExpPadding3d:
def __init__(self, load_size, training=True):
"""
Padding the image: C x H x W x D, if H, W, D less than load_size, and will keep the overflow side as it is.
"""
# TODO: Not just support static filling of the padding, but also mirror, etc...
... |
4e3e8f12f734ade0ba990cfe45ed3dd2d30a51d134c921a29ec350d2d0736c89 | Python | 1,736 | 53 | import os, pickle
import numpy as np
import pandas as pd
from common_functions import get_indeces_identical_mols, calc_similarity_matrix
root = os.path.dirname(os.getcwd())
D = pd.read_csv(root + "/data/data.csv")
cpds_inchikey_smiles = D[["inchi_key", "smiles"]].drop_duplicates()
print("data =", D.shape)
# remove... |
be1c4cd37b20c4f4cf467e34ade51339195f9616166866f0215301c996ca8890 | Python | 1,738 | 63 | import json
import pandas as pd
from pathlib import Path
from itertools import repeat
from collections import OrderedDict
def ensure_dir(dirname):
dirname = Path(dirname)
if not dirname.is_dir():
dirname.mkdir(parents=True, exist_ok=False)
def read_json(fname):
fname = Path(fname)
with fname.... |
e089d0053f7a1f34dbbbd0262c455521fc7c59b5e9d54d1d3626820e54da06f3 | Python | 1,740 | 49 | import numpy as np
import random
class RandomFlip3d:
def __init__(self, horizontal=True, vertical=True, deep=False, training=True):
self.horizontal = horizontal
self.vertical = vertical
self.training = training
self.deep = deep
def __call__(self, sample):
"""
R... |
f1d5d3b3022e7fc3ed850d698d66b9a6d579ff76798a6127551b4e8cc4d10f3f | Python | 1,740 | 50 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
from scipy.signal import savgol_filter
from .builder import FILTERS
from .filter import TemporalFilter
@FILTERS.register_module(name=['SavizkyGolayFilter', 'savgol'])
class SavizkyGolayFilter(TemporalFilter):
"""Savizky-Golay filter.
Adapted... |
e8691618950343f92ce0dd17577ca7f235fd9d126a2709b4288f0ba04a53fbde | Python | 1,742 | 52 | #!/usr/bin/env python
# Example of tcp tagging client
# The tag format is the same as with Shared Memory Tagging. It comprises three blocks of 8 bytes:
#
# ----------------------------------------------------------------------
# | padding (8 bytes) | event id (8 bytes) | timestamp (8 bytes) |
# -----------------... |
79b0b6038292645d74089553eead112adc8ec329bd47e034c02a6dcf016260b9 | Python | 1,743 | 68 | import json
import pandas as pd
import cv2
def read_csv(root):
data_all = pd.read_csv(root)
data = data_all[["Pic", "ADI_L_X", "ADI_L_Y", "ADI_R_X", "ADI_R_Y", "SAC_L_X", "SAC_L_Y", "SAC_R_X", "SAC_R_Y"]]
data = data.values
return data
def split_list_n_list(original_list, n):
# spilt data by fol... |
4e209b802eac787459b2e5cf9fc1de9749f5a76acb7f2b943fcc73f7c23e0ad3 | Python | 1,744 | 55 | import pytest
from pathlib import Path
from clipkit.clipkit import execute
from clipkit.files import FileFormat
from clipkit.modes import TrimmingMode
from clipkit.settings import DEFAULT_AA_GAP_CHARS, DEFAULT_NT_GAP_CHARS
here = Path(__file__)
@pytest.mark.integration
class TestCSTOut(object):
@pytest.mark.par... |
fe9d789cb1b7c751fa69d894e8601c5b4476144b7bcff126a0ef6456fe144852 | Python | 1,745 | 57 | from os.path import dirname, join
from setuptools import find_packages, setup
with open(join(dirname(__file__), "foolbox/VERSION")) as f:
version = f.read().strip()
try:
# obtain long description from README
readme_path = join(dirname(__file__), "README.rst")
with open(readme_path, encoding="utf-8") ... |
825519d76ff6c0c106cce9667b16ff8aab7414139d93229d4db689f6b42d3ab7 | Python | 1,746 | 54 | # -*- coding: utf-8 -*-
# Copyright 2021 Tomoki Hayashi
# MIT License (https://opensource.org/licenses/MIT)
"""Feature matching loss modules."""
import torch
import torch.nn.functional as F
class FeatureMatchLoss(torch.nn.Module):
"""Feature matching loss module."""
def __init__(
self,
av... |
13d9d6d45876c4920bd2d7d8db0d1035e05ac0dbb90d2eed4e4a2839c8ff8081 | Python | 1,747 | 49 | # dataset settings
dataset_type = 'CocoDataset'
data_root = 'data/uva/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True, with_mask=True),
dict(type='Resize', img_... |
41245abd65ce44be0f94dc773a9473d82e761d8b32c2c4e697dcf78d50374856 | Python | 1,748 | 42 | from mpi4py import MPI
from fedml_api.distributed.classical_vertical_fl.guest_manager import GuestManager
from fedml_api.distributed.classical_vertical_fl.guest_trainer import GuestTrainer
from fedml_api.distributed.classical_vertical_fl.host_manager import HostManager
from fedml_api.distributed.classical_vertical_fl.... |
3f7350ae09dddfdfc73ab1bfaf64e9b8dfd31421da09ad7b44ea07d0f806dc03 | Python | 1,749 | 48 | # Copyright (c) OpenMMLab. All rights reserved.
import glob
import os.path as osp
from unittest import TestCase
import numpy as np
from mmcv import Config
from mmpose.core.post_processing.temporal_filters import build_filter
class TestTemporalFilter(TestCase):
cfg_folder = 'configs/_base_/filters'
def get_... |
32edceda751affe8d069147cdc04879a8a2273dcac888ce1569250282e0b2e3a | Python | 1,751 | 52 | from torch.nn import CrossEntropyLoss, MSELoss
from transformers import BertModel, PreTrainedModel, BertConfig, load_tf_weights_in_bert
from transformers.modeling_outputs import Seq2SeqSequenceClassifierOutput, SequenceClassifierOutput
import torch
from torch import nn
import torch.nn.functional as F
from model.bert_mo... |
4e1e39b632a56f841c6fb688e99ba2fbd37914d3ec09303e8850067cd8b11f60 | Python | 1,752 | 39 | import numpy as np
import pandas as pd
from sklearn.feature_selection import VarianceThreshold
from sklearn.pipeline import make_pipeline, make_union
from sklearn.preprocessing import RobustScaler
from tpot.builtins import StackingEstimator
from tpot.export_utils import set_param_recursive
from metstab_shap.grid impor... |
561046fc986566b55d02ca2911b482024d1995df6c8662fc2a4209bf42ff3827 | Python | 1,753 | 47 | """ Python Server entry point """
import argparse
import logging
import os
import sys
from .server import __version__, serve, start, status, stop, wait, widget
__all__ = ["start", "stop", "status", "wait", "serve", "widget", "__version__"]
def main():
""" main entry point """
parser = argparse.ArgumentParse... |
e1eb35f77e5e3faa4ab8594dacba60b16900c191eadd241b1257ce2dc49b3871 | Python | 1,753 | 56 | from os import path
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
with open(path.join(here, "README.md"), encoding="utf-8") as f:
long_description = f.read()
def _read_version():
version_ns = {}
with open(path.join(here, "clipkit", "version.py"), encoding="utf-8... |
05574612f02304d1f096c41f8259bfec33097082c2f165f1c2b40bd9e218c547 | Python | 1,754 | 49 | #!/usr/bin/env python3
from flystim.stim_server import launch_stim_server
from flystim.screen import Screen
from time import sleep
def main():
stim_time = 4
x_trajectory = {'name': 'tv_pairs',
'tv_pairs': [(0, -2), (stim_time, 2)],
'kind': 'linear'}
y_trajecto... |
97ddb9ab8fe6b9152def226abdbe962283e3bc215b118b1e5ec007e46615055c | Python | 1,754 | 49 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 14:31:17 2020
@author: bariskuru
"""
import numpy as np
from elephant import spike_train_generation as stg
from neo.core import AnalogSignal
import quantities as pq
from scipy import signal, interpolate
loaded_traj = np.load('/Users/bariskuru/D... |
0b960758a44552c3577972713839fb6d87fc89da3ee0809d02c099da14ad9a90 | Python | 1,756 | 37 | import numpy as np
from scipy.ndimage import zoom
from skimage.transform import resize
class Zoom3d:
def __init__(self, zoom_size, interp="bilinear", training=True):
"""
Resize the image: C x H x W x D to the C x load_size[0] x load_size[1]
order will apply to image and mask separately. 0:... |
ddd3a30252485cfb76d9241b2c87e58ac8b901d860d37e188ebf427b48069b79 | Python | 1,758 | 51 | import os
import numpy as np
from Bio import AlignIO
from clipkit.msa import MSA
from clipkit.modes import TrimmingMode
from clipkit.plot_report import write_trim_plot_report
def get_biopython_msa(file_path, file_format="fasta"):
return AlignIO.read(open(file_path), file_format)
def test_write_trim_plot_repor... |
e85864b7b5a1f95610aae0459aef430025c5fdef795d71d43259093467c2cb44 | Python | 1,758 | 45 | import dit
import numpy
from .admUI_numpy import computeQUI_numpy
def computeQUI(distSXY, eps = 1e-7, DEBUG = False, IPmethod = "GIS",
maxiter = 100000, maxiter2 = 100000):
'''
Compute an optimizer Q
distSXY : A joint distribution of three variables (as a dit.Distribution).
eps : T... |
9f6539b0d02965580b410a4757bd27bd1ad3104c0ad833a7112c930fc5d50f44 | Python | 1,759 | 38 | import numpy as np
import cv2
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter
# Function to distort image
def elastic_transform(image, alpha, sigma, alpha_affine, random_state=None):
"""Elastic deformation of images as described in [Simard2003]_ (with modif... |
4826c1388425b65020aba2459a183c8e8309bac0b19d45c0b7885fac1a4de1e6 | Python | 1,763 | 38 | import numpy as np
import pytest
from sklearn.linear_model import LinearRegression, LogisticRegression
import doubleml as dml
from doubleml.irm.datasets import make_iivm_data
from doubleml.utils._propensity_score import _normalize_ipw
@pytest.mark.ci
def test_iivm_normalize_ipw_uses_instrument():
# The inverse p... |
4ac2169369d50d4c41d02b5ec958146c3df2556bfe356a78ec1e6e8855e926fc | Python | 1,764 | 55 | from __future__ import division, print_function
import codecs
import re
class LanguageModel:
"simple language model: word list for token passing, char bigrams for beam search"
def __init__(self, fn, classes):
"read text from file to generate language model"
self.initWordList(fn)
self... |
9edff239dee5f15854cb294c7d9306f62b93b8daf97a851cc52fe7f5900d261f | Python | 1,764 | 65 | from __future__ import division
from __future__ import print_function
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC,SVC
from sklearn.metrics import *
from sklearn.linear_model import LogisticRegression
import warnings
def multiclass_node_classification_eval(X... |
e8d740d79ed583ca06cd06e53c8c4c47bbfc6d8229b80a154752759fe8c65298 | Python | 1,764 | 50 | import numpy as np
import torch
import torch.nn as nn
class Interpolate(nn.Module):
def __init__(self, scale_factor, mode, align_corners=False):
super(Interpolate, self).__init__()
self.interp = nn.functional.interpolate
self.scale_factor = scale_factor
self.mode = mode
self... |
131302ff3133546f86ff4d1318f6b0ab9da329af74abd5f30754de5d03779c11 | Python | 1,767 | 48 | import unittest
from pathlib import Path
import yaml
from pydantic import ValidationError
from oligo_designer_toolsuite.config.pipelines.oligo_seq_probe_designer import OligoSeqProbeDesignerConfig
_CONFIGS = Path("data/configs")
def _load(filename: str) -> dict:
with open(_CONFIGS / filename) as fh:
da... |
764efb5fd10dbc28bd388306681559e75b41a366c341aceafbdb3b9b72fb2f86 | Python | 1,767 | 50 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 18:06:38 2021
@author: fhu14
This file will contain misc functions like get_dftb_vals and plotting
utilities for the splines.
Functions here should be exposable at the top level
"""
#%% Imports, definitions
from Elements import ELEMENTS
import numpy as np
from Mast... |
bd20ea8dda4d43900e1945ed65f3b12ad54c84923845799222d3e1c43a7a0449 | Python | 1,767 | 60 | import copy
import numpy as np
import torch
from daart.models import Segmenter, Ensembler
def test_reparameterize_gaussian():
from daart.models.base import reparameterize_gaussian
n = 10
m = 4
mu = 40
mus = mu * torch.ones((n, m))
logvars = 0.1 * torch.ones((n, m))
sample = reparameter... |
67df339068e00f6c4abbec04500dc1855a55148ef01be67ec01817e741f13891 | Python | 1,768 | 56 | # General parameter interface information:
# Dictionary: par = parDict['C-N']
# Constructor: par = SkfInfo(name='C-N', paramPath='./mio-0-1')
# Getters:
# par.GetSkInt(key='Hss0', dist=1.5)
# par.GetAtomProp(key='Es')
# par.GetRep(dist=1.5)
# SKF parameter interface:
import os
from SKF import SkfInfo
PARAMPATH... |
9d4e6ee161ac29cc0e44edc97608689fea75c2e45ed39f69d2c1fca6c1f00aee | Python | 1,768 | 66 | #!/usr/local/bin/python
import sys
import subprocess
import os
import numpy as np
if len(sys.argv) < 2:
print('usage:' + sys.argv[0] + ' <bam 1> <bam 2> <..>')
exit(1)
order = []
for i in range(1,len(sys.argv)):
bam_file = sys.argv[i]
print(bam_file)
p = subprocess.Popen(\
['samtool... |
2d577f96336c0fd1c27e15f679c9f1985790edca18b75a1cce8bdbead3f1b643 | Python | 1,771 | 52 | # General parameter interface information:
# Dictionary: par = parDict['C-N']
# Constructor: par = SkfInfo(name='C-N', paramPath='./mio-0-1')
# Getters:
# par.GetSkInt(key='Hss0', dist=1.5)
# par.GetAtomProp(key='Es')
# par.GetRep(dist=1.5)
# SKF parameter interface:
import os
from deprecated.skfinfo_v0 import S... |
888d17087b9fa0f4b38d15fb7e7bbc1877faeac48b490ad196641885340a977c | Python | 1,773 | 42 | from nipype.interfaces.base import (traits, TraitedSpec,
BaseInterfaceInputSpec,
BaseInterface,
isdefined)
class Direct_File_Provider_InputSpec(BaseInterfaceInputSpec):
subject_id = traits.Str(mandatory=Tr... |
d1bfb2130ac239505e3978decde6ece6e9fd7b293e9414da44576c194f67b92e | Python | 1,775 | 58 | import torch
from torch import nn
import torch.nn.functional as F
class BCELoss(nn.Module):
def __init__(self, alpha=None, reduction='sum'):
'''reduction: mean/sum'''
super().__init__()
self.alpha = alpha
self.reduction = reduction
def forward(self, inputs, target):
'... |
08f694a6e371f0963cc20b928e1d88398e1cf9806d4e4e2135418a5d25ece5e9 | Python | 1,777 | 52 | import numpy as np
class RandomCrop:
"""
Crop the 2D numpy [c, h, w] and mask [h, w] in a sample
"""
def __init__(self, output_size, padding=0, training=True):
assert isinstance(output_size, (int, list))
if isinstance(output_size, int):
self.output_size = (output_size, out... |
9a1eebc37cfd9acb948e9502ea14af38a3b66b5b0120a5010f714a698e736871 | Python | 1,778 | 41 | import multipagetiff as mtif
import matplotlib.pyplot as plt
import numpy as np
# paths_in = {'before_deconvolv': '/media/mathilde.lapoix/SCAPE_MARCO/SCAPE/data/220118/unCorrected_F2_run2_HR.tiff',
# 'after_deconvolv': '/media/mathilde.lapoix/SCAPE_MARCO/SCAPE/data/220118/unCorrected_F2_run2_HR_deconvolved... |
9ec9e1259208b8e8f5b742c512fcec5a05f567f0c82be99309f989c7c11851d6 | Python | 1,780 | 49 | import pandas as pd
from sklearn import svm
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import accuracy_score, confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
# Load data from CSV file
# Create a new column after the first column in the gene... |
93683ed7753bb4015be0600971bf35ab89fc04d38cfb973024644d92a292ac64 | Python | 1,781 | 67 | # Make the rst file scripts.rst
from p4.P4Error import P4Error
start = """
========================
Scripts for common tasks
========================
This is a cook book of reminders, suggestions, and points of departure
for customization. You can copy and paste these into your own files.
Or you can use the p4 recip... |
c80557603e0101e138e60a2f9cefc2ae65c20ce4de0d8def08a546e3f7d7dfe9 | Python | 1,781 | 61 | import copy
import numpy as np
import pytest
import torch
from daart.models import Segmenter, Ensembler
def test_reparameterize_gaussian():
from daart.models.base import reparameterize_gaussian
n = 10
m = 4
mu = 40
mus = mu * torch.ones((n, m))
logvars = 0.1 * torch.ones((n, m))
sample... |
192804d1deb03bd926d5d2ada0e5552f5e7ffafa9270ecded8f479cf04f6e337 | Python | 1,782 | 39 |
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be usef... |
3403002f5cf79da61eb0be437b907586c5a639c8e66ca53f98228c407dc92bc8 | Python | 1,782 | 40 | """Static dependency floor: from entry-point .m files at a commit, follow identifiers
that name .m files present in the tree at that commit. A floor, not a census."""
import subprocess, re, sys, os
repo, commit = sys.argv[1], sys.argv[2]
entries = sys.argv[3:]
ls = subprocess.run(['git','-C',repo,'ls-tree','-r','--name... |
243f8efc9b2eb497d40df4d1e8145b6094e0540d37c3b1e6a68f9d3e36072dc6 | Python | 1,783 | 59 |
from __future__ import division
from __future__ import print_function
import codecs
import re
class LanguageModel:
"simple language model: word list for token passing, char bigrams for beam search"
def __init__(self, fn, classes):
"read text from file to generate language model"
self.initWord... |
6e9cc06bd77df84ce7463bd31eb3e76ec470d69114c2794a71b747b3f28d304f | Python | 1,783 | 53 |
def check_pysam_version(min_pysam_ver="0.8.4"):
"""Checks that the imported version of pysam is greater than
or equal to provided version. Returns 0 if version is high enough,
raises ImportWarning otherwise."""
import pysam
min_ver = [int(x) for x in min_pysam_ver.split(".")]
pysam_ver = [int(... |
1580b533333ccda50cdf7e06327b78ced343fa282f82982cfd63684bc57e0370 | Python | 1,784 | 52 | # deal with data format differences
import numpy as np
import pandas as pd
import os
from .utils import *
from natsort import natsorted
def listdir_nohidden(path):
for f in os.listdir(path):
if not f.startswith('.'):
yield f
# load any data from convrntionl Wasatch
def data_loader_b... |
6da9ee4715bf82b91401bd1d88243ad2541f84dd39344ece0e9304f3e174ef66 | Python | 1,784 | 52 | from typing import Any
from ..models import Model
from .git_cloner import clone
from .model_loader import ModelLoader
def get_model(
url: str, module_name: str = "foolbox_model", overwrite: bool = False, **kwargs: Any
) -> Model:
"""Download a Foolbox-compatible model from the given Git repository URL.
... |
7fffdc65d2ec9c72e94a5215ea6f61420c46dd2067d711222ed41c43c31a6be7 | Python | 1,785 | 46 | from mpi4py import MPI
from fedml_api.distributed.fedgkt.GKTClientManager import GKTClientMananger
from fedml_api.distributed.fedgkt.GKTClientTrainer import GKTClientTrainer
from fedml_api.distributed.fedgkt.GKTServerManager import GKTServerMananger
from fedml_api.distributed.fedgkt.GKTServerTrainer import GKTServerTr... |
bd3185ac0b78ad96d08ebc69572ede25fc5078d0cb9a3297649d7790ab622363 | Python | 1,786 | 46 | import typing
import models.abstract
from models.abstract import ModelClassMetaData
from models.keras.geography_weighted_model import GeographyWeightedKerasModelMeta, GeographyWeightedKerasModel
# Import bez importu :)
if False:
import tensorflow.keras as keras
class GeographyWeightedLinearModelMeta(GeographyWe... |
115e21031ce55189b8b33c53d1a40bbf88dd4f39c1cf92c30cbab8c31fa9fc7f | Python | 1,789 | 58 | ############################################
# imports
############################################
import logging
import os
from datetime import datetime
from pathlib import Path
############################################
# Logging utils
############################################
# Library-wide logger
logger = ... |
6959f390f90f04a76fc4fc46f5c319943cf32057ac3c99038610d69494beb0d7 | Python | 1,789 | 58 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import tempfile
from collections import OrderedDict
import torch
from mmcv import Config
def parse_config(config_strings):
temp_file = tempfile.NamedTemporaryFile()
config_path = f'{temp_file.name}.py'
with open(config_path, 'w') as f:
... |
fb128a8fd36d919cc201ebefa0a5af96b5fc6fa14508c459ed704c6db6b1c6cb | Python | 1,791 | 54 | import ctypes
import logging
import threading
import traceback
from ..message import Message
class MPIReceiveThread(threading.Thread):
def __init__(self, comm, rank, size, name, q):
super(MPIReceiveThread, self).__init__()
self._stop_event = threading.Event()
self.comm = comm
self... |
47c869b858f938c9dc6e8ed2c36a01379c188d33c39affefa51b42c409279ca8 | Python | 1,800 | 68 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 18:54:37 2021
@author: fhu14
"""
#%% Imports, definitions
from MasterConstants import Model, RawData
from typing import List, Dict
import numpy as np
Array = np.ndarray
#%% Code behind
class Input_layer_DFTB:
def __init__(self, model: Model) -> None:
r""... |
52acf9fa9fcee326bcb8e1357a9108ce776ebdb61dd60e2ee85c4d3b398bbcf8 | Python | 1,800 | 46 | import pathlib
import json
import argparse
from exsclaim.figures.scale.train_label_reader import train_crnn
from exsclaim.figures.scale.evaluate_scale import test_label_reading
current_file = pathlib.Path(__file__).resolve(strict=True)
parent_directory = current_file.parent
ap = argparse.ArgumentParser()
ap.add_arg... |
6bbbb4bb5c7ae6dbaa7cd3a1c0c65a0681dba9d154831330712a33ecd58e66aa | Python | 1,801 | 56 | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
import os
import sphinx_rtd_theme
import sys
sys.path.insert(0, os.path.abspath('../'))
# -- Project information -... |
b2a6e5b7e1590e56eb2847ff9ec9b75fb2a61e8b4a54fcad0740f01f6cd7bb83 | Python | 1,802 | 65 | #!/usr/bin/env python
# coding: utf-8
# # Install pyem on your machine
# ## Create a new conda environment and install the dependencies
#Run these commands
get_ipython().system('conda create -n pyem')
get_ipython().system('conda activate pyem')
get_ipython().system('conda install numpy scipy matplotlib seaborn num... |
ad8294dc5c4f5e34ed6bd8c71ae392fc22153d07301f39eeb93d1c86b0469abd | Python | 1,808 | 50 | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn.bricks.wrappers import NewEmptyTensorOp, obsolete_torch_version
if torch.__version__ == 'parrots':
TORCH_VERSION = torch.__version__
else:
# torch.__version__ could be 1.3.1+cu92, we only need the first two
# for comparison
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.