sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
ee339026eac34ab2ad2466db7fcf6dd782e8d0b12d1371eec494b50128212dea | Python | 2,408 | 86 | import math
from rdkit import Chem
from utils.chemistry_parse import canonical_smiles
def _canonicalize_prediction(smi):
mol = Chem.MolFromSmiles(smi)
if mol is None:
return None
return canonical_smiles(Chem.MolToSmiles(mol))
def _sort_scores(score_map):
ranked = sorted(score_map.items(), ... |
2c11ffc35517b0ad3c738ed6a3734d6d3af6a15b449a9029cc59cca9a53a9ab9 | Python | 2,410 | 62 | import argparse
import pandas as pd
import os
def get_parser():
"""
Function to parse command line arguments.
:return: command line arguments
"""
parser = argparse.ArgumentParser(description='Generate a Bland-Altman and correlation plot in one figure.')
parser.add_argument('-i', required=True, ... |
3909c150bd5a3faee88272dbdc3c89c459f4cce295142ca0c1bdf02c631362b2 | Python | 2,410 | 62 | import pathlib
path = pathlib.Path.cwd()
if path.stem == 'tmb_survival':
cwd = path
else:
cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')]
import sys
sys.path.append(str(cwd))
import numpy as np
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
import pandas as pd
i... |
998d3b9d3fc11ef56c92de53292b38625edf1a86917ab46080786387b557f18d | Python | 2,410 | 78 | from typing import Optional, Callable, Union
import numpy as np
from numpy.typing import ArrayLike
import jax
import jax.numpy as jnp
from quspin.tools import misc
from ..global_defs import get_sites, get_lattice, get_subkeys
def ints_to_array(basis_ints: ArrayLike, N: Optional[int] = None) -> np.ndarray:
"""Conv... |
b30f62db179c7a26ef3518a7dfcd2e260a96c62a1a1ec1ddd13723cfad0c6860 | Python | 2,411 | 61 | import torch
from matplotlib import pyplot as plt
from .fourier import fft_3d
def plot_tomo_slices(tomo, domain="image", figsize=(7, 5)):
# docstring
"""
Plot central slices of a 3D tomogram in either image or Fourier domain.
"""
fig, ax = plt.subplots(1, 3, figsize=figsize)
# plot in image d... |
d9ac25386fead66f49f09075fc18b9f3e6762eb0a0a0654331dd0a5f8e1659b6 | Python | 2,411 | 54 | import sklearn as sk
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.metrics import precision_recall_curve, average_precision_score
from sklearn.metrics import precision_rec... |
994e371f858a3ae46b3e9494e7c1df6a94bb36fd764403ff851c012362421b5b | Python | 2,412 | 62 | import torch
from agent.classifiers.utils.models_cache_mgmt import get_tokenizer
def get_special_tokens(pretrained_model):
if pretrained_model in ["bert-base-cased", "bert-base-uncased", "bert-large-cased", "bert-large-uncased",
"emilyalsentzer/Bio_ClinicalBERT", "dmis-lab/biobert-v1.... |
a2c800663ff83f430087499bb700cd1583a4474d8f818100dba4e292510db13e | Python | 2,412 | 68 | import numpy as np
from lib.data_utils.sta_metadata import compute_sig_stixel_mask
from dataclasses import dataclass
from collections import namedtuple
from lib.dataset_config_parser.dataset_config_parser import LookupKey
@dataclass
class MaskHyperparameters:
threshold: float
n_coverage: int
use_cc_al... |
ea89f5cfa268e956c7c13839577ca9ac4c09c2415474d2c9c5fd60a831b1fcab | Python | 2,412 | 64 | # Ultralytics YOLO 🚀, GPL-3.0 license
import os
import re
import shutil
import socket
import sys
import tempfile
from pathlib import Path
from . import USER_CONFIG_DIR
from .torch_utils import TORCH_1_9
def find_free_network_port() -> int:
"""Finds a free port on localhost.
It is useful in single-node tra... |
7867011ee34cb6bb7186f4faf3d0ba389b8433a19031bdc31b3bf9a9ea130ca4 | Python | 2,413 | 60 | """Plot lead II of a synthetic 12-lead ECG before and after representative augmentations.
Usage: python examples/plot_augmentations.py [output.png]
"""
import sys
import matplotlib.pyplot as plt
import torch
import ecg_augmentations as ea
FS = 500
ORIGINAL, AUGMENTED, INK, SURFACE = "#b4b3ad", "#2a78d6", "#3d3d3a",... |
7c5733bb7443df23fa017a1629c7de47a8810ea912ba332e853dad3f09ce8e19 | Python | 2,413 | 82 | # -*- coding: utf-8 -*-
"""
"""
import numpy as np
import os, sys
import pytest
import vtkplotlib as vpl
pytestmark = pytest.mark.order(9)
def test_legend():
import vtkplotlib as vpl
self = vpl.legend(None, fig=None)
assert self.fig is None
assert self.length == 0
vpl.gcf().... |
c6a4acc5c96277afb730aa97a71206dbc431174105711a06276b39c553b0f8ba | Python | 2,415 | 82 | import socket
import os
import sys
if socket.gethostname() == 'kelarion':
CODE_DIR = '/home/kelarion/github/'
SAVE_DIR = '/mnt/c/Users/mmall/Documents/uni/columbia/assignment_errors/'
LOAD_DIR = '/mnt/c/Users/mmall/Documents/uni/columbia/assignment_errors/server_cache/'
repler_DIR = 'repler/src'
else: ... |
f3f670e1533ab7c23be027c02481e2794d3b9a1500e185ea29ac48c4f5a697cc | Python | 2,417 | 85 | #import pandas as pd
import numpy as np
from functools import partial
from multiprocessing import Pool
def gen_row(ndarray):
r"""Generate rows from numpy array.
Arguments:
ndarray: Numpy array to iterate through
Yields:
Row vectors from the input array
"""
for i in ra... |
8b807d9ed340ab4dadf737289a5e97f209b287ad1e80f72f8acdd964cbcb7ef5 | Python | 2,419 | 70 | from abc import ABC
from typing import TYPE_CHECKING, Optional
from ray.data.context import DataContext
if TYPE_CHECKING:
from ray.data._internal.execution.interfaces.physical_operator import (
PhysicalOperator,
)
from ray.data._internal.execution.resource_manager import ResourceManager
from r... |
f1a45a2378215587d20d1ddb1005113267b7b5f5dc016b089f90b5cd956e75aa | Python | 2,419 | 70 | # Copyright 2023 Google LLC
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
0cd2e167fbd14a9f9700acc525dc5ba89bc45f0287952837901d35da0c63e6b9 | Python | 2,420 | 87 | # flake8: noqa
import ray
ray.init(
_system_config={
"memory_usage_threshold": 0.4,
},
)
# fmt: off
# __last_task_start__
import ray
@ray.remote(max_retries=0)
def leaks_memory():
chunks = []
bits_to_allocate = 8 * 100 * 1024 * 1024 # ~100 MiB
while True:
chunks.append([0] * bits_... |
6ee537a848c16a96a8ae665ebcc22229bcc6bc83f3ff7db806f6bf8a04dc2a47 | Python | 2,420 | 87 | from scipy.io import loadmat
from scipy.special import erfcinv
import numpy as np
import pandas as pd
from scipy.stats import kruskal
from itertools import combinations
from matplotlib import pyplot as plt
def star(p_val):
assert 0 <= p_val <= 1
if p_val >= 0.05:
return 'ns'
if p_val >= 0.01:
... |
726c14d151a0feb83cf8e5526b0e390b99cea9b1621eb6f63a3ac3f824ab8da3 | Python | 2,420 | 77 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#... |
90e97819542ae78f57c58311ba1a70eb6d99b0abf71235133c6a016dc13eeccf | Python | 2,420 | 71 | from tqdm import tqdm
import numpy as np
from rdkit import Chem
from rdkit.Chem import Descriptors
from rdkit.Chem.SaltRemover import SaltRemover
ORGANIC_ATOM_SET = set([1,5,6,7,8,9,15,16,17,35,53])
GOOD_N_ATOM_MAX = 50
GOOD_N_ATOM_MIN = 3
REMOVER = Chem.SaltRemover.SaltRemover()
def preprocess_smiles(smiles_list):
... |
c18731a7005f87a53ea8d436065029d56f77f227b8f3aae085f370397b4e40f9 | Python | 2,421 | 63 | SCHEMA_VERSION = "0.1"
# The key to store / obtain cluster metadata.
CLUSTER_METADATA_KEY = b"CLUSTER_METADATA"
# The name of a json file where usage stats will be written.
USAGE_STATS_FILE = "usage_stats.json"
USAGE_STATS_ENABLED_ENV_VAR = "RAY_USAGE_STATS_ENABLED"
USAGE_STATS_SOURCE_ENV_VAR = "RAY_USAGE_STATS_SOU... |
ffcbc18a480d08dadcbee9634ae0267ded130557507430c710ec820615c5455e | Python | 2,421 | 54 | #!/usr/local/bin/ipython -i
from mozaik.experiments import *
from mozaik.experiments.vision import *
from mozaik.sheets.population_selector import RCRandomPercentage
from parameters import ParameterSet
def create_experiments(model):
return [
# Spontaneous Activity
NoStimulation(model, ParameterSet... |
239e853189a28d701845d9807a5852a61b230b1289b2cfad03dbd268b7f0434e | Python | 2,422 | 70 | import numpy as np
import tifffile
import h5py
import os
import scipy.io as sio
import cv2
median_area_target = 377
list_name_video = ['blood_vessel_10Hz','PFC4_15Hz','bma22_epm','CaMKII_120_TMT Exposure_5fps']
list_median_area = [61, 108, 170, 613]
ID_part = ['_part11', '_part12', '_part21', '_part22']
for (nid, nam... |
db011966dabb243183e68df25b706e0637e831b8e2941062978a91ffa08feb32 | Python | 2,422 | 85 | _base_ = [
'../_base_/datasets/rtts_coco.py', '../_base_/schedules/schedule_1x.py',
'../_base_/default_runtime.py'
]
# model settings
model = dict(
type='ATSS',
data_preprocessor=dict(
type='DetDataPreprocessor',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
... |
3cfd009074587edbb9e6597232c38988be3dce9ecf8052e2ace3b8840e7f8eb6 | Python | 2,423 | 90 | import torch
import torch.nn as nn
class CRPNN(nn.Module):
'''
NN with 1 RELU hidden layer, and CRP sends c_k to the hidden layer,
where c_k is the vector representation of the k-th context/task
'''
def __init__(self, dim_input, dim_hidden, dim_output, dim_context):
super(CRPNN, self).__... |
53e8bac2a5679eec777a8732e0cbb52bb969b3e339564d9baee1152202c4cb26 | Python | 2,425 | 65 | #!/usr/bin/env python
# Convert each directory in the root directory to a tgz file
from pathlib import Path
import shutil
import sys
import os
import tarfile
import os.path
import ctypes
import csv
from datetime import datetime
import glob
import shutil
if __name__ == "__main__":
"""Remove facial features from M... |
4739c32603a759bd501989952b28ec011224746e5a2737f8945aea6109816c75 | Python | 2,427 | 96 | """
Helpers for distributed training.
"""
import io
import os
import socket
import torch as th
import torch.distributed as dist
# Change this to reflect your cluster layout.
# The GPU for a given rank is (rank % GPUS_PER_NODE).
GPUS_PER_NODE = 8
SETUP_RETRY_COUNT = 3
def setup_dist():
"""
Setup a distri... |
94d8e248d9b7667077fa9c0c984b529c980c92b6a58477e8013efe93fdc05113 | Python | 2,427 | 75 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""aihwkit example 12: simple network with one layer using Mixed Precision learning rule.
Mixed precision is based on the paper Nandakumar et al (2020) (see
htt... |
c592d4f975144caeb81fa629a0a64b5649b062fad88600efa454f07bcd2190fa | Python | 2,428 | 81 | import logging
import yaml
import json
import sys
import os
logger = logging.getLogger('telemanom')
sys.path.append('../telemanom')
class Config:
"""Loads parameters from config.yaml into global object
"""
def __init__(self, path_to_config):
self.path_to_config = path_to_config
if os.... |
e4d7080ddde647f2c0a471032bacc7e4906a046ae39c7da6cc3da2308a8b400f | Python | 2,428 | 64 | '''
Created on May 6, 2016
@author: jivan
'''
from HTMLParser import HTMLParser, HTMLParseError
class HTMLTableStripper(HTMLParser):
''' | *brief*: Collects values from html tables.
| *author*: Jivan
| *created*: 2016-01-22
This class parses HTML and provides the content of any tables as ... |
c3d599787a14face95812792f1189d0b554843085e2826f924dc659d3aba7415 | Python | 2,429 | 69 | """Pure row-group coalescing for the footer-based Parquet chunking path."""
from dataclasses import replace
from typing import List, Optional, Tuple
from ray.data._internal.datasource_v2.interfaces.file_manifest import FileChunk
__all__ = [
"coalesce_row_groups",
]
def coalesce_row_groups(per_rg: List[FileChunk... |
dd3f66393a45469923ca16c726b4afd5cb6a7ceaa31af0c286dd1c3359d0a452 | Python | 2,430 | 70 | #!/usr/bin/env python
from setuptools import setup, Extension
from distutils import sysconfig
from pathlib import Path
import subprocess
import glob
import sys
srcs = [x for x in
glob.glob("libBigWig/*.c")]
srcs.append("pyBigWig.c")
libs=["m", "z"]
# do not link to python on mac, see https://github.com/deeptool... |
2a851f7058bbbcca7f16e543e98ca780b7516b227b9b3fb1fa9d5b4043e90504 | Python | 2,431 | 89 | import pickle
import multiprocessing
import sys
import numpy as np
sys.path.append('../model/')
from model import RBCM, compute_p_change
########## Parameters ##########
# Possible states
states = {'S1': np.array([1, 0]), 'S2': np.array([0, 1])}
# Valence signals
R_negative = -1.
R_positive = 1.5
Rs = {'phase_1':... |
5cc39003e9ea99d9508654a0f2c68de6c58e48a351191ef6d186deafd633b72d | Python | 2,431 | 56 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_roi_data():
from samri.report.utilities import roi_data
means, medians = roi_data('/usr/share/samri_bidsdata/preprocessing/sub-{subject}/ses-ofM/func/sub-{subject}_ses-ofM_task-JogB_acq-EPIlowcov_run-1_cbv.nii.gz',
'/usr/share/mouse-brain-templates/dsurqec_20... |
430d57d2952a84dfd9758dd99d361110330786d326d989f295ca52d6f74475ed | Python | 2,432 | 48 | from pathlib import Path
import torch
from candycrunch.model import CandyCrunch_CNN, CandyCrunch_CNN2
def load_checkpoint(model_path, device=None, temperature=1.15):
"""Return keyword arguments for prediction.wrap_inference or wrap_inference_batch.
model_path accepts a string or Path pointing to a training c... |
ae286387c6db6a026eba0fad95bcf7a4e07f9834969fce7057f6b267c2c61321 | Python | 2,432 | 74 |
import argparse
from matplotlib import cm, pyplot
import numpy
import tifffile
from pysted import base, utils
parser = argparse.ArgumentParser(description="""Simulate the acquisition of an
image serie with bleaching.""")
parser.add_argument("pixelsize", type=float,
... |
04a2e1922bcd5dac976aec4b5aa1aa51af82340bd4f068d66e355783b67c1c51 | Python | 2,433 | 63 | import argparse
import pickle
import numpy as np
from collections import defaultdict
def parse_argument():
parser = argparse.ArgumentParser()
parser.add_argument('--freq-matrices', nargs='+', required=True)
parser.add_argument('--tss2fragment', required=True)
parser.add_argument('-c', '--chromosomes',... |
2581b8ac3651128ce7d275ad005843e76fa3be9a8cca9b5815f06b77e9b04ebd | Python | 2,433 | 81 | """Monoexponential decay (T2star) fitting."""
import os
import nibabel as nb
import numpy as np
# from scipy.linalg import lstsq
import glob
# =============================================================================
DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti'
# Set subs to work on
S... |
5dff25ecf905288b914d246aef928601a738b6adc7df9f3205a2eabbbaa2583a | Python | 2,434 | 62 | ####################################################################################################
# Copyright (c) 2016 - 2024, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis>
#
# This program is fre... |
1a8465c8a868681ffd116a0b997205e66e8326a4545e032c969a2976cf57a684 | Python | 2,435 | 53 | #Imports relevant modules.
import os
import csv
#Defines the path of the FDR directory.
FDR_dir = '\\<directory root>\\JASP\\FDR'
#Defines paths for the input and output folders we'll need.
Input_dir = os.path.join(FDR_dir, 'Input')
Corrected_dir = os.path.join(FDR_dir, 'Corrected')
#Iterates over the inp... |
3dd337137adf5cc719fbd0a391397cd061825751ec7a25787a851d8296f0e19a | Python | 2,435 | 34 | import os,sys,json,tempfile
from pathlib import Path
summary_path=Path(sys.argv[3]).resolve()
root=Path(sys.argv[1]).resolve();out=Path(sys.argv[2]).resolve();out.mkdir(parents=True,exist_ok=True)
os.environ.setdefault('TF_CPP_MIN_LOG_LEVEL','2');os.environ.setdefault('TF_ENABLE_ONEDNN_OPTS','0')
import tensorflow as t... |
6a4965b89cfbdd0a5b89674691e2cdec78a108b3600905292a3a158894d47277 | Python | 2,435 | 108 | #!/usr/bin/env python
'''
Brian2 example for lif_curr_exp
'''
from brian2 import *
import numpy as np
defaultclock.dt = 1*ms
dt = defaultclock.dt
print(dt)
n_in = 1 # number of stimuli
n_out = 1 # number of output neurons
duration = 0.1*second
alpha_decay = 0.9
exc_decay = 0.3
inh_decay = 0.4
#############
# Equa... |
ac438c18ed544dde53a8c01921fd64a1b4a5610d24d909687840da0b8905da82 | Python | 2,435 | 58 | import logging
from logging import Logger
import optuna
import transformers
def get_custom_logger(name: str, level: int=logging.DEBUG) -> Logger:
"""
Get project specific custom logger.
Example usage:
import logging
logger = get_custom_logger(__name__, level=logging.INFO)
Args:
name (str): Na... |
c53976d65af869cc752393ef44c617d1259ba8aee639398f8ff8b5c6b3f48181 | Python | 2,435 | 69 | # Copyright 2026 Google LLC.
#
# 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 applicable law or agreed to in writing, ... |
fb1256cf2a0e0ce730ebcb50574745cd7b49c59b0adb6e097894ac2d22c7f4f8 | Python | 2,435 | 100 | # This file is part of the INTREPPPID programme.
# Copyright (c) 2023 Joseph Szymborski.
#
# This programme is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3.
#
# This programme is distributed i... |
8bd3d271c287b8537c01a1a9ac7a8ee204c06fd0be2da72b0a3d8b6efb723eda | Python | 2,436 | 65 | from numpy.random import seed
seed(1)
import tensorflow as tf
tf.random.set_seed = 1
import random
random.seed(1)
import numpy as np
np.random.seed(1)
import pandas as pd
import tensorflow as tf
import SimpleITK as sitk
from tensorflow.keras.utils import to_categorical
import sys
class DataGenerator(tf.k... |
03a29ece3b676afc810470ec643eaf300e179c7871766b06d4eb34cab4aa8bed | Python | 2,437 | 77 | import numpy as np
import argparse
import functions as fct
# Parameter dictionary
param = {
# Integration
"total_t" : 405.,
"dt" : 0.1,
# Initial conditions
"init_phi_A" : 0.,
"init_phi_B" : 0.,
# Frequencies
"omega_A" : 0.0457,
"omega_B" : 0.0457,
# Cou... |
ac35cc5f4b41d71e7c4b3dea48bc7bed382094a062caee3d34d41754ab0e019b | Python | 2,437 | 91 | # flake8: noqa
# __nixl_full_example_start__
import torch
import ray
@ray.remote(num_gpus=1)
class MyActor:
@ray.method(tensor_transport="nixl")
def random_tensor(self):
return torch.randn(1000, 1000).cuda()
def sum(self, tensor: torch.Tensor):
return torch.sum(tensor)
def produce(s... |
313e6bdb2b31edeb96840e205f661fe4b0cc2ad164c03fcae236f26803969cd7 | Python | 2,438 | 73 | import torch
from pfrl.agents import pal
from pfrl.utils.recurrent import pack_and_forward
class DoublePAL(pal.PAL):
def _compute_y_and_t(self, exp_batch):
batch_state = exp_batch["state"]
batch_size = len(exp_batch["reward"])
if self.recurrent:
qout, _ = pack_and_forward(
... |
48df67604b4ed893bccb98b22794c27186cd59050c1c3d75ede0d21a7a9e3fce | Python | 2,439 | 78 | """Workflow-aware runtime helpers for OVAgent."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Optional
from .run_store import AnalysisRun, RunStore
from .workflow import WorkflowDocument, load_workflow_document, resolve_repo_root
class OmicVerseRuntime:
"""Minimal workfl... |
f4e71caffea2723219859e6f089f8822f6877c549ddbf1ea5d2140bf06de13c6 | Python | 2,439 | 74 | _base_ = 'ssd300_120e_ruod.py'
# model settings
input_size = 512
model = dict(
neck=dict(
out_channels=(512, 1024, 512, 256, 256, 256, 256),
level_strides=(2, 2, 2, 2, 1),
level_paddings=(1, 1, 1, 1, 1),
last_kernel_size=4),
bbox_head=dict(
in_channels=(512, 1024, 512, 2... |
bce6b849364cff012e42f4835f7f17f0c01b08aa7c7a8d3bc9945c43d51b7766 | Python | 2,440 | 79 | import glob
import logging
import os
from typing import Dict, List, Optional, Tuple
from ray._private.accelerators.accelerator import AcceleratorManager
from ray._private.ray_constants import env_bool
logger = logging.getLogger(__name__)
TENSTORRENT_VISIBLE_DEVICES_ENV_VAR = "TT_VISIBLE_DEVICES"
NOSET_TENSTORRENT_VI... |
fbf4c6153698f51e59e4a3abdbcca36a8de0ae7dd20c65ffc05c2b930cfc804a | Python | 2,440 | 78 |
from urllib import request
import gzip
from lisa.core.data_interface import DataInterface
from lisa.core.genome_tools import Region, BadRegionError
from lisa.core.utils import Log, LoadingBar
import argparse
from scipy import sparse
import os
from scipy.stats import gamma
import numpy as np
from sys import stdout, std... |
a597dc484e3ac903a9f3b0f73ed0a31673395e033c1e54fa01d7fde9af62174b | Python | 2,441 | 67 | # Copyright 2023 The HuggingFace 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.0
#
# Unless required by applicabl... |
d6b8100ee27892081079ef11c68f76000e4cf11b377928fd22e6a40918724fd2 | Python | 2,441 | 62 | import numpy as np
import pytest
from deepface.modules.detection import extract_faces, DetectedFace, FacialAreaRegion, is_valid_landmark
from deepface.commons.logger import Logger
logger = Logger()
def sanitize_landmarks(region, width, height):
landmarks = {
"left_eye": region.left_eye,
"right_eye... |
9a836a6e2e227e37457a53756f460a9d9e3cbea9936896a5ae0207fc642d6495 | Python | 2,443 | 86 | import pandas as pd
import pytest
from data_profiling.config import Settings
from data_profiling.model.pandas.correlations_pandas import (
pearson_compute as pandas_pearson_compute,
)
from data_profiling.model.pandas.correlations_pandas import (
spearman_compute as pandas_spearman_compute,
)
from data_profilin... |
694e6b243dc3c286a286fbe5dada3b0bd3505760db5d5949e8033a21968a252b | Python | 2,444 | 57 | """Keep MyST ``{eval-rst}`` blocks from pickling the build environment into doctrees.
MyST parses an ``{eval-rst}`` block into a throwaway docutils document that shares
the page's ``settings`` object, then moves the parsed nodes into the page with
``extend()`` (``myst_parser.mdit_to_docutils.base.render_restructuredte... |
9d36ad009df8f0b91f7839967b0073782b720409dd8d6acb9ba3eac8ba7df397 | Python | 2,444 | 61 | # Copyright (c) 2017-present, Facebook, Inc.
#
# 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 applicable law or agreed... |
a562a9b97cbf29bc537ad8f07b6a7c5184da70747ba9e96f5f91ca95f434238e | Python | 2,444 | 68 | import sys
import json
import pickle
import argparse
from lop.utils.miscellaneous import *
from lop.utils.plot_online_performance import generate_online_performance_plot
def add_cfg_performance(cfg='', setting_idx=0, m=2*10*1000, num_runs=30):
with open(cfg, 'r') as f:
params = json.load(f)
list_param... |
19496efcb753d068a780f5772ec667e22db04981edee9a7b8b6820c6b83bf945 | Python | 2,445 | 71 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 02 17:02:00 2020
@author: ju-bar
Routines for powder diffraction data analysis.
This code is part of the 'emilys' repository
https://github.com/ju-bar/emilys
published under the GNU General Publishing License, version 3
"""
# %%
#from numba import jit # include compilat... |
460a0223ae05135f79de1e0de1b6a72f49929b82e1347670297a3a240a72136b | Python | 2,445 | 74 | _base_ = 'ssd300_120e_duo-coco.py'
# model settings
input_size = 512
model = dict(
neck=dict(
out_channels=(512, 1024, 512, 256, 256, 256, 256),
level_strides=(2, 2, 2, 2, 1),
level_paddings=(1, 1, 1, 1, 1),
last_kernel_size=4),
bbox_head=dict(
in_channels=(512, 1024, 51... |
88fddd649e6f515a78e213717617941cd2184a54525ee693f47916d12e5b44ec | Python | 2,445 | 62 | import pytest
from conftest_graph_extractor import args_GraphExtractor
from sinabs.backend.dynapcnn.nir_graph_extractor import GraphExtractor
def fix_node_ids(expected_output, graph_extractor):
"""Match node IDs between graph extractor and expected output.
Node IDs can be assigned in many ways. This functio... |
c679f1803202f3f8962f134e8c6cf791f1601f89f34356170dcaf11cec7b735d | Python | 2,445 | 73 | import os
import xml.etree.ElementTree as ET
import gym
from gym.utils import EzPickle
from gym.envs.mujoco.ant import AntEnv
from gym.envs.mujoco.ant_v3 import AntEnv as AntEnv3
from gym.envs.mujoco.mujoco_env import MujocoEnv
class SlipperyAntEnv(AntEnv, MujocoEnv, EzPickle):
"""
SlipperyAnt-v2
"""
... |
28657874ae826a7b2e737c33a6754d4ec08099addce9bc098d3640f1ff494569 | Python | 2,446 | 101 | import torch
import torch.nn as nn
import sinabs
import sinabs.layers as sl
import sinabs.utils as utils
class SNN(nn.Module):
def __init__(self, hidden_dim=10):
super().__init__()
self.net = nn.Sequential(
nn.Linear(2, hidden_dim),
sl.IAF(),
nn.Linear(hidden_d... |
9b8e01adf2741be20fa63b8bb5327f5e422827c0fdf454fbe6d61bfd7dbd3877 | Python | 2,448 | 73 | # gets the gene loci start, end, and strand from all the src_neg
import os
import gffutils
def run(db_name):
# define output folder
output_folder = './1_output/'
input_folder = '../data/'
input_filename = input_folder + db_name + '.gff'
db_filename = input_folder + 'databases/' + db_name + '.... |
a72cf64df953389f9c676424e5b926d390951e8eca003383aeddbd3e2c85bcd4 | Python | 2,448 | 67 | import torch
from .base import randint, randperm, uniform
def beta(alpha, n, like, generator=None):
"""Sample Beta(alpha, alpha) as a ratio of Gamma draws, honoring the generator."""
device = generator.device if generator is not None else like.device
concentration = torch.full((2, n), float(alpha), dtype... |
74b201e67c18d24731826fa36fe2fc552e014ad5debeef82875d635e4874bb79 | Python | 2,454 | 79 | # %% This will do perturbation of the target data.
# solve for 6 configurations for G + image response and H + non-image response.
# the penalty value is fixed to 10.
import numpy as np
# from SSN_model_funcs import * # tentatively...
import SSN_model_funcs as ssn
import create_new_target_data as cnd
import sys
impor... |
7fb9d4a2c32449261cb2f308164acddbe523795db9e3d2fe5777dbb81b82a562 | Python | 2,454 | 67 | import os
import torch
from deprecated import deprecated
from transformers.file_utils import WEIGHTS_NAME, CONFIG_NAME
#from pytorch_pretrained_bert.modeling import WEIGHTS_NAME, CONFIG_NAME
from utils.logger_utils import get_custom_logger
logger = get_custom_logger(__name__)
@deprecated(version='', reason="This meth... |
49e036158b50be9e1852014d70e8762fa90f82a722264076ec9b3aa7ab92b48b | Python | 2,455 | 81 | from typing import List, Sequence
import numpy as np
import pandas as pd
from scipy.sparse import coo_matrix
from omicverse.external.scTenifold.core._networks import make_networks
def ko_propagation(B: np.ndarray,
x: np.ndarray,
ko_gene_id: Sequence[int],
deg... |
28b6a0edcfd13b06a619f781986b88daf3b0d633522d7df22bb8bc863c270d4d | Python | 2,457 | 57 | import torch as th
import numpy as np
import scanpy as sc
import scipy as scp
from sklearn.model_selection import train_test_split
from .utils import normalize, sparse_mx_to_torch_sparse_tensor
from .dataloader_utils import handle_adata_view
class ANVIDatasetNoGCN(th.utils.data.Dataset):
def __init__(self, adata... |
5a3041fe985672dffc77996a26afe0a519d70d2ea2fb109d50ce5221b0f8ad91 | Python | 2,457 | 63 | import os
from importlib import resources as impresources
from pathlib import Path
from ... import bids
from ...bids.convert2bids import BidsConverter
from ...load_annotations.tuh import loadAnnotationsFromEdf
BIDS_DIR = impresources.files(bids)
DATASET = BIDS_DIR / "tuh"
def convert(root: Path, outDir: Path):
... |
6a04194ff030b169c2648276c962dc6bd7124e2ef1b39d09c2a6ddc98cb22ac4 | Python | 2,458 | 74 | import re
import json
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Draw
DEFAULT_SP = {'<CLS>', '<UNK>', '<PAD>', "<END>"}
SMI_REGEX_PATTERN = r"""(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>>?|\*|\$|\%[0-9]{2}|[0-9])"""
SMI_REGEX_PATTERN_EXT = r"""(\[[... |
9bdf0af5c4e76546903b4faea5b224e6ec097ff59ec1104954bfe652894f46c4 | Python | 2,458 | 58 | import pathlib
path = pathlib.Path.cwd()
if path.stem == 'tmb_survival':
cwd = path
else:
cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')]
import sys
sys.path.append(str(cwd))
import numpy as np
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
import pandas as pd
i... |
cd3a61d52b4d82719b03e5fc881c1b301472170a7c651b14c7516a2f7b645736 | Python | 2,459 | 108 | from os.path import join
LATENT_DIR = 'latent'
IMG_DIR = 'images'
EMB_DIR = 'embeddings'
OUT_DIR = 'results'
PATH_TO_EXPORT = '../feature_condensation/feature_condensation.py'
PATH_TO_GWAS = '../lmm/run_lmm.py'
def get_latent_pkl(exp_var, n_causal, seed):
latent_pkl_templ = 'exp_var%.3f_nc%d_seed%d.pkl'
re... |
0c354b67cb8062f5d9579e135f103c0ef516eff75c51a1fd71b8703d0b2bf7d6 | Python | 2,460 | 69 | import numpy as np
import h5py as h5
import pandas as pd
def comput_subplot_layout(n):
base = np.sqrt(n)
min_base = int(np.floor(base))
max_base = min_base+1
if min_base * max_base >= n:
return min_base, max_base
else:
return max_base, max_base
def load_data_file(f... |
3d7c08f2ef529ffa99eccf319f9db8033a739a2f62d65515d5e152edb75d8fb4 | Python | 2,461 | 73 | from scipy.signal import find_peaks
import numpy as np
from scipy.io import wavfile
import matplotlib.pyplot as plt
def sec2samp(sec, sr):
"""
This function converts seconds to samples according to the sampling rate
:param sec: (float) seconds to convert to sample
:param sr: (float) sampling rate
... |
42c5f3e9e85de66537aff98f8954f7eaee46b213f608696e464d022f323833a1 | Python | 2,466 | 72 | """
# Code adapted from:
# https://github.com/facebookresearch/Detectron/blob/master/detectron/utils/collections.py
Source License
# Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... |
8fb4660944e6f8c1bbc3bfc9b14b7f2bf40233d13591e63ae470a4cc8cd9ccbc | Python | 2,466 | 69 | import eelbrain as eel
import mne
import numpy as np
def preprocess_eeg(eegfile, refc=['EXG1', 'EXG2'], ch=['Cz'], thr=0.1, verbose=True):
'''
load EDF, rereference and find Erg start time
eegfile: path to .bdf file
refc: list of reference channels
'''
if verbose: print('LOADING', e... |
89c1660a0fc20703a32e23f5bcfbfb0abd248bf1e180a0710796062763003431 | Python | 2,468 | 75 | import os
import subprocess as sp
import unittest
import shutil
import tempfile
import numpy as np
from neuron_morphology.swc_io import morphology_to_swc, morphology_from_swc
from neuron_morphology.morphology_builder import MorphologyBuilder
class TestRunPiaWmStreamlines(unittest.TestCase):
def setUp(self):
... |
d14ed597fe955282f06e05bf32487f8fd2fa972066ffae40911befbd8ecfb0e5 | Python | 2,468 | 73 | # dataset settings
dataset_type = 'BasicImageDataset'
data_root = 'data/uw_enhance/'
file_client_args = dict(backend='disk')
train_pipeline = [
dict(type='LoadImageFromFile', file_client_args=file_client_args),
dict(type='LoadGTImageFromFile', file_client_args=file_client_args),
dict(
type='TransB... |
eea2af165393f7cbab5c91f476138766869e4f66e830a1bdabcb8f931f695e56 | Python | 2,468 | 70 | from __future__ import annotations
import numpy as np
import qcelemental as qcel
from .pair_model import PairModel
"""
These functions are included for backwards compatibility with an old version of AP-Net
"""
def predict_sapt(dimers : list[qcel.models.Molecule], return_pairs=False, batch_size=200):
if not isi... |
7596cffa14bc39d269f664de500239f13dddb9804bcef3e01a683e348d99c011 | Python | 2,471 | 101 | import logging
import pickle
from pathlib import Path
from urllib.parse import urlparse
import torch
import tqdm
logger = logging.getLogger(__name__)
def write_list(data, f, use_prog_bar=True):
nlen = len(data)
pickle.dump(nlen, f)
if use_prog_bar:
for i in tqdm.tqdm(data):
pickle.du... |
ad0c8c4f8eaa692dcbe98b095267ef041326fbc9991e2a5a349b4c2911338bf5 | Python | 2,471 | 68 | """Upsample images."""
import os
import subprocess
import glob
# =============================================================================
DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti'
# Set subs to work on
SUBS = ['sub-07']
# ==========================================================... |
57143a0b783ae65c92c56d8951bac75a48e74cd862225570c184ba6d277b3dc4 | Python | 2,472 | 74 | import cv2.dnn
import numpy as np
from ultralytics.yolo.utils import ROOT, yaml_load
from ultralytics.yolo.utils.checks import check_yaml
CLASSES = yaml_load(check_yaml('coco128.yaml'))['names']
colors = np.random.uniform(0, 255, size=(len(CLASSES), 3))
def draw_bounding_box(img, class_id, confidence, x, y, x_plus... |
bb5bdeaedd07683e2be740d457463e514daa9d20b771e15c297a972efff3db24 | Python | 2,472 | 79 | from __future__ import annotations
import numpy as np
from . import Operator
from ..sites import Lattice
from ..global_defs import is_default_cpl, get_sites
def _get_site_operator(index: tuple, opstr: str, strength: float = 1.) -> Operator:
sites = get_sites()
if not isinstance(index, int):
... |
dd5980bc17b33da2bf9784391b9e539ece02952a7ac09c47994c9f66383884a9 | Python | 2,472 | 87 | """Shared test utilities for raydepsets tests."""
import shutil
from pathlib import Path
from typing import List, Optional
import runfiles
from ci.raydepsets.workspace import Depset
_REPO_NAME = "io_ray"
_runfiles = runfiles.Create()
def copy_data_to_tmpdir(tmpdir, ignore_patterns: Optional[str] = None):
"""C... |
a2fb34769af6e7cf9848e607caea5f9ef61cdea3cd14317897df3251f4137d6f | Python | 2,474 | 78 | import torch
from pfrl.agents import dqn
from pfrl.utils.recurrent import pack_and_forward
class PAL(dqn.DQN):
"""Persistent Advantage Learning.
See: http://arxiv.org/abs/1512.04860.
Args:
alpha (float): Weight of (persistent) advantages. Convergence
is guaranteed only for alpha in [0, 1)... |
c31c160a9b0f31d7c134957864f25f92dbd7a6e8b22c841af6f7ee48320f0239 | Python | 2,474 | 82 | # %%
import numpy as np
from SSN_model_funcs import * # tentatively...
import sys
import pickle
import model_data
types = ["G", "H"]
homedir = "/home/shinya.ito/realistic-model/visual_behavior_modeling/"
dpath = homedir + "neuropixels_data/l23_mean_traces.pkl"
with open(dpath, "rb") as f:
l23data = pickle.load(... |
994812f306f6f281eed63cd42468f702767474240b9492a4252f66821b63ddeb | Python | 2,476 | 64 | import numpy as np
from lib.surface import read_surface_from_gifti, write_surface_to_gifti
from lib.utils import setup_logger
log_file = snakemake.log[0] if snakemake.log else None
logger = setup_logger(log_file)
# Run the processing pipeline
mesh, metadata = read_surface_from_gifti(snakemake.input.surf_gii)
mesh_na... |
dd0782e7892b20cd8194a026bc78b6ffc7092bce962dc7a136349e0a7efa1e9e | Python | 2,478 | 61 | # MIT License
#
# Copyright (c) 2020 Marcus D. R. Klarqvist, PhD, MSc
# https://github.com/mklarqvist/tf-computer-vision
#
# 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 Software without restriction,... |
5842c6a8205a313a734e1fff6ce863abf04e0084a1c393f1a318b5e1220bd0a0 | Python | 2,480 | 87 | # -*- coding: utf-8 -*-
#
"""
std_delly.py
Standardize a Delly record.
"""
from .standardize import VCFStandardizer
from svtk.utils import is_smaller_chrom
@VCFStandardizer.register('delly')
class DellyStandardizer(VCFStandardizer):
def standardize_info(self, std_rec, raw_rec):
"""
Standardize D... |
59a07537d9529dbb4e28b8833150892c8ff3f93973985e90e972920a61cdee4c | Python | 2,480 | 60 | import logging
import pandas as pd
from agent.classifiers.evaluation.statistic_test import normality_test_jarque_bera, normality_test_shapiro_wilk
from agent.classifiers.evaluation.statistic_test import paired_t_test, wilcoxon_test
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
INPUT... |
620f1534e9d630fdc772fb59c50c8fda99116d5c40d3623cd723d3f3212a9c64 | Python | 2,481 | 56 | __author__ = "Simon Andermatt"
__copyright__ = "Copyright (C) 2017 Simon Andermatt"
# Warning: this file is obsolete and not maintained anymore.
from mdgru.helper import argget
import copy
import tensorflow as tf
from tensorflow_extra_ops import CaffeBiCGRU3D
class CaffeMDGRU(object):
def __init__(self, inputarr... |
730943b9b61294e2ac321f16adea2511dd70e95616eb52ed6c0aa2f3add17781 | Python | 2,481 | 72 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Do PCA to extract the first PC score and loadings to use as gPCA.
Output:
PCA_load.csv PCA loadings.
PCA_scores.csv PCA scores.
"""
import os
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
if __name__ == '__main__':
__spec__ = ... |
a29d0c978883aafe2cf99a24bbcd480c04d72c07a91850ac36314aa6042005d3 | Python | 2,481 | 82 | from os import path
DATA_DIR = path.join(path.dirname(path.realpath(__file__)),'../tests/data/')
def assert_and_feedback(obtained, expected,
debug='',
):
try:
assert obtained == expected
except AssertionError:
print(debug)
raise AssertionError('The compared strings are not identical:\n"{}" - computed.\n"{}"... |
ffb6125ae29e8c220309f5ca95fc6c7a8a4f53c8695668271406530e362ae6c3 | Python | 2,481 | 74 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#... |
2685cb1a54566010d454ce535d9bcb4ffc82bf3dc9de4d40d85ac86fd467b724 | Python | 2,482 | 80 | # Copyright 2023 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
3dbeae227d7b623c867f0c9612e8ff5394e3f863760b922d127467c7175f0fc3 | Python | 2,483 | 70 | # Ultralytics YOLO 🚀, GPL-3.0 license
import requests
from ultralytics.hub.utils import HUB_API_ROOT, request_with_credentials
from ultralytics.yolo.utils import is_colab
API_KEY_PATH = 'https://hub.ultralytics.com/settings?tab=api+keys'
class Auth:
id_token = api_key = model_key = False
def __init__(sel... |
617a0c65927a280acf82762c6c748ab0109cf50278262f5ec5d49710cc3f2a08 | Python | 2,483 | 68 |
"""
Date: Oct 25 2019
Author: Shaoju Wu
Email: swu3@wpi.edu
see also:
https://github.com/Jilab-biomechanics/CNN-brain-strains
"""
import numpy as np
import scipy.io
import tensorflow as tf
import keras
from keras.models import load_model
from scipy.io import loadmat
from scipy.io import savemat
from sklearn.metrics ... |
cfc6395d7f17eb6ed93446f2ca62d95823221e8ff59e3aea5fda32d7ae79a465 | Python | 2,484 | 59 | import torch
import torch.nn as nn
import torch.nn.functional as F
from layers import GraphConvolution
class GCN(nn.Module):
def __init__(self, nfeat, nhid1, nhid2, nclass, dropout):
super(GCN, self).__init__()
self.gcA1_1 = GraphConvolution(nfeat, nhid1)
self.gcA1_2 = GraphCon... |
681b01fe14470f0375ae3fac8c00766792bfc8904293e24af05988c043159801 | Python | 2,485 | 75 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
Tests: CPU smoke tests for the public NVT and NPT Hydra examples.
Models: none; the UMA calculator factory is replaced with ASE EMT.
CI: test (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.