sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
54b698938ba063f86f739f9d7363da5e2725fdfc984483bd9021423a649d2fe5 | Python | 4,150 | 117 | """
Script to compute and save inter-trial distributions
(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
num_itr: int, default=100000, -n
start_ind: int, default=0, -s
end_ind: int, d... |
66f8ac4aa064aa41e4e22be2b0d7950b466d353b92fc1cfa586fee3d6d282fa0 | Python | 4,152 | 122 | import torch
from torch import nn as nn
from torch.nn import functional as F
import numpy as np
from basicsr.models.losses.loss_util import weighted_loss
_reduction_modes = ['none', 'mean', 'sum']
@weighted_loss
def l1_loss(pred, target):
return F.l1_loss(pred, target, reduction='none')
@weighted_loss
def mse... |
8e17fc7954bbe2f8672a8f2b841829d5303d77914498dc8675f50c29e55d8fa8 | Python | 4,152 | 117 | """bluepyopt.optimisations tests"""
import numpy
from unittest import mock
import deap.creator
import deap.benchmarks
import bluepyopt.deapext.algorithms
import pytest
@pytest.mark.unit
def test_eaAlphaMuPlusLambdaCheckpoint():
"""deapext.algorithms: Testing eaAlphaMuPlusLambdaCheckpoint"""
deap.creator... |
20b6d397677e7bb5ee71f81e6ea7be9a16f6626f1022ebd663833b6e6e35d0d8 | Python | 4,156 | 126 | import numpy as np
from numpy.random import shuffle
import random
import pandas as pd
import copy
from scipy import special
def simulate_hrl(parameters, numtrials, pval, pswitch, numbandits, agentid):
softmaxbeta = parameters[0] # softmax beta
learningrate = parameters[1] # learning rate
stickiness = ... |
b974ea74d6af8866bdf1d35e5f1d4d70143c9f290403fe9ea744e2e1e04b16ec | Python | 4,157 | 122 | from __future__ import annotations
from typing import Any
import numpy as np
from CybORG import CybORG
from CybORG.Agents.Wrappers.BlueFixedActionWrapper import (
MESSAGE_LENGTH,
EMPTY_MESSAGE,
NUM_MESSAGES,
)
from gymnasium.spaces import Space
from CybORG.Agents.Wrappers import BlueFlatWrapper, BlueFix... |
4f43adbcdeb070351b6caa16b12651cb58d741291bba2c25b7949b717cb3b064 | Python | 4,163 | 160 | import os
import time
import random
import logging
from typing import OrderedDict
import torch
import torch.linalg
import numpy as np
import yaml
import json
from easydict import EasyDict
from glob import glob
class BlackHole(object):
def __setattr__(self, name, value):
pass
def __call__(self, *args,... |
c69f8e0195bc707f79936c1ba7281aedca59e64e53034a6773d58e8e126f1f7e | Python | 4,164 | 160 | import os
from kgx.source import TsvSource
from kgx.transformer import Transformer
from tests import RESOURCE_DIR
def test_read_tsv():
"""
Read a TSV using TsvSource.
"""
t = Transformer()
s = TsvSource(t)
g = s.parse(filename=os.path.join(RESOURCE_DIR, "test_nodes.tsv"), format="tsv")
n... |
0150b498204ae4e6916a790566fffacb3dea7b5c90e2b2594452bb8ccbccf68e | Python | 4,165 | 119 | import logging
from collections.abc import Iterable
from importlib import resources
import numpy as np
import pandas as pd
from rdkit import Chem
from rdkit.Chem import Descriptors
from ..Helper_funs.utils import canonicalize_smiles
with (
resources.path(
"DiastereomericResolutions.data", "cosmo_descript... |
70fbe7fa3ee7a5e648307a8d85a2f0221d6afea8eb00215a69528df0d3b3868f | Python | 4,165 | 111 | from logging import basicConfig
import torch
from torch import nn
import json
from tqdm import tqdm
import os
import numpy as np
from transformers import BertTokenizer
import pytorch_lightning as pl
from pytorch_lightning import trainer, loggers
from transformers import AlbertTokenizer
from transformers import AutoCon... |
850ba403a41be515710c94439094e9d2104fa4722539ffa835515f7a47101f10 | Python | 4,165 | 122 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
from dash import Input, Output, callback, html
import json
import plotly.express as px
import numpy as np
import scripts.styles as c
from scripts.prep_data import load_json_as_table
from scripts.utils import order_by_species
# ======================... |
ee033d1cc7c54c169c37cf8a363f7fab15cb4510872e919c71230ee6c53b354c | Python | 4,168 | 115 | """Context-Aware Implicit Neural Representations to Compress Earth Systems Model Data
DEVELOPED AT:
Department of Chemical Engineering
University of Utah, Salt Lake City,
Utah 84112, USA
DIRECTOR: Prof. Salah A Faroughi
DEVELOPED BY:
... |
573ec09df7c98503fc4a0ee8c2ec560dfbdca07ea06eb12456f623ba7a0b8ce0 | Python | 4,169 | 102 | import sys
from Bio.Seq import Seq
import re
import pandas as pd
def perfect_revcomp_match(driver, target):
"""
Returns if the perfect reverse complement of the driver is in the target.
"""
driver_revcomp = driver.reverse_complement()
return target.find(driver_revcomp) != -1
def imperfect_revcomp_... |
c7d55df6637c89f8db09a699eadd7dcf9f83c87c7e0a3163f74ae901593dec55 | Python | 4,171 | 135 | # RF_final.py
import pandas as pd
import time
import shap
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from pathlib import Path
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import (
accuracy_score... |
d3ee13d40224e0d41f4a39f33ab4d9dafa60522fda8699f285eea4ffc700fad6 | Python | 4,174 | 128 | """Tests for application lifespan management.
Tests verify:
1. App starts without REDIS_URL (auto-starts TcpFakeServer)
2. App starts with REDIS_URL (uses external Redis)
3. Storage backends are correctly initialized based on config
"""
import os
from collections.abc import Generator
import httpx
import pytest
from... |
231824f825465e9230cd353ffae039d09c9e70878b79e4a72f9dee6bbd74ba93 | Python | 4,179 | 103 | import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
from grid_cell.util import get_line
import matplotlib.gridspec as gridspec
import os
from global_setting import *
#################### Hyperparameters ####################
mouse_name = 'S'
day = 'day1'
module = '1'
session = 'open_field_1'
... |
861927055c9962e39524721db4e787c2a294d78898d058a3204114341af41b4f | Python | 4,180 | 155 | #!/usr/bin/env python3
#
# Figure 4: Highlighted subgroups
#
import sys
import numpy as np
import matplotlib.pyplot as plt
import base
# Exclude ooocytes
nooocytes = True
qand = 'and cell != "Oocyte"' if nooocytes else ''
def fit_line(ax, x, y):
""" Fit line to x and y and plot on ax """
p = np.corrcoef(x,... |
124f8c24cedee586a29fa2334d8405a66c42d47c9aaf3fa9dd3740070231896a | Python | 4,181 | 142 | #!/usr/bin/env python
# coding: utf-8
import os.path as op
import random
import time
import matplotlib.pyplot as plt
import numpy
import sklearn
import torch.nn.functional as nn_func
from sklearn import preprocessing
from sklearn.metrics import adjusted_rand_score
from torch.nn import Linear
from torch_geometric.data... |
0c14608bf772b79739762e6453590439110b5827c472ff2ad25e2ca0045cf789 | Python | 4,183 | 84 | import os
def create_key(template, outtype=('nii.gz','dicom'), annotation_classes=None):
if template is None or not template:
raise ValueError('Template must be a valid format string')
return (template, outtype, annotation_classes)
def infotodict(seqinfo):
"""Heuristic evaluator for determining w... |
af1692840d90e3c8378ccb93a32db1c2fed34274309eec5cd8ee9f9d895a5170 | Python | 4,185 | 130 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# encodermap/tests/delete_run_directories.py
################################################################################
# EncoderMap: A python library for dimensionality reduction.
#
# Copyright 2019-2024 University of Konstanz and the Authors
#
# Authors:
# Kevin Saw... |
8e3eb534f552f0a969eeef687bb208c00ec4b993d884c7208d303a119668a216 | Python | 4,189 | 126 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmengine import Config
from mmengine.structures import PixelData
from mmseg.models.decode_heads import SideAdapterCLIPHead
from mmseg.structures import SegDataSample
from .utils import list_to_cuda
def test_san_head():
H, W = (64, 64)
clip_cha... |
b41794d1b817397c67219fa4a9084e5af38f162fee6834958c5f5c190cbc41ba | Python | 4,190 | 139 | """
Visual demo for survival analysis (regression) with Accelerated Failure Time (AFT) model.
=========================================================================================
This demo uses 1D toy data and visualizes how XGBoost fits a tree ensemble. The ensemble
model starts out as a flat line and evolves in... |
a4a8d8066de20237f5570ede4cf6d8733552b3c1c5264a6e2033b4359be36b5a | Python | 4,192 | 131 | """
Quantile Regression
===================
.. versionadded:: 2.0.0
The script is inspired by this awesome example in sklearn:
https://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_quantile.html
.. note::
The feature is only supported using the Python, R, and C packages. In addition,... |
3cbf4c6feb8cd3eb2539bd64043d3284705426bc41e7e9ca3b83676d66dbb368 | Python | 4,193 | 132 | import os
import yaml
from medperf.comms.entity_resources import resources
from medperf.utils import get_file_hash, remove_path, untar
from medperf.exceptions import InvalidEntityError, MedperfException
import medperf.config as config
from medperf.entities.interface import Entity
from medperf.entities.schemas import ... |
fba982b0cf2f3e8fb77451ad47503281e26382d234e5ef43d8864fdb99cde90f | Python | 4,193 | 124 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import tempfile
from pathlib import Path
import torch
from mmengine import Config, DictAction
from mmengine.logging import MMLogger
from mmengine.model import revert_sync_batchnorm
from mmengine.registry import init_default_scope
from mmseg.models import... |
aabe8125b3d9d2647082545dd7aec852fcfee24a7284952ea08cb8bad8e2e133 | Python | 4,195 | 77 | from __future__ import division
from builtins import range
from sciunit import Score
import numpy
from sciunit.utils import assert_dimensionless
from scipy import stats
class P_Value_ObliqueIntegration(Score):
"""
P valuee from t-test. Used in ObliqueIntegrationTest.
"""
def __init__(self, score, rel... |
5178ac2811dba898fb22645a75007d7fadfb824e77059579564e1484c0ce1096 | Python | 4,197 | 79 | # 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... |
6646ba4565791d7c5135164993554a3b7ec9377dfb17ce267c96e0f5e7ca00ee | Python | 4,198 | 97 | import numpy as np
import segmented_fit
import binning
import seaborn as sns
from sklearn.preprocessing import normalize
from importlib import reload
reload(binning)
def perform_regressions_and_binning(counts_mat, expert_ind,gastonmix_labels, isodepth, gene_labels,
cell_type_df=Non... |
123b83ec8282a8ca318db9cd825c5f13fd3db82fd28e9207d2fc150ceff5d05f | Python | 4,199 | 97 | import numpy as np
import segmented_fit
import binning
import seaborn as sns
from sklearn.preprocessing import normalize
from importlib import reload
reload(binning)
def perform_regressions_and_binning(counts_mat, expert_ind,gastonmix_labels, isodepth, gene_labels,
cell_type_df=Non... |
18b7c3e39ebdf2de8aff1a36cb793f0adf17fd9b481c7a03e939fb5004fe6622 | Python | 4,199 | 89 | import os
import numpy as np
from .utils import split_filename, get_image_data_format
def undo_reorient(data, orig_orient, target_orient):
import nibabel as nib
orient_dict = {'R': 'L', 'A': 'P', 'I': 'S', 'L': 'R', 'P': 'A', 'S': 'I'}
target_orient = [orient_dict[char] for char in target_orient]
... |
1eade410b939ba4e7c7db35016e0308212cf2fba8099872867d2ffa3b650b289 | Python | 4,199 | 130 | import os
from pathlib import Path
import pickle
import numpy as np
import pytest
from masscube.params import Params
from masscube.raw_data_utils import (
MSData,
Scan,
TDFReader,
get_raw_data_format,
read_raw_file_to_obj,
)
class _UnitFloat(float):
unit_info = "second"
def test_raw_data_u... |
e42b5ef3cb3433bc7b5b082b1aaceaaa8b2a91d47f88bcbc3eb60ea81b42db3f | Python | 4,200 | 126 | """Test optional udocker feature."""
import copy
import os
import subprocess
import sys
from pathlib import Path
import pytest
from _pytest.tmpdir import TempPathFactory
from .util import get_data, get_main_output, working_directory
LINUX = sys.platform in ("linux", "linux2")
UDOCKER_VERSION = "1.3.12"
@pytest.fi... |
26977f07c19b35a9200f74e2da1bde56cbc81ec963bd4d19683ae17dc480d17e | Python | 4,201 | 144 | #!/usr/bin/env python3
import os
import re
import numpy as np
def parse_raw_xmf(xmfpath):
'''
Returns shape and path to `.raw` file
xmfpath: path to `.xmf` metadata file
'''
with open(xmfpath) as f:
text = ''.join(f.read().split('\n'))
m = re.findall(
'<Xdmf.*<Attribute.*'
... |
3aa2b180d941727bb151e358c3968981aa702822cd37fa8c97823c14a3b8c07a | Python | 4,204 | 120 | 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... |
43d81cec85df427af03eafdaa17d0ff37b68dd21202e552dea9eb67a0a799ef1 | Python | 4,207 | 117 | # -*- coding: utf-8 -*-
# tests/conftest.py
################################################################################
# EncoderMap: A python library for dimensionality reduction.
#
# Copyright 2019-2024 University of Konstanz and the Authors
#
# Authors:
# Kevin Sawade, Tobias Lemke
#
# Encodermap is free softwa... |
0b2f9bc51c6654eae0cfd056f2bd356c82af81e8ce633164d89e7270c13ac6b2 | Python | 4,210 | 101 | 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... |
6d40d51ab09f559249c011484e10b5a805a58fdc567128f08f2b04258e6a99ff | Python | 4,210 | 120 | import torch
import pytorch_lightning as pl
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger
from pytorch_lightning.callbacks import ModelCheckpoint
import wandb
import yaml
from collections import defaultdict
from pathlib import Path
import argparse
import shutil
from models.egnn_model import ddg... |
e5b2fd8c24f7d6a918f86f4cb0ae6ce7f421073f2e6b2f50d6704a04e584f7e1 | Python | 4,211 | 120 | from behavior_analysis.experiment import PreyCaptureExperiment
import numpy as np
from sklearn.manifold import TSNE
from sklearn.neighbors import NearestNeighbors
from matplotlib import pyplot as plt
from scipy.spatial.distance import pdist, squareform
from scipy.stats import ttest_ind, wasserstein_distance
if __na... |
9abd924eb1e0f1d538f0416397b55a6dd7b9bd3ce60d84fd5755f7cd19d2e859 | Python | 4,212 | 92 | # compute the speed modulation of each cell, by fitting a line between firing rate and speed
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from grid_cell.grid_cell_processor import Grid_Cell_Processor, Speed_Processor, Data_Transformer
from grid_cell.lasso_evaluation import lasso_evaluate_multi... |
976a7844fa2ac1a0456ef737f84c8c1074b099b90ecc5e32c3b1072251c8442d | Python | 4,215 | 101 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from common import db_connection
import sys
limit = 50
if len(sys.argv) != 2:
print("Usage: describe-concept.py <CONCEPT-ID>", file=sys.stderr)
sys.exit(1)
cid = int(sys.argv[1])
c = db_connection.cursor()
# Find which table the concept is really in, and also ... |
bf5f3b4d93c4c290085dba8c8fd273eae777e56b09acc3cb27309b682c4a3bc5 | Python | 4,215 | 126 | """Helper functions for docker."""
import subprocess # nosec
def docker_vm_id() -> tuple[int | None, int | None]:
"""
Return the User ID and Group ID of the default docker user inside the VM.
When a host is using boot2docker or docker-machine to run docker with
boot2docker.iso (As on Mac OS X), the... |
6945f44bbb773c02805ce41e74c2fd3debfd363d0cb0eb1d49dc4c9c51446af7 | Python | 4,218 | 127 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmseg.registry import MODELS
from ..utils import SelfAttentionBlock as _SelfAttentionBlock
from ..utils import resize
from .cascade_decode_head import BaseCascadeDecod... |
b61e7260697883afcced16e5bdb284b06001f8283b50deddc57ba2a0f6b93de1 | Python | 4,220 | 119 | import logging
from google.cloud import compute_v1
import time
from .types import GCPOperatorConfig, CCWorkloadID
# taken and adapted from
# https://docs.cloud.google.com/compute/docs/samples/compute-start-instance#compute_start_instance-python
def __wait_for_extended_operation(operation, verbose_name, timeout: int =... |
378084c27d12fbfcbcfb2e1e509f9df38f25132fa9a8c4404a47599e3f48f902 | Python | 4,221 | 135 | """
A demo for multi-output regression
==================================
The demo is adopted from scikit-learn:
https://scikit-learn.org/stable/auto_examples/ensemble/plot_random_forest_regression_multioutput.html#sphx-glr-auto-examples-ensemble-plot-random-forest-regression-multioutput-py
See :doc:`/tutorials/mult... |
c045a1ada11c7d336552cb49cd81b727ce4341622b28b0480b6087a8904f70f1 | Python | 4,223 | 99 | import numpy as np
import matplotlib.pyplot as plt
from grid_cell.linear_regression import fit_a_line, output_params, draw_line
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 hickle as hkl
import os
from global_set... |
869175c2810fdc815c40d479300a339d3d144e4dadc78864eb9808f2a5be08b2 | Python | 4,224 | 117 | from glob import glob
import json
import CCF_translator
import cv2
from utils.generate_target_slice import (
generate_target_slice,
generate_target_coordinates,
)
import numpy as np
from tqdm import tqdm
from utils.deform_utils import triangulate, transform_vec
import nibabel as nib
from utils.NearestNDInterpol... |
d45e9d8fe08388ce8489954151760fc6c90959630bde21d22e77faf2380a52a6 | Python | 4,224 | 134 | import numpy as np
import matplotlib.pyplot as plt
def LRT_basic(LRT_res):
fig = plt.figure(figsize=(10, 3))
plt.subplot(1, 3, 1)
plt.hist(LRT_res.Wc_loc.numpy()[:, 0], 30)
plt.xlabel("weight")
plt.ylabel("#genes")
plt.subplot(1, 3, 2)
plt.hist(LRT_res.LR[:, 0], 30)
plt.xlabel("log lik... |
b7a6c94273ec8527c4b015e4233e2b2fdebf04b1ac813f2690e542518d91a388 | Python | 4,225 | 109 | import matplotlib.pyplot as plt
import seaborn as sns
import os
import pandas as pd
# top_node: CTX-Ex 11637
# top_edge: DG_DG 9352
# top_triangle: DG_DG_DG 2966
simulate_type = 'cc'
level = "size5"
original_result_path = 'spatial_13months-disease-replicate_1/spatial_13months-disease-replicate_1_disease_'+ level + '... |
f41086fa05c0e20e68f424350620fd9b46811993021723af59b9ffa44be129c1 | Python | 4,225 | 116 | import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from matplotlib.gridspec import GridSpec
import imageio.v3 as iio
import matplotlib.image as mpimg
from pathlib import Path
img = mpimg.imread(Path("WFE_Cartoon.png"))
im = iio.imread(Path("WFE_Cartoon.png"))
print(im.shape)
time2_synced = pd.r... |
32d2e1cbe59b468395568110e7b1de9af8a388528492d034983410b4986966dc | Python | 4,226 | 84 | import torch
import math
import matplotlib.pyplot as plt
import seaborn as sns
import scienceplots
import matplotlib.gridspec as gridspec
import numpy as np
from scipy import stats
centaur_70b = torch.load('../generalization/results/additional_generalization_full_log_likelihoods_marcelbinz-Llama-3.1-Centaur-70B-adapte... |
86b84aab01638e190772a5a2ee6f4f570d99c6df788eb179aa21181cd038093e | Python | 4,227 | 101 | import numpy as np
import matplotlib.pyplot as plt
from grid_cell.grid_cell_processor import Speed_Processor
from ripser import Rips
from grid_cell.persistent_homology import find_quantile_lifetime, cloud_2_sparse_mat
import hickle as hkl
import os
from grid_cell.grid_cell_processor import Grid_Cell_Processor
from grid... |
637ba4ca2fe0d4703390eff478b8bbbcb9b8930e5130234b5fab43331a1952b8 | Python | 4,232 | 143 | #!/usr/bin/env python
"""
MetaWIBELE: extract_abundance_sample_subset module
Extract the subset of abundance table based on specific samples
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 fi... |
d7a8d463bfe4447a98cbbb80ecb53941265dfe222a6190479335cfdc456d64ed | Python | 4,232 | 99 | ######################################
# wrapper for rule: filter_single_genomic
######################################
import os
import sys
import math
import subprocess
import glob
from snakemake.shell import shell
UMITOOLS = "umi_tols"
SAMTOOLS = "samtools"
BAMCOVERAGE = "bedGraphToBigWig"
shell.executable("/bin/b... |
0abe9e893a12f6cf2576a0ac15bfa9fe08891900101a975097250899f880c36d | Python | 4,235 | 122 | """Tests for admin token minting."""
import pytest
from httpx import AsyncClient
from zndraw_auth import TokenResponse, UserCreate, UserRead
async def _get_auth_header(
client: AsyncClient, email: str, password: str
) -> dict[str, str]:
"""Register, login, return auth header."""
user_data = UserCreate(e... |
a59f868d5a22e60080466c5172a77d341bd9adef41f52cd9f3e182f2dc9ccf40 | Python | 4,235 | 88 | """Pipeline tests for the DOID data handler, run against a real built concord.
Skipped by default unless pytest is run with --pipeline. Run with:
uv run pytest tests/pipeline/test_doid.py --pipeline --no-cov -v
"""
import collections
import os
import pytest
from src.babel_utils import remove_overused_xrefs
fro... |
69cae6ea83c2440f9e96a9d1ad494cf785cd6dbd39d78c909f23cfdc8211c7ef | Python | 4,237 | 107 | from medperf.entities.certificate import Certificate
from medperf.entities.model import Model
from medperf.exceptions import MedperfException
from medperf.asset_management.asset_management import update_model_cc_policy
from medperf.asset_management.gcp_utils import CCWorkloadID
from medperf.entities.benchmark import Be... |
72686086a35ee58a1ddd530d50d1c1bf6fa3275b65784eac0649bcce9e19561a | Python | 4,237 | 122 | import os
import numpy as np
import matplotlib.pyplot as plt
import torch
import shap
import Adversarial_Observation as AO
def getData(dataloader):
"""
Get one sample of each class from the dataloader.
"""
data = []
target = []
for batch_idx, (data_batch, target_batch) in enumerate(dataloader... |
7cc26248ac163d2946527b7ef701984995db00fc6c75f38d593391d179659a42 | Python | 4,240 | 124 | import inspect
from typing import Dict, Tuple
from pprint import pprint
from random import randint
from CybORG import CybORG
from CybORG.Agents.SimpleAgents.BaseAgent import BaseAgent
from CybORG.Shared.Enums import TernaryEnum
from CybORG.Simulator.Actions import Action, Sleep, InvalidAction
class LinearAgent(BaseA... |
e419a746fe4bbcc1933595895412398d54994130d07771d4319b52f2ccd572f1 | Python | 4,240 | 112 | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
import numpy as np
from mmcv.transforms import to_tensor
from mmcv.transforms.base import BaseTransform
from mmengine.structures import PixelData
from mmseg.registry import TRANSFORMS
from mmseg.structures import SegDataSample
@TRANSFORMS.register_modu... |
016c4795f3da4c3af0ded8af7ef4fdfdb99203e79164d7d4b844e7862a5ff91c | Python | 4,241 | 133 | import pytest
import numpy as np
import pandas as pd
import networkx as nx
from neuprint import Client, default_client, set_default_client
from neuprint import (fetch_skeleton, heal_skeleton, reorient_skeleton, skeleton_df_to_nx, skeleton_df_to_swc, skeleton_swc_to_df)
from neuprint.tests import NEUPRINT_SERVER, DATA... |
f1bd6a1fad637f77669c1dd3b464b88ba53d87012ae0a911708ba8af55174d4b | Python | 4,244 | 133 | """
Script for transforming the motion timing instructions for the motion
timing experiment into a corresponding exclusion mask.
"""
import numpy as np
import matplotlib.pyplot as plt
import os
import h5py as h5
def create_scan_order_file(h5_file, out_file):
"""
Generate text file containing the acquisition ... |
6fe4908c473bb2f4e72ba7ef140c68fd7df4277285c37d2ec6cf598714a47aee | Python | 4,245 | 114 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import tempfile
import zipfile
import cv2
import mmcv
from mmengine.utils import mkdir_or_exist
def parse_args():
parser = argparse.ArgumentParser(
description='Convert DRIVE dataset to mmsegmentation format')... |
20830d9acbc8f5ad08c428bd94bf260aa307849b6a9f6cbbd1ff5d74a8841f94 | Python | 4,246 | 150 | """
Generate random rotation matrices of arbitrary size and rotate matrices
"""
import numpy as np
from numpy.linalg import qr
from sklearn.utils.validation import check_random_state
from scipy.stats import special_ortho_group
def direct_method(n, seed=None):
rs = check_random_state(seed)
# 1. Draw n independe... |
652e941b6f1bf83afa30d100de6a53ce959a11eb3172786ec3041b5f6ea6a472 | Python | 4,247 | 110 | """Reusable Panel component for Step-4 transient-peak visualization.
A terminal read-only display composed by ``orchestration/transients_view.py`` and served
on the persistent main app after the transient-analysis compute job finishes. A single
selector switches between every ``z_score`` / ``dff`` trace across the run... |
1ad838b230038b79f3915011c5f3adb21ad07c0d46ae78438d07b6db150a9bc2 | Python | 4,250 | 150 | import os
import pytest
import rdflib
from pprint import pprint
from kgx.sink import RdfSink
from kgx.transformer import Transformer
from tests import TARGET_DIR
from tests.unit.test_sink import get_graph
def test_write_rdf1():
"""
Write a graph as RDF N-Triples using RdfSink without reifying all edges.
... |
bbcb170750ba1fcb6369d0dca80fc76b0ba2805c5239aac2c27ccaa91f023b83 | Python | 4,251 | 141 | """
Generate Tripos mol2 files with AM1-BCC charges from canonical isomeric SMILES strings.
Molecules will be named after database key.
"""
import os
from openeye import oechem
from openeye import oeiupac
from openeye import oeomega
from openeye import oequacpac
import utils
def generate_molecule_from_smiles(smil... |
edd44dc9779e3366ced10a8a53757ef4988ad018aa043cdf6cff05e66101483c | Python | 4,253 | 104 | from experiment import *
import numpy as np
import cv2
from scipy import ndimage
def rotate_and_center(img: np.ndarray, xy: tuple, radians: float):
h, w = img.shape
x, y = xy
cos = np.cos(-radians)
sin = np.sin(-radians)
M1 = np.array([[1, 0, -y],
[0, 1, -x],
... |
4f0d5a6e6a078b5474198e01b39fb247b6203a73acd9571610ce2d13fdebd616 | Python | 4,254 | 108 | import gzip
from json import loads
from src.babel_utils import make_local_name, pull_via_ftp, pull_via_urllib
from src.predicates import HAS_EXACT_SYNONYM, HAS_RELATED_SYNONYM
def pull_pubchem_labels():
print("LABEL PUBCHEM")
f_name = "CID-Title.gz"
cname = pull_via_ftp("ftp.ncbi.nlm.nih.gov", "/pubchem/... |
be4c3e34dba9c0aca9f79771c18b0ee664446701420471f05f181f60e7bdd5c8 | Python | 4,258 | 141 | ###########################################################################################
# Tools for torch
# Authors: Ilyes Batatia, Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
import logging... |
baf8461f6a1f224b1abbea491380c3adc8fa92be18c8fbc6043fd6a394c14709 | Python | 4,259 | 78 | 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
from brokenaxes import brokenaxes
selected_tasks = ['peterson2021using', 'ruggeri2022globalizability']
df_random = pd.read_c... |
63ca3519c52eb129af93e9ddcd0d99d0d03bf21746f9e555f405176af50f3b74 | Python | 4,260 | 110 | import random
import torch
from ._base import _index_select_data, register_transform, _get_CB_positions
@register_transform('focused_random_patch')
class FocusedRandomPatch(object):
def __init__(self, focus_attr, seed_nbh_size=32, patch_size=128):
super().__init__()
self.focus_attr = focus_attr
... |
15e5bcf3d9121aa0045a007aa85645524ff23e0f7861c7fec2b36b68e26ef1bd | Python | 4,263 | 115 | import os
import shutil
from glob import iglob
import random
import json
random.seed(7)
def __copy_modalities(input_folder, modalities, output_folder):
for file in iglob(os.path.join(input_folder, "*.nii.gz")):
for modality in modalities:
if file.endswith(f"{modality}.nii.gz"):
... |
9e65e58469b04b80a994c86e032f6e24a8483e2a81d236e45f04dcc7859db4dc | Python | 4,266 | 137 | # model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
data_preprocessor = dict(
type='SegDataPreProcessor',
mean=[122.7709, 116.7460, 104.0937],
std=[68.5005, 66.6322, 70.3232],
bgr_to_rgb=True,
pad_val=0,
seg_pad_val=255,
size_divisor=640,
test_cfg=dict(size_divisor=32))
... |
02f365f314a59c46b296e885bd0180b03f76b3331c7fee2504658bc93799efeb | Python | 4,268 | 115 | from rest_framework import serializers
from django.utils import timezone
from benchmark.models import Benchmark
from model.models import Model
from .models import BenchmarkModel
from utils.associations import (
validate_approval_status_on_creation,
validate_approval_status_on_update,
should_auto_approve_mo... |
549d77cb1646273bc2c94366672683c2b907ddb7d5d2705a7b4bf677d1d1b6e3 | Python | 4,268 | 75 | # pytest unit tests for sct_get_centerline
import logging
import os
import numpy as np
import pytest
from spinalcordtoolbox.image import Image
from spinalcordtoolbox.scripts import sct_get_centerline
from spinalcordtoolbox.utils.sys import sct_test_path
logger = logging.getLogger(__name__)
@pytest.mark.sct_testin... |
eca7b1664d24b2cd2d839b6ac402fea5e5cdc9753909916ec0d866c673297490 | Python | 4,268 | 124 | import jax
import jax.numpy as jnp
import pathlib
from mlff.mdx.potential.mlff_potential_sparse import load_model_from_workdir
def make_so3lr(
lr_cutoff=12.,
dispersion_energy_cutoff_lr_damping=2.,
calculate_forces=True,
workdir=None
):
if workdir is None:
# Use default SO3LR params direc... |
53ef2fd345025833b85f80a86a004be03ac96e2144ee9995af6a25395eb72b6b | Python | 4,269 | 105 | """
## 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... |
b63f86be9ea5aa0fddb6148bbb0a391e4c0ac0b03106872fc0b3a53aff54131b | Python | 4,269 | 135 | """
calculate time to generate 1000 nulls for each surface
"""
# load libraries
import numpy as np
from eigenstrapping import SurfaceEigenstrapping, VolumetricEigenstrapping
import time
import threadpoolctl
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from parspin import simnulls
from data... |
7ef9e7cbf101444801b9ce8f4d22bfb7f6c8e3b91925ba4e5ae10d7c02e12bc8 | Python | 4,270 | 101 | import numpy as np
import pandas as pd
from ..gui.sda_widgets import _precalculate
from PyQt5.QtWidgets import QApplication
def extract_event_based_data(session, cells, event_indices, window_size, event_type="events", num_subwindows=1, name=""):
"""
Returns a dict mapping each cell_id to its own DataFrame.
... |
bce9152d3840e05cbcd570dd02a997706ca4228a826263b72a9ae3f59c1208e2 | Python | 4,270 | 124 | import pandas as pd
import numpy as np
import scipy.stats
# AUC comparison adapted from
# https://github.com/Netflix/vmaf/
def compute_midrank(x):
"""Computes midranks.
Args:
x - a 1D numpy array
Returns:
array of midranks
"""
J = np.argsort(x)
Z = x[J]
N = len(x)
T = np.z... |
17927380179ecb1bff1442144202ed643989bf3c04725f95876f519919605c70 | Python | 4,271 | 105 | # 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... |
2c986aeb689a94b96841ff82e4edf40ba038189a69a4e5f67a3eff2b1561ec22 | Python | 4,273 | 172 | import numpy as np
import numpy.testing as npt
import pathlib
import pytest
from ase.io import read
from mlff.md.calculator_sparse import mlffCalculatorSparse
@pytest.mark.parametrize('name', ['atat', 'dha', 'bb'])
def test_molecules(name: str):
package_dir = pathlib.Path(__file__).parent.parent.resolve()
ta... |
37eff995814a93afa68f55bb0c4696c7c4469be68a6266af41cae3fd0678514b | Python | 4,275 | 101 | import torch
import torchvision
import Adversarial_Observation as AO
import numpy as np
import matplotlib.pyplot as plt
import os
import tqdm
def main():
# Seed everything
AO.utils.seed_everything(6991)
train_loader, test_loader = AO.utils.load_MNIST_data()
model = AO.utils.load_MNIST_model()
if ... |
7156ace17256a5115fb6959355a57a56ca8ba99244993bf2664c4638bcdcae48 | Python | 4,275 | 118 | from django.db import migrations, models
import django.contrib.gis.db.models.fields
forward = """
BEGIN;
ALTER TABLE connector_geom RENAME TO connector_geom_old;
-- Create new version of the connector_geom table which uses the bigint
-- data type for its ID. All other constraints will be added after... |
7435457096703c41a89c5b5253bf0de2e9b84b24f9bf06003cfb79742527cdb2 | Python | 4,279 | 131 | import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from matplotlib.gridspec import GridSpec
import numpy as np
from pathlib import Path
time2_ced = pd.read_csv(Path("time2_ced.csv"))
ycurrent = pd.read_csv(Path("ycurrent.csv"))
apdm_data = pd.read_csv(Path("apdm_data.csv"))
leftSide = pd.read_cs... |
8b8788a34a4d620af5caf1f06e430752f4dd84733c5369e377d76e522de69c78 | Python | 4,279 | 144 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm
from mmseg.models.backbones.hrnet import HRModule, HRNet
from mmseg.models.backbones.resnet import BasicBlock, Bottleneck
@pytest.mark.parametrize('block', [BasicBlock, Bottleneck... |
0fb6d670ecaf0b9e5422b230ea7ef5df668aeea3e452205613bc1bd28099c710 | Python | 4,280 | 122 | import requests
import os
from .ProvenanceObject import ProvenanceObject
from .dependency import Dependency
from .task_status import TaskStatus
from .dataset import DataSet
from .performance import Performance
from datetime import datetime
dfa_url = os.environ.get('DFA_URL',"http://localhost:22000/")
class Task(Prov... |
bce54a6a81807213042fc41546a309565c246ae8592c96fe63329b427244c136 | Python | 4,283 | 114 | ##
## CPCantalapiedra 2020
from collections import Counter
from ...emapperException import EmapperException
from ...utils import colorify
from .pfam_denovo import pfam_align_denovo
from .pfam_scan import pfam_align_parallel_scan
PFAM_REALIGN_NONE = 'none'
PFAM_REALIGN_REALIGN = 'realign'
PFAM_REALIGN_DENOVO = 'deno... |
236b1805ed43b03b979d17e6395420c730ff4d58c0a0a93e4526fec02aebc97f | Python | 4,287 | 95 | import multiprocessing
import os
from pathlib import Path
import holoviews as hv
import panel as pn
import pytest
from guppy.settings import SETTINGS_PATH_VARIABLE
# Use "spawn" start method for all multiprocessing in tests. "fork" (the Linux
# default) can deadlock when forking a multi-threaded pytest host, and can... |
81adf4778449807786c4b412a34a4826a73cd91972a6c33bb15b7aa233071b78 | Python | 4,288 | 113 | # -*- coding: utf-8 -*-
import json
import logging
from typing import Any, Dict, Optional
from django.http import HttpRequest, JsonResponse
from django.contrib.auth.decorators import user_passes_test
from catmaid.models import UserRole, Log, ReviewerWhitelist
from catmaid.control.common import get_request_bool
from ... |
6b623c2689678806e8bc3c259dfbdc993c38c2a2f07173b1767762fdcf18ab8f | Python | 4,289 | 136 |
fileNum=152000
numJobsPerHour = None # adds a delay to submit jobs
# remove the delay by using None
baseFileName = './shellScripts/genReport_SHD_'
commandsPerJob = 4
commandLength = 55 # minutes
jobLength = commandsPerJob * commandLength
# automatically determine the smallest
# node for the j... |
c5a5fd5366b8724a3d3e239726958a1220ab822bfdca4be3e907bc344c99e792 | Python | 4,290 | 92 | # run lca_iid first
import numpy as np
import matplotlib.pyplot as plt
import hickle as hkl
import os
from sklearn.linear_model import LogisticRegression
from grid_cell.grid_cell_processor import Speed_Processor
from grid_cell.locf_grid_cell import compute_locf
from grid_cell.toy_locf import calculate_locf_accuracy_upp... |
7175d2d1330274a35ac1926f6fefdbe321eda139b51d538f0d9654094dba8b32 | Python | 4,291 | 87 | # 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... |
bedb7528696950db891c2340673e66959ba292003b7e1f72c7fc718514cfb54b | Python | 4,296 | 130 | import ml_collections
def get_b16_config():
"""Returns the ViT-B/16 configuration."""
config = ml_collections.ConfigDict()
config.patches = ml_collections.ConfigDict({'size': (16, 16)})
config.hidden_size = 768
config.transformer = ml_collections.ConfigDict()
config.transformer.mlp_dim = 3072
... |
e5866abf43efb66a640a259857c21fe5c0930970b438faf22d418c10e280e2fd | Python | 4,296 | 116 | # Copyright (c) OpenMMLab. All rights reserved.
import os
from typing import Dict, List, Optional, Sequence, Union
from mmseg.registry import DATASETS
from .basesegdataset import BaseSegDataset
try:
from dsdl.dataset import DSDLDataset
except ImportError:
DSDLDataset = None
@DATASETS.register_module()
class... |
e89eea83e691dd3fd857820373a0665f99177f6020d0cfc001e5bf3ab6776071 | Python | 4,297 | 111 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
from fig_utils import *
import os
def panela_model(fig, grid, data_dict, il, transl):
ax1 = plt.subplot(grid[0,0])
il = plot_label(ltr, il, ax1, transl, fs_title)
ax1.set_title('Minimodel structure')
ax1.axi... |
b512a90902f65b3a04350ae5382509061576ff94d90a97ad5677dac25086d675 | Python | 4,298 | 87 | import numpy as np
import pandas as pd
import pytest
from guppy.analysis.standard_io import read_tonic_epochs, write_tonic_to_hdf5
from guppy.analysis.tonic import compute_tonic_means
class TestComputeTonicMeans:
@pytest.fixture
def traces(self):
# timestamps 0,1,2,...,10; z_score = timestamps; dff =... |
5465c818d732f265efb450b67bbc251fe9609e4ffb8e8919467240e8cb661233 | Python | 4,299 | 112 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sep 5, 2023
@author: Claire Cooper
"""
from RipNetClaire import RipNetClaire
from tensorflow.keras.regularizers import l2
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import argparse
import os
import scipy.io
from butter impor... |
b666cd620817ab3471b432860d0f812a641fba37e83bdd02c2f606eea680e5ff | Python | 4,305 | 148 | """Curve geometry for ZnDraw."""
import typing as t
import numpy as np
import splines
from pydantic import BaseModel, Field
from pydantic.json_schema import SkipJsonSchema
from .base import (
BaseGeometry,
ColorProp,
InteractionSettings,
PositionProp,
)
class CurveMarker(BaseModel):
"""Settings... |
0c75c7d3d39d07d7db58978183caf87ef820320398899cc8f21e59fe159e8071 | Python | 4,306 | 155 | """
Generate random rotation matrices of arbitrary size and rotate matrices
"""
import numpy as np
from numpy.linalg import qr
from sklearn.utils.validation import check_random_state
modes = np
def direct_method(n, seed=None):
rs = check_random_state(seed)
# 1. Draw n independent random normal N(0, 1) variate... |
2ec3c1b1cec85adb0ee585bd25913a0cc64c8c62aff97df3c6bdd7f9b8ffd93e | Python | 4,306 | 106 | import numpy as np
import pandas as pd
from pathlib import Path
from rdkit.Chem.Scaffolds import MurckoScaffold
from AddingLabel import adding_label
def scaffold_cluster(csv_path):
df = pd.read_csv(csv_path)
df['Scaffold'] = None
print(len(df.SMILES.tolist()))
# create dict of the form {scaffold_i: [... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.