sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
2250af62697cc37c1733d1b15bbc77fecd7547f3eb2712fd47b0e0cbde5c6ff9 | Python | 613 | 31 | # __cgraph_visualize_start__
import ray
from ray.dag import InputNode, MultiOutputNode
@ray.remote
class Worker:
def inc(self, x):
return x + 1
def double(self, x):
return x * 2
def echo(self, x):
return x
sender1 = Worker.remote()
sender2 = Worker.remote()
receiver = Worker.re... |
3e0fb5cf879ef8b68a70bb0b6219a3cb198d66f7afa77f835941df8a4f3b7765 | Python | 614 | 24 | # ---- voxelmorph ----
# unsupervised learning for image registration
from . import generators
from . import py
from .py.utils import default_unet_features
# import backend-dependent submodules
backend = py.utils.get_backend()
if backend == 'pytorch':
# the pytorch backend can be enabled by setting the VXM_BAC... |
d43c573c3b8d04b2808f041b8a772ec5aa812739f14f8bab3ca4dd1d3a98e388 | Python | 615 | 18 | import pandas as pd
from data_profiling.model.pandas.imbalance_pandas import column_imbalance_score
def test_column_imbalance_score_many_classes():
value_counts = pd.Series([10, 20, 60, 10])
assert column_imbalance_score(value_counts, len(value_counts)).round(2) == 0.21
def test_column_imbalance_score_unif... |
657fe0d5d451225ef50ed97ed496a73166ea0b045b12f6b948d8fe5a8f97751b | Python | 616 | 17 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from django.db.models.signals import post_save
from django.dispatch import receiver
from cvat.apps.consensus.models import ConsensusSettings
from cvat.apps.engine.models import Task
@receiver(post_save, sender=Task)
def __save_task__initialize_con... |
980e388a430d9a3e9094ccbf9b9a0390ff16868b94a5ce22113db7e1416d4c91 | Python | 616 | 19 | from ray.job_submission import JobSubmissionClient
client = JobSubmissionClient("http://127.0.0.1:8265")
kick_off_xgboost_benchmark = (
# Clone ray. If ray is already present, don't clone again.
"git clone https://github.com/ray-project/ray || true; "
# Run the benchmark.
"python ray/release/train_tes... |
eb5ae0bb335ed1932ec8e91482c4b41542f6d745622f1f1e4f11b545f7737f63 | Python | 616 | 18 | import skein
import sys
from urllib.parse import urlparse
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python dashboard.py <dashboard-address>")
sys.exit(1)
address = sys.argv[1]
# Check if the address is a valid URL
result = urlparse(address)
if not all([result.sc... |
44808ba42ad3d2c79c3feb3348f498b81af2ee19130d51b4e79c9bb070f62bc2 | Python | 617 | 23 | import numpy as np
import pyarrow
from ray.data.block import BlockAccessor
from ray.data.datasource.file_datasink import BlockBasedFileDatasink
class NumpyDatasink(BlockBasedFileDatasink):
def __init__(
self,
path: str,
column: str,
*,
file_format: str = "npy",
**f... |
026d632f1e0ae957a77f0bfcfc1e9f677c09c43586be5b7fdef5eb261a80072d | Python | 618 | 22 | # Generated by Django 4.1.6 on 2023-02-06 04:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("infer", "0007_ppidatabase_version"),
]
operations = [
migrations.AlterField(
model_name="dataset",
name="negatives_pa... |
1b2970e8336759c3b870489f271062e69581b63876cb25b18d97cbfba60fca5d | Python | 618 | 24 | import logging
import sys
# Import asyncio timeout depends on python version
if sys.version_info >= (3, 11):
from asyncio import timeout as asyncio_timeout
else:
from async_timeout import timeout as asyncio_timeout
logger = logging.getLogger(__name__)
async def http_get(http_session, url, timeout_seconds=6... |
4974352f56d0c1401d893aeda6824791847a05bf1198d66554358d8e475b567c | Python | 618 | 22 | import configparser
from os.path import isfile, join
from config import ROOT_DIR
def get_config(config_file, logger):
config = configparser.ConfigParser()
configFile = join(ROOT_DIR, config_file)
logger.info(f'The path of the configure file is {configFile}')
assert isfile(configFile)
config.read(c... |
81518ed946504ef0f75fe17cb1a07f51d58c0550eca662a31c2e69d38756261a | Python | 620 | 18 | import numpy as np
import pandas as pd
from siapy.features.spectral_indices import compute_spectral_indices
# --8<-- [start:map]
# Data with custom column names
custom_data = pd.DataFrame(
{"red_band": np.random.random(100), "green_band": np.random.random(100), "nir_band": np.random.random(100)}
)
# Map custom n... |
d5843baee7dc766a8afcef1181a31895ed95bbccc550da3154cd9f435cca761d | Python | 620 | 15 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""High level analog tiles."""
# Convenience imports for easier access to the classes.
from aihwkit.simulator.tiles.analog import AnalogTile
from aihwkit.simul... |
85578fd7517e7c633bc9ca236a4ab4042b8f29b90bb3352f9e386e133326f18d | Python | 621 | 17 | import numpy
import scipy.stats
def confidence_interval(data, confidence=0.95):
mean = numpy.mean(data)
n = len(data)
sem = scipy.stats.sem(data)
confidence_interval = scipy.stats.t.interval(confidence, n-1,mean, scale=sem)
return mean, *confidence_interval
def prediction_interval(data,confidence... |
48f9d767f76a352c617e98eaac15d191be0782d747167e9723691daf81023423 | Python | 622 | 21 | """Initializes the weights and biases of a layer to chainer default.
"""
import torch
import torch.nn as nn
from pfrl.initializers.lecun_normal import init_lecun_normal
@torch.no_grad()
def init_chainer_default(layer):
"""Initializes the layer with the chainer default.
weights with LeCunNormal(scale=1.0) and... |
81e1db82cfd8950bdefcf2d3e84fbf5eb21f1e6bd7cd07baed57a879d1d258f9 | Python | 622 | 21 | """Pure-Python implementation of the SuperCell algorithm.
Reference
---------
Bilous et al., *Metacells untangle large and complex single-cell transcriptome
networks*. BMC Bioinformatics 23, 336 (2022).
https://doi.org/10.1186/s12859-022-04861-1
Original R implementation: https://github.com/GfellerLab/SuperCell
This... |
cbcd55245fddadcfd085fc8a5aae780c6bbd4332afff9836b87cff5552daef83 | Python | 622 | 15 | from models.DeepLab.modeling.backbone import resnet, xception, drn, mobilenet
def build_backbone(backbone, output_stride, BatchNorm):
if backbone == 'resnet101':
return resnet.ResNet101(output_stride, BatchNorm)
elif backbone == 'resnet50':
return resnet.ResNet50(output_stride, BatchNorm)
e... |
a89d8b0dab68977ed1297cd0e73ebfdb6cbc4f32a170cdaaa73781ce389dc503 | Python | 623 | 30 | #!/usr/bin/env python
import sys
def log(msg):
print(msg, file=sys.stderr)
numbers = list()
for i, line in enumerate(sys.stdin):
for j in line.split():
try:
x = int(j)
numbers.append(x)
except:
log("Error parsing line {}: {}".format(i, line))
if len(number... |
0da9611794ad2e81a610cc97899d59068b73fbe145a4db8812552c9fb18b4575 | Python | 625 | 19 | '''
Running intitial segmentations in FSL FAST on upsampled UNI image cropped to sphere.
'''
import subprocess
SUBS = ['sub-09']
DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives'
for sub in SUBS:
command = 'fast '
command += '-t 1 -n 3 -H 0.1 -I 4 -l 20.0 '
command ... |
9a41440f6adcaae581492d7131dc4566c5653090a947953fd2591d6c746961f2 | Python | 625 | 23 | import pyranges as pr
import snakemake
gr = pr.read_gtf(snakemake.input["gtf_file"])
gr = gr[(gr.Feature == "gene") & (gr.gene_type == "protein_coding")]
df_genes = gr.df
df_genes["gene_id_orig"] = df_genes["gene_id"]
df_genes["PAR_Y"] = df_genes["gene_id"].apply(lambda x: "PAR_Y" in x)
df_genes = df_genes[df_genes["... |
bc5c088bf8fd41046c7a26037021d27ca39cff7eea94c6ca9e759c3700d41cad | Python | 625 | 24 | from typing import TYPE_CHECKING
from ray.data._internal.arrow_block import ArrowBlockBuilder
from ray.data.datasource.file_based_datasource import FileBasedDatasource
if TYPE_CHECKING:
import pyarrow
class BinaryDatasource(FileBasedDatasource):
"""Binary datasource, for reading and writing binary files."""... |
6f606da92359e0118b3adc03d501bd5116b8aabbb896004c0de609a2b5c1923b | Python | 626 | 24 | KEEP_COLs = ["responseN",
"participant",
"blockOrder",
"age",
"sex",
"date",
"frameRate",
"imageFile",
"trials.thisN",
"index"
"trials.thisIndex",
"blocks.thisN",
"... |
b5b3a998561afd20ecf3e02ca596526795120fd96c97639716f42288203bcfc9 | Python | 626 | 20 | import importlib
def __getattr__(name):
cnmf_module = importlib.import_module("..external.cnmf.cnmf", __package__)
if hasattr(cnmf_module, name):
value = getattr(cnmf_module, name)
globals()[name] = value
return value
if name == "Hotspot":
from ..external.hotspot import Hot... |
bb49cfa33b14349c419f328a74d3c8a63f18db43f78d641cb6bc6dc4acf38fa3 | Python | 626 | 23 | import requests
from fastapi import FastAPI
from ray import serve
# 1: Define a FastAPI app and wrap it in a deployment with a route handler.
app = FastAPI()
@serve.deployment
@serve.ingress(app)
class FastAPIDeployment:
# FastAPI will automatically parse the HTTP request for us.
@app.get("/hello")
def s... |
451cf354febaaee9d49e4d24299edeefbeb22302d24754249022403382bc4254 | Python | 627 | 11 | # Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software... |
a6ece0641e11b00e7ff78baef4777126d53dbe9150f24fc9cc361d33b9817ae1 | Python | 627 | 33 | """
AVA: Autoencoded Vocal Analysis
Contents
--------
::
ava
│
├── data
│ └── data_container
├── models
│ ├── vae_dataset
│ ├── vae
│ └── window_vae_dataset
├── plotting
│ ├── grid_plot
│ ├── latent_projection
│ ├── mmd_plots
│ ├── shotgun_movie
│ └── tooltip_plot
├── preprocessing
│ ├── preprocess
... |
ac2da86a8bda172b2cb039e691b70483c490f4e982e9ea2bcd71c062ce7a83fc | Python | 627 | 13 | from exputils.misc.misc import numpy_vstack_2d_default
from exputils.misc.misc import replace_str_from_dict
from exputils.misc.misc import do_subdict_boolean_filtering
from exputils.misc.misc import get_dict_variable
from exputils.misc.misc import str_to_slices
from exputils.misc.misc import list_equal
from exputils.mi... |
4cdafad3f7ca20c155027dea763b339e28a2008ec7c3b6ef0e6ed6875bf8aa8b | Python | 628 | 26 | """
Test for issue 664:
https://github.com/Data-Centric-AI-Community/data-profiling/issues/664
"""
import numpy as np
import pandas as pd
from data_profiling import ProfileReport
def test_issue664():
n = 10000
df = pd.DataFrame({"a": [np.nan] * n, "b": ["b"] * n, "c": [pd.NaT] * n})
df = df.fillna(value=... |
bf3391be5776fb3944a86a52e7d3412cac4f9438a3cd8ac8e07264b2c165bdeb | Python | 628 | 19 | from typing import Optional
from ray._raylet import GcsClient, NodeID
class HealthChecker:
def __init__(self, gcs_client: GcsClient, local_node_id: Optional[NodeID] = None):
self._gcs_client = gcs_client
self._local_node_id = local_node_id
async def check_local_raylet_liveness(self) -> bool:... |
31c60c7371c170d9f91d2baafaeb956475aec71199b6ad9e5fb07f5051ce3612 | Python | 630 | 18 | from dataclasses import dataclass
# Version 0 -> 1: Added log streaming and changed behavior of job logs cli.
# Version 1 -> 2: - Renamed job_id to submission_id.
# - Changed list_jobs sdk/cli/api to return a list
# instead of a dictionary.
# Version 2 -> 3: - Added optional fields en... |
71be3d1cee0d0eafab8ccb051bab2bf5f25a72b3e91cf2d70fd90c68852589f2 | Python | 630 | 25 | from typing import Tuple
from pyspark.sql import DataFrame
from data_profiling.config import Settings
def describe_text_1d_spark(
config: Settings, df: DataFrame, summary: dict
) -> Tuple[Settings, DataFrame, dict]:
"""Describe a categorical series.
Args:
series: The Series to describe.
... |
9ee814781dae411bed866d8d1f5a54d7dcce731fb9c438d3156b2427f350edfc | Python | 630 | 20 | import sys
file_path = sys.argv[1]
current_metrics_dict = {}
with open(file_path) as my_file:
header_line = my_file.readline()
for line in my_file:
line_items = line.rstrip("\n").split("\t")
current_metrics_dict[line_items[0]] = float(line_items[1])
current_metrics_dict["f1"] = 2 * (cur... |
b5fe075d2f6ef84481ab53810987a41e88ab06c756a0e600a994fa509dd23a2c | Python | 630 | 17 | from sklearn.model_selection import RepeatedKFold
from siapy.optimizers.scorers import Scorer
# Basic cross-validation scorer
cv_scorer = Scorer.init_cross_validator_scorer(scoring="accuracy", cv=5)
# Advanced cross-validation with custom CV strategy
repeated_cv = RepeatedKFold(n_splits=3, n_repeats=5, random_state=... |
63966a2be266c47f92f51beb07cd33df67739dbbf4c8be1856c5ca6719ac00ea | Python | 631 | 20 | import pandas as pd
from sklearn.datasets import make_classification
from siapy.features import AutoFeatClassification
# Generate sample data
X, y = make_classification(n_samples=200, n_features=5, random_state=42)
data = pd.DataFrame(X, columns=[f"f{i}" for i in range(5)])
target = pd.Series(y)
# Create and configu... |
484fc9e4bffa7657ba2a3cb6028f64d938d5becba1e636f204f06a8269c19c73 | Python | 632 | 19 | import numpy as np
from luminance_analysis import PooledData
from luminance_analysis.utilities import reliability
def load_pooled_dataset(path, resp_threshold=None, nanfraction_thr=0.15):
pooled_data = PooledData(path)
# Load stimulation arrays and traces
stim = pooled_data.stimarray_rep
traces = poo... |
4c518b87f4a4454276b0ade52cf4310fd755f783828e2d244aba3640118c7099 | Python | 632 | 21 | from setuptools import setup, find_packages
from NeuroMotion import __version__
def fetch_requirements():
with open("requirements.txt", "r", encoding="utf-8", errors="ignore") as f:
reqs = f.read().strip().split("\n")
return reqs
setup(
name='NeuroMotion',
version=__version__,
author='Shi... |
f9e56e9043630051e96ebd258bad1b715750fc9554678290e63166fb5c203b04 | Python | 633 | 21 | """
OmicVerse Jarvis — multi-channel bot bridge for mobile single-cell analysis.
Launch via::
omicverse jarvis --channel telegram --token BOT_TOKEN
or for Feishu mode::
omicverse jarvis --channel feishu --feishu-app-id APP_ID --feishu-app-secret APP_SECRET --feishu-connection-mode websocket
or for iMessage... |
f4db6c084cf111c39db1818eeb62476d3b4b3f5f1bef29385a63dec8dabbf4d8 | Python | 634 | 17 | from exputils.io.numpy import load_numpy_files
from exputils.io.numpy import save_dict_to_numpy_files
from exputils.io.general import makedirs
from exputils.io.general import makedirs_for_file
from exputils.io.odsreader import ODSReader
from exputils.io.json import ExputilsJSONEncoder
from exputils.io.json import ex... |
c29d01dae4b2d3ffb8a4b160edefaf98bb2ba5488e1756a6a4135f840b2bb7c5 | Python | 635 | 25 | from operator import add
from neuron_morphology.constants import *
# TODO this is a port of an older statistics module. We should roll it into the
# feature extractor.
def count_number_of_independent_axons(morphology):
""" This functions counts the number of independent axons (parent is -1) """
count = 0
... |
d2d76669f429889dfb203805c740d7ff6e40469e8f83bbf801778aa53a9f7097 | Python | 635 | 17 | from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")):
raise OptionalDependencyNotAvailable()
except Opt... |
1b02d98e8ed4ba42efba7e3d27a59bc9026656fc2d8d72bcc9691a89ea8fee39 | Python | 636 | 25 | import pandas as pd
import pytest
from data_profiling import ProfileReport
from data_profiling.utils.compat import pandas_version_info
@pytest.fixture()
def df():
df = pd.DataFrame(
{
"foo": [1, 2, 3],
"bar": ["", "", ""],
}
)
return df
@pytest.mark.skipif(
p... |
b4bc9555793053eca58e6c6739d6aca33dbc822f6da295158c80b24834da24b2 | Python | 636 | 28 | """Analyze weight distribution of Braille graph."""
import matplotlib.pyplot as plt
import numpy as np
import nir
nir_model = nir.read("braille.nir")
def analyze_weights(weight, name):
print("Analyze weight matrix", name)
print(30 * "=")
print("shape:", weight.shape)
print("min:", np.min(weight))
... |
c1507a46965774b38d57470d78092f93dd2f768f091d84ea7d375ae507e1f435 | Python | 636 | 17 | from ray._private.ray_constants import env_integer
NODE_STATS_UPDATE_INTERVAL_SECONDS = env_integer(
"NODE_STATS_UPDATE_INTERVAL_SECONDS", 15
)
RAY_DASHBOARD_HEAD_NODE_REGISTRATION_TIMEOUT = env_integer(
"RAY_DASHBOARD_HEAD_NODE_REGISTRATION_TIMEOUT", 10
)
MAX_COUNT_OF_GCS_RPC_ERROR = 10
# This is consistent w... |
d3a41816bd32336129ca24a99648d0af4f24fcf905daa596af8f3a86cf45db73 | Python | 637 | 26 | from operator import add
from . import bits_validation as bv
from . import marker_validation as mv
from . import radius_validation as rv
from . import resample_validation as rev
from . import type_validation as tv
from . import structure_validation as stv
from functools import reduce
swc_validators = [bv, rv, rev, tv... |
471c10948403be287861bc6a32dfb9284b735053e05049bbc428452403031cbc | Python | 638 | 17 | # This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends
class StableDiffusionKDiffusionPipeline(metaclass=DummyObject):
_backends = ["torch", "transformers", "k_diffusion"]
def __init__(self, *args, **kwargs):
requires_backends(se... |
88226e6f24d2289a144a796e0361a26f519f1cf61ffbe0255dd74ff12eda25b4 | Python | 638 | 22 | # Generated by Django 4.1.6 on 2023-02-06 04:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("infer", "0008_alter_dataset_negatives_path_and_more"),
]
operations = [
migrations.AlterField(
model_name="dataset",
... |
b3dd52fa8c1f915db7ea4772f525fa583e2e76fe7fd0b7b9c57b1bdf0c9d47bf | Python | 638 | 22 | from .common import NodeIdStr
from .execution_options import ExecutionOptions, ExecutionResources
from .executor import Executor, OutputIterator
from .physical_operator import PhysicalOperator, ReportsExtraResourceUsage
from .ref_bundle import BlockEntry, BlockSlice, RefBundle
from .task_context import TaskContext
from... |
4ee4e83fcd8456510c5cc44bb1eb2386894a51bcbab07a8308a804b07d85d856 | Python | 639 | 23 | """This is scSemiProfiler, a tool for semi-profiling single-cell sequencing data."""
__version__ = '0.1.0'
import pdb,sys,os
from .representative_selection import activeselection
from .get_eg_representatives import get_eg_representatives
from .initial_setup import initsetup
#from .initial_setup import inspect_data
... |
7debb0b15de2eef4daee22d40ac9ba3a8a56958764677d53b56aeb90d50973e3 | Python | 639 | 18 | from exputils.data.loading import load_experiment_descriptions
from exputils.data.loading import load_experiment_data
from exputils.data.loading import load_single_experiment_data
from exputils.data.selection import select_experiment_data
from exputils.data.statistics import calc_repetition_statistics
from exputils.dat... |
064f60ea8e5a6a61a8f9abd2ddd0f36f6b393a5ed441e7b51d02b085272ea402 | Python | 640 | 22 | """The Neuromorphic Intermediate Representation reference implementation.
Documentation: https://nnir.readthedocs.io
"""
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as metadata_version
try:
__version__ = version = metadata_version("nir")
del metadata_version
exc... |
1516836ee713bacff3b2f386446a875ded13d60fbc4874fab9136754fe7c36e3 | Python | 640 | 16 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Experiment Runners for aihwkit."""
# Convenience imports for easier access to the classes.
from aihwkit.experiments.runners.cloud import CloudRunner
from ai... |
77c338f3768c9eeb0b6b773bdca7828dc6ca71340a57f7438fbc05db9086df95 | Python | 640 | 24 | import json
import pandas as pd
class DictionaryFormatter(object):
@classmethod
def normalize(cls, d):
# Normalize dictionary to a flatten table.
normalized = pd.json_normalize(d, sep="_")
normalized = normalized.astype(str)
normalized = normalized.to_dict(orient="records")[0... |
83c65a0983e3688c141231f27fa63c8165910ee7f341a6bd184c44cbd437987b | Python | 640 | 36 | # flake8: noqa
import ray
# __deployment_start__
# File name: configure_serve.py
from ray import serve
@serve.deployment(
name="Translator",
num_replicas=2,
ray_actor_options={"num_cpus": 0.2, "num_gpus": 0},
max_ongoing_requests=100,
health_check_period_s=10,
health_check_timeout_s=30,
... |
f9f09dce99a5b34b4e59bf9eaefadd08d0a7ba1d42a6d92c7722d1a17305cdb8 | Python | 640 | 20 | import pathlib
rawdata_path = pathlib.Path(r'')
click_path = pathlib.Path(r'')
preprocessed_path = pathlib.Path(r'')
predictor_path = pathlib.Path(r'')
wav_path = pathlib.Path(r'')
wav_switch_path = pathlib.Path(r'')
oss_path = pathlib.Path(r'')
oss_switching_path = pathlib.Path(r'')
zil_path = pathlib.Pat... |
1e6555cf802b3206e593882469b9c972ab15eab052b834963ff3e44d879c665a | Python | 642 | 26 | __all__ = [
'ODENet'
]
import torch
from .velocity_net import VelocityNet
class ODENet(torch.nn.Module):
def __init__(self, n_frames : int = 10, **vnet_kwargs):
super().__init__()
self.n_frames = n_frames
self.v = VelocityNet(**vnet_kwargs)
def forward(self, x : torch.Tensor) -> ... |
a8c4a661bac41fd9a858a6693924c26a90ed5318444e70828ee357b9e72ea99b | Python | 642 | 34 | # __anti_pattern_start__
import ray
ray.init()
outputs = []
for i in range(10):
@ray.remote
def double(i):
return i * 2
outputs.append(double.remote(i))
outputs = ray.get(outputs)
# The double remote function is pickled and uploaded 10 times.
# __anti_pattern_end__
assert outputs == [i * 2 for ... |
18969137826acdd54e696a268c44801e7c27eeb6ec03f341da70f9e8d959ef42 | Python | 643 | 22 | FORBIDDEN_URLS = ["facebook.com", "youtube.com", "instagram.com", "snopes.com", "politifact.com",
"cdc.gov", "who.int"]
FORBIDDEN_SUBSTRINGS = ["download", ".pdf", ".jpeg", ".jpg", ".png"]
def is_url_allowed(url):
for forbidden_url in FORBIDDEN_URLS:
if forbidden_url in url:
... |
608b0f3d318a26161f352c1a468a2e733973c04f78ce422901d88533e5f33bd9 | Python | 643 | 23 | # __main_code_start__
import requests
# Prompt for the model
prompt = "Once upon a time,"
# Add generation config here
config = {}
# Non-streaming response
sample_input = {"text": prompt, "config": config, "stream": False}
outputs = requests.post("http://127.0.0.1:8000/", json=sample_input, stream=False)
print(outpu... |
2a8f24127853b11fa3c506adb1f5c095cf768c10c894a3444bb96bf82d0feb55 | Python | 644 | 22 | """
Test for issue 147:
https://github.com/Data-Centric-AI-Community/data-profiling/issues/147
"""
import pandas as pd
from data_profiling import ProfileReport
def test_issue147(get_data_file):
file_name = get_data_file(
"userdata1.parquet",
"https://github.com/Teradata/kylo/raw/master/samples/sa... |
466ab7cce9a902a2fda639c8eaaabb519342f7053dce853d09720c3197829570 | Python | 645 | 17 | r"""``ov.epi.bulk`` — bulk epigenomics tooling.
Passthrough to :mod:`epione.bulk` (``epione.bulk.atac`` /
``epione.bulk.hic``): the ``bigwig`` track/matrix engine, HOMER motif
enrichment (``find_motifs_genome`` / ``run_homer_motifs``), ArchR-style
footprinting (``footprint_archr``), and bulk Hi-C compartment/insulatio... |
ac20782758f4b20b5f79da86aa960664369489f5b3e99b92c6137c31587a5ee0 | Python | 646 | 36 | # -*- coding: utf-8 -*-
"""
"""
import numpy as np
import sys
import os
from pathlib import Path
import collections
class FigureHistory(object):
def __init__(self):
self.deque = collections.deque(maxlen=2)
@property
def max_length(self):
return self.deque.maxlen
@max_length.setter... |
f6dbbeb80813158c59a79471ade1cb2fcf8d150037f338f85528f6b0cb5e5112 | Python | 646 | 26 | from typing import Any, Optional, Sequence
from data_profiling.config import Style
from data_profiling.report.presentation.core.item_renderer import ItemRenderer
class Table(ItemRenderer):
def __init__(
self,
rows: Sequence,
style: Style,
name: Optional[str] = None,
captio... |
ac17bbf30364a1c57be9d139ffe6527ef7272aa3c88b8d10ff9320d91047a7cf | Python | 647 | 24 | import os
import sys
from scipy.stats import norm
from scipy.stats import t
import nibabel as nib
import numpy as np
#set the input image and the output image names on the terminal
inTfile = sys.argv[1]
outZfile = sys.argv[2]
#degrees of freedom of the map to be transformed
dof = n
sided = 2 # 1 for one-sided, 2 for ... |
b289b562272198b6d2fe2e6f4ab91fc333edbe62845808dfcbabd596d336f0ca | Python | 647 | 20 | import numpy as np
from rising.loading.dataset import AsyncDataset
class LoadDummySample:
def __init__(self, keys=("data", "label"), sizes=((3, 128, 128), (3,)), **kwargs):
super().__init__(**kwargs)
self.keys = keys
self.sizes = sizes
def __call__(self, path, *args, **kwargs):
... |
94c453a9b0c4af6836626b94d5c8e51e70b551ce3c7303873fd227ac080bc504 | Python | 648 | 19 | from .molecule_3D_dataset import Molecule3DDataset
from .molecule_3D_masking_dataset import (
Molecule3DMaskingDataset,
Molecule3DHybridDataset,
)
from .molecule_contextual_datasets import MoleculeContextualDataset
from .molecule_datasets import (
MoleculeDataset,
allowable_features,
graph_data_obj_... |
7ad421ea6afc76df6a5d450721245fe764ae8cba763522abf6401ad24df13f0a | Python | 649 | 27 | """Caching utilities for the research workflow."""
from functools import lru_cache
from typing import Callable, Optional
def cache(func: Optional[Callable] = None, *, maxsize: int = 128):
"""Decorator that applies an LRU cache to ``func``.
Parameters
----------
func:
The function to decorate... |
a6024091528a8c69aff01a81c0bb0b946e9155d22407ad54c738b1f05e439143 | Python | 649 | 28 | #!/bin/python
#------------------- Description & Notes --------------------#
#------------------- Dependencies ---------------------------#
# Standard imports
# Third-party imports
# Internal imports
#------------------- Constants ------------------------------#
## Base infomation
NUCLEOTIDES = ['A', 'C', 'G', '... |
d1a041808112ddf2ee7f7dc12ad3e105d08084be853310b0955d6624356a10b9 | Python | 649 | 26 | """
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 typing import TypeVar
_T = TypeVar("_T")
def assert_is_instance(obj: object, cls: type[_T]) -> ... |
6963538556b727a3913297f21847774f8d19be2e4f62e537abd9f84d35c79b31 | Python | 650 | 19 | # Copyright 2024 The bayesnf 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 applicable law or agreed to in ... |
a306fbf4aa9dd4fad7e89556ce7f73006b2ed34e282dee60e4214277821a6d98 | Python | 650 | 19 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Legacy class for import the noise models for inference"""
import warnings
from aihwkit.inference import * # pylint: disable=unused-wildcard-import, wildcard... |
0591b61874a4e0d381c7862165787c39a2e39673679df86c97953ec084327b65 | Python | 651 | 14 | from .perceptual_loss import (PerceptualLoss, PerceptualVGG,
TransferalPerceptualLoss)
from .pixelwise_loss import (CharbonnierLoss, ColorLoss, ExposureLoss, L1Loss,
MaskedTVLoss, MSELoss, SpatialLoss)
from .ssim_loss import SSIMLoss
from .structure_fft_loss im... |
334f601a56fe79ca81997d4b7a8ee92f5501c6d09a745a0e9ff6efdaa7d98faf | Python | 651 | 22 | def get_alert_styles() -> dict:
return {
"constant": "warning",
"constant_length": "primary",
"duplicates": "secondary",
"empty": "info",
"high_cardinality": "danger",
"high_correlation": "secondary",
"infinite": "info",
"imbalance": "primary",
... |
5d7460dd5f9b23241dce3457d74e0421fe1d17ea1caefbcb12895dad51e069d9 | Python | 651 | 27 | from setuptools import setup, find_packages
with open('README.md', 'r') as f:
description = f.read()
setup(
name="UnitMatchPy",
version="1.5b",
description="Description of the package",
author="Enny van Beest, Celian Bimbard and Sam Dodgson",
author_email="e.beest@ucl.ac.uk",
packages=find... |
972940fba6e27f199ac90c69694e433100daf3685548d210adefe8d030938a24 | Python | 651 | 33 | """Vamb - Variational Autoencoders for Metagenomic Binning
Documentation: https://github.com/RasmussenLab/vamb/
"""
__version__ = (4, 1, 3)
from . import vambtools
from . import parsebam
from . import parsecontigs
from . import cluster
from . import encode
from . import aamb_encode
from . import semisupervised_encode... |
8078ce6bd6b5b93f90ea16dbdc06c0ead4efaa45061abcef6fef41d7a24fe02d | Python | 652 | 29 | from ray.autoscaler.sdk.sdk import (
bootstrap_config,
configure_logging,
create_or_update_cluster,
fillout_defaults,
get_docker_host_mount_location,
get_head_node_ip,
get_worker_node_ips,
register_callback_handler,
request_resources,
rsync,
run_on_cluster,
teardown_clust... |
cdacbd464c6e8afb0c146d02b59968225d47571b70f38bdf403d72efba2d233e | Python | 652 | 24 | """
This module provides a Python object that contains the configurations from the config.yml file.
The config.yml file should be in the parent directory of this file.
Example usage:
from core.config import cfg
print(cfg['DATASETS']['TDBRAIN']['bids_root'])
"""
import yaml
from pathlib import Path
config_path = Pa... |
1728457854a867a3579b8a47c3aeea7bd338f7ba169a96eabe171fdb7ab8c6e5 | Python | 653 | 24 | from mmdet.datasets import CocoDataset
from lqit.registry import DATASETS
from .xml_dataset import XMLDatasetWithMetaFile
URPC_METAINFO = {
'classes': ('holothurian', 'echinus', 'scallop', 'starfish'),
'palette': [(235, 211, 70), (106, 90, 205), (160, 32, 240), (176, 23, 31)]
}
@DATASETS.register_module()
c... |
adb970639fb589ce37b36f7f4612a7fcebcce46ddb2ab607872753a005568dbf | Python | 653 | 16 | import gffutils
db = gffutils.create_db(snakemake.input[0],
dbfn=snakemake.output.db,
force=True,
keep_order=True,
merge_strategy='merge',
sort_attribute_values=True,
disable_... |
c58a08efcd8be761fe777c5f150213bbdc39769a98b5288b3498fb463992531c | Python | 653 | 23 | from pathlib import Path
from siapy.entities import SpectralImage
from siapy.utils.plots import pixels_select_click
# Set the path to the directory containing the data
# !! ADJUST THIS PATH TO YOUR DATA DIRECTORY !!
data_dir = "./docs/examples/data"
# Get arbitrary image
header_path_img0 = sorted(Path(data_dir).rglo... |
019b3c0c7a9dd6de066f5e1ab5708b64313c857ea8015a2cce871545849c9977 | Python | 654 | 18 | import torch as th
import torch.nn as nn
def latent_time_path_reg(z_traj, z_data, ts, ts_data, hinge_value=0.025):
vals = []
for i in range(z_traj.shape[1]): # loop over time
_, indices_ts = th.topk(th.cdist(ts[None,i], ts_data[None])[0], 100,
dim=1, largest=False... |
73268af2a3a55a82cb5f8d5edb0b8bb1cec8556ab642bd59f4ae0b3307a47a31 | Python | 654 | 18 | import os
import argparse
import subprocess
if __name__ == "__main__":
# Get the command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument("input_dir", type=str, help="Input data directory")
parser.add_argument("output_dir", type=str, help="Output data directory")
parser.add_a... |
b9c444ae2d667fac6547407df486edadc48a29f3e41b52eb4c8802b040bfe2d2 | Python | 654 | 25 | """
Test for issue 120:
https://github.com/Data-Centric-AI-Community/data-profiling/issues/120
"""
import pandas as pd
from data_profiling import ProfileReport
def test_issue_120(get_data_file):
file_name = get_data_file(
"data_profiling_bug.txt",
"https://github.com/pandas-profiling/pandas-profi... |
daecb0711d38c860a893780be80fb57acee728c7a4a596341de790557e2b962b | Python | 654 | 17 | r"""``ov.epi.utils`` — epigenomics utilities & region operations.
Passthrough to :mod:`epione.utils`: genome accessors
(``utils.genome.hg38`` / ``hg19`` / ...), peak-set operations
(``merge_peaks``, ``annotate_peaks``, ``classify_peaks_by_overlap``),
gene-annotation parsing and AnnData on-disk helpers (``obs_to_pandas... |
6938fdf459c149afe5f70431024ddaf913bafe60a2eb2e35dae245650b2ee8a3 | Python | 655 | 23 | import numpy as np
import pandas as pd
from data_profiling import ProfileReport
def test_interactions_target():
n_rows = 10
n_columns = 50
n_targets = 2
df = pd.DataFrame(
np.random.randint(0, 1000, size=(n_rows, n_columns)),
columns=[f"column_{c}" for c in range(n_colum... |
d4e961637b1b29546c8f3891cd618fb2015e837fdbfcd3223d8f519cf841d8b8 | Python | 655 | 24 | """
Expression and regulation-related API clients for DataCollect.
This module provides API clients for gene expression databases including:
- GEO: Gene expression datasets
- OpenTargets: Drug target information
- OpenTargets Genetics: Genetics evidence
- ReMap: Transcriptional regulators
- CCRE: Candidate cis-regul... |
550739a71bfdb1666b0f33ab76fb372f249cc2b3865626b5fbad0fb83de27092 | Python | 656 | 14 | # Copyright 2024 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, ... |
e4a2143510bbc62459f3bdf604e03f987399db8ba0b81f5e8c84c467968547a2 | Python | 656 | 14 | # Copyright 2023 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, ... |
f5ec1ad1e0e35fd05c1454d96de002621e60c566bc113ac655eedd535ad7a6fc | Python | 658 | 26 | import requests
from starlette.requests import Request
from typing import Dict
from ray import serve
# 1: Define a Ray Serve application.
@serve.deployment
class MyModelDeployment:
def __init__(self, msg: str):
# Initialize model state: could be very large neural net weights.
self._msg = msg
... |
62d39a322235f39fa27984855f5d74a9f154b1d93dbefbbf7a4ae897ae6c2452 | Python | 659 | 28 |
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_var: float = field(default=None)
apt_std: ... |
bd49ce20867ebbbe70df024b14d1acd6d6e9e4072a0e509696d882b5358626e3 | Python | 659 | 17 | # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
16e9bac66de63046edc1c1ba2d8ef95777f9d740be145cb4592c854b67458b4f | Python | 660 | 24 | #!/usr/bin/env python3
import fire
import pandas as pd
def get_categories(clini_excel: str, *columns: str):
"""Read all categories for a target label.
Args:
clini_excel: Clini table to read from.
columns: target labels to determine categories for.
"""
# clini_file = '/run/media/jxia... |
580ac2449b1a3068de35fe6d4d434165f2fb90daa4ae984f3fcc8866317ce790 | Python | 660 | 21 | import numpy as np
import matplotlib
def overlap_colors(n, l=0.1, r=0.7):
cmap = matplotlib.cm.get_cmap("bone")
colors = [cmap(x) for x in np.linspace(l,r,n)]
return colors
def single_unit_colors():
colors = ['indianred','salmon','darkred','firebrick','orangered']
return colors
def single_unit_co... |
ae56cf006f99ecdc33c50eb3c270f2d3d24aa2f17ef9e5ba52ba514977078b61 | Python | 660 | 20 | import torch.nn as nn
from argparse import Namespace, ArgumentParser
from .base import BaseModelConfig
from optuna import Trial
from monai.networks.nets import VNet
class VNetConfig(BaseModelConfig):
model_name = "vnet"
def setup_search_space(self, trial: Trial, args: Namespace) -> Namespace:
return... |
40b2443161a365de97230492966a8bc3a1791636083ad6385d5e6a03a0805995 | Python | 661 | 16 | from .model_dummy_1 import dcnnl_map_1, expected_output_1
from .model_dummy_2 import dcnnl_map_2, expected_output_2
from .model_dummy_3 import dcnnl_map_3, expected_output_3
from .model_dummy_4 import dcnnl_map_4, expected_output_4
# Args: dcnnl_map, discretize, expected_output
args_DynapcnnLayer = [
(dcnnl_map_1,... |
ac37d17c5adc971e33cf859a6b2186b5f882e603cd9571bf9c30d4e8e7e8c8ad | Python | 661 | 22 | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'site1.settings')
try:
from django.core.management import execute_from_command_line
except Import... |
d99af178274fb3e9c13ff430ba7870ecc9bd8142f49b906d971a827f24ba4e5e | Python | 661 | 35 | import json
import pandas as pd
import pytest
from data_profiling import ProfileReport
@pytest.fixture
def data():
return pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]})
def test_json(data):
report = ProfileReport(data)
report_json = report.to_json()
data = json.loads(report_json)
assert s... |
50cccb470828423aab2fbc7d6abef58505d0e283a6fa41cef6bce183413d0a3e | Python | 664 | 19 | import logging
import os
logger = logging.getLogger(__name__)
RAY_PICKLE_VERBOSE_DEBUG = os.environ.get("RAY_PICKLE_VERBOSE_DEBUG")
verbose_level = int(RAY_PICKLE_VERBOSE_DEBUG) if RAY_PICKLE_VERBOSE_DEBUG else 0
if verbose_level > 1:
logger.warning(
"Environmental variable RAY_PICKLE_VERBOSE_DEBUG is se... |
d0432f02486ec5878786f66f9b07529a131631827e5f328052e3a4514c786ae1 | Python | 664 | 22 | import typing
from importlib.metadata import (
PackageNotFoundError,
version as _version,
)
try:
_found_version: str = _version('numpy-stl')
except PackageNotFoundError:
_found_version = '0.0.0'
__version__: typing.Final[str] = _found_version
__package_name__: typing.Final[str] = 'numpy-stl'
__import... |
d34b587abaa551614ffde4f6d693f200f1f631bb15c19991a0735cd55bf941ae | Python | 664 | 26 | """
Run pipelines to extract envelope and speech features on the audio snippets.
"""
import json
import envelopes
import linguistic_features
from pathlib import Path
import mne
mne.set_log_level('WARNING')
if __name__ == '__main__':
print('Running: ', __file__)
with open('config.json') as f:
config ... |
5f48a1b18d8077a0e8f83578996234bde0323d07962391d5a13c3e395ccbb450 | Python | 665 | 21 | import PIL.Image
import PIL.ImageOps
from packaging import version
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
PIL_INTERPOLATION = {
"linear": PIL.Image.Resampling.BILINEAR,
"bilinear": PIL.Image.Resampling.BILINEAR,
"bicubic": PIL.Image.Resampl... |
c5396b85d547bf653851b342f7fbc5eba6bd46c4b5274017de14e2cfcbcf6e36 | Python | 665 | 28 | from typing import TypedDict
class PythonVersionInfo(TypedDict):
bin_path: str
BUILD_TYPES = [
"optimized",
"debug",
]
ARCHITECTURE = [
"x86_64",
"aarch64",
]
PYTHON_VERSIONS = {
"3.9": PythonVersionInfo(bin_path="cp39-cp39"),
"3.10": PythonVersionInfo(bin_path="cp310-cp310"),
"3.11"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.