sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
6d327d9eca7d60c6e860b591f700d5419a707944a616f53cead0d40b3bf23705 | Python | 507 | 25 | import numpy as np
year_range = np.arange(1996, 1997)
file_names = []
for year in year_range:
file_names.append('opt'+str(year))
for file_name in file_names:
with open(file_name, 'r') as f:
content = f.readlines()
if content[4] == 'YES\n':
content[4] = 'NO\n'
if content[5] == 'NO\n'... |
5e559d13c23be06072556c4fe77c60e4dfe73cd10fac52f81d9f548952dbad67 | Python | 508 | 23 | """Snakemake wrapper for picard SortSam."""
__author__ = "Julian de Ruiter"
__copyright__ = "Copyright 2017, Julian de Ruiter"
__email__ = "julianderuiter@gmail.com"
__license__ = "MIT"
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
log = snakemake.log_fmt_shell(stdout=False, stderr=Tr... |
c585c073e84c931b6544a4ec4a74a9ba43b0f08d1312c8694732ea306c3d63d1 | Python | 508 | 16 | from .detectors_resnet import DetectoRS_ResNet
from .detectors_resnext import DetectoRS_ResNeXt
from .hourglass import HourglassNet
from .hrnet import HRNet
from .regnet import RegNet
from .res2net import Res2Net
from .resnet import ResNet, ResNetV1d
from .resnext import ResNeXt
from .ssd_vgg import SSDVGG
from .resnet... |
01fea8188b5f78a94417ff01bf8a30a33cb4ca4517854cef8e37a75220affefd | Python | 512 | 22 | import torch
import sys
class AbstractTorchModule(torch.nn.Module):
def __init__(self):
torch.nn.Module.__init__(self)
def save(self, path):
print("Saving to path " + path, file=sys.stderr)
torch.save(self.state_dict(), path)
def load(self, path):
print("Loading from pat... |
0e3d6c18ceab9499c3f662dd9882679125b22488eba2fbc34738f019c85ba3b6 | Python | 512 | 22 | """
AS sleep build using SPINDLE output.
"""
import time
from scripting.sleep import dataset
from scripting.spectrum.io import persist
SAVE_PATH = './sleep_dataset.pkl'
#Build dataset
t0 = time.perf_counter() #initiate timer
dset = dataset.build() #see dataset.py
delta_t = time.perf_counter() - t0
print('Dataset buil... |
67e7dd2d3ba589332610451b666781dc40ea2423298d4ffa30611e9806e1c02e | Python | 514 | 18 | def pytest_ignore_collect(path, config):
"""Return True to prevent considering this path for collection.
This hook is consulted for all files and directories prior to calling
more specific hooks.
"""
path = str(path)
if 'interfaces' in path:
return True
if '/docs' in path:
re... |
c26b6fd3402ee6d77aaf91c2d4dcf61835f819ae5a9d79c5f76d4fd64cecfefd | Python | 514 | 22 | __author__ = "Patrik Smeds"
__copyright__ = "Copyright 2019, Patrik Smeds"
__email__ = "patrik.smeds@mail.com"
__license__ = "MIT"
from snakemake.shell import shell
log = snakemake.log_fmt_shell()
extra = snakemake.params.get("extra", "")
shell(
"picard CollectTargetedPcrMetrics "
"{extra} "
"INPUT={s... |
972d2e455f251cd563c79ad3e84ca53b511eeebddefc25066aa6494e2dfcceda | Python | 515 | 6 | from oaklib.implementations.pronto.pronto_implementation import ProntoImplementation
from oaklib.implementations.sqldb.sql_implementation import SqlImplementation
from oaklib.implementations.ubergraph.ubergraph_implementation import UbergraphImplementation
from oaklib.implementations.ontobee.ontobee_implementation impo... |
99d699458289500c49372410bd7b56432e6a32b252aaf37bbff9cdcd280277e5 | Python | 515 | 13 | from .compute_speed import compute_speed
from .compute_memory import compute_memory
from .compute_madd import compute_madd
from .compute_flops import compute_flops
from .stat_tree import StatTree, StatNode
from .model_hook import ModelHook
from .reporter import report_format
from .statistics import stat, ModelStat
__a... |
bda165de249732c62fb24ad5ed5f4fb69333a25f284b26e0375de2d52cb37b13 | Python | 515 | 17 | from torch_geometric.utils.subgraph import subgraph
from graphxai.datasets import ShapeGGen
SG = ShapeGGen(model_layers = 3, prob_connection = 0.1, num_subgraphs = 30, subgraph_size = 13)
data = SG.get_graph()
nidx, exp = SG.choose_node(inshape = True, label=1)
print('node index', nidx)
edge_mask = exp.edge_imp.boo... |
632c7a76e663cf57f82270dab73afd9fffc5a6697db66b9c7faeaf3aa66a05e5 | Python | 516 | 22 | #!/usr/bin/python3
import sys, os
import pylab
def plot(filename):
print('Plotting %s' % filename)
pylab.plotfile(filename, cols=(0,1), delimiter=' ', subplots=False)
pylab.show()
if __name__ == "__main__":
try:
filename = sys.argv[1]
if os.path.exists(filename): ... |
908459049a928919b66954435c5a8a18e01048377b6f718005866ae89d821e53 | Python | 516 | 14 | import numpy as np
from sklearn.neighbors import radius_neighbors_graph
import pandas as pd
def density_filtering(
pos: pd.DataFrame, radius: float = 0.2, n_neighbors: int = None
) -> pd.Series:
# Filtering based on number of neighbors in radius
A = radius_neighbors_graph(pos[["x", "y"]].values, radius=ra... |
9e4d75205cf846eb655b98fb9d7c38cfb43df9d33b4ec95368b87951fbeb2669 | Python | 518 | 29 | # -*- coding: utf-8 -*-
"""
@author: Satoshi Hara
"""
import sys
sys.path.append('../')
import numpy as np
from AlternateLinearModel import AlternateLasso
# setting
seed = 0
num = 1000
dim = 2
dim_extra = 2
# data
np.random.seed(seed)
X = np.random.randn(num, dim + dim_extra)
for i in range(dim_extra):
X[:, dim... |
cf10df70d18594deb53ee0e041654463667f5a8eda3a13a102b4a06e1071b78c | Python | 519 | 22 | #!/usr/bin/env python
import sys, os
import pylab
def plot(filename):
print('Plotting %s' % filename)
pylab.plotfile(filename, cols=(0,1), delimiter=' ', subplots=False)
pylab.show()
if __name__ == "__main__":
try:
filename = sys.argv[1]
if os.path.exists(filename): ... |
d3f641bab098a3d405d30ff9462de8f3409178e6dc4321986b44426301efd4d0 | Python | 519 | 18 | import os
from IPython.lib import passwd
# c = c # pylint:disable=undefined-variable
c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = int(os.getenv('PORT', 8888))
c.NotebookApp.open_browser = False
# sets a password if PASSWORD is set in the environment
if 'PASSWORD' in os.environ:
password = o... |
acef2192d1baf1373cc531ebc2e4622b206ab8596dae99bcfb14c26d6bc55e27 | Python | 520 | 17 | """
This module provides classes and methods for sampling labeled data
examples.
"""
from .sampler import Sampler
from .online_sampler import OnlineSampler
from .intervals_sampler import IntervalsSampler
from .random_positions_sampler import RandomPositionsSampler
from .multi_file_sampler import MultiFileSampler
from .... |
a9e300d6e89b6078b60944569422c802e68daf7112cbdb9771bc006f571f4ebf | Python | 521 | 20 | import sys
sys.path.append('../PCWA')
import matplotlib.pyplot as plt
from src.pcwa import pcwa
import numpy as np
y0 = 0
plt.figure(figsize=(10,10))
for n in range(1,12):
y = pcwa.msg(scale=10,window=1,N=n,skewness=1,dx=0.1)
x = len(y)
x = np.linspace(-x/2,x/2,x)
plt.plot([x[0],x[-1]],[y0,y0],color='b... |
da32d186fc8fab45dcc8572b60711a23480954f3fec8c0abd2edd23a9b1d6343 | Python | 521 | 22 | import navis
import pytest
from .common import with_igraph
def test_from_swc(swc_source):
n = navis.read_swc(swc_source)
assert isinstance(n, navis.TreeNeuron)
@pytest.mark.parametrize("parallel", ["auto", True, 2, False])
def test_from_swc_multi(swc_source_multi, parallel):
n = navis.read_swc(swc_sou... |
4224a36a4fba0a049cef43a7a68f9f84b955b075cff1ea33b077e8fdeb9c43ed | Python | 522 | 20 | from typing import Type
from oaklib.parsers import AssociationParser
def get_association_parser(syntax: str, *args, **kwargs) -> Type[AssociationParser]:
"""
Get an association parser for a given syntax
:param syntax:
:param args:
:param kwargs:
:return:
"""
if syntax is None:
... |
aee936ff8d447cfea58a9b4cd49dc9ffd4b2a697abadc83a7bc8dc322d2165df | Python | 522 | 21 | __author__ = "Johannes Köster"
__copyright__ = "Copyright 2018, Johannes Köster"
__email__ = "johannes.koester@protonmail.com"
__license__ = "MIT"
import os
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
java_opts = snakemake.params.get("java_opts", "")
log = snakemake.log_fmt_shell(s... |
b668a58af14ddde12e65600775eb07db82ecbcc44056bc8fdfb32d61d2114047 | Python | 523 | 14 | import timeit
setup = """from SmilesEnumerator import SmilesEnumerator, SmilesIterator\n
import numpy as np
sm_en = SmilesEnumerator()\n
smiles = np.array([ "CCC(=O)O[C@@]1(CC[NH+](C[C@H]1CC=C)C)c2ccccc2","CCC[S@@](=O)c1ccc2c(c1)[nH]/c(=N/C(=O)OC)/[nH]2"]*100)\n
sm_en.fit(smiles, extra_chars=["\\\\"])\n
sm_it = SmilesI... |
3d715650bc908847ff739c6f85981b56343c29dd65e0be9c3bffa0cf8f5a3b54 | Python | 524 | 12 | # Copyright (c) Open-MMLab. All rights reserved.
from .flops_counter import get_model_complexity_info
from .fuse_conv_bn import fuse_conv_bn
from .weight_init import (bias_init_with_prob, caffe2_xavier_init,
constant_init, kaiming_init, normal_init,
uniform_init, xavi... |
6585dc585336fe82813ccc28cc18119e341635d338c70d05e31e36dd279f31c2 | Python | 524 | 28 | from torch.autograd import Function
class FakeQuantize(Function):
@staticmethod
def forward(ctx, x, qparam):
x = qparam.quantize_tensor(x)
x = qparam.dequantize_tensor(x)
return x
@staticmethod
def backward(ctx, grad_output):
return grad_output, None
d... |
a38f5171b052e18484fe6c650dc50d2f7f9bbf902e52ddf82f89ddc251a1b7e8 | Python | 524 | 14 | from torch.nn.modules.module import Module
from ..functions.roi_pool import RoIPoolFunction
class _RoIPooling(Module):
def __init__(self, pooled_height, pooled_width, spatial_scale):
super(_RoIPooling, self).__init__()
self.pooled_width = int(pooled_width)
self.pooled_height = int(pooled_... |
10753e07c17b0eaae3351db0c3b58fd7f8e2dade322dc3f7c097a6299713ae4b | Python | 526 | 14 | import numpy as np
from skimage import exposure
from lib import File
def rescale_intensity(channel_file: File, lower_percentile=2, upper_percentile=98) -> np.ndarray:
image_stack = channel_file.image
rescaled_image_stack =[]
for image in image_stack:
lower, upper = np.percentile(image, (lower_per... |
f315a91749c1d10165c14c383ba9834498d09d1d23a72f56972f4f649c79022f | Python | 526 | 14 | """Parser for GAF association formats"""
from dataclasses import dataclass, field
from oaklib.parsers.parser_base import ColumnReference
from oaklib.parsers.xaf_association_parser import XafAssociationParser
@dataclass
class PairwiseAssociationParser(XafAssociationParser):
"""Parsers for simple subject-object 2... |
090b02503c3e2161b6c7f63b7e8aba0138bd504f67b1233e5b57e43316f8bb90 | Python | 527 | 19 | """Install grr."""
import setuptools
import os
import re
currdir = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(currdir, 'grr', '__init__.py'), 'r') as f:
version = re.search(r"__version__ = '([^']+)'", f.read()).group(1)
setuptools.setup(
name='grr',
version=version,
descriptio... |
b467b6dae220475ee7c30df2d024c0bf031521a79816ad5f02219205b9cae350 | Python | 527 | 23 | """Snakemake wrapper for picard MergeSamFiles."""
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2018, Johannes Köster"
__email__ = "johannes.koester@protonmail.com"
__license__ = "MIT"
from snakemake.shell import shell
inputs = " ".join("INPUT={}".format(f) for f in snakemake.input.vcfs)
log = snakemak... |
187bbdc7cbf2c2c056897e18acde26c0bb7318f5876289ec45ca3d6037574661 | Python | 528 | 18 | import numpy as np
class Collector:
def __init__(self, collection_period_ms, expr):
from neuron import h
self.collection_period_ms = collection_period_ms
self.rvec = h.Vector()
self.rvec.record(expr, collection_period_ms)
def get_values_np(self):
result = np.empty([int... |
34d8ce8038c989bc2c8336ccd752aa3cefed75fded72172aa5d1f8d469611324 | Python | 529 | 20 | import torch
import torch.nn as nn
class Scale(nn.Module):
"""A learnable scale parameter.
This layer scales the input by a learnable factor. It multiplies a
learnable scale parameter of shape (1,) with input of any shape.
Args:
scale (float): Initial value of scale factor. Default: 1.0
... |
9ff2432897fa152e1c30076f259a70f6d53159a77d9b9c5acc7166e1b1404296 | Python | 529 | 19 | # Copyright (c) Open-MMLab. All rights reserved.
__version__ = '2.5.0'
short_version = __version__
def parse_version_info(version_str):
version_info = []
for x in version_str.split('.'):
if x.isdigit():
version_info.append(int(x))
elif x.find('rc') != -1:
patch_version... |
d832b118744197b3eabfa3d2b638f405d84d5e0584fbf430990896fb9f5474f6 | Python | 529 | 19 | import glob
# Kripo needs a header line to be able to read pdbs
# We add a dummy header to every file
file_list = glob.glob(
"../../../data/masif_ligand/data_preparation/00b-pdbs_assembly/*.pdb"
)
header = (
"HEADER DEHYDROGENASE 16-JAN-98 {} \n"
)
for f in file_lis... |
08df63de90663cffeb7d2e26ac79cde40fee5ce5b7ce87688c34fb911a0b99ba | Python | 530 | 17 | import pandas as pd
import os
import sys
import numpy as np
import statsmodels.api as sm
import statsmodels.formula.api as smf
def format_ols_results(res):
''' Converts statsmodels summary results (table2) into dataframe with minimum usuful stat results'''
results_summary = res.summary()
results_as_html =... |
6fe566a2d77bc5baeb4ccf2b8d594256baf81f93aa2e3862a04589979b0f848a | Python | 530 | 23 | """Snakemake wrapper for picard MergeSamFiles."""
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2018, Johannes Köster"
__email__ = "johannes.koester@protonmail.com"
__license__ = "MIT"
from snakemake.shell import shell
inputs = " ".join("INPUT={}".format(f) for f in snakemake.input.vcfs)
log = snakemak... |
a7bd54ed18340ba91b882616649bfa400fe34f5750425409bce7e62f231b5aa2 | Python | 530 | 17 | __author__ = "Johannes Köster"
__copyright__ = "Copyright 2016, Johannes Köster"
__email__ = "koester@jimmy.harvard.edu"
__license__ = "MIT"
from snakemake.shell import shell
# Samtools takes additional threads through its option -@
# One thread for samtools merge
# Other threads are *additional* threads passed to t... |
9032a0c3eaad900f5d26913462dd9dfe08521d83894e5be4947a3ff774d3bd8d | Python | 531 | 13 | from .approx_max_iou_assigner import ApproxMaxIoUAssigner
from .assign_result import AssignResult
from .atss_assigner import ATSSAssigner
from .base_assigner import BaseAssigner
from .center_region_assigner import CenterRegionAssigner
from .grid_assigner import GridAssigner
from .max_iou_assigner import MaxIoUAssigner
... |
bc10a07575cf56be09b2664f1dd808081f58073fa974380af5df98edfd93b9a3 | Python | 532 | 26 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
def add_path(paths):
if not isinstance(paths, (list, tuple)):
paths = [paths]
for path in paths:
if path not in sys.path:
sys.path.insert(0, path)
de... |
94d776d0b318ab919d88718f81d91e73f586f94ae1a99fc1491494d6096cb8a1 | Python | 533 | 10 |
# This recipe attaches different camera / sensors to a vehicle with different attachments.
# ...
camera = world.spawn_actor(rgb_camera_bp, transform, attach_to=vehicle, attachment_type=carla.AttachmentType.Rigid)
# Default attachment: carla.AttachmentType.Rigid
gnss_sensor = world.spawn_actor(sensor_gnss_bp, transfo... |
d2f7fb3e467421d48c555f82fea9a27b1077223cab6b95385b223a1cbe2b3aeb | Python | 533 | 15 | # This recipe turn visibility off and on for two specifc buildings on the map
# Get the buildings in the world
world = client.get_world()
env_objs = world.get_environment_objects(carla.CityObjectLabel.Buildings)
# Access individual building IDs and save in a set
building_01 = env_objs[0]
building_02 = env_objs[1]
obj... |
324243484fef1bab637d15f13ba4f906680b72b361138de6c3365a3be92278e7 | Python | 534 | 22 | from typing import List, Tuple
import os
import tmkit as tmk
from tmkit.topo import from_pdbtm, from_phobius, from_tmhmm
from . import dir_data, fin_fasta, fin_pdb
def test_read_from_fasta():
sequence = tmk.seq.read_from_fasta(fasta_fpn=fin_fasta)
assert len(sequence) == 362
assert sequence[0] == "A"
... |
6d3014d06665eb725344e98700eeb86b221bd13f18561f935a810ef3673ed9df | Python | 534 | 17 | import torch
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
class GCN(torch.nn.Module):
def __init__(self, hidden_channels, input_feat, classes):
super(GCN, self).__init__()
self.conv1 = GCNConv(input_feat, hidden_channels)
self.conv2 = GCNConv(hidden_channels, clas... |
6517e47d2ec3917756f788eea6931cad4dd2c5d77153cba09fe05b21cb8e104b | Python | 538 | 29 | # -*- coding: utf-8 -*-
"""
@author: Satoshi Hara
"""
import sys
sys.path.append('../')
import numpy as np
from AlternateLinearModel import AlternateLogisticLasso
# setting
seed = 0
num = 1000
dim = 2
dim_extra = 2
# data
np.random.seed(seed)
X = np.random.randn(num, dim + dim_extra)
for i in range(dim_extra):
... |
6caaf9fb09dfb3713023133db37ea2791e5ee2c623f697325b1e8d12d6f5817a | Python | 538 | 15 | # -*- coding: utf-8 -*-
from .config import ( INPUT_SHAPE, KERNEL_SHAPE,
POOLING_SHAPE, LEARNING_RATE, EPOCHS,
OPTIMIZER, LOSS_FUNCTION, STRIDE, BATCH_SIZE, MULTI_GPU,
DATA_SOURCES, N_LABELS, DEPTH, N_FILTERS, ACTIVATION, VALIDATION_FRACTION,
SPATIAL_DROPOUT_RATE, NORMALIZE_SAMPLES, SAMPLES_TO_PREDICT )
DEFAULT=0
... |
cd80a70a9d8977491e9faac11224265ad10d24f8761d64b1137d8ef8c6086fcf | Python | 540 | 21 | __author__ = "Aarthi Mohan"
__copyright__ = "Copyright 2021, Aarthi Mohan"
__email__ = "aarthi.mohan@sickkids.ca"
__license__ = "MIT"
from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
if not snakemake.threads:
threads = 8
else:
threads = snakemake.threads
shell(
... |
01d692fad867c7d54269e9df3ee2a08e25518e629de8023c89e468dfaba24ce7 | Python | 541 | 22 | from fvcore.common.registry import Registry
MODEL_REGISTRY = Registry("MODEL")
MODEL_REGISTRY.__doc__ = """
Registry for model.
The registered object will be called with `obj(cfg)`.
The call should return a `torch.nn.Module` object.
"""
LOSS_REGISTRY = Registry("LOSS")
LOSS_REGISTRY.__doc__ = """
Registry for loss f... |
5ba47f2349a1e189af1831bbf53beada4d18759f0677067ef00fd7d6a930c344 | Python | 541 | 18 | import torch.nn as nn
import torch.nn.functional as F
from pygcn.layers import GraphConvolution
class GCN(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout):
super(GCN, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.gc2 = GraphConvolution(nhid, nclass)
se... |
9f3c3bad0befbbaac0956994a5b4819609cc4beee82d661059d3f1b38c053e10 | Python | 541 | 32 | # Libraries
import pandas as pd
import numpy as np
# Load specific dataset
from sklearn.datasets import load_iris
# Load dataset
dataset = load_iris(as_frame=True)
# Show keys
print("\nKeys:")
print(dataset.keys())
# Label conversion
lblmap = dict(enumerate(dataset.target_names))
# Show label conversion
print("\nL... |
c5749153849b21e5dfe3bce0858bcf3bf8b9efbad705be7089ed4a75e0f3a953 | Python | 541 | 18 | import torch
from sklearn.metrics import confusion_matrix, f1_score
def accuracy(output, target):
with torch.no_grad():
pred = torch.argmax(output, dim=1)
assert pred.shape[0] == len(target)
correct = 0
correct += torch.sum(pred == target).item()
return correct / len(target)
... |
95ba6d1a5e16418d51a801bad298ebdca944b52dcf31190b801baa143e9c3477 | Python | 542 | 21 | import torch
import torch.nn as nn
import torch.nn.functional as F
class SpkClassifier(nn.Module):
def __init__(self, hp):
super().__init__()
self.mlp = nn.Sequential(
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(hp.chn.speaker.token, hp.chn.speaker.token),
... |
9f9bcdf0c586edf552ddadff411862013ed8b8c5dd8b05098ff39bb17222ca7a | Python | 542 | 16 | from collections import Iterator
from dataclasses import dataclass
import oaklib.datamodels.obograph as og
from oaklib.utilities.obograph_utils import index_graph_edges_by_subject, index_graph_edges_by_subject_object
@dataclass
class RelationGraphReasoner:
ontology: og.Graph = None
def get_non_redundant_edge... |
c0b19c998a384b11502f8741e0575b30cb31813f1f531dc7358dc2acdbaefcc5 | Python | 544 | 23 | import time
class RunTimer:
def __init__(self):
self.start_time = None
self.end_time = None
pass
def __enter__(self):
self.start_time = time.time()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.end_time = time.time()
print("... |
46f2eabedb137c9c0b5b170a94570dd8e911308100869982d6e0419aa3aa4fa5 | Python | 545 | 24 | __author__ = 'jieqing jiao'
__email__ = "jieqing.jiao@gmail.com"
import numpy as np
def srtm_theta2kp(theta):
# theta - output from models/srtmb
# theta[0] - linear coeff of input(Cr)
# theta[1] - linear coeff of the conv
# theta[2] - exp coeff (no -)
r1 = theta[0] # R1
k2 = theta[1] + theta... |
6eb6f9dc72b825826d5cce6ffc397af88750e55a9ec4bd38823d95211969870e | Python | 545 | 29 | #!/usr/bin/python3
"""
@author: Eduardo Romero
"""
import zipfile
import sys
import psutil
def check_process_done(pid):
try:
process = psutil.Process(pid)
return process.is_running()
except:
return False
if __name__ == "__main__":
pid = int(sys.argv[1])
filename = sys.argv[... |
f0ac62e46256a7cb06668e1aac8772c45243a21f88df196f2a3730162c8e87ee | Python | 545 | 13 | import os
import pandas as pd
df = pd.read_csv('datasets/simulator_classification_dataset_list.csv')
for i in range(len(df)):
df1 = pd.read_csv(df.Path.iloc[i])
if 'p' not in df1.columns:
df2 = pd.read_csv(os.path.join('models_predictions', os.path.basename(df.Path.iloc[i]).replace('.csv', '_predictio... |
c0ebc7febefef9b8f84804635bf5759682395dae8b48b7020f552c77575f4b2e | Python | 547 | 19 | '''
For convergence,
beUNPRE should reach the specified threshold.
Sometimes simulations fail to converge (and would take a lot of time before the simulations are aborted).
- We can extract data from many log files to a pandas dataframe => perform some analysis.
- We can also print some basic info: e.g. how many simul... |
e8586575b63892349cdf83ebd8e2eaed33421ddd7baac08af281f5bf5ba16796 | Python | 548 | 11 | from flask_restx import reqparse
search_arguments = reqparse.RequestParser()
search_arguments.add_argument('query', type=str, action="append", required=True)
search_arguments.add_argument('species', type=str, required=False)
search_arguments.add_argument('taxonomy', type=str, required=False)
search_arguments.add_argum... |
fdcc3bb28346a995e48275f1f55bbf8a226f7538734b33be1c9b5ba1ae7cc329 | Python | 548 | 24 | from ..resample import resample
import torch
def test_resample():
a = torch.randn(10, 20, 40, 50)
res_scale = [2, 3]
axis = [-2, -1]
b = resample(a, res_scale, axis)
assert b.shape[-1] == 3 * a.shape[-1] and b.shape[-2] == 2 * a.shape[-2]
a = torch.randn((10, 20, 40, 50, 60))
res_scale... |
d5b9e6fd15f7ad48c9666a2d0fd5540b7314938025bdd32cc6633be7ee89bf4d | Python | 550 | 15 | import pyreadr
import scanpy as sc
import pandas as pd
result = pyreadr.read_r('/share/quonlab/workspaces/ruoxinli/multitask_/data/iPSC_neuronal/FPP/regress_cellcycle_expid_selected_cells_genes.rda')
hvgs_rita = result['HVGsel_tmp'].values.reshape(-1)
df = pd.read_csv('data/D11/experiment/FPP/hvg.csv',index_col=0)
hv... |
03d64940af5cc3fceac117bbe181d434074d269c7b0143cb06d12e07e8b2ff86 | Python | 551 | 17 | """setup for python"""
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(name='roipool3d',
ext_modules=[
CUDAExtension('roipool3d_cuda', [
'src/roipool3d.cpp',
'src/ms_ext.cpp',
'src/roipool3d_kernel.cu',
... |
5b885c032ffdf68e70b83e41b46fa8884071c9d78502f3697545cc98e264d583 | Python | 551 | 22 | import torch
import torch.nn.functional as F
from .core import Distribution
class Multinomial(Distribution):
def __init__(self, log_probs):
super().__init__()
self.log_probs = log_probs
def sample(self):
inds = torch.multinomial(torch.exp(self.log_probs), 1)
samples = torch... |
72dd13d1a2286d0c112ca9028bb151e467d06ac05bf8900d22d7a5bedd8b2ec4 | Python | 551 | 23 | from snakemake.shell import shell
import os.path
from os import path
extra = snakemake.params.get("extra", "")
vcf = snakemake.input[0]
shell(
"bcftools stats -s - {vcf} > {snakemake.output[0]}"
)
#rename sample name in output file
dir = os.path.dirname(snakemake.output[0])
base = path.basename(snakemake.outp... |
b9bd02af7357bcf9b056bf668b20af37dfec22ec64bcd5c9d6d95ed2d9f7619c | Python | 551 | 19 | from http import HTTPStatus
class BDSApiException(Exception):
default_status_code = HTTPStatus.BAD_REQUEST
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_cod... |
3e4f508b2a62a2b11769fd69907999475d398fe6f53be51dc37444bc71d04835 | Python | 552 | 26 | """
Utilities for geometry etc.
"""
import torch
def transform_vectors(matrix: torch.Tensor, vectors4: torch.Tensor) -> torch.Tensor:
"""
Left-multiplies MxM @ NxM. Returns NxM.
"""
res = torch.matmul(vectors4, matrix.T)
return res
def normalize_vecs(vectors: torch.Tensor) -> torch.Tensor:
... |
957b7a7f6cdf78684eb44e4c3ac4a91958b080e4018deb49acd513823cd3f2b2 | Python | 552 | 24 | #!/usr/bin/env python
import subprocess
import sys
threshold_method_gui = {
"autolocal": "segment_autolocal_bokeh.py",
"fixed": "segment_fixed_gui.py"
}
if __name__ == "__main__":
threshold_method = sys.argv[1]
file_name = sys.argv[2]
print(f"Starting boke server for {threshold_method}"... |
a942e3ca83f25081c6107a8340b7b7765e338de8615236b7a6af003a0842f536 | Python | 552 | 20 | import torch
if torch.__version__ == 'parrots':
import parrots
def get_compiler_version():
return 'GCC ' + parrots.version.compiler
def get_compiling_cuda_version():
return parrots.version.cuda
else:
from ..utils import ext_loader
ext_module = ext_loader.load_ext(
'_ext', ... |
aa25bc3562b331f0eaaf28a3dff2d7217369bfcc86e3c401ba1c72958eecbbc9 | Python | 552 | 23 | import random
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
G = nx.barabasi_albert_graph(100, 1)
node_idx = random.choice(list(G.nodes))
edges = nx.bfs_edges(G, node_idx, depth_limit=1)
e = list(edges)
#print(list(edges))
nodes = np.unique(e)
print(nodes)
subG = nx.Graph()
subG.add_nodes_fr... |
1c4a5f1edab18522bb4f14f45fea17fbdda4dcce651d95551f8fbb33f60ffe7d | Python | 553 | 30 | import sys
input = sys.argv[1]
output = sys.argv[2]
print("in: "+input)
print("out: "+output)
fh = open(input,'r')
fho = open(output, 'w')
lnctr = 0
written = 0
for line in fh:
line = line.strip()
while " " in line:
line = line.replace(" "," ")
elems = line.split()
if lnctr == 0:
fho.write(line+"\n")
els... |
47360f2063831f39af1e6cce04cdc06c69afc4ca7e9930eaa7c5abffa677f3bb | Python | 553 | 17 | from setuptools import setup
from setuptools import find_packages
setup(name='pygcn',
version='0.1',
description='Graph Convolutional Networks in PyTorch',
author='Thomas Kipf',
author_email='thomas.kipf@gmail.com',
url='https://tkipf.github.io',
download_url='https://github.com/tki... |
814b9764d75e6f3f64358ba8ee492b703c9b8e33ebb73e0d0b86246c5b5abedc | Python | 553 | 17 | from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
shell(
"(configManta.py "
"--runDir {snakemake.params.outdir} "
"--reference {snakemake.input.fasta} "
"--bam {snakemake.input.bam} "
"{snakemake.params.include_chroms}; "
"cd {snakemake.params.outdir}; "... |
ddb51043b91baa440a608767c5036ff1bf80c5b5cc63f9a5912d81714458f70c | Python | 553 | 22 | # GENERATED by harness/registry.py in the oxynet orchestration repo. Do not edit.
# Sources: registry/brand.toml (authored), registry/core-surface.json (extracted from
# oxynet-core). Change the source, then run `python3 harness/registry.py sync`.
BRAND = {
"background": "#0a0a0a",
"surface": "#121212",
"b... |
0d84add68162b0c38036585fd9c45f35b6b74f69821e53d963521dee62d7adc7 | Python | 554 | 29 | # -*- coding: utf-8 -*-
"""
@author: Satoshi Hara
"""
import sys
sys.path.append('../')
import numpy as np
from EnumerateLinearModel import EnumLasso
# setting
seed = 0
num = 1000
dim = 10
dim_extra = 3
# data
np.random.seed(seed)
X = np.random.randn(num, dim + dim_extra)
for i in range(dim_extra):
X[:, dim + i... |
27b92c763a9a5c8d42b66773c0d57dc682cd660b03ca0df2be6cc46e3f40ce47 | Python | 554 | 15 | from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
java_opts = snakemake.params.get("java_opts")
shell(
"export _JAVA_OPTIONS=\"{java_opts}\" && "
"rtg vcfsubset -i {snakemake.input} -o annotated/{snakemake.wildcards.p}/vcfanno/noDP.vcf.gz --remove-info DP && "
"bc... |
3076f76a966cc08c79c15c35260f3d8a73563ee1d34b623cc0c9162476e71510 | Python | 554 | 18 | import importlib
import modeltest.settings as settings
from modeltest.settings import *
from modeltest.plot import plot
def print_info():
print("Using DrugEx version: ", DRUGEX_VERSION)
print("Experiment ID: ", EXPERIMENT_ID)
print("Settings:")
# print variables in this module
for var in [x for x i... |
4b84a786fa5dd5d0f3b44f6fe974700caf6e7f711662efd473f789ea4c010489 | Python | 555 | 29 | #!env python
import sys
import numpy as np
import scipy as sp
import dit
import scipy.io
from dit.pid import PID_BROJA
fname = sys.argv[1]
dat = sp.io.loadmat(fname)
P = np.squeeze(dat['P'])
s = P.shape
Nvar = len(P.shape)
if Nvar != 3:
raise ValueError("not supported")
d = dit.Distribution(*zip(*np.ndenumerate(... |
9876c2da8fe892c6a6daad959283b368e9471f92f4d3b2724cfbb90612a58c8f | Python | 555 | 18 | """
This module contains classes and methods for target feature classes.
These are classes which define a way to access a "target feature" such
as a label or annotation on an input sequence.
"""
from .target import Target
from .genomic_features import GenomicFeatures
from .q_genomic_features import qGenomicFeatures
fro... |
bcea1e0b80cd7d612e7deef859758e2126de74d215eee5ffa9b1b10862130de5 | Python | 555 | 18 | import os
import sys
def main(path):
fids = []
for fname in os.listdir(path + '/decoded'):
fid = fname.replace('_decoded.txt', '')
fids.append(fid)
for fid in fids:
try:
candidate = open(path + '/decoded/{}_decoded.txt'.format(fid)).read()
ref = open(path + '/reference/{}_reference.txt'.f... |
ec07deda1d2c1daea2f50220dc7d461e4e023be47efc934798c104fae2085489 | Python | 555 | 19 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Variational Animal Motion Embedding 0.1 Toolbox
© K. Luxem & P. Bauer, Department of Cellular Neuroscience
Leibniz Institute for Neurobiology, Magdeburg, Germany
https://github.com/LINCellularNeuroscience/VAME
Licensed under GNU General Public License v3.0
"""
import... |
170b252e011ab923d7812aa7165108eecbf23f8efce3e944d7b079bc8288fcef | Python | 557 | 23 | from PyInstaller.utils.hooks import collect_all
def hook(hook_api):
packages = [
'tensorflow',
#'tensorflow_core',
#'astor'
]
for package in packages:
datas, binaries, hiddenimports = collect_all(package)
hook_api.add_datas(datas)
hook_api.add_binaries(binar... |
2dc0ff86a0a1c08692a59940814b450c44fa25049a8da12cc3cbafaa9bff43e1 | Python | 557 | 19 | def parse_net_config(net_config):
if isinstance(net_config, list):
return net_config
elif isinstance(net_config, str):
str_configs = net_config.split('|')
return [eval(str_config) for str_config in str_configs]
else:
raise TypeError
def load_net_config(path):
w... |
94fc3cf60d7c41434203e052ac7094c9a8e81374b25d67257817f9e631c95d78 | Python | 557 | 20 | import numpy as np
def compute_density(adjacency, loops=False):
n_edges = np.count_nonzero(adjacency)
n_nodes = adjacency.shape[0]
n_possible = n_nodes ** 2
if not loops:
n_possible -= n_nodes
return n_edges / n_possible
def compute_density_adjustment(adjacency1, adjacency2):
density... |
ef696a04fdc19a3ad6f140ea01f5a390c51ec743b385840111e849730772de4a | Python | 558 | 26 | import cProfile
import os
import pstats
import mne
import numpy as np
import eelbrain
from eelbrain import *
fname = 'profile_of_connectivity.profile'
mne.set_log_level('warning')
eelbrain._stats.testnd.multiprocessing = False
ds = datasets.get_mne_sample(-0.1, 0.2, src='ico', sub="modality == 'A'")
code = '''
res... |
599982451f146432bad2d5ee036826633c538facfd034f4b8fbaf66ec838ac12 | Python | 559 | 16 | from scripting.spectrum.io import persist
from scripting.sleep.metrics import get_distribution
#path to the saved dataset pickle
DPATH = '/home/guest/Desktop/sleep_dataset.pkl'
GROUP = 'd' #'a','b','c', or 'd'
NUM_SEG = 12
dset = persist.pkl_load(DPATH)
#dist --> state x segment x animal
#states are always artifac... |
7f59340ea995be328e7f8f60d62b7f8e4d204305e86b3872fe1e111702cf2369 | Python | 559 | 32 | # Libraries
import pandas as pd
import numpy as np
# Load specific dataset
from sklearn.datasets import load_breast_cancer
# Load dataset
dataset = load_breast_cancer(as_frame=True)
# Show keys
print("\nKeys:")
print(dataset.keys())
# Label conversion
lblmap = dict(enumerate(dataset.target_names))
# Show label con... |
c1fb7b06ef399b1c58f7f8d610831ba7042a7cab61d881bb4b6923f02342f193 | Python | 559 | 25 | """Exceptions used throughout Eelbrain"""
class DefinitionError(Exception):
"MneExperiment definition error"
class DimensionMismatchError(Exception):
"Trying to align NDVars with mismatching dimensions"
class WrongDimension(Exception):
"Dimension that is supported"
class IncompleteModel(Exception):
... |
8ad2b468e6cfbd9dc5a4688f640396e6e2824a829143fb62f4d7e54f671bfe07 | Python | 560 | 18 | import zarr
import sys
import napari
raw = zarr.load(sys.argv[1], path="volumes/raw")
gts = zarr.load(sys.argv[1], path="volumes/gt_instances")
viewer = napari.Viewer(ndisplay=3)
for idx, gt in enumerate(gts):
viewer.add_labels(
gt, rendering='translucent', blending='additive', name=f'gt_{idx}')
viewer.... |
f7ec01703e296d9840c7f0ea46e7599826e51a85a5a4c4e2bf513cc46f25233b | Python | 560 | 11 | IMG_CVPATH = "gs://microns_public_datasets/pinky100_v0/son_of_alignment_v15_rechunked"
SEG_CVPATH = "gs://microns_public_datasets/pinky100_v185/seg"
CLF_CVPATH = "matrix://sseung-archive/pinky100-clefts/mip1_d2_1175k"
MITO_CVPATH = "matrix://sseung-archive/pinky100-mito/seg_191220"
NUC_CVPATH = "matrix://sseung-archive... |
99f14e50ec5bbcc8ce123d7456f9b569c5b50f68379ada0fed0b0bd5b8176142 | Python | 561 | 22 | __author__ = "Johannes Köster"
__copyright__ = "Copyright 2018, Johannes Köster"
__email__ = "johannes.koester@protonmail.com"
__license__ = "MIT"
import os
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
java_opts = snakemake.params.get("java_opts", "")
gvcfs = list(map("-V {}".format,... |
a18d76e3e3a7caf2f51f9374fa80cb32049a43a5c9a831baec517651973cb2ec | Python | 562 | 29 | # -*- coding: utf-8 -*-
"""
@author: Satoshi Hara
"""
import sys
sys.path.append('../')
import numpy as np
from EnumerateLinearModel import EnumLasso
# setting
seed = 0
num = 1000
dim = 10
dim_extra = 3
# data
np.random.seed(seed)
X = np.random.randn(num, dim + dim_extra)
for i in range(dim_extra):
X[:, dim + i... |
69fda29179c9f5ec68bda02c34092f8bac2f4a87f679f61e95e742187b4bef22 | Python | 563 | 20 | __version__ = "0.1.1"
# Check for OpenMM installation
try:
import openmm
except ImportError:
import warnings
warnings.warn(
"\n"
"OpenMM is not installed. Polychrom requires OpenMM for molecular dynamics simulations.\n"
"\n"
"Please install OpenMM with the appropriate backe... |
b9f106b98e42bcd77301f102c3db87fc195a9cad08aaea83dd01950a822f7261 | Python | 564 | 21 | import nibabel as nib
import glob
import os
def get_masked_image(img_path, mask_path, masked_img_path):
''' Applies brain binary mask to nii.gz image'''
# load main image
zmap = nib.load(img_path)
img_data = zmap.get_data()
# load anothor image to mask
mask = nib.load(mask_path)
mask_data... |
ded2928ba23d1a34b148d54a9b024469900431f02c98aeba66484691e158d676 | Python | 566 | 28 | #!/usr/bin/env python
from setuptools import setup, find_packages
project_name = "simphox"
setup(
name=project_name,
version="0.0.1a8",
packages=find_packages(),
install_requires=[
'numpy',
'scipy',
'pandas',
'jaxlib',
'jax',
'scikit-image',
'pyd... |
64d5fbe0a1cbf8029f543a238e2eb684a4a694996ac23446ac711798be7d2d62 | Python | 567 | 26 | #%%
import pandas as pd
import numpy as np
from graspy.embed import ClassicalMDS
import seaborn as sns
from sklearn.metrics import pairwise_distances
data_loc = "maggot_models/data/external/17-08-26L6-allC-cl.csv"
ts_df = pd.read_csv(data_loc, index_col=None)
ts_mat = ts_df.values.T
# %% [markdown]
# #
corr_mat = pai... |
fb31caf88cc5aba855f033d09e6e0faf715c4a1a1eff87d5580a076715146370 | Python | 569 | 21 | from collections import Iterator
from dataclasses import dataclass
import oaklib.datamodels.obograph as og
# from oaklib.utilities.obograph_utils import (
# index_graph_edges_by_subject,
# index_graph_edges_by_subject_object,
# )
@dataclass
class RelationGraphReasoner:
ontology: og.Graph = None
def... |
1135f3e5a8e22ca7938ee307568e08b6d124b193bcbcfb78a8f28bfc787bdc76 | Python | 570 | 24 | __author__ = "Aarthi Mohan"
__copyright__ = "Copyright 2021, Aarthi Mohan"
__email__ = "aarthi.mohan@sickkids.ca"
__license__ = "MIT"
from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
if not snakemake.threads:
threads = 8
else:
threads = snakemake.threads
filters = ... |
b0218661f8266ce0423626ccb16a6d30cc4ebd3a49b26ef419c28423d4b88977 | Python | 571 | 22 | import torch
import networkx as nx
from graphxai.utils import khop_subgraph_nx
from graphxai.datasets import BAShapes
class Hyperparameters:
num_hops = 2
n = 30 # Invalid for bound
m = 1 # Invalid for bound
num_shapes = 5 # Invalid
shape_insert_strategy = 'bound_12'
shape_upper_bound = 1
s... |
d2df19e2791106baf78443cc9a6fa56d077eabe2e521e6014eba28bd8702bc74 | Python | 572 | 20 | import unittest
from linkml_runtime.loaders import json_loader
from oaklib.datamodels.obograph import GraphDocument
from tests import INPUT_DIR
ONT = INPUT_DIR / "go-nucleus.json"
class OboJsonParserTest(unittest.TestCase):
"""Tests parsing OBO JSON directly."""
def test_parser(self):
"""Tests par... |
7fd6256f1982f722946e720701afdd7127704bfb227f9677b1c62cd2e1de2c73 | Python | 574 | 10 | """ Parameters used throughout the analysis """
cooled_threshold = 20 # Temperature below which cortex is considered to be 'cooled'
warm_threshold = 35 # Temperature above which cortex is considered to be 'warm'
min_level = 50 # Min sound level used
min_trials = 10 ... |
e6792833a80ea19baca4fdfa714da36bfa2da2ca26df471789ffffab182d096e | Python | 574 | 7 | from ._experiment.mne_experiment import MneExperiment
from ._experiment.preprocessing import RawSource, RawFilter, RawICA, RawMaxwell, RawReReference, RawApplyICA
from ._experiment.epochs import PrimaryEpoch, SecondaryEpoch, SuperEpoch
from ._experiment.groups import Group, SubGroup
from ._experiment.parc import SubPar... |
7233620dc2b5a5688275deb02ca092ad40e71d4e6c25f2031338ec777afc0aa4 | Python | 575 | 32 | import gzip
import sys
## replaces duplicate IDs in SNPs.txt.gz with id_number
infile = sys.argv[1] # SNPs.txt.gz with ids
outfile = sys.argv[2] # Output filename prefix
fh = gzip.open(infile,'rt')
fho = gzip.open(outfile+".txt.gz",'wt')
set = set()
for line in fh:
# dostuff
# 1_10497_C_T_b37
outid = line.rtri... |
a388e88ba1bec36b3dea4c849f4f6269835037194e477f9f44be7ffdf8f230cb | Python | 576 | 22 | import os
import pandas as pd
import tmkit as tmk
from . import dir_data
# def test_rrc_read():
# df1, df2 = tmk.rrc.read(
# prot_name="1xqf",
# seq_chain="A",
# fasta_fp=os.path.join(dir_data, "fasta/"),
# pdb_fp=os.path.join(dir_data, "pdb/"),
# xml_fp=os.path.join(dir_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.