sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
6c1c21bdd544ed11c94c872a18bcd82c2544dfd2028e0eff9f4f1d3645546b9a | Python | 3,520 | 93 | """ Multiverse preprocessing """
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
import mne
from scipy.signal import detrend
import sys, os
from tqdm import tqdm
import pickle
from glob import glob
if sys.platform.startswith('darwin'):
mne.viz.set_browser_backend('qt', verbose=None) #... |
cfa712f02ac0847201729eea2d71d9a4bc13e9b57acc4099c9cec3211766851f | Python | 3,521 | 92 | import ftplib
import os
import urllib.error
import urllib.request
from src.babel_utils import get_config, get_user_agent, pull_via_ftp
from src.metadata.provenance import write_metadata
from src.prefixes import PANTHERFAMILY
from src.util import ensure_parent_dir, get_logger
logger = get_logger(__name__)
FTP_HOST = ... |
039fb7d10baa9b9ba44cd1fc161e594006835711453898f1df0305877211f447 | Python | 3,522 | 67 | # 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... |
269ed40d6a2e2a36fc202807f3e3ad0c63af337cf88e8199e177fda9ae676e5a | Python | 3,522 | 119 | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-ignore-all-errors
import copy
import unittest
from fvcore.common.param_scheduler import MultiStepParamScheduler
class TestMultiStepParamScheduler(unittest.TestCase):
_num_updates = 12
def _get_valid_config(self):
return {
"num_u... |
b2d41488d1c134fccecc7922789141d061d3b7eb91150f9b7a9d65d919f9c7d3 | Python | 3,522 | 88 |
"""Tsodyks-Markram model Evaluator.
This module contains an evaluator for the Tsodyks-Markram model.
@author: Giuseppe Chindemi
@remark: Copyright (c) 2017, EPFL/Blue Brain Project
This file is part of BluePyOpt
<https://github.com/BlueBrain/BluePyOpt>
This library is free software; you can... |
5e82770350e45b997890fd5c378af3372897f5d6596b6607af2235e463755438 | Python | 3,528 | 98 | ##################################################################
# Code change in NCEM
# Reproducibility for Figure.5OPQR
##################################################################
from typing import Dict, List, Optional, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
import scanpy as sc
imp... |
acb319d70374d940c7d20cf27aeb5caf7299fefc55d12158fb889bdef8c74773 | Python | 3,528 | 81 | import typing
from urllib.parse import urlparse
import torch
class TritonRemoteModel:
""" A wrapper over a model served by the Triton Inference Server. It can
be configured to communicate over GRPC or HTTP. It accepts Torch Tensors
as input and returns them as outputs.
"""
def __init__(self, url... |
ad33c952aa3d1a2071b8a22c5033ebc5165c0179dbb3a6a75f43e6899a0095c6 | Python | 3,530 | 80 | import gzip
from src.babel_utils import pull_via_wget
from src.prefixes import CHEBI, CHEMBLCOMPOUND, DRUGBANK, DRUGCENTRAL, GTOPDB, HMDB, PUBCHEMCOMPOUND, UNII
# global for this file
data_sources: dict = {
"1": CHEMBLCOMPOUND,
"2": DRUGBANK,
"4": GTOPDB,
# "6": KEGGCOMPOUND, # Removed from UniChem —... |
053f2acf5116f2308505fbc7563776ae4a764b6fd9db5ba546d6d5b6f37ae51d | Python | 3,533 | 94 | import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import adfuller
import argparse
import pickle
def _load_raw_KPI(train_filename, test_filename):
train_data = pd.read_csv(train_filename)
train_data = train_data.set_index(['KPI ID', 'timestamp']).sort_index()
x_train = {}
y_train = {... |
3658e38ea641f28f17a1055d091eaa756ee3ddd3a33ff2692524a010865f743d | Python | 3,535 | 76 | # Generated by Django 2.1.7 on 2019-03-07 03:23
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
forward = """
CREATE TABLE catmaid_group_inactivity_period (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
max_inactivi... |
55578d899d99a291e98fe6ee492135f3c3a986ba1a756d8fbc982b0ffadadcb6 | Python | 3,537 | 124 | """Utilities."""
import numpy as np
import pytest
import scipy.interpolate as interpolate
from numpy.testing import assert_array_equal, assert_equal
from msalign.utilities import (
check_xy,
convert_peak_values_to_index,
find_nearest_index,
format_time,
generate_function,
shift,
)
class TestS... |
faaa0a5a1fa3a4027b8753ca1b0df409df9e4fa8a50c3d7c413cdba5132cd0b2 | Python | 3,538 | 110 | """
Utility functions for file management.
License: BSD-3-Clause
Author: Hanna M. Tolle
Date: 2024-10-31
"""
import os
import shutil
def project_root():
'''Returns project root path (where utils/ is located).'''
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def add_project_root(dir_nam... |
db949287da69e2003abbc74caa72175ca8162a9605193aa85532d5cb3f63966c | Python | 3,539 | 126 | # 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.
"""
Demonstrates how to use h5py with the multip... |
91329b5103195ff2d8b1ea5031df0703c5c028d4261bfefa89084b35ef1640e1 | Python | 3,540 | 141 | """Access-control primitives for rooms, groups, and share links."""
from dataclasses import dataclass
from enum import StrEnum
from typing import Protocol
from uuid import UUID
class Visibility(StrEnum):
PRIVATE = "private"
GROUP = "group"
PUBLIC = "public"
class GroupRole(StrEnum):
VIEWER = "viewe... |
ec352d9aa6ef5c3ee9490140fe20f1ab0cd1be05d7632936c3b7f881115776b6 | Python | 3,541 | 94 | import os
import logging
from typing import Optional
from medperf.utils import generate_tmp_path, get_file_hash
from .sources import supported_sources
from medperf.exceptions import InvalidArgumentError, InvalidEntityError
def __parse_resource(resource: str):
"""Parses a resource string and returns its identifier... |
7ec8cd14d0fd8f3b87b028c2613dad3ce1a28685c19e1df37d517b78892adb61 | Python | 3,544 | 94 | import numpy as np
# TODO: Make the thresholding adaptive such that it searches for a value that results
# in the same number of expected and corrected trials
def detectMissingEvents(
eventTimestampsObserved,
eventTimestampsExpected,
latencyThresholdRange=(0.01, 1.0),
latencyThresholdStep=0.01,
pad... |
dd72a4e032ed5f404420693acfdf018f2b84d3c96e4b90f7f1db761b2c1f0b1a | Python | 3,544 | 76 | import pandas as pd
import jsonlines
from glob import glob
import numpy as np
import statsmodels.formula.api as sm
import pandas as pd
import jsonlines
from glob import glob
import numpy as np
import statsmodels.formula.api as sm
import matplotlib.pyplot as plt
import scienceplots
import matplotlib.gridspec as gridspec... |
e766895c30b17b94a6b803f68048a5a49486dc6abf3ec72480d1e3ddf5fb63e9 | Python | 3,544 | 124 | import time
from unittest.mock import ANY
from medperf.tests.mocks import MockResponse
from medperf.comms.auth.auth0 import Auth0
from medperf import config
from medperf.exceptions import AuthenticationError
import sqlite3
import pytest
PATCH_AUTH = "medperf.comms.auth.auth0.{}"
@pytest.fixture
def setup(mocker):
... |
fba9a26e3e045af1e375fe09dae193ef648fe1fd884f323fd6e17954025ea033 | Python | 3,545 | 110 | from django.http import Http404
from model.models import Model
from model.serializers import ModelSerializer
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework import status
from drf_spectacular.utils import extend_schema
from .models import Asset
from .... |
ab126fbca48a02c623c7d726638e41ca3ed425f9e7c1b593f4073ccf5e00380b | Python | 3,546 | 98 | #!/usr/bin/env python
"""
Classifier is an image classifier specialization of Net.
"""
import numpy as np
import caffe
class Classifier(caffe.Net):
"""
Classifier extends Net for image class prediction
by scaling, center cropping, or oversampling.
Parameters
----------
image_dims : dimensio... |
b1a3fd618f63673b9c6a1d71f418dfc1d0961b07807e590a53414ae698498452 | Python | 3,546 | 129 | from typing import List
import numpy as np
from pymatgen.core import Molecule
from pymatgen.analysis.molecule_matcher import BruteForceOrderMatcher, GeneticOrderMatcher, HungarianOrderMatcher, KabschMatcher
from pymatgen.io.xyz import XYZ
from torch import Tensor
def xh2pmg(xh):
mol = Molecule(
species=... |
f03598e2443f69a98109e378d928f4f0795110587fbbe50a1aec4305d987cbdc | Python | 3,546 | 108 | """
Copyright (c) 2022 EPFL-BBP, All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE BLUE BRAIN PROJECT ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE BLUE BRAIN PROJE... |
57d8a7b415925683eab9c44ab9419b82b5e242c6845d8168284a46e633d28f4d | Python | 3,550 | 108 | #!/usr/bin/env python
"""BluePyOpt setup """
"""
Copyright (c) 2016-2020, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt>
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 3.0 as... |
038a18be8fe0007970d318985c383e9a02a9d1917bacef614b0c1eec7b8eaaac | Python | 3,551 | 105 | import pandas as pd
import os
import nupack
from nupack import Domain, TargetStrand, TargetComplex, TargetTube, tube_design, Diversity
from . import util
def design_nupack(target):
"""
Args:
target - Dict, e.g.
target = dict(a='SN6NN6S',
b='SN6NN6S',
struct='... |
72e3c29e8471a4d306ea238b978a91893d5ef90741f0cb0c02c462fbbb6f4dee | Python | 3,551 | 121 | import io
import os
import sys
from abc import ABC, abstractmethod
from typing import Optional
import torch
from pyalfe.interfaces.freesurfer import FreeSurfer
class InferenceModel(ABC):
"""The parent class for all inference models."""
@abstractmethod
def predict_cases(
self, input_image_tuple_... |
d48e48a087db1b49b1ecfe912803cbf044aef1d33a1c1bc64bfa61ef5bd27e88 | Python | 3,552 | 75 | #!/bin/python
# arrange
import truster
import os
import gzip
raw_path = "/Volumes/MyPassport/trusTEr/test/raw/"
lunarc = "config_files/lunarc_config.json"
modules = "config_files/software_modules.json"
test = truster.Experiment("test", lunarc, modules)
test.register_samples_from_path(raw_path)
merge_samples_outdir =... |
31f67e6449228776e0c5754b1b8827cf4636277e79b807ced10e02254333a543 | Python | 3,553 | 107 | import glob
import os
import numpy as np
from PIL import Image
root_path = 'data/'
img_suffix = '.jpg'
seg_map_suffix = '.png'
save_img_suffix = '.png'
save_seg_map_suffix = '.png'
tgt_img_train_dir = os.path.join(root_path, 'images/train/')
tgt_mask_train_dir = os.path.join(root_path, 'masks/train/')
tgt_img_test_di... |
5c4ef1585615fabc5fb877b36b696d212e8fe4ca8c75ee91a167e1b51e886aed | Python | 3,553 | 98 | import os
import numpy as np
import pytest
from dante.obj_functions import (
Ackley,
Griewank,
Levy,
Michalewicz,
ObjectiveFunction,
Rastrigin,
Rosenbrock,
Schwefel,
)
from dante.utils import Tracker, generate_initial_samples
@pytest.fixture
def tracker():
"""Fixture to create a Tr... |
afdb2c76b779f5f4920fb70c00c6ca5c345473a1ebe29f4f075de263a7f28e17 | Python | 3,554 | 109 | import numpy as np
import pandas as pd
class Hurst:
"""
Hurst exponent per-channel, see http://en.wikipedia.org/wiki/Hurst_exponent
Another description can be found here: http://www.ijetch.org/papers/698-W10024.pdf
Kavya Devarajan, S. Bagyaraj, Vinitha Balasampath, Jyostna. E. and Jayasri. K.,
"EEG... |
bd8f9b1d5441aebadeba1014fff7271df6126e129ca738b4284d68a274bb19d0 | Python | 3,554 | 98 | #!/usr/bin/env python
'''Utility functions to read the tasks.db from ipyparallel when used
with BluePyOpt.
The script is executable, as an example on how to extract the top 10
longest running engines for the l5pc model.
'''
import sqlite3
import pandas
import numpy as np
from ipyparallel.controller import sqlitedb
... |
0f6c67428b2d9c55c2da438a751515170ddc7e6629577e1d1c7b83ed5e77f47d | Python | 3,556 | 120 | # Copyright DST Group. Licensed under the MIT license.
import pprint
from copy import deepcopy
from CybORG.Shared.Observation import Observation
class Results:
""" Results class that is returned after each step
Only the observation attribute is used in CC4.
Attributes
----------
observatio... |
68803ac2d2eca5775caa082d05aadab2bbe87c5d0a011a9a9d32e8373a13f8a0 | Python | 3,558 | 102 | import torch
import numpy as np
import itertools
import Images as imgs
def loss_fn(e1, e_t_0):
loss = 0
for i in range(len(e1)):
loss += torch.norm(e_t_0[i] - e1[i]) ** 2
loss /= len(e_t_0)
return loss
def optimize(HP, Z, T, Z_test_images, perf_test_images):
if HP['eta_rat... |
d497e710411c2084f1a077b70ede121f39c42fa4e4a8178547bf53fb35872e64 | Python | 3,558 | 87 | #!/usr/bin/env python
# Noise2Void - 3D Example
from n2v.models import N2VConfig, N2V
import numpy as np
from csbdeep.utils import plot_history
from n2v.utils.n2v_utils import manipulate_val_data
from n2v.internals.N2V_DataGenerator import N2V_DataGenerator
from matplotlib import pyplot as plt
import urllib
import os
i... |
de33c7000417d92ac58946c0dc6993e919ae94439e6412b3c30ced21b5c8dd68 | Python | 3,558 | 124 | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
from matplotlib.widgets import Button
from pymss import EnvManager
use_cuda = torch.cuda.is_available()
FloatTensor = torch.cuda.FloatTe... |
18b85f4556b9c48431f7c4c303d0d9e93a18bdb126cc1776b6dc2455d592e4a9 | Python | 3,559 | 89 | DOCS = """
train the model on the a dataset (gabor or mnist) or show the model learns to represent the data and predict the input
Current figures: figure 2.
"""
from dataset import GaborDatasetOrientation
from model import ShallowMLP
from experiment.utils import set_seed, init_model, Logger, Trainer, Checkpointer
impo... |
27c873b5e786dc25fd90a79799612a76465a9308d879508f5a52b7dd112644d7 | Python | 3,560 | 99 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.registry import MODELS
@MODELS.register_module()
class KLDivLoss(nn.Module):
def __init__(self,
temperature: float = 1.0,
reduction: str = 'mean',
... |
a6611db25b0a94219489ee74403da62187e9e3030a4c9c59d0f694a86b8d1e58 | Python | 3,561 | 116 | from functools import wraps
import os
import os.path as op
import sys
import heudiconv.heuristics
HEURISTICS_PATH = op.join(heudiconv.heuristics.__path__[0])
TESTS_DATA_PATH = op.join(op.dirname(__file__), 'data')
import logging
lgr = logging.getLogger(__name__)
def gen_heudiconv_args(datadir, outdir, subject, he... |
1445185473b04d41633597434fc0e12713102f3301a86350fa4d82c58e4973e0 | Python | 3,562 | 148 | import pytest
from unittest.mock import MagicMock
from medperf.ui.cli import CLI
@pytest.fixture
def cli(mocker):
mocker.patch("yaspin.yaspin", MagicMock)
cli = CLI()
return cli
@pytest.mark.parametrize("msg", ["test", "msg", "cube loaded successfully"])
class TestDisplayingMessages:
def test_print... |
aa3a0e5da8a3b38d36e419894834426571d5e9de88a7e1faec62f73ebc256c90 | Python | 3,562 | 96 | from itertools import product
import random
from igraph import Graph
import os
def generate_3order_pattern(pattern_vertices_labels): # 6 nodes
pattern = Graph(n=3, edges=[[0,1],[0,2],[1,2]])
pattern.vs["label"] = pattern_vertices_labels
pattern.es["label"] = 0
return pattern
def gener... |
61c9ee7beb10e92f084debfde02a7c8819b924275bcc85c3fecd20c1d387facd | Python | 3,563 | 96 | from __future__ import annotations
import pytest
import torch
from chgnet.model.basis import Fourier, RadialBessel
from chgnet.model.encoders import AngleEncoder, AtomEmbedding, BondEncoder
center = torch.tensor([[1, 0, 0], [0, 0, 0]])
neighbor = torch.tensor([[0, 0, 0], [1, 0, 0]])
bond_i = torch.tensor([[1, 0, 0]... |
68d283248caee65e35796db2c61165cafc510956755381c5bf9306ab3f284d7f | Python | 3,563 | 109 | """Simple cell test model"""
import os
import bluepyopt.ephys as ephys
class SimpleCell:
def __init__(self):
self.nrn_sim = ephys.simulators.NrnSimulator()
self.morph = ephys.morphologies.NrnFileMorphology(
os.path.join(
os.path.dirname(os.path.abspath(__file__)),
... |
a41d9eda93f3a8b35983136e8c66a9ac933fcc8619fc097477ccca0b4d70dca8 | Python | 3,564 | 102 | """Tsodyks-Markram model ODEINT.
This module contains functions to numerically integrate the Tsodyks-Markram
model. The current implementation is a port of an Igor Pro (WaveMetrics)
routine, written by Rodrigo Perin with the help of Raphael Holzer. Many thanks
to Misha Tsodyks and Henry Markram for their support during... |
a643b85082e4abc67afb7e9628bb2e82fddfa1e8d31a1276574e313ea3e9f63c | Python | 3,564 | 113 | #!/usr/bin/env python
# coding: utf-8
import scanpy as sc
import scib
import argparse
import os
import sys
import warnings
warnings.filterwarnings('ignore')
RESULT_TYPES = [
"full", # reconstructed expression data
"embed", # embedded/latent space
"knn" # corrected neighbourhood graph
]
if __name__ ==... |
9456c04206c3b988c9d703ec64296c60938b6023c75c9fffecfdc0c9a28baaff | Python | 3,567 | 109 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import List
PREDEFINED_TEMPLATES = {
'imagenet': [
'a bad photo of a {}.',
'a photo of many {}.',
'a sculpture of a {}.',
'a photo of the hard to see {}.',
'a low resolution photo of the {}.',
'a rendering o... |
d483d3bf5d18a3cd820ca314b024db252f397b3bcc9ad920c3f153f62899f95f | Python | 3,567 | 134 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 10 14:22:45 2023
@author: george
"""
#%matplotlib qt
import numba
import numpy as np
import pandas as pd
import skimage.io as skio
from tqdm import tqdm
import os, glob
import trackpy as tp
tiffFile = '/Users/george/Data/trackpyTest/GB_199_2022_0... |
af1a7c1f1a871236296c54b471d2857a81984ede5e3203aff19f7118d40b9900 | Python | 3,570 | 109 | import pytest
from keras.models import Sequential, Model
from keras.layers import Dense, Input, Average
from keras.utils import np_utils
from keras.utils import test_utils
from keras import regularizers
from keras import backend as K
data_dim = 5
num_classes = 2
batch_size = 10
def get_data():
(x_train, y_train... |
f001d1693be705cbd1d104bda8738b11d7a50b5f479280a3cb44ba06f8b16677 | Python | 3,570 | 99 | import shutil
from pathlib import Path
import pytest
from guppy.testing import compare_output_folders
from guppy.testing.api import locate_run_folder, step1, step2, step3, step4
from guppy_test_data import TESTING_DATA, event_ts_offset_for
CONSISTENCY_CASES = [
(
"SampleData_Clean/Photo_63_207-181030-103... |
8552981d27da846fccb6e30636e16228ba547990156363cc76644b4c5f74c09d | Python | 3,571 | 122 | from rest_framework.permissions import BasePermission
from benchmark.models import Benchmark
from dataset.models import Dataset
from .models import ModelResult
class IsAdmin(BasePermission):
def has_permission(self, request, view):
return request.user.is_superuser
class IsResultOwner(BasePermission):
... |
081aa4c3f2318b7ada2faa1d475a574a7034fa29e531cb10405c2f13540e80e3 | Python | 3,572 | 72 | from experiment import *
from behavior_analysis.io import TrackingInterface
import numpy as np
import pandas as pd
if __name__ == "__main__":
for species, species_directory in expt.directory["artemia_tracking"].items():
if species == "a_burtoni": # skip AB
continue
print(species)
... |
5675c516d5cca2f7ac91e9f3bc484512ab7149a24f0a235ed4f272136632f28a | Python | 3,572 | 83 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-23 12:04
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
"""
Add the SQL function update_skeleton_summaries() to update all entries in
the catmai... |
e948f224c564e308bde83097d373ca434e3cf225ad20a7401151d5731da62e35 | Python | 3,578 | 130 | from transformers import TrainingArguments
from trl import SFTTrainer, DataCollatorForCompletionOnlyLM
from unsloth import FastLanguageModel
from datasets import load_dataset
import pandas as pd
import argparse
import torch
def full_log_likelihoods(logits, labels):
with torch.no_grad():
logits = logits.float().cpu(... |
c993220faabfa8efe7054887fc32e4de62e9fd48ca332b750dc5b07e15d6478d | Python | 3,580 | 121 | """
ReactBench Calculators Package
Provides MLFF calculators for both run_pygsm.py and pysisyphus interfaces
"""
# Import LeftNet calculator classes
from .leftnet import (
LeftNetMLFF, get_leftnet_calculator
)
from .mace import (
MACEMLFF, get_mace_calculator
)
# Factory functions for calculators
# LeftNet
d... |
bcdbb0f7b9a7a07222b3a38de995677b0997c5d8410658fd4c2dc1d94262c2ce | Python | 3,585 | 120 | import os
import sys
import re
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import tempfile
from dotenv import load_dotenv, find_dotenv
from embedding.call_embedding import get_embedding
from langchain.document_loaders import UnstructuredFileLoader
from langchain.document_loaders import UnstructuredMarkd... |
42f64629360c894d0c9289c532c15988636a95ecff7ab5e63e5e579b7d88e195 | Python | 3,586 | 119 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import logomaker
import seaborn as sns
class motif():
alphabet = ['A', 'C', 'G', 'T']
colorscheme = {
'G': [0.004, 0.125, 0.305],
'TU': [0.007, 0.514, 0.569],
'C': [0.965, 0.8... |
6a9cb4904cb320a4315790cfde553878c3108cf8703f3ce40a9af9ed907f64db | Python | 3,586 | 138 | """Selection Groups REST API endpoints."""
import json
from fastapi import APIRouter
from zndraw.broadcast import broadcast_to_room
from zndraw.dependencies import (
AccessReadDep,
SessionDep,
SioDep,
WritableRoomDep,
)
from zndraw.exceptions import (
NotAuthenticated,
RoomLocked,
RoomNot... |
73afaae74fae3251ce4c1580daaa3706db32d33699e1c6a3ff6ae8d8843fe4e4 | Python | 3,589 | 107 | # Copyright (c) OpenMMLab. All rights reserved.
def nlc_to_nchw(x, hw_shape):
"""Convert [N, L, C] shape tensor to [N, C, H, W] shape tensor.
Args:
x (Tensor): The input tensor of shape [N, L, C] before conversion.
hw_shape (Sequence[int]): The height and width of output feature map.
Retur... |
8eb518aac28150bc7a0a27e1c02d25f61ccaaeb6aeb697997ab143190f6723cb | Python | 3,589 | 108 | # Author: Tobias Plötz, TU Darmstadt (tobias.ploetz@visinf.tu-darmstadt.de)
# This file is part of the implementation as described in the CVPR 2017 paper:
# Tobias Plötz and Stefan Roth, Benchmarking Denoising Algorithms with Real Photographs.
# Please see the file LICENSE.txt for the license governing this code.
... |
d11517b69252fb902e8a1d3abfb06fbc10d72b1e94269fc0daf36fad626d0cfc | Python | 3,589 | 66 | import torch
import math
import matplotlib.pyplot as plt
import seaborn as sns
import scienceplots
import matplotlib.gridspec as gridspec
import numpy as np
centaur_70b = torch.load('../generalization/results/additional_generalization_full_log_likelihoods_marcelbinz-Llama-3.1-Centaur-70B-adapter.pth')
centaur_8b = tor... |
4d772fd17b9497880dcdf84f3e1b694a84773bf64755ff78971ad409712bfa66 | Python | 3,593 | 95 | from itertools import chain
from typing import Optional, Tuple, Union, List
import numpy as np
import torch
from pyhealth.datasets import SampleDataset
# TODO: train_dataset.dataset still access the whole dataset which may leak information
# TODO: add more splitting methods
def split_by_visit(
dataset: Sa... |
9e215c7d6247ff529ef71ebf8b24b50313c871258162042cf4a734fe9f339ea0 | Python | 3,594 | 130 | """Bond geometry for ZnDraw."""
import typing as t
from pydantic import Field
from pydantic.json_schema import SkipJsonSchema
from .base import (
BaseGeometry,
ConnectivityProp,
InteractionSettings,
)
class Bond(BaseGeometry):
"""A bond geometry."""
position: str = Field(
default="arra... |
cf132c816a3e12d4570129e136ec9a6f206d1a880b9d9d86932c96cc8e003edf | Python | 3,595 | 103 | """Frame serialization helpers for the ZnDraw client."""
from __future__ import annotations
import base64
from typing import TYPE_CHECKING, Any
from asebytes import decode, encode
from zndraw.enrichment import add_colors, add_radii
if TYPE_CHECKING:
import ase
# ===============================================... |
46859afc4f137f73d87a6fea123cf7eb13055246143e9068f97fdc102cf01bae | Python | 3,596 | 87 | """
This file is part of the Firmware project to interface with small Async or Neuromorphic chips
Copyright (C) 2022 Willian Soares Girao - University of Groningen
Copyright (C) 2023 Ole Richter - University of Groningen
This program is free software: you can redistribute it and/or modify
it under ... |
be395ea06ca464a90bfd29cae1cb74d8da10a9c792c37ca55fbe52a232171c22 | Python | 3,599 | 99 | from rest_framework import serializers
from .models import EncryptedKey
from django.db import IntegrityError, transaction
class EncryptedKeySerializer(serializers.ModelSerializer):
class Meta:
model = EncryptedKey
fields = "__all__"
read_only_fields = ["owner"]
def validate(self, data... |
3b186f096721af29efdded71c4e083e43c9e56bece1bda955886e2e24ef415da | Python | 3,600 | 72 | import json
from src.babel_utils import norm, pull_via_urllib
from src.prefixes import DOID, OIO
def pull_doid():
pull_via_urllib(
"https://raw.githubusercontent.com/DiseaseOntology/HumanDiseaseOntology/main/src/ontology/",
"doid.json",
subpath="DOID",
decompress=False,
)
de... |
c2eedfa2ef604dc8cca3bfbb1e4a9e181c6b1bf053347b716224cf01dee6661c | Python | 3,600 | 107 | import os
from medperf.utils import get_file_hash
import pytest
import medperf.config as config
from medperf.comms.entity_resources import resources
url = "https://mock.url"
@pytest.fixture(autouse=True)
def setup(mocker, fs):
def download_resource_side_effect(url, outpath, expected_hash=None):
fs.create... |
01e0fdc4800bdf65bb5f49ae96e569eddeaa5ca459e514b76d6680f6bd1f0200 | Python | 3,601 | 126 | # -*- coding: utf-8 -*-
import numpy as np
import pytest
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.text import one_hot
from keras.preprocessing.text import hashing_trick
from keras.preprocessing.text import text_to_word_sequence
def test_one_hot():
text = 'The cat sat on the mat.'
... |
202bde964888b823801ad98048bc6996740d5c967e2a38cc395b51faea04415e | Python | 3,601 | 119 | """Tests that ZNDRAW_ROOM env var works as a substitute for --room."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
import pytest
from zndraw.cli_agent import app
from zndraw.schemas import StepResponse
from zndraw_joblib.schemas import JobSummary, PaginatedResponse, TaskResponse
... |
8823e68aaa9fa035091e0aa78c304ef7a6d016a1cee1ff4e72348556d4f6436b | Python | 3,601 | 85 | from mpi4py import MPI
import hickle as hkl
import numpy as np
from grid_cell.persistent_homology import Is_Torus
from grid_cell.manifold_fitter import GP_Fitter, Avg_Fitter
from grid_cell.ploter import error_bar_plot
import matplotlib.pyplot as plt
import tensorflow as tf
import os
from sklearn import datasets
from gl... |
70e7751cb39a19d9abe2b1089c6f9adf3449ce8cfb54cd85d5bd8667bb335f4e | Python | 3,603 | 134 | from typing import List
import math
import torch
from torch import Tensor
from torch_scatter import scatter_add, scatter_mean
import ase
from ase.calculators.emt import EMT
from ase.neb import NEB
from ase import Atoms
def remove_mean_batch(x, indices):
mean = scatter_mean(x, indices, dim=0)
x = x - mean[in... |
147275365d5875a802dacc0e37ece22817dc373358ebfd2a3762fd385c745242 | Python | 3,604 | 131 | import csv
condition_mapping_file = "../../resources/CCSCM.csv"
procedure_mapping_file = "../../resources/CCSPROC.csv"
drug_file = "../../resources/ATC.csv"
condition_dict = {}
with open(condition_mapping_file, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
condition_dict[... |
dd67a7b7d6bc52c72ca498dcd5d8f8fa69a6a972f343a9ca69f8aaac590c1e20 | Python | 3,607 | 116 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
###
# File: /home/richard/projects/biology_llm_platform/mlm/pepland/utils/commons.py
# Project: /home/richard/projects/biology_llm_platform/mlm/pepland/utils
# Created Date: Thursday, November 28th 2024, 10:42:24 am
# Author: Ruochi Zhang
# Email: zrc720@gmail.com
# -----
#... |
8a475376e6dc0e0d2d21132231bee17c1e39a3b64d9eef3fde8d6498bf44eaab | Python | 3,610 | 83 | from utils import mkdirs, savePickle, fileExist, rm
import os, sys
import subprocess, argparse, copy
"""
#############################################################################################
Script Name : main_render.py
Run : python main_render.py --blenderBin=experiments/... |
ed56bc4fc8db86576cf3450d0b849dd73d94e17149527c24e23514634e5dbd97 | Python | 3,611 | 134 | """A series of utilities for dealing with sequences.
"""
import numpy as np
"""
Note: DNA sequences are always stored from 5' end to 3' end by convention.
5'-AGGT-3'
||||
3'-TCCA-5'
sequence: 5'-AGGT-3'
complement: 3'-TCCA-5'
reverse complement: 5'-ACCT-3'
"""
# DNA bases (A, T, C, and... |
b9c05f124252d4f003e893b53b4352fe87ad45c50656f6d2a9d0532c1320affb | Python | 3,612 | 118 | import torch
import math
import sys
from tqdm import tqdm
SEED = 1717
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
EPSILON = sys.float_info.epsilon
def transform(y, num_terms=6, bandwidth_term=1/2):
B = bandwidth_term
exp = torch.exp(-B * y**2)
terms = []
for i in range(num_terms):
... |
96cd40f16687e46b2b544dbef9f110ed788f456e24391b343b21588823c79470 | Python | 3,613 | 95 | # compute the geometry of covariance matrix. Run fit_GKR_models.py first.
import os
import numpy as np
import matplotlib.pyplot as plt
import hickle as hkl
from grid_cell.manifold_fitter import label_mesh
import grid_cell.ploter as ploter
import grid_cell.torus_geometry as tg
from grid_cell.util import remove_outliers,... |
21e3357b3a9623c7e5898b58593c22f1b3a0a6755a1512fd54526ae4dcf3fdb5 | Python | 3,614 | 89 | import torch
import torch.nn as nn
import torch.optim as optim
from nnunet_mednext import create_mednext_v1
import data_loader
import yaml
import argparse
import os
'''
In this script, we provide a basic (and simple) pipeline designed for successful execution.
There are numerous advanced AI methodologies and strategi... |
1e633ed01edae9aa1d206be2554471f3c742810d257aae080ead818f32a336df | Python | 3,615 | 113 | """Image viewer support"""
from typing import List, Optional, Sequence, TYPE_CHECKING
from magmap.settings import config
if TYPE_CHECKING:
from matplotlib import artist, backend_bases, figure
_logger = config.logger.getChild(__name__)
# inspired by Matplotlib example:
# https://matplotlib.org/stable/tutorials/... |
4a8dd9f217e1cd4f33e78a3622f6ca2338d735d1ba8e16b1e04e65a5cae0fc65 | Python | 3,617 | 100 | import tensorflow as tf
from tensorflow.keras.layers import Conv2D, MaxPooling2D, \
UpSampling2D, Cropping2D, concatenate, ZeroPadding2D, SpatialDropout2D
import functools
from evidential_deep_learning.layers import Conv2DNormal
def create(input_shape, drop_prob=0.1, reg=None, sigma=False, activation=tf.nn.relu, n... |
e8c7bcb1cbd2e08bd7ff521f3589304812c9bcab89bc89a81a521e511bf8f209 | Python | 3,617 | 122 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmseg.models.decode_heads import PSAHead
from .utils import _conv_has_norm, to_cuda
def test_psa_head():
with pytest.raises(AssertionError):
# psa_type must be in 'bi-direction', 'collect', 'distribute'
PSAHead(
... |
70cf64c799d4c6c0c716c3f72dce12bb640532a932a08c112ec23ab2b27dd7e0 | Python | 3,618 | 92 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
def accuracy(pred, target, topk=1, thresh=None, ignore_index=None):
"""Calculate accuracy according to the prediction and target.
Args:
pred (torch.Tensor): The model prediction, shape (N, num_class, ...)
targe... |
b044ce379154237fa339a8ccf354432357f0723ac4e0083a477ac671c0bb7cbd | Python | 3,623 | 23 | import torch
from transformers import BertTokenizer,T5Tokenizer
from fengshen.models.GAVAE.GAVAEModel import GAVAEModel
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
encoder_tokenizer = BertTokenizer.from_pretrained("IDEA-CCNL/Randeng-GAVAE-1.2B-Augmentation-Chinese")
decoder_tokenizer = T5Toke... |
5b9efdb5cbd2d6d0641840b80b2b1fe011636c783853a8ad6743ecb736014aba | Python | 3,625 | 108 | import os
import argparse
import pprint
import pandas as pd
from rdkit import Chem
# suppress rdkit warning
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
from utils import ATOM_LIST, convert2cls
'''
preprocess:
1. remove the invalid 3d conformer
2. remove the molecules with unlabeled atoms
(we ... |
782bba5634bd5cc56492cef8a6f2ef60ac80c07a364ae8721be61dcd5323dd4e | Python | 3,625 | 101 | from CybORG.Shared import Observation
from CybORG.Simulator.Actions import Action
from CybORG.Simulator.Actions.ConcreteActions.StopService import StopService
from CybORG.Simulator.State import State
from CybORG.Simulator.Host import Host
from CybORG.Shared.Session import RedAbstractSession
from CybORG.Shared.Enums imp... |
afde373a29730d2e5ab9e648b5fb6421f189e38bc494f5f18415a83b539ffb15 | Python | 3,625 | 81 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import math
import scienceplots
import matplotlib.gridspec as gridspec
from functools import reduce
plot_8b = False
df_llama_70b = pd.read_csv('../results/all_data_unsloth-Meta-Llama-3.1-70B-bnb-4bit.csv')
df_llama_70b = df_l... |
6edeb534d474c6e50a9484231b20f0c820a13128ff95ba0f56bf98f175a673bf | Python | 3,628 | 70 | # pytest unit tests for sct_propseg
import os
import sys
import pytest
import logging
from spinalcordtoolbox.image import Image, compute_dice
from spinalcordtoolbox.utils.sys import run_proc, sct_test_path
from spinalcordtoolbox.scripts import sct_propseg
logger = logging.getLogger(__name__)
@pytest.mark.skipif(sy... |
e7b0b04fdbbc0d278983ec6801dd036292c5f44ae12fa27b09fce422cb1fad12 | Python | 3,629 | 131 | # Deep Back-Projection Networks For Super-Resolution
# https://arxiv.org/abs/1803.02735
from model import common
import torch
import torch.nn as nn
def make_model(args, parent=False):
return DDBPN(args)
def projection_conv(in_channels, out_channels, scale, up=True):
kernel_size, stride, padding = {
... |
eb4c2ac64bd22b6e13d4978ef2eb133981aeb919774beee86c1954b0892f44a3 | Python | 3,629 | 105 | #!/usr/bin/env python
import argparse
import numpy as np
import pandas as pd
from tensorflow import keras as k
def parse_input():
"""
function for parsing input parameters
:return: dictionary of parameters
"""
parser = argparse.ArgumentParser(description='Method for prediction of potential smallR... |
6f81e21a3f9a495fbf21c7c87f62b9852819dd6deaae5d56ee9776ee5bae1fda | Python | 3,630 | 112 | from typing import List, Optional
from medperf.account_management import get_medperf_user_data
from medperf.entities.aggregator import Aggregator
from medperf.entities.benchmark import Benchmark
from medperf.entities.cube import Cube
from medperf.entities.model import Model
from medperf.entities.training_exp import Tr... |
f05cd43bc0b6b00606152f0091ccc2d88539fd1c6ee6ad89f9a49af0365db67b | Python | 3,630 | 100 | """Only used when there is a job script or CWLTOOL_FORCE_SHELL_POPEN=1."""
import json
import os
import subprocess # nosec
import sys
from typing import BinaryIO, TextIO
def handle_software_environment(cwl_env: dict[str, str], script: str) -> dict[str, str]:
"""Update the provided environment dict by running th... |
8174b5a1875472ea92873e10d8147218079fc90668372db044e90ec3d4019380 | Python | 3,631 | 104 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import logging
import os
import os.path as osp
from mmengine.config import Config, DictAction
from mmengine.logging import print_log
from mmengine.runner import Runner
from mmseg.registry import RUNNERS
def parse_args():
parser = argparse.ArgumentP... |
71116e9bb5a4d7a41642c594da8289fa486b59d7a308bc10eef78695f8de266b | Python | 3,632 | 92 | """
Audit the ChEBI SDF's data-item tags against the keys make_chebi_relations() asks for.
ChEBI renames SDF tags between releases without notice. Because chebi_sdf_entry_to_dict()
matches tags by exact (normalized) string and simply omits anything it doesn't recognize, a
rename is silent: the ingest keeps running and... |
c0bc00daad4fb57ff599605f77978ab11cd1fc4b492f95091af15ce5d81a810f | Python | 3,632 | 110 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This script will prepare the CATMAID documentation and changelogs for a new
# development cycle. It inserts headers in API_CHANGELOG.md and CHANGELOG.md so
# that new changes can be recorded. It also updates the Sphinx documentation to
# refer to a development version.
... |
02247a82598191f82ce83cb9be16193e894e4bf84d350e9025c79ec8c7057750 | Python | 3,634 | 103 | import pandas as pd
def load_dataframe(base_path, batch, plate, data_level):
"""
Load a dataframe given the base path, batch name, plate name, and data level.
"""
path = f"{base_path}/{batch}/{plate}/{plate}_{data_level}.csv.gz"
return pd.read_csv(path)
def check_matching_columns(dfs_list):
... |
9bc59eafa60a528cb4c879b92224e91982448d671f1daeeb536c8752a4d2a783 | Python | 3,634 | 101 | import importlib.resources
import os
import shutil
from unittest import TestCase
import pandas as pd
from click.testing import CliRunner
from pyalfe.data_structure import DefaultALFEDataDir, Modality
from pyalfe.main import run_command
from tests.utils import download_and_extract
class TestIntegration(TestCase):
... |
54cda0e05d542b986b523134e84e92d7995fe7f7ca65f5e3ba5de80d748475e8 | Python | 3,636 | 98 | #!/usr/bin/env python
"""
Form a subset of the Flickr Style data, download images to dirname, and write
Caffe ImagesDataLayer training file.
"""
import os
import urllib
import hashlib
import argparse
import numpy as np
import pandas as pd
from skimage import io
import multiprocessing
# Flickr returns a special image i... |
038a37c2d437f6d9dd01589c168e0f53e8fbaf7e87f729044fa6e5e3659b68a8 | Python | 3,637 | 123 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 21:32:54 2024
@author: ingvieb
"""
import cv2
import numpy as np
import glob
from PIL import Image, ImageOps
import matplotlib.pyplot as plt
"""
This code makes videos out of ITK-snap screenshots.
"""
img_paths = [r"Z:\HBP_Atlasing\Developmental_atlases\DeMBA_D... |
76a60f1f8905681521e31b361008c07496f4dd7a669910090b38222059631ece | Python | 3,637 | 100 | """Tests for customising the PathMapper used to stage a CommandLineTool's inputs.
Two extension points are exercised:
* setting :py:attr:`RuntimeContext.path_mapper` (like ``make_fs_access``), and
* overriding :py:meth:`CommandLineTool.make_path_mapper` in a subclass.
"""
from collections.abc import MutableSequence
... |
6cb9f946dd88adfdf680e2b7888d674d6a822a3a50171849465d47da0777131d | Python | 3,638 | 121 | import os
import sys
import mlflow
import torch.nn.functional as F
import torch
import torch.nn as nn
from omegaconf import OmegaConf
import numpy as np
import pandas as pd
import dgl
root_dir = os.path.dirname(os.path.abspath(__file__))
def load_model(cfg):
model_path = os.path.join(root_dir, cfg.inference.mode... |
bb90f2973d4df28873532b57cae16c83894d9084714816fae8bea1901aa928fc | Python | 3,638 | 97 | # Generated by Django 4.2.11 on 2024-04-29 13:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
("mlcube", "0002_alter_mlcube_unique_together"),
migrations.swap... |
11455a71b9cb8332ab3f6ee12d5999bf9c0f4f2ba92e6e81b26239ef5752a6f2 | Python | 3,639 | 81 | import numpy as np
import tensorflow as tf
from gpflow.likelihoods.base import ScalarLikelihood
class WishartLikelihoodBase(ScalarLikelihood):
"""
Abstract class for all Wishart Processes likelihoods.
Class written by Creighton Heaukulani and Mark van der Wilk, and is adapted for gpflow 2.
"""
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.