sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
17bdb6fa39befd3bc982c8ce39eba523cb6ec97c39c570824bbcbbbbf4b98a96 | Python | 3,896 | 83 | from train_synergy import *
import argparse
import optuna
import uuid
def train_model_optuna(trial, config):
"""Wrapper function that produces trials using Optuna
trial: the instance optuna passes to each trial
config: The configuration object"""
def optuna_step_callback(epoch, train_r):
"""
... |
2f7fafe093ec6b395a82795920758d036edc4a1773503e62b1c8389a8270c4d3 | Python | 3,898 | 89 | # similar to plot_torus_size, but instead of data and shuffle_data, this plot data and ideal iid grid cell data
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from grid_cell.slope_ploter import SlopeAnalysis, draw_two_line_data, add_small_noise, draw_two_line_data_boot
import hick... |
468badfb3c0fa304d8b810ad92b485e3ba1dacdeb13029d5f581f221a0e08e2a | Python | 3,900 | 130 | #!/usr/bin/env python
"""
MetaWIBELE: metadata_format module
Format the metadata info
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without ... |
701d72be570039f652cb23b09c98ed7c4fdf292ae575f322474e55d3722b5ec0 | Python | 3,900 | 145 | import importlib
from typing import Dict, Any, Optional
import sys
from os import path
import re
import requests
import yaml
import json
import logging
from kgx.graph.base_graph import BaseGraph
config: Optional[Dict[str, Any]] = None
logger: Optional[logging.Logger] = None
graph_store_class: Optional[BaseGraph] = ... |
70d43402fc67acda18b0eede835142783d60e9f4dcc5891d49ffdb142ca595c6 | Python | 3,900 | 117 | import numpy as np
import matplotlib.pyplot as plt
from scipy.sparse import issparse
def loss(losses, last=200):
plt.figure(figsize=(8, 3.5))
plt.subplot(1, 2, 1)
plt.plot(losses)
plt.xlabel("iterations")
plt.ylabel("loss")
plt.subplot(1, 2, 2)
plt.plot(range(len(losses)-last, len(losses))... |
9b6be9dfe32c82fecd2c531ba1cbf8a34131aaaec12a8207fc70af1279692ca4 | Python | 3,900 | 115 | ## Restormer: Efficient Transformer for High-Resolution Image Restoration
## Syed Waqas Zamir, Aditya Arora, Salman Khan, Munawar Hayat, Fahad Shahbaz Khan, and Ming-Hsuan Yang
## https://arxiv.org/abs/2111.09881
import os
import numpy as np
from glob import glob
from natsort import natsorted
from skimage import io
im... |
1fd283631cc629bea3ae880719c5e173dd72d1ebf32a88b326c4147f1cba2836 | Python | 3,903 | 124 | """
Computes and saves bootstrapped distributions of normalizers
(both True & Null distributions) for neural datasets.
Args:
dataset_name: str ['ucsf', 'ucdavis'], -d
bin_width: list of int, -b
mVocs: bool, default=False, -v
session_index: int, default=0, -s
num_itr: int, default=100000, -n
Ex... |
ac160ae87ce0d335d9e368d85ca8a9649dbca1e45c5b82f0ecf497fbddf2a2f8 | Python | 3,903 | 125 | import shutil
from pathlib import Path
import h5py
import numpy as np
import pytest
from bokeh.document import Document
from bokeh.io.doc import set_curdoc
from guppy.testing.api import (
locate_run_folder,
remove_artifacts,
select_artifact_windows,
step1,
step2,
step3,
step4,
)
from guppy... |
d161146b00e83745add2a7b232f2c3ea6daff0266dbd98fed98456e654543eac | Python | 3,903 | 118 | import argparse
import os
import json
from assets.factory import storage_manager, key_manager
from utils import untar
from crypto import SymmetricEncryption, get_file_hash, get_folders_hash, get_string_hash
decryption = SymmetricEncryption()
decryption.check()
def __check_folder_hash(folder_path: str, expected_hash:... |
a9e5c03fec50661f36f2507862a57ed6516ec48cb16791b1433903a8f1ca0fcf | Python | 3,904 | 95 | import os, h5py, sys
import numpy as np
import pytraj as pt
from nearl.io import Trajectory
import nearl.io, nearl.featurizer, nearl.features
class MisatoTraj(Trajectory):
def __init__(self, pdbcode, misatodir, **kwarg):
# Locate the topology and trajectory files based on the directory of MISATO dataset
... |
fd948af4d7f6858607bb6c293775bee4df4f802305e18bcdc0e94d5c7f822b8e | Python | 3,906 | 114 | # -*- coding: utf-8 -*-
# Albert Cardona 2015-02-03
# This file is meant to be run from within ./manager.py shell in the environment, like:
# [1] load 'export_all_annotations.py'
# [2] project_id = 12
# [3] export(project_id, "all", "all")
from django.db import connection
from django.db import transaction
import gzip... |
4eef24b46ac1bf76d4651de41c421463445bf941242a93790a4625ec514ad539 | Python | 3,908 | 91 | import tifffile
from PyQt5 import QtWidgets, QtCore
import numpy as np
from threads.Worker import Worker
from model.Source import Source
from features.MovementCorrection import MovementCorrection
class TIFLoader():
def __init__(self, data_manager, filepath):
"""
Starts the ProgressDia... |
2cd4f011fb1c94653035880b6f7ec7cbffd757ee5f11f00897573ccd62682bed | Python | 3,909 | 94 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
3e0c9dae28156f6d5d8b69e3032dd25e4c42a1ef7da031167fc6b8371f02cee4 | Python | 3,910 | 88 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmcv.ops import point_sample
from torch import Tensor
def get_uncertainty(mask_preds: Tensor, labels: Tensor) -> Tensor:
"""Estimate uncertainty based on pred logits.
We estimate uncertainty as L1 distance between 0.0 and the logits
predic... |
dea7b8ef45cc1aab60e3fb40324b6feee608a1c2be70860bb91d96ce660a80c9 | Python | 3,912 | 109 | # datatest.py
#
# Run data i/o tests on SNAP
#
# There are 3 possibilities for input:
# FQ |SAM | BAM
#
# There are 2 references datatest.fa and datatest2.fa (with an extra refseq)
#
# There are 2 possibilities for output:
# SAM | BAM
#
# There are four possible reference files for output
# FQ | SAM input file (BAM i... |
8bc2fcb4462ce8372ed70957d485207ae5d93dc04bd533b7fabfbc3a4c708e7d | Python | 3,914 | 105 | # -*- coding: utf-8 -*-
"""Reuters topic classification dataset.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ..utils.data_utils import get_file
from ..preprocessing.sequence import _remove_long_seq
import numpy as np
import json
import warnings
... |
e89534e8a6a42c283f1cb7f599c1b68c93d3d857124494da14cd8639706313cd | Python | 3,914 | 100 | from rest_framework import serializers
from django.utils import timezone
from django.conf import settings
from .models import TrainingExperiment
class WriteTrainingExperimentSerializer(serializers.ModelSerializer):
class Meta:
model = TrainingExperiment
fields = "__all__"
read_only_fields ... |
f9f205a1940547258b02ee1de15bf9905ebccad242ab6c1aea896e41bbdccb29 | Python | 3,914 | 121 | #!/usr/bin/env python
"""
MetaWIBELE: format_contig_sequences module
Format contigs sequence info
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Softwa... |
2a01a3ac591f0971ac1e9eb8a98df9cdc9b94fff2dc501ef83edd13a38e3f8d7 | Python | 3,916 | 142 | """
Confirm that we can subclass and/or serializae certain classes used by 3rd parties.
Especially if those classes are (or become) compiled with mypyc.
"""
import pickle
import pytest
from ruamel.yaml.comments import CommentedMap
from schema_salad.avro import schema
from cwltool.builder import Builder
from cwltool... |
2a3ffa8250d146de1b61a3390d72c07fc3722f6fa67c8d7d56060db563bfbd9e | Python | 3,919 | 103 | # 3D Convolutional Neural Network is adoped from atom3d package
# https://github.com/drorlab/atom3d/blob/master/atom3d/models/cnn.py
from collections import OrderedDict
from torch import nn
class Atom3DNetwork(nn.Module):
"""Base 3D convolutional neural network architecture for molecular data, consisting of six... |
72006c2541fae83edeb9450b2b35ae02a13503fb6de118bcd03b41deac9e7716 | Python | 3,921 | 122 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional, Union
import torch
import torch.nn as nn
from torch import Tensor
from mmseg.registry import MODELS
from .utils import weight_reduce_loss
def silog_loss(pred: Tensor,
target: Tensor,
weight: Optional[Tensor] =... |
0fbfce742349c2d06c0325ec949f31a55d877f09ec8b209c57b155535f90741b | Python | 3,922 | 122 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmseg.registry import MODELS
from ..utils import resize
from .decode_head import BaseDecodeHead
class ASPPModule(nn.ModuleList):
"""Atrous Spatial Pyramid Pooling (ASPP) Module.
Args:
... |
bdf4c7d36227b40e0c752830c1783fcc277bddc021ddea27af8aaaf19ef9f1d6 | Python | 3,922 | 113 | """Labels image metadata."""
import pathlib
from typing import Optional, Sequence
from magmap.io import libmag, yaml_io
from magmap.settings import config
_logger = config.logger.getChild(__name__)
class LabelsMeta:
"""Labels image metadata container and I/O.
Attributes:
prefix: Path prefix fo... |
bc0545ac53c9c430cabfc4dfe3d51542617a1b8a4ec9760c64fea8c9c8473f63 | Python | 3,923 | 81 | import torch
import gradio as gr
import numpy as np
from transformers import T5Tokenizer, T5EncoderModel
import esm
from inference import load_models, predict_ensemble
from transformers import AutoTokenizer, AutoModel
import spaces
# Load trained models
model_protT5, model_cat = load_models()
# Load ProtT... |
0a53f51dfc75657564f28fc7f90724ee0c7789807bd48a32bb13b3ee4c28a4dd | Python | 3,929 | 142 | """Authentication utilities for ZnDraw client.
Provides credential validation and auth helper functions.
Token resolution chain (stored token, local_token) is handled by
the pydantic-settings source chain (StateFileSource).
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
impor... |
78d64071f43602ed56e67c1ec19e850db0342544656394788618d93e28dd1a72 | Python | 3,929 | 108 | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
import tempfile
import shutil
import os
import numpy... |
7c6b30e58c0b32e923166b30b535b4230b4a9189c58d7d988b440246930354db | Python | 3,933 | 143 | #!/usr/bin/env python3
from multigrid import (
Multigrid,
MultigridOp,
SparseOperator,
MultiIndex,
StencilDict,
get_shift_csr,
ModNumpy,
ModTensorflow,
ModCupy,
)
import multigrid
from multigrid_plot import plot_3d, plot_grid, plot_grid_matrix
import numpy as np
import scipy.sparse ... |
b2bf5a4553cfb8f39acf308b026ef31c4ce36606fd772ad33492fb832585e8d8 | Python | 3,934 | 117 | from langchain.prompts import PromptTemplate
from langchain.chains import RetrievalQA
from langchain.vectorstores import Chroma
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory
from langchain.chat_models import ChatOpenAI
import sys
sys.path.append('/Users/... |
41859c1592347a44efe962db9fd3841f55f63ddbe272ce06fdddd46a8ac8a845 | Python | 3,935 | 93 | """Regression test for NPM decomposition-parameter persistence across Step 1 → Step 2.
NPM demultiplexes in memory, so the Step-1 choices (event splitting, the session's timestamp
unit and column) are persisted to the output dir as ``.npm_params.json`` and reloaded in Step 2.
This guards the GUI flow where Step 2 does... |
66416da839e7a9b816f55aaeb51fbb1a51ee402a05e68555a214dbcdbebf35d6 | Python | 3,936 | 118 | """Socket.IO room_join tests under the new scope model."""
import pytest
import socketio as socketio_lib
from httpx import AsyncClient
async def _register_and_login(client: AsyncClient, email: str) -> str:
"""Register via REST and return JWT."""
await client.post(
"/v1/auth/register", json={"email": ... |
eda62193913314e74c948289a65af516addb106367674595ca88073c875298cc | Python | 3,937 | 77 | # compute the single neuron noise to signal ratio
import numpy as np
import matplotlib.pyplot as plt
import os
from grid_cell.grid_cell_processor import Grid_Cell_Processor
from grid_cell.speed_partition_processor import Speed_Partition_Processor
from scipy.stats import binned_statistic_2d
from grid_cell.ploter import ... |
0becc2802831a32e620208c1417bad915e168c50b48095981795cedfa4832a9d | Python | 3,941 | 118 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# If you have a skeleton that has multiple root nodes,
# this script will attempt to fix that.
# You may need to install psycopg2, e.g. with:
# sudo apt-get install python-psycopg2
# Requires the file .catmaid-db to be present in your
# home directory, with the followi... |
bb95708bdbf27280cc39165eb55a48a87a9238c4da3147b7fae4db09a908fb59 | Python | 3,943 | 98 | import numpy as np
from dante.obj_functions import *
import os
# import argparse
# parser = argparse.ArgumentParser(description='Process inputs')
# parser.add_argument('--func', help='specify the test function')
# parser.add_argument('--dims', type=int, help='specify the problem dimensions')
# parser.add_argument('--s... |
21e4fc2652dc32c38f28b951044100d308ae4f6809d9f20c5a3c13381212844f | Python | 3,944 | 104 |
baseFileName = './shellScripts/sparse050_10class_noise_base_'
baseSimTag = 'sparse050_10class_noise_base_'
def generateCommand(trial_num=0,
num_trials=10,
learning_rate=0.001,
sim_tag='default',
exc_hid_rat=0.5,
epochs=30,
log_file='example.log',
w1_std=-1,
... |
57e842938340054132192f34b6e1fe51ddbe80dde2b5cb769241d5f19e2cf896 | Python | 3,944 | 104 |
baseFileName = './shellScripts/sparse095_10class_noise_base_'
baseSimTag = 'sparse095_10class_noise_base_'
def generateCommand(trial_num=0,
num_trials=10,
learning_rate=0.001,
sim_tag='default',
exc_hid_rat=0.5,
epochs=30,
log_file='example.log',
w1_std=-1,
... |
67d11a7d3ab2964c202155e099159090b651b1137f598905f8f0951392343706 | Python | 3,944 | 104 |
baseFileName = './shellScripts/sparse100_10class_noise_base_'
baseSimTag = 'sparse100_10class_noise_base_'
def generateCommand(trial_num=0,
num_trials=10,
learning_rate=0.001,
sim_tag='default',
exc_hid_rat=0.5,
epochs=30,
log_file='example.log',
w1_std=-1,
... |
82f7b41505382b3ec33509b68d8602ae53a80d72f2511b623ef92f98f557520c | Python | 3,944 | 65 | import argparse
class TrainOptions():
def __init__(self):
self.parser = argparse.ArgumentParser()
# data loader related
self.parser.add_argument('--dataroot', type=str, default='./datasets/MSRS', help='path of data')
self.parser.add_argument('--phase', type=str, default='train', help='phas... |
fd4612aacb6e3a1227388d403fb939f3b55f089a94fa6de733507d624897e925 | Python | 3,944 | 104 |
baseFileName = './shellScripts/sparse080_10class_noise_base_'
baseSimTag = 'sparse080_10class_noise_base_'
def generateCommand(trial_num=0,
num_trials=10,
learning_rate=0.001,
sim_tag='default',
exc_hid_rat=0.5,
epochs=30,
log_file='example.log',
w1_std=-1,
... |
24a884a3ae593f76474afef5059da649e8e87b6c2735c3eece816d658c034161 | Python | 3,945 | 104 | import torch
import pandas as pd
import time
import torch.nn as nn
import os
# Assuming device is set for GPU or CPU
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print("Using device:", device)
class MLPModel(nn.Module):
def __init__(self, input_size=1024, hidden_sizes=[512, 256, 128], o... |
bbe9e55a52c09df86947cf56664b7d343db9c1805e528d06b8f4146492ff3c7f | Python | 3,945 | 126 | # -*- coding: utf-8 -*-
import textwrap
from abc import ABC
from django.db import connection
from django.test import TestCase, TransactionTestCase
from django.test.client import Client
from catmaid.apps import get_system_user
from catmaid.models import Project
from catmaid.control.project import validate_project_setup... |
0f47527f7aa96ea3aa760b127e5813455c7671512a9a1f556077a371408d7bbc | Python | 3,947 | 138 | import os
from typing import Dict
import numpy as np
import pytest
import xgboost
from xgboost import testing as tm
from xgboost.testing.ranking import run_normalization, run_score_normalization
pytestmark = tm.timeout(30)
def comp_training_with_rank_objective(
dtrain: xgboost.DMatrix,
dtest: xgboost.DMatr... |
a0f2ee2c12acde1463cd68ed43ee3a2850ae206257048a82299edaddb49b2f25 | Python | 3,947 | 142 | from lib.datasets.heartdataset import HeartDataset
def get_mean_std(value_scale, dataset):
assert dataset in ["hcm_hv_LGE_v4"]
if dataset == "hcm_hv_LGE_v4":
mean = [0.047]
std = [0.903]
mean = [x * value_scale for x in mean]
std = [x * value_scale for x in std]
return mean, std... |
e3e100e6dfc163a26590a7ac605d9fa27704dfd3b9b94b5d4102eed34d065be2 | Python | 3,947 | 115 | """BrainGlobe model for integration in MagellanMapper"""
from requests.exceptions import ChunkedEncodingError, ConnectionError
import shutil
from typing import Callable, Dict, Optional
try:
from brainglobe_atlasapi import bg_atlas, descriptors, list_atlases
except ImportError:
# BrainGlobe Atlas API package w... |
5707827fb4270469c6f29a76fa2aa4dd2199782c91000f611c3df15f7274c3b4 | Python | 3,948 | 115 | import logging
import pickle
from datetime import datetime
from pathlib import Path
import pandas as pd
import torch
Path("./data").mkdir(parents=True, exist_ok=True)
isLoaded = False
objDir = './data/obj'
def setupLogger(fileName = 'example.log', customObjDir='./data/obj'):
global isLoaded
global objDir
... |
e0ee251c7a776caea74494c6d590ab3c728df6db1d709de50375d89150de0067 | Python | 3,949 | 114 | import os
import numpy as np
from rdkit import Chem
# from rdkit.Chem.rdchem import BondType
# from rdkit.Chem import ChemicalFeatures
# from rdkit import RDConfig
# from utils.mol2frag import mol2frag
# ATOM_FAMILIES = ['Acceptor', 'Donor', 'Aromatic', 'Hydrophobe', 'LumpedHydrophobe', 'NegIonizable', 'PosIonizabl... |
1256c4fa22d0f164db58fb4b31b54658defc576956207c46c6e75f2066c18d31 | Python | 3,953 | 132 | """Base geometry class for all ZnDraw geometries."""
import typing as t
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, model_validator
from pydantic.json_schema import SkipJsonSchema
if t.TYPE_CHECKING:
from zndraw.transformations import Transform
from zndraw.materials import MaterialProp... |
ff97a9a35867fe1316637e290860879d4b30c7208c7d0d20516897691731a475 | Python | 3,953 | 95 | DOCS = """
train the model on the a dataset (gabor or mnist) and examine the impact of different ablation on the model performance.
Currently figure 3.
"""
from dataset import GaborDatasetOrientation
from model import ShallowMLP
from experiment.utils import set_seed, init_model, Logger, Trainer, Checkpointer
import to... |
2fce8a0850e0ce94c9cf84e3424d3ab0259bb1136531e65a273a4ec8cd5949e7 | Python | 3,954 | 89 | import os
from nvflare.apis.executor import Executor
from nvflare.apis.fl_constant import FLContextKey, ReturnCode
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable, make_reply
from nvflare.apis.signal import Signal
import xgboost as xgb
from xgboost import callback
class Su... |
85ca67e8e84cad09933d2f3ba60de3bc18bafda78706bd5c4c4a509f577dea90 | Python | 3,954 | 128 | import os
import numpy as np
import pickle
import torch
import random
from datetime import datetime
def pkl_save(name, var):
with open(name, 'wb') as f:
pickle.dump(var, f)
def pkl_load(name):
with open(name, 'rb') as f:
return pickle.load(f)
def torch_pad_nan(arr, left=0, right=0, dim=0)... |
121002c50306d92d4e69e63ed24574792b20b6c3fbe0330ac320264e75c76c6c | Python | 3,960 | 132 | import os
import pickle
from pathlib import Path
from cutadapt.files import ProxyTextFile, ProxyRecordWriter, OutputFiles
from dnaio import SequenceRecord
def test_proxy_text_file():
newline = os.linesep.encode()
pf = ProxyTextFile()
print("hello", file=pf)
assert pf.drain() == [b"hello" + newline]
... |
47c855b141db354d8d72f4a8b30e0a6034132fe820a9aa1e07f53dfce99ca788 | Python | 3,960 | 110 | #!/usr/bin/env python
from snakemake.io import load_configfile
from pathlib import Path
from os.path import isfile
def touch_if_exists(file_path):
if isfile(file_path):
Path(file_path).touch()
else:
print(f'{file_path} does not exist.')
def update_timestamp_task(config, task, update_metrics... |
eee8ee2c9df0fa6083cacb9c2ebdc514b7ca4f891ee7c529db5d2fa7620e901d | Python | 3,961 | 120 | from typing import List
import numpy as np
import torch
from ase import Atoms
from mace import data
from mace.calculators import MACECalculator
from mace.tools import AtomicNumberTable, torch_geometric
from .tools import _energies_to_real
def create_atomic_data_by_copy(
configs: List[data.Configuration], z_tabl... |
da2b8afd54daa77ab6ab1b9e082c1b174ec66634f1bff7e0172733d551e3b91b | Python | 3,963 | 126 | import json
from io import StringIO
import pytest
from cwltool.main import main
from .util import get_data, needs_docker
override_parameters = [
(
[get_data("tests/override/echo.cwl"), get_data("tests/override/echo-job.yml")],
{"out": "zing hello1\n"},
),
(
[
"--overr... |
2d2a8f274918a06ddabd0f3c03a5d7bc4656cb6d8168f01a817a1a46d189788f | Python | 3,964 | 115 | import torch
import torch.nn as nn
class HybridViT(nn.Module):
"""
A Convolutional-Transformer Hybrid Architecture.
Dynamically sizes its positional embeddings and patch count based on the input batch,
making it easily adaptable to different image or spectrogram resolutions.
"""
def __init__(se... |
dcbc73c2f2bf8c2b7d468d2619ef71b17cf334ca27695a7b9ffceba21a4a3aad | Python | 3,965 | 100 | import os
import sys
import torch.nn
import yaml
from tqdm import tqdm
import pandas as pd
# Dynamically append project root to sys.path
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if ROOT_DIR not in sys.path:
sys.path.insert(0, ROOT_DIR)
from Models import RNN, LSTM, GRU
from DataS... |
1fb6a711654a71b94674dbdd16ec3ab07c1f8691afb0155124555b21271eb507 | Python | 3,969 | 124 | import torch.nn as nn
import torch.nn.functional as F
import torch
# adapt from https://github.com/MIC-DKFZ/BraTS2017
def normalization(planes, norm='gn'):
if norm == 'bn':
m = nn.BatchNorm3d(planes)
elif norm == 'gn':
m = nn.GroupNorm(8, planes)
elif norm == 'in':
m = nn.Instance... |
b3a6cfa195f4e0a9eeeef590e760e00a90cf433a7f681aae199aa4a2bac921e1 | Python | 3,971 | 133 | # Copyright (c) OpenMMLab. All rights reserved.
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup -----------------------... |
f33928ba484ced7a91d3c96f14717198ffb707944b602697c0426f0ef5ee0e94 | Python | 3,971 | 150 | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
"""
Common high-level operations test
Tests... |
0840dc2418da7ba049c6f0306c0c6539b015bb4acb96cae448a405adbb916195 | Python | 3,972 | 110 | import os
import sys
import scvi
import scanpy as sc
import numpy as np
from sklearn.cluster import KMeans
import metrics as M
#from .metrics import compute_metrics
def train(data_path, dataset_name, save_path):
"""
:param data_path: e.g. data/ including csv h5ad
:param dataset_name: "baron-human"
... |
74dc974f01f6e32cd5653839098b9f2e95ebe920c2ec4e2273e727f53aedea40 | Python | 3,972 | 109 | import hashlib
from typing import List
import medperf.config as config
from medperf.entities.interface import Entity
from medperf.entities.schemas import TestReportSchema
from medperf.entities.utils import handle_validation_error
class TestReport(Entity):
"""
Class representing a compatibility test report en... |
81f194afc7aad9a18802b9a4227c2bc794f08ceb261de275697955a3c50d2583 | Python | 3,972 | 99 | import csv
import shutil
from pathlib import Path
import h5py
import numpy as np
import pytest
from guppy.testing.api import step1, step2
from guppy.utils.progress import StepProgress, _current_step
from guppy_test_data import STUBBED_TESTING_DATA
from .integration_helpers import REPRESENTATIVE_SESSIONS, _locate_out... |
1f809501d9ed11a753db37d2df7b08efe45bd00390c3863ab805fb70a4813610 | Python | 3,973 | 123 | import torch
from torch.distributions.categorical import Categorical
import numpy as np
# TODO: This code is just copied over diffSBDD and has not been modified at all...
class DoubleDistributionNodes:
def __init__(self, histogram):
histogram = torch.tensor(histogram).float()
histogram = histogr... |
9b78f7b4753ac019aa30a34394f333ed0c21f53aac118f6d9852d0385e84bfb2 | Python | 3,973 | 125 | #!/usr/bin/env python
"""
MetaWIBELE: split_family_abundance module
Split the abundance of families
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Sof... |
e0a876a8687539b9e43b2ca0ed3cb717119ce201f10c331d8385007a9cdd6623 | Python | 3,975 | 157 | import pytest
from kgx.transformer import Transformer
from kgx.source.source import DEFAULT_NODE_CATEGORY, Source
@pytest.mark.parametrize(
"node",
[
{"name": "Node A", "description": "Node without an ID"},
{"node_id": "A", "description": "Node without an ID, name and category"},
{"n... |
ed1949435d085c41a93dcae924e0273589772077f598c843edb7f3403ab73384 | Python | 3,976 | 117 | from __future__ import annotations
import os
import random
import torch
from pymatgen.core.structure import Structure
from chgnet import utils
from chgnet.data.dataset import StructureData, StructureJsonData
from chgnet.graph import CrystalGraphConverter
random.seed(100)
# This runnable script shows an example to... |
0fb4fca5fea6891095ddeb8d3a01e92748b0f7148af32b44df0f2d2db497885a | Python | 3,978 | 108 | # Image file import PyQt5 threads
from typing import Any, Callable, Dict, List, Optional
from PyQt5 import QtCore
from magmap.gui import visualizer
from magmap.io import importer
from magmap.settings import config
_logger = config.logger.getChild(__name__)
class SetupImportThread(QtCore.QThread):
"""Thread for... |
c64c2c44126a01c057c27045b1363e3e61b8e52f339f9069fc08a4f245337270 | Python | 3,978 | 104 | """Tests for guppy.utils.nwb_io."""
import json
import subprocess
import sys
import pytest
from guppy.utils.nwb_io import _CORE_TYPE_MAP
from guppy_test_data import STUBBED_TESTING_DATA
MOCK_NWB_NDX_FIBER_PHOTOMETRY_V0_1_FILE = (
STUBBED_TESTING_DATA
/ "nwb"
/ "mock_nwbfile_ndx_fiber_photometry_v0_1_ndx... |
848d5bbcfc44c9cc7a77070b504adfb33a29c431a30122e56d427a92de30b53d | Python | 3,979 | 102 | # -*- coding: utf-8 -*-
# Albert Cardona 2014-11-20
# This file is meant to be run from within ./manage.py shell in the environment, like:
# [1] load export_all_graphml.py
# [2] project_id = 12
# [2] export(project_id, "all.graphml")
#
# Will generate a gzip'ed file like "all.graphml.gz"
#
# Includes all skeletons wit... |
dd3ea7e960223186e66ff95c27cc2e5fef555c8611a7750ddc6e3c0dbfabb005 | Python | 3,979 | 83 | import numpy as np
import gpflow
import tensorflow as tf
import tensorflow_probability as tfp
from gpflow.utilities import positive
from gpflow import Parameter
from grid_cell.gaussian_wishart.src.likelihoods.BaseWishartLikelihood import WishartLikelihoodBase
class WishartLikelihood(WishartLikelihoodBase):
"""
... |
ddd0902ce937a25dbbaf3855a5b9ab9f810c97ab397422cf296f6086f22b388e | Python | 3,981 | 128 | from rest_framework import status
from medperf.tests import MedPerfTest
from parameterized import parameterized, parameterized_class
class EncryptedKeyTest(MedPerfTest):
def generic_setup(self):
# setup users
container_owner = "container_owner"
cert_owner = "cert_owner"
ca_owner ... |
8d9161a34472f563f90ec17648ce7b825b38aec5915b85415b726e208ebf0eda | Python | 3,982 | 124 | from __future__ import absolute_import
from __future__ import print_function
import os
import json
import sys
import importlib
from .common import epsilon
from .common import floatx
from .common import set_epsilon
from .common import set_floatx
from .common import cast_to_floatx
from .common import image_data_format
fr... |
f00cfd79c2cf34b8c2b171dfd9187827984d563f296c1ec1819ee432035fa9bd | Python | 3,982 | 125 | # -*- coding: utf-8 -*-
# An entirely untested jython script to delete all the concepts in the
# CATMAID database for a particular project.
#
# Mark Longair 2010
#
# flake8: noqa
import os, re, sys, ij
from jarray import array
from java.sql import DriverManager, Connection, SQLException, Types
# Set up the JDBC con... |
ea2904141cdf758e02d4003ffea423a8591d55a1e696ef4931620baa0203ef90 | Python | 3,983 | 139 | """Tests for ephys.extra_features_utils"""
import os
import numpy
import pytest
from bluepyopt import ephys
testdata_dir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'testdata'
)
waveforms_fpath = os.path.join(testdata_dir, 'mean_waveforms.dat')
waveforms = numpy.loadtxt(waveforms_fpath)
wavefor... |
53b39ebd2f233588b811476d1c7f21ca26b48486e23b547b2798505e904113e6 | Python | 3,987 | 92 | import os
import cv2
import json
import numpy as np
import random
from data.transforms import ISOSTransform
from data.datasets import AOOCTConeSeg
from tools.visualizations import generate_distinct_colors
random.seed(42)
np.random.seed(42)
if __name__ == '__main__':
num_seg_classes = 5
with open('cfg/model/... |
24057d20384a0770dd77b2a55f70bff5620544ba45c2791084b1de5d1aa554cb | Python | 3,988 | 91 | #!/usr/bin/python3
import anndata
import scvelo as scv
import pandas as pd
import re
import os
import subprocess
import sys
import getopt
def main(argv):
loom_file = ''
umap_file = ''
clusters_file = ''
sample_name = ''
outdir = ''
try:
opts, args = getopt.getopt(argv,"hl:n:u:c:",["loo... |
3801187e947c23f5d21a0c30a392e86bd32fb5258223fa5dfb9a05baf1b3a2cb | Python | 3,988 | 112 | #!/usr/bin/env python
"""
MetaWIBELE: gene_abundance_indexRef module
Build reference index and annotation info file
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to ... |
4206ff0ad7de86292c1db07f4f88e1113da66b3440dda07f6105b29231da07c3 | Python | 3,989 | 114 | from __future__ import annotations
import os
from dataclasses import dataclass, field
from typing import Optional, TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from dante.obj_functions import ObjectiveFunction
@dataclass
class Tracker:
"""A class for tracking optimization results and saving them peri... |
477b5fead927e959016b488ac28ff6c91f2d15972389c49003eb01c51b2a6d28 | Python | 3,990 | 110 | import re
import json
import multiprocessing
from tqdm import tqdm
from pathlib import Path
from itertools import chain
_SPLIT_DATA_PATH = '/data1/datas/wudao_180g'
def cut_sent(path):
"""
中文分句,默认?、。、!、省略号分句,考虑双引号包裹的句子
采用分割替换的方式
"""
path = Path(path)
# print(path)
save_path = str(Path('/d... |
7b4c780b9a3994710f6b628099056ca251d05b0b29799cd3eaccdd4d3b34c517 | Python | 3,990 | 133 | # Copyright (c) OpenMMLab. All rights reserved.
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup -----------------------... |
62009bce26e53a5281e36deda3f56ab2089939f7a4a3bdc4ea5d70e782a4d08f | Python | 3,994 | 100 | """
## Restormer: Efficient Transformer for High-Resolution Image Restoration
## Syed Waqas Zamir, Aditya Arora, Salman Khan, Munawar Hayat, Fahad Shahbaz Khan, and Ming-Hsuan Yang
## https://arxiv.org/abs/2111.09881
"""
import numpy as np
import os
import argparse
from tqdm import tqdm
import torch.nn as nn
import t... |
771e4401b6086fae509f4a902335a1f149727dac77abf94a837f7548d4301856 | Python | 3,995 | 147 | import pytest
import sys
import numpy as np
from numpy.testing import assert_allclose
import keras
from keras import layers
from keras import optimizers
from keras import losses
from keras import metrics
if sys.version_info[0] == 3:
import pickle
else:
import cPickle as pickle
def test_sequential_model_pick... |
d9de02252b793d2ad3afdb8495f42baa7b44cb0c63f9359dde7f4473b9769f5e | Python | 3,995 | 131 | #!/usr/bin/env python3
"""
Generate a violin plot of |attack-vector_best_particle_denoise.csv| sums
grouped by original image classification labels for a single model directory.
Usage:
python attack_vector_violin_by_label.py \
--dataset MNIST \
--model_dir MNIST-rand_model1 \
--label_file i... |
f8dd16fceda5a5276c7e72a35b7693b1b702fb1c1ea3c5f43f0bf6d2dd8be30e | Python | 3,995 | 99 | import pandas as pd
import argparse
from scipy.spatial import Delaunay
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from matplotlib.lines import Line2D
import os
def sort_motif_label(label: str) -> str:
parts = label.split("_")
parts_sorted = sorted(parts)
return "_"... |
ed5086ea990a40a11a0ca79db5f3b1b23ca89f3dd8661615ee7ff887a17eaa93 | Python | 3,999 | 102 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, build_upsample_layer
class UpConvBlock(nn.Module):
"""Upsample convolution block in decoder for UNet.
This upsample convolution block consists of one upsample module
followed by one convolu... |
f7f4e539a7af713576685469c7fb1a358058c49f4661ecb4ba541c34dc7828da | Python | 4,000 | 124 | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
import torch
import torch.nn as nn
from mmengine.model import BaseModule
from mmseg.models.backbones.mscan import (MSCAN, MSCABlock,
MSCASpatialAttention,
OverlapPatchEmb... |
81aa6adadbe490a80bf6e3c745b35e693add72e248b53f7361b5b8b2d0608dc3 | Python | 4,001 | 111 | import logging
from time import monotonic
import ase
import numpy as np
from ase.optimize import LBFGS
from hydromace.interface import HydroMaceCalculator
from simgen.atoms_cleanup import attach_calculator
from simgen.calculators import MaceSimilarityCalculator
from simgen.generation_utils import calculate_restorativ... |
c43ecb753f3ec2e83709eae44d80d9d2e0231be24ac6f2039d48812dd883fe14 | Python | 4,001 | 97 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 31 12:07:33 2015
@author: takeiyuichi
"""
#このスクリプトには以下のpythonパッケージが必要です。
#pydicom https://code.google.com/p/pydicom/downloads/list
# nibabel
# networkx
# nipype
#この処理を行う前に、kg_prepare(_日付).pyを行い、
#解析用ディレクトリの構成を行って下さい。
#macをお使いの場合は、ターミナル(ipythonもしくはpython)から使用して下さい。
#can... |
f09203d03d253a3327c281f29499e75cdb09ebc201d16ce5afcf0876c354c92c | Python | 4,002 | 116 | from medperf.exceptions import CleanExit, InvalidArgumentError, MedperfException
from medperf.utils import dict_pretty_print, approval_prompt
from medperf.entities.execution import Execution
from medperf import config
from medperf.account_management.account_management import get_medperf_user_data
from medperf.commands.... |
49fcca235b3813d30cbf742d2a57e7a47f4065bdca1c16f40949bd234b5fa618 | Python | 4,007 | 117 | #!/usr/bin/env python3
"""
Given the original (full) rigid receptor and the output of --out_flex,
which contains side chain coordinates from flexible docking with smina/gnina,
output the full restored receptors with the flexible residues re-inserted.
This is a bit fragile and may break if atoms do not have standar... |
e2cde9072237a0371f1ae9cd5eeb66d105e458dbc82a5aa4920e8cac0d61e425 | Python | 4,007 | 112 | # Standard library imports
import os
import random
from collections import defaultdict
from io import StringIO
from typing import Dict, List, Tuple
from pathlib import Path
# Third-party library imports
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
fro... |
37440f218d77c02991b2165d3ed74fdcf67e24f96982275924f9d35bbbb58432 | Python | 4,008 | 117 | import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from matplotlib.gridspec import GridSpec
from pathlib import Path
# Load your data for the first plot
time2_ced = pd.read_csv(Path("time2_ced.csv"))
ycurrent = pd.read_csv(Path("ycurrent.csv"))
bertec_data = pd.read_csv(Path("bertec_data.csv"))
... |
87b94d15842c34d1bcd912680f904e646c350a5cb1eac177fa437f995d2d8fdf | Python | 4,010 | 140 | # -*- coding: utf-8 -*-
import fury
import numpy as np
import vtk
from vtk.util import numpy_support
"""
Some functions comes from
https://github.com/scilus/scilpy/blob/master/scilpy/viz/gradient_sampling.py
"""
def analyse_qa(stats_per_subjects, stats_across_subjects, column_names):
"""
Analyse the subject... |
3b49f9f9d357ef4ca7efb092479ec72c70e30fee8f995d04287df1ff799770d9 | Python | 4,012 | 112 | """
Qt dialog for manually segmenting a spinalcord image
Copyright (c) 2017 Polytechnique Montreal <www.neuro.polymtl.ca>
License: see the file LICENSE
"""
import logging
import numpy as np
from PyQt5 import QtWidgets
from spinalcordtoolbox.gui import base
from spinalcordtoolbox.gui import widgets
from spinalcordto... |
5d8ece9237246bf79e9828236198e49615c05702a3b55a5e93763dce2c7666b0 | Python | 4,016 | 113 | import unittest
from xml.etree import ElementTree
import pkg_resources
import json
from prov.model import ProvDocument
from prov.tests import examples
from provdbconnector.utils.converter import to_json, from_json, to_provn, from_provn, to_xml, from_xml, form_string
from provdbconnector.exceptions.utils import NoDocum... |
d3515c1f4c7337c728debce363abf12796d0ccf0b5d0acbce15654a270e70545 | Python | 4,018 | 126 | # #############################
#
# Copyright (C) 2018
# Jennifer Dreiling (dreiling@gfz-potsdam.de)
#
#
# #############################
import numpy as np
from BayHunter.surfdisp96_ext import surfdisp96
class SurfDisp(object):
"""Forward modeling of dispersion curves based on surf96 (Rob Herrmann).
The q... |
365e71efc6c474c890e0b59f5c210bacac10b283fb0d1df4a8fcf26cab7de058 | Python | 4,019 | 114 | import glob
import os
import numpy as np
from PIL import Image
root_path = 'data/'
img_suffix = '.png'
seg_map_suffix = '.png'
save_img_suffix = '.png'
save_seg_map_suffix = '.png'
src_img_train_dir = os.path.join(
root_path, 'wound-segmentation/data/' +
'Foot Ulcer Segmentation Challenge/train/images')
src_i... |
36c2083acaccb1e4eec2a7d205539a46249f0498173aad463cf20dc0c5f41d57 | Python | 4,020 | 116 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Tuple, Union
import torch.nn as nn
from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer
from torch import Tensor
from mmseg.models.decode_heads.decode_head import BaseDecodeHead
from mmseg.models.losses import accuracy
from mmseg.... |
8940d69bf2f2a21ad6b0d24c25766bffa40d8edadc032fb7a332c35f22957378 | Python | 4,021 | 113 | import os
import time
import argparse
import matplotlib.pyplot as plt
from auditory_cortex import opt_inputs_dir, results_dir, cache_dir
from auditory_cortex.analyses import Correlations
from auditory_cortex.plotters.tikzplots import plot_spectrogram_spike_count_pair
# ------------------ save qualitative figures ---... |
765e6ae13c12b18c09f56f970aefda5c3ccfee21f692787d6acce81bad948c03 | Python | 4,022 | 133 | import os
import tarfile
import logging
import typer
from rano_monitor.constants import (
DSET_HELP,
DEFAULT_STAGES_PATH,
STAGES_HELP,
DSET_LOC_HELP,
OUT_HELP,
REVIEW_COMMAND,
REVIEW_CMD_HELP,
)
from rano_monitor.dataset_browser import DatasetBrowser
from rano_monitor.handlers import Invali... |
7e9db09badfcc3b8e4ec7e62521bd61372e10dbb87aaca334c73d9d789c0e7fa | Python | 4,022 | 124 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-07-17 15:45
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
# Construct a PostGIS TIN representation of a bounding box
bb_vertices = """
(({0}, {2}, {1}, {... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.