sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
c86c6c9199cfbdc1bf7b8acfe3148453aaea11f0f32f0d4734efdef24a79f682 | Python | 1,822 | 65 | """ Click parameters for the BiG-SCAPE Dereplicate CLI command """
# from python
import click
import logging
# from other modules
from big_scape.dereplicating.dereplicate import run_bigscape_dereplicate
from big_scape.diagnostics import init_logger, init_logger_file
import big_scape.enums as bs_enums
from big_scape.c... |
aed8f1c688d5d5369ce66f66dba49f9942a8bcf4e6a82e6c309c4cb885041f6b | Python | 1,826 | 58 | """
Module for Python Serial communication with Arduino microcontroller to control trigger rate
Compile campy/trigger/trigger_arduino.ino to operate
Inputs (from config.yaml -> params):
frameRate: rate in frames/sec to trigger
serialPort: COM port on PC for Arduino, e.g. 'COM3'
Currently rely on time delay to a... |
97e39308022cdb996c6a97a303a218a4f67148ce7e0444f8b1d64392a97c8e26 | Python | 1,830 | 55 | from __future__ import annotations
import abc
from typing import TYPE_CHECKING
from pip._internal.metadata.base import BaseDistribution
from pip._internal.req import InstallRequirement
if TYPE_CHECKING:
from pip._internal.build_env import BuildEnvironmentInstaller
class AbstractDistribution(metaclass=abc.ABCMe... |
c079c58cfaa1377a82f14706be05c1d1beee4e07938b8fe66d32e98650f88857 | Python | 1,830 | 60 | from __future__ import annotations
from typing import TYPE_CHECKING, NamedTuple
from qtpy.QtWidgets import (
QHeaderView,
QTableWidget,
QTableWidgetItem,
QWidget,
)
if TYPE_CHECKING:
import useq
ROLE = QTableWidgetItem.ItemType.UserType + 1
class WellInfo(NamedTuple):
pos_idx: int
fov:... |
e88fae536d4a5197408854bc4fc0b72828e01852e6e4a4223eb2d26ebc860f47 | Python | 1,830 | 51 | import os
import json
from glob import glob
from tensorflow.keras import Model
from tensorflow.keras.models import load_model
from tqdm import tqdm
def find_best_model_by(given_metric: str, experiment_name: str, model_type: str, save_model_name: str = None) -> Model:
path = os.path.join(experiment_name, "hsearch... |
ffe467937bce7dff2e17d8401a64fa48b00b7e563580c05c6c6c12d767dbfd8e | Python | 1,830 | 61 | """xmlrpclib.Transport implementation"""
import logging
import urllib.parse
import xmlrpc.client
from typing import TYPE_CHECKING
from pip._internal.exceptions import NetworkConnectionError
from pip._internal.network.session import PipSession
from pip._internal.network.utils import raise_for_status
if TYPE_CHECKING:... |
d3af892fed5682f2a7f69a4dfba7a9ada247bd590fd444ac0c8d218f7c49b649 | Python | 1,831 | 58 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
""" A collection of functions for running commands from the meme suite, FIMO and MEME.
"""
import logging
from .base import execute, get_config
def run_fimo_simple(que... |
f9811105f65b85367778ace3996967f008e84043bb62f69ee9e95abb89e384cd | Python | 1,832 | 60 | import re
import numpy as np
import pytest
from pandas import (
DataFrame,
MultiIndex,
)
class TestDataFrameDelItem:
def test_delitem(self, float_frame):
del float_frame["A"]
assert "A" not in float_frame
def test_delitem_multiindex(self):
midx = MultiIndex.from_product([["A... |
196fa5ca2856998efc5a7ff9f5055b6e8c4f35fd0334ccecf6f7a80feca87077 | Python | 1,833 | 78 | """
The first stage of the multi host run to get the contraction path
before initializing the cluster.
"""
import logging
import jax
import numpy as np
import tensornetwork as tn
import tensorcircuit as tc
from tensorcircuit.experimental import DistributedContractor
logging.basicConfig(level=logging.INFO)
logger = ... |
466c7287c0035e6ccf3a8c3bde01f595ed8339e370ade3214bd842a9259e987e | Python | 1,833 | 46 | from typing import List, Optional
import numpy as np
from grimace.frame_cropper_model import FrameCropperModel
from grimace.preprocessing.bounding_box import square_bounding_box, pad_bounding_box, crop_image_to_bounding_box
class FrameCropper:
def __init__(self, frame_cropper_model: FrameCropperModel, confidenc... |
9b054bf8e2b1eed293bcc7922cd4e1f23bfa56253af8d5dc5abe4ee210a690e7 | Python | 1,835 | 58 | import numpy as np
import pytest
from pandas._libs.tslibs import IncompatibleFrequency
from pandas import (
DataFrame,
Index,
PeriodIndex,
date_range,
period_range,
)
import pandas._testing as tm
class TestJoin:
def test_join_outer_indexer(self):
pi = period_range("1/1/2000", "1/20/2... |
7bd88b38df4f54898b50120c1a2a66cc43a232f94cc0a66bb697b939b2e45656 | Python | 1,837 | 51 | import torch
from torch import nn
def gaussian_smearing(distances, offset, widths, centered=False):
if not centered:
# compute width of Gaussian functions (using an overlap of 1 STDDEV)
coeff = -0.5 / torch.pow(widths, 2)
# Use advanced indexing to compute the individual components
... |
8e28d70ce6bceaa21e5b27c5d46ab843c9741e68645edf4dcea878b144030ff4 | Python | 1,837 | 73 | """Example: Using TiffCollectionReader to import TIFF files.
This example demonstrates how to use the TiffCollectionReader to import
a collection of TIFF files and make them compatible with the cali pipeline.
"""
from pathlib import Path
from rich import print
from cali.readers._tiff_collection_reader import (
... |
76a76b8e1ad3e736ecd66b6f25b9fe8eaf9eeb84368f12b7a3ee8b343f6fde73 | Python | 1,840 | 58 | """Defines ASCENT Exceptions.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent
"""
class MorphologyError(Exception):
"""E... |
39923b17030e7ae57fd56c5e624b7bf128b8dcf3b0edfcb13efad3d7a22fef87 | Python | 1,843 | 59 | import time
import numpy as np
from scipy.stats.mstats import gmean
import torch
from torchdiffeq import odeint
import detest
torch.set_default_tensor_type(torch.DoubleTensor)
class NFEDiffEq:
def __init__(self, diffeq):
self.diffeq = diffeq
self.nfe = 0
def __call__(self, t, y):
se... |
0481f2d1072fc42df1e5c546061446d3258179377457f82b1f1868e5a72d2924 | Python | 1,844 | 70 | import numpy as np
import netket as nk
import argparse
cm_to_hartree = 4.556e-6
# Define the argument parser
parser = argparse.ArgumentParser(description="Adjust input parameters for the script.")
# Add arguments (flags)
parser.add_argument("--L", type=int, default=4, help="Number of modes in the graph (default: 4)"... |
9a646155982d23a0fda63a825ab598715a7a68624604593b0c511b74ca0c7ec3 | Python | 1,844 | 73 | __all__ = ["setup_logger"]
import sys
import logging
import os
import csv
import io
from logging.config import dictConfig, fileConfig
def setup_logger(
name: str = None,
config: dict = None,
filename: str = None,
formatter=None,
stream=sys.stderr,
cfg_filename: str = None,
propagate: bool =... |
af785041cbb357c03814ef5df78faa5508085426b76de32b373f69489f560113 | Python | 1,846 | 55 | from __future__ import annotations
import pytest
from textstat.backend import counts
from .. import resources
@pytest.mark.parametrize(
"lang,text,n_syllables,margin",
[
("en_US", resources.SHORT_TEXT, 7, 0),
("en_US", resources.PUNCT_TEXT, 74, 2),
("en_US", "faeries", 2, 1),
... |
151f9618fed6b725d40738716c391590225ce2f911d7fbf0c2cb43b6b3d2ec0d | Python | 1,847 | 60 | """
Optimizing the parameterized circuit with progressively dense two-qubit gates,
as a potential approach to alleviate barren plateau.
"""
import tensorflow as tf
import numpy as np
import tensorcircuit as tc
K = tc.set_backend("tensorflow")
n = 10
nlayers = 3
g = tc.templates.graphs.Line1D(n)
def energy(params, ... |
7dde5f6e0f8a80fc766ff613801a5f806587e542e1a331be84c9262078c7762b | Python | 1,848 | 50 | import argparse
from pathlib import Path
import torch
import utils
from lightning_modules import LigandPocketDDPM
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('checkpoint', type=Path)
parser.add_argument('--pdbfile', type=str)
parser.add_argument('--resi_list', t... |
e21caabc57010a350d7e7163463b37e295cc03d5304a4c5e5e98d6cdd14199b7 | Python | 1,849 | 67 | from src.utils import get_lr
from src import constants
image_size = (64, 64)
batch_size = 32
base_lr = 3e-4
frame_stack_size = 16
config = dict(
image_size=image_size,
batch_size=batch_size,
base_lr=base_lr,
min_base_lr=base_lr * 0.01,
ema_decay=0.999,
train_epoch_size=72000,
num_epochs=[3... |
1a2414aa27f1b6dc094609262c4a2ae702058d39582c4010d67e4ac38126b22c | Python | 1,850 | 59 | import pytest
import numpy as np
from numpy.testing import assert_array_equal, assert_equal
from . import util
from pathlib import Path
def get_docdir():
parents = Path(__file__).resolve().parents
try:
# Assumes that spin is used to run tests
nproot = parents[8]
except IndexError:
d... |
b07ebc69609a6c8daacb975b8314025de4dfbe7d4d4200df335393e288c599a5 | Python | 1,850 | 54 | import numpy as np
import pytest
from pandas import CategoricalIndex
import pandas._testing as tm
class TestFillNA:
def test_fillna_categorical(self):
# GH#11343
idx = CategoricalIndex([1.0, np.nan, 3.0, 1.0], name="x")
# fill by value in categories
exp = CategoricalIndex([1.0, 1.... |
f5b0e8e275e205b4ce03dfe320dc4189d5d5b2c7af7efbc532ccdc82451cc62e | Python | 1,850 | 60 | import abc
import torch
from scipy.integrate import solve_ivp
from .misc import _handle_unused_kwargs
class ScipyWrapperODESolver(metaclass=abc.ABCMeta):
def __init__(self, func, y0, rtol, atol, min_step=0, max_step=float('inf'), solver="LSODA", **unused_kwargs):
unused_kwargs.pop('norm', None)
u... |
8308485eb249a3d0e279c6862c21cb2418e1c769d51a5eb21eaf3400e5104913 | Python | 1,852 | 58 | import numpy as np
import numpy.matlib
from numpy.testing import assert_array_equal, assert_
def test_empty():
x = numpy.matlib.empty((2,))
assert_(isinstance(x, np.matrix))
assert_(x.shape, (1, 2))
def test_ones():
assert_array_equal(numpy.matlib.ones((2, 3)),
np.matrix([[ 1., ... |
dfc21a26c6b68fbb5fd0dc8db3614a91b02250302c51fe38faa783d76d79773f | Python | 1,852 | 64 | """Utility functions."""
import numpy as np
import warnings
import functools
def zero_padded_numbers(numbers: list[int], prefix: str = "") -> list[str]:
"""Format integers as zero-padded strings sized to the largest value.
For example, ``[0, 1, 13]`` becomes ``["00", "01", "13"]``. The padding
width is ... |
ccefaacb10a29a9d3c166c5fd28862ff63e2530602d7d0a62e26b6d618c6b70f | Python | 1,853 | 67 | from src.utils import get_lr
from src import constants
image_size = (64, 64)
batch_size = 24 #32
base_lr = 3e-4
frame_stack_size = 16
config = dict(
image_size=image_size,
batch_size=batch_size,
base_lr=base_lr,
min_base_lr=base_lr * 0.01,
ema_decay=0.999,
train_epoch_size=72000,
num_epoch... |
ed125a45de98f590f746f403921f47a42fdacfb071fc983102c0c0bbcae92309 | Python | 1,853 | 61 | import yaml
from pathlib import Path
from skimage.io import imread, imsave
from tqdm import tqdm
import numpy as np
from natsort import natsorted
import rpack
def crop(img):
mask = img[..., :3].max(axis=-1)
nz = np.nonzero(mask > 0)
y_min, y_max = np.min(nz[0]), np.max(nz[0])
x_min, x_max = np.min(nz[... |
02807f428a767da9aa40a9d1544c2d8a93f857dc2c533b2c2b6be0fb57765a84 | Python | 1,855 | 52 | import logging
import os
import matplotlib.pyplot as plt
from yass.batch.pipeline import BatchPipeline, PipedTransformation
from yass.batch import RecordingsReader
from yass.preprocess.filter import butterworth, standarize
logging.basicConfig(level=logging.DEBUG)
path_to_neuropixel_data = (os.path.expanduser('~/da... |
0729fd8a7658056c47f19cfaa1971b6b32c895df07856501370d5641aed2e517 | Python | 1,858 | 92 | # %%
import numpy as np
import pandas as pd
import polars as pl
from pymer4.models import lmer, compare
import seaborn as sns
# %%
# read peak data
peaks = pd.read_csv("../results/csv/mismatch_peaks.csv")
# read behavioral halts data
behavioral_results = pd.read_csv('../behavioral_data/collected_results.csv')
# rem... |
2d20e5a2ca9f5968c644c08ad4741db8d126ad9687de1a3719277ca3dc8cef34 | Python | 1,858 | 49 | from .lifneuron import LIFNeuron
class NoteLIFNeuron(LIFNeuron):
'''
classdocs
'''
def __init__(self, tau_ref=0.5, vthresh=5, Rm=2, Cm=0.2):
'''
Constructor
'''
LIFNeuron.__init__(self, tau_ref, vthresh, Rm, Cm)
def setPreference(self):
self.selectivity = ... |
90b7e83a85d102f9c0ffdb529e19f4d3c68478ce8c6872648dcc7286dec943da | Python | 1,858 | 53 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 7 17:27:25 2019
@author: bxin
"""
import os
import argparse
import h5py as h5
import CNN_utils as util
datadir = "../data/SELEX_"
def main():
args = loadargs()
for tf in args.tfs:
print ("------------Intretation method: " + args.method + " for "+ ... |
df2075b9431842d3dc861394fb862c7c3120f91463150029259b9dee7f24a252 | Python | 1,863 | 64 | # _*_ coding: utf-8 _*_
'''
Define two simple functions to write and read from csv/text files.
'''
import csv
# define a function to write to a file
def write_to_csv(data, csvfile, delimiter=','):
'''Simply write a row of data to csvfile appending
contents. There is another method to write several
rows (csv.writero... |
9ee556ff0fe7b55c69136e842c4be780c634374e2c14bb228d747265944e146f | Python | 1,865 | 62 | from __future__ import annotations
import argparse
import subprocess
import sys
from ._implementation import DependencyGroupResolver
from ._toml_compat import tomllib
def _invoke_pip(deps: list[str]) -> None:
subprocess.check_call([sys.executable, "-m", "pip", "install", *deps])
def main(*, argv: list[str] | ... |
80fe86893d27b2f296c2e6b2ba40fa34c08ee91015da137a9b30b6191951c410 | Python | 1,866 | 61 | """
Interactive display of volume FastSRM results in the browser
Authors: Ana Luisa Pinho
Created: April 2021
Last update: May 2021
Compatibility: Python 3.7
"""
import os
import numpy as np
import ibc_public.utils_data
from nilearn.input_data import NiftiMasker
from nilearn import plotting
# Mask of the grey m... |
89ff569f1af245d521b9bfb7ca375310a3b63cc13e6217f96081bc7b69ef0175 | Python | 1,869 | 60 | import pytest
from pandas import DataFrame
from pandas.tests.plotting.common import (
_check_plot_works,
_check_ticks_props,
_gen_two_subplots,
)
plt = pytest.importorskip("matplotlib.pyplot")
class TestCommon:
def test__check_ticks_props(self):
# GH 34768
df = DataFrame({"b": [0, 1,... |
8cdde0c4b8a1ea95d9ee507c0ce1733e2c14e8469794b9054f8bcc2da1ca15b4 | Python | 1,869 | 53 | import pysam
import re
from sinto import utils
from sinto.constants import OUT_FORMAT_CONVERSION
from contextlib import closing
def move(
bam: str,
output: str,
cb_tag: str = "CB",
cb_regex: str = "[^:]*",
from_tag: bool = True,
out_format: str = "t",
) -> None:
"""Copy cell barcode from t... |
aa999dac585056840dc6c56b6e467f10766676fcf6c2f05dc9386dd8cceebb5d | Python | 1,871 | 50 | import torch
import torch.nn as nn
"""
FCN for energy prediction
"""
class EnergyLayer(nn.Module):
def __init__(self, num_in, num_out, activation, zero_init=False):
super(EnergyLayer, self).__init__()
self.num_in = num_in
self.num_out = num_out
self.zero_init = zero_init
s... |
0669c432544417b1b4079cdd68946c773a8845d87c7628938ac05b09523a169d | Python | 1,873 | 63 | from __future__ import annotations
from typing import TYPE_CHECKING
from pandas import (
DataFrame,
concat,
)
if TYPE_CHECKING:
from pandas._typing import AxisInt
def _check_mixed_float(df, dtype=None):
# float16 are most likely to be upcasted to float32
dtypes = {"A": "float32", "B": "float32"... |
41e0e8878e2d4bfff2f4b2bb2f050101cf920f9452fa984f03879858f979c888 | Python | 1,873 | 64 | import numpy as np
import pytest
import pandas.util._test_decorators as td
from pandas import DataFrame
import pandas._testing as tm
class TestCopy:
@pytest.mark.parametrize("attr", ["index", "columns"])
def test_copy_index_name_checking(self, float_frame, attr):
# don't want to be able to modify th... |
cc080143a91692640a50eeee3b29a02fa95741b939e74b3cb7919878b089427c | Python | 1,873 | 37 | #!/usr/bin/env python3
"""R1 scaffold — escape-recoverability margin M^D per PREREG_REANALYSIS.md (frozen).
Status: SCAFFOLD. Blocked by design behind two gates: (1) R0 must reproduce first;
(2) PREREG-MAPPING (column mapping from structure-only inspection) must be committed
before any outcome value is computed. This ... |
d3dfbee1094bd4283877cd05ef4617007d7a3083579576e067b33b9a58ffe68c | Python | 1,873 | 53 | import torch
from torch import optim
from protgps.utils.registry import register_object
from protgps.utils.classes import ProtGPS
@register_object("reduce_on_plateau", "scheduler")
class ReduceLROnPlateau(optim.lr_scheduler.ReduceLROnPlateau, ProtGPS):
"""
https://pytorch.org/docs/stable/generated/torch.optim... |
4b1d7f9008d7b1dd6e669dff99d6eec78730c46685c36926de82a936d07c086a | Python | 1,874 | 63 | '''
Created on 2014.11.13.
@author: Liang Qian
'''
import sys
sys.setrecursionlimit(1000000)
from data import globaldata as Global
class Layer():
'''
layer class is used to build brain cortical layer of cortex
class members are as follows:
@param name: layer name(L1,L2,L3,.etc)
@param neuronnum: t... |
93ac8ff28af68b4fc70a9761a4fef6c753ae9fc2cb68f8a7331bdd1a66d14d14 | Python | 1,875 | 57 | import os
import viz
import vizjoy
import sys
sys.path.insert(0,os.path.realpath('..'))
from defineOptions import *
# ---------------------------
# Joystick & Movement related
# ---------------------------
# wait for specific joystick input before code proceeds
class waitJoy(viztask.Condition):
def __init__(self... |
e6b937e861de1cb712edd5ca1809f7fce8f7b6a64c56579613d9eb4813eb9a84 | Python | 1,875 | 70 | from __future__ import annotations
import json
from pathlib import Path
from typing import TYPE_CHECKING
import tifffile
from fonticon_mdi6 import MDI6
from pymmcore_plus import CMMCorePlus
from qtpy.QtWidgets import QFileDialog, QPushButton, QSizePolicy
from superqt.fonticon import icon
if TYPE_CHECKING:
from q... |
0bf9046b22af483b09cfbd839025eefdab3efb1268a4df11228786bc8d4f06b5 | Python | 1,877 | 60 | import yaml
import nrrd
from tqdm.contrib.concurrent import process_map
from CrystalTracer3D.io import *
from CrystalTracer3D.util import *
from CrystalTracer3D.plot import *
with open('config.yml', 'r') as ymlfile:
cfg = yaml.safe_load(ymlfile)
def take(args):
lut, path = args
lut = [0] + list(lut) ... |
699714ab72b55acb7792020a847206fed5421be29610b80b7b691c664d2aff8e | Python | 1,877 | 59 | import torch.nn as nn
from .self_mixing import SelfMixing
"""
Like a linear layer, but acting on spherical harmonic features (optionally mixes features)
"""
class SphericalLinear(nn.Module):
def __init__(
self,
order_in,
num_in,
order_out,
num_out,
clebsch_gordan=... |
dabf30e4955e33591d4b34fcd83842afc49702fb2f4897077ca2a848d7cc5f29 | Python | 1,877 | 42 | from typing import Optional
from qtpy.QtCore import QModelIndex, QObject, QPoint, Qt, Signal
from qtpy.QtWidgets import QMenu, QStyle, QTreeView, QWidget
from ..models import IMCFileModel
class IMCFileTreeView(QTreeView):
class Events(QObject):
imc_file_closed = Signal(IMCFileModel)
def __init__(se... |
baa6108ced938265c313b7328f726991359f914598d22c879c2bbc78bff2791a | Python | 1,879 | 59 | import argparse
import os
import numpy as np
import pandas as pd
# import torch
def get_args():
parser = argparse.ArgumentParser(
description="Convert unitig presence/absence to node features"
)
parser.add_argument(
"--unitig_query_results", type=str, help="Results from unitig-caller que... |
d05f8c35ce3cc4b5fcba126c455e2fd0839f00c34515b3816498bd16acdd08b2 | Python | 1,879 | 66 | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import argparse
import glob
import os
import re
import sys
# Only strip targeted libraries when checking prefix
TORCH_LIB_PREFIXES = (
# requirements/*.txt/in
"torch=",
"torchvision=",
"torchaud... |
adaa8a76212f8ba6108ee440b87ebd8e31f69c97b18eee2d94ea68430fdab92c | Python | 1,882 | 68 | """
jax pmap paradigm for vqe on multiple gpus
"""
import os
os.environ["XLA_FLAGS"] = "--xla_force_host_platform_device_count=8"
from functools import partial
import jax
import optax
import tensorcircuit as tc
K = tc.set_backend("jax")
tc.set_contractor("cotengra")
def vqef(param, measure, n, nlayers):
c = tc... |
fec0d233a4aeaa388c7316cd86748b1445b03201e67e9e77ce2be979fe653db3 | Python | 1,882 | 57 | # coding: utf-8
import random
import string
import numpy as np
import torch
_sqrt2 = np.sqrt(2)
def generate_id(size=8, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits):
"""Used for creating a "unique" id for a run (almost impossible to generate the same twice)"""
return "".join(rando... |
f34b3c2f5aa4190e80673d1d49a1efe35fde99f129204054f30f05e9c7d46717 | Python | 1,883 | 55 | '''
Related Figures:5a
'''
import time
import numpy as np
import scipy.signal as signal
def wave_filter(sequence,cof,sf,mod,N=4):
if len(sequence.shape)==1:
sequence=sequence.reshape(1,-1)
b, a = signal.butter(N, cof, btype=mod,fs=sf)
filtedData = signal.filtfilt(b, a, sequence)
return filtedDa... |
ff5c7d2b409406d12a514e14ef2782c752fd3a302db630eda4bc9ca65f5505b2 | Python | 1,883 | 64 | """ Creates binary time series of dendritic event occurrences
Author: Drew B. Headley
"""
import numpy as np
import sys
sys.path.append(".") # have to do this for relative imports to work consistently
from .ser_pt import ser_pt
def ph_seg_dendevt(seg_df, rhym_ser, step=10):
"""
Takes a dendritic events dat... |
08970561aafeb0b50455524f73f0bed573f5bdafea1da0997d92e98a0f25ba1f | Python | 1,884 | 56 | from __future__ import annotations
import re
from ..transformations._remove_punctuation import remove_punctuation
from ..utils._typed_cache import typed_cache
from ..utils.constants import RE_CONTRACTION_APOSTROPHE
@typed_cache
def list_words(
text: str,
rm_punctuation: bool = True,
rm_apostrophe: bool ... |
278e292c0030ccb54b4f8b39af725d972e03021c36693bacf619af9abb07868d | Python | 1,885 | 51 | import os
import warnings
from argparse import ArgumentParser
from argparse import ArgumentDefaultsHelpFormatter
import pandas as pd
import joblib
from ..utils.norm_utils import annotate_kmer_information, create_kmer_mapping_df, \
create_norm_dict
def argparser():
parser = ArgumentParser(
formatte... |
8d153bcaeea8a95559a23f3190a1894378e4a798bb6d1cd0fb976b2921bb7fa4 | Python | 1,886 | 59 | import pandas as pd
import numpy as np
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "src/"))
import cc
from numpy.random import randint
import h5py
import matplotlib.pyplot as plt
print(__file__)
spikes = h5py.File("../data/spikes.h5", "r")
spk_t = np.array(spikes["spikes"]["biophysic... |
ed11641f52c14a3ca675cd123c41dd4cef4c1ef72ab3b3392c78231f6cc9c280 | Python | 1,886 | 81 | ## Compute scCpG for a chr
## Test on chr1
## 100kb
import pandas as pd
import numpy as np
from scipy.stats import rankdata
from multiprocessing import Pool
CpG = pd.read_table('reference/hg19.100kbin.CpG.txt', header=0)
print(CpG.iloc[:5,:])
RRes = []
meta_data = pd.read_csv('PseudoTime/diffMap2.csv',index_col=0)
... |
2aa23090928c1e248dc43251ce8b17a4c10c137ca6b6f403f315a336c5de0fe5 | Python | 1,887 | 58 | import numpy as np
import torch
from sklearn import preprocessing
import pandas as pd
from .preprocess import StandardScaler
from omegaconf import DictConfig, open_dict
def load_abcd_data(cfg: DictConfig):
ts_data = np.load(cfg.dataset.time_seires, allow_pickle=True)
pearson_data = np.load(cfg.dataset.node_f... |
45228bcd53a3f7ead9b9bb3bc8f142ff44055e21be43366791fc33b1577fd519 | Python | 1,887 | 59 | """Utility functions for plate map hashing and comparison."""
from __future__ import annotations
import hashlib
import json
def compute_plate_map_hash(plate_maps: dict[str, dict[str, str]] | None) -> str | None:
"""Compute a stable hash from plate_maps dictionary.
This hash is used to detect when plate map... |
93374a7c7d01a034a168f80392c4bcbad8464a07098bd6e1ee9ffb28dcaa1fff | Python | 1,887 | 58 | """
Stability metric example
"""
import os.path as path
import numpy as np
import matplotlib.pyplot as plt
from stability_evaluation import (RecordingBatchIterator, MeanWaveCalculator,
RecordingAugmentation,
SpikeSortingEvaluation)
ROOT = path.join... |
d2074781df69198aadcb20578bb0f0f4adf80d9fc9ddc09788610efb6fc14a98 | Python | 1,887 | 72 | """
Configuration parameters for EEG frequency ratio analysis.
"""
import os
from pathlib import Path
# Golden ratio constant
PHI = (1 + 5**0.5) / 2 # ≈ 1.618033988749895
# Frequency band definitions (Hz)
BANDS = {
'theta': (4.0, 8.0),
'alpha': (8.0, 13.0),
'beta': (13.0, 30.0),
'gamma': (30.0, 45.0... |
a6d4963616b8078fa120d67831771b631387b26aa9d8b5022fd8970a9e82ce6b | Python | 1,890 | 57 | from typing import Optional
from fireworks import LaunchPad, Workflow
from pymatgen.core import Structure
from atomate.openmx.fireworks.core import OpenmxScfFW
from atomate.openmx.powerups import add_additional_fields_to_taskdocs, set_execution_options
def submit_single_openmx_from_poscar(
launchpad_file: str,
... |
b4fc74ac9093219f62a1180b3581b8a627c26c0c1345465d76f2f0f8d7c0936c | Python | 1,891 | 72 | """
pygments.plugin
~~~~~~~~~~~~~~~
Pygments plugin interface.
lexer plugins::
[pygments.lexers]
yourlexer = yourmodule:YourLexer
formatter plugins::
[pygments.formatters]
yourformatter = yourformatter:YourFormatter
/.ext = yourformatter:YourFormatter
... |
55878c1b7ea0b0c92f27ed8a684da4a045c4b65beaff2c3c5a6de89b5cff7a5d | Python | 1,893 | 63 | from typing import Any, cast
from sqlparse import parse
from sqlparse.tokens import CTE
from sqlparse.sql import Identifier, IdentifierList, Parenthesis
def extract_ctes(sql):
""" Extract constant table expresseions from a query"""
p = parse(sql)[0]
# Make sure the first meaningful token is "WITH" which ... |
9c5fb04194f7de0b37792124a09b95acdf0b46e6d9a469e4b83dd187f6dc4e6b | Python | 1,894 | 52 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
# for test files, silence irrelevant and noisy pylint warnings
# pylint: disable=no-self-use,protected-access,missing-docstring
import unittest
from Bio.SeqFeature impor... |
0c90fcc9cba750fe9c4ce686c23196cb4a5b279c3c2db0f1a87dc41205d40319 | Python | 1,895 | 64 | import pandas as pd
import numpy as np
from tqdm import tqdm
tqdm.pandas(ascii=True)
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import DataStructs
from joblib import Parallel, delayed
import os
def ecfp4(smile, bitsize = 1024):
arr = np.zeros((bitsize,), dtype=np.bool)
try:
... |
8b8e59ede9b002725ba11a761e644de5c6cf2a762ac056af5e512d613203c9b1 | Python | 1,895 | 64 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 17 16:54:12 2019
@author: wanxiang.shen@u.nus.edu
@calculate ErG fps, more info: https://pubs.acs.org/doi/full/10.1021/ci050457y#
"""
_type = 'Pharmacophore-based'
import numpy as np
from rdkit.Chem import AllChem
## get info from : https://git... |
deae2659a5187c7bba26adeac22ccc86ce0ed289dc34070e6b003c2bcbbfc4eb | Python | 1,895 | 57 | ## ...........................................................................
##
## PIMMS (Polymer Interactions in Multicomponent Mixtures)
## Alex Holehouse, Pappu Lab
## Copyright 2015 - 2026
## ...........................................................................
##
## Developer sanity-check script for the... |
2ec0a411d7c93c49e558696051515e5d887ff4804c16f0ec062f30c30d4eeccd | Python | 1,898 | 68 | """Configures the sound devices and saves to a config file. Run this if you get no
sound from your experiment:
python config_sound.py
and follow the prompts on screen. You need to have the speakers/headphones on for this.
"""
import argparse
import sounddevice as sd
import soundfile as sf
TEST_SOUND = './sounds/co... |
6a652d91d8587101bc66bf82a0c33f91545a731922bc2d568313756fadca29d5 | Python | 1,898 | 57 | """
Given a list of integers, made up of (hopefully) a small number of long runs
of consecutive integers, compute a representation of the form
((start1, end1), (start2, end2) ...). Then answer the question "was x present
in the original list?" in time O(log(# runs)).
"""
import bisect
from typing import List, Tuple
... |
ddb10ca098cedcdb7cebd2c813c28add269dddc3249f052fb08f246e9d0f0ec9 | Python | 1,898 | 48 | import numpy as np
import scipy.signal as sig
def cross_corr(target, signal, normalize=True, limit=True, fs=44100):
"""Calculates the complex cross-correlation between the target and signal.
Parameters
----------
target : array
The first signal
signal : array
The second signal
... |
466c0ecbac4d86067ad6a9a4fcf167439b16f9156b90e86c97802f432a8eb806 | Python | 1,901 | 63 | from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
)
import numpy as np
from pandas._libs import lib
from pandas.errors import LossySetitemError
from pandas.core.dtypes.cast import np_can_hold_element
from pandas.core.dtypes.common import is_numeric_dtype
if TYPE_CHECKING:
from... |
22d895f7b18ff960d1b9c18d335d4014162b609a91e4b33146f1ea28c5e31653 | Python | 1,903 | 86 | #!/usr/bin/env python
# coding: utf-8
try:
get_ipython # type: ignore
except NameError:
def get_ipython():
class _DummyShell:
def run_line_magic(self, *args, **kwargs):
pass
def run_cell_magic(self, *args, **kwargs):
pass
def magic(s... |
b3012fbc22c731e956d448027cf01109c5b196d9424bc07107197961d85a49ea | Python | 1,903 | 55 | from PySide6.QtCore import QTime
from PySide6.QtWidgets import QDialog, QDialogButtonBox
import logging
from app.layout.recording_name_dialog import Ui_DRecordingName
from app.model.grimace_recorder_model import GrimaceRecorderModel
from util.trace import Trace
logger = logging.getLogger("grimace_box."+__name__)
P... |
f4133f550a80e68f7d994aebcc3ece30148c9f81939d142f07137be278cccfc1 | Python | 1,908 | 60 | import pandas as pd
import pickle
from czifile import imread
from pathlib import Path
from crystal_tracer.visual.draw import draw_contour, draw_circles
import numpy as np
import cv2
out_dir = Path('../../data/case2')
flood_dir = out_dir / "flood"
csv_dir = out_dir / "detection"
draw_dir = out_dir / "draw"
def main... |
60bb694e7662bb4ee7637a0af677d1e84f58d4504784fe4f5fc82f90959c7da8 | Python | 1,910 | 70 | """
pygments.filter
~~~~~~~~~~~~~~~
Module that implements the default filter.
:copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
def apply_filters(stream, filters, lexer=None):
"""
Use this method to apply an iterable of filter... |
88f7f348fc74080af1efd9daef1708f5970f4c0c2aef721d3827111153bb9381 | Python | 1,910 | 49 | import pytest
from pandas import Index
import pandas._testing as tm
def test_add_prefix_suffix(float_frame):
with_prefix = float_frame.add_prefix("foo#")
expected = Index([f"foo#{c}" for c in float_frame.columns])
tm.assert_index_equal(with_prefix.columns, expected)
with_suffix = float_frame.add_suf... |
c351af2e6dc5b4a41df6dda7c0ddef179e57e5fd0640a182197a58159c484e90 | Python | 1,910 | 96 | from textwrap import dedent
import pytest
from pandas import (
DataFrame,
Series,
)
pytest.importorskip("jinja2")
from pandas.io.formats.style import Styler
@pytest.fixture
def df():
return DataFrame(
{"A": [0, 1], "B": [-0.61, -1.22], "C": Series(["ab", "cd"], dtype=object)}
)
@pytest.fi... |
c82c6f9d6fbd09e80e826c59535610318e35a5b7479621fcbbd452df748b42c7 | Python | 1,911 | 55 | import argparse
import os
import numpy as np
import pandas as pd
def get_args():
parser = argparse.ArgumentParser(description="Get the selected kmers")
parser.add_argument("dist_fp", type=str, help="Distance matrix file path")
parser.add_argument("antimicrobial", type=str, help="Antimicrobial drug")
... |
61fcc81dc87cb53676ca2276de4e70ff3392c1bf9292a49b98e402f598d34133 | Python | 1,912 | 35 | """Stage 3b: Replogle tutorial batched GCATE + LFC on the raw-count subset with
the 0.1.0 defaults. ``r`` is the JIC choice from ``2_estimate_r.py``
(``results/replogle-r.csv``; r = 10 on the raw counts, 2026-09-21) unless given
on the command line. Writes ``results/replogle_results_r{r}.h5`` (resumable
cache); copy it... |
fd3a5fef3ada1355e5f7cdeb954cecce81bca050c5dcd6c03765db50fd8c3419 | Python | 1,912 | 51 | import os
import csv
import json
import glob
# Paths
metadata_csv_path = "/mnt/nas7/data/maria/final_features/ct-fm/dicom_metadata/dicom_metadata.csv"
image_folder = "/mnt/nas7/data/reza/registered_dataset_all_doses_pad"
output_json_path = "/mnt/nas7/data/maria/final_features/dicom_metadata.json"
# Read metadata from... |
0fb6e5bb3eb603568b650f576e95f4fa70c16a5f4a3eda7fa63a2493660d63c1 | Python | 1,913 | 78 | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import io
import os
# Classes that can undo reading data from
# a given type of data source.
class Unreader:
def __init__(self):
self.buf = io.BytesIO()
def chunk(self):
raise NotImpleme... |
d2a3142be60b32baf0ec554303e369e4dae23ec53a2160b051ebbaa992757f9e | Python | 1,913 | 81 | """Test functions for FOOOF synth."""
from fooof.tests.utils import default_group_params
from fooof.synth import *
from fooof.synth import _gen_power_vals
###################################################################################################
##############################################################... |
538f5e81b2bd1000eedd8e60b2f42ec7136c111f0e0b8354e762c705c1703570 | Python | 1,914 | 60 | import numpy as np
import json
from scipy import interpolate
tol = 0.1
spline_interpolate = True
fine_grid_size = 200
with open('band.json', 'r') as f:
data = json.load(f)
energies = np.array(data['spin_up_energys']).T # [band, kpoint] -> [kpoint, band]
energies = np.sort(energies, axis=1)
nbnd = energies.shape[... |
5f906e03da3e51a67221a9d5f8f03b4a30b6d87ec28f6e46e80ee2dd33e69e9f | Python | 1,915 | 84 | import copy
import numpy as np
from scipy.stats.distributions import norm
from lmfit import Parameters
from .fid_corrections import minimisation
def edge_removal(total_spectral_ydata):
if total_spectral_ydata[0] > 0:
i = 0
while total_spectral_ydata[i] > 0:
total_spectral_ydata[i] = 0... |
636f7e01c65542ee35d6242928b2d6646acad382345328c55870da30fb8d9b0e | Python | 1,915 | 47 | import torch
import numpy as np
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
def validation(epoch, model, criterion, device, val_loader, model_type, single_channel_idx: int = 0):
"""
Validation logic for a single epoch (no parameter updates).
"""
model.eval()
... |
03b58f176aa8dac6893cd6e4c598b38ad87666f2be4163c296cb275db6560f1d | Python | 1,916 | 63 | from matplotlib.transforms import Transform
import torch
from torch import nn
from torch import optim
from inclearn import models
from inclearn.convnet import sew_resnet
from inclearn.datasets import data
from inclearn.convnet.resnet import SEFeatureAt
def get_optimizer(params, optimizer, lr, weight_decay=0.0):
i... |
553b2aa92a6f552f002a1ee1cce98a4dc772f02bfcd36133530caa08039900fe | Python | 1,916 | 53 | # Tests for SNAP2 class in ExternalCode.py
import pandas
import numpy
import pytest
import sbmlcore
#Loading the wrong .csv file
def snap2_loaded():
with pytest.raises(IOError):
file = sbmlcore.SNAP2('tests/3pl2-snap2.csv')
def csv_interpret():
file = sbmlcore.SNAP2('tests/3pl1-snap2.csv')
b = {'s... |
c63afc1040a9ed64ad70878463c60d866919f74436a3e9778b3a2590ba46d96d | Python | 1,916 | 60 | import re
import numpy as np
import pytest
import pandas as pd
class TestSetitemValidation:
def _check_setitem_invalid(self, arr, invalid):
msg = f"Invalid value '{str(invalid)}' for dtype {arr.dtype}"
msg = re.escape(msg)
with pytest.raises(TypeError, match=msg):
arr[0] = in... |
f05247c5bf69e8d8042349b31718855da2bda41ffe70ac01b90b12d5e13401e7 | Python | 1,919 | 63 | import sys
from contextlib import closing
import pysam
from sinto.constants import OUT_FORMAT_CONVERSION
def header_line_to_str(line):
return "\t".join(f"{k}:{v}" for k, v in line.items())
def build_header(header, tag_vals):
new_rg_lines = []
for val in tag_vals:
for rg in header["RG"]:
... |
19bf1e9b0fb9d1aae7d08faf6f2cb15bc09990ebf88fb06d5d58062fd2cdf717 | Python | 1,920 | 56 | """Main file for BiG-SCAPE dereplicate module"""
# from python
import logging
from datetime import datetime
# from other modules
from big_scape.utility.version import get_bigscape_version
from big_scape.dereplicating.input_data_loading import load_input_data
from big_scape.dereplicating.sourmash_utilities import (
... |
85339d0d7157846bb201c06f893de07a17c1e92871f44f7e3fedd3921a70a8dd | Python | 1,920 | 61 | import numpy as np
import yaml
import nrrd
from tqdm.contrib.concurrent import process_map
from CrystalTracer3D.io import *
from CrystalTracer3D.util import *
from CrystalTracer3D.plot import *
with open('../config.yml', 'r') as ymlfile:
cfg = yaml.safe_load(ymlfile)
def take(args):
lut, path = args
in... |
132029eb7602ed36fecc9055d6dcabacbc10c6b657b164b4c1c3689c228bd39d | Python | 1,921 | 48 | """
Utilities related to model evaluation
==> Inspired by the GitHub repository of Wood et al. 2022 (https://github.com/MIDIconsortium/BrainAge)
"""
import torch
from tqdm import tqdm
def evaluate(net, data_loader, criterion, device, eval_type, print_message=False):
""" Validation or test function
:param ne... |
81506051cff7b922b44335d84355dbbad69c1068dfe380a0c40698920c1fb9c6 | Python | 1,924 | 70 | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
from gunicorn.errors import ConfigError
from gunicorn.app.base import Application
from gunicorn import util
class WSGIApplication(Application):
def init(self, parser, opts, args):
self.app_... |
681c1a0ff4b9e926e0a2922f6b2566a64d18dbcbb06360b905a6f5c25dc1a7e2 | Python | 1,925 | 71 | import sys
from dataclasses import dataclass
@dataclass
class WindowsConsoleFeatures:
"""Windows features available."""
vt: bool = False
"""The console supports VT codes."""
truecolor: bool = False
"""The console supports truecolor."""
try:
import ctypes
from ctypes import LibraryLoader... |
52c917b72991c323a5412ffee8524ea181cfb839694d2fb1591e7f9be30e3a0d | Python | 1,926 | 53 | # -*- coding: utf-8 -*-
from rdkit import Chem
import numpy as np
import pandas as pd
from tqdm import tqdm
tqdm.pandas(ascii=True)
from molmap.feature import descriptor
f = descriptor.property.FilterItLogS
fsol_calculator = lambda x:f(Chem.MolFromSmiles(x))
df_train = pd.read_csv('../train.csv', index_col = 0)
df... |
03114216673852cdff10f4892af231374ec55a1a9ff93e69d24e0e20f37f5112 | Python | 1,927 | 56 | import logging
import cv2
from app.dataflow.qqueue import IQueue
from util.trace import Trace
logger = logging.getLogger("grimace_box."+__name__)
class FPSRenderer(IQueue):
@Trace.trace(logger)
def __init__(self, output_queue: IQueue, timestamp_history_size: int = 10):
self.output_queue = output_qu... |
c717a93bd8bb0c7b2a910ae004476e2ed7e8cf6402b93ebf81b2f85d237585b5 | Python | 1,928 | 38 | """Jinja is a template engine written in pure Python. It provides a
non-XML syntax that supports inline expressions and an optional
sandboxed environment.
"""
from .bccache import BytecodeCache as BytecodeCache
from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache
from .bccache import MemcachedByteco... |
e827236c637b34b63284aa8cfaabc37a2ece568c8f332d136121ddba010e95df | Python | 1,929 | 44 | from tomography_python_programs._metadata_models.relion.tilt_series import RlnTiltSeries
from tomography_python_programs._metadata_models.relion.tilt_series_set import RlnTiltSeriesSet
def test_read_single_tilt_series_metadata(tilt_series_star_file):
"""Simple parsing test."""
tilt_series = RlnTiltSeries.from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.