sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
9fed5663b288e939d99aef538f46453f88af316ee2d4f8734167092bf992d26f
Python
2,996
74
import holoviews as hv import numpy as np import pytest from guppy.visualization.transients import build_peaks_overlay from guppy_test_data import resolve_plot @pytest.fixture def timestamps(): return np.array([0.0, 1.0, 2.0, 3.0, 4.0]) @pytest.fixture def z_score(): return np.array([0.5, 1.5, 0.2, 2.5, 0....
40e8d8c76e1561333bc8dee9e85b0354f1d8a58307ee998036a406ca5c196b11
Python
2,997
94
import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn.metrics as metrics def plot_roc_auc(): # Create figure plt.figure(figsize=(10, 8)) # Define colors for different modes (expand as needed) colors = plt.cm.rainbow(np.linspace(0, 1, len(mode_list))) for mode, col...
db11efd9fee2f5b49668346d569e75d734c1a9c4f2f5e25aa16a35d87d639448
Python
2,997
60
import sys tumor_id=T2 # specify ID age=77*365 # specify age (in days) import math import numpy as np from pyabc.external.r import R r = R(tumor_id+"Run_model_heme_WGS_data_2_branched_clones.R") model = r.model("myModel") distance = r.distance("myDistance") sum_stat = r.summary_statistics("mySummaryStatistics") ...
b934e7f6ebdab7c5faa800c0a261abd31420aba26afb7dce18e15ffddd2b69ca
Python
2,998
89
""" Generate all nulls for annotations """ from pathlib import Path import numpy as np from eigenstrapping_analysis.utils import ( get_rootdir, MSEED, get_medial, join, save_npy, load_npy, get_num_threads ) from eigenstrapping import SurfaceEigenstrapping from neuromaps.nulls import alexander_bloch, burt2020...
300ebe6157c959793a05ebfcca9920f155d004abab8b29122fb2aed7f8900ce1
Python
2,999
92
# Authors: Pierre Ablin <pierre.ablin@inria.fr> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import warnings import pytest import numpy as np from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_warns from picard import Pica...
140b63672eb10555ba0b9899ab5c5ebf6ffabec31c521936c18da5393ffbad0c
Python
3,000
82
#!/usr/bin/env python import argparse import torch from torch.utils.data import DataLoader from rdkit import Chem from rdkit import rdBase from tqdm import tqdm from MCMG_utils.data_structs import MolData, Vocabulary from models.model_rnn import RNN from MCMG_utils.utils import decrease_learning_rate rdBase.DisableL...
226a09fd6f4bee44a4d42a08722ed255a920cc68b0c8ec1af71421e5e34a6944
Python
3,001
115
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import math import torch from ..initializers import he_orthogonal_init class Dense(torch.nn.Module): """ Combines dense layer wit...
3315e6ee6629e831fddc47e0c6af29c4840de1f021f05f7b0df9e5467e5ab28c
Python
3,003
79
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ # Borrowed from https://github.com/rusty1s/pytorch_geometric/blob/master/torch_geometric/transforms/random_rotate.py # with changes to keep t...
9ca8aa517afad244216632ca8c339a276ef43515e5dd73f19fe404025f6aa487
Python
3,003
93
"""E2E test: Client data persists across disconnect/reconnect cycles. Uses a real uvicorn server via the server_factory fixture. """ import ase import numpy as np from zndraw import ZnDraw def _make_atoms(x: float) -> ase.Atoms: """Create a simple H atom at position (x, 0, 0).""" atoms = ase.Atoms("H", pos...
c76314940364e401750ce7a829516305293c8f65fea0eb0a7bb1b0ac8ad54c51
Python
3,003
72
# -*- coding: utf-8 -*- @login_required def initialize_components_for_skeleton(request, project_id=None, stack_id=None): skeleton_id = int(request.POST['skeleton_id']) # retrieve all treenodes for the given skeleton treenodes_qs, labels_qs, labelconnector_qs = get_treenodes_qs( project_id, skeleton_id ) ...
deed638affd6a639f1ffd971f55ed666b0831d82a4239ba59441366505fe51ae
Python
3,003
94
import json import argparse from pathlib import Path def get_class_labels(data): class_labels_map = {} index = 0 for class_label in data["labels"]: class_labels_map[class_label] = index index += 1 return class_labels_map def load_ground_truth(ground_truth_path, subset): with grou...
a422a54ea27d0dfd8b9d0d1fd0596a54a2c3250dc96e8d6fb820eb6bd7c4098c
Python
3,005
74
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ====================================================================== # SCRIPT INFORMATION: # ====================================================================== # SCRIPT: UPDATE THE FIELDMAP JSON FILES # PROJECT: ZOO # WRITTEN BY LENNART WITTKUHN, 2020 # CONTACT: WI...
8fedac02af27225b0c8a23166e190cba6b0db9dc8fb60d089ad6549b85b4a1fe
Python
3,006
92
import logging import numpy as np import torch import torch.nn as nn class SkipNetwork(nn.Module): """ Implements a Skip network which starts with takes a tensor of shape N x in_dims as input and outputs N x out_dims as output Inbetween the input and the output is a fully connected network with added...
c4a0657db2a92bda2a7ff116cd4017f6b1c59af6408093d8874eb08a0df476ad
Python
3,007
93
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """Some utilities for backbones, in particular for windowing""" from typing import Tuple import torch import torch.nn as...
0706eea5dd93baa47ea5ff9895c5b33f0338bc67ae9b346194ca564f4e9eeea4
Python
3,008
106
import numpy as np import pytest import torch from simgen.manifolds import ( MultivariateGaussianPrior, PointCloudPrior, StandardGaussianPrior, ) def test_standard_gaussian_prior_calculates_correct_restorative_forces(): positions = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) forces = StandardGau...
7895389fdf69968338497f72721afe73d6d31773f91c4cac904d59c006bb569d
Python
3,008
89
# -*- coding: utf-8 -*- import json from catmaid.models import Message from .common import CatmaidApiTestCase class MessagesApiTests(CatmaidApiTestCase): def test_read_message_error(self): self.fake_authentication() message_id = 5050 response = self.client.post(f'/messages/{message_id}...
53066c8bd5a1a8aa10a0568836cd794a1d053018b7bc3feae9bb31ab10d0380e
Python
3,009
94
# generate rate map data import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcolors import matplotlib.colorbar as mcolorbar from matplotlib import cm import grid_cell.ploter as plter import os from grid_cell.grid_cell_processor import Grid_Cell_Processor from global_setting import * #######...
198e08f2b470fdfb63fc53cc21e87ae9cd13a7b5608fd12d624ed17fe868777a
Python
3,011
68
# aggregate the results of eegnet import os, sys import pandas as pd import numpy as np from natsort import natsorted # go to base directory and import globals base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #ptmp_dir = "/ptmp/kroma/m4d/" os.chdir(base_dir) sys.path.append(base_dir) from src....
cb9bf179cdb98824c77b93491d4c3aded899f5d1c4adc672e5b5d90668256766
Python
3,011
80
import os.path as op from pathlib import Path import numpy as np from eigenstrapping.fit import SampledSurrogateMaps from eigenstrapping_analysis.utils import ( get_rootdir, MSEED, join, save_npy, load_npy ) from eigenstrapping.stats import compare_maps ROOTDIR = get_rootdir() DATADIR = Path(ROOTDIR, 'datasets',...
d51e0a10069663762a3cfc5d05a20e772c5fc435ec29455e07604d94d9bd746c
Python
3,011
81
import base64 import uuid from medperf.account_management import get_medperf_user_data from medperf.exceptions import CleanExit, MedperfException from medperf.utils import get_pki_assets_path, approval_prompt import os from medperf import config from medperf.ui.interface import UI from medperf.entities.certificate impo...
ef78b332114ea1b1b6082319f43811bb8dd1cf76419d366176c890561ed5df8b
Python
3,011
90
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.pyplot as plt import qtools as qt from qtools.attribution_scores import calculate_mutagensis_scores, mutagenesis # ============================================================================= # set up input an...
29cea1babdc5450102f57e808c1b98eecf1e7e6e0a5a511517efce06bf34d69d
Python
3,012
75
import importlib import torch import numpy as np import random def import_module(module_name: str, class_name: str): """ Import a module (class_name) from a module_name (path). :param module_name: Name of the module from where a class should be imported. :param class_name: Name of the...
1b28ad9e400b457b70a55960af6cbd8ca1c1b298ef975a8f46edee145dca18bb
Python
3,013
102
_base_ = [ '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py', '../_base_/datasets/coco-stuff164k_384x384.py' ] custom_imports = dict(imports=['cat_seg']) norm_cfg = dict(type='SyncBN', requires_grad=True) crop_size = (384, 384) data_preprocessor = dict( type='SegDataPreProcessor', ...
ccab47b3b4b555d5103992974b0993b7420da4faac84358cf4fbde6017b509ab
Python
3,013
90
# dataset settings dataset_type = 'REFUGEDataset' data_root = 'data/REFUGE' train_img_scale = (2056, 2124) val_img_scale = (1634, 1634) test_img_scale = (1634, 1634) crop_size = (512, 512) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', reduce_zero_label=False), dict( ...
61ba0245df67da60e45e8b4e76aa3949216b40b1d9da80d1d05aac86da743f82
Python
3,014
82
#!/usr/bin/env python import argparse import torch from torch.utils.data import DataLoader from rdkit import Chem from rdkit import rdBase from tqdm import tqdm from MCMG_utils.data_structs import MolData, Vocabulary from models.model_rnn import RNN from MCMG_utils.utils import decrease_learning_rate rdBase.DisableL...
cee3425313bd42ff9da93053798a1219258f57c6ba0bbcb10a9dcdea2b29e470
Python
3,016
103
import pathlib from dataclasses import dataclass from typing import List import ase import ase.io as aio import numpy as np import pandas as pd import torch import typer from torch.utils.data import DataLoader from tqdm import tqdm from hydromace.interface import HydroMaceCalculator from hydromace.tools import get_mo...
d0f56313791e1680b223171743870b209007366a35ca18eaa637fb844e4ed270
Python
3,016
94
# Based on https://github.com/lucidrains/siren-pytorch import torch from torch import nn from math import sqrt class Sine(nn.Module): """Sine activation with scaling. Args: w0 (float): Omega_0 parameter from SIREN paper. """ def __init__(self, w0=1.): super().__init__() self.w...
84f4d22a2e6af064f738b26771d9653eb17fc2779906900dab408686c367c7a9
Python
3,018
110
import pytest from kgx.graph.nx_graph import NxGraph from kgx.utils.graph_utils import get_parents, get_ancestors, curie_lookup def get_graphs(): """ Returns instances of defined graphs. """ g1 = NxGraph() g1.add_edge("B", "A", **{"predicate": "biolink:sub_class_of"}) g1.add_edge("C", "B", **...
eb620fd38fc30e39ad0965385df4ca57dea7a7ef1140b96515f9155e744dca75
Python
3,018
71
# run fit_gkr_models.py first import hickle as hkl from umap import UMAP from grid_cell.ploter import gp_torus_surface from grid_cell.persistent_homology import betti1_equal_2, betti_torus_check from grid_cell.util import pca_accumulated_variance_explained_ratio from sklearn.decomposition import PCA import matplotlib.p...
a4b04b5966ab223fc619208447bee20a433b2353a1921928c30674173026fe85
Python
3,019
40
# Module for different configurations classes class ModelConfiguration: def __init__(self, input_size=35, num_layers=3, bidirectional=False, hidden_size=35, kernel_sizes=[3], no_hidden=False, gru=False, frames_per_second=None): """ Initializes the configuration for a neural network model, particula...
3a87f6b5f0577add8164fbc73921c07a78c8bd7f3e12f5d818cdd31a9de2ed5a
Python
3,020
60
import sys tumor_id=T2 # specify ID age=77*365 # specify age (in days) import math import numpy as np from pyabc.external.r import R r = R(tumor_id+"Run_model_heme_WGS_data_2_linear_clones.R") model = r.model("myModel") distance = r.distance("myDistance") sum_stat = r.summary_statistics("mySummaryStatistics") o...
17911302ad2d84ddc6855223f853ee73ee8dfb63acf516505ae917dffa7d8216
Python
3,023
96
"""InternalExecutor implementation for zndraw-joblib. Runs built-in extensions (modifiers, selections, analysis) in a thread because the ZnDraw client uses synchronous HTTP and Socket.IO. Status transitions use the same JobManager HTTP API as external workers. """ from __future__ import annotations import asyncio i...
816c06d7021a4c84987c4cc04d74897ce9b0b11a4b02c78cfe3e8e281f89b232
Python
3,025
76
import torch import math import matplotlib.pyplot as plt import seaborn as sns import scienceplots import matplotlib.gridspec as gridspec import numpy as np hermes = torch.load('../results/custom_metrics_full_log_likelihoods_unsloth-Hermes-3-Llama-3.1-70B-bnb-4bit.pth') nemotron = torch.load('../results/custom_metrics...
cf6176cec3f08b4b637ed29a32b5ff46a6cef3ce7c06477fd36e91a15d4b29d3
Python
3,025
76
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os import logging import pickle from typing import List, Tuple import faiss import numpy as np from tqdm import tqd...
fe6ed946cc2bf81d3aa022ea10d4115f4dd100e89044bd32efe6ecffa4a57268
Python
3,028
105
import logging import sys from pathlib import Path from typing import Optional, Union import colorlog class CustomFormatter(colorlog.ColoredFormatter): """Custom formatter with colors for different log levels""" def __init__(self): super().__init__( "%(log_color)s%(levelname)-8s%(reset)s %(...
99b5aa9e6a192e8c92b6a5bfc242e35c2c405d386891ef893f4a5d48014b2cb6
Python
3,029
92
import ast import numpy as np import pandas as pd from .metrics import Metrics def load_submission_data(submission_path): """ Extract necessary data for model evaluation from the submitted csv file. Args: submission_path (str): Complete path to the submission file. Returns: tuple: ...
1ddf9ee99def854be16b267a7d04e45c32940dc097ca3508b103d841d556b75b
Python
3,031
85
# -*- coding: utf-8 -*- import django.core.validators from django.db import migrations, models import django.db.models.deletion forward = """ CREATE OR REPLACE FUNCTION refresh_skeleton_summary_table_for_project(target_project_id int) RETURNS void LANGUAGE plpgsql AS $$ BEGIN -- Remove all ent...
6933aae8d2cf08dfd9ee672ccdd4ca8f305e74c0dae2e69ef86bb119ee2a4981
Python
3,031
85
from model import common import torch.nn as nn url = { 'r16f64x2': 'https://cv.snu.ac.kr/research/EDSR/models/edsr_baseline_x2-1bc95232.pt', 'r16f64x3': 'https://cv.snu.ac.kr/research/EDSR/models/edsr_baseline_x3-abf2a44e.pt', 'r16f64x4': 'https://cv.snu.ac.kr/research/EDSR/models/edsr_baseline_x4-6b446fa...
76720d1b2a1e9bd9f23f464b19526503de51ebcf90e6351af1019fbd96b52d8b
Python
3,033
78
from pathlib import Path from typing import List, Tuple import SimpleITK as sitk import numpy as np def check_subject_validity( subject_dir: Path, labels_dir: Path ) -> Tuple[List[Path], List[Path], List[Path], List[Path]]: """Checks if all files exist. Also checks size, spacing and label set of images and m...
2a9960c9f587aa1966adc6053e058c41759f650daa0a499b07a87adbad13a835
Python
3,034
75
from PIL import Image import numpy as np def crop_and_resize(source_img, target_img): """ Make source_img exactly the same as target_img by expanding/shrinking and cropping appropriately. If source_img's dimensions are strictly greater than or equal to the corresponding target img dimensi...
392344a9d87b6cda04a2ec04d29a8bfc426d5534201fabe8041722413bbd2629
Python
3,034
84
# 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...
a004426fb72c40407ce56aa7d874cea8729569c8d325eb4705ecf4273248479e
Python
3,036
73
# -*- coding: utf-8 -*- import django.core.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): """This data migration adds missing skeleton summary table entries. They should have been created as part of the original summary table migration,...
a17de990280563b5ebf7ca5e66650cf741e10c38a035b8294b3b1ea822f12cd9
Python
3,037
100
import json import os from medperf.entities.interface import Entity from medperf.entities.schemas import CASchema import medperf.config as config from medperf.account_management import get_medperf_user_data from medperf.entities.utils import handle_validation_error class CA(Entity): """ Class representing a c...
0a9860f7e59792f92eab3ef5b57891ebe89c3cade6b76d1142cd51125f556f6b
Python
3,038
103
_base_ = [ '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py', '../_base_/datasets/ade20k_384x384.py' ] custom_imports = dict(imports=['cat_seg']) norm_cfg = dict(type='SyncBN', requires_grad=True) crop_size = (384, 384) data_preprocessor = dict( type='SegDataPreProcessor', size=cro...
32ba04f126da7ee5968473c0c9938a4467a4f2bd08eaac4fff157f2ff503d8ff
Python
3,038
100
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-04-03 20:07 import catmaid.fields import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion forward = """ SELECT disable_history_tracking_for_table('stack'::regclass, get_history_table_n...
2630f0082aabbaf6fe647823479889c5ca1e28e79aef99ba9ab0752f332ffd4b
Python
3,039
92
# Copyright (c) OpenMMLab. All rights reserved. from mmengine.structures import BaseDataElement, PixelData class SegDataSample(BaseDataElement): """A data structure interface of MMSegmentation. They are used as interfaces between different components. The attributes in ``SegDataSample`` are divided into ...
4755fffc2e5d4f6926fb32789347217943099253b972d08e7e6c3cfa5c13a58b
Python
3,039
84
from medperf import config from medperf.account_management.account_management import get_medperf_user_data from medperf.entities.ca import CA from medperf.entities.training_exp import TrainingExp from medperf.entities.cube import Cube from medperf.utils import get_pki_assets_path from medperf.certificates import verify...
28748a26d8829b8261a4124a253731e43a6efa1bcbf7ed9881bf3d7b638f7c13
Python
3,040
56
#!/usr/bin/python """ This file to create Site Frequency Spectrum (SFS) from Priors or parameters """ import argparse import sys # from Simulation.msprime import Demography # noinspection PyUnresolvedReferences import Class # noinspection PyUnresolvedReferences import Demography from _version import __version__ pars...
cabd0b8283d02566fed743e67a0fa75bead45e3f78a44660ff5bb67e0d591081
Python
3,041
85
# Copyright (c) 2021, EleutherAI # This file is based on code by the authors denoted below and has been modified from its original version. # # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complian...
805c99c87e7d2349bd84ebd907c5a5236864c83870eef0aaeb4b4ec4759e1c1e
Python
3,042
80
# %% auto 0 __all__ = ['TransformerModelMod', 'TransformerPlus'] # %% ../../nbs/108_models.TransformerModel.ipynb 3 from tsai.imports import * from tsai.models.layers import * from tsai.models.utils import * from torch.nn.modules.transformer import TransformerEncoder, TransformerEncoderLayer class TransformerModelM...
996020dc12fc9db27ab61965f714de75d029cafdbbab665bb1068307e35822aa
Python
3,042
92
from neurolib.utils.loadData import Dataset from neurolib.models.aln import ALNModel import matplotlib.pyplot as plt import neurolib.utils.functions as func import neurolib.utils.stimulus as stim import numpy as np import scipy.io as sio from scipy import signal # adding varx to the system path import sys sys.path.ins...
89afe4c06c96743d1ef1f5ee9c5d8c3f86a9b89def735238f637cabb568f212f
Python
3,043
92
# 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 os import threading import time import pytest...
27edbb86ef1a51478fb63c43033b9d5b3581091e72f4ee1d1d5946358f634985
Python
3,044
106
from ..client import inject_client @inject_client def fetch_custom(cypher, dataset="", format='pandas', *, client=None): ''' Make a custom cypher query. Alternative form of :py:meth:`.Client.fetch_custom()`, as a free function. That is, ``fetch_custom(..., client=c)`` is equivalent to ``c.fetch_custo...
46179aef609fbbcb1d7e729038cb78aeb14d037d1ea715b85e5500c5d809af30
Python
3,044
85
import numpy as np import pandas as pd from sklearn.cluster import AgglomerativeClustering from scipy.cluster.hierarchy import dendrogram from matplotlib import pyplot as plt from experiment import * def plot_dendrogram(model, **kwargs): # Create linkage matrix and then plot the dendrogram # create the coun...
4ec5bcd99d69610dd0b0908db7388d3bc86008cc1c99e80d4e4ca18c6a8b00e8
Python
3,044
103
_base_ = [ '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py', '../_base_/datasets/pascal_context_59_384x384.py' ] custom_imports = dict(imports=['cat_seg']) norm_cfg = dict(type='SyncBN', requires_grad=True) crop_size = (384, 384) data_preprocessor = dict( type='SegDataPreProcessor', ...
3c709ca27d1ca261faaa63352446bc985a688a8a6c9c357bc1df712444a8e9c3
Python
3,045
77
import sys sys.path.append(r"C:\Users\dm3169\PycharmProjects\comparative_prey_capture") from experiment import * import pandas as pd import numpy as np from scipy.spatial.distance import cdist from scipy.optimize import linear_sum_assignment class ArtemiaTracker: def __init__(self, x_init, err_tol): self...
c1d6a8e0490bf3a2b72540563426ec9b68c4a47aad864ebfb95d0de2e330a4ec
Python
3,046
88
import numpy as np from myphdlib.general.labjack import filterPulsesFromPhotologicDevice class StimuliProcessingMixin(): """ """ def _processMovingBarsProtocol( self, invertOrientations=True ): """ """ self.log('Processing data from the moving bars stimulus...
020fbd26ebbeb277c607e87491acb63e1f559ef195e60ce7e609301170c12b38
Python
3,049
73
import pytest from src.memory import ( _bytes_to_gib, _parse_cgroup_memory_value, _parse_kv_kb_bytes, _parse_proc_cgroup, log_memory_snapshot, process_peak_rss_bytes, ) @pytest.mark.unit def test_bytes_to_gib_formats_and_handles_none(): assert _bytes_to_gib(None) == "unknown" assert _...
be9b177310a884f3da98403ab2d4e6e0de8d9f0116f053977ef375214506829b
Python
3,051
81
import httpx import pytest import socketio import socketio.exceptions from zndraw_socketio import wrap from zndraw.socket_events import UserGet, UserGetResponse @pytest.mark.asyncio async def test_socketio_connect_without_token(server: str) -> None: """Test that Socket.IO connection is rejected without a token."...
f008b3a0143c16d1bd97236706809e733ad1adec12d6ca73b8eef445d705ec91
Python
3,052
113
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import math import torch from ..initializers import he_orthogonal_init class Dense(torch.nn.Module): """ Combines...
10e4d477895ee7e46cb3bbabb5c426b85097240c31e8d5dddf57277796729df5
Python
3,053
96
from pathlib import Path from modules.run_svr_lsm_iteration import run_svr_lsm_iteration if __name__ == "__main__": base_folder = Path.cwd() # CURRENT DIRECTORY base_folder = base_folder / "symptoms" ''' symptom_folder = base_folder / 'Dysmetropsia' csv_name = "Dysmetropsia.csv" ...
fb0bc65b73d0bb84bfe1b13f57c667bcd685a7b7a2c89ebf52a91170dac9bdbe
Python
3,053
83
import pytest from dnaio import SequenceRecord from cutadapt.qualtrim import nextseq_trim_index, expected_errors, poly_a_trim_index def test_nextseq_trim(): s = SequenceRecord("n", "", "") assert nextseq_trim_index(s, cutoff=22) == 0 s = SequenceRecord( "n", "TCTCGTATGCCGTCTTATGCTTGAAAAAA...
6aa42a336430612f7ea2db05caeef774e245bc30fd9bcb14a5e0b591dd4c6ff3
Python
3,054
109
"""XGBoost Experimental Federated Learning related API.""" import ctypes from threading import Thread from typing import Any, Dict, Optional from .core import _LIB, _check_call, _deprecate_positional_args, make_jcargs from .tracker import RabitTracker class FederatedTracker(RabitTracker): """Tracker for federat...
5c76536c35759e1f212a9329b9136dcf8a37023e020f489f6acabef8766dbb00
Python
3,056
80
from contextlib import contextmanager import pytest # These tests require a live connection to ubergraph.apps.renci.org. # They are only run when pytest is invoked with --network or --all # (see tests/conftest.py for CLI options). # # The shared `ubergraph` fixture (tests/conftest.py) handles three cases: # - Netwo...
d618d6e87cf6138241b035c57b59ffc275d621f2d0cbdec64441243141fe10db
Python
3,056
89
import os import pandas as pd from rano_monitor.messages import InvalidSubjectsUpdated from rano_monitor.messages.report_updated import ReportUpdated from textual.widgets import Label, ListItem, ListView from rano_monitor.utils import ( get_hash, tumor_has_been_finalized, get_finalized_tumor_path, get_b...
cba7c886f43a9a75b202dae97002594b04eb2d41e5b7795cd3601b35923ae5ed
Python
3,059
91
# -*- coding: utf-8 -*- from django.db import connection from django.shortcuts import get_object_or_404 from django.test import TestCase, TransactionTestCase from django.test.client import Client from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from guardian.shortcuts import ...
3d4243b34a90c72bc13827bfad59e3615e28d45384b9f0f001ce25173e1b51b9
Python
3,060
65
"""Shared, import-safe test-data locations and helpers. This module holds constants and helpers that test modules need at *collection* time (e.g. inside ``@pytest.mark.parametrize`` decorators and module-level case lists), so it must stay a plain importable module with no pytest or heavy imports. It lives under a uniq...
2cfc57bb2ad8cf2febcd0686cec28ae1c0537c5bf1fab524d85307901864e877
Python
3,061
51
#!/usr/bin/env python # coding: utf-8 import os, sys, argparse import numpy as np from utils_dp import MASS_LIST, STIFF_LIST, CUR_SCENE_DICT, BLENDER_CAM, mkdir, get_depth_map parser = argparse.ArgumentParser(description='') parser.add_argument('--cur_scene_idx', type=int, default=1, help='wind=1|drape=2|ball=3|rotat...
4714085fc7fc6067545f29ddf4b941ea80e8c59f41df66ac214d4e0fbed4ff88
Python
3,063
97
from pyalfe.tasks.dicom_processing import DicomProcessing from pyalfe.tasks.initialization import Initialization from pyalfe.tasks.quantification import Quantification from pyalfe.tasks.registration import ( CrossModalityRegistration, Resampling, T1Registration, ) from pyalfe.tasks.segmentation import ( ...
b68de822028d56978bd09f5d072c730f82d7436b8082a24f1419b2b4f75e48e3
Python
3,065
91
from django.http import Http404 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 Dataset from .permissions import IsAdmin, IsDatasetOwner from .serializers import ( D...
b8c75efc0be20d19f5166b7ecad29cd53d8f9d5f21609c6935e2047b8568a8ea
Python
3,069
92
# 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 -------------------------------------------------------------- # If ex...
cbbdadcfe9276ef7c68e8d1879468b250de50903c2961e70129339c47ebedd1d
Python
3,069
98
import torch import torch.nn as nn def normalized_cross_correlation(x, y, return_map, reduction='mean', eps=1e-8): """ N-dimensional normalized cross correlation (NCC) Args: x (~torch.Tensor): Input tensor. y (~torch.Tensor): Input tensor. return_map (bool): If True, also return the co...
d433efcd9f232558ee37dcbd74124eac055eb90316650ff123b7520d3a8f2630
Python
3,071
90
from pydantic import BaseModel class ContainerInput(BaseModel): name: str = "" config: str parameters: str = "" additional_local: str = "" additional_remote: str = "" HOST = "127.0.0.1" WEBUI_PORT = 8100 SERVER_PORT = 8000 LOCAL_PROFILE = "Local" BASE_URL = f"http://{HOST}:{WEBUI_PORT}" + "{}"...
4ec43c7346d59538179e9e64e44d4daf40738430a74db606fac40b4ec6cafc15
Python
3,073
58
#!/usr/bin/env python import sys, os use_message = ''' ''' # GRCh38 release 84 def build_indexes(): # Build indexes if not os.path.exists("indexes"): os.mkdir("indexes") os.chdir("indexes") aligners = ["HISAT2", "HISAT", "Bowtie", "STAR", "GSNAP", "BWA", "minimap2"] genomes = ["22_20-2...
58b7fae969779c374e1e496b5b5b7be5ebc1cbc3de7a51b22a7ef58556d081a3
Python
3,073
96
# grab all .csv files # concatenate into one big dataframe # TODO: add sub, ses, run, task info to pandas # resources: # * https://community.plotly.com/t/multiple-traces-plotly-express/23360/4 # %% from operator import index import os, glob from turtle import color import pandas as pd import matplotlib.pyplot as plt ...
bfeda1c788d41d4feee4be5fed8e1258c52b2158a5aa44a6a71e15e8150b13e4
Python
3,074
90
#!/usr/bin/env python """ MetaWIBELE: download_config_file module Download template configuration files and vignette files for prioritization used by MetaWIBELE 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 associa...
b2c4c5622b18344d8b2cae9636d22c738e6153b2e164d68d83d554a8e1862f28
Python
3,075
97
################################################################## # Plotting the PCA t-SNE and UMAP based on TrimNN representations # Reproducibility for Figure.3B ################################################################## import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklea...
719129b7d983f316cb933df045e243874503f05cc0ffe8a97ecfc15a2d4d61b5
Python
3,076
123
"""Tests for automatic connectivity calculation.""" import ase import numpy as np from zndraw.connectivity import add_connectivity def test_auto_connectivity_small_molecule(): """Small molecule gets connectivity computed.""" # Water molecule — O-H bonds should be detected atoms = ase.Atoms( "OHH...
80b5762bbfe1c17592440ff6da56dc714f14f672754686a45173c2cdff69cd36
Python
3,076
67
import pandas as pd import math from functools import reduce df_exp = pd.read_csv('../experiments.csv', sep=';') df_llama_70b = pd.read_csv('../results/all_data_unsloth-Meta-Llama-3.1-70B-bnb-4bit.csv') df_llama_70b = df_llama_70b[df_llama_70b['unseen'] == 'participants'][['task', 'unsloth/Meta-Llama-3.1-70B-bnb-4bit...
f47d0ce857e393104ffc2602fc17017a8bf3a3b9be0a05726592530eb6431c4c
Python
3,076
80
#!/usr/bin/env python3 import os import glob import numpy as np import matplotlib.pyplot as plt import pandas as pd import argparse def main(): parser = argparse.ArgumentParser(description="Generate violin plots of absolute sums per model directory.") parser.add_argument("--dataset", choices=["MNIST", "CIFAR10...
895744531e68024641835220329102d64060119a9d61b685976ed841fae0c18f
Python
3,078
91
# Copyright DST Group. Licensed under the MIT license. from CybORG.Shared.Enums import PasswordHashType from CybORG.Simulator.Entity import Entity from CybORG.Simulator.LocalGroup import LocalGroup class User(Entity): """User entity Attributes ---------- username : str password : str pas...
06ad94160ef915fe4b4ae6de8f1222b743771ac685482004075bc57967848378
Python
3,079
105
from medperf.exceptions import CleanExit import pytest from unittest.mock import ANY from medperf.entities.model import Model from medperf.entities.benchmark import Benchmark from medperf.commands.model.associate import AssociateModel PATCH_ASSOC = "medperf.commands.model.associate.{}" @pytest.fixture def model(moc...
dfe08f737e95404eca86d4a97c2fbef57049b4b360742b0ef0bd736e57a59ed7
Python
3,079
95
"""Logic file""" from pathlib import Path import torch import numpy as np import SimpleITK as sitk from src.utils.utilities import helper def pseudo_predict(subject_dir: Path, output_dir: Path): """ In this dummy example, the four MR sequences are loaded from `subject_dir` and then class 0 is "predicted" fr...
27ad957e90d556f4d03c228ea7e45cf1cf755b54f141615b6add1c6e80346c27
Python
3,081
72
# pytest unit tests for spinalcordtoolbox.deepseg_.gm import os import nibabel as nib import numpy as np import spinalcordtoolbox.deepseg_.gm as deepseg_gm class TestCore(object): def test_data_resource(self): """Test the DataResource manager, and check if files exists.""" resource_models = dee...
3b6b00df5dbbee09aa0f2360159a8010b6be4e7cdcefe03f28ccad2df83e64ca
Python
3,081
94
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import logging import torch class ForceScaler: """ Scales up the energy and then scales down the forces to prevent NaNs and inf...
a8d0e78c9c9bf88eebef32d822521dbf48f96f02b00776052f9f3dcc110c5e4a
Python
3,081
82
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os.path as osp from collections import OrderedDict import mmengine import torch from mmengine.runner import CheckpointLoader def convert_mit(ckpt): new_ckpt = OrderedDict() # Process the concat between q linear weights and kv linear weigh...
5569d18f50faae9e79cb3d174e479fac2498a642ab15e7caf468e66e5655e76c
Python
3,082
105
import os # Encode a fragment. from rdkit import Chem from mol_utils import join_fragments from mol_utils import split_molecule import pandas as pd def encode_molecule(m): fs_list = [] count = 0 error_index = [] for index,i in enumerate(m): try: fs = [Chem.MolToSmiles(f) for f in s...
28017449737463ab37892581a0e51694cd4c26cf1c3863a074ca1699f02f1ca7
Python
3,083
97
import os import torch import pandas as pd from PIL import Image import numpy as np import torchvision import torchvision.transforms as transforms from models import model_attributes from torch.utils.data import Dataset, Subset from data.dro_dataset import DRODataset from data.utils import * from data.torchvision_datas...
2ec742c25c0efc186985e6fadfcb6b2841c7a4e9ae6d6fd4b3e6ae0ae94d06e8
Python
3,084
92
#!/usr/bin/env python """ Time ``cache()`` for every weight/property type. Separates the properties derived from the topology alone from the ones that call out to RDKit/OpenBabel/ChargeFW2. Only the cheap ones belong in a GPU benchmark; the rest measure third-party libraries rather than Nearl. Usage: python profi...
2f8b2d5ebd93241970923014e2e96ff86a88b9d8f83ae03df853518ce7eb0d25
Python
3,085
103
# model settings backbone_norm_cfg = dict(type='LN', eps=1e-6, requires_grad=True) norm_cfg = dict(type='SyncBN', requires_grad=True) data_preprocessor = dict( type='SegDataPreProcessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_val=0, seg_pad_val=255) mo...
4a6827caffcf684f6155439c740589ea35562137ca690dd31ae80f9ce9a47ddb
Python
3,085
91
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmcv.cnn import ConvModule from mmengine.utils import is_tuple_of from mmseg.registry import MODELS from ..utils import resize from .decode_head import BaseDecodeHead @MODELS.register_module() class LRASPPHead(BaseDecodeHead): ...
b0ec2090829370553110c0263315886a00dfad0406f9f9d6ebac3c6ea896dbf5
Python
3,085
76
###################################### # wrapper for rule: deduplicate_single_genomics ###################################### import os import sys import math import subprocess import glob from snakemake.shell import shell UMITOOLS = "umi_tools" SAMTOOLS = "samtools" BAMCOVERAGE = "bamCoverage" shell.executable("/bin...
3f21afb420d331ea9b59f60a92029eb1c68dd9ed6ac0310ed9e44f235a358485
Python
3,086
86
import numpy as np def get_angle(inp, cross, k, direction): # inp is the input plane, represented by 3 xzy sets # cross and k is the normal vector of the plane # Direction defines whether we want the mediolateral or dorsaventral angle section = inp.copy() # transform vector into absolute coordinat...
6115080ad343737655d31a71cc814c4615f7adb23253196960b1ed7687b26c4e
Python
3,086
82
import numpy as np def get_angle(inp, cross, k, direction): # inp is the input plane, represented by 3 xzy sets # cross and k is the normal vector of the plane # Direction defines whether we want the mediolateral or dorsaventral angle section = inp.copy() # transform vector into absolute coordinates...
b474e67265f23e542f07f8263ccea308cbd9eb0488cbcb1d47a1777236b3a048
Python
3,087
93
import copy import torch from torch.utils.data import Dataset from Bio.PDB.PDBParser import PDBParser from Bio.PDB.MMCIFParser import MMCIFParser from Bio.PDB.Polypeptide import index_to_one, one_to_index from rde.utils.transforms import Compose, SelectAtom from rde.utils.protein.parsers import parse_biopython_structu...
e3e41e80da4b1fda763d43d2cfc42b94017fd2fd89e6a4d9cbd605f092ae655e
Python
3,088
103
import os import platform import socket import psutil import shutil import subprocess from datetime import datetime import uuid def is_container(): try: with open("/proc/1/cgroup", "rt") as f: content = f.read() if any(x in content for x in ["docker", "kubepods", "containerd", "podm...
68aff1bb228ea6feefb15c81ff777815075830d92d32761d7daa57ee7dde991d
Python
3,089
71
import os import sys # 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 DeepChemModels.CustomizedDateLoader import * from DeepChemModels.ModelFeatureGenerator import generate_model_f...
96c71bbc8339071f493e9eb76cf4ab51d51e150acc22691ebaf1c283dcd62975
Python
3,090
91
'''Calculate QC metrics that fastqc doesn't explicitly provide.''' import sys import os import re import argparse import zipfile def unzip_fastqc_dir(zipped_file): '''Unzip fastqc raw directory and return data file.''' zip_base = os.path.basename(zipped_file) unzip_dir = os.path.splitext(zip_base)[0] w...
55a7f2ca31fae709eee2713209f695708ebce5d8ff320c4e8a49cfcee4ab3003
Python
3,092
97
import json import os import os.path as op from heudiconv.utils import ( get_known_heuristics_with_descriptions, get_heuristic_description, load_heuristic, json_dumps_pretty, load_json, create_tree, save_json, get_datetime, JSONDecodeError) import pytest from .utils import HEURISTI...
60a7857a57b04cd81e1d3363ab48f4e48642d0f5bd121273d7da393544ecbdf2
Python
3,096
104
"""Shape geometry for ZnDraw - 2D polygons rendered in 3D space.""" from pydantic import Field from .base import ( BaseGeometry, ColorProp, InteractionSettings, PositionProp, RotationProp, ScaleProp, ) class Shape(BaseGeometry): """A 2D polygon shape rendered in 3D space. Vertices d...