sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
e1234138b9823cac201972a8e38c9164b60abb1b82b827b9fd58e74e3d5f097a
Python
689
17
from datetime import datetime import sys import enum sys.path.append("..") from app import db from sqlalchemy.dialects.postgresql import JSON class PreprocessTask(db.Model): __tablename__ = 'preprocess_task' id = db.Column(db.Integer, primary_key=True) description = db.Column(db.String(255)) preproces...
0cd6bd4d6bdf9771f88bed0cf44240d5d8a443383cd6db2c97526df299d04b93
Python
691
20
import os def configure_path_to_parameters( DOCKER: bool, DOCKERPATH: str, MRLPATH: str, model_name: str ) -> str: """ Provides the right path depending on whether Gadgetron is being run for local/offline development (i.e., DOCKER=False) or online/real-time deployment (i.e., DOCKER=True)....
9c482577f4413e4426eb33e1d9f6d365d946557e541e472781d82d26c87b802d
Python
691
25
import sys, os, collections sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts')) import tree def makedepterm ( t, DepDict, w=0 ): for st in t.ch: w = makedepterm ( st, DepDict, w ) if len(t.ch) == 1 and len(t.ch[0].ch) == 0: w += 1 t.ch[0].c = '_'.join(DepDict...
ef3368fa89603527c4f230d8104b6c9489a3f3c1b09aa92b3b50ad44e44bb4e5
Python
692
28
import numpy as np import tensorflow as tf from tensorflow.keras.callbacks import Callback import wandb def cosine_schedule(base_lr, total_steps, warmup_steps): def step_fn(epoch): lr = base_lr epoch += 1 progress = (epoch - warmup_steps) / float(total_steps - warmup_steps) progr...
31faa5f73165f42a988239a7dc9eadbd6a4fe6b983d960b561840755751ffd41
Python
693
27
#python scripts/filterLexicon.py wordcounts # flags all words that are not in the wordcounts file import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts')) from model import Model lexicon = Model('L') with open(sys.argv[1],'r') as lexFile: for line in lexFile.re...
65ddcdf3d2a4633386decf03c970cdd64fd379149f948bed7b2d29132f0d3efe
Python
694
32
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.16.0 # kernelspec: # display_name: ol-connectome # language: python # name: ol-connectome # --- # %% from pathlib import Path import sys ...
c10bcf8ad471a66bb935e08ed47bc913242378d1f7362d6f382de0e42519bdec
Python
694
25
import gymnasium as gym import numpy as np class ExampleEnv(gym.Env): ''' Just example empty env which demonstrates additional features compared to the default openai gym ''' def __init__(self, **kwargs): gym.Env.__init__(self) self.use_central_value = True self.value_size = 2...
f5841bf0bd7a84a5da318e5ca69d895cf46c72bca758d8140a9b4491b6526dff
Python
695
31
import os, sys, re sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts')) import model R = model.Model('R') for line in sys.stdin: R.read(line) proj = {} proj_norms = {} for P in R: if P[0] in proj_norms: proj_norms[P[0]] += R[P] else: proj_norms[...
0a8b867856c40352fc4da2a4d41b664653df5ee2fe0262423353c6d137acf0c1
Python
696
23
"""Fill tensor in-place along a specified dimension with increasing integers.""" import torch from mrpro.utils.reshape import normalize_index def fill_range_(tensor: torch.Tensor, dim: int) -> None: """ Fill tensor in-place along a specified dimension with increasing integers. Parameters ----------...
2ea3773ca2f129c1ab4993d087b7d2fb1697f5205c1431938008ae7dd4036345
Python
697
28
# -*- coding: utf-8 -*- try: import scipy except ImportError: scipy = None import pytest from emcee import moves from .test_proposal import _test_normal, _test_uniform __all__ = ["test_normal_kde", "test_uniform_kde", "test_nsplits_kde"] @pytest.mark.skipif(scipy is None, reason="scipy is not available") ...
44aad40ef7bf46485c97ae1b3edced49c31983f00dd3dbc496fde3e68e4540bc
Python
697
27
from setuptools import setup dependencies = [ 'seaborn', 'statsmodels', 'scipy', 'patsy', 'matplotlib', 'pandas', 'numpy' ] VERSION = "0.3.4.2" setup( name='pymatch', packages=['pymatch'], version=VERSION, description='Matching techniques for Observational Studies', ...
79eae430628aed3cc745ec436b15f792cb3047553c7815143d61caecd0e06409
Python
697
22
__all__ = ["SpectralAngleLoss"] import torch from torch.nn.modules.loss import _Loss from ...util.math import spectral_angle from .data import PeptideMS2DataBatch class SpectralAngleLoss(_Loss): def __init__(self, size_average=None, reduce=None, reduction: str = "mean"): super().__init__(size_average=si...
8409f6a5ce57e974972eaa691af855d2bb0fc2372587b8ae2ad90e1590a70ecd
Python
697
26
"""Mixin for smarter tensor attributes.""" from typing import Any import torch class TensorAttributeMixin(torch.nn.Module): """Create tensor attributes as buffer.""" def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401 """Set attribute. Set tensors not requiring gradients ...
8d875f364eadabee8d911894062062870690c406a4097b388b1320f0ea75e10d
Python
698
22
import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.tseries import offsets class TestPickle: @pytest.mark.parametrize("freq", ["D", "M", "Y"]) def test_pickle_round_trip(self, freq, temp_file): idx = pd.PeriodIndex(["2016-05-16", "NaT", pd.NaT, np.nan], freq...
268fdb544a7712025409d6c88e56e5d20ed1576af178a54658fb7ddd647b1b22
Python
699
30
import numpy as np import scipy.io as io import sys tagmap = io.loadmat('esns/ESN.mat') #location of trained ESNs sents = [] sent = [] for line in sys.stdin.readlines(): sline = line.strip() if sline == '': #end of sentence sents.append(np.array(sent)) #print ' '.join(sent) sent = [] else: #new ...
e48a64cd0063e4117704f1295fbc424bd1b4247c77821fe8746b2657ad1b56f8
Python
699
18
#!/usr/bin/env python3 # coding: utf-8 from .version import __version__ as version __author__ = ( "Cyril Matthey-Doret, Lyam Baudry, Axel Breuer, Remi Montagne, ", "Nadège Guiglielmoni, Vittore Scolari, Etienne Jean, Arnaud Campeas, ", "Philippe-Henri Chanut, Edgar Oriol, Adrien Meot, Laurent Politis, ", ...
ad98e6e475221b1c7cdcf4751e7102a05b375c5a6238df4ed7fe686bcc83c132
Python
700
28
from pathlib import Path from os import environ from pprint import pprint from generate_predictions import generate_inference if __name__ == "__main__": model_dir = Path("../models") data = Path("../data/norbelladine_4OMTase/boxes/4OMTase_dataset.pkl") out_file = None model_glob = "*" use_cpu = ...
02aa8dd06d7c94db4e8c277bc54141e99149575ba8a79d0990bc4cdcb8d7869c
Python
705
21
import os import cv2 image = cv2.imread("figure/1.jpg",cv2.IMREAD_GRAYSCALE) # imput origin image data res_image = None res_image = cv2.resize(image, dsize=None, fx=1, fy=1, interpolation=cv2.INTER_LINEAR) # resize image blur_image = cv2.GaussianBlur(res_image, (13, 13), cv2.BORDER_DEFAULT) # blur image bl...
24c749bb1dcb9a7b3b38383c77424e449698628eeaa02a02f8400fbe2cdd1e81
Python
706
18
def compute_fluorescence_density_fl1(rtdc_ds): """Compute fluorescence area divided by cell volume [a.u./µm³]""" fl1_density = rtdc_ds["fl1_area"] / rtdc_ds["volume"] return {"fl1_density": fl1_density} info = { "method": compute_fluorescence_density_fl1, "description": "fluorescence density 1", ...
62bd730c5db13717142ca6e006fe10bd405e11a2d1c777f510d9b64be0a6a7f4
Python
706
33
import pytest # The various methods we support downsample_methods = [ "min", "max", "first", "last", "sum", "mean", "sem", "median", "prod", "var", "std", "ohlc", "quantile", ] upsample_methods = ["count", "size"] series_methods = ["nunique"] resample_methods = downs...
7fba51085d42aff3c1be43c63fa17369f962bd8ca03a7a134dfa65f41496c886
Python
706
20
# For reference, see <https://github.com/quinlan-lab/hts-python/blob/master/hts/htsffi.py>, even though it uses deprecated .verify() import cffi import os.path cxx_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'x.cpp') with open(cxx_path) as f: src = f.read() ffibuilder = cffi.FFI() ffibuilder...
bf2f06c7e71af7c58c5427beeedcb561e0748e9dbccb964a7a8614e1deb610fc
Python
706
32
"""Define constant values used across the project.""" class DefaultTokens(object): PAD = '<blank>' BOS = '<s>' EOS = '</s>' UNK = '<unk>' MASK = '<mask>' VOCAB_PAD = 'averyunlikelytoken' SENT_FULL_STOPS = [".", "?", "!"] PHRASE_TABLE_SEPARATOR = '|||' ALIGNMENT_SEPARATOR = ' ||| ' ...
a02efa8719757ca3fbccd3aa39a4a0bae32b9236632d697f6b0caf94cffc110f
Python
708
18
import pandas as pd import pandas._testing as tm def test_astype_str_from_bytes(): # https://github.com/pandas-dev/pandas/issues/38607 # GH#49658 pre-2.0 Index called .values.astype(str) here, which effectively # did a .decode() on the bytes object. In 2.0 we go through # ensure_string_array which ...
0f29415d6e0f3508e2443461c1da2e10b542af135d84c3392f62515aa0a04073
Python
709
35
# JN 2016-02-12 """ create channel_names.csv """ from __future__ import division, print_function import os import sys import csv from combinato import NcsFile FNAME_OUT = "channel_names.csv" def main(fnames): """ for each file in fnames, get entity name write everything to a csv file """ fnames....
27711d61399dfe7f8ff0259a7995149cf6d2952e3fcf78fc75d478b3592880ce
Python
709
28
#!/usr/bin/env python """This script is used to get the midpoint of region""" import re import sys from FEICP import open_file try: bed_file = sys.argv[1] except: sys.exit(__doc__) mid_size = 200 with open_file(bed_file) as fh: for line in fh: if re.search('^#', line): ...
391969cda6709b1d85b747954fb4c958d4815889792f74e45d04e2ac169eaf99
Python
709
27
import re class Dependency: def __init__(self, label='',head="", child=""): self.label = label self.head = head self.child = child def __str__(self): return self.label+"("+self.head+", "+self.child+")" def read(self, s): m = re.search("^([^\(]*)\(([^\,]*), ...
7a07a2b2003032fbedb548a98ecfe91cb757c607868bfe048d55ecc29e6cedf5
Python
711
34
import os import nibabel as nib import numpy as np import random import re from skimage.transform import resize from pathlib import Path from const import * def process_dataset(prob=0.9): _dir = ADNI_DATASET_DIR brain_masks = Path(os.path.join(_dir, "masks", "brain_masks")) originals = list(Path(os.path...
842ae856358e53bc207aa9bd37760b26a3672f0dfacd358faa6cb67e251ad6bf
Python
711
22
import torch import pandas import numpy ligandInput = pandas.read_csv('data/macrophage-Ligands.tsv', sep='\t', low_memory=False, index_col=0) inName = ligandInput.columns.values ligandInput = ligandInput.loc[:,inName] sampleName = ligandInput.index.values X = torch.tensor(ligandInput.values.copy(), dtype=torch.double)...
f4ad8543eeeebf21522af5933b57f601e9a68b6381b8d15b4b404fb9eb7b7866
Python
711
20
"""Task-specific PyCaret 4.0 experiments. Each task subclass pre-configures its `TaskType` and `__sklearn_tags__`. The legacy import paths (`pycaret.classification.ClassificationExperiment` etc.) re-export from here so backward-compatible docs still work. """ from pycaret.tasks.anomaly import AnomalyExperiment from p...
28bcc2693a200072e31baf9a6a115f4810e726a6b85d269732aa6d6af8088975
Python
712
19
import seaborn as sns from matplotlib import pyplot as plt from sklearn.metrics import confusion_matrix def plot_lda_confusion_matrix(lda_predictions, group_vals, groups, ax=None): """Plot a confusion matrix for LDA classifications.""" if ax is None: fig, ax = plt.subplots(1, 1) confusion = confu...
7dbc0d7486b99d69b38f6014e667cd86548a617c930018741fad3cc934fc3bce
Python
712
21
import sys import os import numpy as np 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_openpain_condition(diagnosis): all_diagnoses = ['healthy', 'subacute',...
8cf07694ddd943602934d41e348f224b2d1801af41e8e58cf7aac4995d03d7fc
Python
713
26
import sys base_id = 0 last_id = 0 header = True for line in sys.stdin: if line.strip() != '': row = line.strip().split() if header==True: sentid_col = row.index('sentid') header = False else: try: cur_id = int(row[sentid_col]) ...
91928b7d0bc129bd3de228c12383e64a96270e7b15a07c616b970bf815be2d75
Python
714
17
import sys import pandas as pd import csv spr = pd.read_csv(sys.stdin) spr = spr.rename(lambda x: 'fdur' if x == 'time' else x, axis=1) spr = spr[['subject', 'word', 'code', 'fdur']] itemmeasures = pd.read_csv(sys.argv[1], sep=' ') del itemmeasures['word'] spr = spr.merge(itemmeasures, on='code') spr = spr.sort_values...
1b45ad5a9da02f1df08efed5d20f169633dde12216cfff976e92023dcea9f216
Python
716
34
import sys linetoks_path = sys.argv[1] with open(linetoks_path, 'r') as linetoks: h = sys.stdin.readline().strip() print(h) h = h.split() wix = h.index('word') l = sys.stdin.readline().strip() s = linetoks.readline().strip() i = 0 out_cur = '' while s and l: w = l.split(...
72a1e5770e1859bdfb9489c2791c1685dbb5c5c68dd8b7f92659664548112e13
Python
716
23
import pytest import pandas as pd import pandas._testing as tm class TestAstype: @pytest.mark.parametrize("ordered", [True, False]) def test_astype_categorical_retains_ordered(self, ordered): index = pd.IntervalIndex.from_breaks(range(5)) arr = index._data dtype = pd.CategoricalDtype...
8267cc23864869710ece2af5dca770f11ad9e1ea50a97bac825b5ba14012d2ac
Python
716
26
import requests def get_downloads_from_pepy(package_name): response = requests.get(f"https://api.pepy.tech/api/v2/projects/{package_name}") response.raise_for_status() return response.json()["total_downloads"] def create_combined_badge_url(count): base_url = "https://img.shields.io/badge/total%20dow...
022e9d78388697050747d995be59086d76335990031ee3cb95a0630cad11db05
Python
717
27
import pytest from pandas._libs.tslibs.parsing import get_rule_month from pandas.tseries import offsets @pytest.mark.parametrize( "obj,expected", [ ("W", "DEC"), (offsets.Week().freqstr, "DEC"), ("D", "DEC"), (offsets.Day().freqstr, "DEC"), ("Q", "DEC"), (offs...
f1b7241fe70c236769edc3448befb595b75d437540d9b7adf329b25275c41da1
Python
717
17
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Created by Roberto Preste import os DATADIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data") HUMAN = os.path.join(DATADIR, "human.vcf") HUMAN_ANN = os.path.join(DATADIR, "human_ann.vcf") HUMAN_ANN_CSV = os.path.join(DATADIR, "human_ann.csv") HUMAN_ANN...
57b1db8439e855699fe88fe1266eaf86971dc8d89e9cd681dee84eaedc82659d
Python
721
23
import numpy as np, matplotlib.pyplot as plt plt.rc("xtick",labelsize=20) plt.rc("ytick",labelsize=20) plt.rc("axes",labelsize=20) a = np.loadtxt("fpbase_spectra.csv").T l = a[0] ex = a[1] em = a[2] fig = plt.figure(1) ax = fig.add_subplot(111) ax.plot(l,ex,c="C0",lw=4,label="absorption") ax.plot(l,em,c="C2",lw=4,la...
1b33434422650185a7b98b388c4967b1ead88ccb2a7135d73762f6e11a47c609
Python
723
31
#!/usr/bin/env python import json from pathlib import Path from neuronbridge.model import * ROOT_DIR = "schemas" def print_schemas(): for model in [DataConfig, ImageLookup, Matches]: print(model.schema_json(indent=2)) print() def write_schema(schema_name, schema_obj): filepath = Path(ROOT_D...
cb6fdcdbbc355863d77b738c042b6bdcd8fe414011f67fc5023bf4cb082f5873
Python
723
25
import pytest from emcee.pbar import _NoOpPBar, get_progress_bar try: import tqdm except ImportError: tqdm = None def test_display_false(): assert isinstance(get_progress_bar(False, 100), _NoOpPBar) @pytest.mark.skipif(tqdm is None, reason="tqdm not available") def test_tqdm_modes(): assert isinst...
ee88a105496b6d88c97a0e4024331af8f83ff5b01fcabb46b6f9fd6a93d5bb86
Python
723
28
import numpy as np from skimage import util, restoration def subtract_background(image: np.ndarray): inverted = util.invert(image) inv_bg = restoration.rolling_ball(inverted, radius=45) # imshow(inv_bg) # pyplot.show() inv_dif = inverted - inv_bg dif = util.invert(inv_dif) return dif if ...
cb1ab1ce16b969985f0cdee70cc79c2eee955681e9f5247443850e272ec24c6d
Python
724
21
import os # import cloudpickle import compatibility import pandas as pd from . import parent_classes def check(obj): '''checks wherther obj can be saved with this dumper''' return isinstance(obj, (pd.DataFrame, pd.Series)) #basically everything can be saved with pickle class Loader(parent_classes.Loader): ...
4fc986a611897e03953d2d24f016c63d59ccc00d896386a8ec4a5f4e75907df9
Python
725
22
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
95c6df1179bef79ce2e305ce2df6e763545af497d704daf3f392ff6395b8019d
Python
725
26
import reverb import tensorflow as tf def make_reverb_dataset(server_address: str, table: str, batch_size: int): def _make_dataset(unused_idx): return reverb.TrajectoryDataset.from_table_signature( server_address=server_address, table=table, max_in_flight_samples_per_wo...
b1ed6d391eb9088f58afe77b2756469023a67afd91736014dc08cebf81c05c5e
Python
725
22
import numpy as np import pandas as pd import pandas._testing as tm class TestCategoricalComparisons: def test_categorical_nan_equality(self): cat = pd.Series(pd.Categorical(["a", "b", "c", np.nan])) expected = pd.Series([True, True, True, False]) result = cat == cat tm.assert_ser...
f2649a12daa0ff52855026ab288ada248ca659e80e676f8aec5999240787d335
Python
725
11
from aigarmic.plate import Plate, PlateSet, plate_set_from_dir from aigarmic.model import Model, BinaryModel, BinaryNestedModel, SoftmaxModel from aigarmic.file_handlers import (create_dataset_from_directory, predict_colony_images_from_directory, s...
4facd50c0b9fb0cc00e4d3a12a0d5b1ad111a92fd529122bedb51eaefab48ce5
Python
727
28
import sys header = True line = sys.stdin.readline() sentid_base = 0 sentid = -1 docid_last = None while line: if line != '': if header == True: h = line.strip().split() docid_col = h.index('docid') sentid_col = h.index('sentid') print(' '.join(h + ['sampl...
9870bb24894e64866dec79ac69be5dcd4fa0873042b960f72e28c355be590a71
Python
727
27
import os import pysam input_bam = "/data/DATA/CellLine/HCC1395/HiFi_2023Pacbio/HCC1395.GRCh38.bam" # input_bam = "/data/DATA/CellLine/HCC1395/HiFi_2023Pacbio/HCC1395-BL.GRCh38.bam" output_bam = "/data/DATA/CellLine/HCC1395/HiFi_2023Pacbio/HCC1395.GRCh38.nanomonsv.bam" # output_bam = "/data/DATA/CellLine/HCC1395/H...
820bf36da8a3c59b2be8ae5d4666e58646f6b12b94389bb031f7f38f18f05d85
Python
728
27
import sys, json itemmeasures = open(sys.argv[1]) # word time time_info = open(sys.argv[2]) words = list() start_times = list() # header time_info.readline() for l in time_info: word, time = l.strip().split() words.append(word) start_times.append(time) header_cols = itemmeasures.readline().strip().split(...
ead4d94fde065ee25b934e085e7f453e539666219ee6046b00718aef0e669658
Python
728
31
"""cptools2 package initializer. Expose top-level modules and package metadata. """ from . import filelist # noqa: F401 from . import splitter # noqa: F401 from . import commands # noqa: F401 from . import parse_yaml # noqa: F401 from . import utils # noqa: F401 from . import job # noqa: F401 from . import colo...
3bb0c59f4ff61ca19e3a3fdac754c0ab521b5cef479536eda477d8cf3ebc57ef
Python
729
28
# -*- coding: utf-8 -*- """ Pycaret Author: Mavs Description: Module containing all constants of pycaret. """ from typing import Union import numpy as np import pandas as pd from scipy import sparse # Group of variable types for isinstance SEQUENCE = (list, tuple, np.ndarray, pd.Series) # Variable types for type ...
5c560c6b2543f19efbac76e79625205d52f6f90919b311bb0f7596c5c2c3786f
Python
729
19
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 an...
7617a945907335daf0ba0316ddc8d73bd0214e1317e3a11f22c715146aca4f3c
Python
730
28
import torch import numpy as np from abc import ABC, abstractmethod class Pretransformations(ABC): """ Parent class for pretransformations, abstract methods are defined here. """ __slots__ = "gadgetron_array", "device" def __init__(self, gadgetron_array: np.ndarray, device: torc...
a477df1c9bfb1d3f875290bc683cec7d18563ec46cb0ab67d84d3fd5645d3c7a
Python
730
29
# STA Movie Maker # Lloyd Russell 2017 import sys import os import ctypes import json import numpy as np import difflib import glob import colorsys import scipy from scipy import io as sio from skimage.external import tifffile import time import sta, PrairieLink, paq2py, ThorLink from skimage import ex...
1e2f84333c4ebf4db28a0bfe8241597cd0e3d96d8551d2fcf841ae21da2a28b7
Python
734
23
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
b6cc93bebc0415508345e9bf3552047bfde1b51d7fa3530e5b8529ee593a5ba0
Python
734
25
import subprocess def run(model, attention, oversample): att = "-a" if attention else "" ov = "-o" if oversample else "" subprocess.run(["make", "train_eval", f"MODEL={model}", f"ATTENTION={att}", f"OVERSAMPLE={ov}"]) def run_lod(model, attention, oversample=False): att = "-a" if ...
62d75c90ef63dcdfffb2af5eaf3581e2e05387ed097697cc6de34616d4b3bf30
Python
736
20
# 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...
0a755c8b116e99e075d545e470f1919d6af1d1d2e417c7c4c4ed6adb94827f0c
Python
737
32
""" Helpers for sharing tests between DataFrame/Series """ from __future__ import annotations from typing import TYPE_CHECKING from pandas import DataFrame if TYPE_CHECKING: from pandas._typing import DtypeObj from pandas import Series def get_dtype(obj: DataFrame | Series) -> DtypeObj: if isinstance...
5a3b451e3a27695baa6a3d171ee15210791397b851323c97c9dc2a01a0ba34e3
Python
738
33
import matplotlib.pyplot as plt import sys data = sys.argv[1] with open(data) as d: d = d.read().split("\n") allData = d[43:] x = [float(allData[i].split('\t')[0]) for i in range(0,len(allData)-1)] y = [float(allData[i].split('\t')[2]) for i in range(len(allData)-1)] #filter by time tota...
b068ddc69ad1d4d206b53176dab9aa7bb735107e93cf23a8bf800dca83a95297
Python
738
20
import pandas as pd import sys names = ['subject','word','sentid','sentpos','fdur','wlen', 'correct', 'resid', 'startofsentence', 'endofsentence'] data = pd.read_csv(sys.stdin,sep='\t',skipinitialspace=True) data.rename(columns={ 'subj_nr':'subject', 'sent_nr':'sentid', 'word_pos':'sentpos', 'RT':'fdu...
b4d244b9113fdcfade54d2b875eb01bb532a4f9c98f4ab4361b429ce244cd5b5
Python
738
18
# 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...
e233f5bf0001a934bf5c4eed25dcba133c85345b678386398b5a09c3e75f19ed
Python
738
28
#!/usr/bin/env python3 import os from glob import glob from combinato import NcsFile def to_original(): ncsfiles = glob('*.ncs') for nf in ncsfiles: n = NcsFile(nf) oldname = n.header['AcqEntName'] + '.ncs' if os.path.exists(oldname): print('Not renaming {} to {}, file exi...
89168431bd698aa38d1e82434385ad3a0a5fbbe439053747da2c927c1dbffac4
Python
739
32
import numpy as np import pandas as pd class TimeLogicalOps: def setup(self): N = 10_000 left, right, lmask, rmask = np.random.randint(0, 2, size=(4, N)).astype("bool") self.left = pd.arrays.BooleanArray(left, lmask) self.right = pd.arrays.BooleanArray(right, rmask) def time_...
1f0380e06639f5f117d42c80edf3bb86ecad7fd46fa8d05012400c80e1585bb2
Python
740
25
import sys, re docids = sys.argv[1:] # yc: doesn't seemed to be using this? headers = sys.stdin.readline().strip().split() + ['sampleid', 'tr', 'splitVal15'] docid_ix = headers.index('docid') subj_ix = headers.index('subject') time_ix = headers.index('time') print(' '.join(headers)) for l in sys.stdin: row = l....
6ca37482f818c686b9d35da3c3c9978093a4c746b6e7027a19257e26d0227336
Python
740
24
import json from loess import loess_1d from sklearn.ensemble import IsolationForest import real_unit_convert as ruc import aggregate_figures as af import pandas s_tables, l_tables = af.load_all() united_s_table = pandas.concat(s_tables) united_l_table = pandas.concat(l_tables) l_groups = united_l_table.groupby('file...
bb0613009558b91c41b1c9acb241eb1ec627daa4c00ac87f58d0d377e40f319a
Python
741
29
import pytest import pandas as pd @pytest.mark.parametrize( "timedelta_val,expected", [ ("1 day", "day"), ("1 hour", "hour"), ("1 minute", "minute"), ("1 second", "second"), ("1 millisecond", "millisecond"), ("1 microsecond", "microsecond"), ], ) def test_t...
13d1574adf63043d354d27b0c464eebc7e0b0c2dccbf5f3a10aaea4db25d579d
Python
743
20
import warnings import single_cell_parser as scp errstr = "The cell_modify_function synaptic_input is experimental! Make sure synapses " errstr += "are beeing activated as you expect and have the effect you expect!" warnings.warn(errstr) def synaptic_input(cell, network_param = None, synapse_activation_file ...
f83a2d9ac88c1b1c0e8902719b50f64ad00102c1ca930285206853418fd322e2
Python
743
21
import torch.nn as nn from tnn.layers import tLinearLayer class tFullyConnected(nn.Module): def __init__(self, layer_widths, dim3, M, activation=None, bias=True, device=None, dtype=None): factory_kwargs = {'device': device, 'dtype': dtype} super(tFullyConnected, self).__init__() self.M =...
9fcc5e538a1db963b923eb1d845330174f7d7c1215f605bcc2469a2e5765981f
Python
744
16
# 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...
fc177340b627c1bc0b3f52fee2e354121582ad5850589334413e13039259f561
Python
745
23
from matplotlib.colors import to_hex import numpy as np def hex2rgb(value): value = value.lstrip('#') lv = len(value) return [int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)] def rgb_to_hex(rgb): # Normalize RGB values to be within 0-1 range r, g, b = [val / 255.0 for val in rgb] #...
07fcac48fb811aab0bbda6b84f6321976bb9b553cf43d6b8a58b8cc69be6242a
Python
746
23
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
1d37e6a56fde242a9662db1b789f0e340ee7df398e14666fc249756bf0c3a0a2
Python
746
26
import torch from torch import nn class DatasetTransform(nn.Module): def __init__(self): super().__init__() def forward(self, dataset): return dataset class ImageDatasetTransform(DatasetTransform): def __init__(self, **kwargs): super().__init__() import kornia sel...
d0df72e1bbcd5292b00c794a9a948b69c7885895d2668a127f5324fd8a4198b9
Python
746
23
import numpy as np import pytest import pandas as pd import pandas._testing as tm class TestRepeat: @pytest.mark.parametrize("use_numpy", [True, False]) @pytest.mark.parametrize( "index", [ pd.period_range("2000-01-01", periods=3, freq="D"), pd.period_range("2001-01-01...
ecdeee86fd7d7c43e678b4776f6ef68a8130397d355ad1424b35fc891dccf96f
Python
746
26
import ase import os from ase.io import read import numpy as np import csv mofs = ase.io.read('opt-geometries.xyz',index=':') refcodes = np.genfromtxt('opt-refcodes.csv',delimiter=',',dtype=str) properties = np.genfromtxt('opt-bandgaps.csv',delimiter=',',dtype=str) print(len(mofs), len(refcodes), properties.s...
9e699baee422a461f640999ac941d5f261483ed398e8f2d40ef7f72aae451191
Python
748
40
import sys def correct_parens(s): s = s.strip() l = 0 r = 0 for c in s: if c == '(': l += 1 elif c == ')': r += 1 paren_diff = l-r if paren_diff < 0: # print('Too many right parens!') # print(l) # print(r) # print(s + '|') s = s[:paren_diff] # print(s + '|') # pri...
ac3cd92e2b47ed6d0bb486beedcc43d63e4a17ef571bbfe04977efffb7b49fa6
Python
748
30
from __future__ import print_function # makes this work for python2 and 3 import vegas import ctypes # import library cfcn = ctypes.CDLL('cfcn_ctypes.so') # specify argument types and result type for cfcn.fcn cfcn.fcn.argtypes = (ctypes.POINTER(ctypes.c_double), ctypes.c_int) cfcn.fcn.restype = ctypes.c_double # ...
f39dff7ad7db931e3e1f1040e2ba369ac88dce28cf32bf7824bc7ba7489b44ad
Python
749
35
import matplotlib.pyplot as plt def set_axis(ax, x, y, letter=None, fontsize=20): ax.text( x, y, letter, fontsize=fontsize, weight='bold', transform=ax.transAxes) return ax def pval(pvalue): if pvalue<0.05: nap = '*' else: nap='n.s.' if pvalue<0.01: ...
28db6b1528c6258c4849367dc8ac0b0027b6af81b2c7ebd036a80148d8ac63b4
Python
750
31
# flake8: noqa from .aggregation import ( aggregate_counts, calculate_mutation_rates, merge_aggregates, read_aggregates, read_rates, ) from .bam import ( check_bam_contains_duplicate, check_bam_contains_secondary, check_bam_contains_unmapped, get_tags_from_bam, parse_all_reads, ...
40228c2914116af666325a5e46341143e03eccc3aa5a829cef0cb59465017414
Python
751
20
"""Module defining inputters. Inputters implement the logic of transforming raw data to vectorized inputs, e.g., from a line of text to a sequence of embeddings. """ from onmt.inputters.inputter import get_fields, build_vocab, filter_example from onmt.inputters.iterator import max_tok_len, OrderedIterator from onmt.in...
8ec31062badc1fd5c1f04f0a75b7ca71b20dddce138700498c7ff19e5e73980e
Python
751
30
from abc import ABC, abstractmethod class Structmaker(ABC): """ This base class is responsible for preparing the struct to be sent through a socket (e.g., to the MLC tracking software). """ @abstractmethod def __init__(self, acquisition_data: dict, connection_data: dict, *args)...
c4c92e1d08acb2939e1a9584758d59c8c2b624dd73be20afca8df33735f3abb4
Python
751
20
from tests import TestCaseNeSVoR import torch import scipy from scipy.sparse.linalg import cg as cg_scipy from nesvor.svr.reconstruction import cg class TestCG(TestCaseNeSVoR): def test_cg(self): A = torch.tensor( scipy.linalg.hankel([1, 2, 3, 4, 5], [4, 7, 7, 8, 9]), dtype=torch.float32 ...
6cc12728ab1baed2464fe74c13b77b9036b4b7dd13cc9d459c3e474fa1593bb5
Python
752
26
import imp import os #os.chdir('/gscratch/spe/mpun/protein_holography/hologram') import Bio.PDB as pdb from protein_holography.hologram.protein_dir_parse import get_proteins_from_dir from protein_holography.hologram.sample_protein import sample_amino_acid_from_protein as sample import protein_holography.hologram.pdb_...
b01c8989c0d2f55f49e2d5fe839c2122c69c77b0b6b62c94d5884c4828d98b3a
Python
752
29
"""https://stackoverflow.com/questions/39304951/""" from functools import wraps from PyQt6 import QtCore class Runner(QtCore.QThread): """Runs a function in the background""" def __init__(self, target, *args, **kwargs): super().__init__(*args, **kwargs) self._target = target self._ar...
f4d7b1f98fe010ce6585dffb26c9e6e51f46e6cbdf137124e3b0873b792e973e
Python
753
26
from pathlib import Path from typing import List, Dict, Tuple, Union import pickle as pkl import numpy as np def load_dataset(pkl_file: Path) -> Tuple[List[Dict[str, Union[str, int]]], np.ndarray]: """Snapshots provide the residue order of the boxes""" assert isinstance(pkl_file, Path) assert pkl_file.i...
5da8b6cb4cfb047cae42e11b8b9174f1efd356e72d242b0ae3f32c2a582fa2a4
Python
754
23
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
ab1d55dcb4043a4a59f9e0f48acdd0cf2b1ded6ba6b86c94cdc1d6a63336fc63
Python
754
24
import os import pandas as pd gwas_dir = "/cluster/projects/p33/users/alexeas/most_mental/new_start/gwas_merged/touchscreen" outf = "gwas_n.touchscreen.csv" outf_max = outf.replace("gwas_n", "n_max") series_list = [] for de in os.scandir(gwas_dir): if de.name.startswith("orig"): trait = de.name.split('.')[...
beeb9f521dd4f7f62af5e2c43ad92bb75a160224596ff78b8cb216582b9ed4ab
Python
755
36
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.16.0 # kernelspec: # display_name: ol-connectome # language: python # name: ol-connectome # --- # %% # %load_ext autoreload from pathlib ...
df9d1a65f28b81a97ee71ae216df76ba7d0e2eb26f8c8903432960d4cfeb606f
Python
755
27
import pytest @pytest.mark.filterwarnings("ignore:The inplace keyword:pandas.errors.Pandas4Warning") @pytest.mark.parametrize( "func", [ "reset_index", "_set_name", "sort_values", "sort_index", "rename", "dropna", "drop_duplicates", ], ) @pytest.mark...
797798bc921ea8a235373eeec2eff2c0fdb7126e8f9d66249b578ccfa0c39f88
Python
756
23
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
9677c2416909638b9f33fdcd1f80608ee82c03bffeafe6753dcfbf17b1bd2038
Python
757
25
import pytest import pandas as pd import pandas._testing as tm def test_divmod_bool_raises(box_with_array): # GH#46043 // raises, so divmod should too ser = pd.Series([True, False]) obj = tm.box_expected(ser, box_with_array) msg = "operator 'floordiv' not implemented for bool dtypes" with pytest...
bc4d61e72bac7073c7e681421595a713972735df84de6197e7f169fb440bc052
Python
758
19
"""PyTest fixtures for the csm tests.""" from mrpro.data import IData, SpatialDimension from mrpro.phantoms.coils import birdcage_2d def multi_coil_image(n_coils, ph_ellipse, random_kheader): """Create multi-coil image.""" image_dimensions = SpatialDimension(z=1, y=ph_ellipse.n_y, x=ph_ellipse.n_x) # Cr...
dc41c33c6f728e8821a4f9a24298f15ed857bc0c1fc8a41bc324b1b0a4dc472d
Python
758
24
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2026, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
6453579cc34cf66b474bd59a3772aed0b837951112272d7097c9fd549caa00a5
Python
760
31
from values import * def NCC(cell,i,memb_id,xNCC,area): if cell.segment == 'DCT': LzD=i-1 x1=LzD+1 xn=cell.total xdct2=2.0/3.0 if x1/xn<xdct2: NCCexp=1.0 else: NCCexp=2*(1-(x1/xn-xdct2)/(1-xdct2)) else: NCCexp = 1.0 alp=cell.conc[0,memb_id[0]]/dKnncc alpp=cell.conc[0,memb_id[1]]/dKnncc betp=...
72bf335eec009f4ae4f7d46f75b7b0bc8611eba15f98e986402cbe2f0e6f1ab7
Python
760
30
import numpy as np import pandas as pd from pyod.models.cblof import CBLOF def convert_to_fp64(X): if isinstance(X, pd.DataFrame): X = X.astype( { col: np.float64 for col in X.columns if X.dtypes[col] in (np.float32, np.float16) } ...
8d1d68a35c566d0d642050714b0278c2b1c99f16b246943689d83a04b8e62e3b
Python
764
26
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import twixtools import datetime def main(): parser = argparse.ArgumentParser(description="Output the acquisition start time of the first scan in the datfile in iso format.") parser.add_argument("datfile", type=str, help="Path to .dat file") ar...
1d3a7ff72c7c14e261306960b108f9344668410697835c398ce6a9c7adbc169b
Python
765
29
from pathlib import Path from pandas import read_sas ROOT = Path(__file__).parents[3] / "pandas" / "tests" / "io" / "sas" / "data" class SAS: def time_read_sas7bdat(self): read_sas(ROOT / "test1.sas7bdat", encoding=None) def time_read_xpt(self): read_sas(ROOT / "paxraw_d_short.xpt", encodin...
58c25f9877a404999f239de08d7e34962aba4bccc8c7bf85878e5a9150f70a0f
Python
765
42
"""NiMARE: Neuroimaging Meta-Analysis Research Environment.""" import logging import warnings from ._version import get_versions logging.basicConfig(level=logging.INFO) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("ignore") from . import ( annotate, base, corr...
72dea2e937dfa6acf2e0667860b7a38b0e7d35bec7326e97f4da58ba6e15d22a
Python
765
20
import sys, pandas as pd data = pd.read_csv(sys.stdin, sep=' ', skipinitialspace=True) ## Remove non-numeric columns because they can't be reduced data = data._get_numeric_data() del data['sentpos'] dataGrouped = data.groupby('sentid') dataSentID = dataGrouped[['sentid']].agg('max').rename(columns = lambda x: 'sent...
f57512a25d38085c3ff3d2b45db0cd182d15ad8832052273726e6c103ac770a3
Python
766
26
# 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...