sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
46bf55c5b6ee18c6e14745b44e26fca3269c00d4e431dd3b7ac346f234d58890 | Python | 2,407 | 102 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def dump_version_file (
author : str,
email : str,
version : str
):
'''
Dump the __version__.py file as python script
Parameters
----------
author: str
List of author/maintainer names comma separated
... |
f5b386d3a30c083fe1ef13fb0e1d50942e5616da3064ee604b5413b59833ac1d | Python | 2,407 | 84 | """
Code here relates to the creation of arbitrary waveforms to be used as
voltage-clamp or current-clamp stimulus waveforms.
"""
import numpy as np
import matplotlib.pyplot as plt
ATF_HEADER="""
ATF 1.0
8 2
"AcquisitionMode=Episodic Stimulation"
"Comment="
"YTop=2000"
"YBottom=-2000"
"SyncTimeUnits=20"
"SweepStartTi... |
2190d34f6a754cd2447601f8a6b4cac59b4fd4240219d991f73c74e146397e2a | Python | 2,408 | 58 | import numpy as np
import torch
# ----------------------------------------------------------------------------
# Symbolic assert.
try:
symbolic_assert = torch._assert # 1.8.0a0 # pylint: disable=protected-access
except AttributeError:
symbolic_assert = torch.Assert # 1.7.0
# -------------------------------... |
3deb0b7b70d98335dd4a483dcad1b208e65ef21b1e3861b8a177b9f56269a65a | Python | 2,408 | 71 | from typing import Any, Dict, Optional
import requests
from codecarbon.external.logger import logger
def postprocess_gcp_cloud_metadata(cloud_metadata: Dict[str, Any]) -> Dict[str, Any]:
# Attributes contains custom metadata and also contains Kubernetes config,
# startup script and secrets, filter it out
... |
5b4b35c26970c96c3160ae453acaa0ed4c78c95621fffa77b68c64c75aacaf33 | Python | 2,408 | 69 | # Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
from typing import Tuple, Union
import numpy as np
from PIL import ImageFilter
from PIL.Image import Image
from torch import Tensor
from lightly.transforms.torchvision_v2_compatibility import functional as F
class GaussianBlur:
"""Imple... |
610bf0f84ede032daa3a1d622ec2d352a0b9e6c3417f0f03b746a7b5e05360ca | Python | 2,408 | 95 | import time
from constants import get_args
from binary_motif_model import (
MotifModel,
load_model,
save_model,
MotifModelDataset,
evaluate_model,
)
from map_protein_name import (
get_map_protein,
get_rbns_name_psam_idx_map,
)
from utils import write_permute_res
def main(
bs,
p... |
91cd6259628d64abf8430b910aac24d545c1c01619e707709a6c33660100d475 | Python | 2,408 | 54 | """Faster RCNN Demo script."""
import os
import argparse
import mxnet as mx
import gluoncv as gcv
gcv.utils.check_version('0.6.0')
from gluoncv.data.transforms import presets
from matplotlib import pyplot as plt
def parse_args():
parser = argparse.ArgumentParser(description='Test with Faster RCNN networks.')
p... |
a1c2ac3251cb841960729d89815029fdffff3195c8b1556a3a70948ccca174c1 | Python | 2,408 | 87 | from __future__ import print_function, division
import subprocess
import os
import os.path
import sys
import time
import random
import numpy as np
from matplotlib import pyplot as plt
import ctypes
import array
import copy
import cppyy
import cppyy.ll
cwd = os.path.dirname(os.path.abspath(__file__))
good = cppyy.cpp... |
db1112f663c2b106052ab51b5b5f9e86e06738615e820ce2380db7660ebaf8b4 | Python | 2,408 | 80 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Totals(_BaseTraceHierarchyType):
_parent_path_str = "waterfall"
_path_str... |
24b0a311b0f2b5aab7397ccaf91f1bd5224f7b9ba7f061f736648e0f593a4b82 | Python | 2,410 | 94 | import json
import copy
import random
import itertools
from nltk.tokenize import sent_tokenize
from tqdm import tqdm
random.seed(0)
def read_json(d):
with open(d, 'r', encoding='utf-8') as f:
return json.load(f)
def write_json(data, dsave):
outf = open(dsave, 'w', encoding='utf-8')
json.dump(data, outf, e... |
2b3a4c14b2f32f9f7494ca68896f762b3e5d57624c6f981e0d437e0c5be1f895 | Python | 2,410 | 72 | #!/home/ubuntu/miniconda2/bin/python
from __future__ import print_function
import glob, os, gc, sys
import os.path
import csv
import numpy as np
np.random.seed(1337) # for reproducibility
from time import time
from subprocess import (call, Popen, PIPE)
from itertools import product
from IPython.display import display
... |
6e54e6f3cbd5a092273cdba62857773c2b626f26be09934786b517b19410c828 | Python | 2,410 | 64 | import argparse
import json
import os
def convert_json_to_yolo(input_dir, save_dir, class_names_file):
with open(class_names_file, 'r') as f:
class_names = [line.strip() for line in f.readlines()]
class_to_index = {class_name: i for i, class_name in enumerate(class_names)}
for filename in os.li... |
bea2f27212cd425ef94ad59a967c0f629ba2dc04ce0c035af4b63895c16e6792 | Python | 2,410 | 67 | from uuid import uuid4
from celery.canvas import Signature, StampingVisitor
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
class MyStampingVisitor(StampingVisitor):
def on_signature(self, sig: Signature, **headers) -> dict:
logger.critical(f"Visitor: Sig '{sig}' is stamp... |
db3f38937c2b32d641e01a2e3326689fecb014b50e06f8df53efa960d36714c4 | Python | 2,411 | 68 | from __future__ import annotations
import math
import time
from collections.abc import Generator
from itertools import islice
from typing import TYPE_CHECKING, TypeVar
import bream4.legacy.device_interfaces.devices.base_device as legacy_base
if TYPE_CHECKING:
from bream4.device_interfaces.devices.minion import M... |
e8893d648b4e93ddfe06202f65bf175f4fd30582315d59687e9b96841e99a5bc | Python | 2,411 | 76 | # Copyright 2024 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
11d85574dc91be033171619a40dccf27ab143935dcb0939912dfad56afa622eb | Python | 2,412 | 158 | EXPECTED_OUTPUT = [
"0",
"0",
"-0.285687",
"-0.42064",
"-0.248964",
"0.128788",
"0.416349",
"1.51198",
"3.19612",
"3.37101",
"2.99447",
"3.26576",
"3.76964",
"4.08053",
"4.04641",
"3.83413",
"2.68095",
"1.20282",
"0.463271",
"0.671833",
... |
7b7dc0dd7786f610d5ebde7b6ecb45c337bf4f32c54199fdc1207ab0ceb88e39 | Python | 2,412 | 77 | import torch
import torch_geometric
from torch_geometric.data import Data
from sklearn.preprocessing import StandardScaler
from data_loading.loading_utils import train_scaler, scale_dataset, select_target_id
def scale_energies_train(train, test):
y_train, y_test = [], []
for data in train:
y_train.ap... |
deef973d809ff7b126ea9e0be0b32c8468e47ea0c5a106928b9b0f89b2b261ff | Python | 2,412 | 69 | ##########################
# KiCAD standard package library
#########################
# download part data and generate classification by folder structure
from __future__ import print_function, division
import os
import os.path
from global_config import *
if testing:
minimum_sample_count = 1 # set in global_co... |
1abe9a4e0a96c8bb28c232e2b08993fffdfb9bb694be2230755e54a46a40ca4d | Python | 2,414 | 77 | from __future__ import annotations
import typing as t
from contextvars import ContextVar
from werkzeug.local import LocalProxy
if t.TYPE_CHECKING: # pragma: no cover
from .app import Flask
from .ctx import _AppCtxGlobals
from .ctx import AppContext
from .sessions import SessionMixin
from .wrappe... |
70c0625ef864467d4fac2fb7fc12181f1b9c62b511562c699596e47fefeda5bc | Python | 2,414 | 103 | from pprint import pprint as pp
def selective_collapse(mapfile):
collapse_dic = {}
outfile = open(mapfile.replace('.', '_select-collapsed.'), 'w')
o_map = open(mapfile)
head_line = ''
first_line = True
for line in o_map:
if line.startswith('DONT_USE'):
continue
... |
c74c0288369bbed5a583d6d6daa875d32f83e517920f2afd7b1d56e13fafeb25 | Python | 2,414 | 99 | import numpy as np
from impose.structure import StructureLayer
from impose.geometry import shapes
def test_copy():
sl = StructureLayer(
label="test layer",
geometry=[(shapes.Ellipse(a=10), 1)],
point_um=0.5,
)
# create a copy
sl2 = sl.copy()
assert sl.geometry is not sl2.g... |
79755388ff4312db3c49e5fb893cfc00991421e701e97be786b93ba63b31617e | Python | 2,415 | 74 | import time
import unittest
from typing import List
from codecarbon.emissions_tracker import EmissionsTracker, track_emissions
from codecarbon.output import BaseOutput, EmissionsData
def heavy_computation(run_time_secs: int = 3):
end_time: float = (
time.perf_counter() + run_time_secs
) # Run for `r... |
b926e9b06796c77890737aed892b57c677883f410d99c61da829156b8a6e1167 | Python | 2,415 | 54 | from unittest import TestCase, mock
import networkx as nx
import numpy as np
from scipy import sparse
import spateo.segmentation.density as density
from ..mixins import TestMixin, create_random_adata
class TestDensity(TestMixin, TestCase):
def test_create_spatial_adjacency(self):
adjacency = density._c... |
4758a87df5eddc3f2000729219b4c4a1ce99f303155497daccc57b0fbcae5ad1 | Python | 2,416 | 82 | #!/usr/bin/env python
from __future__ import division
import unittest
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from wyrm.types import Data
from wyrm import plot
from wyrm.processing import CHANNEL_10_20
class TestPlot(unittest.TestCase):
@classmethod
... |
4908c8590e9b8284d53257f704911c830ef2cac18e55bea744367fecf30568f3 | Python | 2,416 | 80 | import numbers
import pathlib
import numpy as np
from ..util import hashfile
# Naming conventions for formats:
# fmt_IMAGING-MODALITY_SPECIFIC_SOFTWARE.py
# IMAGING-MODALITY examples:
# - bf: Bright-Field Microscopy
# - bm: Brillouin Microscopy
# - fl: Fluorescence Microscopy
from .fmt_fl_zeiss import load_czi
from... |
2105d6d42ab7ee0e3453f644e755d5e1f9dbfeba3ac1ed8008553a9ceb116eb2 | Python | 2,417 | 75 | #!/bin/python
# -*- coding:utf-8 -*-
AAindex=['GLY','ALA','VAL','LEU','ILE','PHE','TRP','TYR','ASP','ASN','GLU','LYS','GLN','MET','SER','THR','CYS','PRO','HIS','ARG']
aaindex='GAVLIFWYDNEKQMSTCPHR'
RNAindex=['A','U','C','G']
DNAindex = ['DA','DT','DC','DG']
class Atom(list):
def __init__(self,name,num,x... |
9433aace586a15486efcf70627f3fbf6c2d0c720a0c66bb8eec1621e6c23dc69 | Python | 2,417 | 60 | #!/usr/bin/env python
#
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list o... |
9b3146fe1d38e9fea7e6fc397ca6bfeb27ca6593d06ae885fb75a266aae0f0a1 | Python | 2,417 | 71 | #!/usr/bin/env python3
"""
Test script to compare package-0 (CPU only) vs psys (platform/system) RAPL domains.
This helps determine which domain matches powerstat's measurements.
"""
import time
print("=" * 80)
print("Comparing RAPL domains: package-0 (CPU) vs psys (platform)")
print("=" * 80)
# Read both domains
pa... |
27b1008d613b153be2791dad4960358aa3cea54e918c24f938f2d490427a9f40 | Python | 2,418 | 77 | import numpy as np
import pytest
from pyriemann.spatialfilters import CSP
from pyriemann.stats import PermutationDistance, PermutationModel
pytestmark = pytest.mark.numpy_only
def test_permutation_badmode():
"""Test one way permutation test"""
with pytest.raises(ValueError):
PermutationDistance(mod... |
c996db05661342e4216ded9c990ff320c9d126e6eb07d53831a2ebc7838a3388 | Python | 2,419 | 71 | """Test cases for to_rle.py."""
import os
import unittest
from scalabel.label.io import load
from scalabel.label.typing import Frame
from scalabel.label.utils import get_leaf_categories
from bdd100k.common.utils import load_bdd100k_config
from bdd100k.label.to_rle import insseg_to_rle, segtrack_to_rle, semseg_to_rle
... |
f7651cdfd70076ce79507f6d25dedcda2a189527171b2006f97016c59eca06a2 | Python | 2,419 | 72 | from __future__ import print_function, division, absolute_import
import argparse
from PIL import Image
import torch
import torchvision.transforms as transforms
import sys
sys.path.append('.')
import pretrainedmodels
import pretrainedmodels.utils as utils
model_names = sorted(name for name in pretrainedmodels.__dict_... |
41170074592b2f29a39b65ffb4cdadf23a1d27d0553457f14b439701db83729f | Python | 2,420 | 57 | """Tests for the Parameter Database data/controller layer."""
from __future__ import annotations
from larvaworld.lib import reg
from larvaworld.portal.parameter_database import parameter_db_data
def test_build_parameter_table_df_row_count_matches_dict() -> None:
df = parameter_db_data.build_parameter_table_df()... |
a8c83a30a46276a8598341e33f907c19ff60fad492a75cd29645efcef378a1b9 | Python | 2,420 | 80 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Unselected(_BaseTraceHierarchyType):
_parent_path_str = "splom"
_path_str... |
ab6dbaab24b66874e06fc195a200a2fbbfdd37ec0d329d3a6b519081fcbdb98d | Python | 2,420 | 80 | import fire
import numpy as np
import torch
import tqdm.auto as tqdm
from modular_splicing.motif_names import get_motif_names
from modular_splicing.knockdown.models import short_donor_models
from modular_splicing.knockdown.experimental_setting import experimental_settings
from modular_splicing.knockdown.compute_knockd... |
c48be9cb48f7e7556091e1eea0c787d8522e1bd88cd6c3307c450d0ef2392d1b | Python | 2,420 | 66 | import sys
from robustness import datasets
from robustness.attacker import AttackerModel
from robustness.model_utils import make_and_restore_model
from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH
import os
def build_net(ds_kwargs={}, return_metamer_layers=False):
# We need to build... |
c8d2a38336f5b4aa2a78d6fa90b0bb776f0c8197817e2fcdd91a796b73987fd3 | Python | 2,420 | 80 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Unselected(_BaseTraceHierarchyType):
_parent_path_str = "parcoords"
_path... |
f338bbe92cec4f00384a456b46b57fa3817795f5bbc58cc23eec74ec616cf02f | Python | 2,420 | 66 | import sys
from robustness import datasets
from robustness.attacker import AttackerModel
from robustness.model_utils import make_and_restore_model
from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH
import os
def build_net(ds_kwargs={}, return_metamer_layers=False):
# We need to build... |
7b1998bdc189d7e4fc93cb13aff54e3c75c60c8a0cf3997356a9a8a8cc630e51 | Python | 2,421 | 74 | from abc import (
ABCMeta,
abstractmethod,
)
from uuid import UUID
from celery.result import AsyncResult
from galaxy.schema.tasks import (
TaskResult,
TaskState,
)
class AsyncTasksManager(metaclass=ABCMeta):
@abstractmethod
def is_ready(self, task_uuid: UUID) -> bool:
"""Return `True... |
a8079f307a77e71262fcabe39aa81d6e26b29c38e9a5396a79a78dffa03f05d5 | Python | 2,421 | 65 | # Copyright 2023 DeepMind Technologies Limited
#
# 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 agree... |
09e5e07362e369d46f2a952e92f105be29d7e071e199559f50dfa78270708d56 | Python | 2,422 | 72 | """
A general test to try to find out if anything is wrong with the API.
"""
import tempfile
import os
import time
import random
from ethoscope.core.monitor import Monitor
from ethoscope.hardware.input.cameras import MovieVirtualCamera
from ethoscope.utils.io import SQLiteResultWriter
from ethoscope.trackers.adaptive_... |
177a3ce3f6ef3f4610c514834146a6b0e39acec57df3a2dce2dfba2564077fb7 | Python | 2,422 | 73 | import torch
from flash_attn_interface import flash_attn_func
from torch import nn
class EfficienctMultiHeadAttention(nn.Module):
def __init__(self, embed_size, num_heads, dropout=0.0, use_flash_attn=True):
super().__init__()
assert embed_size % num_heads == 0, f"{embed_size=} {num_heads=}"
... |
ab4d3c0a32adb1c3ce8c7e935543457b32020f5ef66d7618c22ca05e4739e4be | Python | 2,423 | 57 | """Mask RCNN Demo script."""
import os
import argparse
import mxnet as mx
import gluoncv as gcv
gcv.utils.check_version('0.6.0')
from gluoncv.data.transforms import presets
from matplotlib import pyplot as plt
def parse_args():
parser = argparse.ArgumentParser(description='Test with Mask RCNN networks.')
parse... |
bde056abffe76a0d075421ddb97a25e0f83c5860722f60138f8cc317bf6a6164 | Python | 2,423 | 90 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created in November 2019
@author: Nathan de Lara <nathan.delara@polytechnique.org>
"""
from abc import ABC
import numpy as np
from sknetwork.hierarchy.postprocess import split_dendrogram
from sknetwork.base import Algorithm
class BaseHierarchy(Algorithm, ABC):
... |
d48023b36d8cff52145fb634d9de59b0ef6f7dd2e4045e12526530fc76fec5f7 | Python | 2,423 | 80 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
8a27dfde8b4168c9637de9c9cf2f49a1f2280bdbe59786fe3d0eccb48e17a9e5 | Python | 2,424 | 66 | import os
import random
import h5py
import numpy as np
import scanpy as sc
import tensorflow as tf
import sys
sys.path.append('../pkgs/ZIFA/')
from ZIFA import block_ZIFA
from scbig.utils import read_data, louvain, calculate_metric
def seed(SEED):
os.environ['PYTHONHASHSEED'] = str(SEED)
random.seed(SEED)
... |
ba067ef182836d9c59423785480c29a7bf942b41dedf1c6d357fb29a52c8762f | Python | 2,424 | 58 | from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from ase import units as ase_units
from figure1 import get_data
from instance_mongodb import instance_mongodb_sei
from plot_params import get_plot_params
__output_dir__ = Path("output")
__output_dir__.mkdir(exist_ok=True)
basis_set = "def2-sv... |
f077c116fa2c54bfa88253915056ef49831a909cd9b4ad555bc38f8971b09643 | Python | 2,424 | 75 | # %%
import nibabel as nib
import matplotlib.pyplot as plt
import numpy as np
import sys
from nilearn.image import new_img_like, coord_transform
from scipy.ndimage import binary_erosion, center_of_mass
from nilearn.image import new_img_like
from nilearn import plotting
sys.path.insert(0, '..')
from functions.data_helpe... |
fee9976bc33f9352801f67db51bb2a66819648cae4ea507fe63e96fe586f1b01 | Python | 2,424 | 82 | import os
import pytest
import numpy as np
from mirp.extract_mask_labels import extract_mask_labels
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
@pytest.mark.ci
def test_extract_mask_labels_generic():
# Single mask.
mask_labels = extract_mask_labels(
os.path.join(CURRENT_DIR, "data", "s... |
08f77c401a99c8cf80f78bab973bfa315690fbd4e0821ea19ed12e1848ac77e5 | Python | 2,426 | 86 | import os
import pytest
import rpy2.robjects as robjects
import rpy2.robjects.help as rh
rinterface = robjects.rinterface
class TestPackage(object):
def test_init(self):
base_help = rh.Package('base')
assert base_help.name == 'base'
def test_repr(self):
base_help = rh.Package('base')... |
11fcf4725607d368840c5306ba56aefd9cb6be7224a78a334d562855648ba8ba | Python | 2,426 | 87 | """Functionality to compute model goodness of fit."""
from inspect import isfunction
import numpy as np
###################################################################################################
###################################################################################################
def compute_... |
4487962f95728c2025c74a81d67f304972423c774ddd955371a311b3e33de22a | Python | 2,426 | 75 | import os
import sys
from robustness import datasets
from robustness.attacker import AttackerModel
from robustness.imagenet_models import ipcl_models
import torch
from PIL import Image
from model_analysis_folders.all_model_info import IMAGENET_PATH
import torch
torch.backends.cudnn.benchmark = True
def build_net(ds_... |
e08ed2891eddccc6b42f21710cec6534ea3de7e7df721f613f4615637654dccf | Python | 2,426 | 78 | """ 'Fast' Normalization Functions
For GroupNorm and LayerNorm these functions bypass typical AMP upcast to float32.
Additionally, for LayerNorm, the APEX fused LN is used if available (which also does not upcast)
Hacked together by / Copyright 2022 Ross Wightman
"""
from typing import List, Optional
import torch
f... |
fd3c94c53b3425440b2459d692a02121e3c4511728986e7c082a46d1396fefd8 | Python | 2,426 | 76 | import torch
import torch.nn as nn
from modular_splicing.models.modules.lssi_in_model import both_lssi_model_types
from modular_splicing.models.modules.spliceai import SpliceAIModule
from modular_splicing.models.motif_models.types import motif_model_types
from modular_splicing.utils.construct import construct
class... |
a62e0dc329126133ce4f9221f7b4831c2a1c39514d48187a3914a5f2eedfa924 | Python | 2,427 | 103 | from pathlib import Path
import pytest
from pyrosm import get_data
@pytest.fixture
def test_pbf():
pbf_path = get_data("test_pbf")
return pbf_path
@pytest.fixture
def helsinki_pbf():
pbf_path = get_data("helsinki_pbf")
return pbf_path
@pytest.fixture
def directory():
import tempfile
impor... |
2b35c1eb023304ec8aa4231c77ce2205635ebfb1e8025fee2cc752aac24822b9 | Python | 2,428 | 84 | from itertools import cycle
import numpy as np
import matplotlib.pyplot as plt
from modular_splicing.utils.plots.plot_psam import render_psams
from .analysis import DONOR_WINDOW_OFF, WINDOW_SPAN, STANDARD_DONOR
def draw_windows(model, motif_idx, window):
plt.figure(dpi=120)
values = window.mean(0) * 100
... |
9a052c09e5df36a6e56b15d68558bed6aaff07caf175c82b09636bc09083ec00 | Python | 2,428 | 66 | import sys
from robustness import datasets
from robustness.attacker import AttackerModel
from robustness.model_utils import make_and_restore_model
from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH
import os
def build_net(ds_kwargs={}, return_metamer_layers=False):
# We need to build... |
10706c149cc357e1b5d61c33cc4920e2126915df480f3ad9ab20b93a25e13fab | Python | 2,429 | 80 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Unselected(_BaseTraceHierarchyType):
_parent_path_str = "violin"
_path_st... |
45607302cb4980a005b1e69ba12a5f0cc7cd5460d895f2e8a04f4c81ecf154d9 | Python | 2,429 | 80 | """
This module define a specific dataset
"""
import logging
import torch
from datasets_pre_processing.generic_dataset import GenericDataset
class ClassificationPerProtDataset(GenericDataset):
"""
This class is a dataset where we have one label per protein/example
"""
def __init__(
self,
... |
5ddb2d298d2dc17884bb8aac213dba40f79aa2e66e6be02514b36372222693b3 | Python | 2,429 | 67 | """
Re-do the HPI fitting by swapping the coil order.
Based on the tutorial: https://neurospinmeg.wordpress.com/troubleshooting/
"""
import sys
sys.path.append("..")
import os
import subprocess
import argparse
import mne
from config import fname
from shutil import copyfile
import pandas as pd
# Be verbose
mne.set_log_... |
f38979040b827800bb2ef6a71b15c50bf648c12790b43806068e878416929b48 | Python | 2,429 | 68 | from __future__ import annotations
from typing import Any
from PySide6.QtWidgets import QHBoxLayout, QSplitter, QVBoxLayout, QWidget
from larvaworld.gui_v2.apps.models_environments.env_builder_canvas_qt import (
EnvBuilderCanvasWidget,
)
from larvaworld.gui_v2.apps.models_environments.env_builder_controller impo... |
e236bfa413d2734b4e441f1697772565aa2411a8a5cc0e7cda981504a9b5538a | Python | 2,430 | 80 | # Copyright 2023 DeepMind Technologies Limited
#
# 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 agree... |
e9e26a4f1d9647fccf65672db5498de42aa34f7c4c41797e4c2fc688f5755c8c | Python | 2,431 | 70 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 7 11:03:33 2022
@author: psicobiologia
"""
import numpy as np
import nibabel as nib
import pandas as pd
from scipy import stats
# define full path to the coefficients map
coefficient_path = 'path_to_output_directory/map_median_coefficient.nii'
# ... |
683cf9f4ff18634fb08d9ffd0d65eb15564029accc5b9ace6befab13e7ae39e0 | Python | 2,432 | 58 | # !/usr/bin/env python
## created by Yun Hao @MooreLab 2021
## code inspired by Bjarten's github repo https://github.com/Bjarten/early-stopping-pytorch/blob/master/pytorchtools.py
## This script contains early stop function of DTox model
## Module
import numpy as np
import torch
## This function stops training of ... |
8f4b5c687d630d596c3e4a7bcb6dea1a53cc71e345af43867d93988cb1e3447d | Python | 2,432 | 79 | from __future__ import annotations
from pathlib import Path
import panel as pn
import pytest
from larvaworld.lib import reg
from larvaworld.lib.reg import config as reg_config
from larvaworld.lib.reg.generators import EnvConf, ExpConf, LabFormat
from larvaworld.portal.config_widgets.conftype_widget import (
Conft... |
d6e5284337dcc7ab188131059284510ca654f77d6a8661d6c34468d61a44389c | Python | 2,432 | 66 | import os
import sys
sys.path.append('..')
import numpy as np
import pandas as pd
from utils.feature_extraction import feature_extractor
from utils.utils import kfold_cross_val, custom_folds_train, plot_cm
class_mapping_dict = {
'alternate picking': 0,
'legato': 1,
'tapping': 2,
'sweep picking': 3,
... |
85308acfff370521bbbd733870b01e07683cf5cdf890d2d77ca2254457b8d510 | Python | 2,436 | 74 | import numpy as np
def normalize_feature(feature,
channel_wise_mean=True, channel_wise_std=True,
channel_axis=0,
std_ddof=1,
shift=None, scale=None,
scaling_only=False):
'''Normalize feature.
Paramet... |
a2c417ba744fd61f2eb4dafda34cbdee5c26c411d2d8b91de5116e5dd8727c56 | Python | 2,436 | 60 | """A02 pretrained real-GPT-2 row: residual + final-norm anchors on real weights.
Venue-gated exactly like ``tests/real_model/r1`` (GATE-ID R1_OFFLINE_VENUE):
runs only under the offline preflighted cache env, loads THROUGH the artifact
registry's checkpoint-evidence hook (pinned revision, never a bare model id),
and s... |
ee2f8e0d2c283a202c727df175a6d8ea697e103e9093b8cc825a80bef983390b | Python | 2,436 | 73 | # Generated by Django 3.2.6 on 2024-09-05 03:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('biomedisa_app', '0111_upload_scaling'),
]
operations = [
migrations.AddField(
model_name='specimen',
name='antscan_c... |
79ced27837693108290b8a4821a0d8f82f29c1676e65d4139f49fab240ac31b7 | Python | 2,437 | 82 | """
The feeder module, generating rhythmic feeding motions.
Feeding is modelled as an oscillation whose every cycle is one attempted
food intake, gated by the intermitter and by contact with a food source.
"""
from __future__ import annotations
from typing import Any
import param
from ...param import PositiveNumber... |
cfd60ec6015dc16e6520c6afe7f8016c02b1db17f41aa8a3de629b1340019798 | Python | 2,437 | 67 | import os
import warnings
import h5py
import numpy as np
import scanpy as sc
from scbig import run_scbig, preprocess, read_data, setup_seed, sample
warnings.filterwarnings('ignore')
for dataset in ['10X_PBMC', 'mouse_bladder_cell', 'mouse_ES_cell', 'human_kidney_counts', 'Adam',
'Human_pancreatic_is... |
d0f9b86f38ad6c2d7db93af7bc3b092c9a5deab26864bc935bc07952449ce542 | Python | 2,437 | 45 | import numpy as np
from dimensionality_all_models import *
import pandas as pd
from scipy.io import loadmat
DATADIR='/om/user/gretatu/aud-dnn/data'
RESULTSDIR='/om2/user/jfeather/projects/aud-dnn/results/dimensionality_output_2022_08_18_Ssquare/'
mean_subtract = True
eig_type = 'corr'
for std_divide in [False, True]:... |
61df61bfe121a589748498599afc19c0293de37689e0f3fcda4847c66fc0df3e | Python | 2,438 | 73 | """
core.lda — Quadratic-feature Fisher LDA.
The pipeline maps an input feature vector x (per paper §2.3, 15 dims)
through a quadratic feature expansion q(x) = [x, x^2] and fits a
Fisher LDA on the expanded space:
score(x) = q(x) @ w - t
where (w, t) are the standard pooled-covariance LDA parameters.
Pairwise p... |
2a09596effcdea0a0a5dd0becda5475144b63b49499915d16f270beed762e1f8 | Python | 2,439 | 94 | """
Plotting of continuous features stored in adata.obs.
"""
from typing import (
Optional, # Special
)
import matplotlib
from anndata import AnnData
from stlearn.pl.classes import FeaturePlot
# @_docs_params(spatial_base_plot=doc_spatial_base_plot, gene_plot=doc_gene_plot)
def feat_plot(
adata: AnnData,
... |
403f895cf07e207a2586b290ef08567374e871f49285ac397bbd05b6533c977b | Python | 2,439 | 70 | from abc import ABC
import numpy as np
import math
def check_performance(gt_image, noisy_image, denoised_image):
"""
Args:
gt_image:
noisy_image:
denoised_image:
Returns:
"""
iqs = IQS(pixel_max=1, ref_image=gt_image.cpu().numpy())
return {
"PSNR_Noisy": iqs... |
503d2b119ebceb599362121dcdcb2a2a7525f0fa33a1c5d697d5414355535a77 | Python | 2,439 | 65 | from distutils import log
import distutils.command.install_scripts as orig
import os
import sys
from pkg_resources import Distribution, PathMetadata, ensure_directory
class install_scripts(orig.install_scripts):
"""Do normal script install, plus any egg_info wrapper scripts"""
def initialize_options(self):
... |
6ae6968724b2d295a4d5d5f3fbe97f5cdba67dbe79493c7deb6ea949293442ee | Python | 2,439 | 84 | import cv2
import numpy as np
def normalise_img(img):
'''Normalize the image.
Map the minimum pixel to 0; map the maximum pixel to 255.
Convert the pixels to be int
'''
img = img - img.min()
if img.max() > 0:
img = img * (255.0/img.max())
img = np.uint8(img)
return img
def img_... |
2ec2b01d50c1b0c00e05c3e97ae6e8c69c4ddcb4e13b69cab48b9d4a7ba21ab2 | Python | 2,440 | 93 | """Screenshots for quick guide import ts (not working automatically)"""
import pathlib
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication
from pyjibe.head.main import PyJibe
jpkfiles = [pathlib.Path("map-data-2015.05.21-18.16.49.170.jpk-force-map")]
def cleanup_autosave(jpkfile):
"""Re... |
c87919e21be8601d5159c70a86a1a84ab8396f549976954edfd56e27ccfbb077 | Python | 2,440 | 71 | from mirp._images.mask_image import MaskImage
from mirp._data_import.utilities import flatten_list
from mirp._masks.base_mask import BaseMask
def alter_mask(
masks: BaseMask | MaskImage | list[BaseMask],
alteration_size: None | list[float] = None,
alteration_method: None | str = None,
... |
a8036d8cf338212d1e93661e78601d55b9dc4f89a44e5bdcaea0915da0f169dc | Python | 2,442 | 88 | import os
import sys
import importlib
import pandas as pd
import anndata as ad
from pyprojroot import here
proj_root: str = str(here())
sys.path.insert(0, os.path.join(proj_root, "package/python"))
from utils import set_file_logger
import cembav2env
importlib.reload(cembav2env)
# * configs
rsc_dir = os.path.join(proj... |
daa8d99ec1cfb1512c200ca345eb95eb9273e304ef2aa4c7e8c1e507c47d2470 | Python | 2,442 | 74 | from collections import namedtuple
import pytorch_lightning as pl
import torch
import torch.nn as nn
from pointnet2_ops.pointnet2_modules import PointnetFPModule, PointnetSAModuleMSG
from scene_graph_prediction.pointnet2_dir.pointnet2.models.pointnet2_ssg_sem import PointNet2SemSegSSG
class PointNet2SemSegMSG(Point... |
11b2ab7be19c4a93fe8aa27c5746ca490ca4084d7dee73772c1bcdcabde6424d | Python | 2,443 | 80 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Selected(_BaseTraceHierarchyType):
_parent_path_str = "scattermap"
_path_... |
12b595c8ae4dd4d07d06c6dcfc1d2381183350cc16e700abed31463af3ca30cf | Python | 2,443 | 58 | # coding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License... |
46ef25b3f4bc3cf291f112849fb8cc7ad10d63f03d8cf7add479614d9c291715 | Python | 2,443 | 75 | from __future__ import absolute_import
import logging
import sys
from email.parser import FeedParser # type: ignore
from pip._vendor import pkg_resources
from pip._vendor.packaging import specifiers, version
from pip._internal import exceptions
from pip._internal.utils.misc import display_path
logger = logging.get... |
484f6724847c73a84b9091cd41dfc6e9ad899e684e7a9e7d8068f33a8dacaa71 | Python | 2,443 | 80 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Selected(_BaseTraceHierarchyType):
_parent_path_str = "choropleth"
_path_... |
95d6d4d582ee27828e1708ffc423ebdc14483009d56f845e18593abaf6f334ce | Python | 2,444 | 69 | """Golden-corpus integrity pins for the harvested release artifacts.
The corpus at ``tests/release_goldens/genuine_release_artifacts.tar.gz`` is
harvested BYTES (ecosystem MEMO section 3.7 / build item G1): seven genuine
artifacts from six writers, parts of which are irreplaceable. These tests pin
the exact bytes and ... |
10d3ee80909c917d88a951aee252caf6c6095aa6f02f37f09634994bc6211fd2 | Python | 2,445 | 83 | import time
import torch
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Timer():
''' Timer for recording training time distribution. '''
def __init__(self):
self.prev_t = time.time()
self.clear()
def set(self):
self.prev_t = time.t... |
319cde876fd6d9e709164a5d9a6de5ac166a884a900473bbfca4f2f8f3072cfb | Python | 2,445 | 104 | """Phase 8 cross-architecture bundle alignment tests."""
from __future__ import annotations
import torch
from torch import nn
import torchlens as tl
class _OneHidden(nn.Module):
"""Single-hidden-layer model."""
def __init__(self) -> None:
"""Initialize modules."""
super().__init__()
... |
8e4690d0d26d9f440e98032b47d3725c514cdd45760728445eace09e72f433bf | Python | 2,446 | 81 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-02-20 14:25
from __future__ import unicode_literals
import biomedisa_app.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('biomedisa_app', '0013_upload_active_contours'),
]
operati... |
84f971caf2f0467737af96c0094489d9220b4ca898a17439fe9b7d26536eea9b | Python | 2,447 | 72 | from typing import List
import os
import copy
import numpy as np
from pymatgen.core.structure import Molecule
from pymatgen.io.ase import AseAtomsAdaptor
import ase.io as ase_io
from instance_mongodb import instance_mongodb_sei
from coeffnet.datagen.utils import perturb_along_eigenmode
if __name__ == "__main__"... |
864d07c20c39a4a60eded59d707fe5b25ccd3bc8c470845cd9ea1f770d8b578a | Python | 2,447 | 75 | """Worker Event Dispatcher Bootstep.
``Events`` -> :class:`celery.events.EventDispatcher`.
"""
from kombu.common import ignore_errors
from celery import bootsteps
from celery.worker.state import reserved_requests
from .connection import Connection
__all__ = ('Events',)
class Events(bootsteps.StartStopStep):
"... |
9fc5bd109ea2ed7bcf2d10347b59bd9db9e7ad2483af5ad773a9e4e6c76ce9ff | Python | 2,447 | 66 | from typing import Dict, List, Union
from pytorch_lightning import LightningModule, Trainer
from pytorch_lightning.callbacks import Callback
from torch import Tensor
MetricValue = Union[Tensor, float]
class MetricCallback(Callback):
"""Callback that collects log metrics from the LightningModule and stores them ... |
ae31cc5ab9820554a0dd9c14560d3235322fc01951daffc963cf4468350b0b63 | Python | 2,449 | 93 | """Screenshots for quick guide import ts (not working automatically)"""
import pathlib
import sys
from PyQt6 import QtCore
from PyQt6.QtWidgets import QApplication
from pyjibe.head.main import PyJibe
jpkfiles = [pathlib.Path("map-data-2015.05.21-18.16.49.170.jpk-force-map")]
def cleanup_autosave(jpkfile):
"""Re... |
ae4e3b06ece9804b139a1ea0febca9e99fc489305d396c030ba414996aa08703 | Python | 2,449 | 87 | import numpy as np
from gym import utils
from gym.envs.mujoco import MuJocoPyEnv
from gym.spaces import Box
class HumanoidStandupEnv(MuJocoPyEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
],
"render_fps": 67,
... |
af93c0e30edeec7c94fd472b4a0559a319b37d7611b2461fb5f8b3cb031007b9 | Python | 2,449 | 82 | """
Tests related to locating and reading command waveforms from stimulus waveform
files. If the stimulus waveforms aren't found you can provide a search path
as an argument when instantiating pyabf.ABF()
"""
import sys
import pytest
import os
import numpy as np
import time
import warnings
try:
# this ensures pyA... |
b6128ec6dd603861d271bf3d28b672471b41f35fbb728235faea957e181afe3a | Python | 2,449 | 90 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created in November 2019
@author: Nathan de Lara <nathan.delara@polytechnique.org>
"""
from abc import ABC
from typing import Optional, Union
import numpy as np
from scipy import sparse
from sknetwork.topology.structure import is_connected
from sknetwork.base import ... |
851ccc1123f4d46fae317690e7487f4c21179a71a6fa10244ad0f5681d723950 | Python | 2,450 | 69 | """Test cases for mot.py."""
import os
import unittest
import numpy as np
from PIL import Image
from scalabel.common.typing import NDArrayF64, NDArrayI32, NDArrayU8
from bdd100k.common.bitmask import bitmask_intersection_rate, parse_bitmask
class TestMaskIntersectionRate(unittest.TestCase):
"""Test cases for th... |
e69b43dafaadd6887744bb86c672b9913498f69541bad7cdfd84d72b3b79f23e | Python | 2,450 | 77 | import os
from mirp._images.generic_image import GenericImage
from mirp._images.mr_adc_image import MRADCImage
from mirp.extract_features_and_images import extract_features_and_images, extract_images
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
def test_basic_adc_mr_feature_extraction():
# Multi-fra... |
fedad04bffd7ef51d038e057bb44139737ce81bdb2768cbe2a8a082a3224a6fb | Python | 2,450 | 61 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created in May 2023
@author: Thomas Bonald <bonald@enst.fr>
"""
from typing import Iterable, Optional, Union, Tuple
import numpy as np
from scipy import sparse
from sknetwork.path.dag import get_dag
from sknetwork.utils.format import bipartite2undirected
from sknetwo... |
1e0c0430a42d1b0893005af4df480ca934a6923fc1d7a8d3ca8d2c29797d30ea | Python | 2,451 | 54 | from src.keras_tuner_cv import *
from src.data_processing import *
from src.mlp import *
import pandas as pd
import numpy as np
import os
import click
import datetime
@click.command()
@click.option('--cuda_device', default='0', help='which GPU to use', show_default=True)
@click.option('--input_train', default='../dat... |
433e01443d23bc4e05a8e16693bd4ed7daa5abaf8466e91e2d793cec8536019f | Python | 2,451 | 60 | import pytest
from pytest_celery import (RABBITMQ_CONTAINER_TIMEOUT, RESULT_TIMEOUT, CeleryBrokerCluster, CeleryTestSetup,
RabbitMQContainer, RabbitMQTestBroker)
from pytest_docker_tools import container, fxtr
from t.integration.tasks import identity
failover_broker = container(
image="... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.