sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
38de619f3f499f0fe6070e251ce3773275d7e18be4becb5333d7bc6c9d4f82f2 | Python | 1,468 | 46 | import numpy as np
import vegas
def f(x):
dim = 4
N = 10
ans = np.zeros(x.shape[0], np.double)
for i in range(x.shape[0]):
for j in range(N):
x0 = j / (N - 1.)
dx2 = 0.0
for d in range(dim):
dx2 += (x[i, d] - x0) ** 2
ans[i] += np... |
42f3a4f952dfb480a4819dc50e5d9af1e5874caa2cc5d03d181becf50958bcdb | Python | 1,468 | 34 | import sys
import os
import pandas as pd
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from app.models import Condition
def get_aibl_dx(visit_dx, symptoms):
condition = None
# At this moment, al... |
6cb84c64a7e8ad7b06c32b26a09dd6883dd4c6f9d073c636f5ddb30d549c88de | Python | 1,469 | 45 | #!/usr/bin/env python
__version__ = '1.0'
import os, sys, random
from collections import defaultdict
from Bio import SeqIO
def type_fa_or_fq(file):
file = file.upper()
if file.endswith('.FA') or file.endswith('.FASTA'): return 'fasta'
else: return 'fastq'
def sep_by_primer(file, output_prefix, sample_s... |
f5ee49fdb7430ebf22dc7eb3d3d852179b4e33559da6fbaed659a3cced224dd1 | Python | 1,469 | 49 |
import random
import glob
from cine import Cine
import tube2
import align
from skimage.io import imsave
from numpy import int16
videonames = glob.glob("data2/*.cine")
videonames2 = glob.glob("videos_surface_bug/*.cine")
videonames.extend(videonames2)
for i, name in enumerate(videonames):
vid = Cine(name)
m... |
d4d40fd710387cb11e62b461bc92f679399332666ab00daa92ee744208819728 | Python | 1,470 | 54 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 5 11:47:43 2023
@author: Noelia Martínez-Molina, adapted from code provided by Yonatan Sanz-Perl at CNS, UPF
"""
from numpy import genfromtxt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.style as style
import seaborn as sn... |
54a8793af4ce8cb0b7f5b2fbbbea193f37e049fadf8579bf746e4558fbba9904 | Python | 1,472 | 45 | from nesvor.transform import (
axisangle2mat,
mat2axisangle,
mat2point,
point2mat,
mat2euler,
euler2mat,
axisangle2mat_torch,
mat2axisangle_torch,
)
from tests import TestCaseNeSVoR
class TestTransformConvert(TestCaseNeSVoR):
def test_axisangle2mat(self):
for ax, mat in sel... |
ad3106b19ee70b59de1829721ac6ec762efe06939c6e2cbbcd488792b16bc33c | Python | 1,472 | 31 | import os
# import cloudpickle
import compatibility
import numpy as np
from . import parent_classes
import pandas as pd
def check(obj):
'''checks wherther obj can be saved with this dumper'''
return isinstance(obj[0], np) and isinstance(obj[1], np)
class Loader(parent_classes.Loader):
def __in... |
340c195dd1ca17dd0c56642be2f9ebbac2b2c57b89b50500e218a802c9089480 | Python | 1,473 | 49 |
import random
import glob
from cine import Cine
import tube2
import align
from skimage.io import imsave
from numpy import int16
videonames = glob.glob("data2/*.cine")
videonames2 = glob.glob("videos_surface_bug/*.cine")
videonames.extend(videonames2)
for i, name in enumerate(videonames):
vid = Cine(name)
m... |
f65966dd4e6deaa345a6fab1a14e395684225db7326ee2f15bceb0f2bd5b9a42 | Python | 1,473 | 50 | #!/usr/bin/env python
"""
File: structure
Date: 5/8/18
Author: Jon Deaton (jdeaton@stanford.edu)
"""
import os
from enum import Enum
from BraTS.load_utils import find_file_containing
class DataSubsetType(Enum):
hgg = 0
lgg = 1
train = 2
validation = 3
def get_brats_subset_directory(brats_dataset_... |
18a22388086d3d73895434ee5e6554e4eefa085298929ff242b4132a1d5ca4cc | Python | 1,474 | 39 | from io import StringIO
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays import ExtensionArray
class BaseParsingTests:
@pytest.mark.parametrize("engine", ["c", "python"])
def test_EA_types(self, engine, data, request):
if isinstance(data.dtype... |
97f58a0518491eecfc2591835b76ffff17cc958f31a7bde00d6e72cd55b66f3b | Python | 1,474 | 44 | # Copyright 2018-2023 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... |
c0c82135098bf6fb14ebd7ab421616b1181d7b703fff1118d1bd3bc7112cd161 | Python | 1,474 | 52 | """App command for the lightning-pose CLI."""
import argparse
import logging
from typing import Any
logger = logging.getLogger(__name__)
def register_parser(subparsers: Any) -> argparse.ArgumentParser:
"""Register the app command parser."""
app_parser = subparsers.add_parser(
"run_app",
desc... |
15c7713a60879e098dcba21a7bee7942a2b7109c6cbbfe4387be7071c1ee2cc1 | Python | 1,477 | 36 | import sys, argparse, pandas as pd
if __name__ == '__main__':
argparser = argparse.ArgumentParser(description='Add evid (event ID) column to data table')
#argparser.add_argument('data', type=str, help='Path to data table')
argparser.add_argument('-i', '--id_columns', nargs='+', default=['docid', 'subject'... |
6390763d6446c36b902bb459b4b2ef4afc285ff39e9fdffe5c4d2448f8b04f3a | Python | 1,479 | 67 |
from skimage.io import imsave, imshow
from skimage.feature import SIFT, plot_matches, match_descriptors
from skimage.measure import ransac
from skimage.filters import threshold_isodata
from skimage.morphology import binary_erosion
import cine
import tube2
import meniscus
from matplotlib import pyplot
video = cine... |
467e2298f9b44d8d9d5726a2a876f47808ae15d7683c12f287fdbf71ef5802da | Python | 1,480 | 62 | from multiprocessing import Array, Process, Event
import numpy as np
import time
import random
N_CHANNELS = 2
BUFFER_LEN = 10 # samples per channel
def writer(shared_array, event):
buffer = np.frombuffer(shared_array, dtype=np.float64)
buffer = buffer.reshape(2, -1)
while True:
time.sleep(4)
... |
a81097154a3c80bf0bb0b7c92e80897c1fed5e1da65e14d58845726e8876d258 | Python | 1,480 | 41 | import torch
from torch import nn
from torch_geometric.utils import scatter
from ..mlp import MLP
# Typing
from torch import Tensor
from typing import List, Optional, Tuple
class EGNNConv(nn.Module):
"""EGNN equivariant graph convolution.
References:
- https://arxiv.org/pdf/2102.09844.pdf
- https:/... |
47348a41285fb7b7071bfd4f667b80f7d3e9849fe1f64a0b639e628f1d4375e0 | Python | 1,482 | 49 | import sys, re, os
Makefiles = []
ParamVal = ''
KernelBlockDefs = ''
CompositeBlockDefs = ''
TargetBlockDefs = ''
for root, dirs, files in os.walk('../'):
for name in files:
if name.endswith('Makefile'):
Makefiles.append(os.path.join(root,name))
for path in Makefiles:
with open(path, 'rb') as M:
li... |
956115791040749d592096bb2dd14e3094b60d3dc4dbfa4c791552952d31a6ac | Python | 1,482 | 49 | """Tests for Magnitude Operator."""
import pytest
import torch
from mrpro.operators import MagnitudeOp
from mrpro.utils import RandomGenerator
from tests import autodiff_test
def test_magnitude_operator_forward():
"""Test that MagnitudeOp returns abs of tensors."""
rng = RandomGenerator(seed=2)
a = rng.... |
305c8bf332018b0d7642a340776f1ec11025ab98babc13437be5e41314fc19f1 | Python | 1,483 | 44 | #
# clebsch.py module for protein holographic machine learning
#
import numpy as np
import sympy
from sympy.physics.quantum.cg import CG
import tensorflow as tf
# this class and function implements the Clebsch Gordan coefficients
# as a function that takes the parameters of a Clebsch Gordan coefficient
# and returns ... |
641a20d461033d4c7ed35851cee1629d648de926166b1f3c66c7b9240e9e9577 | Python | 1,483 | 57 | import os
import pytest
from pandas.compat import is_platform_windows
import pandas as pd
import pandas._testing as tm
def test_numpy_err_state_is_default():
expected = {"over": "warn", "divide": "warn", "invalid": "warn", "under": "ignore"}
import numpy as np
# The error state should be unchanged aft... |
c4783f40fa1b1810a4112d44bccefb000163288705d84ddb9eeeb80a65463afc | Python | 1,483 | 38 | #Run sweeps over number of fields
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.objects import *
from placerg.runfunc import *
N0 = 4096 # number of cells
N = 1024 # number of cells after removing silent ones
percell= 1.0 # probability that each field is accepted
phi=1.0 ... |
1dec64b734db1711b7e8c4be79ea1e52c37c30b59dd72e66efcf4d597096f6b3 | Python | 1,485 | 33 | # 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... |
d68dc8ebae665ea12f9758e54d54a0603f568d6393b8ed437b178cc638356d5a | Python | 1,485 | 30 | import os
import models.args
def get_args():
parser = models.args.get_args()
parser.add_argument('--mode', type=str, default='rand',
choices=['rand', 'static', 'non-static', 'multichannel'])
parser.add_argument('--output-channel', type=int, default=500)
parser.add_argument('-... |
982c58cc9360ca6d3587a4c06683d83ce67632b21ae14bdc3d4b062440a4bf42 | Python | 1,489 | 42 | #!/usr/bin/env python
"""
A temporary CSV file for isoseq3 (v3.4+) dedup output
INPUT: dedup.fasta
OUTPUT: dedup.info.csv
"""
import os, re
from Bio import SeqIO
from Bio.Seq import Seq
import pysam
rex = re.compile('(\S+) full_length_coverage=(\d+);length=(\d+);XM=(\S+);XC=(\S+)')
rex_umi_only = re.compile('(\S+) fu... |
a10cfcf05684100a27a49713d4d866897bcda0b66ed4f92bdd60ab4d49c41173 | Python | 1,490 | 36 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'spikes.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectN... |
e216fdfd123b7a9d09cab6f3fe038f8d1b449f290e144d7b7f2d1bf02f189d91 | Python | 1,490 | 44 | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master... |
64387281e3b284fedf1550bb818604cd6e9db10a1b09c8e04f39adf19722355b | Python | 1,495 | 54 | """Test axes."""
# ------------------------------------------------------------------------------
# Imports
# ------------------------------------------------------------------------------
import os
from ..axes import Axes, format_time_ticks
from . import show_and_wait
# -------------------------------------------... |
d1e72a91a918efb2df235adc43b633f4f81f729404b4cce26bded1d6d48b3e6c | Python | 1,495 | 53 | from datetime import UTC
import numpy as np
from pandas._libs.tslibs.tzconversion import tz_localize_to_utc
from .tslib import (
_sizes,
_tzs,
tzlocal_obj,
)
try:
old_sig = False
from pandas._libs.tslibs import tz_convert_from_utc
except ImportError:
try:
old_sig = False
from... |
162ef23903fe8a96d9fd50fdae355e8a44ea8135cfddc60c60ad52877db45ba4 | Python | 1,496 | 49 | import numpy as np
import torch
vocab = ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL', '*']
def gram_schmidt(A):
"""Orthogonalize a set of vectors stored as the columns of matrix A."""
# N-CA-C order
v1 = A[2]-A[... |
7d2cdd7c33c895ebe0c03793dc3ab3c9d2df5a3fab0c962941986c87860042af | Python | 1,496 | 58 | import os
def check_region_paramater(position):
if position == "None":
position = None
else:
position = int(position)
return position
def check_step(step,window_size):
if step == "None":
step = int(window_size / 20)
else:
step = int(step)
return step
def ge... |
f3c9a24e877e37965e2236906362dc340b8077fa63ea2226a66177b3a8b874ef | Python | 1,496 | 48 | __all__ = ["PeptideRTTrainer"]
import os
from logging import Logger
from typing import List, Optional, Union
from ....util.progress import ProgressFactoryProto
from ...common.training import TrainerBase
from ...util.writer import SummaryWriterProto
from .data import PeptideRTData, PeptideRTDataBatch
from .loss import... |
fa84f40a0f59e55a84bfc29d1ff0e1dfc8f981dd3afca78df82201128a8c3f80 | Python | 1,496 | 46 | import collections
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestSeriesToDict:
@pytest.mark.parametrize(
"mapping", (dict, collections.defaultdict(list), collections.OrderedDict)
)
def test_to_dict(self, mapping, datetime_series):
# GH#16122
... |
08fe7b5207ce4f74d971b2c29bd507e8c4ffac9cff2771688e5405e2bb0aedfd | Python | 1,497 | 39 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for GCPNet (https://github.com/BioinfoMachineLearning/GCPNet):
# ----------------------------------------------------------------------------------------------... |
0bcf572c83c4f11c0e19976c2e5018d6016d8dbc7ebfca97d20eb2cf506dfd34 | Python | 1,497 | 39 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for GCPNet (https://github.com/BioinfoMachineLearning/GCPNet):
# ----------------------------------------------------------------------------------------------... |
c8ef42a75c7c42f0cd58bfbb40f0f57908ef6a28ff0a3b85f39b4e1ded4ea352 | Python | 1,500 | 45 | #!/usr/bin/env python
import os
import requests
from tqdm import tqdm
def download_model(local_dir=None):
if local_dir is None:
user_dir = os.path.expanduser('~')
# url = "https://github.com/LinB203/test/releases/download/v1/pytorch_model.bin"
url = "https://figshare.com/ndownloader/files/... |
2479e3bf333658f0fddff59779acba79f8f53ebd6fb28d2595faf946f4057402 | Python | 1,501 | 40 | import pytest
import pandas as pd
import pandas._testing as tm
class BaseAccumulateTests:
"""
Accumulation specific tests. Generally these only
make sense for numeric/boolean operations.
"""
def _supports_accumulation(self, ser: pd.Series, op_name: str) -> bool:
# Do we expect this accum... |
8428d86b6b0acca927a373ea1119fde5c53c6fe1b91977a80a62630a3e469435 | Python | 1,501 | 44 | from deepglyco.chem.gpep.glycans import GlycanNode
class GlycoGlyphGlycanFormatter():
def __init__(self, monosaccharide_names=None):
if monosaccharide_names is None:
monosaccharide_names = {
'H': 'Man',
'N': 'GlcNAc',
'F': 'Fuc',
... |
de67c135450b2b68202a23bc8206592ec7432c54605fc25df486f6f68080fec0 | Python | 1,502 | 50 | """PyCaret 4.0 plot library — Plotly-native, framework-agnostic.
Replaces the legacy ``plot_model`` API (deleted in s46). Each plot
function takes a fitted estimator (typically a sklearn / sktime
``Pipeline``) plus data and returns a ``plotly.graph_objects.Figure``.
The figure is the universal currency: notebooks cal... |
147403a687e2c1c6af7ee559dcdee176e110caa47e6ff1f5a5320a04f2c84d3c | Python | 1,503 | 49 | #!/usr/bin/env python
#############################################################################
## this file is part of TreeShrink.
## see "license.txt" for terms and conditions of usage.
#############################################################################
PROGRAM_NAME = "TREESHRINK"
PROGRAM_AUTHOR = [... |
4e010938c830d8101097ee4bd520baec449f87a9d732c7e87d177027c5e2a1b1 | Python | 1,503 | 50 | # 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... |
9c8ecf0d35c76a6da66348c1794571d26245a9a53abee6f6db1168e87c938a44 | Python | 1,503 | 39 | from Environment_ui import *
class DiceLoss(nn.Module):
def __init__(self, n_classes):
super(DiceLoss, self).__init__()
self.n_classes = n_classes
def _one_hot_encoder(self, input_tensor):
tensor_list = []
for i in range(self.n_classes):
temp_prob = input_tensor == ... |
b3d79ed6039fefcdb579b330d067c836ebafde220e45317844ce4d9b4270cd18 | Python | 1,503 | 62 | import numpy as np
import pandas as pd
# Search dimensions
# n : number of random samples to draw from each dim
# m : scale of continuous random var
# b : shift of continous random var
# Dropout
n_dropout = 3
dropout_m = 0.45
dropout_b = 0
# Learning rate
n_lr = 5
lr_m = -2.
lr_b = -3.5
# Whether to learn message... |
c481b6eea4e9839894bef2bc166d55cce248f9429eca0662ea420ba0b4289756 | Python | 1,503 | 42 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for GCPNet (https://github.com/BioinfoMachineLearning/GCPNet):
# ----------------------------------------------------------------------------------------------... |
a376571739aef00f7fa56814f3198ee41a702d291672921725c8ff4c01d8b801 | Python | 1,504 | 57 | import numpy as np
import pandas as pd
import time
import datetime
def log_normalize(df: pd.DataFrame, constant: int=1, scale: int=1e4, verbose: bool=False):
"""
Normalizes data by scaling and log-transformation
Default scale is 10,000
Parameters
----------
df : DataFrame
Raw expre... |
420c639c87ca6260fa5aebdcb95abecd4b6c7118c6ab536b85cd54753aed6468 | Python | 1,505 | 53 | """BasePlayer must accept both the classic 4-tuple and gymnasium 5-tuple env
contracts: the myo_gym path returns gymnasium-native envs since MyoSuite
dropped OldGymWrapper."""
import numpy as np
import torch
from rl_games.common.player import BasePlayer
class _Shim:
"""Just enough BasePlayer surface to run env_s... |
c9cc72a736cca6dad0d166cfbf6617834c01367796a462385f89dd70554c4a74 | Python | 1,505 | 49 | import tensorflow as tf
from tensorflow.keras.callbacks import Callback
from rl_toolkit.utils import VariableContainer
class DQNAgentCallback(Callback):
def __init__(self, db_server: str):
super(DQNAgentCallback, self).__init__()
self._db_server = db_server
def on_train_begin(self, logs=None... |
ea92873043beb18e99de2c10299e2e24499de6a31048c9a04fa4ecc1e8b386fb | Python | 1,505 | 51 | #!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import gc
import PE
# Label for estimation, weights and outputs, according to the specific test case.
label = 'TLV' # ['TLV', 'Tatria', 'Tventricles', 'Tall'].
# If this flag is true, HMC runs after MAP estimation.
inverse_U... |
9df64dcc832e7c5650dcaf9edb328ffae6a84105a32d3b74a98680f83fe4a113 | Python | 1,506 | 46 | import numpy as np
import pytest
from pandas.errors import Pandas4Warning
import pandas as pd
import pandas._testing as tm
def test_groupby_skew_equivalence():
# Test that the groupby skew method (which uses libgroupby.group_skew)
# matches the results of operating group-by-group (which uses nanops.nanskew... |
41ca3cb9ecfdf1dd89260f33d38188b5439e9791949020ef517a61c814bcb23c | Python | 1,507 | 28 | import pandas as pd
import os
import sys
import pdb
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from app import create_app, db
from app.models import Subject, Visit, SourceDataset, Image, PreprocessTas... |
77ec3fcb1e7666c9228bfc5a94b02216f26fb03f2b8e931c8e0f082cd451ef51 | Python | 1,507 | 56 | __all__ = ["PeptideRTBiLSTM", "PeptideRTCNNLSTM"]
import torch
from torch import nn
from ...util.attention import AttentionSum
from ..common.data import PeptideDataBatch
from ..common.model import PeptideBiLSTM, PeptideCNNLSTM
class PeptideRTOutput(nn.Module):
def __init__(self, configs: dict, in_features: int)... |
0f35a9caa497295149997031a541a77b19aa0d5b1c7172abed8740896a9f7a12 | Python | 1,508 | 67 | import pytest
import pandas as pd
from pandas.core.arrays.integer import (
Int8Dtype,
Int16Dtype,
Int32Dtype,
Int64Dtype,
UInt8Dtype,
UInt16Dtype,
UInt32Dtype,
UInt64Dtype,
)
@pytest.fixture(
params=[
Int8Dtype,
Int16Dtype,
Int32Dtype,
Int64Dtype,
... |
0eb5d305aad26b4eaff42cfa8e559ba5cfb10dd8af397761b0d3eda01590bf77 | Python | 1,510 | 59 | import importlib
import inspect
import pytest
import pyaging
from pyaging.models import (
_author_extensions,
_base_models,
_models,
_organage,
_paopac,
_pc_extensions,
_proteoclock,
_replication,
)
SUBPACKAGES = ["data", "logger", "models", "predict", "preprocess", "utils"]
@pytest... |
8dbc6ff30d4cdbeec56504edf0bbead702417ea70e5e9dfb7a24ef5785d860e2 | Python | 1,510 | 42 | import pandas as pd
def test_is_monotonic_with_nat():
# GH#31437
# PeriodIndex.is_monotonic_increasing should behave analogously to DatetimeIndex,
# in particular never be monotonic when we have NaT
dti = pd.date_range("2016-01-01", periods=3)
pi = dti.to_period("D")
tdi = pd.Index(dti.view("... |
b527da6cccf8e109a687403f51229833e8a0ab921026ced5a0235b9dc09eec0b | Python | 1,511 | 49 | import tensorflow as tf
from tensorflow.keras.callbacks import Callback
from rl_toolkit.utils import VariableContainer
class SACAgentCallback(Callback):
def __init__(self, db_server: str):
super(SACAgentCallback, self).__init__()
self._db_server = db_server
def on_train_begin(self, logs=None... |
3c3e6e5bed2cb2561e405c0100c5508789ad316564307abeb1afd6abd60dac08 | Python | 1,512 | 50 | from evcouplings.utils.calculations import *
from evcouplings.utils.config import *
from evcouplings.utils.helpers import *
from evcouplings.utils.system import *
from evcouplings.utils.batch import *
from evcouplings.utils.constants import *
from evcouplings.utils.tracker import *
class ASubmitterFactory(abc.ABCMeta... |
c2968d528e52105fa069439f38cdf4b45b9d0a84cc18a97dee54910a6af826da | Python | 1,512 | 58 |
class Sequence:
def __init__(self, sequence):
self.bases = sequence
self.segSequence = []
def add_sequence(self, sequence):
sequence = sequence.upper()
self.bases += sequence
def clear(self):
self.bases = ""
def length(self):
return len(self.bases)
... |
cd92c67d19e673fc21b8740080d686e4a1b0b3b667371e1a5c171347c1c6692b | Python | 1,512 | 40 | # 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... |
455a05d45164f974e2b4f44b66fb9a1f77181901ba275d73c85ec09f8cd06823 | Python | 1,513 | 38 | from torch_geometric.graphgym.register import register_loader
import torch_geometric.transforms as T
from data import MFGEcoli
from transforms import FlowProfile
@register_loader('MFGEcoli')
def load_dataset_MFG(format, name, dataset_dir):
from torch_geometric.graphgym.config import cfg
dataset_dir = f'{datas... |
4e13e8226638709484260489f6916aba76ee9000fbc3f6e806653d93ca276dd5 | Python | 1,513 | 31 | #3rd plotting setting
import matplotlib as mpl
mpl.use("pdf")
import seaborn as sns
mpl.rcParams["pdf.fonttype"] = 42
mpl.rcParams["figure.figsize"] = (4, 2.75)
mpl.rcParams["figure.dpi"] = 100
mpl.rcParams["savefig.transparent"] = True
mpl.rcParams["savefig.bbox"] = "tight"
mpl.rcParams["font.size"] = 10.0
mpl.rcParam... |
e4aa01bef3285f65d54f4ddebfc9ca5e1f194ed07f86358aec74217437f6e409 | Python | 1,514 | 47 | """Shared test-suite setup.
Auto-fixtures that run for every test module:
- ``_reset_singletons_between_tests`` — clears the process-wide caches that
Phase 1 (crypto, object store, orchestrator) introduced so each test
starts with a fresh resolution from its monkeypatched settings.
Individual test files still ow... |
acb6d69d71a0ed2c784dae7f5279c002209fbf37e5db91f8191d40101c2e42ea | Python | 1,515 | 58 | """Identity Operator."""
import torch
from mrpro.operators.LinearOperator import LinearOperator
class IdentityOp(LinearOperator):
r"""The Identity Operator.
A Linear Operator that returns a single input unchanged.
"""
def __init__(self) -> None:
"""Initialize Identity Operator."""
... |
15f1c4cb8320b739de7f79193fa75d6936ae1dff93b4e62c41125f23b6f6e4d9 | Python | 1,516 | 43 | from string import Template
import subprocess
import os
ref_file = "/path/ref9545380_1kgPhase3eur_LDr2p1.mat"
trait_folder = "/path/sumstats"
trait_file1 = ['PGC_MDD_2018_no23andMe_noUKBB.mat', 'PGC_ADHD_2017_EUR.mat', 'PGC_ASD_2017_iPSYCH.mat']
trait_name1 = ['MDD', 'ADHD', 'ASD']
trait_file2 = ['multimodal_eig26.mo... |
dde7700111861be1d2674fa918514c2f0730e785155676d245dc95f3fa812722 | Python | 1,517 | 56 | import numpy as np
from msmfcode.core.logging import log
from msmfcode.core.config import *
from msmfcode.execution.optimization import ContGeneticAlgorithm
from msmfcode.models.cann import Grid, FMSMF, DMSMF
from msmfcode.execution.parallel import ParallelExecutor
from msmfcode.evaluation.plot import plot_fitness
fro... |
327a3e32ffd6ec65c384be6d4a2ec1656a0bc49063a4f37c2a0f74cc41a434b3 | Python | 1,518 | 44 | import os
from unittest import TestCase, mock
import dynast.ref as ref
from tests import mixins
class TestRef(mixins.TestMixin, TestCase):
def test_STAR_genomeGenerate(self):
with mock.patch('dynast.ref.utils.get_STAR_binary_path', return_value='path/to/STAR'), \
mock.patch('dynast.ref.utils... |
b5c510ebb10b8ddc6fca0bf2bdfeeffdf6f4bd777a2d3732acb71bf5b1dfc3aa | Python | 1,518 | 66 | """SAM (Self-Assembling Manifold) algorithm for single-cell RNA sequencing analysis.
SAM iteratively rescales the input gene expression matrix to emphasize
genes that are spatially variable along the intrinsic manifold of the data.
Example
-------
>>> from samalg import SAM
>>> sam = SAM()
>>> sam.load_data("expressi... |
a9fe292ed4a56414452cac2c758da4cc7538f7a11abde6dc331f8cfc2a2aae27 | Python | 1,519 | 58 | """PyCaret 4.0 engine primitives.
This package hosts the task-agnostic core of the PyCaret 4.0 engine:
- `Experiment` — sklearn-compatible base class. Task-specific subclasses in
`pycaret.tasks.*`.
- `SupervisedExperiment` / `UnsupervisedExperiment` — verb-set mixins used as
intermediate bases.
- `TaskType` — enu... |
b884275aed3dbb88fa80e8fdfd7ef528aa699b4deb2c866a0be9a138ce756c9e | Python | 1,519 | 30 | import os
import models.args
def get_args():
parser = models.args.get_args()
parser.add_argument('--max-tokens', type=int, default=5000, help='Number of features to use in our BoW Model')
parser.add_argument('--use-idf', type=bool, default=True,
help='True, uses term frequency and... |
b1ba646024207efd6328909c0e26b82564e601e29cb734490854dcdaa5aeefe9 | Python | 1,520 | 45 | # -*- coding: utf-8 -*-
import click
import logging
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
import subprocess
import shutil
from pathlib import Path
parent = str(Path(__file__).resolve().parent)
def spec2csv(root):
subprocess.run([f"{parent}/spec2csv_recursive.py", "-d", "-f", "jws",... |
51e644f41bac7afb6112810f492bcec9ff8799a41116fa3afff859fbd74bb86e | Python | 1,522 | 42 | from datetime import datetime
import sys
import enum
sys.path.append("..")
from app import db
from sqlalchemy.dialects.postgresql import JSON
class TypeEnum(enum.Enum):
T1 = 1
DWI = 2
rsfMRI = 3
FieldMap = 4
class PreprocessedEnum(enum.Enum):
none = 0
minimal1 = 1
locked = 2
failed = ... |
c07268a86be3f4249b921b286cc95d6e784385a83c2f7842172ad638f7d20c87 | Python | 1,522 | 33 | import torch
from torchvision import datasets, transforms
import argparse
def setup_cifar100(n_train=40000, n_val=10000, n_test=10000, batch_size=64, data_dir='data'):
# https://priyanshwarke2015-ndcs.medium.com/image-classification-with-cnn-model-in-cifar100-dataset-8d4122b75bad
transform = transforms.Compos... |
9ab5535d3342558557a6a9dc5a939ea8de24084ae95d0d1e61076e96cb94deda | Python | 1,523 | 46 | """Test the remap CLI command argument parsing."""
import argparse
from pathlib import Path
import pytest
from lightning_pose.cli.commands.remap import get_parser
class TestGetParser:
"""Test the get_parser function."""
def test_returns_argument_parser(self):
"""Returns an ArgumentParser instance.... |
e0fec0ed77dacfa541d4969d21e658e8ec5b78b74c5a42a8588bfc6634cf7a79 | Python | 1,523 | 45 | import os
from .DropDownMenu import DropDownMenu
class SelectSub(DropDownMenu):
"""
A dropdown menu widget specifically designed for selecting subject directories.
"""
def __init__(self, default_msg):
"""
Initialize the SelectSub widget.
Args:
default_msg (str): T... |
e2c1531c12fb234b712d8d689a69fdd034ff393559c5b0c0a9c11001ec16c95f | Python | 1,524 | 47 | # MOFTransformer version 2.0.0
import re
from setuptools import setup, find_packages
with open("requirements.txt", "r") as f:
install_requires = f.readlines()
with open("README.md", "r") as f:
long_description = f.read()
extras_require = {"docs": ["sphinx", "livereload", "myst-parser"]}
with o... |
20a2354612afb91781cab4517e2ce362652d60b8494a0683fcc711805832828d | Python | 1,525 | 48 | import logging
import pytest
from pyaging.logger import Logger, LoggerManager, main_set_level
def test_constructing_logger_preserves_dependency_logging_configuration(monkeypatch):
dependency = logging.getLogger("anndata")
monkeypatch.setattr(dependency, "level", logging.WARNING)
monkeypatch.setattr(depe... |
bf08c510110cc2b0bd49ae2c482d3978d0df60ff1b69e46416d0fd8fd5310f8d | Python | 1,525 | 44 | import sys
import os
# python2 uses ConfigParser but python3 uses configparser. The two versions
# have different APIs
if sys.version_info[0] == 2:
import ConfigParser as configparser
else:
import configparser
config = configparser.ConfigParser()
config.optionxform = str
config.readfp(sys.stdin)
prereqs = []
... |
dcab5a10a419f444643945018fd41535eca2bf078c357b5639d4273ed9e0b4de | Python | 1,525 | 47 | # Arithmetic tests for TimedeltaIndex are generally about the result's `freq` attribute.
# Other cases can be shared in tests.arithmetic.test_timedelta64
import numpy as np
import pandas as pd
import pandas._testing as tm
class TestTimedeltaIndexArithmetic:
def test_arithmetic_zero_freq(self):
# GH#51575... |
4aac6d68869d56ef553416d2bd24046199daa9a75223eea66068d1ad7d87235a | Python | 1,528 | 56 | # %%
from omegaconf import OmegaConf
from typing import Union
from pathlib import Path
from torch import load
from twoandahalfdimensions.utils.config import Config
from twoandahalfdimensions.utils.setup import setup
from twoandahalfdimensions.utils.data import make_data, make_loader
from twoandahalfdimensions.models.... |
eff8ddd45b195663a1d36ec7488fac668ed28ccc82e2bfa58df32687bce562a1 | Python | 1,529 | 49 | import math
import arviz as az
import pymc as pm
from pcntoolkit.normative_model import NormativeModel
def compare_hbr_models(models: dict[str, str]):
"""Compares HBR models
Args:
models (dict[str, str]): dictionary of [model name, path]
Returns:
dictionary of (responsevar, comparison)... |
66587a05454c68794544a3eb417efccca733ea32882abf73401d6348bd0db50f | Python | 1,531 | 53 | import numpy as np
import vegas
import sys
if sys.argv[1:]:
if sys.argv[1] == 'mpi':
vegas.Integrator.defaults['mpi'] = True
NPROC = 1
else:
vegas.Integrator.defaults['mpi'] = False
NPROC = eval(sys.argv[1]) # number of processors
else:
NPROC = 1
import gvar as gv
gv.r... |
699099c3e904a836d18f84834ba4fb5867921cd4daec2486e779a7e95427a797 | Python | 1,531 | 51 | from argparse import ArgumentParser, FileType
def main():
p = ArgumentParser()
p.add_argument('term_file', type=FileType('r'))
p.add_argument('output')
args = p.parse_args()
term_file = args.term_file
next(term_file)
labels = {}
for line in term_file:
curie = line.split('\t')[... |
644ebdd12da6f0a0f11218f4915f44ae98a0a79b857bb6c001c3b09d9bfceb8f | Python | 1,532 | 34 | from models.SegmentationUnet import UNet
import segmentation_models_pytorch as smp
def select_model(net_name, in_channels=3, width=1, backbone=''):
if net_name == 'unet':
model = UNet(in_channels=in_channels, n_classes=1, width=width)
return model
elif net_name == 'unetpp':
model = sm... |
993c3489b308dd951443fde418a3f0bc4811a78e94330bd5c73f43bdb53b58c5 | Python | 1,532 | 64 | import torch
def modek_product(A, M, k=None, transpose=False, conjugate=False, inverse=False):
r"""
Mode-k product
:param A:
:type A:
:param M:
:type M:
:param k:
:type k:
:param transpose:
:type transpose:
:param conjugate:
:type conjugate:
:param inverse:
:typ... |
2134966496ff3eb7a13b504f2385badab3c3f81c8652c218fc2a5d1330661e83 | Python | 1,534 | 51 | """Test of filter functionalities"""
import pathlib
from shapeout2.gui.main import ShapeOut2
from shapeout2.gui.analysis import DlgSlotReorder
from shapeout2 import session
import pytest
datapath = pathlib.Path(__file__).parent / "data"
@pytest.fixture(autouse=True)
def run_around_tests():
# Code that will run ... |
36f722d1d809ddc166dcd910d9c6a584d27696e8855b1b18fe2ebc7a50f6c8f4 | Python | 1,534 | 55 | """Basic integration tests for the Datasets Service API"""
import pytest
import requests
import pennylane.data.data_manager
from pennylane.data.data_manager.graphql import GRAPHQL_URL
# pylint: disable=protected-access
class TestGetGraphql:
"""Tests for the ``get_graphql()`` function."""
query = """
... |
5b20482ee106c8ed13b9bb12038bbd380415468e5aa1a41918a9b96a89267be3 | Python | 1,534 | 53 | #####################################################################################################################
# Date created : 10/21/2022
# Date modified: 10/21/2022
# Purpose : To generate contact count feature
############################################################################################... |
aab0f988f91e560e849c1f8451dd135978489fb5e205b25e75fdfb233a5cb905 | Python | 1,535 | 42 | import torch
from torch import nn
from rl_games.common import common_losses
from rl_games.algos_torch.layers import symexp, symlog
from rl_games.common.extensions.distributions import TwoHotDist
class OneHotEncodedAction(nn.Module):
def __init__(self, in_size, num_actions):
nn.Module.__init__(self)
... |
40df3440ecfcdc2c49d653a40a3f1a60821afeec2ef83ee8c9d13606bf3fb7d1 | Python | 1,536 | 38 | """Test reduce_repeat"""
import pytest
import torch
from mrpro.utils import RandomGenerator, reduce_repeat
@pytest.mark.parametrize('dtype', [torch.float32, torch.complex64], ids=['float32', 'complex64'])
def test_reduce_repeat_expanded(dtype: torch.dtype) -> None:
"""Test reduction of broadcasted dimensions."""... |
95f38f35fdae5ff616b844ac96236e19f2dd9defa38b34173147047e64933e46 | Python | 1,536 | 28 | """Analytic edge-case checks for consequential numerical operations."""
import os
os.environ.pop('PROJ_LIB',None)
os.environ.pop('PROJ_DATA',None)
import numpy as np
from rasterio.transform import from_origin
from shapely.geometry import box
from risk_core import who_band,lag01_reduction,transferred_rr,longest_exceedan... |
1cd5f8fa5c1709a9b4c8983185a89c424a92fcf561c071e97f76a01863f4ed48 | Python | 1,537 | 38 | import os
def log_params(sim_params):
print(f'Simulation parameters:')
print(f'\ttimestep = {sim_params.timestep}')
print(f'\ttau_mem = {sim_params.tau_mem}')
print(f'\tbatch_size = {sim_params.batch_size}')
print(f'\tlr = {sim_params.lr}')
print(f'\tdelay_distribution = {sim_params.delay_dist... |
49a4b4106bea782f5442f433687049dddf8baad8bec3ffb842c05d71ad944239 | Python | 1,537 | 45 | """Partitions the sequences in a fasta file
Given an input sequence file, write new text files consisting of the sequences partitioned into groups.
Also prints the total number of records in the file.
"""
from Bio import AlignIO, Align, SeqIO
import argparse
def main(input_path, output_prefix, ids_per_partition):
... |
dbcb11078bc397c3d540516eebd10ac0ec18c5a772eb763be780785864d41bf9 | Python | 1,539 | 43 | """Deprecated module: use ``scsims.contrib.upload`` instead.
This shim exists so existing code that does
``from scsims.networking import UploadCallback`` still works for one
release. It will be removed in scsims 5.0.
"""
import warnings
from scsims.contrib.upload import UploadCallback as _RealUploadCallback
from scs... |
8b4cd01bb69ad0cf1020e147d56263d07e242da7ab7dd034c84d53c35070f26b | Python | 1,540 | 45 | import sys
import pandas as pd
import numpy as np
import scipy.io
import scipy.stats
import argparse
import os
def parse_args(args):
parser = argparse.ArgumentParser(
description="Produce csv files for FUMA from mostest_light_stats results.")
parser.add_argument("--mat", help="Path to mostest_... |
fcc2c77731e5c73d003c480fdafc2444b1d339889869221ad88ba1f4a8d5b484 | Python | 1,540 | 51 | import sys, re, os
from numpy import inf
R = re.compile('(\[[0-9]+\] "?)?([^"$]*)"?')
def deRify(s):
return R.match(s).group(2)
# Thanks to Daniel Sparks on StackOverflow for this one (post available at
# http://stackoverflow.com/questions/5084743/how-to-print-pretty-string-output-in-python)
def getPrintTable(r... |
b9444481b46d5c4700a07facbba3b0fb108a000da9f4f786bd5aafd3c6896d2d | Python | 1,541 | 57 | '''
Dataset base class
'''
class Dataset(object):
def __init__(self):
self._image_ids = []
self.image_info = []
def add_image(self, source, image_id, path, **kwargs):
image_info = {
"id": image_id,
"source": source,
"path": path,
}
... |
d27ab530990939991ce61ffea7736353166314af05035aac6060ad01ee274c92 | Python | 1,541 | 47 | import numpy as np, matplotlib.pyplot as plt, sys
import pumpprobe as pp
q_th = 0.3
for s in sys.argv:
sa = s.split(":")
if sa[0]=="--q-th": q_th=float(sa[1])
plt.rc('xtick',labelsize=14)
plt.rc('ytick',labelsize=14)
plt.rc('axes',labelsize=14)
act_conn = np.loadtxt("/projects/LEIFER/francesco/simulations/ac... |
3b3e7b6a0f44cf22f28c70fbd813994f775e46d51e446c4c6568825fdfffb80a | Python | 1,542 | 54 | 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='\t', index_col=0)
total_data = total_data.append(data)
print(total_data.shape)
new_index = []
tmp_index = total_... |
8941070f7b1719f53bfdd0476be832fedef3e4d40db9fc4db0577c76d10883da | Python | 1,543 | 56 | """Custom argparse type validators for CLI path arguments."""
import argparse
from pathlib import Path
def config_file(filepath: str) -> Path:
"""
Custom argparse type for validating that a file exists and is a yaml file.
Args:
filepath: The file path string.
Returns:
A pathlib.Path object ... |
4b05bc263a0254e2ae7ff9eb1ad925b099f3bc0425b585ff6b1e95e3adaa2144 | Python | 1,545 | 57 | import torch
# create three-dimensional data with three classes based on distance to the origin
def setup_circle_3D(n=1000, R=5.5, r=3.5):
x = 3 * torch.randn(n, 3)
y = torch.zeros(n, dtype=torch.long)
y[(x ** 2).sum(dim=1) < R ** 2] = 1
y[(x ** 2).sum(dim=1) < r ** 2] = 2
return x, y
def setu... |
50cfe3965f0eada43192346d0089322c9cf9a558fffda4abe31abf53745b3594 | Python | 1,546 | 47 | """reduce_repeat utility function."""
from collections.abc import Sequence
import torch
from mrpro.utils.reshape import normalize_indices
def reduce_repeat(tensor: torch.Tensor, tol: float = 1e-6, dim: Sequence[int] | None = None) -> torch.Tensor:
"""Replace dimensions with all equal values with singletons.
... |
8d638aaf483a15980613c7c4036d8dfb81a3e0e89d5661865505706dd5e8b01b | Python | 1,546 | 44 | from __future__ import print_function
import argparse
import os
import subprocess
import pysam
def submitter(commander):
"""Submits commands directly to the command line and waits for the process to finish."""
submiting = subprocess.Popen(commander,shell=True)
submiting.wait()
parser = argpars... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.