sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
0dbd17dd3811b1ced6ea3c6ba0eb6f5785c48d7361f3a639af0d3fd874e35b07 | Python | 2,349 | 83 | import json
from tqdm import tqdm
import argparse
import numpy as np
def save_data(data,file_path):
with open(file_path, 'w', encoding='utf8') as f:
for line in data:
json_data=json.dumps(line,ensure_ascii=False)
f.write(json_data+'\n')
def load_data(file_path,is_training=False):
... |
695a841c2772c1f6d01779de3ed8688e7842a5123801dd5d4ca6bbf90a391ade | Python | 2,349 | 97 | from zndraw.geometries.arrow import Arrow
from zndraw.geometries.base import (
ColorProp,
InteractionSettings,
PositionProp,
RotationProp,
SizeProp,
)
from zndraw.geometries.bonds import Bond
from zndraw.geometries.box import Box
from zndraw.geometries.camera import Camera, CameraType
from zndraw.ge... |
a42e24c9da6fd52c2efd9479eaa9bf9b6434325e14f954658317de1254297a85 | Python | 2,350 | 46 | # 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... |
e40f5566b20897ea3f93b80502745189716ab5d215659ea884b20e6c14d872be | Python | 2,350 | 61 | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import os.path as osp
import unittest
import numpy as np
import pytest
from mmengine.structures import BaseDataElement
from mmseg.datasets.transforms import PackSegInputs
from mmseg.structures import SegDataSample
class TestPackSegInputs(unittest.TestCase)... |
3fd0a077655cc0687ea31068673566e79f861dbaa9077ec18f8eb55d3f1ec037 | Python | 2,351 | 74 | import numpy as np
from scipy.ndimage.morphology import binary_erosion
from scipy.spatial.distance import cdist
def dice(a, b, labels=None):
'''
Computes dice coefficients for each label between two hard segmentations.
dice = 2 * |A ∩ B| / |A| + |B|
If labels are not provided, all unique int... |
06860180f3e205882c17e07184978d6291ec2e0b9f9682a3babf5b42a314daba | Python | 2,355 | 69 | #!/usr/bin/env python3
import pandas as pd
import matplotlib.pyplot as plt
import argparse
def main(file1, file2, output):
# --- Load and combine data ---
df1 = pd.read_csv(file1, sep='\t')
df2 = pd.read_csv(file2, sep='\t')
df = pd.concat([df1, df2], ignore_index=True)
# --- Ensure correct types ... |
24d3e51949caf100b160cceb4fa6648916b1200c00b68534a635a7b12256255f | Python | 2,355 | 64 | # Copyright (c) OpenMMLab. All rights reserved.
from unittest import TestCase
from unittest.mock import Mock
import torch
from mmengine.structures import PixelData
from mmseg.engine.hooks import SegVisualizationHook
from mmseg.structures import SegDataSample
from mmseg.visualization import SegLocalVisualizer
class ... |
ba10b4a2b3bade3ac5644154e145c41b33d2e136488f3c844460e35ed5aaab27 | Python | 2,355 | 60 | import pytest
from random import randint
from .conftest import create_sleep_cyborg, create_cc4_complex_cyborg
from CybORG import CybORG
from CybORG.Shared.Session import VelociraptorServer
# issue-174 fixes problem
def test_action_space_server():
# test 100 random seeds
for i in range(100):
seed = ra... |
d17488fc31d1f1440d825605ad4236747e3c91d6cde840037c3f3259a7e59eb0 | Python | 2,355 | 72 | import json
from tqdm import tqdm
import os
import argparse
def load_data(file_path,is_training=False):
with open(file_path, 'r', encoding='utf8') as f:
lines = json.loads(''.join(f.readlines()))
result=[]
for line in tqdm(lines):
data = line
texta = '\n'.join(data... |
c7b30baac693d9a261a927da0be40b0cd6e38a9483711ef430bcf96987f03cb1 | Python | 2,356 | 83 | import numpy as np
from numpy.testing import assert_approx_equal
import xgboost as xgb
train_data = xgb.DMatrix(np.array([[1]]), label=np.array([1]))
class TestTreeRegularization:
def test_alpha(self):
params = {
"tree_method": "exact",
"verbosity": 0,
"objective": "r... |
69fc79b7b3addc7696b30be42d9bdd14eb8cb9caa4db7d23b42dd7e617be64e6 | Python | 2,357 | 74 | #!/usr/bin/env python3
"""
@author: Andrei Istudor andrei.istudor@gmail.com
"""
import os
import sys
from PyQt5 import QtWidgets, QtMultimedia, uic, QtCore
from PyQt5.QtWidgets import (QMainWindow, QTextEdit,
QAction, QFileDialog, QApplication)
from PyQt5.QtWidgets import *
from PyQ... |
88d19df07d5a8ee621ac18ea8f963a9ca649980fd3f07b06f7c6c6ce83dbd1ce | Python | 2,358 | 64 | import torch
from transformers import BertModel, BertTokenizer
from Bio import SeqIO
import sys
import pickle
import numpy as np
import time
if len(sys.argv) != 3:
print("Usage: python3 embed_fasta_protbert_aa.py <fasta path> <output path>")
# Load ProtBert model
model_name = "Rostlab/prot_bert"
print("Loading m... |
44ebbac2a28802524477c56bc59396bd418782664c52d0086624f7396e979a79 | Python | 2,359 | 68 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
###
# File: /root/CAMP/distribution.py
# Project: /home/richard/projects/pepland/inference/cpkt/model/code/utils
# Created Date: Saturday, July 30th 2022, 3:50:55 pm
# Author: Ruochi Zhang
# Email: zrc720@gmail.com
# -----
# Last Modified: Sat Dec 23 2023
# Modified By: Ruo... |
306a370ae87328b5702f0685239a386f557db41a674745f9802bb57bcec5ba98 | Python | 2,360 | 59 | from experiment import *
import json
import numpy as np
import pandas as pd
from scipy.spatial.distance import pdist, squareform
from sklearn.cluster import AffinityPropagation
if __name__ == "__main__":
for species in expt.species_names:
print(species)
# Paths
bouts_path = expt.direct... |
6800b7c849b11fbfac8e0ef481601659e2621d9a2d7ed335c24c18d6453d0ba9 | Python | 2,360 | 74 | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
import mmcv
import mmengine
from packaging.version import parse
from .version import __version__, version_info
MMCV_MIN = '2.0.0rc4'
MMCV_MAX = '2.2.0'
MMENGINE_MIN = '0.5.0'
MMENGINE_MAX = '1.0.0'
def digit_version(version_str: str, length: int = 4):... |
0f5a0d319ba9dff52aa224d739b0313de7cd8aa49e11f061c38f856f5fe88929 | Python | 2,361 | 67 | """Support utilities for CUDA."""
import subprocess # nosec
import xml.dom.minidom # nosec
from cwl_utils.types import CWLObjectType
from .loghandler import _logger
def cuda_version_and_device_count() -> tuple[str, int]:
"""Determine the CUDA version and number of attached CUDA GPUs."""
try:
out:... |
4d9f0cfb6576c9e807e28ae75aabcaf5832b7dfb45f24d0ebd64b92f70d925c0 | Python | 2,362 | 54 | ######################################
# wrapper for rule: disambiguate_and_filter
######################################
import os
import sys
import math
import subprocess
import glob
from snakemake.shell import shell
STAR = "STAR"
SAMTOOLS = "samtools"
BEDGRAPH2BIGWIG = "bedGraphToBigWig"
shell.executable("/bin/bas... |
6cc4f5e55a5d58078e8f2fe01d5e2748d00c8be644b686445f74c6499af52b58 | Python | 2,364 | 70 | DEFAULT_FOLLOW_BATCH = [
"protein_element",
"ligand_context_element",
]
def seperate_outputs(outputs, n_graphs, batch_node, halfedge_index, batch_halfedge):
outputs_pred = outputs["pred"]
outputs_traj = outputs["traj"]
new_outputs = []
for i_mol in range(n_graphs):
ind_node = batch_no... |
e398e650a2bb78b26bc8e41059dbea9217f015193a13b7df15b78b11962928fa | Python | 2,364 | 81 | import os
import sys
from pdb import set_trace as bp
import matplotlib.pyplot as plt
import numpy as np
from connPFM.connectivity.connectivity_utils import calculate_ets
from nilearn.masking import apply_mask
N_MASKS = 23
N_SAMPLES = 202
MASKS_DIR = "/mnt/d/Experiments/Experiment2-Blink_Tic/SPFM/Subregion_masks"
WHOL... |
e32f20be969cc80616f75d6429c161f8313f42e28329b9896784a5beb7871867 | Python | 2,365 | 64 | #!/usr/bin/env python
import os, pickle, glob, sys
import numpy as np
from pymbar.timeseries import statisticalInefficiency
def doStatistics( filename ):
array = np.genfromtxt( filename, skip_header = 100 , usecols = 1, dtype = float)
return np.mean(array), np.std(array) / np.sqrt(len(array)/statisticalIneffic... |
1eed13a0d560696a4a9a30a0a5fafbe835c75b3f587e077a31535de0e5d70f67 | Python | 2,366 | 93 | # Standard Library Imports
import os
# Third Party Imports
import matplotlib.pyplot as plt
import MDAnalysis as md
import numpy as np
# Encodermap imports
import encodermap as em
molname = "diubi"
run_id = 3
step = 50000
selection_for_alignment = "resid 0:77"
main_path = "runs/{}/run{}".format(molname, run_id)
#... |
26a8c3b1d4bd92d81089eb9f385fa912cf843da50ef329e2044e50568f673f57 | Python | 2,367 | 63 | import shutil
from pathlib import Path
import pytest
from guppy.testing import compare_output_folders
from guppy.testing.api import locate_run_folder, step1, step2, step3, step4
from guppy_test_data import TESTING_DATA, event_ts_offset_for
SESSION_SUBDIR = "SampleData_csv/sample_data_csv_1"
STANDARD_OUTPUT_SUBDIR = ... |
5cba0126b916e9d1377c3920ac776c770deff4412be2066ee6e208d9f7bfea2b | Python | 2,367 | 73 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# pyre-strict
from typing import List, Optional, Tuple
import numpy as np
class HistoryBuffer:
"""
Track a series of scalar values and provide access to smoothed values over a
window or the global average of the series.
"""
... |
e323c1ee011438f569242f25719c378251873815ff09d9420dcfddbf18a297bf | Python | 2,367 | 79 | #!/usr/bin/env python
#
# Concatenate bvecs files in time.
#
# Copyright (c) 2015 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import sys
from typing import Sequence
from spinalcordtoolbox.utils.fs import extract_fname
from spinalcordtoolbox.utils.sys import init_sct, set_loglevel, La... |
8d15a753137d6f096175c4ab72c80496da356a65473a0e7ae3f4adbc0f567150 | Python | 2,369 | 89 | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
"""
Tests the h5py.File object.
"""
import thre... |
98e403c48935bedd72a5de0ec0c0b9d54ee2d5b44f41e52f88fa8a3a8532846a | Python | 2,369 | 65 | from os import path as osp
from torch.utils import data as data
from torchvision.transforms.functional import normalize
from basicsr.data.transforms import augment
from basicsr.utils import FileClient, imfrombytes, img2tensor
class FFHQDataset(data.Dataset):
"""FFHQ dataset for StyleGAN.
Args:
opt (... |
b2622cd2d0bada9713cf2ecea3e7a490e55b9e36f72371892bc0534443361849 | Python | 2,369 | 63 | '''
convert a distance matrix to nexus file and plot it with SplitsTree4
(https://software-ab.informatik.uni-tuebingen.de/download/splitstree4/manual.pdf)
USAGE:
imgformat: One of ['jpg', 'eps', 'svg', 'png', 'pdf'].
plot_now: [True, False]. If True, plot directly to same dir as outfile
cmdfile: ... |
343ec6cca10be06d7cee8768b849352325af7ad9fa087df0a5acbfdd3be6608d | Python | 2,370 | 53 | import catmaid.fields
from django.conf import settings
import django.contrib.postgres.fields
import django.contrib.postgres.fields.jsonb
import django.contrib.postgres.functions
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
"""This mig... |
ed2e2ed282312ff1e83d826ed0b587561ed970281fc370c805c2a3214b1d431f | Python | 2,370 | 75 | import importlib
roi_dict = {
'tissue_seg': {'sub_dir': None, 'measure': 'volume', 'type': 'derived'},
'VentriclesDist': {'sub_dir': None, 'measure': 'distance', 'type': 'derived'},
'template': {
'sub_dir': 'TemplateReg',
'measure': 'volume',
'type': 'template',
'source': im... |
33c6b590491192de779142259cd209df81c8dd8868edcf82f8726715f3b8cb53 | Python | 2,371 | 71 | """Shared room-lookup helpers for joblib emit machinery.
Both ``router.py`` and ``sweeper.py`` need to map a joblib ``room_id``
(real UUID, composed ``<uuid>/<name>``, ``@global``, ``@internal``, or
unknown garbage from the wire) to either the persisted ``Room`` row or
the address that should be surfaced on the wire w... |
584a348198dfb4ceeb2de584c9ce63eb41aa43b286a01cc8cec99f52e23e641f | Python | 2,372 | 77 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# encodermap/tests/find_undocumented_package_parts.py
################################################################################
# EncoderMap: A python library for dimensionality reduction.
#
# Copyright 2019-2024 University of Konstanz and the Authors
#
# Authors:
# ... |
8c3b6bbbed3a05345014248ead2bdb52557917484d0750aa58bb44b83b201db3 | Python | 2,373 | 78 |
numJobsPerHour = 101
baseFileName = './shellScripts/genReport_'
def generateCommand(reportFile='sparse050_10class_147_t7_e29.html',
objPath='./data/obj',
baseSimTag='sparse050_10class',
trialRange=[147,148],
activity=False,
distance=False,
epoch=29):
command = 'pyth... |
147043e9f4ad1e0f131d8ce4f33095c8f26d8068db7cf14b5368aef9af9e51c4 | Python | 2,374 | 65 |
baseFileName = './shellScripts/SHD/SHD_080_'
baseSimTag = 'SHD_080_'
def generateCommand(
sim_tag='default',
log_file='example.log',
obj_dir='./data/obj',
w1_std=-1,
w1_sparse=-1,
exc_hid_rat=0.5):
command = 'python3.7 scripts/paramSHDTraining.py'
command += '... |
3afbc363977b6bf58283e13479c794d2340b4604d2cf1a98c77b817216ac7583 | Python | 2,374 | 65 |
baseFileName = './shellScripts/SHD/SHD_050_'
baseSimTag = 'SHD_050_'
def generateCommand(
sim_tag='default',
log_file='example.log',
obj_dir='./data/obj',
w1_std=-1,
w1_sparse=-1,
exc_hid_rat=0.5):
command = 'python3.7 scripts/paramSHDTraining.py'
command += '... |
86c8a132fc4c0bccd811e5378b24c6ba0c601d2b471a2c936463fda81ab2568c | Python | 2,374 | 65 |
baseFileName = './shellScripts/SHD/SHD_100_'
baseSimTag = 'SHD_100_'
def generateCommand(
sim_tag='default',
log_file='example.log',
obj_dir='./data/obj',
w1_std=-1,
w1_sparse=-1,
exc_hid_rat=0.5):
command = 'python3.7 scripts/paramSHDTraining.py'
command += '... |
999c53e66396ac8f665d0dcdf38bf44c7dfdc075708f9ee7c163357ef755f4d4 | Python | 2,374 | 64 | import catmaid.fields
from django.conf import settings
import django.contrib.postgres.functions
from django.db import migrations, models
import django.db.models.deletion
forward = """
CREATE TABLE catmaid_favorite_project (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
user_id int REFERENCE... |
2071e480cc4f1ba9062f89d193a10f0b3a69cdc7c06e48575f6acb45af9dd990 | Python | 2,375 | 89 | from medperf.exceptions import CleanExit
import pytest
from medperf.tests.mocks.execution import TestExecution
from medperf.tests.mocks.dataset import TestDataset
from medperf.commands.execution.submit import ResultSubmission
PATCH_SUBMISSION = "medperf.commands.execution.submit.{}"
@pytest.fixture
def result(fs):... |
5cdced510742b80e7f19664c197f8b23232cf9afbea0d40ba77fa6b5d47e69cc | Python | 2,375 | 59 | ## Restormer: Efficient Transformer for High-Resolution Image Restoration
## Syed Waqas Zamir, Aditya Arora, Salman Khan, Munawar Hayat, Fahad Shahbaz Khan, and Ming-Hsuan Yang
## https://arxiv.org/abs/2111.09881
import os
import numpy as np
from glob import glob
from natsort import natsorted
from skimage import io
im... |
73ebc10e7cdd5a6640a57b65534950af49e92f9f96488097b2ae4cc5da87b223 | Python | 2,375 | 65 |
baseFileName = './shellScripts/SHD/SHD_095_'
baseSimTag = 'SHD_095_'
def generateCommand(
sim_tag='default',
log_file='example.log',
obj_dir='./data/obj',
w1_std=-1,
w1_sparse=-1,
exc_hid_rat=0.5):
command = 'python3.7 scripts/paramSHDTraining.py'
command += '... |
81d4e483c7e9bfe200c1c177baa0d75300275f569c49e3d0bbe7978c1eccb152 | Python | 2,375 | 72 | #!/usr/bin/python
import logging
import os
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_ref_gtf = os.path.abspath(args.ref_gtf... |
8213d1fdd50b7dcc15fb8f688a205672b50adaae0b961f5114df34f4266734a0 | Python | 2,375 | 61 | import tensorflow as tf
import numpy as np
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
def standardize_cifar(x):
"""Standardize CIFAR10 data to the [0, 1] range."""
return x / 255.0
def load_data(batch_size=32):
"""
Loads CIFAR10 train and test data ... |
b577c7b8427a47095ed03c74807d82e8490ce5055e2e8bdaeb5d94b5f7b603d0 | Python | 2,376 | 67 | import json
import requests
from src.categories import BIOLOGICAL_PROCESS, MOLECULAR_ACTIVITY, PATHWAY
from src.prefixes import REACT
# Reactome doesn't have a great download, but it does have a decent service that lets you get the files you could have
# downloaded. In reactome, there are "events" which have subc... |
c748db398f0a501e6d2354309f542c737f26848d64f43ed2b0f51508d92a55e2 | Python | 2,376 | 59 | ## Restormer: Efficient Transformer for High-Resolution Image Restoration
## Syed Waqas Zamir, Aditya Arora, Salman Khan, Munawar Hayat, Fahad Shahbaz Khan, and Ming-Hsuan Yang
## https://arxiv.org/abs/2111.09881
import os
import numpy as np
from glob import glob
from natsort import natsorted
from skimage import io
im... |
435d6cf921f80b48ecab28c84cb95df5db3a59a629ac03a92bf7f998eb4a2aac | Python | 2,377 | 75 | """Run simple cell optimisation"""
"""
Copyright (c) 2016-2020, 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
... |
6df05fe8e5e225e403ab0a00a9ce171f6ff52f1fbaba8a76ec5f4f72b68e404b | Python | 2,377 | 82 | # -*- coding: utf-8 -*-
from django.db import migrations
add_missing_primary_keys = """
CREATE VIEW primary_keys
AS
SELECT a.attname AS column_name, i.indrelid AS rel
FROM pg_index i
JOIN pg_attribute a ON a.attrelid = i.indrelid
AND a.attnum = ANY(i.... |
dde3c07a147d50657961bdffdf50d077461f7d629578a73c5d4c50a80f41adb5 | Python | 2,377 | 62 | import os
import subprocess
from .extractor_cartridge import ExtractorCartridge
class RawDataIndexer(object):
"""
This class defines a Raw Data Indexer.
Attributes:
- cartridge (:obj:`ExtractorCartridge`): An :obj:`ExtractorCartridge`.
- extractor_tag (:obj:`str`): The tag of an extractor... |
19797a8f71fc8d2b1dc08dabf965b1ff42d322201011c62ed8521d93cb54e458 | Python | 2,378 | 71 | #!/usr/bin/env python3
# #############################################################################
# Copyright (c) 2018-present lzutao <taolzu(at)gmail.com>
# All rights reserved.
#
# This source code is licensed under both the BSD-style license (found in the
# LICENSE file in the root directory of this source t... |
8d4132c7234b1f707ecfa1fd1d90825e38e24f107f642a9bcddb318b16a008da | Python | 2,378 | 69 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmseg.models.backbones import MSCAN
from mmseg.models.backbones.mscan import (MSCAAttention, MSCASpatialAttention,
OverlapPatchEmbed, StemConv)
def test_mscan_backbone():
# Test MSCAN Standard Forward
... |
95a3f657ffff88a91869fba967640e36d24cab3409b4bea9453a2a081bac4c01 | Python | 2,379 | 99 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 31 17:54:31 2023
@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
def calcDensity(df, n = 10):
#get 1st n frames of df
... |
b0d162f31025f9eacdc32a9f40e2693ba5f345638e38e5fe32ab4108663fb7ca | Python | 2,379 | 82 | # model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
data_preprocessor = dict(
type='SegDataPreProcessor',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
bgr_to_rgb=True,
pad_val=0,
seg_pad_val=255)
model = dict(
type='EncoderDecoder',
data_preprocessor=data_... |
cb39d26d4f582c541b9e7cf8869ffe2e659feab83053018d8b4cb0be14ac8a01 | Python | 2,379 | 58 | """
Resolve error that scans.tsv does not have corresponding BIDS column
"""
import os, glob
import json
from pathlib import Path
import subprocess
import pandas as pd
datalad_dir = '/Users/h/Documents/projects_local/1076_spacetop'
# for * ses-01, ses-02, ses-03 * .json files, update column "task-social_runtype"
sessio... |
0814f82b9635719b301f845d3a21367631c041c6f680008fa1c2cf9575a6d99f | Python | 2,382 | 89 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
def quartet2score(dm, split):
"""
Calculate whether the predicted distance matrix is in accordance with the provided split
Parameters
----------
dm : distance matrix with distances between predicted y (aka distances between featur... |
42f934a75d29e24fa112d7abfbffc2515e15c87f6cfa8fca478766904058e108 | Python | 2,382 | 55 | ######################################
# wrapper for rule: alignment_softclip
######################################
import os
import sys
import math
import subprocess
import glob
from snakemake.shell import shell
STAR = "STAR"
SAMTOOLS = "samtools"
shell.executable("/bin/bash")
f = open(snakemake.log.run, 'a+')
f.w... |
6af9eb5c59c780058fe94c239feb166fd252f824a4f2aa1fb56eb5342fe64c66 | Python | 2,382 | 60 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.cnn import DepthwiseSeparableConvModule
from mmseg.registry import MODELS
from .fcn_head import FCNHead
@MODELS.register_module()
class DepthwiseSeparableFCNHead(FCNHead):
"""Depthwise-Separable Fully Convolutional Network for Semantic
Segmentation.
... |
7eda38706b3a1d796f747870275c3c1dd6307c7e5adf1983228731f3386a10db | Python | 2,383 | 77 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# encodermap/tests/find_long_comments.py
################################################################################
# EncoderMap: A python library for dimensionality reduction.
#
# Copyright 2019-2024 University of Konstanz and the Authors
#
# Authors:
# Kevin Sawade
... |
5d57e638ca16bc4ef0f4dce6ae3ab31d768f1bfe1a06bcd29b9e514418e59c90 | Python | 2,385 | 72 | #! /usr/bin/env python
import os
import setuptools # noqa; we are using a setuptools namespace
from setuptools import setup
descr = """Preconditoned ICA for Real Data"""
version = None
with open(os.path.join('picard', '__init__.py'), 'r') as fid:
for line in (line.strip() for line in fid):
if line.star... |
6f7115b7bbf9634fe93ff22afc4a5cacfca916444c1e8ddbc94e6f7309515714 | Python | 2,388 | 51 | # Start your first Nearl featurization
######################################
import nearl
import nearl.io, nearl.featurizer, nearl.features
from collections import OrderedDict
if __name__ == "__main__":
# Get the example data
EXAMPLE_DATA = nearl.get_example_data("/tmp/nearl_test")
# Initialize the trajecto... |
5b0c82ef958e64776750325863ebfec8d7340851b3190a8cb1400d422c5994b2 | Python | 2,390 | 62 | """
Based on manual observation of scannotes and datalad
(after `datalad/delete_func_scannotes/01_remove_scannotes_nodata.py` and
`datalad/delete_func_scannotes/delete_bold.tsv`), we have a final list of files
to delete. In this code, we delete funcs and keep ones that require further investigation or false alarms.
... |
eedf434a59e4e7d8d9bd37ed073c17b005315e9df434adcb604050ba422bcd05 | Python | 2,390 | 70 | '''Mixin class to make dictionaries'''
# Disabling lines below, generate error when loading ephys.examples
# from future import standard_library
# standard_library.install_aliases()
SENTINAL = 'class'
class DictMixin(object):
'''Mixin class to create dictionaries of selected elements'''
SERIALIZED_FIELDS ... |
b78628ac3fb29c6ed68d5b5942dc9bd39a124b31e4f9d59803229b445b8d57dc | Python | 2,393 | 65 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 24 10:50:22 2024
@author: AC
"""
import pandas as pd
from pathlib import Path
# Define path for the dataset
data_dir = Path("D:/ownCloud/Articol Foisor/csv2")
# Load the dataset
data = pd.read_csv(data_dir / 'foisor_en_cleaned_final.csv')
# Function to... |
17f7f03a72d9d8aa543f0e6f13be23b6d8190f30e4523b79d1bf73c10cb5c53f | Python | 2,394 | 60 | """Unit tests for the babel-overused-xrefs CLI wrapper.
The analysis itself is tested in tests/model/test_concords.py; these cover the argparse/CSV layer
and the one guard that stops a regenerated audit from silently losing its labels.
"""
import pytest
from src.tools.overused_xrefs.cli import resolve_labels
# One ... |
35f92ce02c9160c57e62d44fa5d9efd99b574f58d208a25f8f69eee9e3c4d1e6 | Python | 2,394 | 72 | """
Tests write output (should it return True or False or write)
"""
import pytest
from dnaio import SequenceRecord
from cutadapt.predicates import TooManyN, TooHighAverageErrorRate
from cutadapt.steps import PairedEndFilter
@pytest.mark.parametrize(
"seq,count,expected",
[
("AAA", 0, False),
... |
8ca07ed601596730be0cfddf60ccfb0414fa7483c493705cb9541856a554ef33 | Python | 2,395 | 79 | import random
import numpy as np
import pandas as pd
import scipy
from scipy.optimize import minimize
# get_4prl_latent derives latent variables: chosen Q values given
# observable actions and rewards + recovered parameters from MLE/MAP.
def get_4prl_latent(actions, rewards, parameters):
alpha, neg_alpha, beta, _ ... |
02e1b7ff0a5955cb373e9e7f825c7410bb20b6fdac8ffc74abde87da61a43875 | Python | 2,398 | 68 | from medperf.commands.list import EntityList
import medperf.commands.list as list_module
from medperf.exceptions import InvalidArgumentError
import pytest
from medperf.entities.interface import Entity
def generate_display_dicts():
"""Mocks a list of dicts to be returned by Entity.display_dict"""
return [
... |
f9013af03b4410eae9bebc3527dac7f54e217944593c0ad71f64894164371425 | Python | 2,398 | 75 | """Test the loadContents feature."""
import json
from pathlib import Path
from unittest.mock import patch
import pytest
import cwltool.builder
from cwltool.main import main
from .util import get_data
def test_load_contents_file_array(tmp_path: Path) -> None:
"""Ensures that a File[] input with loadContents lo... |
75230ff41279ed736eb8a3ac9f43125b9c400fb50c2c50cd1b8a2f5d99ff40de | Python | 2,399 | 101 | import gzip
import typing
import ijson
from itertools import chain
from typing import Dict, Tuple, Any, Generator, Optional, List
from kgx.config import get_logger
from kgx.source.tsv_source import TsvSource
log = get_logger()
class JsonSource(TsvSource):
"""
JsonSource is responsible for reading data as rec... |
e8e33982bf440842a40940c51e6aef374f5e304dfe608c4f3380a5a263cd76f6 | Python | 2,399 | 90 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py,md
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.16.1
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# + [markdown] ... |
05f05260acd7acd99f350764402780e1918c506530e08d70aa057fbe8651e000 | Python | 2,400 | 72 | # dataset settings
dataset_type = 'PascalContextDataset59'
data_root = 'data/VOCdevkit/VOC2010/'
img_scale = (520, 520)
crop_size = (480, 480)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', reduce_zero_label=True),
dict(
type='RandomResize',
scale=img_scale... |
fae453c078f624e04f4a650531e7b1953c06afcb3230fe853ea5b8306f978f33 | Python | 2,400 | 72 | # dataset settings
dataset_type = 'PascalContextDataset59'
data_root = 'data/VOCdevkit/VOC2010/'
img_scale = (520, 520)
crop_size = (384, 384)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', reduce_zero_label=True),
dict(
type='RandomResize',
scale=img_scale... |
013a6a96cb2c7d3493c8046ef003f016853103b5e4f36172a1a6bba4f58af31d | Python | 2,401 | 85 | import pytest
import numpy as np
import tsgm
@pytest.mark.parametrize("ds", [
np.array([[[1, 2, 3], [3, 4, 5]]]), tsgm.dataset.Dataset(np.array([[[1, 2, 3], [3, 4, 5]]]), y=None)
])
def test_visualize_dataset(ds):
tsgm.utils.visualize_dataset(ds)
@pytest.mark.parametrize("feature_averaging", [
True, Fa... |
e015df2f56df843eb138e3aee4d79bacbf270d9a3f22c420abc2123d902b0dba | Python | 2,402 | 67 | #!/usr/bin/env python
#
# Refresh `index.html` to reflect changes in `_assets/json`
#
# Copyright (c) 2024 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE in the $SCT_DIR
"""
This script collects QC entries from the '_assets/json' folder, then writes them to the index.html file.
Usage:
... |
c91a0c587744316a32bc1af360944849c270fea7fa5e9592aab4f7c950fb2fca | Python | 2,403 | 67 | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.cnn import build_norm_layer
from mmseg.registry import MODELS
@MODELS.register_module()
class Feature2Pyramid(nn.Module):
"""Feature2Pyramid.
A neck structure connect ViT backbone and decoder_heads.
Args:
embed_dims... |
11de8de996f7b691e4534b0346073623583e50949b494348acfc117e48b9def0 | Python | 2,405 | 70 | """Behavioral round-trip tests for client serialization helpers."""
import pytest
from molify import smiles2atoms
from zndraw.client.serialization import (
_estimate_frame_size,
atoms_to_json_dict,
json_dict_to_atoms,
)
@pytest.fixture(params=["O", "CCO", "c1ccccc1"], ids=["water", "ethanol", "benzene"]... |
262cd553524e212a0717624e80bcd87ec03d26b476bb164c2659ee54a003081c | Python | 2,405 | 61 | import tensorflow as tf
import numpy as np
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
def standardize_mnist(x):
"""Standardize MNIST data to the [0, 1] range."""
return x / 255.0
def load_data(batch_size=32):
"""
Loads MNIST train and test data and pr... |
6eef1aab73cacc83105bec3901af92c277ef6bee909489b742b9554bc17b8816 | Python | 2,405 | 63 | try:
import cPickle as pickle
except:
import pickle
import gzip
import numpy
import os
import matplotlib
import matplotlib.pyplot as plt
nmda_compare = '/mnt/csoport31-2/Modellezo_csapat/CA1_pyramidal/Spine_project_validation_results60/Basic_set_newopt/Active_spine_F_factor_with_R/For_NMDA_compare/'
nmda_compa... |
5a9a8d85e5ba82e316367babb6809c809b40089ec7a2843577a9414dd15d11dd | Python | 2,406 | 60 | from os import path
from zipfile import ZipFile
import xmltodict
from src.babel_utils import pull_via_urllib
from src.prefixes import HMDB
from src.util import get_config, get_logger
logger = get_logger(__name__)
HMDB_DOWNLOAD_URL = "https://hmdb.ca/system/downloads/current/"
HMDB_ZIP_FILENAME = "hmdb_metabolites.z... |
8ecb71bb7ecaf53327a6561b5520575e4d151521aab268cd625f1c8cc3063bdc | Python | 2,407 | 45 | # Generated by Django 3.2.20 on 2023-08-03 19:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
op... |
4a20b42a43d1a44fd047a0bd82ed90e39abaa085aa85176e6da2856df2d60120 | Python | 2,408 | 60 | ##
## CPCantalapiedra 2020
import os
from .pfam_common import filter_fasta_file
from .pfam import PfamAligner, get_pfam_args
##
def pfam_align_denovo(queries_pfams, queries_fasta, resume, translate, trans_table,
cpu, num_servers, num_workers, timeout_load_server, cpus_per_worker, port, end_port... |
d52449e7123c3d3779bb0ae44667408b1307662e3ac50c8316420ee9235bd1e5 | Python | 2,408 | 53 | # main.py
# This script facilitates testing different video-based facial emotion recognition models in a demo mode.
# It supports both SVM and GRU with Attention models for classifying emotions from a single input video.
#
# Usage:
# To run the GRU with Attention model:
# python main.py --path_to_video {your_vide... |
d7792936b2549181464afd40651fada3fe417be8fea19234b423771d60d817cb | Python | 2,408 | 76 | # allertrans/utils.py
import h5py
import torch
import click
def load_h5_embeddings(h5_path):
"""
Load all embeddings from an H5 file (ProtT5) into a tensor and return protein IDs.
"""
embeddings = []
ids = []
with h5py.File(h5_path, "r") as f:
for key in f.keys():
... |
86dd525f3167f1b3f525ee25b48ce91d3e7ad41a5265e3b9d9b8edc91d45c74b | Python | 2,409 | 65 | # https://github.com/juexinwang/scGNN.git
import pandas as pd
from sklearn.metrics import adjusted_rand_score as ARI
from sklearn.metrics import normalized_mutual_info_score as NMI
import os
import sys
def train(root_path, dataset_name, save_path):
labels_path = os.path.join(root_path, dataset_name + "_labels.csv"... |
d1dd1a7fac7fa62f9890ff54d1ab1a7b046230c9b7c4dd34b77dc3d1f4c798bb | Python | 2,409 | 71 | import pytest
from CybORG import CybORG
from CybORG.Simulator.Scenarios import EnterpriseScenarioGenerator
from CybORG.Agents import SleepAgent, EnterpriseGreenAgent, FiniteStateRedAgent
from CybORG.Simulator.Actions import *
@pytest.fixture()
def cyborg():
sg = EnterpriseScenarioGenerator(
blue_agent_cl... |
92f9dfd75b8b5af400dcdd17904dd1c28350ab30f915b2419db3f619befb8e7f | Python | 2,410 | 67 | import logging
import numpy as np
from scipy import signal
logger = logging.getLogger(__name__)
def compute_cross_correlation(
signal_a_trials: list[np.ndarray], signal_b_trials: list[np.ndarray], sample_rate: float
) -> np.ndarray:
"""
Compute normalized cross-correlations between paired trial arrays.
... |
e5c65c9db88dae96b072cecc5752e35208838b1bfdada82d949adbcad7081ee4 | Python | 2,410 | 60 | # -*- coding: utf-8 -*-
from django.test import TestCase
from django.test.client import Client
from catmaid.models import Class, ClassInstance, TreenodeClassInstance, Relation
from catmaid.models import Treenode
from catmaid.control.label import remove_label
from catmaid.tests.common import CatmaidTestCase
class Tag... |
52a6d09bf08b7e00dcc2728b7fa202973e37e4a53454c1554890610017918968 | Python | 2,411 | 56 | # from disco_huge import Diffuser
# from utils import *
from disco import Diffuser
import streamlit as st
from io import BytesIO
from PIL import Image
from disco import steps
@st.cache(show_spinner=False, allow_output_mutation=True) # 加装饰器, 只加载一次。
class ST_Diffuser(Diffuser):
def __init__(self, custom_path):
... |
540ebac7b4871a8a41bb54b8fd9fff16fa11d34975cf69ed8b49b14950d82cde | Python | 2,411 | 66 | """Multi-stage temporal convolutional network model architecture
as described in TeCNO paper: https://doi.org/10.1007/978-3-030-59716-0_33 .
Script Author: Armine Vardazaryan"""
import tensorflow as tf
class DilatedResidualLayer(tf.keras.models.Model):
def __init__(self, dilation, out_channels, dropout... |
f5a95589717facd47ebff641ded077cff840c73ec74ce558388797651059a8ee | Python | 2,412 | 66 | import os
from collections import defaultdict
from os import path
import jsonlines
from src.util import Text
# TODO: Assess whether we are bringing in any new identifiers (we shouldn't, unless we just don't have id's for a thing)
def assess_completeness(input_dir, compendia, reportfile):
"""Given a directory co... |
4fb4432bef9010b29d4811187cb50f2c50fba2554ee05a1700a547a85010097b | Python | 2,415 | 70 | import synapseclient
from synapseclient.core.exceptions import (
SynapseNoCredentialsError,
SynapseHTTPError,
SynapseUnmetAccessRestrictions,
)
from medperf.exceptions import (
CommunicationRetrievalError,
CommunicationAuthenticationError,
)
import os
import shutil
from .source import BaseSource
imp... |
10a34fe8a57ffb09f871845cdd29a532d1d966b0e4037488e75c9c5188543d2c | Python | 2,416 | 68 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmseg.registry import MODELS
from ..utils import Upsample, resize
from .decode_head import BaseDecodeHead
@MODELS.register_module()
class FPNHead(BaseDecodeHead):
"""Panoptic Feature Pyra... |
4610f3272cff4d9f8f79bb38636d4bcb9be60bdd784ffd7b0d2d914658b22afa | Python | 2,416 | 78 | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import seaborn.objects as so
from seaborn import axes_style
import os
from params import palette
palette['fren'] = palette['transfer']
palette['langdecode'] = palette['transfer']
plt.style.use('../training/mpl_stylesheet')
mtypes = [
'homo... |
d1ba1c1a1880b7f32bdf36065eed10fe06a3029d3c674aa35b187aaf909139df | Python | 2,416 | 66 | import numpy as np
from unittest.mock import MagicMock
import tsgm
def test_sine_cosine_simulator():
data = tsgm.dataset.DatasetProperties(N=10, T=12, D=23)
sin_cosine_sim = tsgm.simulator.SineConstSimulator(data)
syn_dataset = sin_cosine_sim.generate(10)
assert type(syn_dataset) is tsgm.dataset.Datas... |
4122ba1718f4375640a4d826be1bce807e612b81582912044f6018044e7da5b3 | Python | 2,419 | 50 | # 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... |
526593e78d8acebe668b08ead960a6cf9cd1ab7ae60f0a49a6ed6d6f7fdbec2e | Python | 2,419 | 64 | from transformers import TrainingArguments
from trl import SFTTrainer, DataCollatorForCompletionOnlyLM
from unsloth import FastLanguageModel
from datasets import load_dataset
import pandas as pd
import argparse
import torch
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("... |
8b34acbcc7550608c3253a7d3f33c12fb5dbb69b4453d092e3e0c4e98f2c8d5b | Python | 2,419 | 64 | from transformers import TrainingArguments
from trl import SFTTrainer, DataCollatorForCompletionOnlyLM
from unsloth import FastLanguageModel
from datasets import load_dataset
import pandas as pd
import argparse
import torch
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("... |
1c90fb01ed263878c5f3b10668e66608f443793f76eadd70c39b9f92f1c911c4 | Python | 2,421 | 76 | # model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
data_preprocessor = dict(
type='SegDataPreProcessor',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
bgr_to_rgb=True,
pad_val=0,
seg_pad_val=255)
model = dict(
type='CascadeEncoderDecoder',
data_preprocesso... |
9b7e6cff39fb71f807f7ed093c53fc4e07633500c2ae5edbb3c16c19c1f8bd22 | Python | 2,421 | 80 | _base_ = [
'../../../configs/_base_/datasets/cityscapes.py',
'../../../configs/_base_/default_runtime.py',
'../../../configs/_base_/schedules/schedule_80k.py'
]
data_root = '../../data/cityscapes/'
train_dataloader = dict(dataset=dict(data_root=data_root))
val_dataloader = dict(dataset=dict(data_root=data_... |
a083bf5ca3228c4095c2c9b6a155893e86029be47867637784cd90624dc34e04 | Python | 2,422 | 85 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 5 11:48:41 2023
@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
from sklearn.neighbors import KDTree
#from scipy.spatial i... |
1fb176b58c01d2b7e67aff50bb8f2d2537e3b4c0ec166ff967a282699d746970 | Python | 2,423 | 58 | import os
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
def process_subfolder(main_folder, subfolder_name):
file_path = os.path.join(main_folder, subfolder_name, 'best_particle_stats_denoise.tsv')
if not os.path.isfile(file_path):
return subfolder_name, None, None
... |
d4a6b99041be0202a912f408a0968c5cccf09c973e5c2f203ad6c448b4a88fca | Python | 2,423 | 89 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmseg.models.utils import (nchw2nlc2nchw, nchw_to_nlc, nlc2nchw2nlc,
nlc_to_nchw)
def test_nchw2nlc2nchw():
# Test nchw2nlc2nchw function
shape_nchw = (4, 2, 5, 5)
shape_nlc = (4, 25, 2)
def test_func(x... |
17a8debab91e6113d7e8519a32980281d486b2f67caaf28a5ba7edeb7e420cc0 | Python | 2,424 | 99 | """
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 numpy as np
import torch
from .base_layers import Dense
class AtomEmbedding(torch.nn.Module):
"""
Initial atom embeddings b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.