sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
88378665f0b1b2ff1b0b52880669b1746c7d9632fc4958863abc99877415b721
Python
3,773
128
""" Extract static/dynamic featuresfor single residue classification """ import argparse import os from collections import OrderedDict import nearl.data import numpy as np import nearl from nearl.io.traj import MisatoTraj nearl.update_config( verbose=False, debug=False, # verbose = True, # debug =...
e86cd6475aac4cc4b387190251cf1eeb6f335132b7a71a8b12455886b7c58d26
Python
3,775
106
# -*- coding: utf-8 -*- # tests/test_xarray.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 sof...
0da5b1b768b56851aef211299254f2d1acf1cb12dfcb673783c6ad2ff8af60cd
Python
3,778
123
import itertools import ase.io as aio import numpy as np import torch from ase import Atoms from fire import Fire from mace import data, tools from mace.tools import torch_geometric from energy_model.diffusion_tools import ( HeunSampler, SamplerNoiseParameters, ) from simgen.utils import get_system_torch_devi...
6e02b876b9c22ceb901198cadfcdb3ff1c1b4208994d03b84a71f44fa5c2d262
Python
3,778
113
import socket import time import numpy as np import pandas as pd import panel as pn import pytest from playwright.sync_api import expect from guppy.frontend.frontend_utils import scanPortsAndFind from guppy.frontend.parameterized_plotter import ParameterizedPlotter from guppy.frontend.visualization_dashboard import V...
6edfd9e065e8c792ef38660aa4e7d5dfb2ad68808cdbdebb8a0cddb5d4fb21f2
Python
3,780
123
import pickle from types import SimpleNamespace import numpy as np import pandas as pd from scipy.interpolate import interp1d from masscube.alignment import gap_filling from masscube.mzpkl import convert_MSData_to_mzpkl, read_mzpkl_to_MSData from masscube.raw_data_utils import MSData, Scan, save_mcraw def _make_msd...
1e0e8df3017445271da4de1e4e63a9abca55765d227daf4fca0b8ec39afaf627
Python
3,781
102
#!/usr/bin/env python import sys, os from argparse import ArgumentParser, FileType def get_data(small = False): data_root = "http://www.ccb.jhu.edu/software/hisat2/downloads/evaluation" # Download the reference human genome, SNPs, and gene annotations if not os.path.exists("data"): os.mkdir("...
c082543294c6160ae8db27002069deaec0e66e0bcc90404be1a2d631945ba2b4
Python
3,783
80
# coding=utf-8 # Copyright 2022 IDEA-CCNL and The HuggingFace Inc. team. All rights reserved. # # 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://www.apache.org/licenses/LICENSE-2....
23fb332a8d44182f51ed492153ac58c8f39e4fcae725ef8d4db7a9886a6a956d
Python
3,784
87
from modules.atlas_read_cluster import atlas_read_cluster from modules.time_func import get_current_datetime_for_filename from modules.time_func import easy_time from modules.load_lesions_and_behaviors import load_lesions_and_behaviors from modules.filter_voxels_by_patient_count import filter_voxels_by_patient_coun...
67a305bd58ba1232b886f5e7381654e97f73d311435fe7b72586ae81d510bb07
Python
3,785
127
#!/usr/bin/env python # -*- coding: utf-8 -*- # tests/run_doctests.py ################################################################################ # EncoderMap: A python library for dimensionality reduction. # # Copyright 2019-2024 University of Konstanz and the Authors # # Authors: # Kevin Sawade # # Encodermap is...
8b9b3303db4fe3a0f00328dc6f62551dfb4daa32c66a24ca943c694fd724b2f7
Python
3,785
121
#!/usr/bin/env python # -*- coding: utf-8 -*- from common import db_connection import sys import os first_migration = '2011-07-10T19:23:39' if len(sys.argv) != 1: print >> sys.stderr, "Usage: " + sys.argv[0] sys.exit(1) everything_ok = True c = db_connection.cursor() c.execute("select tablename from pg_t...
8e12c1ddfa705c7b84502b6a2260ae515b459837d1bd2c5e7aadc08392abb007
Python
3,786
94
from CybORG.Shared import Observation from CybORG.Simulator.Actions.Action import RemoteAction from CybORG.Simulator.Actions.ConcreteActions.StopProcess import StopProcess from CybORG.Simulator.State import State from ipaddress import IPv4Address class Withdraw(RemoteAction): """ A red action that removes all the ...
335a477dcc6488722957d8716ae069e1585fc65957903d21e7e59fe77ef462cb
Python
3,788
95
# pytest unit tests for spinalcordtoolbox.resampling # TODO: add test for 2d image import logging import pytest import numpy as np import nibabel as nib from spinalcordtoolbox import resampling @pytest.fixture(scope="session") def fake_3dimage_nib(): """ :return: an almost empty 3-d nibabel Image """ ...
630a9a91b26fafdf94e80dab5d7810b9bd22b007f1c34760f025ddd2bf7e54a2
Python
3,791
86
# -*- coding: utf-8 -*- from django.db import migrations, models forward = """ -- Remove constraints if they exist (in case they have been added manually ALTER TABLE ONLY class_instance_class_instance DROP CONSTRAINT IF EXISTS class_instance_class_instance_project_id_fkey; ALTER TABLE ONLY class_i...
519e514abfb1964cba406b44ffda740f81be1754f61181cca8933e96b7b4de4b
Python
3,793
80
############################################# # See GASTON code: https://github.com/raphael-group/GASTON/blob/main/src/gaston/isodepth_scaling.py ############################################# import numpy as np from sklearn.metrics import pairwise_distances import matplotlib.pyplot as plt # Linearly scale isodepth r...
63716ff66d43fc99216da87a78fa686e56b14af722bd23eebeb17cd22fcd12e4
Python
3,794
103
"""Layer 1: static schema audit for RoomScopedEvent subclasses. Fails fast at collect time if any subclass forgets to declare both ``room_id: UUID`` and ``room_address: str``. LIMITATION: discovery uses ``RoomScopedEvent.__subclasses__()``, which only enumerates classes that have been imported. The audit imports ``zn...
6a6ae8dbc6605aca12c4ce31dc51641c186293a0871dd6ebc750ab84022f9b5b
Python
3,794
111
import numpy as np import random # from IPython.display import display, HTML def fetchSize(genome): '''Input a genome.fa file, get the chromsome bounderies.''' genomeSize = {} sequence = '' with open(genome, 'r') as refFh: for line in refFh: line = line.strip() if '...
6e9c62a56919587c4b213b78914239b8c98e5e945e6b7ce00333979ab0a17cca
Python
3,795
102
import os import torch import pandas as pd from PIL import Image import numpy as np import torchvision.transforms as transforms from models import model_attributes from torch.utils.data import Dataset, Subset from data.confounder_dataset import ConfounderDataset class CUBDataset(ConfounderDataset): """ ...
8d6b41d520e315fc5262bae7e7b9c451a8cfdf4b087e13224e4b1951c03e347f
Python
3,795
97
#-*- coding: utf-8 -*- #setting############################################## n_jobs=16 #並列処理の数 t_n_jobs=16 PARAMETER_DIR='/Volumes/Siena/CP/parameter' #n_jobs=40 #並列処理の数 #t_n_jobs='cuda' #PARAMETER_DIR='/home/takeiyuuichi/Dropbox (MEG)/CP/parameter' set_environment='main' SET_EVENTID=[2,3] event_id = dict(control=2...
db5023f1452a35f0be42bdaebe040184f576cdb1289a74d9662d26a3fcdb59e3
Python
3,797
124
from __future__ import annotations import json from typing import Annotated import typer from zndraw.schemas import ( SelectionGroupResponse, SelectionGroupsListResponse, StatusResponse, ) from .connection import ( PasswordOpt, RoomOpt, TokenOpt, UrlOpt, UserOpt, cli_error_handle...
35464d7a54c8f4db1bdf0146b3f2887e132c1c82784a1db33062393c253e6509
Python
3,798
119
import pytest from cutadapt.kmer_heuristic import ( kmer_chunks, minimize_kmer_search_list, create_back_overlap_searchsets, create_positions_and_kmers, ) @pytest.mark.parametrize( ["sequence", "chunks", "expected"], [ ("ABC", 3, {"A", "B", "C"}), ("ABCD", 3, {"AB", "C", "D"}),...
c87b978e9054be71f6a2773d72e0a78eede8237743707fc9522b7f5564696450
Python
3,798
104
import numpy as np import torch from SurrGradSpikeLIF import SurrGradSpikeLIF from SurrGradSpikeIZ import SurrGradSpikeIZ class surrParams: def __init__(self): self.version = 1.2 self.simTag = "Test" self.debug = False # the other option for dataset is the "SHD" self.data_s...
cf7138b761d3ab0afe3e28104c7b1e53fc24371f6c7a190c253d7539fb30da8d
Python
3,798
114
from dfa_lib_python.extractor import Extractor from dfa_lib_python.extractor_cartridge import ExtractorCartridge from dfa_lib_python.extractor_extension import ExtractorExtension def test_get_cartridge_pass(): tag = "ext1" cartridge = ExtractorCartridge.EXTRACTION extension = ExtractorExtension.FITS e...
6c632be65b5b97eb2adcd43877a8450d37b9665da887780ebb4965a185276b77
Python
3,801
133
import re import sys import time import multiprocessing import logging import locale logger = logging.getLogger(__name__) try: "µ".encode(locale.getpreferredencoding()) MICRO = "µ" except UnicodeEncodeError: MICRO = "u" def available_cpu_count(): """ Return the number of available virtual or phy...
aff884bb16e2e3a2add2c188e7603420add6f5d8f9d16d796e5ad5d07a9e3b0d
Python
3,802
101
from __future__ import annotations import base64 import logging from medperf.entities.interface import Entity from medperf.entities.schemas import EncryptedKeySchema from medperf import config from medperf.exceptions import ( MedperfException, DecryptionError, PrivateContainerAccessError, ) from medperf.com...
b8350635e25b8b1a249291d6dfd98cbc52776373dc64d528171e988a5e33a531
Python
3,802
115
"""MLCube handler file""" import typer import os from collaborator import start_collaborator from aggregator import start_aggregator from plan import generate_plan from utils import ( get_train_val_paths, get_server_connection, setup_job, get_collaborators_public_keys, get_openssh_format_private_k...
c80d761b6a5174e037c8e3bb906f2f4fd8e889baee70195d185eec0fb0d93155
Python
3,802
84
from contextlib import contextmanager from json import JSONDecodeError from urllib.error import HTTPError import pytest from src.categories import ANATOMICAL_ENTITY, CELLULAR_COMPONENT, GROSS_ANATOMICAL_STRUCTURE, PHENOTYPIC_FEATURE from src.createcompendia import anatomy, diseasephenotype from src.datahandlers impor...
5b99a100de17bb324c7c366b330bff8c8b62833c809d55dc14a3dfe795457e1d
Python
3,803
101
import shutil from pathlib import Path import pytest from guppy.testing import compare_output_folders from guppy.testing.api import ( group_analysis, label_groups, locate_run_folder, step1, step2, step3, step4, ) from guppy_test_data import TESTING_DATA, event_ts_offset_for SESSION_SUBDIR...
97f86164033c94ea7fd10166ce6f0e784194da9d183dc633a26b5395ed9eb715
Python
3,803
94
import torch from torch.utils.data import Dataset, DataLoader from torchvision import datasets import numpy as np import matplotlib.pyplot as plt import pathlib import os class Digit(Dataset): ''' Sequence of images ''' def __init__(self, digit_mode, n_samples, topdown, noise=0): self.n_sampl...
e7ddf15930c5004197589f6175b1273158dea66abd714dd95bff16e4bc5ae216
Python
3,803
122
"""Unit tests for InternalProviderExecutor.""" import json import time from pathlib import Path import httpx import pytest from httpx import MockTransport, Response from zndraw import ZnDraw from zndraw.providers.executor import InternalProviderExecutor from zndraw.providers.filesystem import FilesystemRead @pytes...
ac1467eb219187c8f9e8a9a9f4c6f2fd40eaed20bfa25221a5d695d3cd7eb64d
Python
3,805
108
from typing import Dict from hypothesis import given, note, settings, strategies import xgboost as xgb from xgboost import testing as tm pytestmark = tm.timeout(20) parameter_strategy = strategies.fixed_dictionaries({ 'booster': strategies.just('gblinear'), 'eta': strategies.floats(0.01, 0.25), 'tolera...
597f50a990902868c6e48cc087b9e459680f93b43c3780148a9d4d6cacf70909
Python
3,806
122
from __future__ import annotations import pathlib from typing import Annotated import typer from zndraw.schemas import ( CollectionResponse, FigureCreateResponse, FigureData, FigureResponse, StatusResponse, ) from .connection import ( PasswordOpt, RoomOpt, TokenOpt, UrlOpt, U...
9d62fbe4930731da0436b47d475edd22d75766a7f3d8b3090c693797f8f47078
Python
3,806
135
"""Tests for CLI geometries commands.""" from __future__ import annotations import json from typing import TYPE_CHECKING from zndraw.cli_agent import app from zndraw.schemas import GeometryResponse, StatusResponse from .conftest import invoke_cli if TYPE_CHECKING: from typer.testing import CliRunner def test...
73423562558e2cdbf1450a0202d7badc614ba7f97d65ed039e2d97d87af841dc
Python
3,807
92
from mpi4py import MPI import numpy as np from grid_cell.persistent_homology import Is_Torus from grid_cell.manifold_fitter import GP_Fitter, Avg_Fitter import matplotlib.pyplot as plt import tensorflow as tf import os from sklearn import datasets from global_setting import * comm = MPI.COMM_WORLD size = comm.Get_size...
13602b8d87b5afa0ee162da0010328f6b13652de30f7d4532504e593b3155389
Python
3,808
125
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # pyre-strict import itertools import unittest from typing import Iterable import torch from fvcore.nn.squeeze_excitation import ( ChannelSpatialSqueezeExcitation, SpatialSqueezeExcitation, SqueezeExcitation, ) class TestSqueezeExci...
dbba024498246b3e821929df48a323aa340505847012b56f69a6cff4e0d9fd87
Python
3,811
102
from transformers.models.llama import LlamaForCausalLM, LlamaTokenizer, LlamaConfig from fengshen.models.megatron import mpu from fengshen.models.llama.modeling_llama import LlamaForCausalLM as FengshenLlama from fengshen.models.llama.configuration_llama import LlamaConfig as FengshenConfig import argparse import torch...
7ff769e6a96027c0a220b3e2018ef1349db624b4a7a57f9dfc8b59885df644b9
Python
3,812
84
import numpy as np import scipy.io as scio import datetime from configobj import ConfigObj def init_params(): ''' Initialize network training parameters. tc: training_configurations always define x as the prior dimension (matrix rows, along the height), y as the following inner (last) dimension ...
9754f24d37e5e9f797bada76ad3169d225a847f40404e8fadeacd4de2b558fc5
Python
3,812
109
# select a group of metabolic features for correcting m/z and retention time error # the selected features should be: # 1. present in all (most) biological samples # 2. confirmed by unique m/z, good peak shape, and MS/MS spectra # input: a list of files from __future__ import annotations from typing import TYPE_CHECK...
f913b910af55445c8d459ae783cdf16c1ea4f74cbbb16630d963b4693ebc875e
Python
3,812
146
"""Server management utilities for ZnDraw CLI. Retained utilities: process checking, server readiness polling, and shutdown. Server registry and token storage moved to zndraw.state_file. """ from __future__ import annotations import logging import os import time import httpx log = logging.getLogger(__name__) DEFA...
567831a14bf8585f100bef52533c4c7da2a9c7ec8433df262b919a6ae6a3ea66
Python
3,813
126
"""Tests for local admin token authentication. Tests cover: - Local token grants admin access to the shutdown endpoint - Wrong local token is rejected - Normal JWT auth still works when no local token is configured """ from unittest.mock import patch import pytest import pytest_asyncio from helpers import create_tes...
1445bdc4a08dca7e28918393e41d37d37018bdfff5c1a066a52b6fc811061051
Python
3,816
122
"""Quality control for data set.""" import argparse import os from typing import Tuple import matplotlib.pyplot as plt import numpy as np import pandas as pd from brainbuilder.utils import utils from joblib import Parallel, delayed def get_min_max(fn: str) -> str: """Get min and max values from image file. ...
4d7de81663ac7efdf56a0934426d63d2379e3bf970a97acef9fd2069db285d6b
Python
3,816
107
import os import gensim from Utils.dataloader_GRAZPEDWRI import * from Utils.models import * from Utils.TrainModel import * from Utils.config import * # OPTIONAL: Load the "autoreload" extension so that code can change #%load_ext autoreload # OPTIONAL: always reload modules so that as you change code in src, it gets ...
5c3f61860ade714d3dbf4af550a0d0ea0ca80728b72c9129422a89dbd9553cf2
Python
3,817
115
import io import logging import os import pytest import nearl @pytest.fixture def isolated_logger(tmp_path, monkeypatch): stdout_buf = io.StringIO() stderr_buf = io.StringIO() monkeypatch.setattr(nearl._stdout_handler, "stream", stdout_buf) monkeypatch.setattr(nearl._stderr_handler, "stream", stderr...
f6313c991ae34129361df2b67ce20aab2f52e3f9741c17f4fc7fd31049135032
Python
3,817
66
# preprocess and fitting GKR model import numpy as np import os import hickle as hkl from grid_cell.grid_cell_processor import Grid_Cell_Processor, Data_Transformer from sklearn.decomposition import PCA from grid_cell.gkr import GKR_Fitter import argparse from global_setting import * parser = argparse.ArgumentParser(d...
0a8fe4fa9eec374aeb90fa64eeabf786f77bcf5bf533c505ac4e0bc193693f72
Python
3,819
128
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 10 14:22:45 2023 @author: george """ #%matplotlib qt import numpy as np import pandas as pd import skimage.io as skio from tqdm import tqdm import os, glob from matplotlib import pyplot as plt import pyqtgraph as pg tiffFile = '/Users/george/Data...
25aa4517db725eb425c917149545937964fb0e9fdd4727ac2ccaadbc0c7d1978
Python
3,819
83
import sys class Ts2vcf: """ tree sequence from msprime simulation will be converted to vcf file and will be printed in stdout. given a msprime function coming from demography.py and set of parameters defined by a tsv file with first column names of the parameters and the second columns are the parame...
a0105c2e2eb6996c6fc93fa07c6280393e77f3ca5b211148f3b84314a92933fa
Python
3,820
119
# 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...
e3cc32573d83bbf268a4f7558ce56469b577b05d663ec8c924f8526d879bf93e
Python
3,824
91
# MLCube Entrypoint # # This script shows how you can bridge your app with an MLCube interface. # MLCubes expect the entrypoint to behave like a CLI, where tasks are # commands, and input/output parameters and command-line arguments. # You can provide that interface to MLCube in any way you prefer. # Here, we show a wa...
5c48c7aca8d0de7fef88ca5734940586cc8f420164683f4de64ade1fb53f8d38
Python
3,828
106
import time import numpy as np from nearl import all_actions, commands np.random.seed(0) # For dummp data generation atom_nr = 100 frame_nr = 30 # For the settings of the grid dims = np.array([32, 32, 32], dtype=np.int32) spacing = 0.5 cutoff = 0.5 sigma = 1.0 def test_frame_voxelize(): """ Voxelize a se...
c7ea538347d79352b7ed53fd6503c3f53ac5690ab50e2342fc2decd49970fc67
Python
3,830
112
# Copyright (c) OpenMMLab. All rights reserved. from argparse import ArgumentParser import cv2 from mmengine.model.utils import revert_sync_batchnorm from mmseg.apis import inference_model, init_model from mmseg.apis.inference import show_result_pyplot def main(): parser = ArgumentParser() parser.add_argume...
e818e4ca18d986460db7bae146ad7c7bf3341f82643c90ce0fe5db3a1a6431a0
Python
3,830
114
import torch import torch.nn as nn import torch.nn.functional as F from rde.modules.encoders.single import PerResidueEncoder from rde.modules.encoders.pair import ResiduePairEncoder from rde.modules.encoders.attn import GAEncoder from rde.utils.protein.constants import BBHeavyAtom from .rde import CircularSplineRotame...
1a98e10e61ab88db9fb7ef644c4e3be5f812799c2926ad2c43b8ae24fbc213c4
Python
3,833
136
from asciitree import LeftAligned from ..client import inject_client from .general import fetch_meta @inject_client def fetch_all_rois(*, client=None): """ List all ROIs in the dataset. """ meta = fetch_meta(client=client) return _all_rois_from_meta(meta) def _all_rois_from_meta(meta): rois...
81e1946d43cfde5a9a6213def5e5eda349268ea2b9478ef32e1e378569d0e040
Python
3,833
100
import logging from pathlib import Path import numpy as np from .standard_io import ( read_freq_and_amp_from_hdf5, write_freq_and_amp_to_csv, write_freq_and_amp_to_hdf5, ) from ..utils.utils import output_label_under logger = logging.getLogger(__name__) def average_transients_for_group( *, member_r...
8681e69db1b855f6c828f9848d2091aeb7206defd67f1dfcae82c8fcfc1a5be3
Python
3,835
108
from __future__ import annotations from typing import TYPE_CHECKING, Literal import pytest from pymatgen.core import Lattice, Structure from chgnet.graph import CrystalGraph from chgnet.graph.converter import CrystalGraphConverter if TYPE_CHECKING: from collections.abc import Generator lattice = Lattice.cubic(...
ef14584d6ea13a121b79aa2f73808d0e769916c0677cd700ef1676b0e711863d
Python
3,835
95
# %% from PIL import Image from os.path import join import os, glob, re import pathlib # def gifify(sub, img_dir, save_dir, file_pattern, save_fname): # image_files = glob.glob(join(img_dir, f"{file_pattern}"))# f"*sbref*.png")) # images = [] # for filename in sorted(image_files): # img = Image.ope...
a4b82183539d8893f2914382c2122a2080290db7f5acf7bf0817171997d576c9
Python
3,836
105
from torch.utils.data import Dataset, DataLoader from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \ CenterCrop from transformers import BertTokenizer import pytorch_lightning as pl from PIL import Image import os class flickr30k_CNA(Dataset): def _...
b12aac0fb633af665440839ec3c38fd46de213160ad566dc7c71a089b4639b7b
Python
3,837
90
"""Unit tests for src/datahandlers/obo.py that don't require network access.""" import json import pytest from src.datahandlers import obo from tests.conftest import assert_synonyms_file_valid class _FakeUberGraph: """Stand-in for src.ubergraph.UberGraph returning a fixed synonym set.""" def __init__(self...
ed4fdb3ef68249298b1fd17e3b9640d37983070b1c8d055362130733e4d01242
Python
3,841
126
from fastapi import Request, Form, APIRouter, Depends from fastapi.responses import HTMLResponse, JSONResponse from medperf.web_ui.common import ( initialize_state_task, reset_state_task, templates, ) from medperf.account_management import read_user_account from email_validator import validate_email, Email...
e3ec365f2ab00c6e813d5596a81b12e5cceb8e54998af7b9176d0b08c428bca3
Python
3,844
124
import numpy as np from pyscf import gto, dft from pyscf.geomopt.geometric_solver import optimize from pyscf.hessian import thermo # from pyscf import dftd3 from molSimplify.Classes.mol3D import mol3D from pymatgen.core import Molecule from pymatgen.analysis.molecule_matcher import BruteForceOrderMatcher from pymatge...
6ed8e567275afbdcdf986e28d35ead6c5117ed0d042a2c10c25ca1c4f1680c0d
Python
3,847
99
import json import numpy as np import pickle as pkl import random from collections import defaultdict from tqdm import tqdm from concurrent.futures import ThreadPoolExecutor def load_data(filename): with open(filename, 'rb') as f: return pkl.load(f) def two_hop_mapping(mapping_dict, umls_cuis, triple_set,...
c2f3dab95e8169711118a0333f3bd8e975381a316d8efd1ff9a96c68f93c0bc9
Python
3,847
90
#!/usr/bin/env python # -*- coding: utf-8 # TODO # # For usage, type: python average_images.py -h # Example: # python average_images.py -path-data ~/duke/temp/sebeda/rootlet_reg/results_spine-generic_sub-amu01_rootlets_2024-10-18/data_processed/ -path-file reg_discs -path-out ~/duke/temp/sebeda/rootlet_reg/results_spin...
93248e1b9771ff09ec988631b30463138058c1b618e9ac18bb13e4abf7622425
Python
3,850
108
import os import torch import random import numpy as np import cv2 from typing import List, Tuple from torch import nn, Tensor import torch.distributed as dist def get_params_groups(model): regularized = [] not_regularized = [] for name, param in model.named_parameters(): if not param.requires_gra...
0674046985e940a104fb08b1fc05f08e50257d667a88fc2e22c096dfbab207bd
Python
3,851
96
#!/usr/bin/env python # -*- coding: utf-8 # fslstats thresh_zstat1_med.nii.gz -V | cut -d " " -f1 >> voxels_med.txt # fslstats thresh_zstat1_high.nii.gz -M >> zscore_high.txt # fslstats thresh_zstat1_med.nii.gz -H 15 3.1 9 >> hitogram_med_15_3.1-9.txt import os import argparse import nibabel as nib import numpy as np...
2da2287d4c779bab999ef67f6d5aa306bd17d8e9eb0996b60cbb7b4dda2e28b3
Python
3,851
107
"""Smoothing the raw channels before they are fit and normalized.""" import logging import numpy as np from scipy import signal as ss logger = logging.getLogger(__name__) def validate_chunk_lengths_for_filtering(tsNew: np.ndarray, coords: np.ndarray, filter_window: int) -> None: """ Ensure every artifact-r...
d502f0c14b7017c764b16a71f2b118b3b63637cb7433b55a242666f4abc20939
Python
3,851
70
import sys sys.path.append('../') from data import make_loaders,create_dataset,MaskAtom,MolGraphSet,Mol2HeteroGraph from dgl.dataloading import GraphDataLoader from omegaconf import DictConfig, OmegaConf import pandas as pd from rdkit import Chem import torch # def get_dataset(dataset, mask_edge=False): # transfor...
81442bfbb13ce79ed5be9f6d0aa39ebcdd974ceb67dc6ec4cfb76a930092a369
Python
3,852
118
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import ConvModule, build_norm_layer from mmseg.registry import MODELS class MLAModule(nn.Module): def __init__(self, in_channels=[1024, 1024, 1024, 1024], out_channels=256, norm...
ae26bb368f70832b40de556644b129530ead2c83aeb0bf37b7b2ff610a3d1dbf
Python
3,853
85
# SPDX-License-Identifier: Apache-2.0 from transformers import T5ForConditionalGeneration from .models import CombinedDecoder, SimplifiedT5Encoder import torch def create_t5_encoder_decoder(pretrained_version='t5-base'): """ Generates an encoder and a decoder model with a language model head from a pretrained hu...
950c3084586c712c8bfa52f89b1e63a8254fa7072a02b40f2d4dd2a77212bb89
Python
3,854
89
from experiment import * from behavior_analysis.io import TrackingInterface import pandas as pd import numpy as np from scipy.interpolate import interp1d from scipy.stats import linregress if __name__ == "__main__": strike_clusters = [1, 2, 4] time_window = 0.2 # time (seconds) to study pre-strike onset...
ff5e6d5e39560c94f2f761109729b73ef1b70d034263ae81db60444ef744fd46
Python
3,856
134
# pylint: disable=invalid-name, too-many-arguments, too-many-positional-arguments """Tests for compatiblity with sklearn.""" from typing import Callable, Optional, Type import numpy as np import pytest from ..core import DMatrix from ..sklearn import XGBClassifier, XGBRFRegressor from .utils import Device def run_...
9356f86f8a631ccbf8d0f10a115a592b361cf673e0d46f8f9791c1908ddde927
Python
3,858
91
from __future__ import print_function, division import torch import torch.nn as nn class ConvLayer(nn.Module): def __init__(self, atom_fea_len, nbr_fea_len): super(ConvLayer, self).__init__() self.atom_fea_len = atom_fea_len self.nbr_fea_len = nbr_fea_len self.fc_full = nn.Linear(...
b60eeb20de7a78bdf5c1391a32b43d9783a1056e571556e9e544aa01eb0c6f91
Python
3,858
91
"""Network tests for the UniChem download. These verify that the UniChem HTTP mirror URLs are reachable with the User-Agent Babel sends, that each file is a valid gzip archive, and that the reference file header matches the constant in unichem.py. Run with: uv run pytest --network tests/datahandlers/test_unichem.py ""...
9c7a8ec4db3a0b3fc46fb09625faec8fd642b3f92b8e535c1cc9db57d9448b5e
Python
3,859
109
""" Functions for loading models and datasets from experiment folders. Author: Hanna Tolle Date: 2025-01-12 License: BSD-3-Clause """ import sys sys.path.append('../') import os import importlib import copy import torch from utils.configs import fill_missing_configs from experiments.ingredients.data_ingredient impo...
d3ac7898b4a7f7a1918fe2a76fe003d9d5d1a9ba0b8444b069eb2f5d953f1635
Python
3,862
94
import json from importlib.metadata import version from pathlib import Path import numpy as np import pytest from guppy.testing.api import default_output_root_folder, save_parameters_snapshot @pytest.fixture(scope="function") def default_parameters(): return { "combine_data": False, "isosbestic_...
7a909454f8347ce7b9de9a6718e73e562551595b32725875cfca897c07e5c047
Python
3,865
114
""" Demonstrate the use of h5py in SWMR mode to write to a dataset (appending) from one process while monitoring the growing dataset from another process. Usage: swmr_multiprocess.py [FILENAME [DATASETNAME]] FILENAME: name of file to monitor. Default: swmrmp.h5 D...
c667e1179bc788d7f71b92827185c3e042c5bde08cd249f32a5c9d424a5a723c
Python
3,866
80
# 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...
c022bde96e7e6d1ff2c33d78ae553887ae0e5a8e95d712f566ede49fbcf61161
Python
3,867
117
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmcv.cnn import ConvModule from mmseg.registry import MODELS from ..utils import resize from .decode_head import BaseDecodeHead class PPM(nn.ModuleList): """Pooling Pyramid Module used in PSPNet. Args: pool_scale...
19cbb9270cd7d6194d109a108ee7060cf7a0646a33cbe5bce098acdcc0e21cc1
Python
3,871
89
import os def create_key(template, outtype=('nii.gz',), 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 which run...
a899faee4e3211a732f114f83b057a367b3a1ccdd1de84fceebf0525ae3ea7db
Python
3,872
153
import os import numpy as np import pathlib as pl import subprocess as sp try: import cv2 as cv except ImportError: cv = None from tifffile import imsave def ffmpegInstalled(): """ """ return def reflectVideo(video, flipAxis='hflip', suffix=' (reflected)', speed='medium', deleteOriginalVideo=Fals...
b1322eea0ca9bb4b7940ec4ec44564716a60d220eaa7500f5ffbb09e8049389a
Python
3,872
112
from collections import Counter import ase import ase.io as aio import numpy as np from ase.calculators.mixing import LinearCombinationCalculator from ase.calculators.morse import MorsePotential from ase.optimize import LBFGS from simgen.manifolds import StandardGaussianPrior from .calculators import MopacCalculator...
e24aa8876025ac5e7f8e78bde011f2ff66c47f3361c17854335946f280590bdb
Python
3,873
108
from rest_framework import serializers from .models import Model from mlcube.serializers import MlCubeSerializer from asset.serializers import AssetSerializer from mlcube.models import MlCube from asset.models import Asset from django.db import transaction class ModelSerializer(serializers.ModelSerializer): conta...
eeb419625125cb78a69b2ce193d973cb614787b64d76aa7cfe0584b94726ebd2
Python
3,873
118
import sqlite3 import collections from datetime import datetime, timedelta import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') def get_engine_data(): """Main""" conn = sqlite3.connect('tasks.db') cursor = conn.cursor() tasks = collections.defaultdict(list) SQL = 'SELECT ...
fda1d64e2228d60ea7070a3c815d01435eb09f315e5e0f98e1b4458f6e8d1167
Python
3,873
114
import jaxlib.xla_extension import jax.numpy as jnp import jax import numpy as np import roadrunner from jaxkineticmodel.load_sbml.sbml_model import SBMLModel import pandas as pd import os from jaxkineticmodel.utils import get_logger logger = get_logger(__name__) import tellurium as te # noqa: E402 jax.config.updat...
c48d814b77bc9ee03c68ccf541c6a8e815f57ed038e6e507024b1fac14618522
Python
3,874
107
import os import gensim from Utils.dataloader_COVID import * from Utils.models import * from Utils.TrainModel import * from Utils.config import * # OPTIONAL: Load the "autoreload" extension so that code can change #%load_ext autoreload # OPTIONAL: always reload modules so that as you change code in src, it gets loade...
ba807843ad165681e9d1483762f7010571e92fdc7380e3512c8f8832b2c97442
Python
3,875
128
from similarity import similarity import numpy as np from tree import build_tree_from_list import bisect from mol_utils import split_molecule, join_fragments from global_parameters import MAX_FRAGMENTS import rdkit.Chem as Chem import os # Get a martix containing the similarity of different fragments def get_dist_mat...
8e1b67e3dd68b13e48ee17ed159a02785b3c56e1d763104bb10f315701e4b672
Python
3,877
116
import json from pathlib import Path import panel as pn import pytest from guppy.orchestration.home import build_homepage from guppy.orchestration.save_parameters import save_parameters from guppy.testing.api import default_output_root_folder # Written into the snapshot but not produced by the parameter form: the ve...
a1c90fab53f59f6277f87e08f5b91dece0c933dd86f37a7f0f1ef56f0b9ccbf3
Python
3,878
110
import argparse import os import shutil import re import yaml import json import pandas as pd def prepare_data_input( predictions, original_data, missing_modality_json, intermediate_folder, ssim_csv ): modalities = {"t1c": "t1ce", "t1n": "t1", "t2f": "flair", "t2w": "t2"} os.makedirs(intermediate_folder, ...
0e0ad92d16b81f3bd2ca4dcd401e07ab857ec021c83ecd7be711f727c5b244b6
Python
3,879
128
#!/usr/bin/env python """ MetaWIBELE: filter_prevalence module Filtering features based on prevalence Copyright (c) 2019 Harvard School of Public Health Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the S...
0b7f137dc78812331ea060d6b0e10c33b87ee16acdaeca462b6f00443b752464
Python
3,880
109
import os import numpy as np import pytest import xgboost as xgb from xgboost import testing as tm from xgboost.core import DataSplitMode pytestmark = pytest.mark.skipif( tm.no_arrow()["condition"] or tm.no_pandas()["condition"], reason=tm.no_arrow()["reason"] + " or " + tm.no_pandas()["reason"], ) import p...
770ec9cc64822b11498c6536c077b8cb2ca5bcb1086c4a4d644e6bd017b89607
Python
3,881
103
from .models import BenchmarkModel 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 .permissions import IsAdmin, IsModelOwner, IsBenchmarkOwner, IsCommit...
4df6638567b37b17e9cb22d8c8fac0ea8a6426aac5af2b653107bb58d0b843ac
Python
3,882
139
"""Progress tracking REST API endpoints. Ephemeral progress trackers stored in Redis (hash), broadcast via Socket.IO. """ import json from fastapi import APIRouter, Response, status from zndraw.broadcast import broadcast_to_room from zndraw.dependencies import ( AccessEditDep, RedisDep, SioDep, ) from z...
9f13229547c4128438e2098c2ca207a04cfc5243aeeaf1daf9283b22b4947c34
Python
3,885
112
import os from typing import TYPE_CHECKING import medperf.config as config from medperf.entities.model import Model from medperf.utils import remove_path from medperf.enums import ModelType if TYPE_CHECKING: from medperf.commands.mlcube.submit import SubmitCube from medperf.commands.asset.submit import Submit...
2bb6640810465c3f044535bd99236007ae970c910f75183b4c8b64ecb77cb466
Python
3,886
120
# 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 compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
395679e93796c741b60589228fdd7524e965ad0437b89d9ee4bad0e7d703fe62
Python
3,886
99
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...
30b4fbee5582b9b1fd9509d3e842e42578483d0ebfaf23982b2dac5a2c98abd0
Python
3,887
111
#!/usr/bin/python import logging import os import shutil import sys from isorefiner.common import get_version, run_command logger = logging.getLogger(__name__) def main(args): try: # Set variables raw_bam_files = [os.path.abspath(_) for _ in args.bam] raw_genome_file = os.path.ab...
37e7575375c3fdde38fb5b0384146f7de896b09bb21a8eef319793ae4512e219
Python
3,890
82
import pandas as pd import matplotlib.pyplot as plt import torch import seaborn as sns import scienceplots import matplotlib.gridspec as gridspec import matplotlib.colors as colors import numpy as np import nilearn import nibabel as nib from nilearn import plotting, datasets, surface, image from nilearn.plotting import...
bfc16610c13d67ca54899fb569bd2bca74506bb89331b3981f69e5c9eaf7c138
Python
3,890
124
################################################################## # Selecting patient ids that have size-4 motif enriched # Reproducibility for Figure.3F ################################################################## import pandas as pd import numpy as np import re import os import ast file = 'CRC_clusters_neigh...
d581b2499e6d6bace3267665b4e2ba9124f3a930a3f5b9f7b1e1d801f88fa7d8
Python
3,891
106
# Copyright DST Group. Licensed under the MIT license. from datetime import datetime from CybORG.Shared.Enums import FileType, FileVersion from CybORG.Simulator.Entity import Entity from CybORG.Simulator.LocalGroup import LocalGroup from CybORG.Simulator.User import User import enum class File(Entity): """A File...
0e4128ecde40075fab0de117d00ead131c5c974d22b66aa987ef1fb1ddea3bce
Python
3,892
121
#!/usr/bin/env python """ MetaWIBELE: extract_non_redundance_seq module Extract representative sequences from the clusters based on representative IDs 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 docume...
abd6b872d247b1e0f969f3428e07686a1254495c8953ab15cba02d91cb8d568d
Python
3,892
117
import pytest from guppy.utils import progress from guppy.utils.progress import StepProgress, _current_step, step_error_handler @pytest.fixture def bound_step(): """Bind a StepProgress for the duration of one test, as ``home.py`` does per step run.""" step = StepProgress() token = _current_step.set(step)...
27f482a48ffd064d2f21316205d700970291a3b3c0be5e6f67742c7491095e16
Python
3,894
131
""" Unit tests for the pipelining primitives in :mod:`nearl.pipeline`. These tests exercise :class:`PrefetchBuffer` and :class:`AsyncWriter` in isolation (no CUDA required) so they run on any machine. """ import threading import time import pytest from nearl.pipeline import _ERROR, _SENTINEL, AsyncWriter, PrefetchB...
3666e4072bc2aeaad5ce0ca40f50bbab9bc609e6315e6ea8886d0bede0aed1a4
Python
3,894
99
import os import pickle import functools os.makedirs(os.path.join('/tmp', 'luna_cfg'), exist_ok=True) LUNA_CONFIG_PATH = os.path.join('/tmp', 'luna_cfg', 'config.pkl') class LunaPaths: """ A Paths object containing config for LUNA dataset. """ ROOT: str = '' """Root directory where LUNA dataset...