sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
20f462cadf897e57853d52efee3c7110f41d9297a66d29fa1b28bb1cbff58dba | Python | 2,523 | 52 | import os
from os import path
import glob
import argparse
from base import diffeo
from base import surfaces
def main():
parser = argparse.ArgumentParser(description='Computes isosurfaces over directories')
parser.add_argument('dirIn', metavar='dirIn', type = str, help='input directory')
parser.add_argumen... |
ac61cfc2dc92e2f16f563cb89467a24ae6c3bbbb5c5dfcb09e392b7c8f4f3186 | Python | 2,524 | 97 | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
d31c2d3d2b91a4b70c5d413d2dcaf9ec955275dbe16f4fa2a8c80562bac82bdf | Python | 2,525 | 59 | """Data loading, preprocessing, and augmentation for pose estimation.
**Three-stage factory pipeline** (the main entry points for all callers):
1. :func:`get_imgaug_transform` — build an ``imgaug`` augmentation pipeline from config.
2. :func:`get_dataset` — build a labeled dataset that pairs images with CSV keypoints... |
7275dfd712dc0d0cd827a6d0dc06d594cbf124f2189a01ee0e34e98f5c99ab79 | Python | 2,526 | 85 | '''
For parsing files containing selection data
Formatted for a table from Grossman et al.'s paper,
"Identifying Recent Adaptations..."
Loads the data and allows for lookups.
Because the data is non-overlapping and in genome order,
loading and lookups are very fast
Author: Rebecca Riley
Date 06/12/2023
'''... |
96bf07129d725bd9106a1f5949e269ec0b732b6aeeba3d7d0fb884bce7659a1f | Python | 2,526 | 70 | import numpy as np
import random
import os
import sys
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
import time
import sklearn.linear_model
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Perceptron, LogisticRegres... |
5ef711904b8bfdd899e1047733081a06c869716652c33530658d4739c16c8894 | Python | 2,529 | 75 | import argparse
import pandas as pd
import random
import glob
import os
import numpy as np
# Parse command line arguments
parser = argparse.ArgumentParser(description='Split dataset.')
parser.add_argument('--dataset_dir',
required=True,
metavar='dir/to/dataset',
... |
a0c1e96a45d89e8c98464a169302d919f91477ad27307497b4a25ec27ffbaec4 | Python | 2,529 | 72 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestSeriesArgsort:
def test_argsort_axis(self):
# GH#54257
ser = pd.Series(range(3))
msg = "No axis named 2 for object type Series"
with pytest.raises(ValueError, match=msg):
ser.a... |
5b6130f8089f870417b7ffe1e558b4cced8a0e6a7fd24ac180f40b92bdf216f6 | Python | 2,530 | 82 | #python calcngramprobtoks.kenlm.py --fwprobs genmodel/fw.5.probs.tmp [--uprobs genmodel/fw.1.probs.tmp] [--bwprobs genmodel/bw.5.probs.tmp] > $@
#from __future__ import division
import re
import sys
OPTS = {}
for aix in range(1,len(sys.argv)):
if len(sys.argv[aix]) < 2 or sys.argv[aix][:2] != '--':
#filename ... |
28192f9edae781b05b40f757ec8591057f11832737fb32fa0b22745afc686f65 | Python | 2,533 | 51 | """Tests for total variation denoising."""
import pytest
import torch
from mrpro.algorithms.denoiser import total_variation_denoising
from mrpro.data import IData
from mrpro.utils import RandomGenerator
from tests.helper import relative_image_difference
@pytest.mark.parametrize('tensor_input', [True, False], ids=['t... |
84c6c5da2a996a79f2eb0800417664149c6f3f787e329caf106228a1782b3b91 | Python | 2,534 | 82 | """OpenAI provider.
Uses OpenAI's structured-output mode (``response_format={"type": "json_schema", ...}``)
to force a JSON response matching `output_schema`. Works against the native
OpenAI API + Azure OpenAI + any OpenAI-compatible endpoint (Ollama, LM Studio,
vLLM) via ``base_url``.
Imports the ``openai`` SDK lazi... |
0708ce2a178f170048ed1e284cd0563aa1a45dcb4bf9f644f0418c1a270cc332 | Python | 2,535 | 69 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestBetween:
def test_between(self):
series = pd.Series(pd.date_range("1/1/2000", periods=10))
left, right = series[[2, 7]]
result = series.between(left, right)
expected = (series >= left) & (... |
1d8300010d0acdf18d95f385679ac41ac943e36bab60c02ad4f5a8253e634fdd | Python | 2,537 | 73 | # Arithmetic tests specific to DatetimeIndex are generally about `freq`
# retention or inference. Other arithmetic tests belong in
# tests/arithmetic/test_datetime64.py
import pandas as pd
import pandas._testing as tm
class TestDatetimeIndexArithmetic:
def test_add_timedelta_preserves_freq(self):
# GH... |
76e86bd7b41244930dbadcd8788da73e7d72104dcab5df14be4b3fee4b200c3b | Python | 2,538 | 74 | import argparse
import importlib
import sys
from isaacgymenvs.pbt.launcher.run_ngc import add_ngc_args, run_ngc
from isaacgymenvs.pbt.launcher.run_processes import add_os_parallelism_args, run
from isaacgymenvs.pbt.launcher.run_slurm import add_slurm_args, run_slurm
def launcher_argparser(args) -> argparse.ArgumentP... |
2b3d671b9fe1a4c082b245af1e3fc8d4b81398ea289885cd64b51a3aa620ef30 | Python | 2,539 | 71 | __AUTHOR__ = 'Bahram Jafrasteh'
from esFCM.FCM import esFCM
from esFCM.FCM import FCM_pure as FCM
from esFCM.utils import *
def run_gmm(img, num_tissues=3):
from sklearn.mixture import GaussianMixture
# Number of tissue types
n_components = num_tissues+1
im_T1 = img.get_fdata()
data = im_T1.get_... |
3e82af50bf2d82fffa2ecdf88ee5f01edfd2ff524ab4c388ad89b2b22cd02a2d | Python | 2,539 | 78 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestSeriesSubclassing:
@pytest.mark.parametrize(
"idx_method, indexer, exp_data, exp_idx",
[
["loc", ["a", "b"], [1, 2], "ab"],
["iloc", [2, 3], [3, 4], "cd"],
],
)
def ... |
85a5e77dd805ed4bac298de40320a03bf166ec14c6679062885ce4f402c32cad | Python | 2,539 | 68 | import unittest
from unittest import TestCase
from evcouplings.utils import *
from evcouplings.couplings import CouplingsModel
import numpy as np
MONO_MODEL = os.getenv('HOME') + "/evcouplings_test_cases/monomer_test/couplings/RASH_HUMAN_b03.model"
# MONO_MODEL = "/home/travis/evcouplings_test_cases/monomer_test/coupl... |
d5b67785726c25a419ae98829abece1bcecdf24d72f55a1b95146cd319bdf9b8 | Python | 2,539 | 87 | import numpy as np
import numba
from sklearn.neighbors import KDTree
from umap.distances import named_distances
@numba.njit()
def trustworthiness_vector_bulk(
indices_source, indices_embedded, max_k
): # pragma: no cover
n_samples = indices_embedded.shape[0]
trustworthiness = np.zeros(max_k + 1, dtype=... |
f817518b404f129d00382540cdfba5517332b71c0c373562e04149ea7af03301 | Python | 2,539 | 69 | #!/usr/bin/env python3
"""Parse timing_config.yaml and print shell variable assignments for run_benchmark.sh.
Keeps the config file itself in YAML, matching the convention used by
scripts/hyper-sweep/sweep_config.yaml, while keeping run_benchmark.sh a bash
orchestrator: each (panel, variant, decoder) combination still... |
ea91edbc619b92dafc3c21b2141e6c0c9ec35d977360676cbb3dc87e4c153ba5 | Python | 2,540 | 95 | """
Training utilities functions
"""
import torch
import torch.nn.parallel
import torch.optim
import torch.utils.data
best_prec1 = 0
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
... |
c30c9dec2a1b8490d8ba7bcd3db72bf46d949ce74d1ee3211b5d242af5cd9281 | Python | 2,542 | 79 | from spycon import coninf
def get_eann_coninf_dict(
num_cores, remove_bursts=False, N_burst=50, ISI_N_burst=0.1
) -> tuple:
"""Setup the base connectivity inference methods for the eANN model.
Note: This is a specific function for the model presented in the paper.
If you want to train a different mod... |
43dc7ce3e4226f58716642cb29236bed8226d5ff40685223f87b3cb4323b6580 | Python | 2,543 | 72 | import torch
from torch import Tensor
import torch.nn as nn
import torch
class DiceLoss(nn.Module):
"""
require sigmoid at the end of network
"""
def __init__(self):
super(DiceLoss, self).__init__()
self.smooth = 1.0
def forward(self, y_pred, y_true):
assert y_pred.size() ... |
4528454afa5d9b53b4dfcf82a308ca28aab1857c2663dca00108c76341ad87eb | Python | 2,543 | 74 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
@pytest.mark.parametrize(
"in_vals, out_vals",
[
# Basics: strictly increasing (T), strictly decreasing (F),
# abs val increasing (F), non-strictly increasing (T)
([1, 2, 5, 3, 2, 0, 4, 5, -6, 1, 1], [Tr... |
bb554592faf58fc267e19aa48ae391b3b198a3918c43b313eeae06fb22fa4663 | Python | 2,543 | 70 | """Density compensation data (DcfData) class."""
from functools import reduce
from typing import TYPE_CHECKING
import torch
from typing_extensions import Self
from mrpro.algorithms.dcf.dcf_voronoi import dcf_1d, dcf_2d3d_voronoi
from mrpro.data.Dataclass import Dataclass
from mrpro.data.KTrajectory import KTrajector... |
bff9664cec2ea82aa4a93039e247d74024697e02cbe72167b57c3842405eed96 | Python | 2,543 | 77 | import time
import numpy as np
from StimulationProcess.BasicStimulationProcess import BasicStimulationProcess
from psychopy import visual, core, event
import math
import os
import pickle
class IdleProcess(BasicStimulationProcess):
def __init__(self) -> None:
super().__init__()
def change... |
cfa9c42eb540c79e2d4e62528729c2472fe465480c59cda117421c9471ec3f0a | Python | 2,544 | 81 | from datetime import timedelta
import numpy as np
import pytest
from pandas._libs import iNaT
import pandas as pd
import pandas._testing as tm
class TestSeriesMissingData:
def test_categorical_nan_handling(self):
# NaNs are represented as -1 in labels
s = pd.Series(pd.Categorical(["a", "b", np.... |
e2c909979ae2073eff39ea0d4c515d59aea942b996d6a1349d7311d9101ef710 | Python | 2,544 | 83 | # 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... |
4b117c7744d08dbf76476207b8e704754193e217abb8c816d7a96b8d0f3282b9 | Python | 2,545 | 95 | import dependency
import DepsTools
import re
import sys
# take a sd dep and minus the word idx by 1
def decreaseWordIdx(d):
# print(d)
m = re.match("(^.*)-(.*)", d.head)
if m.group() != None:
headW = m.group(1)
headIdx = int(m.group(2))-1
# print("head", headW, headIdx)
newHea... |
ae78ac3386b4ada3d771e8aaf73bcd203f00f2747ec1d47fc62e03e971937f2b | Python | 2,546 | 98 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.14.5
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# %%
# %load_ext autoreload
from pathlib... |
482e40189a2252fafe7341594558749793f7390f84cc7f472236bfde61f18585 | Python | 2,548 | 84 | #python calcngramprobtoks.kenlm.py --fwprobs genmodel/fw.5.probs.tmp [--uprobs genmodel/fw.1.probs.tmp] [--bwprobs genmodel/bw.5.probs.tmp] > $@
#from __future__ import division
import re
import sys
OPTS = {}
for aix in range(1,len(sys.argv)):
if len(sys.argv[aix]) < 2 or sys.argv[aix][:2] != '--':
#filename ... |
b624e1cb1ea1a3bdd114383299edb3b8ca00158925a422096f64e1c1fe448389 | Python | 2,548 | 56 | #!/usr/bin/env python
from distutils.core import setup, Extension
from distutils.command.build_ext import build_ext
class CustomBuildExtCommand(build_ext):
"""build_ext command for use when numpy headers are needed."""
def run(self):
# Import numpy here, only when headers are needed
import n... |
0703bd16ed5655d73ff301b186513ac9053387ade58599f083dd654e40cc53dc | Python | 2,549 | 83 | import numpy as np
import pandas as pd
import plotnine as p9
def heatmap(esw: pd.DataFrame,
genes: list=None,
annotations: list=None,
figsize: tuple=None) -> p9.ggplot:
"""
Args:
esw : DataFrame of ES weights
genes : a list of genes to inc... |
a03476e166cd62eb1ef6ea56d0c9e456ca8af14424bc8a285eb180ea0819d7f9 | Python | 2,550 | 57 | import os
import pandas as pd
import sys
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 config.globals import ENVIRONMENT
from app import create_app, db
from app.models import SourceDataset, Subject,... |
e65195a6fc6ba740de2537eec035f72aab5bce072b670cc74f38a0c9c81ea953 | Python | 2,550 | 89 | import numpy
import pandas
import seaborn as sns
from scipy import interpolate
import matplotlib.pyplot as plt
def displayResult(df, normalize, name):
df.columns = df.columns.values.round(2)
df.index = df.index.values.round(2)
if normalize:
df = df/numpy.max(df.values)
ax = sns.heatmap(df, cma... |
f6df30ad1e66a99b2c655ae5f51e6fa0909849beeb6109d27fa9276f27b9a556 | Python | 2,550 | 60 | """Masked diagnostics regressions (diagnostics-only paths, use_diagnostics)."""
import torch
from rl_games.algos_torch.torch_ext import explained_variance, policy_clip_fraction
def _row_mask(n, n_valid):
masks = torch.zeros(n)
masks[:n_valid] = 1.0
return masks
def test_masked_diagnostics_match_unmask... |
63db752674e61cbe17c38cf1310b9e1dab88f1cec02731c05822469dd664b164 | Python | 2,551 | 95 | import pytest
from pandas.util._decorators import deprecate_kwarg
import pandas._testing as tm
@deprecate_kwarg(FutureWarning, "old", new_arg_name="new")
def _f1(new=False):
return new
_f2_mappings = {"yes": True, "no": False}
@deprecate_kwarg(FutureWarning, "old", new_arg_name="new", mapping=_f2_mappings)
... |
878229acbda8968d8487622ee99472add50df2c1d94a23aa322102615d501bdf | Python | 2,553 | 86 | import contextlib
import uuid
import pytest
import pandas as pd
from pandas.io.excel import ExcelWriter
xlsxwriter = pytest.importorskip("xlsxwriter")
@pytest.fixture
def ext():
return ".xlsx"
@pytest.fixture
def tmp_excel(ext, tmp_path):
tmp = tmp_path / f"{uuid.uuid4()}{ext}"
tmp.touch()
retur... |
94d63e867135157cc44382a8434468ce56e6bb04c8fe13a54d3cdc7ea6e63d6c | Python | 2,553 | 70 | #Run and save results of sweeps over eps, eta for 5 fields.
#Date written and executed: 2022-04-26
#Runs multiple replicates at each set of parameter values
# ran test run with two replicates at one set of parameter values
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.object... |
f017fd878d4319d1cfed85e144255f1e687899b883d75b91c59ac38a3f964d09 | Python | 2,553 | 80 | import torch
import pkg_resources
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
import pandas as pd
from typing import List, Tuple
from rxn_yields.core import SmilesClassificationModel
from rxn_yields.data import generate_buchwald_hartwig_rxns
import sklearn
try:
import wandb
wandb_a... |
ad2696d91f5823ad3774977bd6e85892c589ef4f1967613f54d9f6e9ab2b6fb7 | Python | 2,555 | 70 | # 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... |
be123f2838a6d8cdfaa1a0069a52dbabadaf881d8d68b11026958a88e95e913a | Python | 2,555 | 67 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 23 08:26:03 2022
@author: danielkerschensteiner
"""
import numpy as np
import pandas as pd
import tkinter as tk
import tkinter.filedialog
import glob
import os
def collect_columns(path_name, ind_col, target_col):
files = glob.glob(path_n... |
00b4d29659b4576750101658ff327af074faddc3f8f95f610a76556e899cbbeb | Python | 2,556 | 79 | #python spargeComplexity.py [-o] [-id id_file]
#extract complexity from stdin (mixed complex/output)
#-o: extract output from stdin (instead of complexity)
#-id: output sentence ids from the given id_file
import re
import sys
REPORT_COMPLEX = True
idlist = []
if len(sys.argv) > 1:
for i,arg in enumerate(sys.argv):
... |
4cb3d067ff30543442bd4a0d09295a5359a2f9e0cacc7bef57ff61b00652cab7 | Python | 2,556 | 85 | """Metrics used in paccmann."""
import tensorflow as tf
import numpy as np
from scipy import linalg
def pearson(x, y):
"""
Compute Pearson correlation.
Args:
- x: a `tf.Tensor`.
- y: a `tf.Tensor`.
Returns:
Pearson correlation coefficient.
"""
mx = tf.reduce_mean(x)
... |
c4cfb85e8a8387693a6a70daa9d84c27fd47e719574efc6c6a045acb0dae2e09 | Python | 2,556 | 73 | import os
import unittest
from unittest import TestCase
import evcouplings
from evcouplings.utils import SubmitterFactory, Command
class TestSubmitter(TestCase):
def setUp(self):
self.module_path = os.path.dirname(evcouplings.__file__)
self.test_db = os.path.join("./", "test", "test.db")
... |
0a9b9776519c71ace00ee7b96d5a98f622a79ffc77f36fa753af4afec40076fd | Python | 2,559 | 72 | import dateutil.tz
import numpy as np
import pytest
import pandas as pd
from pandas.core.arrays import datetimelike
class TestDatetimeIndexIteration:
@pytest.mark.parametrize(
"tz", [None, "UTC", "US/Central", dateutil.tz.tzoffset(None, -28800)]
)
def test_iteration_preserves_nanoseconds(self, tz... |
5d6d329388aaaef82950ac67ff56df55c1837378a5e41e8170662f9386766e71 | Python | 2,559 | 89 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 2 10:09:20 2023
@author: tomas
"""
from loess import loess_1d
import numpy as np
import glob
from matplotlib import pyplot
from pathlib import Path
from sklearn.ensemble import IsolationForest
import real_unit_convert
def calc_derivative(predic... |
f1797b8c448787e2af6efc583ea50e5e390ba914dff9914be24711bc00da15ec | Python | 2,559 | 56 | import sys, os, collections, re
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts'))
import tree
## recursive function to add referent type to
def type ( tree, Types, artnum, linenum, toknum=1 ):
if len(tree.ch)>=1 and len(tree.ch[0].ch)==0:
####if tree.c.startswith('N... |
4fd5404590be708cd67d58f4f1c7a33fa33ec4f36f1be6bb32c93f8a534225c0 | Python | 2,560 | 74 | # Copyright 2018-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... |
b59b9fe3db009ea40174f5ccdb02fcdf9625ef4f3ce092b4562302eee1f98c9f | Python | 2,560 | 120 | from datetime import (
datetime,
timedelta,
)
import numpy as np
import pytest
import pandas.util._test_decorators as td
import pandas as pd
@pytest.fixture(params=[True, False])
def raw(request):
"""raw keyword argument for rolling.apply"""
return request.param
@pytest.fixture(
params=[
... |
345b00e77eb8d4a3cfc87270913938ee85a623eb7f21c9e67e9da88996696e50 | Python | 2,561 | 72 | from Common import loggingUtils
from Surfaces.surfaces import *
from Common.kernelFunctions import *
from Surfaces.surfaceMultiPhase import *
def compute():
outputDir = '/Users/younes/Development/Results/twoBallsSliding2ndTry'
#outputDir = '/cis/home/younes/MorphingData/twoBallsStitched'
#outputDir = '/Us... |
b7f605debe9bd7cf1283f99b10f08add5feac3d1b6edeb2aad526851b650a4f4 | Python | 2,562 | 78 | __all__ = ["filter_dataframe", "merge_dataframes"]
import functools
from typing import Any, Iterable, Literal, Mapping, Sequence, cast
import numpy as np
import pandas as pd
def filter_dataframe(data: pd.DataFrame, filters: Mapping[str, Mapping[str, Any]]):
if filters is None:
return data
should_re... |
2e14104989a31502eb930bc7eafc6177df4f18473abeb8bdf74ecd84fed0ddf0 | Python | 2,563 | 107 | import sys
from enum import Enum
from pathlib import Path
from hydra.core.config_store import ConfigStore
from dataclasses import dataclass, field
from omegaconf import MISSING
from typing import Any, Optional
sys.path.insert(0, str(Path.cwd()))
@dataclass
class GeneralConfig:
force_cpu: bool = False
log_wan... |
a8d1595e9b9ce1cb84be94bf51df58cfff4f2cdba2025ee0256a9d2e54da37e0 | Python | 2,563 | 73 | # Classification model imports
from imutils import paths
from tensorflow.keras.applications import ResNet50V2
from tensorflow.keras.layers import AveragePooling2D, Flatten, Dense, Dropout
from tensorflow.keras.layers import Conv2D, Conv3D
from tensorflow.keras import Input, Model
from tensorflow.keras.optimizers import... |
90a2f62ba5c1d12870fc668c4431d8df399d82fbf18c0919dd22373970646891 | Python | 2,564 | 60 | # Copyright (c) 2018-2023, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... |
005e497699b36ee5cef8fb857320f10283ef17c85e416931561f2d53139b3397 | Python | 2,565 | 85 | import numpy as np
import pandas as pd
import scanpy as sc
from warnings import simplefilter
def Scanpy_Obj_IO(test_obj=None, ref_obj=None, label_obj=None, scale = False):
'''
:param test_obj: Input Anndata object for cell type annotation
:param ref_obj: Input reference cell atlas, please note that an csv... |
ecf05d03e3a93effd5031ec8278a1b7ab3c02cd632101e128e4e6c8e6c670019 | Python | 2,566 | 83 | import sys
import os
import setproctitle
import numpy as np
import tensorflow as tf
setproctitle.setproctitle("DASDC")
def max_minNorm(data):
if np.ndim(data) == 3:
max_value = np.max(data,axis=(0,2)).reshape(1,data.shape[1],1)
min_value = np.min(data,axis=(0,2)).reshape(1,data.shape[1]... |
44b36a7d35f779cc967e6f174b7867713e1bf429925c6d6cc9f92d5635d5ea4a | Python | 2,568 | 126 | from collections import namedtuple
Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat')
PRIMITIVES = [
'none',
'max_pool_3',
'avg_pool_3',
'skip_connect',
'sep_conv_3',
'sep_conv_5',
'dil_conv_3',
'dil_conv_5',
]
LINEAR_PRIMITIVES = [
'linear_block',
... |
481c88d1ec54b63652c0f6fbf1268cd7dabe1c0559356a2ba00b068ad08b5f1c | Python | 2,568 | 72 | """Test cases for DataFrame.plot"""
import pytest
import pandas as pd
from pandas.tests.plotting.common import _check_visible
pytest.importorskip("matplotlib")
class TestDataFramePlotsGroupby:
def _assert_ytickslabels_visibility(self, axes, expected):
for ax, exp in zip(axes, expected, strict=True):
... |
29dd72140134a9cb9ece6edf113553ba6d20322790f7bca764a6e31463628713 | Python | 2,569 | 68 | import os
from typing import *
import boto3
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
class UploadCallback(pl.callbacks.Callback):
"""Custom PyTorch callback for uploading the best model checkpoint to a S3 bucket.
Parameters:
path: Local path to folder where m... |
9d784891dfd62a1b9f68ac974dd237f541f1149e2915b4bd206887d99dae74bc | Python | 2,569 | 76 | from Environment_ui import *
from scipy import ndimage as ndi
def get_2d_local_voxels(block, yc, xc, rad ):
"""
"""
xst = xc-rad if xc-rad>=0 else 0
yst = yc-rad if yc-rad>=0 else 0
xen = xc+rad+1 if xc+rad+1<=block.shape[1] else block.shape[1]
yen = yc+rad+1 if yc+rad+1<=block.shape[0] else bl... |
5edcdfe0c5633d4f187e93d53bee369992a8739e5f59b36969d358d8a9248b5e | Python | 2,572 | 132 | # 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... |
563076f9ca2b59fd0a193fa058de1de3be5da79a9de92e21829ca39df5bbe814 | Python | 2,573 | 69 | """Synthetic data pipeline quickstart CLI.
Generates a deterministic synthetic dataset and runs it through the full
data path (manifest -> volume processing -> subject-wise split), so the
pipeline can be exercised end to end without OASIS-3 data. Intentionally a
thin `argparse` wrapper, not a framework: `python -m mul... |
ee185885d01790f7ac8ff43abc62cd0c0f95434f61fc8e5da007a3a90c8b21a6 | Python | 2,573 | 92 | #!/usr/bin/env python
"""
File: modalities
Date: 5/4/18
Author: Jon Deaton (jdeaton@stanford.edu)
Generic information about the different image types
available in the BraTS data sets.
"""
from BraTS.load_utils import *
from enum import Enum
# Each of the "images" is a 3D volume of this shape
image_shape = (240, 24... |
6e8f46bec6a4081f4248f010bf5641f71b51cdbaa0282bce76e6ef5580caace7 | Python | 2,574 | 60 | # SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of sourc... |
802b9acdf656fc60dca1b4584932b4003f99ed5f7e2cd2d6205fec4f23830eea | Python | 2,578 | 60 | import sys, argparse, pandas as pd
argparser = argparse.ArgumentParser('''
Accumulates user-specified fields over saccades in a space-delimited table of reading time data, and appends them as additional fields to the output. Rows must be in order of presentation to subjects.
''')
argparser.add_argument('-a', '--all', ... |
889f5b9de2bfa36e7eba921a8809e20b395f0ecf4f17e76d9f10fab34c3aa7da | Python | 2,579 | 75 | import os
from typing import Iterable
if 'PYTHONPATH' not in os.environ:
print("Error: Run `source env.sh` to be able to run `/scripts/*.py`")
exit(1)
from pathlib import Path
import matplotlib.pyplot as plt
LEAD_PICTURES = [
'lead-pictures/002-49853179.png',
'lead-pictures/002-81476687.png',
'le... |
eeac2087cfbc0b9324b1530278f14dee8d626c762d5467c7ea4dbfabf3470b62 | Python | 2,579 | 92 | import dclab
from dclab.features import contour, inert_ratio
import numpy as np
import matplotlib.pylab as plt
from scipy.ndimage.interpolation import rotate
from skimage.draw import polygon
# setup inertia ratio contours
img1 = np.zeros((300, 800), dtype=bool)
pol1 = np.array((
(50, 50),
(50, 750),
(250, ... |
5237d24bf4b0e06da33c70168fe2524e946c5d75ebd49cc66f72eef3f191d727 | Python | 2,581 | 91 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 26 18:06:05 2023
@author: jeanbaptiste
"""
import os
import json
import numpy as np
import matplotlib.pyplot as plt
import deepcellcontrol as dcc
#%% Parameters:
_folder = "D:/deepcellcontrol/assets/simulated_inverter/"
with open(_folder + "/training_parameters.json", ... |
c0e6db99f19ab2ea70fb9c12a50caebeea59e8cc9f0c4650c70e314f70e2a4a1 | Python | 2,581 | 68 | # Copyright 2018-2020 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... |
0a431787850d38741ffe875912671ed3b05a9dc68a9b46360a80e68c16369d85 | Python | 2,582 | 59 | """Test the device module."""
import sys
from unittest.mock import MagicMock, patch
import pytest
from lightning_pose.utils.device import get_accelerator, require_cuda_for_semi_supervised
class TestGetAccelerator:
"""Test the function get_accelerator."""
def test_get_accelerator_returns_gpu_when_cuda_avai... |
3530b9844fcf88c416e7d63b7f0050a1b47c07c62892e205d53e0b4fa20a1c07 | Python | 2,582 | 88 | #!/usr/bin/env python
"""
File: Patient
Date: 5/1/18
Author: Jon Deaton (jdeaton@stanford.edu)
"""
import numpy as np
import nibabel as nib
from BraTS.modalities import *
from BraTS.load_utils import *
def load_patient_data(patient_data_dir):
"""
Load a single patient's image data
:param patient_data... |
6790e282dcea4f8d4adbce8acdb49a53e8df5c18dd4e386732411738ca1eefa4 | Python | 2,582 | 80 | # 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... |
bc48eda4e6cfd5f185bdb82470140b1cc43bc8708cd5200c055a38f53a18ffe9 | Python | 2,582 | 69 | # Copyright 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 agre... |
c3babc4c384d1a231e105c0d87f646b5b1d922c94fa355330fbc553c6a4e6ae6 | Python | 2,585 | 72 | """Run a contrast permutation meta-analysis on a set of images."""
import logging
import os
import pathlib
import numpy as np
from nilearn.masking import apply_mask
from nilearn.mass_univariate import permuted_ols
from ..results import MetaResult
from ..utils import get_template
LGR = logging.getLogger(__name__)
d... |
350ec6c5b0a86e6f516c819054b7ac9fa2c6b8026bae85b4e51854d1c2748e85 | Python | 2,587 | 64 | """Sampling from von Mises-Fisher distribution."""
# based on: https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/util.py
# http://stats.stackexchange.com/questions/156729/sampling-from-von-mises-fisher-distribution-in-python
# https://www.mitsuba-renderer.org/~wenz... |
effbe432d650e81e252bb872a5089863d496d04e1abf5bed790082bfcbbf550d | Python | 2,587 | 79 | import sys
import os
import configparser
from cdr.formula import Formula
X_path = sys.argv[1]
y_path = sys.argv[2]
outdir = sys.argv[3]
main_effects = sys.argv[4:]
config = configparser.ConfigParser()
config.optionxform = str
config.readfp(sys.stdin)
#config['data']['X_train'] = X_path
#config['data']['X_dev'] = X_... |
4eab6777d2bf615ec545a5ddd56686500e95269ca3950e795ba41fd337e7c95a | Python | 2,588 | 90 | import argparse
import multiprocessing as mp
import numpy as np
import pandas as pd
from pathlib import Path
from tqdm.auto import tqdm
from global_config import config
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--dataset-name", required=True, help='Synthetic SeRANN datas... |
9d2521d131a1d7c8d431d13bb56605c6c8aab50497c2210d23ee034e2c08762e | Python | 2,591 | 76 | """Test the convert CLI command argument parsing and dispatch."""
import argparse
from unittest.mock import patch
import pytest
from lightning_pose.cli.commands.convert import get_parser, handle
class TestGetParser:
"""Test the get_parser function."""
def test_returns_argument_parser(self):
"""Ret... |
18b07e90f8d6fbe4c8e88d9f81ff1f79e2ebbefd13d2e71a842a6009ae569550 | Python | 2,593 | 77 | import unittest
from unittest.mock import MagicMock, patch
from brainflow import BoardShim, BrainFlowInputParams, BoardIds
from real_time_plotting import Graph, main
import time
class TestRealTimeEEG(unittest.TestCase):
@patch.object(BoardShim, 'get_current_board_data')
def test_data_acquisition_and_frame_dr... |
5134c5eb1b2dff29094f9ff5a3916c35700f1dfd4fff2fcc832871f139cd45c8 | Python | 2,593 | 46 | import pandas as pd
import os
import sys
from pathlib import Path
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, SourceDataset
from config.gl... |
d507296f6e982ad888f4b7d11bfdc1ace0a29c07a4f4bc274fc8d6ce93a65924 | Python | 2,593 | 99 | __all__ = ["flatten_dict", "chain_item", "chain_get"]
from typing import Any, Dict, Mapping, Optional, Type, TypeVar, overload
def flatten_dict(d: Mapping[str, Any], sep: str = ".") -> Dict[str, Any]:
def _flatten_dict_gen(d, parent_key, sep):
for k, v in d.items():
new_key = str(parent_key) ... |
02ef7467e4ff80bd209069e08a4c1bee9bc3d2f45b8bfd76aaa0f885ac871646 | Python | 2,594 | 94 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from nilearn.plotting.matrix_plotting import _reorder_matrix
from fmriprep_denoise.visualization import utils
strategies= list(utils.GRID_LOCATION.values())
def load_data(path_root, datasets, fmriprep_version):
"""Ave... |
31a164dc27aad760cba20cd9b42040cb91f5c5c75dc1394496747f127242afad | Python | 2,594 | 79 | # 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... |
eaa6cd7ffa25e7fb353b136d7948e3893cfd95179562a1d7f6592d86c1918ad4 | Python | 2,595 | 72 | """Run a contrast permutation meta-analysis on a set of images."""
import logging
import os
import pathlib
import numpy as np
from nilearn.masking import apply_mask
from nilearn.mass_univariate import permuted_ols
from nimare.results import MetaResult
from nimare.utils import get_template
LGR = logging.getLogger(__n... |
1e755349469a0db6ecd6c7b3311d9d06fb8f8b9870fa1f025a4cb9ddb5970259 | Python | 2,596 | 80 | import re
import argparse
from rdkit.Chem import AllChem
from rdkit import Chem
def Fragment_recombination(n, frags):
mols1 = [Chem.MolFromSmiles(smi) for smi in frags]
rxn = AllChem.ReactionFromSmarts("[$(*[#2:1]):1][#2].[$(*[#2:1]):2][#2]>>[*:1][*:2]")
if n == 0:
return frags[0]
els... |
4ac680b381ea18c7746d59a8f3473752bb9f178e4f2a6c621080c74216a03b7c | Python | 2,598 | 67 | # 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... |
eb907a004c7f1e9dfe0078edcc02f0ced7185f2dcee40b0dc9f0e823e6ef2ee7 | Python | 2,598 | 77 | #! /usr/bin/env python
"""A template for mne-python compatible packages."""
import codecs
import os
import re
from setuptools import find_packages, setup
# get __version__ from _version.py
ver_file = os.path.join('sesameeg', '_version.py')
with open(ver_file) as f_ver:
version_file = f_ver.read()
version_mat... |
2f41a177cc89203c0c75ea39e8ef1d898d328a18a06e82339ecb01ad961230de | Python | 2,602 | 74 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Created by Roberto Preste
import pytest
import os
from click.testing import CliRunner
from mtoolnote import cli, annotate
from mtoolnote.tests.constants import (
HUMAN, HUMAN_ANN, HUMAN_ANN_CSV, GGALLUS, GGALLUS_ANN, GGALLUS_ANN_CSV,
TEST_CSV, TEST_VCF
)
# modul... |
cf019486eeda48af6d77ed446c685019cf3764315412ad5ae9993b399ae5b7b6 | Python | 2,602 | 63 | import os
import pandas as pd
from cptools2 import loaddata
from cptools2 import filelist
CURRENT_PATH = os.path.dirname(__file__)
TEST_PATH = os.path.join(CURRENT_PATH, "example_dir")
TEST_PATH_NEW = os.path.join(CURRENT_PATH, "example_dir_new_paths")
TEST_PATH_PLATE_1 = os.path.join(TEST_PATH, "test-plate-1")
TEST_P... |
1d799a84fdd0bc606f625e3c5f7d7f0ade3d46a5b7c2d1933b104fc1ea28166b | Python | 2,604 | 73 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestSeriesPctChange:
def test_pct_change(self, datetime_series):
rs = datetime_series.pct_change()
tm.assert_series_equal(rs, datetime_series / datetime_series.shift(1) - 1)
rs = datetime_series.pct_c... |
43b9b02bf8e6162ab5bd98f13ba8e57cdfa3e076b922b5ee5f4210965e34de92 | Python | 2,605 | 65 | # https://github.com/drivendataorg/zamba/blob/master/zamba/pytorch/layers.py
# Modifications:
# - Change x.view to x.reshape, allowing non-contiguous tensor
__all__ = ["TimeDistributed"]
import torch
def _stack_tups(tuples, stack_dim=1):
"""Stack tuple of tensors along `stack_dim`
NOTE: vendored (with minor... |
9c51826f1e8995ff3a1f2230a13eefaaa3272d197f4ac15f7ef70cb75f98c3ba | Python | 2,605 | 111 | """
Linear operations.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from darts.api import Model
OPS = {
'none' : lambda c, stride, affice: Zero(),
'skip_connect' : lambda c, stride, affine: Identity(),
'linear_block' : lambda c, stride, affine: LinearBlock(c, c, affine=... |
1b5438a05c9ec3b9775269647dc247bfcd34f34b56dc85414f7aaa21c8ba7544 | Python | 2,606 | 85 | # -*- coding: utf-8 -*-
"""
morphological operations
"""
import numpy as np
from skimage import morphology
from scipy.ndimage import binary_dilation, binary_erosion
import logging
logger = logging.getLogger(__name__)
def fill_holes_2D(mask,minsize=[]):
out = np.copy(mask); out = out>0
if not minsize:
... |
d223b358634b6e646d64948ca14dba30ea1bd7cc4a7abb6c52af8578c8e8da5c | Python | 2,607 | 76 | #!/usr/bin/env python
'''
Testcases for the ulog utilities
'''
import windseer.utils as utils
import windseer
import numpy as np
import os
import unittest
windseer_path = os.path.dirname(windseer.__file__)
testdata_folder = os.path.join(windseer_path, 'test', 'testdata')
test_file_data = os.path.join(testdata_folder... |
d061c6ba921a10c353236d8bd004e0432cbcbcacf321a56195169558ead2f6f0 | Python | 2,608 | 90 | """
Summarise data for visualisation.
To retrievel atlas information, you need internet connection.
"""
import argparse
from pathlib import Path
import pandas as pd
from fmriprep_denoise.features.derivatives import get_qc_criteria
from fmriprep_denoise.visualization import utils
import itertools
qc_names = ["stringen... |
310423541cf749641afc18a38f1a413acd132925e15229081be746190e3db885 | Python | 2,609 | 91 | try:
import smbus
except:
print ('Try sudo apt-get install python-smbus')
from time import sleep
# Valid units
UNITS_Centigrade = 1
UNITS_Farenheit = 2
UNITS_Kelvin = 3
class TSYS01(object):
# Registers
_TSYS01_ADDR = 0x77
_TSYS01_PROM_READ = 0xA0
_TSYS01_RESET ... |
e30320a6fec266b6ef3e0ef38583c794a8ce1f72ac5c6ae9c49f01dd5db5e3e5 | Python | 2,609 | 70 | #Run and save results of sweeps over eps, eta for 5 fields.
#Date written and executed: 2022-04-26
#Runs multiple replicates at each set of parameter values
# ran test run with two replicates at one set of parameter values
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.object... |
67df8fa98f73f53923ac0c3f33797cf70e9df8e475fc8c78805a29cbb6554b91 | Python | 2,611 | 60 | import numpy as np
import pytest
import torch
from kilosort import run_kilosort
# Use `pytest --runslow` option to include this in tests.
@pytest.mark.slow
def test_pipeline(data_directory, results_directory, saved_ops, torch_device, capture_mgr):
bin_file = data_directory / 'ZFM-02370_mini.imec0.ap.short.bin'
... |
818f14b7aa4fc024af99e0a8be221b7dae63aaf28ba22583e356c61847f69ddc | Python | 2,611 | 92 | import os
import json
from typing import List
from darts.genotypes import Genotype
class GenotypeStorage:
""" Disk storage for Genotypes
Args:
root: rooth path to save genotype
"""
def __init__(self, root: str):
self.root = root
def save_genotype(self, genotype: Genotype, filen... |
749f07fddab7b3f8889896da754016f27bef77ef6612bb7dc9132f140c32d1bd | Python | 2,612 | 50 | import sys, argparse
import pandas as pd
argparser = argparse.ArgumentParser('''
Shifts user-specified fields from one saccade to the previous saccade in a space-delimited table of reading time data, and appends them as additional fields to the output. Rows must be in order of presentation to subjects.
''')
argparser.... |
64ff0b0634880ac24d3a0c84f94b88b51ca5e089d05c13ad83af21715735b31a | Python | 2,614 | 97 | import numpy as np
import pytest
import pandas.util._test_decorators as td
import pandas as pd
import pandas._testing as tm
def test_get_dummies(any_string_dtype):
s = pd.Series(["a|b", "a|c", np.nan], dtype=any_string_dtype)
result = s.str.get_dummies("|")
expected = pd.DataFrame([[1, 1, 0], [1, 0, 1],... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.