sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
4ec4ee353d99b58f39d6f2fef37f88cbe25eb26cf64d17d16d12cbcd9f05acc1
Python
377
12
def save_data(df, filename, data_id, dset): """ Helper function to save results from the analysis of a single subvolume. To be used to generate plots of mean +- std over subvolumes. """ import os root = os.path.split(filename)[0] if not os.path.exists(root): os.makedirs(root) ...
9621da163ec52194dd5188dd45d45ef09bba0d3cc6a9b10095ff89fb36ebbbdf
Python
377
15
import unittest class TestDreaming(unittest.TestCase): def test_imports(self): try: from dreamcoder.dreaming import backgroundHelmholtzEnumeration from dreamcoder.dreaming import helmholtzEnumeration except Exception: self.fail('Unable to import from dreaming m...
2becc2d64dcd279d421d32128c2223590576fb5c03c23e25dcafe4c76fdae4d4
Python
379
14
#!/usr/bin/env python #================================================================ # Copyright (C) 2022 Yufeng Liu (Braintell, Southeast University). All rights reserved. # # Filename : __init__.py # Author : Yufeng Liu # Date : 2022-04-18 # Description : # #======================...
9bc378fce5ac5aa201bc427f5432bab51fe0ff4490ec85f61d6d424fd6819573
Python
379
15
#!/usr/bin/env python import sys from ckg.init import installer_script from ckg.graphdb_builder.builder import builder as builder import ckg.debug as debug if __name__ == '__main__': if len(sys.argv) > 1: if sys.argv[1] == 'init': installer_script() elif sys.argv[1] == 'debug': ...
d6a3ee8b9d42fd71a0c9d95c6de2207635d6c599ffa4f28193b22359f0544f82
Python
379
9
""" Manual Contour Correspondence module. Interactive GUI for defining, saving, and exporting correspondence points between a registered brain volume and the Allen CCF template. Default target region is CA3 (Allen CCF id 463) - the dominant source of DG over-counting in this pipeline. Override via ``region_ids...
194744894f8975ea6b7b76d67c6c977067a82fbbf45101041076a5cd980addd8
Python
380
14
from __future__ import print_function import argparse from topaz.commands.normalize import add_arguments, main name = 'preprocess' help = 'downsample and normalize images in one step' if __name__ == '__main__': parser = add_arguments() parser.prog = 'Script for performing image downsampling and normalizatio...
a28ceb3a97feb9eac6b27293f09e37c20f5ec56963186f08828b14107a65913c
Python
381
17
import tensorflow.keras as tfkeras from .models_factory import ModelsFactory class TFKerasModelsFactory(ModelsFactory): @staticmethod def get_kwargs(): return { 'backend': tfkeras.backend, 'layers': tfkeras.layers, 'models': tfkeras.models, 'utils': tfk...
707fe508cee0288c3203093def43e0a597188ac2d661c03d196e40d81cc72bad
Python
382
13
from __future__ import division, print_function import numpy as np def compute_R2(x, y): return(((x - x.mean()) * (y - y.mean())).mean() / (x.std()*y.std()))**2 def effective_dof(X, lambda_val): """ Compute the effective degrees-of-freedom for data matrix X and lambda value. """ s = np.linalg.svd(X, co...
ffa4a964ecf86c416c5ffc1a2f337e72c96081977c543745fb384f3fd7a6a10f
Python
383
20
import os from sys import argv def countstep(filename): textfile=open(filename, "r") inputString=textfile.readlines() i = 0 for line in inputString: line = line.split() wanted='Step' if wanted in line: i+=1 print( i) if __name__ == "__main__": try: filename, outputfile = argv except...
15df8891dbdc2ec1d61ecd60018db7cf8a3b2659dd15802b8be53fa124cb0873
Python
384
12
"""Solving one dimensional heat conduction equation.""" try: from importlib.metadata import version, PackageNotFoundError # type: ignore except ImportError: # pragma: no cover from importlib_metadata import version, PackageNotFoundError # type: ignore try: __version__ = version(__name__) except Packag...
9a9306bd1b725c2358a27145380251db944058a215c454552c38b94f5531f632
Python
384
12
""" Set of specific utilities for combining PySeg with Subtomogram Averaging tools (PyTom) # Author: Antonio Martinez-Sanchez (Max Planck Institute for Biochemistry) # Date: 1.06.16 """ __author__ = 'Antonio Martinez-Sanchez' from .plist import TomoPeaks, SetTomoPeaks, Score, SingleTiltWedge, Particle, ParticleList,...
0d231a989259a4b9a2920eb54b1760b20e661f2b82f3393a3935af342b7b7e4e
Python
385
18
from .base import Canvas, ViewTransform from .camera import Camera, Viewpoint from .compositor import CompositorTree from .engines import EEVEE, Cycles from .recorder import FrameRecorder from .world import WorldTree __all__ = [ "Canvas", "Camera", "Viewpoint", "CompositorTree", "EEVEE", "Cycle...
3f0e297712eec1861bc1317877461877cd2bcdb3ab02c7cdcb0b3fdac98d0676
Python
385
14
import my_notebook from cog import BaseRunner, Input class Runner(BaseRunner): def setup(self) -> None: """Prepare the model so multiple predictions run efficiently (optional)""" def run(self, name: str = Input(description="name of person to greet")) -> str: """Run a single prediction""" ...
4dfd2dbb03c40409fde373446c5c8451515b8bd1ec02ce05c4f0eea9abab9b71
Python
385
12
import argparse from trainval import main parser = argparse.ArgumentParser(description='Re-run prototypical networks training in trainval mode') parser.add_argument('--model.model_path', type=str, default='results/best_model.pt', metavar='MODELPATH', help="location of pretrained model to retrain ...
4fe109ea71593fc51f87e143cf023d7acf893ab13c43753964dde6b41e85d77d
Python
385
10
from .conv2_5d_converter import Conv2_5dConverter from .conv3d_converter import Conv3dConverter from .acsconv_converter import ACSConverter from .soft_acsconv_converter import SoftACSConverter print("The ``converters`` are currently experimental. " "It may not support operations including (but not limited to) " "Funct...
cd69de2bc3873b6755c9d626c5b161867193648abb7ee2891c7464798e9dd7af
Python
385
15
from __future__ import annotations from ase.build import bulk from maggma.stores import MemoryStore from quacc.wflow_tools.db import results_to_db def test_results_to_db(): atoms = bulk("Cu") store = MemoryStore(collection_name="db3") results_to_db(store, {"atoms": atoms}) with store: assert...
25cec086c9a4086e0834934c74983b6fff43b6e19b36e969b0b8db778202f4fe
Python
386
12
import logging import os from cirrocumulus.envir import CIRRO_LOG_LEVEL logger = logging.getLogger("cirro") log_level = os.environ.get(CIRRO_LOG_LEVEL, "ERROR") logger.propagate = False logger.setLevel(log_level) logger.addHandler(logging.StreamHandler()) # Logs go to stderr logger.handlers[-1].setFormatter(logging....
71a7ddb67e6abe44f9ba49688912eda417c9732cce877b69ad4142f2d3cbcf9a
Python
387
15
from .config import InstanceRefinementConfig from .stage import ( InstanceRefinementResult, load_saved_instance_refinement, passthrough_instance_refinement, run_instance_refinement, ) __all__ = [ "InstanceRefinementConfig", "InstanceRefinementResult", "load_saved_instance_refinement", "...
98ccf10cf688a28ce48928e4dc4600e6d34b1f98b7340d47715d2431890b79e6
Python
387
20
# set QT_API environment variable import os import sys os.environ["QT_API"] = "pyqt5" import qtpy # qt libraries from qtpy.QtCore import * from qtpy.QtWidgets import * from qtpy.QtGui import * # app specific libraries import control.gui_tiscamera_DZK250 as gui if __name__ == "__main__": app = QApplication([]) ...
516e2f3c42327d92b8f4dc8de90494b722c81a13869b4d4ccf065a1aefc86625
Python
389
20
# Overwrite values of src/default_net_params.py net_params = {} # Overwrite values of src/default_sim_params.py sim_params = { 't_sim': 12500.0, 'master_seed': 2106 } # Parameters for the analysis ana_params = { 'plotRasterArea': { 'fraction': 0.05, 'low': 12000, 'high': 12500 ...
b4f14b884e03fe69187c4d6d3899759e4b200ccda0f8f152e6207bc4aa0a04e8
Python
390
12
""" DeepLabCut2.0 Toolbox (deeplabcut.org) copyright A. & M. Mathis Labs https://github.com/AlexEMG/DeepLabCut Please see AUTHORS for contributors. https://github.com/AlexEMG/DeepLabCut/blob/master/AUTHORS Licensed under GNU Lesser General Public License v3.0 """ #from deeplabcut.post_processing.filtering import * fr...
1d0aea2d1327a5ff7992e233b85a7cb80d129aecf81eed00e4d462fda5f42aa4
Python
391
16
from biotite.structure.io.mol import MOLFile from .reader import ReaderBase class SDFReader(ReaderBase): _extra_annotations = {} def read(self, file_path): return MOLFile.read(file_path) def get_structure(self): return self.file.get_structure() def _assemblies(self): # TODO ...
42787398e029ad50664f8baa23776b3a99682f0ec8f66e1a8cb4d69f2515083c
Python
391
18
""" Plot memory usage of a numeric computation using numpy and scipy """ import pylab as pl import numpy as np from memory_profiler import memory_usage from scipy import linalg X = np.random.randn(1000, 1000) mem = memory_usage((linalg.qr, (X,))) x = np.linspace(0, len(mem) * .1, len(mem)) p = pl.fill_between(x, mem...
56e91819fd1abb2068ef4839acf9a908748bdf334fa7ec49715775c0ea7c4fba
Python
391
19
#!/usr/bin/python3 class ModelConfigError(Exception): """Error to be raised in the case of wrong parameters of a model config.""" pass class DatasetError(Exception): """Error to be raised in the case of problems with the dataset.""" pass class LayerDefinitionError(Exception): """Error to be ...
9744014f818371b62bcbdc63421a0589391f47fb2d8c4ca4ae27222b45544746
Python
391
12
banner = r""" _____ _ __ __ / ____| | | \/ | | (___ | | ___ _| \ / | __ _ _ __ \___ \| |/ / | | | |\/| |/ _` | '_ \ ____) | <| |_| | | | | (_| | |_) | |_____/|_|\_\\__, |_| |_|\__,_| .__/ __/ | | | |___/ |_...
080abaf7746ee037cff1734625c4b1393d3ba43c4419cda6c72b39efb4644585
Python
392
13
from unittest import TestCase from codex.data.neuron_data_initializer import ( HEATMAP_GROUP_BY_ATTRIBUTES, NEURON_DATA_ATTRIBUTE_TYPES, NETWORK_GROUP_BY_ATTRIBUTES, ) class Test(TestCase): def test_group_by_attribute_types(self): for k in HEATMAP_GROUP_BY_ATTRIBUTES + NETWORK_GROUP_BY_ATTRIB...
923d9ddbfcb8dc22a5da4bfa3e0c8870c9d1008795df60863da5946df570a250
Python
392
20
# set QT_API environment variable import os import sys os.environ["QT_API"] = "pyqt5" import qtpy # qt libraries from qtpy.QtCore import * from qtpy.QtWidgets import * from qtpy.QtGui import * # app specific libraries import control.gui_camera_only_tiscamera as gui if __name__ == "__main__": app = QApplication...
93d4fbd01fc64ed954fffaef04a912110b840900ebdeeac7aa12d9cf6e2c7d2a
Python
392
17
import optuna def objective(trial): # Binh and Korn function. x = trial.suggest_float("x", 0, 5) y = trial.suggest_float("y", 0, 3) v0 = 4 * x**2 + 4 * y**2 v1 = (x - 5) ** 2 + (y - 5) ** 2 return v0, v1 study = optuna.create_study(directions=["minimize", "minimize"]) study.optimize(objecti...
2fda94f014934bb9656cee53681d96028956df55e9b9fb279c1ee3de6dcdd419
Python
393
19
from elasticai.creator.function_utils import FunctionDecorator def test_can_call_with_name_and_fn(): outer_name = "" def callback(name: str, fn): nonlocal outer_name outer_name = name return fn decorate = FunctionDecorator(callback) def fn(): return "x" fn = dec...
448757e588de58a6d9a36480905b471983409679ac94a165f57cc7df27858a5d
Python
394
18
#! /usr/bin/env python # -*- coding: utf-8 -*- from downward import suites import common_setup exp = common_setup.IssueExperiment( search_revisions=["issue422-base", "issue422-v1"], configs={"lmcut": ["--search", "astar(lmcut())"]}, suite=suites.suite_optimal_with_ipc11(), ) exp.add_absolute_report_...
c6c3fcf0a66eb4d8c07112d430d99d8f351528e5f4d35707d86e81b5504caff8
Python
394
17
#!/bin/env python3 """ Example script to test ithildin.filament """ import ithildin as ith import matplotlib.pyplot as plt filaments = ith.filament.read_filaments("example_filament.yaml") print(f"read {len(filaments)} filaments") for fil in filaments: print(fil.points) print(fil.payload.get('color')) pri...
2e4f2e6d5947212a3e9440bd11576a7b9ecda09daa2f7e1f3b22ca0b7e241a9e
Python
395
11
import torch import torch.nn as nn def run_network(inputs, fn, netchunk): """ Prepares inputs and applies network "fn". """ uvt_flat = torch.reshape(inputs, [-1, inputs.shape[-1]]) out_flat = torch.cat([fn(uvt_flat[i:i + netchunk]) for i in range(0, uvt_flat.shape[0], netchunk)], 0) out = out_f...
5d1b371691f20fa4686d64ec222cef7b3bd5be1c8b2214baaccdc80dddcb385c
Python
395
20
""" Utility file to select GraphNN model as selected by the user """ from nets.contrastpool_net import ContrastPoolNet def ContrastPool(net_params): return ContrastPoolNet(net_params) def gnn_model(MODEL_NAME, net_params): models = { "ContrastPool": ContrastPool } model = models[MOD...
cc37dc62592a3b5538cbb641507178552ab8d895a84acf1332347a2b629d2344
Python
395
13
from enum import Enum, auto class BondOrderType(Enum): '''Enum class for the different modes of determining bonds in the molecule.''' # Use the Wiberg index matrix to determine bonds WIBERG = auto() # Use the Localised Molecular Orbitals (LMO) to determine bonds LMO = auto() # Use the Natura...
e1b5eaa0c1ac8a34de16cf21f3aae1bdb8edcc2696ee5768cda9605ac1d70686
Python
395
12
""" Set of specific utilities for combining PySeg with Subtomogram Averaging tools (PyTom) # Author: Antonio Martinez-Sanchez (Max Planck Institute for Biochemistry) # Date: 1.06.16 """ __author__ = 'Antonio Martinez-Sanchez' from .plist import TomoPeaks, SetTomoPeaks, Score, SingleTiltWedge, Particle, ParticleList,...
1d9952a69381f15ae8ef77dfbcffb1ace46e32b8781a75643aa26ca45446f0f8
Python
396
12
from distutils.command.bdist import bdist import sys if 'egg' not in bdist.format_commands: try: bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file") except TypeError: # For backward compatibility with older distutils (stdlib) bdist.format_command['egg'] = ('bdist_egg', "Pyt...
26153057ae830758381efb7551009531d7c2bbe220015f055e6bc353da27c5de
Python
396
11
# SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: 2021 Taneli Hukkinen # Licensed to PSF under a Contributor Agreement. __all__ = ("loads", "load", "TOMLDecodeError") __version__ = "2.0.1" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT from ._parser import TOMLDecodeError, load, loads # Pre...
5cddd8cd8cf3629a7da88fe778304ee5f2a15de4076e791b73771a1769053be4
Python
396
16
import random from .shape import Shape class RandomShapeSelector: def __init__(self, shapes: list[Shape]): self.__shapes = shapes def __len__(self): return len(self.__shapes) def __getitem__(self, idx): if idx >= len(self.__shapes): raise StopIteration idx...
a28862e39dd6125e18ba9392dc2f00bc14c6f511b5e145145a23d285ea0913dc
Python
396
22
#! /usr/bin/env python # -*- coding: utf-8 -*- from downward import suites import common_setup CONFIGS = { 'astar_gapdb': [ '--search', 'astar(gapdb())'], } exp = common_setup.IssueExperiment( search_revisions=["issue482-base", "issue482-v1"], configs=CONFIGS, suite=suite...
ab8169dccdedc1a564813053f85c5713b2041f0fa5fa23a733630dab903854e4
Python
396
17
from __future__ import annotations import pytest @pytest.fixture(autouse=True) def ESPRESSO_PARALLEL_CMD(): from shutil import which import psutil from quacc import change_settings if which("mpirun") and psutil.cpu_count(logical=False) >= 2: change_settings({"ESPRESSO_PARALLEL_CMD": "mpiru...
bf3683f5eb5cab994c6dac7b44b489a5af5ff4db734b4e507bb42ba52995af92
Python
396
15
from cellmincer.models.denoising_model import DenoisingModel from cellmincer.models.fetch_model import \ init_model, \ get_temporal_order_from_config, \ get_window_padding_from_config, \ load_model_from_checkpoint __all__ = [ 'DenoisingModel', 'init_model', 'get_temporal_order_from_config'...
42e177ff244507b704439f0f4fe2f431d4c244bdd1b3ea8809c9b132226f2315
Python
397
14
from elasticai.creator.base_modules.relu import ReLU from .batchnorm2d import BatchNorm2d from .conv1d import Conv1d from .conv2d import Conv2d from .linear import Linear __all__ = ["ReLU", "BatchNorm2d", "Conv1d", "Conv2d", "Linear", "parametrized_modules"] parametrized_modules = [ "ParametrizedBatchNorm2d", ...
727cbef14daa1c4008717dc719c5ac63308881ffff3a4d2cf086bf3c5a8104fb
Python
397
27
import numpy as np import glob import re def load_elbow_flow(path): return np.load(f"{path}")[1:] def load_channel_flow( path, t_start=0, t_end=1200, t_every=1, ): return np.load(f"{path}")[t_start:t_end:t_every] def load_periodic_hill_flow(path): data = np.load(f"{path}") return data ...
9081d3d2ab4bb95d72fbebdbd41fdd7ee80a277de4505f459f902cbeb1e238e5
Python
397
16
# Libraries import os import sys code_path = os.path.split(os.path.split(os.getcwd())[0])[0] sys.path.append(code_path) from setting import * from download_data import * # Download data_path = get_data_path("tcga") database = "gdc" ## cancers = read_file(os.path.join(data_path, "cancers")) cancers = ["BRCA", ] # "KI...
cabd070ab7e4beb310f6d6aca1afe9d63cd99d50cc7ee734869c25d1c793114d
Python
397
11
import torch class AdaptableSiLU(torch.nn.SiLU): def __init__(self) -> None: super().__init__(inplace=False) self.scale = torch.nn.Parameter(torch.ones(1, requires_grad=True)) self.beta = torch.nn.Parameter(torch.zeros(1, requires_grad=True)) def forward(self, input: torch.Tensor) -> ...
3b70d4de24492d8c894d5ee903cf7030dc7f213dcfd38d72592623d1c642fea0
Python
398
22
import numpy as np import scipy.signal @profile def create_data(): ret = [] for n in range(70): ret.append(np.random.randn(1, 70, 71, 72)) return ret @profile def process_data(data): data = np.concatenate(data) detrended = scipy.signal.detrend(data, axis=0) return detrended if __na...
41e376f69fda079f9693da5f757e87e262c0c8469c49f6447f58f23977a5e8ed
Python
398
20
# set QT_API environment variable import os import sys os.environ["QT_API"] = "pyqt5" import qtpy # qt libraries from qtpy.QtCore import * from qtpy.QtWidgets import * from qtpy.QtGui import * # app specific libraries import control.gui_PDAF_demo as gui if __name__ == "__main__": app = QApplication([]) win...
7d8525344229be66880d355cd4b85224e928e2c7bf81778d64e2e8621c4aa368
Python
398
22
from datetime import date import os today = date.today() # delete old version file os.remove('+crabsort/version.m') out_file = open('+crabsort/version.m','a+') out_file.write('function v = version()') out_file.write('\n') temp = ("v = 'v" + today.strftime('%y.%m.%d') + "';") temp = temp.replace('.0','.') out_file....
a3f32b33aba1c84fd960d4045618df46fa7a7b59aa08adf2be9ab0c68c14d7c9
Python
398
17
from cocotb.triggers import RisingEdge async def _write_current_d_in(dut) -> None: dut.src_valid.value = 1 await RisingEdge(dut.clk) dut.src_valid.value = 0 async def _reset_dut(dut) -> None: dut.src_valid.value = 0 dut.dst_ready.value = 0 dut.rst.value = 1 await RisingEdge(dut.clk) ...
c15fab9836772a287e6209ecd320f82fbf2b28446d7df6059a69759088d5f3f3
Python
398
16
""" see kernel.m """ import numpy as np from numba import jit @jit # @partial(jit, static_argnums=(0,)) def exponential(duration, tau): """ kernel = exponential(duration, tau) normalized exponential kernel: EXP(-t/tau), width TAU in points.""" if duration>=1: kernel = np.exp(-(np.arange(0, dur...
7b3e0546f37929a4a8b09789d96cd4c8a743760df91c3cbf4922cf5ca09db793
Python
402
16
from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: # TypedDict was introduced in Python 3.8. # # TODO: Remove the else block and TYPE_CHECKING check when dropping support # for Python 3.7. from typing import TypedDict class ResultDict(TypedDict): encoding: Optional[str] ...
b41da0e55fb38e840e27fe9dd6966f8dbf32e2abba956b5230fc0fbe7112bf66
Python
402
7
################################################################################ # Copyright (c) 2021-2023, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # Written by D. Jones <djones@llnl.gov> and UCSD collaborators in listed in CONTRIB.md # # All rights reserved....
4e8cab58507f78765fc1639dce458a520b07e8fbec62b5676588c3600a09d7da
Python
403
16
from . import actflowcomp from .actflowcomp import * from . import model_compare from . import connectivity_estimation from . import dependencies #from . import infotransfermapping #from . import pipelines #from . import preprocessing from . import simulations from . import tools #from . import latent_connectivity __...
81a779b00aa57b6482991374e2f3e648b9f363c816ce0c0edc826330bcb9a231
Python
403
10
from .config import get_default_config, update_config from .collators import create_collator from .transforms import create_transform from .datasets import create_dataset, create_dataloader from .models import apply_data_parallel_wrapper, create_model from .losses import create_loss from .optim import create_optimizer ...
20f174f646a5badbec647c4f5a6a5489e6e6bc336a587467c2e4e9ddbfe125d1
Python
404
19
#!/bin/env python3 ''' Draw Feynman diagrams for the quasi-particles in the 2D patterns of cardiac arrhythmia ''' import sys import yaml from pdlfeynman.diagram import layout_diagram diagramfile = sys.argv[1] posfile = sys.argv[-1] with open(diagramfile) as f: diagram = yaml.safe_load(f) pos = layout_diagram(dia...
30310b1fc02f82c3c1ef2d629eab8b4b11cf0f5158b35c3116a46459f1a7f35d
Python
404
19
from . import analysis as analysis from . import build as build from . import cfg as cfg from . import components as components from . import interactions as interactions from . import sequence as sequence from . import sim as sim from . import utilities as utilities __all__ = [ "analysis", "build", "cfg",...
4ef4859e0c59e53798e1de62184cc730a8228e9b8d4aa055ef0110caf3d58c51
Python
404
10
import molecularnodes as mn def test_coll(): assert mn.blender.coll.mn().name == "Molecular Nodes" assert mn.blender.coll.mn().name == "Molecular Nodes" assert mn.blender.coll.data().name == ".MN_data" assert mn.blender.coll.cellpack().name == "cellpack_" assert mn.blender.coll.frames().name == "....
6a38a54cd4fa8e3916a53ca0b69fb865c5803e340d328730911d43f83b57fa00
Python
404
20
# -*- coding: utf-8 -*- ''' Python module to read common electrophysiology file formats. ''' from . import utils from . import haussio from . import movies from . import scalebars from . import pipeline2p from . import spectral from . import cnmf try: from . import thor2tiff except ImportError: print("Could no...
cfed37a08e7330854da9b986dfa8056c8a01ebf8478c309f0ce7fb4e6370435a
Python
404
14
import unittest class TestOrderExample(unittest.TestCase): def test_z_third(self): print("This runs third despite being defined first") def test_a_first(self): print("This runs first despite being defined second") def test_b_second(self): print("This runs second de...
385fbe5e31decd59c44f5a7e3b26e3c72c9363d41a633f2f207e1cba0bc10a95
Python
405
17
from neuroquery_image_search import _datasets def test_fetch_data(request_mocker): data = _datasets.fetch_data() assert data.keys() == { "masker", "atlas_maps", "atlas_inv_covar", "studies_loadings", "terms_loadings", "studies_info", "document_frequenci...
39bdb5c576bbdddeb0820e348b46a052a845bbc8667f630c672230fc89454776
Python
405
20
# set QT_API environment variable import os import sys os.environ["QT_API"] = "pyqt5" import qtpy # qt libraries from qtpy.QtCore import * from qtpy.QtWidgets import * from qtpy.QtGui import * # app specific libraries import control.gui_PDAF_calibration as gui if __name__ == "__main__": app = QApplication([]) ...
01447932062b1ab183ab8e609795e22dc972f19fa80cc0d2a2855eb88c6fc861
Python
406
11
import sys import os from PySide6 import QtCore, QtWidgets if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'): QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'): QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, Tru...
5f26668103e8c5ccc0eec25a2964c34b53b7072cb36df79b43aae7edaab5cd8a
Python
406
11
""" DeepLabCut2.0 Toolbox (deeplabcut.org) copyright A. & M. Mathis Labs https://github.com/AlexEMG/DeepLabCut Please see AUTHORS for contributors. https://github.com/AlexEMG/DeepLabCut/blob/master/AUTHORS Licensed under GNU Lesser General Public License v3.0 """ from deeplabcut.pose_estimation_tensorflow.dataset.fact...
db76c9d41cfc16ef341e68e0a29af82a201392bee5beb2ec9fe2de954f877b33
Python
406
18
import torch import torch.nn as nn from pathlib import Path from abc import ABCMeta, abstractmethod class Predictor(metaclass=ABCMeta): @abstractmethod def __init__(self, model: nn.Module, model_pth: str | Path, device: torch.device): ... ...
f1c4ee460272511e9f32aa6a2908babe7b5afe43c852e85d1761733d2306e7bb
Python
406
15
class Memory: def __init__(self): self.episodes = [] def __len__(self): return len(self.episodes) def __getitem__(self, idx): episode = self.episodes[idx] return episode["observations"], episode["actions"] def add_episode(self, observations, actions): self.epis...
f3f0c61871065024b228aea7c04db67e8e15d2fce0a935f81ae1c8adb547845a
Python
406
8
### Submit script "XY.py" to HPC (Torque) cluster import subprocess subprocess.run(['echo "$PWD/create_dataframes_from_matrices_upper.py" | qsub -l nodes=1:ppn=1,walltime=01:00:00,mem=8gb -N create_dataframes_upper'], shell = True) subprocess.run(['echo "$PWD/create_dataframes_from_matrices_full.py" | qsub -l no...
38e604c75b7ef4d8cd7ce7a08ec6caf3b1342c38ed7db91d729607fb7b6cdfe4
Python
407
16
# version:1.0.1808.9101 import control.gxipy as gx def main(): # create a device manager device_manager = gx.DeviceManager() dev_num, dev_info_list = device_manager.update_device_list() if dev_num is 0: print("Number of enumerated devices is 0") return for i in range...
7d25065f492d4d421917461fd0464ef39868b50ccf1d7c541749381703226503
Python
407
21
#!/usr/bin/env python """Tests for `m6a_calling` package.""" import unittest from m6a_calling import m6a_calling class TestM6a_calling(unittest.TestCase): """Tests for `m6a_calling` package.""" def setUp(self): """Set up test fixtures, if any.""" def tearDown(self): """Tear down test...
dca1f2d41a012a4c74eefe1ef2e9bae3e849656cd2ff83501838e6ed6a0bf70c
Python
407
12
"""Look at alpha values of model's PReLUs""" from src.model import ModelSpikeSorter from torch.nn import PReLU import torch model = ModelSpikeSorter.load("/data/MEAprojects/DLSpikeSorter/models/v0_4/2954/rms_conv") prelus = [module for module in model.modules() if isinstance(module, PReLU)] for i, prelu in enumerate...
5543c5e5e3b24e8147677ddda0c4a5c333621028f9248c074116d5061047813b
Python
408
16
"""Interfaces init file.""" from .dimensions import Dimensions from .acquisition_data import AcquisitionData from .rx_data import RxData from .unrolled_sequence import UnrolledSequence from .acquisition_parameter import AcquisitionParameter from .enums import DDCMethod __all__ = [ "Dimensions", "AcquisitionDat...
00167e2f2c3e8a02b0045a0b177418b4599fbadc192e201d59ca5131b71a7065
Python
411
20
import functools # from jaraco.functools 3.5 def pass_none(func): """ Wrap func so it's not called if its first param is None >>> print_text = pass_none(print) >>> print_text('text') text >>> print_text(None) """ @functools.wraps(func) def wrapper(param, *args, **kwargs): ...
8c55d9c4fc8405b206b509209b8e371b71b51de1693105baa6286d947f26dc42
Python
411
16
""" ASGI config for PeerJCode project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefaul...
fe76ab1331ffd154e8f294d7a6d303e9045bd4c4c2a2fb51a584ec70535bda5b
Python
411
16
""" WSGI config for PeerJCode project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefaul...
0c064e13271b67575e9da7e632588314d097c5995436e14b7b77758fb6edb139
Python
412
16
""" Set of specific utilities for processing biological membranes # Author: Antonio Martinez-Sanchez (Max Planck Institute for Biochemistry) # Date: 12.06.15 """ __author__ = 'Antonio Martinez-Sanchez' from .connectors import CloudMbConn from .connectors import ConnSubGraph from .filament import ConnDom from .filame...
3b4b3b0f1b8e9eadf04f48327df3f93ab0f10bab17887a51567c3b360d1fefc0
Python
412
20
from .functional import ( get_stats, fbeta_score, f1_score, iou_score, accuracy, precision, recall, sensitivity, specificity, balanced_accuracy, positive_predictive_value, negative_predictive_value, false_negative_rate, false_positive_rate, false_discovery_rat...
c61e221093d3e97a90917d42bafb73aafd0807010b1d3c790de3e168bf58ec83
Python
413
14
import torch AVAILABLE_OPTIMIZERS = { "Adam": torch.optim.Adam, "SGD": torch.optim.SGD, } def get_optimizer(config:dict): lr = config["lr"] optimizer = AVAILABLE_OPTIMIZERS[config["optimizer"]] if config["optimizer_params"] is not None: return lambda params: optimizer(params, lr=lr, **...
078154fe364faf9c47c2b53e9ec8805be3b3d5e9d233d05378a6ca58516bcca6
Python
414
15
import numpy as np def get_matrix(n, m, pd=False, symm=False, rng=None): """Generates a random n-by-m matrix""" if rng is None: rng = np.random.RandomState(1) A = rng.normal(size=(n, m)) if symm: assert n == m A = 0.5 * (A + A.T) if pd: assert n == m lams, ve...
1957333026e5b28f3a3852c90a997384ac6b98c684e7e3c4f2448d4e88355bcb
Python
415
11
from .amigos import AMIGOSDataset from .bci2022 import BCI2022Dataset from .deap import DEAPDataset from .dreamer import DREAMERDataset from .mahnob import MAHNOBDataset from .seed import SEEDDataset from .seed_feature import SEEDFeatureDataset from .seed_iv import SEEDIVDataset from .seed_iv_feature import SEEDIVFeatu...
dcb09920d0e3c2036e03d2d025015bdc3559404bb57e71199bf93facfb71dd1b
Python
415
20
import sys argv = sys.argv tag_ids = argv[1].split(',') tag_files = argv[2].split(',') id_out = argv[3] id_len = len(tag_ids) file_len = len(tag_files) if id_len != file_len: raise ValueError("Arrays must have the same size") i=0 with open('%s_samples.txt' % id_out,'w') as f: while i < id_len: id = ...
33d89f55a5758264fb96a5212b4562ed8db15883bf227961dbf0ac42e74f8337
Python
417
15
# This file is to check that future division works. from test_binary_ops import arg_pairs import autograd.numpy as np from autograd.test_util import check_grads def test_div(): fun = lambda x, y: x / y make_gap_from_zero = lambda x: np.sqrt(x**2 + 0.5) for arg1, arg2 in arg_pairs(): arg1 = make_...
3b510c60c423803e53ac884c1e283009c18e126d681b9c5d4e5ac335a94dd382
Python
417
12
import cv2 from synergy3DMM import SynergyNet if __name__ == '__main__': model = SynergyNet() I=cv2.imread('img/sample_2.jpg', -1) # get landmark [[y, x, z], 68 (points)], mesh [[y, x, z], 53215 (points)], and face pose (Euler angles [yaw, pitch, roll] and translation [y, x, z]) lmk3d, mesh, pose ...
272a21d7de53bd0ec4e932fa5268c1b426b59c42b3f44d062211621d9910b5a9
Python
418
18
"""FID Net Wrapper.""" import warnings try: from fidnet._version import __version__ except ImportError: __version__ = "not-installed" warnings.warn( "You are running a non-installed version of fidnet." "If you are running this from a git repo, please run" "`pip install -e .` to ins...
8b205190a4747fe344430e9bc2922e07cb5aed19c1784d4a5c657e9d14a3c8df
Python
418
11
from .dataprocessor import AutosomeDataProcessor from .first_layers_block import AutosomeFirstLayersBlock from .coreblock import AutosomeCoreBlock from .final_layers_block import AutosomeFinalLayersBlock from .trainer import AutosomeTrainer __all__ = ("AutosomeDataProcessor", "AutosomeFirstLayersBlock", ...
941e2461fb541ca7e3c52d2ee23751a9805b2397ce887126c1b61d61f7d3a36d
Python
418
12
from cog import BaseRunner, Input class Runner(BaseRunner): def run( self, text: str = Input(description="A string input"), count: int = Input(description="An integer", default=5), temperature: float = Input(description="A float", default=0.7), flag: bool = Input(descriptio...
97cf152c59422950fc56614ea69d33c153f1916d2a304c30863e5fea2a4adfc4
Python
418
11
from downward.reports import PlanningReport class CSVReport(PlanningReport): def get_text(self): sep = " " lines = [sep.join(self.attributes)] for runs in self.problem_runs.values(): for run in runs: lines.append(sep.join([str(run.get(attribute, "nan")) ...
50a77a5eb9b3d0bf18d4e05434297680b63cd41af3bd5a3ff73479867d97694e
Python
419
16
"""Opaque marker for Cog input and output annotations. Use inside ``typing.Annotated[T, Opaque]`` to tell Cog to treat ``T`` as an opaque JSON object. Cog emits an object schema and passes values through without custom encoding or decoding. """ class _OpaqueMarker: """Marker singleton exposed publicly as ``cog.O...
549c4daeed9f2e78831914f5b126eee22b46c4f2c9b693fe435ddf3d17e24363
Python
419
14
from utils.logger import setup_logging, get_logger, TensorboardWriter from pathlib import Path from utils import set_random_seed SEED = 1126 set_random_seed(SEED) if __name__ == '__main__': setup_logging(Path('./Logs/Tests')) tensorboard_logger = get_logger('Tensorboard') writer = TensorboardWriter(Path('...
0a705073542820ab4153493ae77f4c57a7171f28684445c01fe29e793c09742d
Python
420
17
# Types from typing import Union, Optional import numpy as np import torch ArrayOrTensor = Union[np.ndarray, torch.Tensor] OptionalArrayOrTensor = Optional[ArrayOrTensor] # models from .pairwise import Pairwise from .pairwise import Pairwise as Ising from .independent import Independent from .rp import RP from .rp i...
3541020d311281475415dc29e44be15f69861084cf550ed1b395f5c00fd32e65
Python
420
14
from __future__ import division, print_function import numpy as np class gaussian: def __init__(self, mu, var): self.mu = mu self.var = var self.sigma = np.sqrt(var) def loglik(self, weights): exponent = -0.5 * (weights - self.mu) ** 2 / self.var log_coeff = ...
8ae0961670ab4aba285ab3cbab30d5fbe55ee048d270b440f9bc9aea848c9583
Python
420
17
import bpy import molecularnodes as mn def test_template(): mn.assets.template.install() bpy.ops.wm.read_homefile(app_template="Molecular Nodes") assert not bpy.data.objects.get("Cube") mn.assets.template.uninstall() try: bpy.ops.wm.read_homefile(app_template="Molecular Nodes") as...
bcd7993c64f70d2373e00075a2c2fe6dfb47d1fc17b690e4205be11e6a993dbe
Python
420
19
import torch def CORAL(source, target): d = source.data.shape[1] # source covariance xm = torch.mean(source, 0, keepdim=True) - source xc = xm.t() @ xm # target covariance xmt = torch.mean(target, 0, keepdim=True) - target xct = xmt.t() @ xmt # frobenius norm between source and targ...
2a3d7ab95bd246c549856e96d651d54bc901a508d4a2d9563dc5ed4a9bc4b8de
Python
421
7
from .builder.aln import ALNNetwork, ALNNode from .builder.fitzhugh_nagumo import FitzHughNagumoNetwork, FitzHughNagumoNode from .builder.hopf import HopfNetwork, HopfNode from .builder.thalamus import ThalamicNode from .builder.wilson_cowan import WilsonCowanNetwork, WilsonCowanNode from .builder.wong_wang import Redu...
365ecd5168e98e9cbc8cc59897a838e421ef716e9a77ec2a9bf292620b834d39
Python
421
9
from ..utils import IKFastInfo from ..ikfast import * #FRANKA_URDF = "models/franka_description/robots/panda_arm.urdf" #FRANKA_URDF = "models/franka_description/robots/hand.urdf" FRANKA_URDF = "models/franka_description/robots/panda_arm_hand.urdf" PANDA_INFO = IKFastInfo(module_name='franka_panda.ikfast_panda_arm', b...
596df61d8fd888803dc37643dcf1293177e6474bb50e5c3bf45c5e060810b6ea
Python
421
15
#!/bin/env python outfile = '../SAMPL7-user-map-HG.csv' # Read user map from submission server file = open('/Users/dmobley/SAMPL/submissions/downloads/submission_table.txt', 'r') text = file.readlines() file.close() # Write output file, removing e-mail addresses file = open(outfile, 'w') for line in text: tmp = ...
8e20c656a65a4cba6069a89701599a9ef030a07b927bf2bc99621746f675fe85
Python
422
28
# .. an example with a for loop .. import time def test_1(): a = {} for i in range(10000): a[i] = i + 1 return @profile def test_2(): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7) del b for i in range(2): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7) del b ...
086112e7f4128f8b980b3d9c0bcdf5089d7b93cc032e9948e814913a7474963e
Python
424
17
#!/usr/bin/env python # -*- encoding: utf-8 -*- import json import bindings as bi def main(): bi.init("Docs Json", "../../../h2o-docs", clear_dir=False) bi.vprint("Writing schemas.json...") bi.write_to_file("schemas.json", json.dumps(bi.schemas(raw=True))) bi.vprint("Writing routes.json...") bi.w...
876819a81bf4bd573d63839da401a29ba2c0fb986de9c1a637f7bf9ebc16add5
Python
425
9
"""Registration-pipeline output viewers and writers. This package owns code that knows how to walk a completed registration output directory (01_affine/ - legacy runs: 01_axis_alignment/ -, 02_nonlinear/, 03_laplacian_refinement/, registered_points/, etc.) and surface its contents to napari or other consumers. Th...
b10166b87b22f2dcd75462894b5ab69cb4ea5e8a3a05359e246ff64f73dbcb16
Python
426
22
# external import pytest # project import textdistance ALG = textdistance.Bag @pytest.mark.parametrize('left, right, expected', [ ('qwe', 'qwe', 0), ('qwe', 'erty', 3), ('qwe', 'ewq', 0), ('qwe', 'rtys', 4), ]) def test_distance(left, right, expected): actual = ALG(external=False)(left, right) ...
f915f564f9132ac9c1b0b05c84ad33c69153d8752e4e8150a29a2f56e99fb79d
Python
426
16
import torch.nn as nn # Model should include nn.LogSoftmax layer def nll_loss(*args, **kwargs): return nn.NLLLoss(*args, **kwargs) def cross_entropy(*args, **kwargs): return nn.CrossEntropyLoss(*args, **kwargs) # Model should include nn.Sigmoid layer def bce_loss(*args, **kwargs): return nn.BCELoss(*arg...
09514217b8ed60f12f5df0c1f1b5257b1c3c0195ad31d79d3d5f17f3e41b4e9f
Python
427
9
from .src.absolute import absolute as absolute from .src.hardtanh import hardtanh as hardtanh from .src.heaviside import heaviside as heaviside from .src.precomputed import precomputed_lut as precomputed_lut from .src.precomputed import precomputed_scalar as precomputed_scalar from .src.prelu import prelu as prelu from...