sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
e4493f5aed854cca4ab305e07c348430d40a0362d23b0b3ec6c935c1c4fe009d | Python | 1,145 | 45 | import logging
logger = logging.getLogger('DARTS')
fh = logging.FileHandler('darts_accuracy.log')
logger.addHandler(fh)
def log_accuracy(accuracy, split: str='train'):
""" Log the average accuracy
Parameters
----------
accuracy: darts.MultitaskAccuracyMeter
Current accuracy meter state
... |
ea1180cd14a874a9ecdab37b68ca72ee61f04a7ebece07557d4dfc4bbafb9acd | Python | 1,145 | 26 | import pandas as pd
import os
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 app import create_app, db
from app.models import SourceDataset
from config.globals import ENVIRONMENT
from path... |
fb7e02acb3328d0f033654d4f919791d749c3528884800962debc452223f9773 | Python | 1,145 | 45 | """
.. module:: ui_utils
:platform: Linux, Windows
:synopsis: UI utils for creating dialogs via Tkinter
.. moduleauthor:: Fredrik Nysjo
"""
import tkinter as tk
import tkinter.filedialog
import tkinter.messagebox
def askopenfilename(filetypes):
"""Show an open dialog asking for a filename
Returns: st... |
293b0221d813ec62951481cfcbfc577b866e091d2153215d1b198b7fe81e596c | Python | 1,146 | 38 | import os
from setuptools import setup, find_packages
from src.version import __version__
cur_path = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(cur_path, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='SVision-pro',
version=__version__,
des... |
d962dd0580e52b70395c09a440ebb0697eede9cf3675efe501e7594474383ef9 | Python | 1,146 | 44 | import sys
sys.path.append('.')
import time
from CommonSystem.Config import Config
from StimulationSystem.stimulationOperator import stimulationOperator
from StimulationSystem.StimulationProcess.StimulationController import StimulationController
from CommonSystem.MessageReceiver.ExchangeMessageManagement impor... |
06fffdf0022ac470e062ee68efda9bf56f19081aaea914e76c9eec6f81207dc9 | Python | 1,148 | 35 | """Module contains utility functions."""
import collections
import click
def dict_merge(dct: dict, merge_dct: dict):
"""Recursive dict merge.
Inspired by `dict.update()`, instead of updating only top-level keys,
dict_merge recurses down into dicts nested to an arbitrary depth,
updating keys. The `me... |
6e91e5a4d3db80a8d684d2652b20fd6475be6e5f382494363999d1d1e2492791 | Python | 1,149 | 45 | # JN 2016-06-10
import numpy as np
EMPTY = np.array([], dtype=np.float64)
def cross_correlogram(times1, times2, lag, is_same):
"""
Calculate cross-correlogram. This assumes that the input arguments are sorted!
In most cases, np.histogram(res, bins) will follow.
"""
if times1.shape[0] < times2.shap... |
489fa8ff9e3fde7db531b3b18f6c2d78ec16dccce8b51ec8d94c5eff449ee7d7 | Python | 1,150 | 35 | """Operator returning the magnitude of the input."""
import torch
from mrpro.operators.EndomorphOperator import EndomorphOperator, endomorph
class MagnitudeOp(EndomorphOperator):
"""Magnitude of input tensors."""
@endomorph
def __call__(self, *x: torch.Tensor) -> tuple[torch.Tensor, ...]:
"""Ca... |
25f838394b1a7e5580219ae8e450ec6edf385abe0cbde409c1e9d174c0330ba4 | Python | 1,151 | 44 | import numpy as np
class ObservableDict(dict):
"""
Simple class that holds an argument dictionary.
Triggers a call to .notify_change() of the observer class(es) whenever
a key is changed (not when it is initialized)
"""
def __init__(self, *observers, **kwds):
self.__dict__.update(kwd... |
3118c2a204109581d5aaed27e0dd725449b1c6468fd3b79f4bcf5a9e81503f4e | Python | 1,151 | 25 | # 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... |
6fd6d0bc595d9c970638549e651fb4b9a1de91cbfd3219d2a87d310eb23da630 | Python | 1,151 | 30 | import pandas as pd
import cellex
from pathlib import Path
# To run tests:
# * activate your venv and ensure cellex is not installed
# * navigate to CELLEX/
# * run `python -m pytest`
BENCHMARK_DIR = Path(__file__).parent / Path('_benchmark/')
def test_recreate_benchmark():
path_data = str(Path(BENCHMARK_DIR, "... |
7d8090df3966581676339884eaf7831f25435881d4c095a175fd8aaaa6a4fbff | Python | 1,151 | 33 | def scale_apical_morph_86(cell):
'''
This is the method, robert has used for scaling the apical dendrite of CDK morphology 86
scale apical diameters depending on
distance to soma; therefore only possible
after creating complete cell
'''
import neuron
h = neuron.h
dendS... |
109660cbb26031023a9cb51a5cd21054891213e59f356fe817ecd2a69f7b2bb3 | Python | 1,152 | 41 | # Copyright 2013-2015. The Regents of the University of California.
# All rights reserved. Use of this source code is governed by
# a BSD-style license which can be found in the LICENSE file.
#
# Authors:
# 2013 Martin Uecker <uecker@eecs.berkeley.edu>
# 2015 Jonathan Tamir <jtamir@eecs.berkeley.edu>
import numpy as ... |
2e985dc62de61a8c70dbc463c2f6ca1d717bd97e47a79f7ef0e5139753d3c626 | Python | 1,152 | 27 | import pandas as pd
import os
import sys
import pdb
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from app import create_app, db
from app.models import Subject, Visit, Condition, SourceDataset, Image
fro... |
684a5da99b12835539d5014bd7613183cdd7f2cddf435eaac328f3068d2f8e17 | Python | 1,153 | 39 | from collections import Counter
import numpy as np
import pandas as pd
def estimateFragSize(ds, top=500):
"""
Estimation PETs fragment size.
@param ds: list, PET distance
"""
ds = pd.Series(Counter(ds))
ds.sort_values(inplace=True, ascending=False)
ds = ds[:top]
frags = int(np.median(ds... |
4905defb3f0e4c28492e192aeff59a443e6e27b520d9913b3e7405571174d35d | Python | 1,154 | 46 | import os
import plotnine as p9
from datetime import datetime
def save_as_pdf(plot: p9.ggplot, filename: str=None, path: str=None, dpi: int=None, verbose: bool=False) -> None:
"""Save a plotnine ggplot as pdf
Parameters
----------
plot : p9.ggplot
The plot to save
filename : str, optional... |
b0738cc3b605f34e046c65761b26675f303a5743c8fd24521b8ddd7b388e8f96 | Python | 1,154 | 31 | #
# Simple script to go from berkeley's lexicon files to
# our own CKY format
#
# usage:
# cat berk_lexicon | scripts/berklexicon2ckylex.py
import re
import sys
for line in sys.stdin:
match = re.search('([^ ]+) ([^ ]+) \[(.*)\]', line)
if match is not None:
(m1,m2,m3) = match.group(1... |
b2ddb0319f9e406ddbcb53b0e795f3943288634321c2f58d339ffec91c130891 | Python | 1,156 | 46 | import time
import logging
import os
import numpy as np
import torch
import ismrmrd
import gadgetron
from modules.schemas.edsr_sr import (
EdsrModel,
EdsrPretransformations,
EdsrPosttransformations,
)
def main(connection):
logging.basicConfig(level=logging.DEBUG)
device = t... |
e29237c6e0e18bc2ce71bcaca591abf64b95ac7a82aa841f46039aaca3a0f646 | Python | 1,158 | 41 | import argparse
import os
import ete3
import pandas as pd
from ete3 import NCBITaxa
def get_args():
"""
Get arguments from command line with argparse.
"""
parser = argparse.ArgumentParser(
prog='Run_ete3_NCBI_update.py',
description="""More or less make sure ete3 NCBI taxonomy will work... |
ac3eac260bf04332233f8561b8711bdee4e6b8814af2b1d441ac3c8af85740d8 | Python | 1,159 | 24 | # Copyright 2018-2024 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
dfe2b37920ee0e322e3326a4b3003f38388dc3a79a0f47c2a6f1c8b606aab01e | Python | 1,161 | 35 | #######
# PMIpred was developed by Niek van Hilten, Nino Verwei, Jeroen Methorst, and Andrius Bernatavicius at Leiden University, The Netherlands (29 March 2023)
#
# When using this code, please cite:
# Van Hilten, N.; Verwei, N.; Methorst, J.; Nase, C.; Bernatavicius, A.; Risselada, H.J., Bioinformatics, 2024, 40(... |
19004bcdf63e2c66b2a534ea6a5a39decd0ab598e27a068a24e1ef261c3ab4fb | Python | 1,162 | 37 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 1 09:55:10 2019
@author: vman
"""
from sklearn import linear_model
import numpy as np
class LinearRegression(linear_model.LinearRegression):
"""
LinearRegression class after sklearn's, but calculate t-statistics for... |
7e14b0557e3a24edb6d8a47894bbb0b2f37fd0cc0a54530df0d312ca12ee31d1 | Python | 1,162 | 34 | """
config for datetime formatting
"""
from __future__ import annotations
from pandas._config import config as cf
pc_date_dayfirst_doc = """
: boolean
When True, parses ambiguous dates with the day first, eg 20/01/2005.
This affects parsing only, not how dates are displayed, and applies to
the Period con... |
a75d79b5de5c8fbb924ffd19ae574acf54b193076ece0fdfc61462968e925e47 | Python | 1,162 | 29 | # Vanilla Gradient
from ..utils.process import get_last_layer
import numpy as np
import tensorflow as tf
from skimage.transform import resize # for N-dimensional images
def get_vanilla_grad(model, io_imgs, class_id, LAYER_NAME=None, MODALITY="FLAIR", XAI_MODE="classification", DIMENSION="2d"):
modality_dict = {"F... |
bf43613283c371afd32981c9c1ac8eb7c536800c9215d4a2ebadbd1437b15481 | Python | 1,162 | 40 | import pytest
from pandas.core.frame import DataFrame
class TestDataFrameValidate:
"""Tests for error handling related to data types of method arguments."""
@pytest.mark.filterwarnings(
"ignore:The inplace keyword:pandas.errors.Pandas4Warning"
)
@pytest.mark.parametrize(
"func",
... |
54d638fe64f67db09e414df9dd49fcad873b5684ce76feb527917b9554905f65 | Python | 1,163 | 47 | #!/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_rows_to_columns(path_name):
files = glob.glob(path_name +'/**/*.c... |
73ea587bd4f017d4a7ca8e936c3b24195dd71b8f31880485418bfd6afa7b1742 | Python | 1,164 | 35 | """Operator returning the phase of the input."""
import torch
from mrpro.operators.EndomorphOperator import EndomorphOperator, endomorph
class PhaseOp(EndomorphOperator):
"""Phase of input tensors."""
@endomorph
def __call__(self, *x: torch.Tensor) -> tuple[torch.Tensor, ...]:
"""Calculate the ... |
1d7fb10e668b330e711a58c3e79e249387ecaf7c29434ae63ff4cea6b1910259 | Python | 1,165 | 33 | from rl_games.common.transforms import transforms
import torch
class SoftAugmentation():
def __init__(self, **kwargs):
self.transform_config = kwargs.pop('transform')
self.aug_coef = kwargs.pop('aug_coef', 0.001)
print('aug coef:', self.aug_coef)
self.name = self.transform_config['n... |
29ce87bc20ac01c3fb876fd9099709b3417bd23b635bbf541ab23cb9f77d6b02 | Python | 1,165 | 35 | from tempfile import TemporaryDirectory
import pandas as pd
import subprocess
import os
def go(data: pd.DataFrame):
tempdir = TemporaryDirectory()
data.index = data.index.str.upper()
data.to_csv(f"{tempdir.name}/data.csv", index=True)
cmd = f"Rscript {os.path.dirname(__file__)}/_go_pipeline.R -t {temp... |
bea2e98b70b7a9dc76caa3145127a12511d42a8fe0419b96a1efb113b38bd556 | Python | 1,166 | 35 | """empty message
Revision ID: 35fca522d209
Revises:
Create Date: 2021-08-30 10:48:25.455031
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '35fca522d209'
down_revision = None
branch_labels = None
depends_on = None
... |
f632e68fef8c7550362b01b3182b818eaf7d00f3f75657ed1d80a4f9f37afe6a | Python | 1,166 | 43 | import tensorflow as tf
from functools import reduce
class Loss(object):
def __init__(self, model, weight=1.):
self._model = model
self._weight = weight
def __call__(self, *args, **kwargs):
raise NotImplementedError
class CustomScore(Loss):
def __init__(self, model, weight, score_func):
super... |
5f10556ade5baedf1bf51afd8c061bd4404c5d152ac88f2075d7ce1de4c378bd | Python | 1,167 | 33 | import logging
import os
def setup_default_logging(output_dir=None, config=None, fileName=None, stdOutput=True):
logger = logging.getLogger()
#print 'Before', logger.handlers
for h in logger.handlers:
logger.removeHandler(h)
#print 'After', logger.handlers
logger.setLevel(logging.INFO)
... |
3f5399e797237f1b8cc9adf07466ca0e0633222e04b584abf6073dbb97a4aefe | Python | 1,169 | 40 | import unittest
import twixtools
import os
import hashlib
import tempfile
infile = 'example_data/gre.dat'
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.digest()
class test_wr... |
53bc3b9b0263c12fea4f9adbf964c0bd4454c4c93013a6ca8135dd0476683840 | Python | 1,171 | 42 | #!/usr/bin/env python
'''
Testcases for the neural network training
'''
import windseer.utils as utils
import windseer.nn as nn_custom
import windseer
import os
import unittest
windseer_path = os.path.dirname(windseer.__file__)
testdata_folder = os.path.join(windseer_path, 'test', 'testdata')
test_filename = os.path... |
2edca2ecbc9f90e17db82fe4198330be3763a264bda24799a7782069429b2a16 | Python | 1,172 | 41 | from setuptools import setup, find_packages
setup(
name="DREDDA",
version="0.1.0", # Adjust as per your versioning
author="Zhongxiao Li",
author_email="lzx325@outlook.com",
description="Drug Repositioning through Expression Data Domain Adaptation",
keywords="drug repositioning, domain adaptati... |
e4e66d94dba01c19503712fbe5347a1f313b186886357869628473c633016520 | Python | 1,172 | 40 | import pytest
from scripts.check_test_naming import main
@pytest.mark.parametrize(
"src, expected_out, expected_ret",
[
(
"def foo(): pass\n",
"t.py:1:0 found test function which does not start with 'test'\n",
1,
),
(
"class Foo:\n de... |
cf4992f98efb21ec2c6234498620ce26a873de6de3f3cae974b08b9b650ac3af | Python | 1,175 | 48 | """PyCaret 4.0 — lean, modern, agent-native open-source AutoML engine.
Canonical 4.0 API
-----------------
from pycaret.tasks import (
ClassificationExperiment,
RegressionExperiment,
ClusteringExperiment,
AnomalyExperiment,
TimeSeriesExperiment,
)
from pycaret impor... |
b7117f394915e14b6c0ee29a15be8424047e9383c6816ce892b401b9c0d318cb | Python | 1,176 | 35 | from Environment import *
from torch.utils.data import Dataset
class Transform(object):
def __init__(self, output_size):
self.output_size = output_size
def __call__(self, sample):
image = sample['image']
image = np.expand_dims(image, axis=0)
image = torch.from_numpy(image.astyp... |
de656f4ff03d6c34e453459f6eed5d2f6b2dcfa2ebf1a9de6a69519d2621eb2c | Python | 1,176 | 29 | from Environment_ui import *
from torch.utils.data import Dataset
class VISoR_dataset(Dataset):
def __init__(self, base_dir, list_dir, split):
self.split = split
self.sample_list = open(os.path.join(list_dir, self.split+'.txt')).readlines()
self.data_dir = base_dir
def __len__(self):
... |
e33e1a3ef9dff97d04decd26c7e48e87f3e6b721d0f469b53d41be9659dcfd33 | Python | 1,177 | 41 | import corner
import gvar as gv
import numpy as np
import matplotlib.pyplot as plt
import vegas
np.random.seed(123)
@vegas.rbatchintegrand
def g_pdf(p):
ans = 0
h = 1.
for p0 in [0.3, 0.6]:
ans += h * np.exp(-np.sum((p-p0)**2, axis=0)/2/.01)
h /= 2
return ans
g_param = gv.gvar([0.5, ... |
480a205e7fef395f4efb1b8f97c62a5f76cad26cd632ddeff4ed135b64a97ec8 | Python | 1,178 | 42 | import os
import pandas as pd
from darts.meters.average import AverageMeter
class MultitaskAccuracyMeter:
def __init__(self, tasks):
self.tasks = tasks
self.reset()
def reset(self):
self.meters = self.create_meters()
def create_meters(self):
""" Create an average meter ... |
0d9ac5efe686bb234c9c4d546462057df1182f48807193a6c7e4cbf64f41ab95 | Python | 1,179 | 35 | from Environment_ui import *
from torch.utils.data import Dataset
class Transform(object):
def __init__(self, output_size):
self.output_size = output_size
def __call__(self, sample):
image = sample['image']
image = np.expand_dims(image, axis=0)
image = torch.from_numpy(image.as... |
29c3666c84248d9e12ece4d453837d2eff509e03cf17abd20ed936b6df6df1d7 | Python | 1,179 | 22 | def years_education_convertion(subject_data):
"""
Map the education specified in the approved_data.tsv file to a number of years
based on the information provided by
https://www.brightworldguardianships.com/en/guardianship/british-education-system/
"""
if subject_data["phd_doc_years"] or subject... |
2b4a172adbc5a4698e7e8dd7758dbfac7b13a88b0e91baa8924ed9f490c820ea | Python | 1,179 | 25 | # Synthetic 3d brain slices were cut into 70 patches.
from Environment_ui import *
def single_cutting(files, index, save_path, cut_size, cut_index_x, cut_index_y, patch_weight_num, patch_hegiht_num):
image = sitk.ReadImage(files)
image_ROI = image[cut_index_x : cut_size*patch_weight_num + cut_index_x, cut_ind... |
37802a968c2b7102ea49e803c84b2d8371c28fb113911771732dd81a393104e9 | Python | 1,179 | 47 | # JN 2015-10-03 refactor
"""
cumulative spike time plot
"""
import logging
logger = logging.getLogger(__name__)
import numpy as np
TEXT_SIZE = 'small'
def spike_cumulative(plot, times, special, ylim=None, text=True,
lw=1, alpha=.7):
"""
draw cumulative spike line
"""
if ylim is... |
3e6f93d4e2a506ae249e860b2425df9143b2723205ac4eb1b5ea511eb6bc21a1 | Python | 1,179 | 43 | from datetime import datetime
import numpy as np
import pandas as pd
import pandas._testing as tm
def test_multiindex_period_datetime():
# GH4861, using datetime in period of multiindex raises exception
idx1 = pd.Index(["a", "a", "a", "b", "b"])
idx2 = pd.period_range("2012-01", periods=len(idx1), freq... |
6a5882f8537afe7c5b68b146330fde6d3a1c82da53c9f8fd8c79d4cb1aaa3169 | Python | 1,179 | 37 | from PyQt5.QtWidgets import QPushButton, QApplication, QStyle
from PyQt5.QtCore import pyqtSignal
class PushButton(QPushButton):
"""
A custom push button widget with signal emission on click.
"""
sgn = pyqtSignal(bool) # Signal emitted when the button is clicked
def __init__(self, label=""):
... |
0f13f2ab976cd67ce440385efe0de9c226b6aed61f4c4a7ee14a2c40cd6fd335 | Python | 1,180 | 46 | import time
import logging
import os
import numpy as np
import torch
import ismrmrd
import gadgetron
from modules.schemas.bicubic_sr import (
BicubicModel,
BicubicPretransformations,
BicubicPosttransformations,
)
def main(connection):
logging.basicConfig(level=logging.DEBUG)
... |
74f6f8f6af55f1a5d04c36b44d9b475ed4583c96eab955e9b2e65094f2ae2b2b | Python | 1,180 | 33 | """Test DataExtractor functionality."""
from lightning_pose.data.extractor import DataExtractor
class TestDataExtractor:
"""Test the DataExtractor class."""
def test_data_extractor_single_view(self, base_data_module):
num_frames = (
len(base_data_module.dataset)
* base_data_m... |
9cb150ec75597a5adc6a0cadc40afe62000c135572d1727d9974430b04e9172d | Python | 1,180 | 30 | # Copyright 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 agre... |
f558dfc3370ed4e076e49237085581906f85c3aa472437719583fd496ec3abaf | Python | 1,181 | 21 | from datetime import datetime
import sys
sys.path.append("..")
from app import db
class SourceDataset(db.Model):
__tablename__ = 'source_dataset'
id = db.Column(db.Integer, primary_key=True)
designation = db.Column(db.String(255), unique=True)
description = db.Column(db.String(255))
subject = db.r... |
66b048a0d3e3e99d4e984c2283dd79d360f73723b0f399b2038dba427b63ec63 | Python | 1,182 | 33 | # Copyright 2018-2024 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
5fe00d7cde6f90d4050cf28abcab1bdd7bc5ec9020849a3bc80ffb346732cd28 | Python | 1,183 | 46 | import pytest
@pytest.fixture(params=[True, False])
def check_dtype(request):
"""
Fixture returning `True` or `False`, determining whether to check
if the `dtype` is identical or not, when comparing two data structures,
e.g. `Series`, `SparseArray` or `DataFrame`.
"""
return request.param
@p... |
8bb66ca2f8932a817edb05087e5217c3e55d9f634e2da7b0e4a8c4824b3d1704 | Python | 1,183 | 31 | #! /usr/bin/env python
from treeshrink.filter_lib import filter_branch
from sys import argv
from treeshrink._vendor.dendropy import Tree
from os.path import splitext
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i','--input',required=True,help="input file")
parser.add_argument('-o','--out... |
5e7f0ad341912f14453f6296149f2e11e356f8c6d00f56892e3dec687b1a36be | Python | 1,184 | 36 | #! /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... |
9723d353ffa69fb0f6e63d9c56bfabcab952edf6c5db3118e9ab329276ce84b3 | Python | 1,184 | 38 | import collections
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestSeriesToDict:
@pytest.mark.parametrize(
"mapping", (dict, collections.defaultdict(list), collections.OrderedDict)
)
def test_to_dict(self, mapping, datetime_series):
# GH#16122
... |
9e2024f0ff97d59fc365bfbf8b7e1cba4d0019b93c8cc19841ec4e82fffa4ecc | Python | 1,185 | 42 | import numpy as np
import pandas as pd
def esw_star(esw: pd.DataFrame, pvals: pd.DataFrame, verbose: bool=False) -> pd.DataFrame:
"""Compute ESw_star
Computes rank-normalized ESw, i.e. ESw*
Parameters
----------
esw : DataFrame
ESw's.
pvals : DataFrame
Empirical p-val... |
b0b77cde94bc04df242130ae9cfa193f5faba4c5542c594ef1b22db5e2603da5 | Python | 1,185 | 39 | # NeuroXAI parameters
XAI_MODES = ["segmentation","classification"]
XAIs = ["VANILLA","GBP","IG","GIG","GCAM","GGCAM","SMOOTH"]
MODALITIES = ["FLAIR","T1","T1CE","T2"]
DIMENSIONS = ["2d","3d"]
TUMOR_LABEL = "all" # for GCAM visualization
# segmentation mode
#DIMENSION = "3d"
#MODALITY = "FLAIR"
#XAI_MODE = "segmentati... |
c077e646bbf2a34ec4e959749b8fad384c9e11a22d63d616f1f2ea6ece8413c6 | Python | 1,188 | 34 | # Copyright 2018-2024 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
6a127f8b494258a2e8952464983216ded1c479050fbab983f50a501bc65c8967 | Python | 1,189 | 35 | # 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... |
6bde5ced65a72dae4a6b8ebfcefee45f6b1f4a1997930dfea40b74841a4d26a1 | Python | 1,189 | 43 | """Test segmentation module."""
import numpy as np
import pytest
from gradec.segmentation import KMeansSegmentation, PCTSegmentation
@pytest.mark.parametrize(
"segmentation",
[
(PCTSegmentation(n_segments=10)),
(KMeansSegmentation(n_segments=10)),
],
ids=["PCT", "KMeans"],
)
def test... |
ab436abfbc755be41a613901f761bc2f1a4c346e126a8251c5594b95c7ef27ee | Python | 1,189 | 24 | from Environment import *
from Parameter import *
def split(image, index, save_root):
for ind in range(Preprocessing['z_num']):
for i in range(len(image)):
split_image = image[i][ind, :, :]
split_image = sitk.GetImageFromArray(split_image)
save_path = os.path.join(save_r... |
e0fe5bddcb36d091bb61a2598d1c30f4536b793a975b22e5cae1642e3e8ecc1b | Python | 1,189 | 31 | #if two consecutive regions have the same annotation, then they should be merged into a single region
def merge_bed(file_path):
merged_rows = []
with open(file_path, 'r') as file:
previous_row = None
for line in file:
row = line.strip().split('\t')
#print(row)
... |
2328b8d70c13048ff8a17ff825f9898dccb574390fde5e48aed003f85cc727b7 | Python | 1,190 | 32 | import torch
import torchmetrics
from numpy.random import seed as npseed
from random import seed as rseed
def setup(config):
torch.manual_seed(config.general.seed)
npseed(config.general.seed)
rseed(config.general.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = Fals... |
b7d6ba0bb7d6f768797f4b49ea3bc1459285f0ea3e10274aea3f6a59d2d75bcd | Python | 1,190 | 21 | """Prediction head classes, re-exported at the package level.
Unlike ``models/backbones/``, this package has no ``factory.py`` and no dispatch function:
each tracker hardcodes its own head class directly in ``__init__`` --
``RegressionTracker`` -> ``LinearRegressionHead`` (``regression_tracker.py``),
``HeatmapTracker`... |
d67b42fdcc8455ccb040afcebb0814733b1798127f599fc9bb7e8e772a58d274 | Python | 1,190 | 47 | import cv2
# from skvideo.io import VideoCapture
# import skvideo.io
import torch
import torch.utils.data as data
from torchvision.datasets.folder import DatasetFolder
from PIL import Image
import os
import os.path
import sys
class VideoFolder(DatasetFolder):
def __init__(self, root, transform=None, target_tran... |
e7c2bf4068d21876be684ae59ba5029230ceb608471b8ce7c2633be19eee3278 | Python | 1,191 | 53 | import logging
import sys
from PyQt5 import QtCore
class QtHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
def emit(self, record):
record = self.format(record)
if record:
XStream.stdout().write(f"{record}")
class XStream(QtCore.QObject):
... |
24f532658fd2cc28cf8dbd8c2cc6514e02c63177126fb942f09d378db8a0ba89 | Python | 1,192 | 26 | # 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... |
6fcd6edbd0640242e2d30bbf3e5e3db84edd3f8437d0edc9c372e00324e1d403 | Python | 1,192 | 39 | """PyCaret Control Plane SDK — drive a running ``pycaret-server`` over HTTP.
Distinguishes from the engine package (``pycaret``):
* ``pycaret`` — runs ML in-process; notebook / script workflow.
* ``pycaret-client`` — drives a remote Control Plane over HTTP; managed
runs with art... |
d4c838b38f154872ed1141977759c22a9e4c45b15aa10522d9dff3964da3bfd0 | Python | 1,193 | 28 | from torch import nn
from torch.autograd import Function
import torch.nn.functional as F
import torch
from torch.nn.modules.utils import _triple, _pair, _single
class SoftPool2d(torch.nn.Module):
def __init__(self, kernel_size=2, stride=None, force_inplace=False):
super(SoftPool2d, self).__init__()
... |
cc23d4662d548fc9140935ba0de7e81032c3627f3e1671b7336ef16707d1faf8 | Python | 1,194 | 41 | """Prints info about emoji fonts."""
from fontTools import ttLib
from pathlib import Path
import sys
NAME_ID_VERSION = 5
def name(font, name_id):
return ",".join(n.toUnicode() for n in font["name"].names if n.isUnicode() and n.nameID == name_id)
def main():
font_files = []
for sub_dir in [Path(__file... |
57158d675ba6c308d4a9fa8c8432eac9d7a6d09186432ac097300b3f2ffce4cd | Python | 1,196 | 39 | import numpy as np
from typing import Dict
from torch.utils.data import Dataset
class RandomData(Dataset):
""" Random dataset - Useful for quick iterating """
def __init__(self, x_dim: int, num_samples: int, tasks: Dict[str, int], seed: int=13):
np.random.seed(seed)
self.data = self.create_da... |
67dbb597ddb8b884cdf09b61e268ce9e40f98a8d482d1d58e9042c6b187e3449 | Python | 1,196 | 40 | import os
import pandas as pd
from darts.meters.average import AverageMeter
from darts.meters.accuracy import MultitaskAccuracyMeter
class EpochMeter:
""" Track epoch loss and accuracy """
def __init__(self, tasks, name='train'):
self.name = name
self.loss_meter = AverageMeter(name)
... |
f7a6df36f56d5087fe9013b02e10d89f87511efee47ccd097495e6537574d7ae | Python | 1,196 | 38 | import sys, os, re, collections
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts'))
import tree
for a in sys.argv:
if a=='-d':
gcgtree.VERBOSE = True
semcuegraph.VERBOSE = True
################################################################################
def c... |
233399b403df5d89226e5c860bca20cd472d233c09ba92aa8a7f03b165f2328c | Python | 1,197 | 28 | from distutils.core import setup
import os
lib_requires = ["torch", "tqdm", "scipy", "numpy"]
test_requires = lib_requires + ["pytest", "pytest-cov", "pandas"]
demos_requires = lib_requires + ["jupyter", "matplotlib"]
with open(os.path.join(os.path.dirname(__file__), 'README.md'), 'r') as readme:
long_descriptio... |
ea83b9782876d6d80a473143eb48e81f29fe64d26142b6e19a9144521b0bad6a | Python | 1,198 | 36 | import logging
from logging.handlers import RotatingFileHandler
from Bio import SeqIO
from bokeh.resources import INLINE
from flask import Flask, render_template
from utils.webplots import (make_coord_plots, make_num_sequences_per_year_plot,
make_vaccine_effectiveness_plot)
app = Flask(__... |
04b4efa88333a6fb0712838acca737636c34ae86980b928b014338e1977248d4 | Python | 1,199 | 41 | """Screenshots for quick guide statistics"""
import sys
from PyQt6 import QtCore
from PyQt6.QtWidgets import QApplication
from shapeout2.gui.main import ShapeOut2
from shapeout2.gui import compute
app = QApplication(sys.argv)
QtCore.QLocale.setDefault(QtCore.QLocale(QtCore.QLocale.Language.C))
mw = ShapeOut2()
mw.s... |
095b4be26e2dbca1e2cf9d36dbcf574ee3c187671e93938a811a42ae455afc06 | Python | 1,199 | 32 | import numpy as np
def max_array_dimensions(*args):
'''takes numpy arrays and returnes the maximal dimensions'''
for x in args:
if not isinstance(x, np.ndarray):
raise RuntimeError("wrong input type. Expect numpy.array, got %s" % str(type(x)))
#ignore empty arrays
args = [a for a i... |
7042cb5f41b2b7536fc82cd189515c91cb7aa7a497ec58c7e0df3104911df214 | Python | 1,200 | 59 | # 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... |
85e487bccf45b26d850cf1ff17c2b615d9fe3ed1b0e16ddfda60d5ad6ce4e4f6 | Python | 1,200 | 45 | # %%
# Imports
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('talk')
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
# %%
# Load Data
fn = 'data/raw/N2_Adult/091321_N2_Adult_Swim_0002_W5.txt'
with open(fn) as f:
first_line = f.readli... |
c6be5c5f3077ec180e45ae1fd73618ee0d5537925baf361cea04d72a7c693e5c | Python | 1,200 | 37 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.tests.copy_view.util import get_array
@pytest.mark.parametrize("box", [lambda x: x, pd.PeriodIndex])
def test_periodindex(box):
dt = pd.period_range("2019-12-31", periods=3, freq="D")
ser = pd.Series(dt)
idx = b... |
00c2a9c4d034afe62f1315643bb2b191f417f4e845f0eaf3d8b01167301ca817 | Python | 1,202 | 33 | import pandas as pd
import pandas._testing as tm
def test_relabel_no_duplicated_method():
# this is to test there is no duplicated method used in agg
df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4]})
result = df["A"].agg(foo="sum")
expected = df["A"].agg({"foo": "sum"})
tm.assert_series_e... |
ff84edc89d6a43da43e97f64e5ed6842eaca03b62cb308694010678b9f385364 | Python | 1,203 | 33 | import numpy as np
import pandas as pd
class TestEquals:
def test_equals(self, closed):
expected = pd.IntervalIndex.from_breaks(np.arange(5), closed=closed)
assert expected.equals(expected)
assert expected.equals(expected.copy())
assert not expected.equals(expected.astype(object)... |
299c5f799ed8ab2fbf05f8d28a839b16b48da54763c6438192b868e7508b006c | Python | 1,205 | 35 | import os
import glob
import cPickle
import copy
import argparse
import pandas as pd
from keras.models import load_model
from sklearn.preprocessing import MultiLabelBinarizer
def predict_DDI(output_dir, output_file, ddi_input_file, trained_weight, threshold):
with open('./data/multilabelbinarizer.pkl', 'rb') as... |
7a597d61e94f5865ace6c77de81cc625f7b35e5d45e13e6cbe3dc20867ff3c2b | Python | 1,205 | 48 | import sys
sys.path.append('.')
import time
from CommonSystem.Config import Config
from StimulationSystem.stimulationOperator import stimulationOperator
from StimulationSystem.StimulationProcess.VTbciStiController import StiController
from CommonSystem.MessageReceiver.ExchangeMessageManagement import ExchangeM... |
cc13f49ede00f337d0fd8889797ea6a3e4d4158145e131c63053147a3659d8da | Python | 1,206 | 48 | import sys
sys.path.append('.')
import time
from CommonSystem.Config import Config
from StimulationSystem.stimulationOperator import stimulationOperator
from StimulationSystem.StimulationProcess.VTbciStiController import StiController
from CommonSystem.MessageReceiver.ExchangeMessageManagement import ExchangeM... |
ccb3bb5f0cf0f27894a5dabf1d0f44442f1df631ae0a611b9edead4ef7cf576e | Python | 1,206 | 37 | #! /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... |
eaab5a8cc8df5838234a3f475fb5bf2a283da4c4b0b2cfe58937ef426e8a24f7 | Python | 1,206 | 23 | from Environment_ui import *
def split(image, index, save_root, param):
for ind in range(int(param['Network_input_z'])):
for i in range(len(image)):
split_image = image[i][ind, :, :]
split_image = sitk.GetImageFromArray(split_image)
save_path = os.path.join(save_root, 'w... |
81300c4cd3610f32bff5f4bfc530ce3549ca0094215edf3f8c2fae98762ff956 | Python | 1,207 | 43 | import numpy as np
def L2Norm0(x1):
return (x1.points**2).sum()
def L2NormDef(xDef, x1):
return -2*(xDef*x1).sum() + (xDef**2).sum()
def L2NormGradient(xDef,x1):
return 2*(xDef-x1)
# Measure norm of fv1
def measureNorm0(fv1, KparDist):
cr2 = fv1.weights[:, None]
return (cr2*KparDist.applyK(fv1.... |
050831801e2cb4b6e7950f469a9e64336a90652b1b1500afb1099d902e4746f2 | Python | 1,208 | 23 | from Surfaces.surfaces import *
from Common.kernelFunctions import *
from Surfaces.surfaceMatching import *
def main():
# fv1 = byufun.readbyu('/Volumes/project/bipolar/AmygdalaShape/1892b87d/1892b87d_l_amyg_reg.byu')
#fv0 = byufun.readbyu('/Volumes/project/bipolar/AmygdalaShape/12aaa4b6/12aaa4b6_l_amyg_reg... |
30e881e363857f5056016539dab9a744578b5dfd8ecc17ce2c3584d1c2b38657 | Python | 1,209 | 45 | from __future__ import annotations
import pickle
import pytest
import pandas as pd
import pandas._testing as tm
pa = pytest.importorskip("pyarrow")
from pandas.core.arrays.arrow.array import ArrowExtensionArray
def test_pickle_roundtrip(data):
# GH 42600
expected = pd.Series(data)
expected_sliced = e... |
62584574a475a3daf0a72a9dad102fa747cf58d810e2b04593d0f56f32f6d7b2 | Python | 1,209 | 41 | import shutil
from tests.conftest import COLONY_IMAGE_PATH, NO_COLONY_IMAGE_PATH
from aigarmic._img_utils import Deleter, is_similar, in_list
from os import path
import cv2 # pylint: disable=import-error
def test_delete_file(tmp_path):
temp_file = tmp_path / "test_image.jpg"
assert not path.exists(temp_file)... |
ad1c4f5b8a24307ca24e96b12e6b92c0747d2fb083d2853e116d7cfdd89d55a1 | Python | 1,209 | 49 | from defs import *
from values import *
import numpy as np
import math
#%%
def ncx1(cell,i, ep,memb_id,act,area):
Km_NCX1 = 0.125e-3
Km_Nao = 87.5 ##
Km_Cao = 1.3 ##
Km_Nai = 12.29 ##
Km_Cai = 3.59e-3 ##
k_sat = 0.27
gamma = 0.35
Phi_R = np.exp((gamma-1)*cell.ep[1]*EPref*F/RT... |
e92c95af91fce15dd01dd55ad7c334388d0975aa66ea81989577d112b61dc75f | Python | 1,209 | 45 | try:
from pandas._libs.tslibs import (
is_date_array_normalized,
normalize_i8_timestamps,
)
except ImportError:
from pandas._libs.tslibs.conversion import (
normalize_i8_timestamps,
is_date_array_normalized,
)
import pandas as pd
from .tslib import (
_sizes,
_tz... |
2f82559aa1824c7fc886812ad227bd66df984d134744313e4396b9cf42639811 | Python | 1,210 | 33 | from subprocess import check_output
# Hyper-parameters
table = "cnn_tuning" # _post_spec_fix"
target = "dspln_SOCIALWORK_12"
channels = [500]
# dropouts = [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95]
# dropouts = [0.6, 0.65, 0.7, 0.75, 0.8, 0.85]
dropouts = [0.85]
# dropouts = [0.4, 0.5, 0.6, 0.7, 0.8] # ... |
96d3579742a31192d70fc53ae43f898461f7434a63af6b9d2179decf34080699 | Python | 1,210 | 48 | # 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... |
a9e038aea8a5deea761e7653c779c55c2dc811ce3ad98e9c2bb5f8efb9ed651e | Python | 1,211 | 49 | import copy
import json
import subprocess
import torch
import logging
LOG = logging.getLogger(__name__)
def load_json(jsonfile):
with open(jsonfile, "r") as jf:
res = json.load(jf)
return res
def save_config(config, filepath):
with open(filepath, "w") as outfile:
json.dump(config, o... |
c4a5c87257e74735eacfd97f4db87dafcea21750d4bc0ee44141516bcebd8926 | Python | 1,211 | 37 | """PyCaret 4.0 exception hierarchy.
Every error an engine operation raises should be (a subclass of) `PyCaretError`
so that a UI / agent caller can catch the engine's errors without also catching
unrelated upstream library errors.
"""
from __future__ import annotations
class PyCaretError(Exception):
"""Root of ... |
defa34ba7dc5b9dfba21010bd789e59e94de8f027e2049776d0ef53a81b85071 | Python | 1,211 | 38 | from src.step_factory import Step, StepScaler, StepFactory
from src.test_config import step_config, supported_steps, get_step_config
from sklearn.preprocessing import StandardScaler
def test_step(step_config):
step = Step(step_config)
assert step.name == 'scaler'
assert step.kwargs == step_config['kwargs']... |
5e51117224291c392b7dcc623fca5dec9d72347b486a7c517b2c2b0909dbf29c | Python | 1,213 | 41 | __all__ = ["SummaryWriterProto", "TensorBoardSummaryWriter"]
from typing import Protocol
from torch.utils import tensorboard
from ...util.collections.dict import flatten_dict
class SummaryWriterProto(Protocol):
def write_model_params(self, model, epoch):
...
def write_summary(self, summary, epoch)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.