sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
d6bbeb414b9d20fbb6b799a42d28f5aee31526f27ef471ebcc31943de4981122 | Python | 694 | 20 | def parse_report(text: str):
lines = text.split("\n")[:-2]
def split_first_five_colons(line):
all_split = line.split(":")
reassembled = all_split[0:5] + [":".join(all_split[5:])]
return reassembled
separated = [split_first_five_colons(line) for line in lines]
fields = ("source"... |
efda10f5be577607f1f580c807efda6ddf8d3b2477dac245c159ff3445fb367c | Python | 694 | 24 | from setuptools import setup, find_packages
setup(
name='DSCT',
version='0.0.1',
description='Efficient Spatial Transcriptomic Cell Typing Method Using Deep Learning and Attention Mechanisms',
url='https://github.com/coffeei1i/DSCT/',
author='Yiheng Xu',
license='GNU General Public License v2.0... |
1022b785c252690af1f3e9bc475bc85486a1c6c5be0bbefcbfc848d552285081 | Python | 695 | 26 | from itertools import chain, combinations
def walk(path, values, ending):
l_filenames = []
for name in possible_filenames(values, ending):
filename = path / name
if filename.exists():
l_filenames.append(filename)
if not (path / 'dataset_description.json').exists():
l_... |
7096d1f3d22837a6238bc8829303843631b4c03a3f6d440caad2ecde2145c569 | Python | 695 | 20 | from elasticai.creator.file_generation.savable import Path
from elasticai.creator.file_generation.template import (
InProjectTemplate,
module_to_package,
)
from elasticai.creator.vhdl.design.design import Design
class LSTMTestBench:
def __init__(self, name: str, uut: Design):
self._uut = uut
... |
87a5ea9cee1413f2434750c2cab98f5f60aa9f79bce5260e5a838572b21e56af | Python | 695 | 18 | from PIL import ImageDraw
from typing import Optional
from .shape import Shape, calculate_short_side
class Rectangle(Shape):
def draw(self, draw: ImageDraw.Draw, color: tuple[int, int, int]):
draw.rectangle((self.x, self.y, self.x + self.width, self.y + self.height), fill=color)
class HorizontalRectangl... |
8ddb61f1b4ab14b269a40e1cb845fc384b4b1337b045f6557ca5b5957ed9be05 | Python | 695 | 23 | import numpy as np
from sella.peswrapper import _svd_rank
def test_svd_rank_well_scaled():
# O(1) spectrum: relative and absolute agree.
s = np.array([2.0, 1.0, 1e-9])
assert _svd_rank(s) == 2
def test_svd_rank_relative_not_absolute():
# Poorly-scaled spectrum where a relative cutoff (1e-6 * s[0] =... |
3c6298f948df315fd1c1221a461351c2ac24f478f5d2873fcfaff7718020e1cf | Python | 697 | 24 | import pandas as pd
import numpy as np
from multiprocessing import Pool
def transform_data_5(seq):
tmp = [np.array(list(seq[(17 + i):(-13 + i)])).reshape(-1, 1) for i in range(-2, 3)]
tmp = np.concatenate(tmp, axis=1)
tmp = ' '.join([''.join(x) for x in tmp])
return tmp
data = pd.read_csv('./data/tr... |
49a2b8ce0e04d44544da47b82c9844446e9c898aafc09d11616b6ab16d5e99f1 | Python | 697 | 24 | #!/bin/env python3
'''
Apply a chain reactions for the quasi-particles in the 2D patterns of cardiac
arrhythmia
'''
import yaml
from pdlfeynman.pool import ParticlePool
from pdlfeynman.reaction import REACTIONS
from pdlfeynman.history import ReactionHistory
# applying a bunch of random reactions...
import random
rand... |
52163371d6c1e19626494d8f36372c12d316e93f28f358c7257af0f405448aa3 | Python | 697 | 31 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import downward.suites
import common_setup
import configs
NICKS = [
'eager_greedy_alt_ff_cg', 'eager_greedy_ff', 'eager_greedy_ff_no_pref',
'eager_pareto_ff', 'eager_wa3_cg'
]
CONFIGS = {}
for nick in NICKS:
CONFIGS[nick] = configs.default_configs_satisficin... |
5a9d0e08b6c78f5edbc7f2b3b7bf5f105f214333d89a807e8c21a0c041dff593 | Python | 698 | 32 | """Classes for projecting data into new component space.
Classes
-------
PCA
Project channels into principal component space based on the covariance matrix among electrodes
Custom
Apply a user-defined linear combination of original channels to a new set of virtual channels
Identity
Returns the channels in ... |
eab850830b1661c32e6a998416faf30e36fdf0abeea0fbe0f8112099acda71ef | Python | 698 | 18 | '''Script to submit to cluster statistics of decoding patterns sources'''
from stormdb.cluster import ClusterBatch
import os
project = 'MINDLAB2020_MEG-AuditoryPatternRecognition'
os.environ['MINDLABPROJ']=project
os.environ['MNE_ROOT']='~/miniconda3/envs/mne'
scriptdir = '/projects/{}/scripts/working_memory/'.format(p... |
19d4276cff43f51914daeb906aa9a8061656834e061eca4e533cd38178d28e08 | Python | 699 | 20 | import os
import sys
fast5_dir_path = sys.argv[1]
output_dir_path = sys.argv[2]
ref_path = sys.argv[3]
index_dir = sys.argv[4]
sigmap_exe_path = sys.argv[5]
options = " -p /mnt/batty/bcavlak/bio/tools/sigmap/extern/kmer_models/r9.4_180mv_450bps_6mer/template_median68pA.model -t 128 "
dir_list = os.listdir(fast5_dir... |
df5f07321c723f342e8db4457b25f1146b0750be7cc7366f8de486afbb913e29 | Python | 699 | 19 | import torchvision.transforms as tvtransforms
AVAILABLE_TRANSFORMS = {
"ToTensor": tvtransforms.ToTensor
}
def get_transforms(config):
list_of_transforms = []
if config["transforms"] is not None:
for i in range(len(config["transforms"])):
transform_name = config["transforms"][i]
... |
97b359fef739e605b53afa6ba31194ebf0d24ecf4c30c55a9e616e072d788794 | Python | 700 | 26 | import typing
import cv2
import numpy as np
def processing_slow(img: np.ndarray, shape: typing.Tuple[int, int] = (800, 800)) \
-> np.ndarray:
img = cv2.resize(img, shape)
img = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21)
return img
def processing(img: np.ndarray, shape: typing.Tup... |
9eee6f9978f520b852904c8999cf2ad0200a871cd978833b52a482ad867a05d4 | Python | 700 | 21 | import numpy as np
import numpy.testing as npt
import astrovascpy.ou as OU
def test_OU_calibration():
"""Verify that the calibration is able to calculate the correct kappa and sigma"""
def verify(kappa_test, sigma_test):
r_max_test = 2.8 * sigma_test / np.sqrt(2 * kappa_test)
target_time = O... |
e4fcd8710d9eba5c64f08df12a4638b9874233495d15458b91268a318184c2c6 | Python | 700 | 30 | import numpy as np
from neuron import h, gui
params = np.genfromtxt('params.param')
soma = h.Section(name='soma')
soma.insert('hh')
soma.gnabar_hh = params[0] # Sodium conductance in S/cm2
soma.gkbar_hh = params[1] # Potassium conductance in S/cm2
soma.gl_hh = params[2] # Leak conductance in S/cm2
stim = h.ICl... |
621aad9d1202b57ef20024d175d31022a5a647642cad4f5a171571d0452ed3f3 | Python | 701 | 23 | extensions = dict(
required_params=[], # empty to override defaults in gen_defaults
validate_required_params="""
# Required args: either model_key or path
if (is.null(model_key) && is.null(path)) stop("argument 'model_key' or 'path' must be provided")
""",
set_required_params="",
)
doc = dict(
preamb... |
839048bec7311923c832dfe677f4a22d7ee30ffb091c2f5753c3837593791216 | Python | 701 | 26 | from __future__ import annotations
import pytest
pytest.importorskip("pymatgen.analysis.defects")
from ase.build import bulk
from quacc.recipes.emt.defects import bulk_to_defects_flow
def test_bulk_to_defects_flow(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
atoms = bulk("Cu")
output = bulk_to_... |
8c436027f99959f3af7994b253553cf35abf6a26e718ba4b966107c5816af83a | Python | 701 | 21 | # coding=utf-8
# Copyright 2026 The Google Research Authors.
#
# 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 applicab... |
b5b2c308ac2d26e54c5b7b4d57ccd7b057755aca82f7b3c763f144c6fd779b6d | Python | 701 | 26 | """
Plugin system for OXASL
=======================
Design
~~~~~~
A plugin is registered as a Python entry point. It must be an instance of
OxaslPlugin and provide the following information:
- Name
- Brief description
- Version
- Optional OptionCategory defining command line options supported
- Dictionary of im... |
1f33b7f9afea1516fba4c18acb8561f01b8ed800c279a6021e1f63462243c632 | Python | 702 | 24 | try:
import binutil # required to import from dreamcoder modules
except ModuleNotFoundError:
import bin.binutil # alt import if called as module
from dreamcoder.domains.tower.main import main, TowerCNN, tower_options
from dreamcoder.dreamcoder import commandlineArguments
from dreamcoder.utilities import numb... |
af1867b8f63f23fb992d5f99732b63562b9d7fa738792832191a0da08cdc42e2 | Python | 702 | 19 | import os
import glob
from pybullet_tools.utils import read_json, write_json
from pddlstream.utils import mkdir
if __name__ == '__main__':
SKILL = 'scoop'
MATERIAL = {'pour': 'red_men', 'scoop': 'chickpeas'}
all_dirs = glob.glob('data/pr2_{}_*'.format(SKILL))
all_trials = []
for dir in all_dirs:
... |
08250e5e627113c41d97837d97711a67a6895dd49ff4e4c1920f326deb8c87c9 | Python | 703 | 24 | """Pure Python implementation of bayesian global optimization with gaussian processes."""
from __future__ import annotations
import importlib.metadata
from bayes_opt import acquisition
from bayes_opt.bayesian_optimization import BayesianOptimization
from bayes_opt.constraint import ConstraintModel
from bayes_opt.dom... |
468279c9764667e422186d7277722efdd22ce1e945920473e0e64d43a0cbf25b | Python | 703 | 30 | """Deep learning and Reinforcement learning library for Researchers and Engineers"""
from __future__ import absolute_import
try:
install_instr = "Please make sure you install a recent enough version of TensorFlow."
import tensorflow
except ImportError:
raise ImportError("__init__.py : Could not import Tens... |
97d4334fb858473b310555365170bd16284100cf42f5a4bb786afd47eb89ed45 | Python | 703 | 28 | # By Shuran Liu, 2023
import random
import numpy as np
from torch.utils.data import Dataset
import h5py
import cv2
# from prepare_data import z_length
class TestDataset(Dataset):
def __init__(self, h5_file, scale):
super(TestDataset, self).__init__()
self.h5_file = h5_file
self.scale = s... |
aa90fa53f03aff96442cbefe20c315d25c3c6302424d8fee44683fa14b031dc1 | Python | 703 | 18 | # coding=utf-8
# Copyright 2026 The Google Research Authors.
#
# 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 applicab... |
1ccc9d322f232139920c4f2e30788ebb11e8760bc199dfc30d9b8650960be6a3 | Python | 704 | 19 | from pylearn2.utils import serial
import sys
_, model_path = sys.argv
model = serial.load(model_path)
from pylearn2.gui.patch_viewer import make_viewer
space = model.generator.get_output_space()
total_dimension = space.get_total_dimension()
import numpy as np
num_colors = 1
#if total_dimension % 3 == 0:
# num_colors... |
b92780f1d88f04ab515e60f39a1dc0d2b43952356180c25435e7387350fa05d5 | Python | 706 | 26 | """
Set of utilities for pyseg packages to extract topological and geometrical information
from biological samples
# Author: Antonio Martinez-Sanchez (Max Planck Institute for Biochemistry)
# Date: 08.09.14
"""
__author__ = 'martinez'
__version__ = "$Revision: 002 $"
from .memb import MembSideSkelGraph
from .memb im... |
592630685aea485c51ad1cab2d0aca74a5d42f156c9dceec2d5c6fb46b2d0503 | Python | 707 | 24 | """实现GAT 类。"""
import torch.nn.functional as F
import torch.nn as nn
import torch_geometric.nn as pyg_nn
class GAT(nn.Module):
def __init__(self, in_c, hid_c, out_c, log_attention_weights=False):
super(GAT, self).__init__()
self.conv1 = pyg_nn.GATConv(in_channels=in_c, out_c... |
63abd8013c228fc10a8e50c8353e1b661912eff38a91656b86b46a24909238c5 | Python | 707 | 21 | ##Get first 20 amino acids
from Bio import SeqIO
import pandas as pd
df = pd.read.csv('ProtienID_for_Fig-4C.csv')
def write_fasta_for_column(column_name, df):
genome_prefix = column_name.split('_')[0]
genome_file = f"{genome_prefix}.faa"
output_file = f"{column_name}.faa"
gene_ids = df[column_name].to... |
a305f8e334f2a2f33fa9a9a60833c446f196764034c4257437b778c86684df16 | Python | 709 | 19 | """
Testing the analysis pipeline on synthetic spike trains
last modified: András Ecker 06.2023
"""
from assemblyfire.utils import ensure_dir
from assemblyfire.spikes import SpikeMatrixGroup
from assemblyfire.clustering import cluster_spikes, detect_assemblies
if __name__ == "__main__":
spikes = SpikeMatrixGroup... |
27780075cb1753133cf33bcfb3f1abfb79b11b1a30cfab2bafb89b26021d0c16 | Python | 710 | 24 | from ..neuralnodes import params
import dataclasses
@dataclasses.dataclass
class Params(params.Params):
delay: float = 0.020
nonlinearity_gain: float = 2.000000
def get_bounds(self):
param_dict = self.to_dict()
bounds = []
for key in param_dict.keys():
if 'tau' in key ... |
6696df993728ba25be660772b9bd254e9f512f65df9406ee8e9b6d4f5d751ad3 | Python | 711 | 16 | """Bundled research inputs must match the published hash manifest."""
import hashlib
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def test_bundled_data_and_configs_match_manifest():
manifest = json.loads((ROOT / "MANIFEST.sha256.json").read_text())
assert any(path.startswit... |
6b2cdba215936cf15f06e205877a1cad3add295f22cee3db07ad5d601d39e123 | Python | 711 | 16 | """ layer_recognition """
# Copyright (C) 2021 Blue Brain Project, EPFL
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versi... |
aa046f81041f6e1ae250482423308eda1abbdbebf74fdecf57a0b8e8aed1c27b | Python | 711 | 23 | from __future__ import annotations
from pathlib import Path
from shutil import rmtree
TEST_RESULTS_DIR = Path(__file__).parent / "_test_results"
TEST_SCRATCH_DIR = Path(__file__).parent / "_test_scratch"
def pytest_sessionstart():
import os
file_dir = Path(__file__).parent
os.environ["QUACC_CONFIG_FILE... |
40754c02a7a3e8e831c8b67ff0dff5e85569efbbfa9b25b25a6143f9cdca42de | Python | 714 | 25 | import pytest
import shutil
from sleeplab_format.models import *
from pathlib import Path
from .create_datasets import create_datasets
from sleeplab_format.test_utils.fixtures import *
@pytest.fixture(scope='session', autouse=True)
def recreate_test_files() -> None:
"""Recreate the separate test data files at t... |
2938125fffdc2feebb9e9644d1be59515a7c9243f1e9b3614cad0a277f2eb474 | Python | 715 | 35 | # Configuration file for the Sphinx documentation builder.
# -- Project information
project = 'HyGDL'
copyright = '2022, Kneiding'
author = 'Hannes Kneiding'
release = '0.1'
version = '0.1.0'
# -- General configuration
extensions = [
'sphinx.ext.duration',
'sphinx.ext.doctest',
'sphinx.ext.autodoc',
... |
1aeda09de2128dcc8010407bdd464de5759fe3bfd112beb33861625e914de49f | Python | 716 | 11 | from ..utils import format_channel_location_dict
BCICIV2A_CHANNEL_LIST = [
'FZ', '0', '1', '2', '3', '4', '5', 'C3', '6', 'CZ', '7', 'C4', '8', '9', '10', '11', '12', '13', '14', 'PZ', '15', '16'
]
BCICIV2A_LOCATION_LIST = [['-', '-', '-', 'FZ', '-', '-', '-'],
['-', '0', '1', '2',... |
8bc5c04347850a8836e85c3dc95d186f5ca002a298075c3d0b3f67d1f8fc8195 | Python | 716 | 27 | """Filetype information.
"""
from typing import Tuple
from pip._internal.utils.misc import splitext
WHEEL_EXTENSION = ".whl"
BZ2_EXTENSIONS: Tuple[str, ...] = (".tar.bz2", ".tbz")
XZ_EXTENSIONS: Tuple[str, ...] = (
".tar.xz",
".txz",
".tlz",
".tar.lz",
".tar.lzma",
)
ZIP_EXTENSIONS: Tuple[str, ..... |
aec4e488619b833ac886ff52475ef2b75fab5b201020ce21c86aed5eeb49f512 | Python | 716 | 34 | import sys
from random import random, seed
from pybioshell.core.data.io import read_fasta_file, create_fasta_string
if len(sys.argv) < 3 :
print("""
Reads a multiple FASTA files and print a randomly selected fraction of sequences.
USAGE:
python3 read_fasta.py faction input.fasta
EXAMPLE:
python3 read... |
42043af366d8a21da0457408682037b078c4874976d2b1e808ab8e8b5429e53a | Python | 717 | 13 | from .io import input_choice, literal_eval, no_rdkit_log, capture_rdkit_log
from .file import download, smart_open, extract, compute_md5, get_line_count
from .torch import load_extension, cpu, cuda, detach, clone, mean, cat, stack, sparse_coo_tensor
from .decorator import copy_args, cached_property, cached, deprecated_... |
c2790aa01392d331d91fc9a732ba149e9032e1c520d57dee58320065eb90b984 | Python | 717 | 26 | import unittest
import torch
from torcheeg.models import BCUNet, BUNet
class TestDDPM(unittest.TestCase):
def test_bddpm(self):
unet = BUNet()
mock_eeg = torch.randn(2, 4, 9, 9)
t = torch.randint(low=1, high=1000, size=(2, ))
fake_X = unet(mock_eeg, t)
self.assertEqual(tu... |
8440a459b6913dc746c6f55c2cd39971cd3ca13a379664c0a2dd72cf418bb8f0 | Python | 718 | 36 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward.suites import suite_optimal_with_ipc11
import common_setup
REVS = ["issue420-base", "issue420-v1"]
CONFIGS = {
"blind": ["--search", "astar(blind())"],
"lmcut": ["--search", "astar(lmcut())"],
}
TEST_RUN = False
if TEST_RUN:
SUITE = "gripper... |
c9f6bb99cad75fac7da2a656f633d4f10949241bcb731a34d2790c42309d22ae | Python | 718 | 19 | import numpy as np
import pandas as pd
import os
from pathlib import Path
host="lassen595"
length_list = [1000, 10000, 100000, 1000000]
radius_list = [1,2,4]
for length in length_list:
for radius in radius_list:
result_dir = Path(f"ecfp_{length}_{radius}")
time_data = np.load(result_dir / Path("ti... |
3d1e2e2eb41f33d7fbf096b0ec74836fc1254ec435b8a3a196851532615cae68 | Python | 719 | 24 | from .basedatatype import BaseDataType
from .commonsmedia import CommonsMedia
from .entityschema import EntitySchema
from .externalid import ExternalID
from .form import Form
from .geoshape import GeoShape
from .globecoordinate import GlobeCoordinate
from .item import Item
from .lexeme import Lexeme
from .math... |
85325956ce682c640a2209808da147e7a6cbbfd86041ddd64a77ec1e9a2a40b2 | Python | 719 | 30 | import platform
def windows_only(func):
if platform.system() != 'Windows':
return lambda *args, **kwargs: None
return func
@windows_only
def hide_file(path):
"""
Set the hidden attribute on a file or directory.
From http://stackoverflow.com/questions/19622133/
`path` must be text.
... |
6734a1dbbe4cc3848cd9977828414ec8b0f87436133464f4d0f8827aacda44cb | Python | 720 | 21 | import random
import numpy as np
from merlin.util import binary
def test_bit_array_to_int_conversion():
for i in range(50):
intIn = random.getrandbits(64)
listOut = binary.int_to_bit_list(intIn, 64)
intOut = binary.bit_list_to_int(listOut)
assert intIn == intOut
def test_flip_bit... |
e1c67f407c5d3c6831c99915b2e08ebf8ab35c7537bcd4f333ef74ad7fcf22c8 | Python | 720 | 25 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 23 00:16:27 2023
@author: daltonm
"""
import subprocess
from pathlib import Path
import os
import sys
import time
script_directory = Path(os.path.dirname(os.path.abspath(sys.argv[0])))
code_list = ['analyze_trajectory_only_models_figure_reproduct... |
6a0b915cac27f87bd408fc703c2e960fb703a18000a63186e4f3ce0d2fd4f187 | Python | 721 | 24 |
# run in coloc directory
import subprocess
for pheno in ['grossinf', 'microinf']:
cmd = [
"python", "./coloc_qtl.py",
"--out_pref", "../np_phewas/output/coloc/mega/" + pheno + "/",
"--gwas_sumstats",
"../np_phewas/output/gwas/mega/saige/" + pheno + "_saige_results.txt",
"-... |
cc3104702412ea047f762070cc65d8dbe2e2df20a6a24911dadca6a83500fe91 | Python | 721 | 31 | import sys
import glob
#get runid
#runid=glob.glob("./wandb/latest-run/run-*.wandb")[0].split('-')[-1].replace('.wandb','')
metric_file=sys.argv[1]
metric_file = metric_file.strip()
runid=sys.argv[2]
runid=runid.strip()
fobj = open(metric_file)
header=fobj.readline().strip().split("\t")
body=[]
f... |
08bc441971a69743999acd253bd6e61ec2ff2031a8b4b338718d21e3862525f3 | Python | 723 | 32 | import sys
from pybioshell.core.chemical import PdbMolecule
from pybioshell.core.chemical import find_rings
if len(sys.argv) < 2 :
print("""
Reads in a mall molecule (PDB file format) and prints all cycles (i.e. rings) that can be found.
Note, that rings may be nested, e.g. naphthalene molecule has actually three ... |
1ced31462e48f6098cb5b601404714b2224fd6cb71d981c8e44699e363bc2f2d | Python | 725 | 27 | import numpy as np
from abc import ABC, abstractmethod
class DistBase(ABC):
def __init__(self):
super().__init__()
@abstractmethod
def dist(self, x, y):
pass
class SimpleMatrixDist(DistBase):
def __init__(self, dist_matrix):
super().__init__()
self.dist_matrix=d... |
7b1bebf584cc17806dae9d0f6fade05bd103b620ae9cbb9f5f4d09f525eb5daf | Python | 725 | 16 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2024 Clinic for Diagnositic and Interventional Radiology, University Hospital Bonn, 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 ... |
ccded8d72a73b8bdb153eed949bc00c35919d1b467cb7472e17a4ef8c908bcfd | Python | 725 | 23 | import argparse
import json
import numpy as np
from scipy import stats
# For whole data prediction
# loc : mean of standardized expression from train data
# scale : 1
def postprocess(x):
return stats.norm.cdf(x, loc=0.06201038511068657, scale=1)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
... |
2f0b20e6b426eba0bf35633c53dc7ff3079913e458e74e5792a2176123c45972 | Python | 726 | 17 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2024 Clinic for Diagnositic and Interventional Radiology, University Hospital Bonn, 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 ... |
99920ad7343f8bdbec251d2ba676b375fd8249a58c718cca4c1834f9c1ea0a6c | Python | 726 | 28 | from typing import Protocol
import torch
from torch import Tensor, nn
from elasticai.creator.base_modules.math_operations import Quantize
class MathOperations(Quantize, Protocol): ...
class PReLU(torch.nn.PReLU):
def __init__(
self,
mathops: MathOperations,
num_parameters: int = 1,
... |
af459177ded25448114b02ff4498c91b728a1552d5f38fe0f63c255ae63a6548 | Python | 726 | 16 | from .conv1d import BatchNormedConv1d as BatchNormedConv1d
from .conv1d import Conv1d as Conv1d
from .hard_sigmoid import HardSigmoid as HardSigmoid
from .hard_tanh import HardTanh as HardTanh
from .leaky_relu import LeakyReLU as LeakyReLU
from .leaky_relu2 import LeakyReLU2 as LeakyReLU2
from .linear import BatchNorme... |
a061e99c21b9188f23835bb1e65668c4a37d99787f450e3807287855fa9b7ccc | Python | 727 | 26 | from .graph_element import GraphElement
class Node(GraphElement):
"""Class for representing a node in a graph."""
def __init__(self, features: dict = {}, position: list[float] = None, label: str = None, id: str = None):
"""Constructor
Args:
features (list[float]: List containin... |
f877d2f95a9064a872c8b64e6223dae8113d8152cb7f7b28f1ebac420a79f357 | Python | 727 | 20 | # coding=utf-8
# Copyright 2026 The Google Research Authors.
#
# 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 applicab... |
1a9be40c32399faa7eb8346634df1dc2f0ca7e3e9836d8d16c517b93be6e2504 | Python | 728 | 23 | # CREATE INITIAL RANDOM NETWORKS
import numpy as np
import pickle
import rewire
# network settings
n_vertices = 100
edges = int(np.round(2 * np.log(n_vertices) * (n_vertices - 1), decimals=0))
# number of different configurations
K = 150
# Weight distribution: normal
vertices_coord = {}
initial_matrix = {}
for k in... |
5f49224e398461fb44ec4b7e0d9305c8082888d6063462e7356720558f909efc | Python | 728 | 25 | import logging
c_formatter = logging.Formatter("%(asctime)s %(message)s", datefmt='%H:%M:%S')
f_formatter = logging.Formatter("%(message)s")
log_level = {
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR}
def set_logger(name=None, level="IN... |
717cfe9a35f7260914c742f7165cf3d669cd0c229265c40a35db5fb00f0381c2 | Python | 728 | 26 | __all__ = ["cancerGenomeInterpreterParser",
"drugGeneInteractionDBParser",
"hmdbParser",
"oncokbParser",
"siderParser",
"disgenetParser",
"gwasCatalogParser",
"intactParser",
"mutationDsParser",
"pathwayCommonsParser",
... |
d51d1d5ae0c7358fecb3c53a4fd839978d9fc0182e7b6a1311aa15fd116e9004 | Python | 728 | 18 | # +
import torch
import torch.nn as nn
import numpy as np
def keras_init(m):
if isinstance(m, nn.Conv1d):
fin, fout = nn.init._calculate_fan_in_and_fan_out(m.weight)
a = np.sqrt(6/(m.in_channels*(fin+fout)))
torch.nn.init.uniform_(m.weight, a=-a, b=a)
#print(m,nn.init._calculate_fa... |
1c25601aebb7e4fd3ccad7ed3595c202f38e9e6148177f81b0b95cd41d24dc8e | Python | 729 | 32 | import sys
from pybioshell.core.data.io import Pdb,create_seq_string
if len(sys.argv) < 2 :
print("""
Converts sequence in a PDB format to SEQ format.
USAGE:
python3 pdb_to_ss2.py input.pdb [input.ss2]
EXAMPLE:
python3 pdb_to_ss2.py 2gb1.pdb 2gb1.out
python3 pdb_to_ss2.py 2kwi.pdb
CATEGORIES: core... |
348d8e82c807f6206af65e6f07ee7abce83962cc9b3b2f80538544e424823b62 | Python | 729 | 23 | from pip._internal.distributions.base import AbstractDistribution
from pip._internal.index.package_finder import PackageFinder
from pip._internal.metadata import BaseDistribution
class InstalledDistribution(AbstractDistribution):
"""Represents an installed package.
This does not need any preparation as the r... |
62e736ab1c78ab10731f574c85e0916c279385d66504cf33e1f7e61961f0db84 | Python | 729 | 20 | import pandas as pd
import plotly.express as px
import matplotlib.pyplot as plt
import pdb
import seaborn as sns #Strange I know, but sns box plots look better
import plotly.graph_objects as go
df = pd.read_csv('JPSTHTable.csv')
dfstim = pd.read_csv('JPSTHTableStim.csv')
fig = go.Figure(data=go.Scatter(x=df['... |
fcf9364e2f5d4b5d9f397416938fd7fbb1fa85479b1bf11c1f8c1b689976f390 | Python | 729 | 27 | from __future__ import print_function
import importlib
import operator
packages = ['numpy', 'scipy', 'matplotlib', 'h5py', 'sklearn', 'networkx',
'cython', 'numexpr', 'tables', 'nitime', 'joblib', 'spams']
missing = list()
versions = dict()
for pkg in packages:
try:
mod = importlib.import_mod... |
282bf825b2fae48d02a825c46d743871d27e9af79944dc719673dd9ab0ccdff9 | Python | 730 | 38 | from elasticai.creator.hdl_ir import Edge, Node, Shape, ShapeTuple
from .ir2verilog import (
Code,
DataGraph,
Ir2Verilog,
PluginLoader,
Registry,
factory,
type_handler,
type_handler_iterable,
)
from .language import BaseWire, Instance, NullWire, VectorWire, Wire
from .templates import T... |
779be423889b8df6c48c7e329ffb5c12a50eef2fc22d42bbe1641a54214d8a12 | Python | 730 | 26 | from __future__ import annotations
import pytest
torch = pytest.importorskip("torch")
pytest.importorskip("matcalc")
pytest.importorskip("matgl")
pytest.importorskip("phonopy")
pytest.importorskip("seekpath")
from ase.build import bulk
from quacc.recipes.mlip.phonons import phonon_flow
def test_phonon_flow(tmp_pat... |
88f42ec724fb429df2672538f1bc1be37d8461cea78f6224d19ff4bd362632a2 | Python | 730 | 22 | # -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
# update in 7/14 correct onehot function
def onehot_test_label(num_classes,class4Decoder):
# num_classes : how many classes you decide to have
# class4Decoder : if dataframe can be directly applied
# if np, with length()
if type(class4Decode... |
9f233be63303046a1514eab0737ed9da454ab36d025f9a6ba718762d45fe9351 | Python | 730 | 26 | from unittest import TestCase
from torch import Tensor
def _unify_inputs(*inputs: float | list | Tensor) -> list[float | list]:
def unify(obj: float | list | Tensor) -> float | list:
if isinstance(obj, (float, list)):
return obj
return obj.detach().tolist()
return list(map(unify,... |
f7ad4eaf336e39270df6753d08229b6018812e7ae4daa4796b8646ed869fcefa | Python | 730 | 25 | # ## Random assignment as a control
from BEBE.models.model_superclass import BehaviorModel
import numpy as np
import pickle
import os
class random(BehaviorModel):
def __init__(self, config):
super(random, self).__init__(config)
self.rng = np.random.default_rng(self.config['seed'])
self.num_clusters = sel... |
0d6f8c3e16cc4f70a96c862c966d41445f85bc7e5e9637ba275a784700280792 | Python | 731 | 30 | import json
import os
import pandas as pd
import numpy as np
import torch
import pickle
import json
from datetime import datetime
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import roc_auc_score
def read_params():
"""
reading parameters
"""
params = dict()... |
3fa6aa77a8b29a038c2630a212836b240afa72a378368004d9acbe90b8f311b9 | Python | 731 | 24 | from elasticai.creator.file_generation.savable import Path
from elasticai.creator.file_generation.template import (
InProjectTemplate,
module_to_package,
)
class Middleware:
def save_to(self, destination: Path):
file_names = [
"icapInterface",
"InterfaceStateMachine",
... |
44061dfe50aa9c13a550884c22ef826330045fd40f81de516f34f1298d944a9d | Python | 731 | 16 | # -*- coding: utf-8 -*-
OPTIMAL = True
CONFIGS = [
(800, ["--search",
"astar(merge_and_shrink(merge_strategy=merge_precomputed(merge_tree=linear(variable_order=reverse_level)),"
"shrink_strategy=shrink_bisimulation(greedy=true),"
"label_reduction=exact(before_shrinking=true,before... |
4e4cfc6ec95c6f40edd91fb1959d3ee1fc27534767728ae39a95bc06dc30e6f4 | Python | 731 | 30 | import numpy as np
from sklearn.feature_selection import chi2
def chi_square(X, y):
"""
This function implements the chi-square feature selection (existing method for classification in scikit-learn)
Input
-----
X: {numpy array}, shape (n_samples, n_features)
input data
y: {numpy array... |
825bcad04aa77edc00e0e72fcf2e6f95ae7ba836a1b642d825d8b8c0f5ba97de | Python | 731 | 32 | # -*- coding: utf-8 -*-
#
# Populate namespace with io routines
#
# Import __all__ routines from local modules
from . import (
utils,
load_spy_container,
save_spy_container,
load_ft,
load_tdt,
load_nwb,
nwb,
mne_conv,
)
from .utils import *
from .load_spy_container import *
from .save_s... |
9d60da598f49d710d279cb87d5d816cd106e0749c42f3cf040f8537ab17e4918 | Python | 731 | 24 | from elasticai.creator.file_generation.savable import Path
from elasticai.creator.file_generation.template import (
InProjectTemplate,
module_to_package,
)
from elasticai.creator.vhdl.design.design import Design
from elasticai.creator.vhdl.design.ports import Port
class Ram(Design):
def __init__(self, nam... |
1e28ef9592539df822442f162d756183f9a4f5c14ccc47cb6e8a9d9ebc335b85 | Python | 732 | 27 | import cocotb
import pytest
from cocotb.triggers import Timer
from elasticai.creator.testing import CocotbTestFixture, eai_testbench
def adder_model(a: int, b: int) -> tuple[int, int]:
return a ^ b, 1 if a + b > 1 else 0
@cocotb.test()
@eai_testbench
async def adder_truthtable(dut):
input_a = [1, 0, 1, 0]
... |
9996c27d81d2fd5fe6c10c3acc1789fa55d1932e8037d21dfce79a98f361242c | Python | 732 | 21 | # coding=utf-8
# Copyright 2026 The Google Research Authors.
#
# 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 applicab... |
afb8c7570918427b3f16e69ed13ccbc26e73bb61510541093449330b782ecbbb | Python | 732 | 38 | # external
import pytest
# project
import textdistance
ALG = textdistance.LCSStr
@pytest.mark.parametrize('left, right, expected', [
# prefix
('ab', 'abcd', 'ab'),
('abcd', 'ab', 'ab'),
# middle
('abcd', 'bc', 'bc'),
('bc', 'abcd', 'bc'),
# suffix
('abcd', 'cd', 'cd'),
('abcd'... |
3004a7d173b79f3ad9cdd7b4b328cb227215839fa1a8bc9c361308bf7b2bc533 | Python | 733 | 23 | from cog import BaseRunner, Input
class Runner(BaseRunner):
def run(
self,
prompt: str = Input(description="The prompt", default="hello"),
temperature: float = Input(
description="Sampling temperature", ge=0.0, le=2.0, default=0.7
),
top_k: int = Input(descripti... |
7db60ee2a62bb532b31247769f51a47e7bf7f8044ce026eac614a368fb77186a | Python | 733 | 20 | from __future__ import absolute_import
import torch
# Device configuration
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
use_cuda = torch.cuda.is_available()
# FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor
def FloatTensor(tensor, device=0):
if use_cud... |
34e6d4252c7aa352e8d1536e8d2773c33d9f8e4e1f43fe9efc3fdaa91c500e8d | Python | 734 | 22 | """Tests for the h5ad per-file mapping loader/resolver."""
import json
from regtools.registration.h5ad_mapping import load_h5ad_map, mapping_for
def test_load_and_resolve(tmp_path):
m = {"/data/a.h5ad": {"obsm_key": "spatial", "order": "yx", "units": "um", "spacing_um": 25.0}}
p = tmp_path / "map.jso... |
b61c28ff6e491ffcdc65f5e53c6573e938747ed76c9fe15575484ca6e2286834 | Python | 734 | 15 | from requests.adapters import HTTPAdapter
from urllib3.poolmanager import PoolManager
'''
This adapter is necessary for the download logic when files are located in alt endpoints and the presigned urls
generated from the query-package-service contain '.' characters
Reason - VHostCalling format fails SSL certificatio... |
de45ce959c97062cebd9f078a69675784838ad9c1b435fffdaf99c78b69fd04d | Python | 734 | 18 | # coding=utf-8
# Copyright 2026 The Google Research Authors.
#
# 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 applicab... |
16b31ce6b9b1c439efef48d2270d888ef8af769505d9c433734c18d20e09bb4b | Python | 735 | 30 | import datetime
import os
import random
import numpy as np
import binutil
import arckit
print(arckit.load_data())
from dreamcoder.ec import commandlineArguments, ecIterator
from dreamcoder.grammar import Grammar
from dreamcoder.program import Primitive
from dreamcoder.task import Task
from dreamcoder.type import ar... |
bcdead6783608de06bdb8cd93da2993963b4ebb4426dae143293427ffa3e2fa9 | Python | 737 | 38 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 10 14:18:33 2022
@author: Raúl Luna
"""
import numpy as np
import random
def boost_node_selector(init_mat):
number_nodes = init_mat.shape[0]
deg_out = np.sum(init_mat > 0, axis=0, keepdims=False,)
nodes_sending = np.where((de... |
7f16d24298a533e5ab30d5130afdc084a9a70f55bd8b3c86d767476c6c452568 | Python | 738 | 21 | from ETL.Transform.tf_NIFTI2BIDS import NIFTI2BIDS
# Main program
if __name__ == "__main__":
"""
Main workflow to convert NIFTI files to BIDS format
1. Read the export_info.json file to get the subject information
2. Create the BIDS root and derivatives dir and Patients dir (if not exists)
3. Copy... |
ad607caff626b0794b97b100b568008ec51d03a0e60fb2b5ab022eec1ed2a6b0 | Python | 738 | 18 | """ qupath_processing version """
# Copyright (C) 2021 Blue Brain Project, EPFL
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... |
dc4150a7f202bbfb211f5f9306a865d1002eb0a08f0c53a580715e3785e8c16b | Python | 738 | 31 | """
For types associated with installation schemes.
For a general overview of available schemes and their context, see
https://docs.python.org/3/install/index.html#alternate-installation.
"""
SCHEME_KEYS = ["platlib", "purelib", "headers", "scripts", "data"]
class Scheme:
"""A Scheme holds paths which are used... |
4c22078750a8d97d7882c486e49623365cfd967fc0278c6a6cd452df98685b97 | Python | 739 | 21 | import numpy as np
from torch.utils.data import Dataset
class Dataset(Dataset):
def __init__(self,training_data):
self.fs_list = training_data['fs_0'].transpose()[:, 0]
self.ksw_list = training_data['ksw_0'].transpose()[:, 0]
sig = training_data['sig'].transpose()
self.norm_sig_lis... |
d1a9115594bf89c758ce1db52045804aafac1dd6000aa56e24613008c790644a | Python | 740 | 21 | import numpy as np
from torch.utils.data import Dataset
class Dataset(Dataset):
def __init__(self,training_data):
self.fs_list = training_data['fss_0'].transpose()[:, 0]
self.ksw_list = training_data['ksw_0'].transpose()[:, 0]
sig = training_data['sig'].transpose()
self.norm_sig_li... |
36e144a6bbb9b5945a0d2ac1d63809febf416297132e49967b40b925bf5d80f5 | Python | 741 | 34 | # Librairies
import os
import sys
code_path = os.path.split(os.path.split(os.getcwd())[0])[0]
sys.path.append(code_path)
import argparse
import json
from setting import *
from dataset import *
# Arguments
argParser = argparse.ArgumentParser()
argParser.add_argument("-n", "--name", type=str, help="dataset name (BRCA, ... |
8bead181534b982ca631ea65d51873944b2007931ed2d8281548661b97edfe17 | Python | 741 | 28 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import suites
import common_setup
REVS = ["issue269-base", "issue269-v1"]
LIMITS = {"search_time": 600}
SUITE = suites.suite_optimal_with_ipc11()
CONFIGS = {
"mas-label-order": ["--search", "astar(merge_and_shrink(shrink_strategy=shrink_bisimulation,... |
edddd3eff2b1df884706de7320711444bba28e20d65f4d0297eae1c20088b9fe | Python | 741 | 27 | import torch
import math as m
import numpy as np
class Rastrigin_func:
def __init__(self, a):
self.a = a
self.name = 'rastrigin'
self.formula = r'$\min\ f(x_1,x_2)={0} + x_1^2+ x_2^2 -{1}(\cos(x_1)+\cos(x_2))$'.format(2*self.a, self.a)
def function(self, x):
retu... |
12f5fc9377cd7ca9442263f9d76313ed377a991d418b08eed39e617e5b0a789b | Python | 742 | 24 | # coding=utf-8
# Copyright 2026 The Google Research Authors.
#
# 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 applicab... |
089d0e4c21c88d6034648552e2fa0e440b27d91e11d9c40112d3ec6442690126 | Python | 743 | 30 | import collections
# from jaraco.collections 3.3
class FreezableDefaultDict(collections.defaultdict):
"""
Often it is desirable to prevent the mutation of
a default dict after its initial construction, such
as to prevent mutation during iteration.
>>> dd = FreezableDefaultDict(list)
>>> dd[0]... |
544f011e87eb9c4c4ffaaa188b14e26ca096f854282f0e5b4b1050812771ee32 | Python | 743 | 25 | from dataclasses import dataclass
@dataclass(frozen=True)
class Alphabet:
"""
Represents the standard alphabet for amino acid sequences,
including a dash for gaps or unknown amino acids.
For example, "ARNDCEQGHILKMFPSTWYV-U"
"""
str: str
def __post_init__(... |
e753f264d2f395cc69cc5a96e385c37cb9522317cb9b83f38ae0f93bdc295af4 | Python | 743 | 19 | examples = dict(
out_of_bounds="""
>>> import h2o
>>> from h2o import H2OFrame
>>> from h2o.estimators.isotonicregression import H2OIsotonicRegressionEstimator
>>> from sklearn.datasets import make_regression
>>> import numpy as np
>>> h2o.init()
>>> X, y = make_regression(n_samples=10000, n_features=1, random_stat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.