sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
4232cb9ab476c3a7ce3b74a513929f6e5ec87354f9d4934bfd970305ed740e4f | Python | 719 | 33 | #!/usr/bin/env python
import fmm3dpy as fmm
import numpy as np
#
# This is a sample code to demonstrate how to use
# the fmm libraries
#
# sample with one density, sources to sources,
# charge interactions, and potential only
#
n = 200000
nd = 1
sources = np.random.uniform(0,1,(3,n))
eps = 10**(-5)
charges = np.... |
ac43122cd0c4ccc90b74d20e9b904056d6f44b9d1727e8eafc05764ffd19814f | Python | 719 | 21 | # def get_paragraphs(from_item):
# extracted_text = ""
# paragraphs = from_item.find_all("p")
# for paragraph in paragraphs:
# if extracted_text == "":
# extracted_text = paragraph.text
# else:
# extracted_text = extracted_text + "\n" + paragraph.text
# return ex... |
58d14d48764de988829d448ca448c31d92ae5f9c4c4d711f279a8ee9ef9dc0a5 | Python | 720 | 23 | # 3rd party dependencies
import pytest
# project dependencies
from deepface.models.face_detection import Ssd
from deepface.commons.logger import Logger
logger = Logger()
def test_ssd_requires_opencv_below_5(monkeypatch):
monkeypatch.setattr(Ssd.cv2, "__version__", "5.0.0")
def download_weights_if_necessary... |
4f83898cec5d094227a909489533a889f313e592f9138e50cc4f22f2808c7b7f | Python | 721 | 27 | import logging
from datetime import datetime
from agent.data.entities.config import ROOT_LOGGER_ID
from agent.data.sql.sql_mgmt import get_connection
from agent.data.entities.sentence import generate_sentences_from_items
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logger = logging.... |
7494816668716938e99f0c57ff1084ada5f4bac40e2c3504669867fd6f2639d5 | Python | 722 | 43 | from scipy.special import kl_div
import numpy as np
def ber_kl_div(p, q):
return kl_div(p,q) + kl_div(1-p,1-q)
def ber_kl_div(p, q):
return p * (np.log(p/q)) + (1-p) * (np.log((1-p)/(1-q)))
small_num = .001
dim = 10
p_ = np.array([.5, .5]) # model
q_ = np.array([1, 0]) # target
p_ = np.array([.5, .5])
q_ = ... |
d04b3485ac957ab02299ddc2fea88f6878986e719ac9c0b583a0c13984075d84 | Python | 723 | 28 |
from setuptools import find_packages
from distutils.core import setup
setup(
name="optim-sted",
version="0.1",
author="Anthony Bilodeau",
install_requires=[
"bandit-optimization",
"pysted",
"abberior-sted",
"h5py",
"pyyaml",
"metrics @ git+https://github... |
1a598d02a101319a2d79179198e30c0e41be1f93da91e74257e63ef8ffe6e1e4 | Python | 724 | 23 | """
Test for issue 502:
https://github.com/Data-Centric-AI-Community/data-profiling/issues/502
"""
import pandas as pd
from data_profiling.model.summary import describe_1d
def test_issue502(config, summarizer, typeset):
series = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dtype=pd.Int64Dtype())
... |
2bc87a20ac58033a398c59a360ca0b5b28f79b12c08bd3df294642ced5c31f7f | Python | 724 | 28 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from .adsorbates import ( # noqa
AdsorbateBindingSites,
AdsorbateSlabRelaxations,
Lifetime,
UnsupportedAdsorbateException,
... |
dc116b81dba3fddcb5e44047f63aba7fbac0cf26c1afc851875d805bd2af152b | Python | 724 | 33 | import os
import click
from ci.ray_ci.utils import ci_init
from ray_release.test import (
LINUX_TEST_PREFIX,
MACOS_TEST_PREFIX,
WINDOWS_TEST_PREFIX,
Test,
)
BAZEL_WORKSPACE_DIR = os.environ.get("BUILD_WORKSPACE_DIRECTORY", "")
@click.command()
def main() -> None:
"""
This script determines... |
df0ca92ca46d8318050448a79f054e809320e789d5e5acbd5720c739c4765d5c | Python | 724 | 20 | from data_profiling.report.presentation.core import FrequencyTable
from data_profiling.report.presentation.flavours.html import templates
class HTMLFrequencyTable(FrequencyTable):
def render(self) -> str:
if isinstance(self.content["rows"][0], list):
html = ""
kwargs = self.conten... |
4e090311d429899c0f1855d08168b720b4b37a12237196cb3c39e91aa9fdc1d4 | Python | 725 | 26 | import pytest
from testbook import testbook
pytest.importorskip("tensorflow")
pytestmark = pytest.mark.tensorflow
@testbook("examples/01a-Getting-started-Tensorflow.ipynb", execute=False)
def test_getting_started_tensorflow(tb):
tb.inject(
"""
import pandas as pd
import numpy as np
... |
799a02cafb7d2b9aa0915b7aebbe44e77c1e2c153d6a79d59a3b42fd854e65f1 | Python | 725 | 30 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import annotations
from fairchem.core.common.parallelism.graph_parallel_a2a import (
GPContext,
all_to_all_collect... |
f875e4498b14e30df90e26b9f38fb4f999e110e312d7480d06786dffad357735 | Python | 727 | 20 | import pandas as pd
import utils
full_df = pd.read_csv("anon_results.csv", index_col=[0, 1, 2])
# Remove post-operation visits from test results
full_df = full_df[full_df["visit_type"] != "post-operation"]
## Accuracy of BOAS positive/negative classification using ground-truth stertor grade
stertor_df = full_df[~pd.... |
8c6415a3438d099b3ae725538ec7de33e457c8fe553843a7b6fcd61ab94044e2 | Python | 728 | 27 | # __sglang_query_start__
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="fake-key")
# Chat completions
print("=== Chat Completions ===")
chat_response = client.chat.completions.create(
model="Llama-3.1-8B-Instruct",
messages=[
{"role": "user", "content": "List 3... |
8cb6e042f810abe7883e9fdd871a6c8b870a7bf7372ad3fc38aa375bbb33c920 | Python | 728 | 26 | import csv
from lib.qc import QCResult, verify
from lib.utils import setup_logger
log_file = snakemake.log[0] if snakemake.log else None
logger = setup_logger(log_file)
results = [
QCResult.load(path, warn_checks=snakemake.params.warn_checks)
for path in snakemake.input.metrics
]
rows = verify(
results,
... |
0966a801d05c29792f82f96bf75613123ac50210be9be2120ba35b7f7efdcfe2 | Python | 729 | 30 | def test_quantize():
import torch
from sinabs.layers import NeuromorphicReLU
x = torch.rand(20, requires_grad=True)
lyr = NeuromorphicReLU(quantize=True, fanout=1, stochastic_rounding=False)
interm = lyr(x)
out = 40 * interm
err = (out.sum() - 100) ** 2
err.backward()
assert out.s... |
0fd5a09117914d40a6946972edcdb598c49df64eaf9838f019cbc7f5ed03c721 | Python | 730 | 23 | import torch
from SPLAM import *
from splam_utils import *
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as pl
import os
device = torch.device("cpu")
# model = torch.jit.load("./MODEL/SPLAM_v11/splam_14.pt")
# model = model.to("mps")
model = torch.load("./MODEL/SPLAM_v... |
29c56074f9cff2e1c150e9c34f786d0225289d9304b458c54c6a25c56dbfc3c8 | Python | 731 | 20 | """This module provides the Python API for emitting internal Ray events
via the ONE-Event framework. Events are buffered and exported through
the C++ RayEventRecorder.
"""
from ray._common.observability.config import is_python_ray_event_enabled
from ray._common.observability.internal_event import InternalEventBuilder
... |
336e0646f7b90acde989b80c0e5566a2b77b7e2aeafc57c5aa051e618204a1d4 | Python | 731 | 26 | import pandas as pd
import numpy as np
def ImportPicke(path):
return(pd.read_pickle(path))
def stdev_of_events(events):
start_times = [pair[0] for pair in events]
return(np.std(start_times))
table_k = ImportPicke("/Volumes/pool-miblab1/users/steen/00_imaging/combi_paint/26_02_12_A549_EGFR-GFP_quenchedMP/... |
7b43e4af6ed18b4c99312c988e00e0a4e0ab5b2c8b61fd6be17c5391245b1bc8 | Python | 732 | 18 | # Copyright 2026 Google LLC
#
# 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 agreed to in writing, ... |
e803c28dbbc2e5ae20b12002567871f612faf70ecc805106a7908412b9933825 | Python | 732 | 19 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#... |
0ff0e0d0f44af32f8f89d74707398276858108a65be5cddcaad1ef77fc521f17 | Python | 733 | 22 | # -*- coding: utf-8 -*-
"""
"""
import matplotlib
matplotlib.use('Agg')
from analysis_and_visualization import perform_analysis_and_visualization, perform_analysis_and_visualization_stc, perform_analysis_and_visualization_spont, perform_analysis_and_visualization_STW
from mozaik.storage.datastore import Hdf5DataStore,... |
df9a3ab7f147b239d94ec63d93b43cd38bbf1b1a3896e7a3e18fc177aaf4d01f | Python | 733 | 27 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import annotations
from fairchem.core.components.benchmark.training import (
TrainingBenchmarkResult,
run_training... |
b0fbaea040d97743a3a86e895ab7dc9dbed6e6e34adf7ad971df11644f959d2c | Python | 735 | 28 | import numpy as np
from siapy.utils.images import spy_create_image, spy_save_image
# Create sample data
rng = np.random.default_rng(42)
image = rng.random((100, 150, 50)) # height, width, bands
# Save image in ENVI format
spy_save_image(
image=image,
save_path="output/my_image.hdr",
metadata={"descripti... |
c8f64e2765e141186ccf63991a6e6c037dce3c23f7a790552d39a7cc017c0f99 | Python | 735 | 23 | __all__ = [
'VelocityNet'
]
import torch
class VelocityNet(torch.nn.Module):
def __init__(self, depth : int = 3, width : int = 100, dim : int = 3):
super().__init__()
self.depth = depth
for i in range(depth):
layer = torch.nn.Linear(dim if i == 0 else width, dim if i == de... |
e55357961cf712902efbdc938d403f3945555c2e2a0d4f7aa027eab24ddadacc | Python | 735 | 28 | import unittest
from spinnaker2.coordinates import WordAddr, ByteAddr
class TestMemoryAddresses(unittest.TestCase):
def test_base(self):
w_addr = WordAddr(10)
b_addr = w_addr.to_ByteAddr()
self.assertEqual(b_addr, ByteAddr(10<<2))
self.assertEqual(b_addr, 10<<2)
self.asse... |
468dc48085fc15e7b1c3c13c32f6177df689dd34626cb951da3dc4f2d366becd | Python | 736 | 29 | import os
import sys
import nibabel as nib
import pandas as pd
from pandas import DataFrame
import numpy as np
import umap
import pickle
#reopen the space
loaded_reducer = pickle.load((open('/BCS_3D.sav DIRECTORY/00_BCS_3D.sav', 'rb')))
#read the csv of the new maps parcellation matrix
mycsvfile = "/CSV_DIRECTORY/PAR... |
5bff30e7a62f85bf43a25e38bc4533e2fbf19b4bc6dc0ce102ba47fd063e7203 | Python | 736 | 26 | import setuptools
setuptools.setup(
name='voxelmorph',
version='0.1',
license='Apache 2.0',
description='Image Registration with Convolutional Networks',
url='https://github.com/voxelmorph/voxelmorph',
keywords=['deformation', 'registration', 'imaging', 'cnn', 'mri'],
packages=setuptools.fi... |
ccc25c23fe84298ec089c5305735300d7a5e614490aaa67bc460f6ddc7116ed7 | Python | 736 | 26 | import numpy as np
from rich import print
from siapy.entities import Pixels, SpectralImage
# Create mock image
rng = np.random.default_rng(seed=42)
array = rng.random((100, 100, 10)) # height, width, bands
image = SpectralImage.from_numpy(array)
# Define pixels
iterable = [(1, 2), (3, 4), (2, 4)]
pixels = Pixels.fr... |
00f6adbc3ccd2e511a358c7a471bb3bb63b5b92e29ce4f144729ec417ab657dc | Python | 737 | 30 | import matplotlib.pyplot as plt
from lib5c.util.plotting import plotter
@plotter
def plot_heatmap(matrix, cmap='Reds', vmin=0, vmax=100, despine=False,
**kwargs):
"""
Plots a simple heatmap of a dense matrix.
Parameters
----------
matrix : np.ndarray
The dense matrix to ... |
5399b8a68279df710db37571b67e7d5641614b50086f34234349922024f37476 | Python | 737 | 26 | # Range of each DoF
RANGE_DOF = {
'deviation': [-0.175, 0.435],
'flexion': [-1.222, 1.221],
'cmc_flexion': [-45, 15],
'cmc_abduction': [-25, 25],
'mp_flexion': [-40, 45],
'ip_flexion': [-25, 75],
'4cmc_flexion': [0, 11.642],
'2mcp_abduction': [-15, 15],
'2mcp_flexion': [-45, 90],
... |
8ae62f3659022788f5f2e32e627d4bf3eb5766940408090f5fc0d9f050268bd2 | Python | 737 | 33 | import numpy as np
class TimeSeriesRegressor:
"""
This is a super class for time series regressors
"""
def __init__(self,
output_directory: str):
"""
Initialise the regression model
"""
self.output_directory = output_directory
self.train_durati... |
206f8e3e836df979ce235dcdd6df0568a3e683bf640ad338a5765d998905990b | Python | 739 | 18 | # Copyright 2026 Google LLC
#
# 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 agreed to in writing, ... |
7a4533b0a1ca2168c341e4c07ee2c3f7bd99e698f89b0989f3568f5857a08de2 | Python | 739 | 22 | # As featured on this Google Cloud Platform page:
# https://cloud.google.com/solutions/building-a-propensity-model-for-financial-services-on-gcp
from pathlib import Path
import pandas as pd
from data_profiling import ProfileReport
from data_profiling.utils.cache import cache_zipped_file
if __name__ == "__main__":
... |
82d30d72f9f369c6586af7a8e8ec59c378bb4f52207427e53a4f44b9dcc9fb2e | Python | 739 | 35 | AMBIGUITY_TABLE = {
'A': 'A',
'T': 'T',
'G': 'G',
'C': 'C',
'N': 'N',
'AC': 'M',
'AG': 'R',
'AT': 'W',
'CG': 'S',
'CT': 'Y',
'GT': 'K',
'ACG': 'V',
'ACT': 'H',
'AGT': 'D',
'CGT': 'B',
'ACGT': 'N'
}
def iupac_amb( dnalist ):
'''
Translates a gi... |
184fe0f503807f4b17226dabc7ad3004b4170aee67882fa26a022eae8d19a4ac | Python | 740 | 33 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 4 20:06:19 2017
@author: lindseykitchell
"""
import json
import os
# get bvals file path
#bvals= os.environ['BVALS']
with open('config.json') as config_json:
config = json.load(config_json)
with open(config["dtiinit"]+'/dt6.json') as dt6_json... |
dda6d5dd14da4ef429e551fdc1cf645f6cdd695bea07c5ff91e471cfe04fb553 | Python | 740 | 29 | import os
import shutil
import mrcfile
import torch
def load_mrc_data(mrc_file):
"""
Loads a .mrc or .rec file as a torch tensors.
"""
with mrcfile.open(mrc_file, permissive=True) as mrc:
try:
data = torch.tensor(mrc.data)
except TypeError:
data = torch.tensor(... |
e16ffc41b4214a71a2cc95427f8409c8ad07e8240d1d39f9ccd66f5105d59f64 | Python | 740 | 28 | import matplotlib.pyplot as plt
import numpy as np
tracc = [96.46, 11.24, 11.24, 11.24, 11.24, 11.24, 11.24]
teacc = [96.19, 11.35, 11.35, 11.35, 11.35, 11.35, 11.35]
plt.plot(tracc, "r-o", label="10x100")
plt.plot(teacc, "r--o")
tracc = [98.36, 97.90, 97.50, 97.23, 97.11, 96.87, 96.48]
teacc = [97.69, 97.26, 96.72,... |
f3602d3bfb4226c6bf7b1656f603bbf7ab5e6f6415bc65a45d6026874a6973e0 | Python | 740 | 24 | import pandas as pd
from data_profiling.report.presentation.core.duplicate import Duplicate
from data_profiling.report.presentation.flavours.html import templates
def to_html(df: pd.DataFrame) -> str:
html = df.to_html(
classes="duplicate table table-striped",
)
if df.empty:
html = html.r... |
1f1629fc10bd77c8748734406f34e25e7adc31f27c45d775e743e737171ecf98 | Python | 741 | 20 | import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import matplotlib.colors
cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list("", ["darkgrey","crimson"])
### Lobule 2 cells excluded since not every slice containe... |
02cfd1003674f04c8d8b79c98e263b48b8788cbea936785f00e4fc4aca67921a | Python | 742 | 26 | from torch import nn
from pfrl.nn.recurrent import Recurrent
class RecurrentBranched(Recurrent, nn.ModuleList):
"""Recurrent module that bundles parallel branches.
This is a recurrent analog to `pfrl.nn.Branched`. It bundles
multiple recurrent modules.
Args:
*modules: Child modules. Each mo... |
3f606cbcf59b9fda06f5ceb8a9d97b25766322ea8f71939fbe1517617b0050e3 | Python | 742 | 24 | import numpy as np
import tensorflow as tf
def preprocess_image(image):
'''Scales pixel values to correct range before passing to the network
Args:
image: image to be passed to the network, should be an unscaled image in
uint8 format (values in range [0, 255]).
Returns:
preproc... |
916b1c9f0694399373571cf11672fd342ae981c1882755b3da721120a233dfbc | Python | 743 | 12 | from ._spatial_communication import spatial_communication
from ._spatial_communication import communication_direction
from ._spatial_communication import cluster_communication
from ._spatial_communication import cluster_communication_spatial_permutation
from ._spatial_communication import cluster_position
from ._downst... |
f7effbcada2113d18412c8611f91b36b9d0ac557449b352b9c9843a47d090f06 | Python | 744 | 28 | import numpy as np
import torch
def set_batch_non_diagonal(array, non_diag_val):
batch_size, m, n = array.shape
assert m == n
rows, cols = np.tril_indices(n, -1)
array[:, rows, cols] = non_diag_val
def set_batch_diagonal(array, diag_val):
batch_size, m, n = array.shape
assert m == n
rows... |
4c0e8dca56a6d2cf098d2c939103a6dd113c6ec669af21df94540a549ba54672 | Python | 745 | 22 | # -*- coding: utf-8 -*-
"""
"""
import matplotlib
matplotlib.use('Agg')
from analysis_and_visualization import perform_analysis_and_visualization, perform_analysis_and_visualization_stc, perform_analysis_and_visualization_spont, perform_analysis_and_visualization_ring_disk
from mozaik.storage.datastore import Hdf5Data... |
804210fdc1b1be199b61b34d45b830c656a68adadcc650e9014b56fc1f1be281 | Python | 745 | 23 | import pandas as pd
import pytest
from data_profiling.model.pandas.describe_categorical_pandas import word_summary_vc
value_counts_w_words = pd.Series(index=["The dog", "is hungry"], data=[2, 1])
def test_word_summary_vc():
assert (
word_summary_vc(vc=value_counts_w_words)["word_counts"].to_dict()
... |
f9ebe552ef58b0739d484e064be5d4384ce9eb7108cfb5aea483ad2f27fd0746 | Python | 745 | 29 | import copy
class EarlyStopping(object):
def __init__(self, patience=10):
self.patience = patience
self.best = None
self.num_bad_epochs = 0
self.best_model = None
def stop_training(self, measure, model):
if self.best is None:
self.best = measure
... |
abc08d1593a2f8b50d9311a684bcc15fe23e21bde4962dbe741ad144127227bd | Python | 746 | 38 | from .initializers import (
variance_scaling,
lecun_normal,
lecun_uniform,
glorot_normal,
glorot_uniform,
he_normal,
he_uniform,
value_pad,
)
from .modules import (
Linear,
Conv,
Conv1d,
Conv2d,
Conv3d,
Sequential,
NoGradLayer,
filter_grad,
filter_vjp,... |
e668a99e087eb8e966daafe89478384a58c86254a0a5eb13e495142240f96fd6 | Python | 746 | 20 | import csv
import code
# code.interact(local=dict(globals(), **locals()))
import os
file = "score_sum_indiv.profile"
dir, _ = os.path.split(file)
with open(file, 'r') as f, open(file + '.reformat', 'wt', newline='') as f2, open(os.path.join(dir, "PRS_MetS_noUKB.csv"), 'wt', newline='') as f3:
reader = csv.reader(... |
8adda091c013e011479fb4ebd908e1f90c984676a2e7ed40e5f3964bb8cc90cc | Python | 748 | 24 | import os
from PIL import Image
ref_path = (
"ref_data/qc/sub-01_space-cropT1w_desc-subfields_atlas-multihist7_volumes.png"
)
new_path = "/mnt/test_out/sub-01/qc/sub-01_space-cropT1w_desc-subfields_atlas-multihist7_volumes.png"
out_path = "sub-01_qc_comparison.png"
if not os.path.exists(ref_path):
raise File... |
bad7b25790edf91f89e9276cc6e657bc91ab3dd9f081cb6a0819f9c877662d00 | Python | 749 | 25 | __version__ = '0.0.1rc2'
short_version = __version__
def parse_version_info(version_str):
"""Parse a version string into a tuple.
Args:
version_str (str): The version string.
Returns:
tuple[int | str]: The version info, e.g., "1.3.0" is parsed into
(1, 3, 0), and "2.0.0rc1" is... |
e5799e9395ec418397086e873b06b011e91cddc620cb7346e8ff81bfda2ff043 | Python | 749 | 28 | import numpy as np
import pandas as pd
from data_profiling import ProfileReport
def test_urls(get_data_file):
file_name = get_data_file(
"whitelist_urls.csv",
"https://raw.githubusercontent.com/openeventdata/scraper/master/whitelist_urls.csv",
)
df = pd.read_csv(
file_name, heade... |
214b57d584f3ab3c104ca32e011b46555994198a9323fb60924477e112c09bf1 | Python | 750 | 23 | import kipoi
import numpy as np
example_input = "./downloaded/example_files/input_file"
example_expr = "./downloaded/example_files/expr_file"
#DataLoader = kipoi.get_dataloader_factory(".", source="dir")
#print(DataLoader(example_input, example_expr).__getitem__(1))
model = kipoi.get_model(".", source="dir")
predict... |
3635bcdf99ee291d017b52a2a3f41d22ee2659c95de5a8b15b0e3caf68e05d9a | Python | 750 | 28 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open("README.rst", encoding='utf-8') as f:
readme = f.read()
with open("LICENSE") as f:
license = f.read()
with open("requirements.txt", "r") as f:
required = f.read().splitlines()
setup(
name="deepinterpolation",
version... |
4d15d966f531e9fdda14b700e94e2f35cf36e3c28b19a849e6481d4d2a2ad073 | Python | 750 | 22 | # Modified from https://github.com/open-mmlab/mmdetection/tree/3.x/
"""Collecting some commonly used type hint in lqit."""
from typing import List, Optional, Sequence, Tuple, Union
from mmengine.config import ConfigDict
from mmengine.structures import InstanceData, PixelData
# TODO: Need to avoid circular import with... |
57955e80f1e94b745fb46459f98d042057e2413f7791a47233c7f3426d17504a | Python | 750 | 20 | import ray._private.ray_constants as ray_constants
RUNTIME_ENV_RETRY_TIMES = ray_constants.env_integer("RUNTIME_ENV_RETRY_TIMES", 3)
RUNTIME_ENV_RETRY_INTERVAL_MS = ray_constants.env_integer(
"RUNTIME_ENV_RETRY_INTERVAL_MS", 1000
)
# Cache TTL for bad runtime env. After this time, delete the cache and retry to c... |
aa609c21a46548ac198cbd68358a41762a6a6c4b2b122c279ca9cdcbbf2c4acc | Python | 751 | 31 | from dataclasses import dataclass
import numpy as np
from .node import NIRNode
@dataclass(eq=False)
class SumPool2d(NIRNode):
"""Sum pooling layer in 2d."""
kernel_size: np.ndarray # (Height, Width)
stride: np.ndarray # (Height, width)
padding: np.ndarray # (Height, width)
def __post_init__... |
c273a6b3720fcdb667d1f6f80e8eec1acdce76d1b350e09b94b42563a68f5fc0 | Python | 751 | 12 | from ..miners.angular_miner import AngularMiner
from ..miners.base_miner import BaseMiner, BaseSubsetBatchMiner, BaseTupleMiner
from ..miners.batch_easy_hard_miner import BatchEasyHardMiner
from ..miners.batch_hard_miner import BatchHardMiner
from ..miners.distance_weighted_miner import DistanceWeightedMiner
from ..min... |
862594cc4457ce92dbf0742c25d93da5a5e7d43b5c2591ddd04efb4bd9db406f | Python | 752 | 20 | import csv
import code
# code.interact(local=dict(globals(), **locals()))
import os
file = "score_sum_indiv.profile"
dir, _ = os.path.split(file)
with open(file, 'r') as f, open(file + '.reformat', 'wt', newline='') as f2, open(os.path.join(dir, "PRS_MetS_noUKB.KoGES.csv"), 'wt', newline='') as f3:
reader = csv.r... |
349e140ca3298a061a5bb7fd43340c35171e1eefbd340ef19672c61c388b63e4 | Python | 753 | 23 | import nibabel as nib
import numpy as np
from scipy.stats import mode
# Load input NIfTI files
nii_files = snakemake.input
nii_images = [nib.load(f) for f in nii_files]
nii_data = [img.get_fdata() for img in nii_images]
# Ensure all images have the same shape
shape = nii_data[0].shape
if not all(img.shape == shape fo... |
34e6bd39ac89d58a082281879c3da464b7fe2534182302120d3985aff6575ff2 | Python | 753 | 33 | import tomlkit
import os
import subprocess
from conf_build import VERSION
file_path = "../pyproject.toml"
# read pyproject.toml
with open(file_path, 'r') as file:
toml_content = file.read()
# parse toml content
parsed_toml = tomlkit.parse(toml_content)
# update value
parsed_toml['project']['version'] = VERSION
... |
1bd2838b0f4790de224b3bff8a4e1d3ada001a88fe18f6e85a4c0f5e260cd393 | Python | 756 | 23 | import numpy as np
import torch
def _as_numpy_recursive(x):
if isinstance(x, torch.Tensor):
return x.detach().cpu().numpy()
if isinstance(x, list) or isinstance(x, tuple):
return np.asarray([_as_numpy_recursive(y) for y in x])
return x
def torch_assert_allclose(actual, desired, *args, **... |
33900ac9da83486dda79c340944325c451159a3a7c20a390f3aedbeb04d787f1 | Python | 756 | 35 | # __serve_example_begin__
import time
from ray import serve
from typing import Any
@serve.deployment(num_replicas=3)
class TextProcessor:
"""A simple text processing deployment that can be scaled externally."""
def __init__(self):
self.request_count = 0
def __call__(self, text: Any) -> dict:
... |
6065738258c6ad4f27f5613f56ec93b550911b52978dec7f838220ceab411b2a | Python | 756 | 20 | from DWonder.RMBG.model_3DUnet import UNet3D
import torch.nn as nn
class Network_3D_Unet(nn.Module):
def __init__(self, UNet_type = '3DUNet', in_channels=1, out_channels=1, f_maps=64, final_sigmoid = True):
super(Network_3D_Unet, self).__init__()
self.in_channels = in_channels
self.out_cha... |
a9ba7b8a457e4b20c1423165e7f81cca5db4ffd8fcfea5974f1df3416d373e9e | Python | 756 | 19 | import torch
from torch import distributions as dists
def mode_of_distribution(distrib):
assert isinstance(distrib, dists.Distribution)
if isinstance(distrib, dists.Categorical):
return distrib.probs.argmax(dim=-1)
elif isinstance(distrib, (dists.Normal, dists.MultivariateNormal)):
return ... |
5d25b7ec62189c072352744b942026409cb4994f53fe266cb1ee134282db4e53 | Python | 757 | 10 | from agent.data.entities.config import TRAIN_ITEM_FILTER, TEST_ITEM_FILTER, TRAIN_LABEL, TEST_LABEL
from agent.classifiers.data.count_features_fd_dataset_mgmt import get_datasets_from_filter, get_raw_datasets_from_filter
def get_datasets(review_level=9, binary_classifier=True, val_split=0.8):
return get_datasets_f... |
e70f0219a0884f1ac2b48bd9cee83b39a0067ce383e13b96df083007f40bcd32 | Python | 757 | 25 | from neuron_morphology.validation.result import NodeValidationError as ve
from neuron_morphology.constants import *
def validate_distance_between_connected_nodes(morphology):
result = []
for compartment in morphology.compartments:
node1 = compartment[0]
node2 = compartment[1]
if node1... |
5339cf242974aa63a5171af2bd8536f9dca181d49a878dc5829c4f4bd96b5401 | Python | 758 | 17 | # This file is part of the INTREPPPID programme.
# Copyright (c) 2023 Joseph Szymborski.
#
# This programme is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3.
#
# This programme is distributed i... |
ec2d25580e616535d885e2893fa63ad26c8dc1ab4bf39295e2abee04bc3538bf | Python | 758 | 17 | """Vendored UCE — Universal Cell Embeddings.
Source: https://github.com/snap-stanford/UCE (Rosen, Roohani, Leskovec et al.,
Stanford University). Copied into omicverse because upstream ships no package on
PyPI; the inference path is used by :mod:`omicverse.llm.uce_model`.
Upstream is MIT-licensed; the license is carr... |
b2ccc22f460fe76cab1a9f4e0ecf9652ca275682f027c344951b5f42a4d4c2ee | Python | 759 | 30 | import sys
import click
from ci.ray_ci.utils import ci_init, filter_tests
@click.command()
@click.option(
"--prefix", required=True, type=click.Choice(["darwin:", "linux:", "windows:"])
)
@click.option("--state_filter", required=True, type=click.Choice(["flaky", "-flaky"]))
def main(prefix: str, state_filter: s... |
4ec05ee7b87800d1b4555b17da4ab071290c1a9892b13c232b3d8c1fa14ed925 | Python | 760 | 24 | from pathlib import Path
import pandas as pd
from data_profiling import ProfileReport
from data_profiling.utils.cache import cache_file
if __name__ == "__main__":
file_name = cache_file(
"vektis_postcodes.csv",
"https://www.vektis.nl/uploads/Docs%20per%20pagina/Open%20Data%20Bestanden/2017/Vektis... |
6e49056a3ffe6133f4600c3e7b1b99999f974f59da21225521212c4980f70379 | Python | 761 | 29 | from dataclasses import dataclass, field
from typing import Any, Dict, Optional
import numpy as np
from .node import NIRNode
@dataclass(eq=False)
class Threshold(NIRNode):
r"""Threshold node.
This node implements the heaviside step function:
.. math::
z = \begin{cases}
1 & v > v_{t... |
0480fe4d66f71b08cc864598b8c4869941292d85556516597e68c4a7da8a5a22 | Python | 762 | 25 | import os
import subprocess
from ci.ray_ci.bisect.validator import Validator
from ray_release.bazel import bazel_runfile
from ray_release.test import Test
TEST_SCRIPT = "ci/ray_ci/bisect/macos_validator.sh"
class MacOSValidator(Validator):
def run(self, test: Test, revision: str) -> bool:
env = os.envi... |
47c11b3d26bc7a3e0bd43fda4c176fbc4e0e288c1bed4a8c3be2330bf5f0fe29 | Python | 762 | 31 | import tempfile
import shutil
import os
from os.path import *
from glob import glob
tdir = tempfile.mkdtemp(prefix='ngs_mappertests',suffix='package')
before = []
def setUpPackage():
global before
os.chdir(tdir)
vpath = join(tdir, '.venv')
before = glob( '/dev/shm/*' )# + glob( '/tmp/*' )
def tearDow... |
c51973ae4915307ac020c1695b2aa3e7ec962c6b1836ca866625da93e4ad3661 | Python | 762 | 29 | import requests
from starlette.requests import Request
from typing import Dict
from transformers import pipeline
from ray import serve
# 1: Wrap the pretrained sentiment analysis model in a Serve deployment.
@serve.deployment
class SentimentAnalysisDeployment:
def __init__(self):
self._model = pipeline(... |
4ef3173b0e7618bfa891114d7ea3418d82970885bb1521bfa2aa60392dc0c42d | Python | 764 | 20 | from .model_3DUnet import UNet3D
import torch.nn as nn
class Network_3D_Unet(nn.Module):
def __init__(self, UNet_type = '3DUNet', in_channels=1, out_channels=1, f_maps=64, final_sigmoid = True):
super(Network_3D_Unet, self).__init__()
self.in_channels = in_channels
self.out_channel... |
8e4446c9fe131e5ccd19d7893c6d0ac3202e0605d5994cf8472891c1c1ef4ab4 | Python | 764 | 26 | from lib.surface import (
read_metric_from_gii,
read_surface_from_gifti,
write_surface_to_gifti,
)
surface, metadata = read_surface_from_gifti(snakemake.input.surf_gii)
ap = read_metric_from_gii(snakemake.input.coords_AP)
pd = read_metric_from_gii(snakemake.input.coords_PD)
pd_flip = 1.0 if snakemake.wild... |
d4d447377d747a97bc1f000c849bead145850e71ea046c49202f19dd1033320d | Python | 764 | 23 | import numpy as np
import pandas as pd
import pyranges as pr
def annotate(df, genes):
gr = pr.PyRanges(df)
return gr.nearest(genes)
df = pd.read_csv("associations.csv", index_col=0)
df['Chromosome'] = df.chr.values
df["Start"] = df.pos.values
df["End"] = df.pos.values
genes = pd.read_csv("ensemble_hg38_biom... |
0177fad48b902287aa55dc6b96f52c6d4add3ab2788fb35e616d2bb8fe26f775 | Python | 765 | 29 | """
Test for issue 545:
https://github.com/Data-Centric-AI-Community/data-profiling/issues/545
"""
from pathlib import Path
import pandas as pd
import pytest
from data_profiling import ProfileReport
from data_profiling.utils.compat import pandas_version_info
@pytest.mark.skipif(
pandas_version_i... |
367dd495b434024cea16d5f7715a267e5d63378d32c3c91838e076e938978fe6 | Python | 765 | 27 | """
Test for issue 1631:
https://github.com/Data-Centric-AI-Community/data-profiling/issues/1631
"""
import pandas as pd
from data_profiling import ProfileReport
def test_issue1631(test_output_dir):
data = {
"value": [1, 2, 3, 4],
"datetime": [
"2022-10-01 00:10:00",
"2022... |
925a2d42727973eb410c928779a4402ca47496cc132c6ad73b2fd8e2aac9c2e3 | Python | 765 | 45 | """Different prompts used for LLMs
Note: When changing the prompt, some tests may start to fail because they check
the predictions using the default prompts.
"""
DELIM = "```"
DEFAULT_PROMPT_ZERO_SHOT = f"""You are a text classification assistant.
The text to classify:
{DELIM}
{{text}}
{DELIM}
Choose the label ... |
48ebe75651b370fa56965aba6b4a1a632ad19e4075a9f82bf5531dda85f7526f | Python | 766 | 30 |
from dataclasses import dataclass, field
from typing import List
import numpy as np
from aptnn.box import Box
@dataclass
class Atom:
symbol: str
position: np.ndarray
velocity: np.ndarray = field(default=None)
apt: np.ndarray = field(default=None)
apt_total_std_norm: float = field(default=None)
... |
8bc6e0e99e6298c3054ec61388261d9050b540f2e28ac1752f185a4411a85f0d | Python | 766 | 33 | import os
from datetime import datetime
import argparse
import traceback
import numpy as np
import torch
import sys
from mpi4py import MPI
from aptnn.committee import CommitteeAPTNN
from aptnn.box import Box
def load_committee_aptnn(aptnn_file):
net = CommitteeAPTNN(committee_size=None, model_parameters=None)
... |
df64b7f6d63b1b1e2524cb33a6df10afeb3c5cc14fc2d5ed8d47d7be334d17c5 | Python | 767 | 18 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#... |
1da0c6d52e8f718d90ff69e95442da34e2f531f359823da57072a08aab49d4c3 | Python | 768 | 18 | """Training optimizers with the historical embedding-gradient semantics."""
import keras
import tensorflow as tf
@keras.saving.register_keras_serializable(package="Mothra")
class DeduplicatingAdam(keras.optimizers.Adam):
"""Sum repeated embedding indices before Adam's second-moment update.
Keras 2's Optimize... |
702eda1008a7e23394f1e68f79926a1ed9815a1daa404994753c5ce7df7dcb2d | Python | 768 | 19 | #!/usr/bin/env python
# coding: utf-8
from tensorflow.keras.regularizers import l2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import (Dense, Dropout, GRU)
import warnings
import os
warnings.filterwarnings('ignore')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # or any {'0', '1', '2'}
def ... |
1dae6bac9fb8f85b382fa6e06ab6eab3f67a24b343d6dc19323180c13138d295 | Python | 769 | 28 | import gym
import gym.spaces
import numpy as np
class NormalizeActionSpace(gym.ActionWrapper):
"""Normalize a Box action space to [-1, 1]^n."""
def __init__(self, env):
super().__init__(env)
assert isinstance(env.action_space, gym.spaces.Box)
self.action_space = gym.spaces.Box(
... |
3f48d867ac35e3c72ee4731090b73a3418430f5314471edc6106c50e08c9548d | Python | 769 | 23 | try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
try:
from subprocess import check_output
except ImportError:
import subprocess
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not al... |
9e93d71f49c7cb1da24c8af60c4534fc66727d5649f9cabb74f09ef5d5600e20 | Python | 769 | 20 | import torch
from torch.nn import Module
from transformers import Wav2Vec2Model
import torch.nn as nn
class Model(Module):
def __init__(self):
super().__init__()
self.alphabet = [ "N", "A", "C", "G", "T" ]
self.sub_model = Wav2Vec2Model.from_pretrained('facebook/wav2vec2-base')
for ... |
be16a48c77f7ed44fc8df408f3aa164e835e26246ee00306a975056ab9f268dc | Python | 769 | 10 | from agent.data.entities.config import TRAIN_ITEM_FILTER, CTT3FR_ITEM_FILTER, TRAIN_LABEL, CTT3FR_LABEL
from agent.classifiers.data.count_features_fd_dataset_mgmt import get_datasets_from_filter, get_raw_datasets_from_filter
def get_datasets(review_level=9, binary_classifier=True, val_split=0.8):
return get_datase... |
532fb1da82e9e4effe4e38dc44f345093b57740b1b81a7d4336c793f707a02d7 | Python | 770 | 30 | import os
import ray
from ray._raylet import GcsClient
from ray.dashboard.modules.job.job_manager import JobManager
TEST_NAMESPACE = "jobs_test_namespace"
def create_ray_cluster(_tracing_startup_hook=None):
return ray.init(
num_cpus=16,
num_gpus=1,
resources={"Custom": 1},
namesp... |
8776d949d99b037c5e15651fb47396c4190993886906ed1faa27f052a7fec7c6 | Python | 770 | 30 | """Shared message runtime for JARVIS channel adapters."""
from .execution_adapter import AgentBridgeExecutionAdapter, ExecutionAdapter, ExecutionCallbacks
from .models import (
ConversationRoute,
DeliveryEvent,
MessageEnvelope,
PolicyDecision,
RuntimeTaskState,
)
from .policy import MessagePolicy
f... |
ef81d6bb1d699bfa183e8c46054ca34b3585feb34015e8ade883c689cb647082 | Python | 771 | 22 | import argparse
import time
import math
import os
import copy
import sys
import torch
import torch.onnx
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import numpy as np
import logging
smnist_dataset_path = "./MNIST/"
traindataset = torchvision.dataset... |
fd9acbe7c743b3afa1f6b497d571cbea0b0591782782895a0f359fbc75d06bc7 | Python | 771 | 14 | from pfrl.nn.atari_cnn import LargeAtariCNN # NOQA
from pfrl.nn.atari_cnn import SmallAtariCNN # NOQA
from pfrl.nn.bound_by_tanh import BoundByTanh # NOQA
from pfrl.nn.branched import Branched # NOQA
from pfrl.nn.concat_obs_and_action import ConcatObsAndAction # NOQA
from pfrl.nn.empirical_normalization import Emp... |
8e8c79277e57f2aad03ac5b8f4382fbe9a38eb16d88dc7967fb37b5673ff3f68 | Python | 772 | 17 | # This file is part of the INTREPPPID programme.
# Copyright (c) 2023 Joseph Szymborski.
#
# This programme is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3.
#
# This programme is distributed i... |
b27b03547c30fe9fd937036eeafc3486a968090f303cae0466c642ae0e085442 | Python | 772 | 27 | import json
import pickle as pkl
from datetime import datetime
from os.path import join
from pathlib import Path
from typing import Dict, Any
def load_json_file(file_path: str) -> Dict:
with open(file_path, 'r') as f:
file = json.load(f)
return file
def load_pickle(file_path: str) -> None:
with op... |
bdd58e564fba38c8cc348d1e1545aa1ab0d769d1337cadd1ae1a92afa902575f | Python | 772 | 10 | from agent.data.entities.config import TRAIN_ITEM_FILTER, CTT3_TEST_ITEM_FILTER, TRAIN_LABEL, CTT3_LABEL
from agent.classifiers.data.count_features_fd_dataset_mgmt import get_datasets_from_filter, get_raw_datasets_from_filter
def get_datasets(review_level=9, binary_classifier=True, val_split=0.8):
return get_datas... |
15cd3f1d50beddf510fc438def4ed58241526154aca9f712ac5b0741b6ce914a | Python | 773 | 32 | """
Scores ItemRendered class
"""
from typing import Any, Dict, List, Optional
from data_profiling.config import Style
from data_profiling.report.presentation.core.item_renderer import ItemRenderer
class Scores(ItemRenderer):
def __init__(
self,
items: List[Dict],
overall_score: float... |
285858ab9dce7055f63a5dff3a6189a999b0620ee31e1e4b0884b35b493d95a3 | Python | 774 | 27 | from setuptools import setup, find_packages
setup(
name='k4a',
version='0.0.2',
author='Jonathan Santos',
author_email='jonsanto@microsoft.com',
description='Python interface to Azure Kinect API.',
keywords=['k4a', 'Azure Kinect', 'Kinect for Azure'],
url='https://github.com/JonathanESantos... |
dba29844bc7e0e3b4ef2cc8fed66432ad4e355cd439b08217de0a4dd8f020816 | Python | 775 | 28 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import annotations
import logging
def get_flops_profile(model, input_data, verbose: bool = False):
try:
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.