sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
0a8b3b365492141fb1a754a830d3251d5790ee76b077139fbdb63188f8853e1d | Python | 9,767 | 237 | from dataclasses import dataclass
from transformers import (
MegatronBertConfig,
MegatronBertForPreTraining,
AutoTokenizer,
)
from pytorch_lightning import (
LightningModule,
Trainer,
)
from pytorch_lightning.callbacks import (
LearningRateMonitor,
)
import argparse
import torch
import os
import... |
b14c9e43bb8630d48d2360df0bd21e28615839daa7b1a06089a8c2e5afb9d4af | Python | 9,768 | 229 | from typing import List, Tuple
import random
import pytest
from pytest_mock import MockerFixture
from CybORG.Shared import Observation
from CybORG.Shared.AgentInterface import AgentInterface
from CybORG.Simulator.Actions.AbstractActions import Impact
from CybORG.Shared.Session import RedAbstractSession, Session
from C... |
e7c5b732ef12083bffd2abe9776147a7649a3100aa65547993658d0e0cc9ff56 | Python | 9,768 | 208 | import pytest
from CybORG import CybORG
from CybORG.Shared.Enums import ProcessName
from CybORG.Simulator.Scenarios.EnterpriseScenarioGenerator import EnterpriseScenarioGenerator
from CybORG.Agents.SimpleAgents.ConstantAgent import SleepAgent
from CybORG.Simulator.Actions.AbstractActions.DiscoverDeception import Disco... |
31bc1b120bf6c95e3ac01004dad33ee6bc7af9965579baaefb2629fd57def746 | Python | 9,769 | 233 | """Aggregate Babel SLURM rule error logs into a single copy-pasteable report.
Reads the main Snakemake ``sbatch-<version>.err`` control-node log, follows each failing rule to
its per-rule log, and groups rules that share identical error content so a recurring transient
failure (e.g. an HTTP 503 from a data source) sho... |
7f2fe7c820afc6b1886c323cad00c4d8c1f3a37c8dd80c6c5684ef15fd699517 | Python | 9,769 | 272 | #!/usr/bin/env python3
# %% Package import
import subprocess
import numpy as np
import pandas as pd
import argparse
import os
from scipy import stats
from statsmodels.stats.multitest import multipletests
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
import pathlib
import re
mpl.rcParam... |
de344d8855867633dc54fa4eaa15721c50761ac2b0d91e30c623a62623e5eda3 | Python | 9,772 | 250 | import logging
from pathlib import Path
import numpy as np
from .save_parameters import save_parameters
from ..analysis.io_utils import is_continuous_label
from ..frontend.parameterized_plotter import available_psth_metrics, build_plotter
from ..frontend.visualization_dashboard import VisualizationDashboard
from ..ut... |
a68dcabeac6c0cb5992ce059fff94474dce7f305a5030c2e51586a79da800655 | Python | 9,777 | 303 | """Internal job registry for taskiq-based server-side execution."""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Protocol
if TYPE_CHECKING:
from collections.abc import Callable
from contextlib import AbstractAsyncContextMana... |
bb59e857053d1dcce7efd268b9996484584b8bd8c9eceb562698242ef2833e44 | Python | 9,779 | 227 | import torch
import torch.nn as nn
import numpy as np
import tqdm
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_auc_score, average_precision_score
criterion = nn.CrossEntropyLoss(reduction='none')
class EarlyStopper:
def __init__(self, patience=1, min_delta=0.001):
self.pa... |
50ff924fb11ad3078936782cd55ca4db6df12c2a804a60a8ede1a42df4d92043 | Python | 9,780 | 339 | # -*- coding: utf-8 -*-
"""stress strain
"""
#@title Function Definitions
from sklearn import linear_model, datasets
def ransac_fit(X, strain_array, subset = False, plot_fit = True):
'''
Linear Fit with RANSAC
subset: interval e.g. [0.1, 0.8] is grabbing data from 10-80 %
i.e. discarding e... |
82525dec2844022a8974132a7ed5620f714dd41403dd7c97fd20d739cf7691cc | Python | 9,782 | 266 | # -*- coding: utf-8 -*-
import json
import os.path
from typing import Tuple
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.http import HttpRequest, HttpResponseRedirect, JsonResponse
from django.shortcuts import redirect
from catmaid.co... |
5798a7e396233edbfbb9bcd850229f66f8a96be9055767d4bd3a6b287e109194 | Python | 9,802 | 177 | import json
import pytraj as pt
import numpy as np
import pandas as pd
# from Nearl import utils, data_io
import nearl
from feater import io
#### Task1:
# 1. Check if the QM and MD data are present in the database
# 2. If NO, update the supercedes list
#### Task2:
# Find the ligand atom index in the MD trajectory
... |
41f4e52141a82fa5db0f67f937ad0956f95a87032329bda9b76b2e3df3fcba43 | Python | 9,809 | 286 | import re
import tarfile
import typing
from typing import Dict, Tuple, Any, Generator, Optional, List
import pandas as pd
from kgx.config import get_logger
from kgx.source.source import Source
from kgx.utils.kgx_utils import (
generate_uuid,
generate_edge_key,
extension_types,
archive_read_mode,
sa... |
396d43511aaa7e8fd0ec20b4a812aa72ab469973fe3b4bc26e1445a525d2ec2e | Python | 9,810 | 237 | import numpy as np
import random
import torch
from pathlib import Path
from torch.utils import data as data
from basicsr.data.transforms import augment, paired_random_crop
from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor
from basicsr.utils.flow_util import dequantize_flow
class REDSData... |
0d15c65cfcad3bc272dd60f347b611bfa61cd4d0f3d8350047d48c8ea7643a00 | Python | 9,815 | 265 | """Tests for TripleStore.execute_query() retry and error-handling logic.
The retry path is tested without a live SPARQL server using two thin fakes:
_FakeQueryResult — wraps a single return value for one call to .convert().
If the value is an Exception instance, .convert() raises it; otherwise it
returns the ... |
7c42b95ca96dca1686b44d2f7c45317ff5a8f28fe949d0dd76d29b9db70f6488 | Python | 9,817 | 234 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 7 17:48:04 2022
@author: george
"""
import warnings
warnings.simplefilter(action='ignore', category=Warning)
import numpy as np
import pandas as pd
from tqdm import tqdm
import os, glob
pixelSize = 0.108
def getStats(df):
stats = df.agg(
... |
4f1d3921b5c3c9bb1e0c2e8f04b8c6e3904fe15a85edee816bbdc31419cf85d7 | Python | 9,823 | 258 | ##################################################################
# Test NSIC in identifying occurrences of CC motifs in diverse simulated data sets
# Reproducibility for Figure.2F
##################################################################
import torch
import os
import numpy as np
import dgl
import l... |
9e44497c883e1d4974818665d66e4adf168d6cef8c3890dd851ae832e80f1244 | Python | 9,826 | 283 | """
Demonstration for parsing JSON/UBJSON tree model files
======================================================
See :doc:`/tutorials/saving_model` for details about the model serialization.
"""
import argparse
import json
from dataclasses import dataclass
from enum import IntEnum, unique
from typing import Any, Di... |
38fdb7a89675f1d1da263e1953bb184643e8616a055972c8f809c6b432f61757 | Python | 9,836 | 306 | import itertools
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import wilcoxon
from statsmodels.stats.multitest import multipletests
import matplotlib.patches as mpatches
def sort_key(key):
"""Define a custom sorting order for a given input key."""
if key == 'uncorr':
return (0,... |
ee0c260780e3d73c01df687b2a8e5fe586cab06981996c8d3d5af21510b13c9a | Python | 9,838 | 333 | import torch
import torch.cuda
import glob
import os
from collections import namedtuple
import pandas as pd
import functools
import json
from collections import *
import random
import diskcache
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import numpy as np
import cv2
import torchvision.... |
f97b9ae3da530014788e2f6bf270ff9fa8d74ee74dbc443dab8d0bb46a32aedd | Python | 9,840 | 265 | import h5py
import numpy as np
import pandas as pd
from exptlib import Experiment, MetadataAttribute, CSVMetadata
import cv2
from exptlib.directory import Directory
from zigzeg import align_peaks, find_runs
from scipy.interpolate import CubicSpline
from .io import TrackingInterface
from .kinematics import compute_tail... |
2ed9cfe4db3df80b60562d3fac099b2374314d23de1eb945e3d3250db54eac32 | Python | 9,841 | 209 | #!/usr/bin/env python
"""
MeteWIBELE workflow: MeteWIBELE prioritization workflow
1) unsupervised prioritization based on abundance and prevalence
supervised prioritization based on association with phenotypes
2) selected prioritization based on interested functions
3) format and finalize prioritization
Copyright... |
8099dc5027a483f8120da74837e2ef80a0f0c35c6d5f5644d29852b284e86113 | Python | 9,843 | 252 | #!/usr/bin/env python3
## CPCantalapiedra 2021
import os, sys, shutil
import argparse
from eggnogmapper.common import set_data_path, get_data_path, pexists, pjoin, existing_dir
from eggnogmapper.backends import get_backend_names, resolve_backend, DEFAULT_BACKEND
from eggnogmapper.utils import ask, ask_name, colorify
... |
6d5cbb8082665be36f03fd0af7a0a0663d3c4ab75702180adca656bfe463f399 | Python | 9,849 | 210 | """
Convert the voxel data to Hilbert curve representation
"""
import time, os, sys, argparse, json
import numpy as np
import h5py as h5
import multiprocessing as mp
from hilbertcurve.hilbertcurve import HilbertCurve
from feater import io, utils
INPUT_TAGNAME = "voxel"
OUTPUT_TAGNAME = "voxel"
def hilbert_map(iter... |
6ab8b49c52a05a3baf5c7a83303035125c3d9d7ccfda5857806fc07eea860fba | Python | 9,850 | 302 | """
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 io
import pytest
import requests
import torch
from ocpmodels.common.registry import registry
from ocpmodels.common.utils import load... |
5b27f735374be0280360b35a3b1a1a77fd4c00adafd756d335231e4daa07877d | Python | 9,853 | 267 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Andrei Istudor andrei.istudor@gmail.com
"""
import os.path
import queue
import socket
import time
from threading import Thread, Lock
import docker
import subprocess
from os import path
# from PhenoPorts import *
# from ProcessingComm import ProcessingCo... |
3f8a610ba85b2ae721627bb5e17eb3ae5831e7daa8e76e8809e243571bc7a21d | Python | 9,857 | 291 | """
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 heapq
import logging
from itertools import chain
from pathlib import Path
from typing import List, Literal, Protocol, Tuple, Union, ru... |
f346d80735a6c77a50a1fd11018d26da389650de3e0dc8971b9cfad7b6841ed7 | Python | 9,861 | 235 | # coding=utf-8
# Copyright 2021 The IDEA Authors. 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 a... |
5a5aa0144e307aafce347d00cd1b533153e82997b7d7e414cb303355f6cdad54 | Python | 9,862 | 235 | """
Unit tests for guppy.orchestration.visualize._validate_psth_outputs_exist.
"""
import logging
import re
from pathlib import Path
from unittest.mock import patch
import pytest
from guppy.orchestration.visualize import (
_validate_psth_outputs_exist,
helper_plots,
visualizeResults,
)
@pytest.fixture
... |
efa631f9be3d9dd07c791da2cc793b36785536c41d6a4da4d1734da9a76d1d47 | Python | 9,864 | 205 | # 导入必要的库
import sys
import os # 用于操作系统相关的操作,例如读取环境变量
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import IPython.display # 用于在 IPython 环境中显示数据,例如图片
import io # 用于处理流式数据(例如文件流)
import gradio as gr
from dotenv import load_dotenv, find_dotenv
from llm.call_llm import get_c... |
51912869048f80aaffa478002af6adfe48dcaa8b8f67e981bb1f6de38927dc44 | Python | 9,869 | 261 | import torch
import torch.nn as nn
import torchvision
from fpga_interface import FPGAInterface
class ChannelAttention(nn.Module):
"""Channel Attention Module from CBAM"""
def __init__(self, in_planes, ratio=16):
super(ChannelAttention, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
... |
c12b9d06c1022f61ac01bcf0bfdd6c01cb4b25236623414c0efdc0ddceae4e03 | Python | 9,870 | 215 | from PyQt5 import QtGui, QtWidgets, QtCore
import time
import numpy as np
from util import colors
from view.ExportDialog import ExportDialog
from model.export import export
from view.AddCopyMultipleDialog import AddCopyMultipleDialog
from view.DeleteMultipleDialog import DeleteMultipleDialog
class ObjectMan... |
7c9da85e8347356afdf6b30f9d94ba19d6c1b65c21a5d84be68742c92e5a78a6 | Python | 9,874 | 244 | """Behavioral covariates aligned to whole-session time bins.
A covariate is a continuous variable measured outside the rig -- an akinesia
severity rated every couple of minutes, say -- ingested as an ordinary GuPPy-CSV
store and labeled ``covariate_<name>`` in step 1. This module averages such a
variable within the bi... |
dd7042ab255b7e19d10f68fa92d1ae204132ae21752619bcb040be31593f0037 | Python | 9,877 | 281 | """Utilities for in-memory MS/MS spectrum preprocessing and matching."""
from __future__ import annotations
from typing import Optional
import numpy as np
_EMPTY_SPECTRUM = np.empty((0, 2), dtype=np.float32)
_EMPTY_INDICES = np.empty(0, dtype=np.int32)
def clean_spectrum(
signals: np.ndarray,
precursor_m... |
5f0f7da3c581f889e7b728f237aa6193f19a8426a05d94b1fd8706d9ca19b3c8 | Python | 9,880 | 294 | import itertools
import numpy as np
import torch
import hydra
from pymatgen.core import Composition
from scipy.spatial.distance import pdist
from scipy.spatial.distance import cdist
from hydra.experimental import compose
from hydra import initialize_config_dir
from pathlib import Path
import smact
from s... |
0a704aa92f3ff99b1835faf5426e3c454c76840a04c540c3c7678fe7d90cd300 | Python | 9,885 | 262 | # -*- coding: utf-8 -*-
from collections import defaultdict
import json
import re
from typing import Any, DefaultDict, Dict, List, Set
from django.conf import settings
from django.db.models import Count
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404
from... |
3e52aba4875c0ca5af500cd0cb2a40e877861db83ae68b998524d0c759f5a2b5 | Python | 9,885 | 261 | import torch
import torch.nn as nn
import timm
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.backends.backend_pdf import PdfPages
from torchvision import transforms, models
from cryocat import cryomap, mdoc
from PIL im... |
4e8d81b257429f94206fcc3d6b896cec19b643c33dea50a8d987db80a5e53ef6 | Python | 9,885 | 204 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .layers.crf import CRF
from .layers.bert_output import BiaffineClassifierOutput, TokenClassifierOutput, SpanClassifierOutput
from transformers import BertPreTrainedModel
from transformers import BertModel
from .layers.linears import PoolerEndLogit... |
c5c65380f385e1bf6ee50adecc14f3c3c039dfc2bfa3150588a5ce4321048f52 | Python | 9,888 | 207 | """
This module contains functionality to read neural spikes
for each recording session in 'ucdavis' dataset.
By organization there is a separate .mat file for each session.
Within the main directory for ucdavis data these files are located in ./Data/*.mat.
Each .mat file contains the following fields:
- TrialStimDat... |
4fe6da7b9761bc587b8e7c2008dde8e12ed7c379dc42865776cb6398e00fde89 | Python | 9,891 | 319 | # -*- coding: utf-8 -*-
import re
import six
import unicodedata
import torch
import rouge
import numpy as np
import random
# from fengshen.examples.pegasus.pegasus_utils import text_segmentate
import sys
sys.path.append('../../../')
rouge = rouge.Rouge()
is_py2 = six.PY2
if not is_py2:
basestring = str
def ... |
818fa538b710850fd26ae2142fff646265cb399a329895239f028cfa4ce22bef | Python | 9,892 | 229 | import json
import logging
from importlib.metadata import version
from pathlib import Path
from guppy.utils.utils import (
discover_run_folders,
run_directory_root,
select_run_folders,
)
logger = logging.getLogger(__name__)
DEFAULT_ARTIFACTS_REMOVAL_METHOD = "replace with NaN"
def read_artifact_provena... |
3918bcd2c008ad5200abc2f62524bdc8afe4e900de9a2688d6b73a26d0784423 | Python | 9,900 | 240 | # -*- coding: utf-8 -*-
import logging
import numpy as np
import progressbar
import sys
from typing import Dict
from django.core.management.base import BaseCommand, CommandError
from django.db import connection
from catmaid.models import Project
from catmaid.util import str2bool
from .common import set_log_level
lo... |
1a9cf72bb0ac05328fd00012eaee02fdd62773f136d2c83ecdc103b7e5d9ff67 | Python | 9,901 | 237 | #!/usr/bin/env python
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list o... |
9b46e1f48b9d6d89d6c60a4f2a30625ab628f7f370038a300d83f5708a9c5b8f | Python | 9,903 | 257 | from collections.abc import Sequence
from typing import List
import numpy as np
import torch
from torch import Tensor
from .data import Data
from .dataset import IndexType
class Batch(Data):
r"""A plain old python object modeling a batch of graphs as one big
(disconnected) graph. With :class:`torch_geometri... |
67478b1e14fdf9adccdaffa33f7ca3d63965e58264492447d2565f3221ae82a1 | Python | 9,905 | 221 | # parse gene annotation
import gzip
from collections import namedtuple
# Initialized GeneInfo named tuple. Note: namedtuple is immutable
gffInfoFields = ["seqid", "source", "type", "start",
"end", "score", "strand", "phase", "attributes"]
GFFRecord = namedtuple("GFFRecord", gffInfoFields)
Pos = namedt... |
a1907f9c38fb31a9e72120cdcd797fd414238df1d0603b10bed9c1ae0846197e | Python | 9,911 | 246 | import re
import numpy as np
from random import choice
from collections import defaultdict
from itertools import chain
import pysster.utils as io
from pysster.One_Hot_Encoder import One_Hot_Encoder
from pysster.Alphabet_Encoder import Alphabet_Encoder
class Data:
"""
The Data class provides a convenient way... |
eb981583e9e9af15564947fa0a2430d5fb9b0c57f1dfb0953fd1cb9a6aa22f65 | Python | 9,912 | 347 | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is modified from the ASE db json backend
and is thus licensed under the corresponding LGPL2.1 license
The ASE notice for the LGPL2.1 license is available here:
https://gitlab.com/ase/ase/-/blob/master/LICENSE
"""
import os
import zlib
from typing... |
6d7d42d63f92c18e05793c6d640192df626dbd8ccf9db3059ef1824721f3b58f | Python | 9,913 | 190 | # 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... |
d65ea6fbc92c85b79a194e3d31a9a9f400cec1d4a1e112133459b1babf6f9c8f | Python | 9,913 | 235 | import time
import argparse
import torch
from tqdm import tqdm
from torch.optim import Adam
from pathlib import Path
from types import SimpleNamespace
from torch_geometric.data import Batch
from eval_utils import load_model
def reconstructon(loader, model, ld_kwargs, num_evals,
force... |
9fd3df5c727b85deaa62a6184a2b5039e2587a97097e22a0148a60c812033717 | Python | 9,916 | 286 | pretrained = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/swin/swin_base_patch4_window12_384_22k_20220317-e5c09f74.pth' # noqa
crop_size = (640, 640)
data_preprocessor = dict(
type='SegDataPreProcessor',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
bgr_to_rgb=True,
... |
98467467fa8fa2a41e41fbf9d03ab3b2aabc13f5a1c41bc2444980ff8ce246d6 | Python | 9,920 | 274 | import itertools
import os
import pickle
from copy import deepcopy
from multiprocessing import Pool
from typing import Sequence
import numpy as np
import torch
from joblib import Parallel, delayed
from rdkit import Chem, DataStructs
from rdkit.Chem import AllChem, Crippen, Descriptors, Lipinski
from rdkit.Chem.FilterC... |
0f878cccafeb726d4dd8c18127ebc459a86bf10fa7e3605bf8523f4b35fb2c10 | Python | 9,939 | 214 | from PyQt5 import QtGui, QtWidgets, QtCore
from copy import copy
from model.Pipeline import Pipeline
from view.FeatureButton import FeatureButton
from view.ActivateMultipleDialog import ActivateMultipleDialog
from view.SetMultipleDialog import SetMultipleDialog
from features.BackgroundSubtraction import Bac... |
63ab2c76d902a837411c9f31088bcd1d6bf9d5a56a096698b9798a4c48b83918 | Python | 9,939 | 247 | """
Frame handling of the two dynamic features, DensityFlow and MarchingObservers.
Both kernels used to be launched once per frame in a host loop. They are now
launched once for the whole slice with ``blockIdx.y`` selecting the frame, which
moves three things into the kernel that the host used to get right by
construc... |
92305efa3608c915a61728a1c1e541059ecf7461bd036fbe033f583b3cb5572b | Python | 9,951 | 281 | """
This script computes and saves regression
results for layers of DNN models and neural areas.
It uses the TRF class to compute the regression
and saves the results in a CSV file.
It also allows for the option to save the
parameters of the regression model.
Args:
dataset_name: str ['ucsf', 'ucdavis'], -d
mod... |
4205680573c498ff9f58ddccd532382bd45599cf80168ac71fbbd340a5bf30bf | Python | 9,952 | 282 | # #############################
#
# Copyright (C) 2018
# Jennifer Dreiling (dreiling@gfz-potsdam.de)
#
#
# #############################
import os
import time
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing as mp
from multiprocessing import sharedctypes
import matplo... |
ac4644d3922b9e344a36530e66ea0b0cafebd0cf1b8a52cae7327a6c2e1fa157 | Python | 9,954 | 320 | import jax
import jax.numpy as jnp
import numpy as np
import numpy.testing as npt
import pathlib
import pytest
from ase.io import read
from jax_md import space, quantity
from mlff.mdx.potential import MLFFPotentialSparse
from so3lr import jaxmd_utils
lr_cutoff = 12.0
lr_cutoff_damp = 2.0
capacity_multiplier = 1.25
b... |
5a07e987b3237269eae4c9b591a3ba9aeaed9b2cc7c5e828e1ddf9ec0518dd05 | Python | 9,957 | 280 | import copy
import os.path as osp
import re
import warnings
from collections.abc import Sequence
from typing import Any, Callable, List, Optional, Tuple, Union
import numpy as np
import torch.utils.data
from torch import Tensor
from .data import Data
from .utils import makedirs
IndexType = Union[slice, Tensor, np.nd... |
5c1776d55b49a07e32b8af45aea784fc50c217f612a3555ca4b84f027f9bd8f9 | Python | 9,960 | 231 | """Unit tests for baseline-epoch control fitting (issue #200).
These tests exercise the estimate/apply split in the control fit and, crucially, the
interaction between baseline-epoch fitting and artifact-removal chunking: coefficients are
estimated once from the fit window intersected with the retained (non-artifact) ... |
a31167a32490b986c4f164c4a38969f61a4f0013f59b4bb2364e62bf3f20da85 | Python | 9,961 | 176 | # Copyright (c) OpenMMLab. All rights reserved.
from mmseg.registry import DATASETS
from .basesegdataset import BaseSegDataset
@DATASETS.register_module()
class MapillaryDataset_v1(BaseSegDataset):
"""Mapillary Vistas Dataset.
Dataset paper link:
http://ieeexplore.ieee.org/document/8237796/
v1.2 con... |
55b4d58d374f7ee97adbb58dc605c97810f565d207cbb388ea320405f9caff63 | Python | 9,968 | 278 | import json
import logging
import subprocess
import numpy as np
import pytest
import sklearn
from xgboost import testing as tm
pytestmark = [
pytest.mark.skipif(**tm.no_spark()),
tm.timeout(240),
]
from pyspark.ml.linalg import Vectors
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder
from pysp... |
8ac66732b489a38455e2597cabeb65b46065fc077b3ce087989ebfe20f60d3cd | Python | 9,973 | 323 | """StoppingCriteria class"""
"""
Copyright (c) 2016-2022, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt>
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 3.0 as published
by th... |
855bf37806cd095205a318d6b266551f18da715d85767e260772d8ab3cebebc2 | Python | 9,979 | 273 | import urllib
from collections.abc import Mapping, MutableMapping, MutableSequence
from typing import Any, NamedTuple, Union, cast
from cwl_utils.types import CWLObjectType
from ruamel.yaml.comments import CommentedMap, CommentedSeq
from .context import LoadingContext
from .load_tool import load_tool, make_tool
from ... |
1c6ccd9ad9a3824a9f7e2c1b60895076371d2abcb7d8fae12eca64e1f633bfc1 | Python | 9,981 | 289 | """
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 torch
from torch_geometric.nn import SchNet
from torch_scatter import scatter
from ocpmodels.common.registry import registry
from ocp... |
1edf9a5574168666ead97a9ef17f9ebbe7a9dbbf74828c3b0a475a7378d3eefa | Python | 9,982 | 177 | # Copyright (c) OpenMMLab. All rights reserved.
from mmseg.datasets.basesegdataset import BaseSegDataset
# from mmseg.registry import DATASETS
# @DATASETS.register_module()
class MapillaryDataset_v1(BaseSegDataset):
"""Mapillary Vistas Dataset.
Dataset paper link:
http://ieeexplore.ieee.org/document/823... |
7a00f136dc0ed7fd4ce8403f5a2f2b0fed82306f973df3293fed39126e3b8810 | Python | 9,983 | 295 | import torch
import itertools
import json
import hashlib
import os
from matplotlib.ticker import FormatStrFormatter, StrMethodFormatter
import umap
from matplotlib import pyplot as plt
import torch.nn as nn
import torch.optim as optim
import torch_geometric
import torch_scatter
import torch.multiprocessing as mp
from ... |
0e75d7cb7c6082349ceef0c89f7981145a415b5d2ba8452c2ba49324613fb656 | Python | 9,986 | 256 | import numpy as np
import time
import cv2
import sys
import os
import pickle
import torch
import torch.nn as nn
import SimpleITK as sitk
from torch import optim
from torch.utils.data import DataLoader, Subset, Dataset
from PIL import Image
import random
from albumentations import (
GridDistortion,
ElasticTransf... |
d59f825eb8ae0eee716c21ebcd2c3dd230be4c2aefdc8c392c92e4ef81f2e122 | Python | 9,989 | 341 | """Functions for creating synthetic data."""
import argparse
import os
from glob import glob
# import nibabel as nib
import brainbuilder.utils.ants_nibabel as nib
import numpy as np
import pandas as pd
from skimage.filters import threshold_otsu
def load(fn: str) -> tuple:
"""Load a NIfTI file."""
img = nib.l... |
03785581ca304d0451ae0df7a08ee0bf1e1dbe66fad285066e6b9ffc0d88d64f | Python | 10,003 | 317 | # 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.
import logging
from functools import partial
from typing import List, Tuple, Union
import torch
import torch.nn as nn
imp... |
583229115ac2c85a4e0a91c455ff9f78865f90067b519ee401fb8ff8179968b1 | Python | 10,012 | 304 | import torch
import logging
import numpy as np
class EnforceDiverseDCWeights:
""" Regulariser to enforce diverse DC weights for different
acceleration rates. """
def __init__(self):
super(EnforceDiverseDCWeights, self).__init__()
def __call__(self, model, device, min_acc=0.05, max_acc=0.5):
... |
5b317d504af8d64fc7900dca9b51e1b0e4c1727615cf3a5c2cb196fffb6ac5e5 | Python | 10,014 | 195 | # 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... |
0ced3785ce3526f63ebe5852f0753f2f56890dc82797f6d738123f5e9c9e4f2a | Python | 10,016 | 155 | #!/usr/bin/python
"""
This file to run ABC-DLS for classification between models
"""
import argparse
from Classes import ABC
from Classes import Misc
from _version import __version__
# input argument is done
parser = argparse.ArgumentParser(description='This file will run Model Selection.')
parser.add_argument('-v',... |
b0ae12e24493253f28c86331b28379e5eddd39a61290ad38bb1e8a5f06931ae1 | Python | 10,016 | 251 | # Provided by the FeTS Initiative (www.fets.ai) as part of the FeTS Challenge 2022
# Contributing Authors (alphabetical):
# Brandon Edwards (Intel), Patrick Foley (Intel), Micah Sheller (Intel)
import os
from copy import copy
from logging import getLogger
from pathlib import Path
import numpy as np
import SimpleITK ... |
1a64a995a99275409047337e88914586b1006e0efbda063838c393bf7baa45b3 | Python | 10,018 | 249 | from pathlib import Path
from typing import Optional
import torch
from torch.utils.data import DataLoader
from typer import Option
import os
import sys
from ..data.handlers.particle_image_preprocessor import \
ParticleImagePreprocessor
from ..models.blocks import LinearBlock
from ..models.decoder import InverseDi... |
fbf04df7db976eb38c1ace5e901cfddb6ecbf731c70453e20f46c34f9239c020 | Python | 10,018 | 181 | import panel as pn
import pytest
from guppy.frontend.store_labeling_config import NO_SIGNAL_OPTION, StoreLabelingConfig
@pytest.fixture
def show_config_button():
return pn.widgets.Button(name="Show Selected Configuration", width=600)
def build_config(show_config_button, store_ids, store_id_to_store_labels=None... |
b859d9a9f85eb1f8be8bd3b9aed6bceef3050df5c6cb00169195bc093efc9dff | Python | 10,020 | 292 | # -*- coding: utf-8 -*-
# encodermap/misc/clustering.py
################################################################################
# EncoderMap: A python library for dimensionality reduction.
#
# Copyright 2019-2024 University of Konstanz and the Authors
#
# Authors:
# Kevin Sawade
#
# Encodermap is free software... |
e7fd1ae102fc5cc18afb87c509a0fe26b5a366a0ffe625047b752b1434eb6c02 | Python | 10,020 | 284 | import numpy as np
import pandas as pd
import os
from anndata import AnnData
from scipy.stats import f
from scipy.sparse import csr_matrix
import scanpy as sc
import scanpy.external as sce
from scipy.stats import spearmanr
from schema import SchemaQP
from sklearn.feature_extraction.text import TfidfTransformer
def pre... |
47052c23b1a8ab964026d3b014c08b0fd52548f19f3b8028b6bd85bd76101dd9 | Python | 10,027 | 318 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 14:51:16 2024
@author: Andrei Istudor andrei.istudor@gmail.com
"""
import numpy as np
from sympy.codegen.ast import float16
from EthoCNN import EthoCNN#, getTensors
import torch
from sklearn.metrics import accuracy_score
from random import rand... |
7ac5f1c2f9377dc0015fba377750bb4747103c3ab19c5dfc8ebe0f9b92959117 | Python | 10,029 | 264 | # Viewer for verifying blobs
"""Blob verifier viewer GUI."""
import dataclasses
from typing import Optional, Dict, Sequence, Any, Callable
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import figure
from matplotlib import gridspec
from matplotlib.widgets import Button, Slider, TextBox
from... |
bb3aa3a7f567adf6a2d2cf638c63db1bb34c3cfc2eaa588c9ba04a2085424697 | Python | 10,034 | 283 | import torch
from torch.utils.data import DataLoader
import numpy as np
from ..models.constants import ConsensusInitializationMode, RegularizationMode
from ..models.encoder import HetEncoder
from ..models.decoder import DisplacementDecoder
from ..data.handlers.particle_image_preprocessor import ParticleImagePreprocess... |
07d82179a49c738aa32a25ae6103671f8f9a46cb6bf89223c71271efe868f03e | Python | 10,038 | 283 | """Tests for provider-aware frame dispatch in GET /v1/rooms/{room_id}/frames/{index}."""
import asyncio
import msgpack
import pytest
from helpers import (
InMemoryResultBackend,
auth_header,
create_test_room,
create_test_user_in_db,
decode_msgpack_response,
make_raw_frame,
)
from httpx import ... |
84eda96f202c83ff6365b213ebb993d932daffffa24fa84b9e5192f597ae2345 | Python | 10,039 | 261 | import os
import random
import tempfile
import subprocess
import numpy as np
import pandas as pd
import scipy.sparse as sp
import sklearn
from sklearn.neighbors import kneighbors_graph
import torch
import scanpy as sc
def get_pathway_activity_with_r(adata, gmt_file, path, r_script="GSVA_scores.R", threads=80):
if... |
60fa3dd1d6f51945ce367dc90b1dfa97be8d2d4c63560358edd3a98c191ec568 | Python | 10,041 | 201 | #!/usr/bin/env python2.7
import os
import argparse
import shlex, shutil
import multiprocessing as mp
from multiprocessing import Lock, Value, Pool
from collections import defaultdict
from collections import Counter
import numpy as np
import chisel
src = os.path.dirname(chisel.__file__)
from ..Utils import *
from .... |
b0f866db691fe7ac00debafb99ff23fa85b4bb57922b44d186f955fed65ef9d2 | Python | 10,041 | 288 | import math
from typing import Optional
import numpy as np
import torch
import torch.utils.data
from torch.utils.data import DataLoader
import pytorch_lightning as pl
from datasets.utils.pad_tensors import PadTensors
from datasets.utils.transforms import TakeEventByTime, AddNoiseByproportion, Flatten
from datasets.uti... |
624bf4091455534ae9e18617ba10503fe7523bc02658f31667e58e510a20f2cb | Python | 10,044 | 214 | # Provided by the FeTS Initiative (www.fets.ai) as part of the FeTS Challenge 2022
# Contributing Authors (alphabetical):
# Brandon Edwards (Intel)
# Patrick Foley (Intel)
# Micah Sheller (Intel)
import os
import numpy as np
import pandas as pd
from fets.data.base_utils import get_appropriate_file_paths_from_subjec... |
3b1174940bcbf63b9553f431f62b3f70da3b0600ecf773b5aa29e2215b9d1c00 | Python | 10,047 | 322 | """
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.
"""
# Copyright (c) Facebook, Inc. and its affiliates.
# Borrowed from https://github.com/facebookresearch/pythia/blob/master/pythia/common/regis... |
dbe4e43e606cd51c5644f5abde42ccf4afcdc8414e22253ebf28e930c169510e | Python | 10,050 | 359 | # pylint: disable=too-many-locals, too-many-arguments, invalid-name,
# pylint: disable=too-many-branches
"""Plotting Library."""
import json
import warnings
from io import BytesIO
from typing import Any, Optional, Union
import numpy as np
from ._typing import PathLike
from .core import Booster, _deprecate_positional_... |
7b21c67c494365525ed0f65f81a983dacfde25f9dd1345e86f06ec03fcfc9022 | Python | 10,062 | 229 | """Unit tests for the source-impact detail files (CSV/JSON/TSV).
Drives the real ``src.tools.source_impact_report.cli.main`` over a synthetic intermediate root
(offline, so ``unit``-marked) and asserts the six detail files written into the report's
``<output-stem>/`` subdirectory are correct, complete, and determinist... |
7cd51dcaf8c004d09a1283059944790285c81d77327ca91e1562ffab90357be9 | Python | 10,064 | 243 | """Integration tests for AnnotationEngine using the sample database."""
import logging
import os
import pytest
from .conftest import TP53_PROTEIN_ID, NIFH_PROTEIN_ID
# Expected result keys from annotate_batch (v3 refactor)
# - annotations_confidence: Phase 3B (per-source cascade)
# - tax_ceiling: resolv... |
3ddc5a48a574b29c25cd038976351af9c6f5411bb6ddcf7e541ac6552a2709db | Python | 10,065 | 220 | import logging
import pyoxigraph
from src.babel_utils import parse_rdf_literal, pull_via_urllib
from src.metadata.provenance import write_concord_metadata
from src.prefixes import EFO, ORPHANET
from src.util import LoggingUtil, Text
logger = LoggingUtil.init_logging(__name__, level=logging.WARNING)
def pull_efo():... |
110ca181643798e91c5a36e34d68c907fe891f93fa4da5881e0e311db2202b52 | Python | 10,071 | 267 | import atexit
import cProfile
import inspect
import io
import logging
import pstats
import time
import tracemalloc
from argparse import Action
from pathlib import Path
GLOBAL_TIMER = None
TIME_PROFILER = None
MEMORY_TRACER = None
# == Time-based Profiling == #
class Timer:
"""
Wrapper class which manages o... |
95343953162cb0033613a1abf9a1c4b7bc640509749ac0d3d42529875b7608a9 | Python | 10,073 | 242 | #!/usr/bin/env python
"""
save_seperate_run_WASABI.py
adjustments for WASABI
Separates acq into runs and saves as bids format.
This script reads the acquisition file collected straight from our biopac PC
Parameters
------------------
operating: str
options: 'local' vs. 'discovery'
task: str
options: 'task-soci... |
b3b6a9ab5ba756adcc6bb98d483ccfedcd4d155d0203643d733830a2ebd23aae | Python | 10,073 | 265 | import imp
import json
import time
from pathlib import Path
import torch
import torch.utils.data as data
import numpy as np
import pandas as pd
from .loader import HeartVolumeLoader
def get_class_labels(data):
class_labels_map = {}
index = 0
for class_label in data['labels']:
class_labels_map[c... |
70c375c35e07b67885a6340089a48c8c808bae0d8bbdb6cbea0872c2e71cc2b7 | Python | 10,086 | 284 | """
API for functions used in the sct_deepseg_gm CLI script
Reference paper:
Perone, C. S., Calabrese, E., & Cohen-Adad, J. (2017).
Spinal cord gray matter segmentation using deep dilated convolutions.
URL: https://doi.org/10.48550/arXiv.1710.01269
Copyright (c) 2022 Polytechnique Montreal <www.neuro.poly... |
2babca86c5b6fb023262223e77618964f985b846209fc9cb19e14361a4722f07 | Python | 10,092 | 204 | # split runs with "trigger event" e.g. binarize the values and identify start stop indices
# ttl onsets
# convert each event into trial number
# do this based on two events: expect and actual
# TODO:
# * identify BIDS scheme for physio data
# * flag files without ANISO
# * flag files with less than 5 runs
# ** for ... |
c50dee070912986e715ad6bfde2c4ca10efcf9a099987322d24f57b8f0221679 | Python | 10,097 | 257 | """
MetaWIBELE Workflow: prioritization module
A collection of tasks for workflows with prioritization
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 So... |
83c0ab0e7264f31c0d162f44437dd0cfa90897c8f7f0a79df5fe7b9d55ac1b88 | Python | 10,098 | 269 | ##################################################################
# Test TrimNN-RGIN in identifying occurrences of CC motifs in diverse simulated data sets
# Reproducibility for Figure.2F
##################################################################
import torch
import os
import numpy as np
import dgl
i... |
80da3eea476b924cf3cc9d7a3b8b6df1e92f6977a130df890b56c1fc43054382 | Python | 10,099 | 279 | from .env import Env, Env_r
from anndata import AnnData
import numpy as np
import torch
import tqdm
from typing import Optional, Self
import time
import psutil
class BaseAgent:
def __init__(self, *args, **kwargs):
# This __init__ will be called by agent and agent_r, which will then call their respective En... |
a0224ebda37ee3c8b430a6fb4f724762c5292bfafdddf5b85807b457de9ce3be | Python | 10,101 | 269 | ##################################################################
# Test TrimNN in identifying occurrences of CC motifs in diverse simulated data sets
# Reproducibility for Figure.2F
##################################################################
import torch
import os
import numpy as np
import dgl
import... |
69db9fc5d042f828302cd5cf0916c1f450c87c964559fa93db7ce716dd1e2de1 | Python | 10,107 | 200 | import numpy as np
from collections import deque
def build_gt2pred_ordered_mapping(gt_coords, cone_prob, pred_coords, dis_threshold):
# O(n*m*log(m)), n: number of gt_coords, m: number of preds_lmax
gt2pred_ordered_map = {}
for gt_idx, gt_coord in enumerate(gt_coords):
available_preds = []
... |
49b51177db4c910d22439be379114a42dc64f9459741d25a33f6e7bc606cd0fe | Python | 10,114 | 310 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 17:06:38 2024
@author: mbmad
"""
from typing import TypeAlias, Union, Tuple, List
import numpy as np
Span: TypeAlias = Tuple[int, int]
SpanList: TypeAlias = List[Span]
class TimeSpan:
# Base factors are in us units
_defaultunits = {'us': 1, 'ms': 1000, 's':... |
674daf96004df18cd7f5943b7ced95d05a7bfd64259562f61751f58310d0cb18 | Python | 10,118 | 263 | """
The code is adapted from: https://github.com/bayesiains/nsf
License:
MIT License
Copyright (c) 2019 Conor Durkan, Artur Bekasov, Iain Murray, George Papamakarios
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.