sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
8f8f6461a4eb8ef3ae5706800cfb9593db0e70c9dc647c1ffd8d066071208667 | Python | 767 | 19 | """Pre-built reconstruction algorithms."""
from mrpro.algorithms.reconstruction.Reconstruction import Reconstruction
from mrpro.algorithms.reconstruction.DirectReconstruction import DirectReconstruction
from mrpro.algorithms.reconstruction.RegularizedIterativeSENSEReconstruction import (
RegularizedIterativeSENSER... |
b34511f4274a57217d001485a2708bf0c4399ea7c1295cf8077437dc1a73eccf | Python | 767 | 31 | """
mafft3di.py
Run MAFFT with the 3di matrix. Directly passes arguments to MAFFT, but specifies the matrix as the 3di matrix
Running with:
--maxiterate 1000 --globalpair
is a good idea for alignments of fragments of single domains
--------------------------------------------------------------------------
"""
impo... |
1885606763e7f3b83073573656947478159cbf41f1e5cddd11469dba704f58d3 | Python | 768 | 27 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
def test_pickle_compat_construction():
# this is testing for pickle compat
# need an object to create with
with pytest.raises(TypeError, match="Must pass both levels and codes"):
pd.MultiIndex()
def test_multiinde... |
8dccea4c98127c3caf16be5635a566deb3326b073a6476b820a0d977ead33e52 | Python | 768 | 30 | import sys
import math
# run with::
# ./bin/vg view -a alt.mega.gam | grep -o "\"length\": [-]*[0-9]*" | cut -f 2 -d ":" | python scripts/calc_insert.py
def calc_mean(vals):
return float(sum(vals)) / float(len(vals))
def calc_sd(vals, mean):
sq_err_sum = 0.0
for i in vals:
sq_err_sum += (float(i)... |
0dc1c06a7ba4e56c88ef8ed8320cfa48e8d71b924e7d832335e46ba3480a19b8 | Python | 769 | 19 | # Copyright 2018-2022 Xanadu Quantum Technologies 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... |
b12b3cc516ffecbf5daede6cc929298ca73e6d5c2961c197d7a9f61fb85da2c7 | Python | 771 | 22 | '''Check that configurable parameters are propagated correctly.'''
import numpy as np
from kilosort.spikedetect import template_centers
def test_dmin():
settings = {'dmin': None, 'dminx': None}
ops = {'xc': np.array([10, 20, 30]), 'yc': np.array([40, 40, 60]),
'settings': settings}
ops = templ... |
0c763d7ca971196f862989696eef522a87cf7ce2c325347d83e9cab5c09d64db | Python | 772 | 22 | import sys
from pybedtools import BedTool
#using bed file with palindrome coordinates from palindrover, identify the coordinates of spacers
if len(sys.argv) != 2:
print("Usage: python script_name.py input_bed_file.bed")
sys.exit(1)
bed_file_path = sys.argv[1]
bed_entries = BedTool(bed_file_path)
bed_entry_l... |
2fee9d2b8fddc679ea1d7e0221d4bcf25cb0f63a94b7069e4bfb1dbf6d576d94 | Python | 772 | 31 | import vegas
import numpy as np
from outputsplitter import log_stdout
def f(x):
return x[0] * x[1] ** 2
m = vegas.AdaptiveMap([[0, 1], [0, 1]], ninc=5)
ny = 1000
y = np.random.uniform(0., 1., (ny, 2)) # 1000 random y's
x = np.empty(y.shape, float) # work space
jac = np.empty(y.shape[0], float)
f2 = ... |
3517eb772f9d8e6bdd0fcf7fcb1ac1986cf6381f117c326085ac462cc44dd7d1 | Python | 773 | 19 | import numpy as np
import pandas as pd
def cohens_d(data: pd.DataFrame, group: pd.Series, regex: str, flip: bool = False) -> pd.Series:
df_group = data.groupby(group)
n = df_group.count().filter(axis=0, regex=regex)
s = df_group.std(ddof=0).filter(axis=0, regex=regex)
xbar = df_group.mean().filter(axi... |
76f1572d7b91066688765d6bbf9082af4d998bb4e7c1f0ef0331466fcd7663e0 | Python | 773 | 30 | #!/usr/bin/env python3
"""
Description:
Retrieves a p-value threshold to be used in detecting significant DTU events. This module determines p-value threshold based on the user-defined parameter K and is obtained as the "K x N"-th smallest p-value among the N sampled by SPIT-Test.
Usage:
./get_p_cutoff.py -k <... |
938586296e9f120ce6f3fca9c0be080d8497b8b799963546d85f32963e3091fd | Python | 773 | 20 | from setuptools import setup
setup(
name="fmriprep-denoise-benchmark",
version="0.0.1",
description="Benchmarking fmriprep denoising strategies on functional connectomes.",
url="https://github.com/SIMEXP/fmriprep-denoise-benchmark",
author="Hao-Ting Wang",
license="MIT",
packages=["fmriprep... |
254d7681454d83bf938e962d6b724257896dc8c80d64a7ddb5b6805f2d20977b | Python | 774 | 24 | #! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this wo... |
33ef8523e9e28dfcf94a7305e2cb9a6508efe83aaa9d3e99dee3a42f0e350db6 | Python | 775 | 21 | #
# module for sampling residues from proteins
#
import Bio.PDB as pdb
import numpy as np
# function to sample a random residue of a given amino acid type from a protein structure
def sample_amino_acid_from_protein(struct,protein,aa):
# parser = pdb.PDBParser(QUIET=True)
# struct = parser.get_structure(protein ... |
ba23b2403def8c70dafc89e006a603f304a40e74467dba964c6bfb7b733a29ac | Python | 776 | 23 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for GCPNet (https://github.com/BioinfoMachineLearning/GCPNet):
# ----------------------------------------------------------------------------------------------... |
fdf169f5b5ed8f431c5a4e928b7a1d54cbf9d4c0e61e290fc58a68c310b95c5b | Python | 777 | 29 | #! /usr/bin/env python
from sys import argv
filein = argv[1]
fileout = argv[2]
d = {}
with open(filein,'r') as fin:
for line in fin:
method, condition, occ, dMS = line.rstrip().split()
key = method + "#" + condition
occ = float(occ)
dMS = float(dMS)
if key not in d:
... |
30c542e9f4479277a21bce84ccd2b030f52d91434038e0dce52c490aed8dd8ba | Python | 778 | 23 | import logging
import torch.nn as nn
from .scale_factor import ScaleFactor
def ensure_fitted(module: nn.Module, warn: bool = False):
for name, child in module.named_modules():
if not isinstance(child, ScaleFactor) or child.fitted:
continue
if child.name is not None:
name ... |
99a27da518b5b13453e6d449c814dab675664fa07eb8485dbe10e7367cb53be8 | Python | 778 | 26 | import numpy as np
import pandas as pd
def test_iat(float_frame):
for i, row in enumerate(float_frame.index):
for j, col in enumerate(float_frame.columns):
result = float_frame.iat[i, j]
expected = float_frame.at[row, col]
assert result == expected
def test_iat_dupli... |
333c0400cbc132d767d3d5c0b58abfe0ab6876312826404baf43d5105caad07f | Python | 779 | 30 | # JN 2016-09-05
"""
create cluster groups in an existing sorting session
useful for testing purposes
"""
from __future__ import print_function, division
import os
from argparse import ArgumentParser
from combinato.cluster.create_groups import main as create_groups_main
def main():
"""
parse arguments
"""... |
a6b01c583b2d3f595ab7646ad2c17eeb6dcf560a7742c3dcb4690c28026899be | Python | 780 | 29 | # JN 2015-01-13
from __future__ import absolute_import, print_function, division
import logging
import matplotlib.pyplot as mpl
from .. import options
logger = logging.getLogger(__name__)
def plot_temperatures(tree, used_points):
"""
show which clusters were selected in temperature plot
"""
upto_lin... |
f07538f1dea3dfdd38001c66fda9c7256e06d8b618b54680d1ab80a7ccdf424f | Python | 780 | 27 | import math
from StimulationProcess.BasicStimulationProcess import BasicStimulationProcess
from psychopy import visual
class PrepareProcess(BasicStimulationProcess):
def __init__(self) -> None:
super().__init__()
def change(self):
self.controller.currentProcess = self.controller... |
81e72ce7e750f646c8b18d953069ea5501ad72543bc12b885604d2e741a395d2 | Python | 781 | 23 | """Tests for fill_range_"""
import pytest
import torch
from mrpro.utils import fill_range_
@pytest.mark.parametrize('dtype', [torch.float32, torch.int64], ids=['float32', 'int64'])
def test_fill_range(dtype):
"""Test functionality of fill_range."""
tensor = torch.zeros(3, 4, dtype=dtype)
fill_range_(tens... |
e0a1d42fc4f5a1b50154b0644c9cfe84b3b21f254690558c199de32adb0b1345 | Python | 781 | 17 | """GUI for analysis and visualization of deformability cytometry datasets
Copyright (C) 2019 Paul Müller
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
o... |
e1c9333e7cc3fc8f3a1924d7d0f240415c564f759e247d1af0e10d11911fdc36 | Python | 781 | 18 | # Copyright 2026 Xanadu Quantum Technologies 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 agre... |
f02ddd6c3e8aaddc8f0c62f5fe887c3ddede94d118eac4f5cebb63023d3279fa | Python | 785 | 25 | import socket
import pytest
from shapeout2.gui import update
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect(("www.python.org", 80))
NET_AVAILABLE = True
except socket.gaierror:
# no internet
NET_AVAILABLE = False
@pytest.mark.skipif(not NET_AVAIL... |
f3de34e00a9ed873c3c0ae58c7b35fea646416fae8c825ded269540d39f70009 | Python | 786 | 21 | # AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"canonicalize_with_dict": "01_data.ipynb",
"generate_buchwald_hartwig_rxns": "01_data.ipynb",
"randomize_smiles": "06_data_augmentation.ipynb",
"precursor_permutation_given_index": ... |
8f88b38cc2e26803878ddae6eb587a08a0e5afae14de4217f5738eb4dbf79a80 | Python | 787 | 31 | import dclab
import matplotlib.pylab as plt
# dataset
ds = dclab.new_dataset("fluorescence/fluorescence.rtdc")
kde1 = ds.get_kde_scatter(xax="time", yax="deform")
kde2 = ds.get_kde_scatter(xax="time", yax="area_um")
scatkw = {"marker": ".",
"s": 2,
"cmap": "jet",
"alpha": .7}
fig = plt... |
adcc2bd4e8b0027fcdba9f001ddb20ce056b27609aa5c9296d6115fc6b127341 | Python | 787 | 27 | from . import config_handler
class Paths:
def __init__(self, json_file):
""" Initializes the paths class.
args:
json_file: json file to read from
"""
self._json_file = json_file
self._jsons = config_handler.read_json(json_file)
def __call__(self, key):
... |
be83ae9e2eec2ad52c3e82b343eb9944b1d9ffe12035dce32bcbafa16e89f2a8 | Python | 787 | 22 | import sys
import pandas as pd
import argparse
import pdb
#int2docname = {1:'Boar', 2:'Aqua', 3:'MatchstickSeller', 4:'KingOfBirds', 5:'Elvis', 6:'MrSticky', 7:'HighSchool', 8:'Roswell', 9:'Tulips', 10:'Tourettes'}
df = pd.read_csv(sys.stdin, sep=' ')
df['docid'] = df['docid'].replace(10,'Tourettes')
df['docid'] = d... |
4f68d2ff639621bf7144cdee47ddf211098f734e839b9affafaed8860f4dab58 | Python | 788 | 30 | import sys
import glob
import pandas as pd
import numpy as np
import h5py
file_list = sys.argv[2:]
print(file_list)
total_data = pd.DataFrame()
for ff in file_list:
data = pd.read_csv(ff, sep=',', index_col=0, header=0)
total_data = total_data.append(data)
print(total_data.shape)
labels = total_data['ass... |
0ef8d62bf5ad191c4479e016dbcb1f90536b61b39420253b8d6ec2d0c2421bd6 | Python | 789 | 28 | """Author-defined IntrinClock and PhenoAge variants."""
import torch
from ._base_models import pyagingModel
from ._models import IntrinClock
class IntrinClock370(IntrinClock):
"""The original cv.glmnet model at lambda.1se, as used by the author demo."""
class DNAmPhenoAgePRC(pyagingModel):
"""Polycomb-rel... |
dedf40c27180aa6386cdd43463bc9e67227a1048fd941fe38f46fd0137e44d0b | Python | 789 | 30 | import sys
sys.path.append('.')
from TrainingProcess import TrainingProcess
from OperationSystem.Streaming.NeuroScanEEG import NeuroScanEEGThread
from CommonSystem.Config import Config
# 实验参数
config = Config()
config.expINFO(winLEN=1,lag=0.14)
config.connectINFO(streaming_ip='192.168.31.70',streaming_port=4... |
120ceaa3ce5c88c4bc951339b969e0e0ccfce413e92e44605db5c364f60d385e | Python | 790 | 32 | import dclab
import matplotlib.pylab as plt
# dataset
ds = dclab.new_dataset("fluorescence/fluorescence.rtdc")
evts = {"reference": 397,
"debris": 1979,
"doublet": 9430,
"aggregate": 2223,
}
# plot
fig = plt.figure(figsize=(7, 3))
for ii, key in enumerate(evts.keys()):
evt = ev... |
a6069ad83502ef8229a1840dd046d6cc59238fedc6b1d7ef4314439572826179 | Python | 790 | 33 | from pandas.core.indexers.utils import (
check_array_indexer,
check_key_length,
check_setitem_lengths,
disallow_ndim_indexing,
getitem_returns_view,
is_empty_indexer,
is_list_like_indexer,
is_scalar_indexer,
is_valid_positional_slice,
length_of_indexer,
maybe_convert_indices,... |
f7c33ebb9fd5188f3bed819781f9e7dfd82f35b8c2ad8aae55dcd91411be3771 | Python | 791 | 31 | import sys
sys.path.append('.')
from TrainingProcess import TrainingProcess
from OperationSystem.Streaming.NeuroScanEEG import NeuroScanEEGThread
from CommonSystem.Config import Config
# 实验参数
config = Config()
config.expINFO(winLEN=1,lag=0.14)
config.connectINFO(streaming_ip='192.168.31.70',streaming_port=4... |
20268b0dfa572be08f4fa726708e026579214fb91498383bd516f7e2cca24b83 | Python | 793 | 30 | import numpy as np
import matplotlib.pyplot as plt
folder = "/projects/LEIFER/francesco/pumpprobe/instrument_characterization/tuningthickness/20220222/stepbystep_20220222_093056/"
x = np.loadtxt(folder+"z.txt")[1:-2]
y = np.loadtxt(folder+"bead.txt").T[1]
y -= y[0]
y /= np.max(y)
fig = plt.figure(1)
ax1 = fig.add_su... |
8d70a4272c8009f74e36dadda12ff57c8c1aaef8a0b86a515e9d1d88c757d254 | Python | 794 | 36 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sys
import matplotlib.ticker as ticker
import matplotlib.transforms as transforms
from pathlib import Path
import math
from statistics import mean, stdev
import seaborn as sns
from plotting_functions import *
#create figure and set font
fig... |
d7e6312d7a0d764b6943bff5a9a6e2a85276ddef63a828e0a54c1adb5578d7fc | Python | 794 | 30 |
from torchsummary import summary
import op_dataset as dataset
from model_unet import Unet
from model_liteunet import LiteUnet
from model_fcn import VGGNet, FCNs
from model_deeplabv3 import DeepLabV3
from model_miniunet import MiniUnet
from model_alexnet import AlexNet
def model_summary(num_classes =dataset.num_clas... |
061ca071cec47071441ddca32e9ba80070d1d7cac3e557d3cfce9290edbcb867 | Python | 795 | 17 | from monai.data.image_dataset import ImageDataset
from pathlib import Path
from numpy import array
from copy import deepcopy
class CTImageFolder(ImageDataset):
def __init__(self, folder: Path, *args, **kwargs) -> None:
class_folders = [f for f in folder.iterdir() if f.is_dir()]
self.mapping_label_... |
1335620c9072ffcf606a30bd73ba9f32007c7b8c0797bee39fadf21947915dc2 | Python | 795 | 29 | import torch
@torch.jit.script
def dx_mic_ortho(dx, box):
"""Minimal distance vectors in orthormbic boxes.
References:
- https://en.wikipedia.org/wiki/Periodic_boundary_conditions
- https://zenodo.org/record/894522
"""
dx -= (dx > box/2) * box
dx += (dx < -box/2) * box
return dx
de... |
c1af303b7a06221e3a1fb980f5278ccd8b1c0f171cc1e7cb628598c4a43f0081 | Python | 795 | 18 | import sys, argparse
import pandas as pd
argparser = argparse.ArgumentParser('''
Calculates the difference between two user-specified fields in a space-delimited table of reading time data, and appends it as an additional field to the output.
''')
argparser.add_argument('cols', nargs='*', help='Names of columns to cal... |
458e599a3e1d5a7a08cae9e9120db3ca76528a80f57465b0db3c69b9b1c267a7 | Python | 796 | 38 | from abc import ABCMeta, abstractmethod
from EventController import EventController
class BasicStimulationProcess:
def __init__(self) -> None:
pass
@abstractmethod
def initial(self, controller, viewcontainer, messenager):
self.controller = controller
self.messenager =... |
4c4964a2f4cb8f522b9c15d7d0e96c53f83b3ce489a79efb99158a7507eba303 | Python | 796 | 25 | import tensorflow as tf
import sys
def run(model_dir, name):
graph = tf.Graph()
with graph.as_default():
sess = tf.Session()
ckpt_path = tf.train.latest_checkpoint(model_dir)
saver = tf.train.import_meta_graph('{}.meta'.format(ckpt_path))
saver.restore(sess, ckpt_path)
... |
ef48dadc2c6590cf974ae50ce2e1d91c8daa95ab7baf526720e7b7519bc3f34f | Python | 797 | 17 | from monai.data.image_dataset import ImageDataset
from pathlib import Path
from torch import tensor
from copy import deepcopy
class CTImageFolder(ImageDataset):
def __init__(self, folder: Path, *args, **kwargs) -> None:
class_folders = [f for f in folder.iterdir() if f.is_dir()]
self.mapping_label... |
ac64be69ccd24b6d21cce3853f3e9b1c2028f353b6e347b7e13cee3cba6372db | Python | 800 | 27 | from .resnet3d import Resnet3DBuilder
from .densenet3d import DenseNet3DImageNet121, DenseNet3DPPI, DenseNet3D
def getModel(modelName, inputsize):
if modelName == 'Resnet3D':
resnet3D = Resnet3DBuilder.build_resnet_50(inputsize, 2)
return resnet3D
elif modelName == 'DenseNet3D':
retur... |
b04f83d441d0e4ce01bcff4d29c9e7256fda5e3fc8093bdd4c1aad8426368e78 | Python | 800 | 24 | from pandas.errors import Pandas4Warning
import pandas as pd
import pandas._testing as tm
class TestFillNA:
def test_fillna_timedelta(self):
# GH#11343
idx = pd.TimedeltaIndex(["1 day", pd.NaT, "3 day"])
exp = pd.TimedeltaIndex(["1 day", "2 day", "3 day"])
tm.assert_index_equal(i... |
c7bc148abb5db017389b61694632244fb17e64591ff0ad26b976d2dea16124bf | Python | 801 | 14 | from scanometrics.cross_validation.loocv import LOOCV
import os
bids_database = 'CH-First-Insel'
proc_pipeline = 'freesurfer'
normative_model = 'Polynomial'
load_subject_options = {'cov2float': {'sex': {'M': 0, 'F': 1},
'scanner': {'Skyra_fit': 0, 'MAGNETOM_Vida': 1},
... |
1edc85dd0597ed69c63d41f73fe4da537c5b1fb9b60619da62d98b8381894b50 | Python | 803 | 35 | """Authentication helpers.
- Password hashing (bcrypt).
- JWT access-token + refresh-token encoding / decoding.
- FastAPI dependencies for current-user resolution.
Trusted publisher / OAuth integrations come later as plugins.
"""
from pycaret_server.auth.deps import (
CurrentUser,
get_current_user,
requi... |
dbadfdc494cc1fed15073293de69e50c8d16ba776ff614f56994391e43aabe17 | Python | 803 | 29 | """replace PR numbers and github usernames with links"""
from __future__ import annotations
import re
from utils import root_dir
change_log = root_dir() / "docs" / "source" / "changelog.md"
with open(change_log) as f:
lines = f.readlines()
with open(change_log, "w") as f:
for line in lines:
if mat... |
451cc59e703644c1546124ea6a26db07ec51d80263b3027964906c6f470c27e9 | Python | 806 | 31 | from pyaging.utils._utils import progress
class RecordingLogger:
def __init__(self):
self.events = []
def start_progress(self, message, indent_level):
self.events.append(("start", indent_level))
def finish_progress(self, message, indent_level):
self.events.append(("finish", inden... |
485b033da51027a577d93e3a296c3d92f7751f081359188d367657b1678f4b9f | Python | 806 | 20 | # -----------------------------------------------------------------------------
# Copyright (c) 2019, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softw... |
08dad8153e6925e97edba9c726c4e73ed5e60f28b4caeb92d3964c5672d0706c | Python | 807 | 30 | #!/usr/bin/env python
'''
Testcases for the neural network prediction
'''
import windseer.utils as utils
import windseer
import os
import torch
import unittest
windseer_path = os.path.dirname(windseer.__file__)
testdata_folder = os.path.join(windseer_path, 'test', 'testdata')
test_dataset = os.path.join(testdata_fol... |
4d1c3e1f4b3aa826d7a1028cd35fd28b180f382466ada8582a99630f21f05a42 | Python | 807 | 24 | """
Implementation of pandas.Series.str and its interface.
* strings.accessor.StringMethods : Accessor for Series.str
Most methods on the StringMethods accessor follow the pattern:
1. extract the array from the series (or index)
2. Call that array's implementation of the string method
3. Wrap the result ... |
7a9d87f67bbde47b142f0c34fa0817a3c554a3e11e32e916c0da70f196ec1b47 | Python | 807 | 31 | # -*- coding: utf-8 -*-
"""The check functions."""
# Authors: Gianvittorio Luria <luria@dima.unige.it>
#
# License: BSD (3-clause)
def _check_h5_installed(strict=True):
"""Aux function."""
try:
import h5py
return h5py
except ImportError:
if strict is True:
raise Runtime... |
45060ea9f7bb0dc87ab41fa59d44b1d0998987037b0a8c422ba0379eaed00b48 | Python | 808 | 23 | import numpy as np
from src.np_implementation.activation import tanh as f
def _generate_noise(mean=0., sd=0.1, shape=None):
return np.random.normal(mean, sd, shape if shape is not None else 2)
def generate_random_nonlinear_data(sampling_frequency, n_dimension, n_samples, x, C, A, seed=0, dt=None):
data = n... |
5ba2b2eb6236f2db48fec31c43987da24b3da96fe0b9c984b51e0fbd6f768171 | Python | 809 | 29 | import torch
from torch import nn
from ..convs import GatedGCN
# Typing
from torch import Tensor
from typing import List, Optional, Tuple
class GatedGCN_Net(torch.nn.Module):
"""GatedGCN model from https://arxiv.org/abs/2003.00982.
"""
def __init__(self, init_embed, output_layer, dim=100, num_convs=3, o... |
62f24e7a2562aff9586c43461e6cf5c4b3cbd016d2215be2448f34581f4f448a | Python | 810 | 23 | """Softly gradient-coupling optimizers.
This module provides a wrapper around any Pytorch optimizer to implement
gradient coupling at the beginning of a step.
"""
import torch.optim as optim
from torch.optim.optimizer import required
class CoupledSGD(optim.SGD):
def __init__(self, params, model, lr=required, mo... |
1bb460601b4cb370e15efa7a09de8bfbae4408f570be046e3e226870d39f8602 | Python | 813 | 31 |
import json
from matplotlib import pyplot
import numpy
from sklearn import neighbors, ensemble, svm
with open("meniscus_measurements.json") as mm:
data = json.load(mm)
data2 = {}
for fname in data:
table = numpy.array(data[fname])
data2[fname] = table
for fname in data2:
clf = neighbors.LocalO... |
acf147749616e3d9aafbf0e81a2ce3ef7c6c83b25805634e4e26f36fdaf76062 | Python | 813 | 23 | import os
# import cloudpickle
import compatibility
import numpy as np
from . import parent_classes
from single_cell_parser.cell import Cell
from single_cell_parser.serialize_cell import save_cell_to_file
from single_cell_parser.serialize_cell import load_cell_from_file
def check(obj):
'''checks whether obj can be... |
ee28ca58783d7a03ee27815237636645d76f49e7bf20f34e3cafc446957fdc62 | Python | 813 | 32 | import argparse
import h5py
import nibabel as nib
import numpy as np
import os
DIR = os.path.dirname(os.path.realpath(__file__))
print(DIR)
# %%
parser = argparse.ArgumentParser(description='convert .h5 to .nii')
parser.add_argument('--input_data',
default='meas_MID00402_FID02551_EPISeg2_67_1p0is... |
3d96feeec6c07590e824f294c520886ae903ce444dc249c2845a9584493defdc | Python | 815 | 35 | import time
from ApplicationProcess.BasicAppProcess import BasicAppProcess
from psychopy import visual, core, event
class AppinitProcess(BasicAppProcess):
def __init__(self) -> None:
super().__init__()
def change(self):
self.controller.currentProcess = self.controller.appdisplayPr... |
060fdb2d929c2202a4c3652f861d6ae58591fbc5f4ac039a76998b40e0270a49 | Python | 816 | 33 |
import os
import subprocess
import math
import shutil
import numpy as np
from os.path import isfile, join
from PIL import Image
import random
import csv
from datetime import datetime, timedelta
path1 = 'phase_recognition_annotations/'
path2 = 'Training_Dataset/'
case_list = os.listdir(path1)
case_list.sort()
for... |
bcbc6387bc26a2f651a04b94db5edc584218c54a87b439b6835cf68fffc47f5b | Python | 816 | 23 | from scipy import sparse
import numpy as np
from scipy import sparse
import scipy
# 先分割
# 再合并
# 再保存
if __name__ == "__main__":
dataset= sparse.load_npz(r'/sub_datasets/dataset8/matrix_api_benign_8.npz')
dataset1 = sparse.load_npz(r'/sub_datasets/dataset8/matrix_api_mal_8.npz')
permission_mat =... |
4136a3d91c4a1a40215a981b02df5d72b279c4110ba10e0cd76b9ceeb9a19a11 | Python | 817 | 17 | # Copyright 2018-2024 Xanadu Quantum Technologies 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... |
ecf63a26dd7f0c4a839c2e19857c3a3a42fe4d2eadfbe3ae533bfc36dccb26a7 | Python | 817 | 19 | # Copyright 2018-2021 Xanadu Quantum Technologies 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... |
977eab133fbfc6320a5f6e94d2a8c8aa867dedd5b27271d6b8b678bdbbdecd0c | Python | 818 | 26 | import rdkit
from rdkit.Chem import PandasTools
import pandas
from rdkit import Chem
import os
dir = os.path.abspath(os.path.dirname(__file__))
def drop_error_mols(path=dir+"/classification/N6512.csv"):
df = pandas.read_csv(path, sep="\t", header=0)
none_list=[]
for i in range(df.shape[0]):
if ... |
a73280e6313bf054fa03cf10af42173a1b0cb5ab93c308c5678f57b75c696079 | Python | 818 | 26 | import setuptools
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='GCNFrame',
version='0.1.2',
packages=find_packages(),
zip_safe = False,
url='https://github.com/deepomicslab/GCNFrame',
license='MIT',
author='WANG Ruoha... |
54051c07a6645d92d448837ded6f3742722daefb4628f62be794d960598a76ef | Python | 819 | 34 | """Import fiberphotopy."""
# flake8: noqa
__version__ = "0.2.31"
from .plotting.fp_viz import (
fp_traces_panel,
plot_dff_data,
plot_fp_session,
plot_raw_data,
plot_single_trial,
plot_trial_avg,
plot_trial_heatmap,
plot_trial_subplot,
)
from .plotting.fp_viz_utils import set_color_pale... |
b89208672438768f5ede1e4a25370166ef3890d8c46d189753deded162bcc613 | Python | 822 | 36 | """
Assertion helpers and base class for offsets tests
"""
from __future__ import annotations
def assert_offset_equal(offset, base, expected):
actual = offset + base
actual_swapped = base + offset
try:
assert actual == expected
assert actual_swapped == expected
except AssertionError a... |
acac9be8c4601f7fe68ab6b35dc7699272dbc0c924d5324aa338a8f1011a14f6 | Python | 824 | 31 | import numpy as np
import pytest
import pandas as pd
def test_contains_nan(using_nan_is_na):
# GH#52840
arr = pd.array(range(5)) / 0
assert np.isnan(arr._data[0])
if using_nan_is_na:
assert arr.isna()[0]
else:
assert not arr.isna()[0]
assert np.nan in arr
def test_hasnans_f... |
e85e099d5d730805d4b4014c557ea84f92a989731313cffaf049fa79ded57233 | Python | 824 | 30 | from abc import ABC, abstractmethod
import struct
class Socketmaker(ABC):
"""
Abstract base class for managing the socket connection to external
programs (e.g., MLC tracking software). Intended to work in a context
manager (see test below) to ensure the closing of the socket connection
upon... |
2b49bae95f156fbb7285441298a65b3ec3817b958790dade50bb95dfbbfd4fba | Python | 825 | 23 | import numpy as np
import pandas as pd
class TestIsMonotonic:
def test_is_monotonic_numeric(self):
ser = pd.Series(np.random.default_rng(2).integers(0, 10, size=1000))
assert not ser.is_monotonic_increasing
ser = pd.Series(np.arange(1000))
assert ser.is_monotonic_increasing is Tru... |
462d04b9d38851e287473d14ad7e4ff48a8f0a2f1800292bc1fe6f3ecf830647 | Python | 825 | 31 | """Screenshots for quick guide extensions"""
import pathlib
import sys
from PyQt6 import QtCore
from PyQt6.QtWidgets import QApplication
from shapeout2.gui.main import ShapeOut2
from shapeout2.gui import preferences
data_path = pathlib.Path(__file__).resolve().parent / ".." / "data"
app = QApplication(sys.argv)
QtC... |
9d70092f36842f9a244509e4e9e7da9754b5ab6eccf58b530a1a0427fcfc434f | Python | 825 | 36 | __all__ = ["MassSpectrum"]
from dataclasses import dataclass
import numpy as np
import numpy.typing as npt
MassArray = npt.NDArray[np.float32]
IntensityArray = npt.NDArray[np.float32]
@dataclass(frozen=True)
class MassSpectrum:
mz: MassArray
intensity: IntensityArray
ms_level: int
run_name: str
... |
0133ed88f2050eb2371d5764b97205c0702cae3ecbbb65e1482c5f267ec6c5c5 | Python | 826 | 21 | # Copyright (c) Twisted Matrix Laboratories.
#
# Copied from Twisted (http://twistedmatrix.com/), see
# http://twistedmatrix.com/trac/browser/trunk/LICENSE for the license.
#
# This makes sure that users don't have to set up their environment
# specially in order to run these programs from bin/.
# This helper is share... |
e7eaab6e4a5b0c84d6baba4d797c74f5de1f1cf16869b926c5db331e4d61989b | Python | 826 | 20 | """Tests the iterative Walsh algorithm."""
import torch
from mrpro.algorithms.csm import inati
from mrpro.data import SpatialDimension
from tests import relative_image_difference
from tests.algorithms.csm.conftest import multi_coil_image
def test_inati(ellipse_phantom, random_kheader):
"""Test the Inati method."... |
e82510429270783f35fa602e1d43d206a48af0cf8c38632f355167a3a85d9b1c | Python | 826 | 20 | """Tests the iterative Walsh algorithm."""
import torch
from mrpro.algorithms.csm import walsh
from mrpro.data import SpatialDimension
from tests import relative_image_difference
from tests.algorithms.csm.conftest import multi_coil_image
def test_walsh(ellipse_phantom, random_kheader):
"""Test the Walsh method."... |
14880b11e8c2f181092277a5bc019e9189b32bca8dace842c53846d57b1bc4bf | Python | 829 | 32 | __all__ = ["ProgressProto", "ProgressFactoryProto", "TqdmProgressFactory"]
from typing import Generic, Iterable, Protocol, TypeVar, Union, runtime_checkable
import tqdm
T = TypeVar("T", covariant=True)
@runtime_checkable
class ProgressProto(Generic[T], Iterable[T], Protocol):
def update(self, n: Union[float, N... |
58d81b30a9e853dcd749c10815865b39e0eddacc5610fdd61d7b0ef1965694b9 | Python | 829 | 24 | #!/usr/bin/env python3
"""Fast pre-submission checks that do not access imaging or targets."""
import numpy as np
import run_end_to_end as workflow
train = {"r2_conventional": 0.8}
validation = {
"r": 0.7,
"r2_conventional": 0.5,
"rmse": 1.0,
"prediction_sd_ratio": 0.8,
"calibration_slope_y_on_pr... |
9864c5ade927cfdc49270e28587f410b7cfdb33f7092e097d4712c52b89756ba | Python | 829 | 32 | import os
import random
import copy
import keras
import shutil
import numpy as np
from tqdm import tqdm
from glob import glob
from skimage.transform import resize
def load_image(config, status=None):
x = np.squeeze(np.load(os.path.join(config.data, 'x_'+status+'_64x64x32.npy')))
y = np.squeeze(np.load(os.... |
d9ff5527bfcd3488e6a95d7a710588f5b898fc2654a9b6f3e677aa5d37c05c49 | Python | 829 | 31 | import sys, os, re
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts'))
import tree
def kill_traces(T):
if len(T.ch) == 1 and len(T.ch[0].ch) == 0:
if T.ch[0].c.startswith('*'):
tmp = T
while len(tmp.p.ch) == 1:
tmp = tmp.p
... |
e749694db008c311b0a1b8f5e6da12f418ddc17a2812d3346b33acc9df6831cd | Python | 829 | 29 | from cffi import FFI
ffibuilder = FFI()
# specify functions, etc made available to Python
ffibuilder.cdef("""
void batch_fcn(double ans[], double x[], int n, int dim);
""")
# specify code needed to build the module
ffibuilder.set_source(
"ffcn_cffi", # Python extension module (output)
"""
... |
2ffec56a912a02a06354c33b6c8c137fda9a497775a53715e9f032efa08cae55 | Python | 833 | 25 | #!/usr/bin/env python
# from https://gist.githubusercontent.com/thewtex/8263132/raw/079eca1603ed750d1707516ef51eed33e4934b44/vtk-unstructuredgrid-to-stl.py
"""Convert PolyData in .vtk files to STL files."""
import sys
import vtk
if len(sys.argv) < 2 or sys.argv[1] == '-h' or sys.argv[1] == '--help':
print('Usage:... |
5a41acc37f2c75e904324bb071f2cbf221b2a8e63b664ea9641e729d0022a964 | Python | 834 | 21 | # Copyright 2022 Xanadu Quantum Technologies 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 agre... |
72936cda4bbd11e3f018f42042b9f974b47ae46e43651a4cce2f50ee2450126a | Python | 834 | 33 | from defs import *
from values import *
import numpy as np
import math
def namgx(cell, memb_id, act, area):
Km_Nao = 62
Km_Mgo = 10
Km_Nai = 40
Km_Mgi = 0.7
n_Nao = 2 #1.72
n_Mgi = 2 #2.4
m = memb_id[1]
flux_Nao = cell.conc[0, m] ** n_Nao / (cell.conc[0, m] ** n... |
7ea6f3ca79c0aa7a7a0fbb546ce308ff1cfa87d03845ec307ebeb2026e90f633 | Python | 834 | 29 | """Screenshots for quick guide statistics"""
import sys
from PyQt6 import QtCore
from PyQt6.QtWidgets import QApplication
from shapeout2.gui.main import ShapeOut2
from shapeout2.gui import export
app = QApplication(sys.argv)
QtCore.QLocale.setDefault(QtCore.QLocale(QtCore.QLocale.Language.C))
mw = ShapeOut2()
mw.se... |
1741a10e639606841c1def3856eb3ec01d01a1d393db41c72e5fc71bc6c52cd0 | Python | 836 | 26 | """Higher-level schemas that compose `ParameterCard`s into UI-ready forms."""
from __future__ import annotations
from dataclasses import asdict, dataclass, field
from typing import Any
from pycaret.api.cards import ParameterCard
@dataclass(frozen=True)
class SetupParamSchema:
"""Schema describing every paramet... |
2028c2727397ea501d7ef974436c0078de1eb9df9ec621674666100d4ab01014 | Python | 839 | 21 | # Copyright 2018-2021 Xanadu Quantum Technologies 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... |
90bebd26fc46d406963a606094f38aa186033bc794ee9b5f695aabe7b91a6d71 | Python | 840 | 24 | import sys
## NOTE: Utterance ID and position are output as sentid and sentpos because downstream scripts require those fields
uttid = 0
## rate is words / second
print('word sentid sentpos timestamp rate')
with open(sys.argv[1],'r') as f:
for line in f:
times,utterance = line.strip().split("''",1)
utterance... |
863e6016fb851f6c9a937013386948ff1b14132eaf1836bf4e5f9fbc36030b08 | Python | 841 | 36 | import time
import logging
import torch
import numpy as np
import ismrmrd
import gadgetron
from modules.schemas.base_image_array import (
BaseImageArrayNormalisation,
BaseImageArrayTransformations,
)
def main(connection):
logging.basicConfig(level=logging.DEBUG)
for acquisition i... |
ceee182735b8e04525d573b7fa6cafc2186662791d2a26ed57b809f02988e617 | Python | 841 | 36 | """Updates the name table for the CBDT flagsonly font."""
from fontTools import subset
from fontTools import ttLib
import functools
from pathlib import Path
import sys
from typing import Set
NAME_ID_FAMILY = 1
NAME_ID_UNIQUE_ID = 3
NAME_ID_FULLNAME = 4
NAME_ID_POSTSCRIPT_NAME = 6
_NAME_VALUES = [
(NAME_ID_FAMI... |
54b59afdddfb06cafb247ce307d78a2966594396e88f10711c1432cd685c8bb4 | Python | 842 | 26 | import numpy as np
import pandas as pd
import pandas._testing as tm
from pandas.tests.copy_view.util import get_array
def test_constructor_copy_input_interval_ea_default():
# GH 63388
arr = pd.array([pd.Interval(0, 1), pd.Interval(1, 2)])
idx = pd.IntervalIndex(arr)
assert not tm.shares_memory(arr, i... |
80ffe647ae5c4b326bafcc8a05be84cb6d90cacc042feb7b48aa9eb556f00aba | Python | 842 | 29 | import sys
import pandas as pd
cols = ['Participant', 'time', 'Trial', 'Sentence_id', 'PennElementType', 'CorrectAnswer', 'Fixation_duration', 'repetition_index']
def rename(x):
if x == 'Participant':
return 'subject'
if x == 'Trial':
return 'trial'
if x == 'Sentence_id':
return 's... |
a821b1e625bff2b135e71eddeb031776833df2df7d5d4a96af449740acf7159f | Python | 842 | 32 | # python preprocess_gigaword.py Gigaword_File
# strips xml from gigaword and renders it in plaintext, line-delimited sents
import sys
with open(sys.argv[1], 'r') as f:
lines = f.readlines()
corpus = []
sent = []
INTEXT = False
for line in lines:
sline = line.strip()
if sline == '':
continue
el... |
2f0902fb3238fd7a594c523e3b8ca2d5419421e249799f877774b108f7591edc | Python | 845 | 23 | # Copyright 2018-2021 Xanadu Quantum Technologies 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... |
03ca7cd5d6c486bc272037ea597ff4831ce118c593713c965ac4adb00addbdbb | Python | 846 | 25 | # Copyright 2025 Xanadu Quantum Technologies 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 agre... |
819515da9548893047c9288af41e05631fc77ea88f181fcd129a4c700aed2125 | Python | 846 | 36 | # -*- coding: utf-8 -*-
__bibtex__ = """
@article{emcee,
author = {{Foreman-Mackey}, D. and {Hogg}, D.~W. and {Lang}, D. and {Goodman}, J.},
title = {emcee: The MCMC Hammer},
journal = {PASP},
year = 2013,
volume = 125,
pages = {306-312},
eprint = {1202.3665},
doi = {10.1086/670067}
}
"""... |
a2c032584de9ef92cff5156a2e6ccfdfc40b083ec0feed15db5af59462c7c96a | Python | 847 | 24 | def find_fastq(chrm: str, start: int, end: int, path: str) -> str:
"""\
Find the fastq file of a specific part of a gene.
:param chrm:
The chromosome to search.
:param start:
Start site of the chomosome.
:param end:
End site of the chomosome.
:param path:
The pa... |
2c38f4a59f43b674d7e3609a0de8717afb53dd0a3aa172f4b0320631980a62c8 | Python | 848 | 27 | # -*- coding: utf-8 -*-
import numpy as np
from emcee.moves import GaussianMove
def test_full_covariance_proposal_is_independent_per_walker():
# With a full (non-diagonal-only-shaped) covariance matrix, each
# walker must receive its own independent proposal step. Before the
# fix, rng.multivariate_norm... |
a1b072df51ffa0d3778df9689fa3be7efe12ff41575e12a35b64d3d2707acd42 | Python | 848 | 28 | import os
#from PyQt4.QtCore import *
from PyQt5.QtGui import QPalette
from PyQt5.QtWidgets import QSizePolicy
import numpy as np
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as mpl
from matplotlib.figure import Figure
class MplCanvas(FigureCanvas):
... |
054c63b5626062a391cd296eca34f6fbb35750053180347a3d518e118d405c3b | Python | 849 | 39 | """
_constants
======
Constants relevant for the Python implementation.
"""
from __future__ import annotations
import platform
import sys
import sysconfig
IS64 = sys.maxsize > 2**32
PY312 = sys.version_info >= (3, 12)
PY313 = sys.version_info >= (3, 13)
PY314 = sys.version_info >= (3, 14)
PY315 = sys.version_info ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.