sample_id
string
instruction
string
completion
string
category
string
label
int64
metadata
string
ray-project/ray:release/train_tests/benchmark/image_classification/s3_url/imagenet.py:_list_s3_image_files_cached
# Context: from functools import lru_cache from typing import Callable, Dict, List, Optional, Tuple def _get_class_labels(bucket: str, prefix: str) -> List[str]: ... def _list_files_for_label(bucket: str, prefix: str, label: str) -> List[Tuple[str, str]]: ... def list_s3_image_files(data_dir: str) -> List[Dict[str, st...
def _list_s3_image_files_cached(data_dir: str) -> Tuple[Tuple[str, str], ...]: """Cached implementation of S3 file listing using Ray tasks for parallelism. Returns a tuple of tuples for hashability (required by lru_cache). """ logger.info(f"Listing JPEG files from {data_dir}...") # Parse S3 URL: s...
function_simple
0
{"cognitive_complexity": 3, "loc": 34, "code_loc": 18, "docstring_loc": 4, "function_name": "_list_s3_image_files_cached", "class_name": null, "qualname": "_list_s3_image_files_cached", "file_path": "release/train_tests/benchmark/image_classification/s3_url/imagenet.py", "repo_id": "ray-project/ray", "has_docstring": t...
ray-project/ray:rllib/utils/metrics/stats/mean.py:MeanStats.push
# Context: from typing import Any, Union class MeanStats(SeriesStats): stats_cls_identifier = "mean" def _np_reduce_fn(self, values: np.ndarray) -> float: ... def _torch_reduce_fn(self, values: 'torch.Tensor'): ... def reduce(self, compile: bool) -> Union[Any, 'MeanStats']: ... def __repr__(self) -...
def push(self, value: Any) -> None: """Pushes a value into this Stats object. Args: value: The value to be pushed. Can be of any type. PyTorch GPU tensors are kept on GPU until reduce() or peek(). TensorFlow tensors are moved to CPU immediately. """ ...
function_simple
0
{"cognitive_complexity": 2, "loc": 13, "code_loc": 3, "docstring_loc": 7, "function_name": "push", "class_name": "MeanStats", "qualname": "MeanStats.push", "file_path": "rllib/utils/metrics/stats/mean.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "file_runnable"}
ocrmypdf/OCRmyPDF:src/ocrmypdf/font/font_provider.py:BuiltinFontProvider._load_fonts
# Context: from ocrmypdf.font.font_manager import FontManager class FontProvider(Protocol): ... class ChainedFontProvider: ... class BuiltinFontProvider: FONT_FILES = { def __init__(self, font_dir: Path | None = None): """Initialize builtin font provider. Args: font_dir: Directory...
def _load_fonts(self) -> None: """Load available fonts, logging warnings for missing ones.""" for font_name, font_file in self.FONT_FILES.items(): font_path = self.font_dir / font_file if not font_path.exists(): if font_name == 'Occulta': raise...
function_complex
1
{"cognitive_complexity": 10, "loc": 29, "code_loc": 26, "docstring_loc": 1, "function_name": "_load_fonts", "class_name": "BuiltinFontProvider", "qualname": "BuiltinFontProvider._load_fonts", "file_path": "src/ocrmypdf/font/font_provider.py", "repo_id": "ocrmypdf/OCRmyPDF", "has_docstring": true, "runnable_level": "pro...
ray-project/ray:rllib/algorithms/tqc/tests/test_tqc.py:module_doc
Write a module-level docstring for the Python module `test_tqc` which contains class `SimpleEnv`, class `TestTQC`.
Tests for the TQC (Truncated Quantile Critics) algorithm.
documentation
0
{"doc_type": "module", "module_name": "test_tqc", "file_path": "rllib/algorithms/tqc/tests/test_tqc.py", "repo_id": "ray-project/ray", "char_length": 57}
huggingface/transformers:src/transformers/models/gemma3n/modular_gemma3n.py:Gemma3nModel.forward
# Context: import torch from ...cache_utils import Cache, DynamicCache from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_compilable_check class Gemma3nTextConfig(Gemma2Config, PreTrainedConfig): ... class Gemma3nAudioConfig(PreTrainedConfig...
def forward( self, input_ids: torch.LongTensor | None = None, # text inputs pixel_values: torch.FloatTensor | None = None, # vision inputs input_features: torch.FloatTensor | None = None, # audio inputs attention_mask: torch.Tensor | None = None, input_features_mask: t...
function_complex
0
{"cognitive_complexity": 8, "loc": 144, "code_loc": 74, "docstring_loc": 30, "function_name": "forward", "class_name": "Gemma3nModel", "qualname": "Gemma3nModel.forward", "file_path": "src/transformers/models/gemma3n/modular_gemma3n.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_level": "p...
docling-project/docling:docs/examples/post_process_ocr_with_vlm.py:no_long_repeats
# Context: import re def is_empty_fast_with_lines_pil(pil_img: Image.Image, downscale_max_side: int, grad_threshold: float, min_line_coverage: float, max_allowed_lines: int, edge_fraction_threshold: float): ... def remove_break_lines(text: str) -> str: ... def safe_crop(img: Image.Image, bbox): ... class PostOcrEnrich...
def no_long_repeats(s: str, threshold: int) -> bool: """ Returns False if the string `s` contains more than `threshold` identical characters in a row, otherwise True. """ pattern = r"(.)\1{" + str(threshold) + ",}" return re.search(pattern, s) is None
function_simple
1
{"cognitive_complexity": 0, "loc": 7, "code_loc": 2, "docstring_loc": 4, "function_name": "no_long_repeats", "class_name": null, "qualname": "no_long_repeats", "file_path": "docs/examples/post_process_ocr_with_vlm.py", "repo_id": "docling-project/docling", "has_docstring": true, "runnable_level": "slib_runnable"}
crewAIInc/crewAI:lib/crewai/src/crewai/a2a/utils/agent_card.py:inject_a2a_server_methods
# Context: from types import MethodType from a2a.types import AgentCapabilities, AgentCard, AgentSkill from crewai.agent import Agent def _get_tls_verify(auth: ClientAuthScheme | None) -> ssl.SSLContext | bool | str: ... async def _prepare_auth_headers(auth: ClientAuthScheme | None, timeout: int) -> tuple[MutableMappi...
def inject_a2a_server_methods(agent: Agent) -> None: """Inject A2A server methods onto an Agent instance. Adds a `to_agent_card(url: str) -> AgentCard` method to the agent that generates an A2A-compliant AgentCard. Only injects if the agent has an A2AServerConfig. Args: agent: The Agent i...
function_simple
0
{"cognitive_complexity": 1, "loc": 18, "code_loc": 5, "docstring_loc": 10, "function_name": "inject_a2a_server_methods", "class_name": null, "qualname": "inject_a2a_server_methods", "file_path": "lib/crewai/src/crewai/a2a/utils/agent_card.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_level": "pro...
infiniflow/ragflow:test/testcases/test_sdk_api/test_chunk_management_within_dataset/test_delete_chunks.py:TestChunksDeletion.test_delete_1k
# Context: import pytest from common import batch_add_chunks from time import sleep class TestChunksDeletion: def test_delete_partial_invalid_id(self, add_chunks_func, payload): ... def test_repeated_deletion(self, add_chunks_func): ... def test_duplicate_deletion(self, add_chunks_func): ... def test_c...
def test_delete_1k(self, add_document): count = 1_000 _, document = add_document chunks = batch_add_chunks(document, count) chunk_ids = [chunk.id for chunk in chunks] from time import sleep sleep(1) document.delete_chunks(ids=chunk_ids) remaining_chunks...
test
1
{"function_name": "test_delete_1k", "class_name": "TestChunksDeletion", "qualname": "TestChunksDeletion.test_delete_1k", "file_path": "test/testcases/test_sdk_api/test_chunk_management_within_dataset/test_delete_chunks.py", "repo_id": "infiniflow/ragflow", "loc": 13, "tested_modules": ["concurrent.futures", "common", "...
crewAIInc/crewAI:lib/crewai/tests/llms/test_multimodal_integration.py:TestLiteLLMMultimodalIntegration.test_describe_image_claude
# Context: import pytest from crewai.llm import LLM from crewai_files import ( AudioFile, File, ImageFile, PDFFile, TextFile, VideoFile, format_multimodal_content, ) def test_image_bytes() -> bytes: ... def test_text_bytes() -> bytes: ... def test_video_bytes() -> bytes: ... def test_audio_...
def test_describe_image_claude(self, test_image_bytes: bytes) -> None: """Test LiteLLM with Claude can describe an image.""" llm = LLM(model="anthropic/claude-3-5-haiku-20241022", is_litellm=True) files = {"image": ImageFile(source=test_image_bytes)} messages = _build_multimodal_message...
test
0
{"function_name": "test_describe_image_claude", "class_name": "TestLiteLLMMultimodalIntegration", "qualname": "TestLiteLLMMultimodalIntegration.test_describe_image_claude", "file_path": "lib/crewai/tests/llms/test_multimodal_integration.py", "repo_id": "crewAIInc/crewAI", "loc": 16, "tested_modules": ["pathlib", "crewa...
ray-project/ray:python/ray/serve/tests/test_direct_ingress.py:TestDirectIngressBackpressure.test_requests_are_not_running_serially
# Context: import asyncio from concurrent.futures import ThreadPoolExecutor import httpx from ray import serve from ray._common.test_utils import Semaphore, SignalActor, wait_for_condition from ray.serve._private.test_utils import ( check_deployment_status, check_num_replicas_gte, check_num_replicas_lte, ...
def test_requests_are_not_running_serially( self, _skip_if_ff_not_enabled, serve_instance ): """Test that requests are processed concurrently, not serially""" @serve.deployment( max_ongoing_requests=20, ) class A: async def __call__(self): ...
test
0
{"function_name": "test_requests_are_not_running_serially", "class_name": "TestDirectIngressBackpressure", "qualname": "TestDirectIngressBackpressure.test_requests_are_not_running_serially", "file_path": "python/ray/serve/tests/test_direct_ingress.py", "repo_id": "ray-project/ray", "loc": 30, "tested_modules": ["concur...
ray-project/ray:python/ray/llm/_internal/common/utils/cloud_filesystem/pyarrow_filesystem.py:PyArrowFileSystem._create_azure_filesystem
# Context: from typing import List, Optional, Tuple, Union from urllib.parse import urlparse import pyarrow.fs as pa_fs import adlfs from azure.identity import DefaultAzureCredential class PyArrowFileSystem(BaseCloudFileSystem): def get_fs_and_path(object_uri: str) -> Tuple[pa_fs.FileSystem, str]: ... def _cre...
def _create_azure_filesystem(object_uri: str) -> Tuple[pa_fs.FileSystem, str]: """Create an Azure filesystem for Azure Blob Storage or ABFSS. Args: object_uri: Azure URI (azure://container@account.blob.core.windows.net/path or abfss://container@account.dfs.core.window...
function_complex
0
{"cognitive_complexity": 10, "loc": 78, "code_loc": 45, "docstring_loc": 13, "function_name": "_create_azure_filesystem", "class_name": "PyArrowFileSystem", "qualname": "PyArrowFileSystem._create_azure_filesystem", "file_path": "python/ray/llm/_internal/common/utils/cloud_filesystem/pyarrow_filesystem.py", "repo_id": "...
ray-project/ray:python/ray/data/tests/test_limit_operator.py:test_per_block_limit_fn
# Context: import pytest from ray.data._internal.execution.interfaces.task_context import TaskContext from ray.data._internal.execution.operators.map_operator import _per_block_limit_fn import pandas as pd def test_limit_operator(ray_start_regular_shared): ... def test_limit_operator_memory_leak_fix(ray_start_regular_...
def test_per_block_limit_fn(blocks_data, per_block_limit, expected_output): """Test the _per_block_limit_fn function with various inputs.""" import pandas as pd # Convert test data to pandas blocks blocks = [pd.DataFrame({"value": data}) for data in blocks_data] # Create a mock TaskContext ctx...
test
0
{"function_name": "test_per_block_limit_fn", "class_name": null, "qualname": "test_per_block_limit_fn", "file_path": "python/ray/data/tests/test_limit_operator.py", "repo_id": "ray-project/ray", "loc": 20, "tested_modules": ["ray.data._internal.execution.interfaces.task_context", "ray.data._internal.execution.operators...
langflow-ai/langflow:src/backend/tests/unit/components/bundles/agentics/test_semantic_map.py:TestSemanticMapComponent.test_should_have_schema_with_table_schema
# Context: from lfx.components.agentics.semantic_map import SemanticMap class TestSemanticMapComponent: def test_should_have_correct_display_name(self): ... def test_should_have_correct_icon(self): ... def test_should_have_required_inputs(self): ... def test_should_have_dataframe_output(self): ... ...
def test_should_have_schema_with_table_schema(self): """Test that schema input has table_schema defined.""" schema_input = next((i for i in SemanticMap.inputs if i.name == "schema"), None) assert schema_input is not None assert schema_input.table_schema is not None assert len(sch...
test
1
{"function_name": "test_should_have_schema_with_table_schema", "class_name": "TestSemanticMapComponent", "qualname": "TestSemanticMapComponent.test_should_have_schema_with_table_schema", "file_path": "src/backend/tests/unit/components/bundles/agentics/test_semantic_map.py", "repo_id": "langflow-ai/langflow", "loc": 12,...
huggingface/transformers:tests/models/dinov3_convnext/test_modeling_dinov3_convnext.py:DINOv3ConvNextModelIntegrationTest.test_inference_no_head
# Context: from transformers.testing_utils import require_torch, require_vision, slow, torch_device import torch from transformers import DINOv3ConvNextBackbone, DINOv3ConvNextModel class DINOv3ConvNextModelTester: ... class DINOv3ConvNextModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): ... def pre...
def test_inference_no_head(self): model = DINOv3ConvNextModel.from_pretrained("facebook/dinov3-convnext-tiny-pretrain-lvd1689m").to(torch_device) image_processor = self.default_image_processor image = prepare_img() inputs = image_processor(image, return_tensors="pt").to(torch_device) ...
test
0
{"function_name": "test_inference_no_head", "class_name": "DINOv3ConvNextModelIntegrationTest", "qualname": "DINOv3ConvNextModelIntegrationTest.test_inference_no_head", "file_path": "tests/models/dinov3_convnext/test_modeling_dinov3_convnext.py", "repo_id": "huggingface/transformers", "loc": 24, "tested_modules": ["fun...
apache/airflow:airflow-core/src/airflow/models/callback.py:ExecutorCallback.__init__
# Context: from airflow.executors.workloads.callback import CallbackFetchMethod class CallbackType(str, Enum): ... class CallbackDefinitionProtocol(Protocol): ... class ImportPathCallbackDefProtocol(CallbackDefinitionProtocol, Protocol): ... class ImportPathExecutorCallbackDefProtocol(ImportPathCallbackDefProtocol, Pr...
def __init__( self, callback_def: ImportPathExecutorCallbackDefProtocol, fetch_method: CallbackFetchMethod, **kwargs ): """ Initialize an ExecutorCallback from a callback definition and fetch method. :param callback_def: Callback definition with path, kwargs, and executor :p...
function_simple
1
{"cognitive_complexity": 0, "loc": 13, "code_loc": 3, "docstring_loc": 7, "function_name": "__init__", "class_name": "ExecutorCallback", "qualname": "ExecutorCallback.__init__", "file_path": "airflow-core/src/airflow/models/callback.py", "repo_id": "apache/airflow", "has_docstring": true, "runnable_level": "project_run...
huggingface/transformers:src/transformers/models/glm_moe_dsa/modular_glm_moe_dsa.py:apply_rotary_pos_emb
# Context: import torch from ...models.llama.modeling_llama import rotate_half class GlmMoeDsaConfig(PreTrainedConfig): ... class GlmMoeDsaRMSNorm(Glm4MoeRMSNorm): ... class GlmMoeDsaIndexer(nn.Module): ... class GlmMoeDsaAttention(nn.Module): ... class GlmMoeDsaDecoderLayer(Glm4MoeLiteDecoderLayer): ... class GlmMoeD...
def apply_rotary_pos_emb( x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1, ) -> torch.Tensor: """ Applies Rotary Position Embedding to a single tensor. This is the transformers equivalent of DeepSeek V3.2's `apply_rotary_emb(x, freqs_cis, interleaved)`. Ins...
function_simple
0
{"cognitive_complexity": 0, "loc": 29, "code_loc": 4, "docstring_loc": 16, "function_name": "apply_rotary_pos_emb", "class_name": null, "qualname": "apply_rotary_pos_emb", "file_path": "src/transformers/models/glm_moe_dsa/modular_glm_moe_dsa.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_l...
infiniflow/ragflow:test/testcases/test_http_api/test_file_management_within_dataset/test_upload_documents.py:TestDocumentsUpload.test_invalid_dataset_id
# Context: import pytest from common import FILE_API_URL, list_datasets, upload_documents from utils.file_utils import create_txt_file class TestAuthorization: ... class TestDocumentsUpload: def test_valid_single_upload(self, HttpApiAuth, add_dataset_func, tmp_path): ... def test_file_type_validation(self, Ht...
def test_invalid_dataset_id(self, HttpApiAuth, tmp_path): fp = create_txt_file(tmp_path / "ragflow_test.txt") res = upload_documents(HttpApiAuth, "invalid_dataset_id", [fp]) assert res["code"] == 100 assert res["message"] == """LookupError("Can\'t find the dataset with ID invalid_dataset...
test
1
{"function_name": "test_invalid_dataset_id", "class_name": "TestDocumentsUpload", "qualname": "TestDocumentsUpload.test_invalid_dataset_id", "file_path": "test/testcases/test_http_api/test_file_management_within_dataset/test_upload_documents.py", "repo_id": "infiniflow/ragflow", "loc": 5, "tested_modules": ["concurrent...
huggingface/transformers:utils/modular_model_detector.py:license_header
Add a Apache-2.0 license header comment for the project 'transformers', authored by The HuggingFace Team, year 2025.
# Copyright 2025 The HuggingFace Team. All rights reserved. # # 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 applicabl...
license
0
{"license_type": "Apache-2.0", "author": "The HuggingFace Team", "year": "2025", "source": "header", "repo_id": "huggingface/transformers"}
crewAIInc/crewAI:lib/crewai/tests/mcp/test_amp_mcp.py:TestBuildMCPConfigFromDict.test_defaults_to_http
# Context: from crewai.mcp.config import MCPServerHTTP, MCPServerSSE from crewai.mcp.tool_resolver import MCPToolResolver def agent(): ... def resolver(agent): ... def mock_tool_definitions(): ... class TestFetchAmpMCPConfigs: ... class TestParseAmpRef: ... class TestGetMCPToolsAmpIntegration: ... class TestBuildMCPC...
def test_defaults_to_http(self): config_dict = { "url": "https://mcp.example.com/api", } result = MCPToolResolver._build_mcp_config_from_dict(config_dict) assert isinstance(result, MCPServerHTTP) assert result.streamable is True
test
0
{"function_name": "test_defaults_to_http", "class_name": "TestBuildMCPConfigFromDict", "qualname": "TestBuildMCPConfigFromDict.test_defaults_to_http", "file_path": "lib/crewai/tests/mcp/test_amp_mcp.py", "repo_id": "crewAIInc/crewAI", "loc": 9, "tested_modules": ["crewai.agent.core", "crewai.mcp.config", "crewai.mcp.to...
crewAIInc/crewAI:lib/crewai/tests/test_flow_ask.py:TestAskMetadata.test_ask_provider_returns_string_with_metadata_sent
# Context: from crewai.flow import Flow, flow_config, listen, start class MockInputProvider: ... class SlowMockProvider: ... class TestAskBasic: ... class TestAskTimeout: ... class TestProviderResolution: ... class TestAskEvents: ... class TestAskCheckpoint: ... class TestInputHistory: ... class TestAskIntegration: .....
def test_ask_provider_returns_string_with_metadata_sent(self) -> None: """Provider returns plain string; history has metadata but no response_metadata.""" class TestFlow(Flow): input_provider = MockInputProvider(["answer"]) @start() def my_method(self): ...
test
0
{"function_name": "test_ask_provider_returns_string_with_metadata_sent", "class_name": "TestAskMetadata", "qualname": "TestAskMetadata.test_ask_provider_returns_string_with_metadata_sent", "file_path": "lib/crewai/tests/test_flow_ask.py", "repo_id": "crewAIInc/crewAI", "loc": 16, "tested_modules": ["__future__", "datet...
infiniflow/ragflow:agent/sandbox/tests/test_providers.py:module_doc
Write a module-level docstring for the Python module `test_providers` which contains class `TestSandboxDataclasses`, class `TestProviderManager`, class `TestSelfManagedProvider`, class `TestProviderInterface`.
Unit tests for sandbox provider abstraction layer.
documentation
1
{"doc_type": "module", "module_name": "test_providers", "file_path": "agent/sandbox/tests/test_providers.py", "repo_id": "infiniflow/ragflow", "char_length": 50}
mem0ai/mem0:openmemory/api/app/models.py:after_memory_insert
# Context: from sqlalchemy import ( JSON, UUID, Boolean, Column, DateTime, Enum, ForeignKey, Index, Integer, String, Table, event, ) from sqlalchemy.orm import Session, relationship def get_current_utc_time(): ... class MemoryState(enum.Enum): ... class User(Base): ... c...
def after_memory_insert(mapper, connection, target): """Trigger categorization after a memory is inserted.""" db = Session(bind=connection) categorize_memory(target, db) db.close()
function_simple
1
{"cognitive_complexity": 0, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "after_memory_insert", "class_name": null, "qualname": "after_memory_insert", "file_path": "openmemory/api/app/models.py", "repo_id": "mem0ai/mem0", "has_docstring": true, "runnable_level": "file_runnable"}
huggingface/transformers:tests/cli/test_chat.py:test_new_chat_history
# Context: from transformers.cli.chat import new_chat_history, parse_generate_flags, save_chat def test_help(cli): ... def test_save_and_clear_chat(): ... def test_parse_generate_flags(): ... # Task: Write a Python test function `test_new_chat_history` to verify the behavior of `new_chat_history`. Module under test:...
def test_new_chat_history(): assert new_chat_history() == [] assert new_chat_history("prompt") == [{"role": "system", "content": "prompt"}]
test
0
{"function_name": "test_new_chat_history", "class_name": null, "qualname": "test_new_chat_history", "file_path": "tests/cli/test_chat.py", "repo_id": "huggingface/transformers", "loc": 3, "tested_modules": ["transformers.cli.chat"], "has_docstring": false, "runnable_level": "plib_runnable"}
langflow-ai/langflow:src/lfx/tests/unit/cli/test_validation.py:TestValidateGlobalVariablesForEnv.test_check_variables_option_in_execute
# Context: from unittest.mock import MagicMock, patch from lfx.cli.validation import is_valid_env_var_name, validate_global_variables_for_env from lfx.graph.graph.base import Graph from lfx.graph.vertex.base import Vertex class TestIsValidEnvVarName: ... class TestValidateGlobalVariablesForEnv: def test_no_valida...
def test_check_variables_option_in_execute(self, mock_get_settings): """Test that check_variables option controls validation in execute command.""" # This test verifies the check_variables option works correctly # when used with the execute command (--check-variables/--no-check-variables) ...
test
1
{"function_name": "test_check_variables_option_in_execute", "class_name": "TestValidateGlobalVariablesForEnv", "qualname": "TestValidateGlobalVariablesForEnv.test_check_variables_option_in_execute", "file_path": "src/lfx/tests/unit/cli/test_validation.py", "repo_id": "langflow-ai/langflow", "loc": 23, "tested_modules":...
huggingface/transformers:tests/models/videomae/test_video_processing_videomae.py:VideoMAEVideoProcessingTest.test_video_processor_properties
# Context: class VideoMAEVideoProcessingTester: ... class VideoMAEVideoProcessingTest(VideoProcessingTestMixin, unittest.TestCase): fast_video_processing_class = VideoMAEVideoProcessor if is_torchvision_available() else None input_name = "pixel_values" def setUp(self): ... def video_processor_dict(sel...
def test_video_processor_properties(self): video_processing = self.fast_video_processing_class(**self.video_processor_dict) self.assertTrue(hasattr(video_processing, "do_resize")) self.assertTrue(hasattr(video_processing, "size")) self.assertTrue(hasattr(video_processing, "do_center_crop...
test
0
{"function_name": "test_video_processor_properties", "class_name": "VideoMAEVideoProcessingTest", "qualname": "VideoMAEVideoProcessingTest.test_video_processor_properties", "file_path": "tests/models/videomae/test_video_processing_videomae.py", "repo_id": "huggingface/transformers", "loc": 12, "tested_modules": ["PIL",...
github/spec-kit:src/specify_cli/extensions.py:ExtensionManager.__init__
# Context: from pathlib import Path class ExtensionError(Exception): ... class ValidationError(ExtensionError): ... class CompatibilityError(ExtensionError): ... class ExtensionManifest: ... class ExtensionRegistry: ... def version_satisfies(current: str, required: str) -> bool: ... class CommandRegistrar: ... class E...
def __init__(self, project_root: Path): """Initialize extension manager. Args: project_root: Path to project root directory """ self.project_root = project_root self.extensions_dir = project_root / ".specify" / "extensions" self.registry = ExtensionRegistry(s...
function_simple
0
{"cognitive_complexity": 0, "loc": 9, "code_loc": 3, "docstring_loc": 5, "function_name": "__init__", "class_name": "ExtensionManager", "qualname": "ExtensionManager.__init__", "file_path": "src/specify_cli/extensions.py", "repo_id": "github/spec-kit", "has_docstring": true, "runnable_level": "file_runnable"}
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/databricks_query_tool/databricks_query_tool.py:_has_data_array
# Context: from typing import TYPE_CHECKING, Any, TypeGuard, TypedDict class ExecutionContext(TypedDict): ... class DatabricksQueryToolSchema(BaseModel): ... class DatabricksQueryTool(BaseTool): ... # Task: Write a Python function `_has_data_array` to type guard to check if result has data_array attribute. Parameter...
def _has_data_array(result: Any) -> TypeGuard[Any]: """Type guard to check if result has data_array attribute. Args: result: The result object to check. Returns: True if result.result.data_array exists and is not None. """ return ( hasattr(result, "result") and resu...
function_simple
0
{"cognitive_complexity": 1, "loc": 15, "code_loc": 6, "docstring_loc": 8, "function_name": "_has_data_array", "class_name": null, "qualname": "_has_data_array", "file_path": "lib/crewai-tools/src/crewai_tools/tools/databricks_query_tool/databricks_query_tool.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "r...
apache/airflow:shared/configuration/tests/configuration/test_parser.py:TestAirflowConfigParser.test_deprecated_options_lookup_disabled
# Context: from configparser import ConfigParser import pytest from airflow_shared.configuration.exceptions import AirflowConfigException class AirflowConfigParser(_SharedAirflowConfigParser): ... class TestAirflowConfigParser: def test_getboolean(self): ... def test_getint(self): ... def test_getfloat(se...
def test_deprecated_options_lookup_disabled(self): """Test deprecated options with lookup_from_deprecated=False""" class TestParserWithDeprecated(AirflowConfigParser): deprecated_options = { ("new_section", "new_key"): ("old_section", "old_key", "2.0.0"), } ...
test
1
{"function_name": "test_deprecated_options_lookup_disabled", "class_name": "TestAirflowConfigParser", "qualname": "TestAirflowConfigParser.test_deprecated_options_lookup_disabled", "file_path": "shared/configuration/tests/configuration/test_parser.py", "repo_id": "apache/airflow", "loc": 20, "tested_modules": ["__futur...
crewAIInc/crewAI:lib/crewai/tests/utilities/test_agent_utils.py:TestParseToolCallArgs.test_valid_json_with_nested_values
# Context: from crewai.utilities.agent_utils import ( _asummarize_chunks, _estimate_token_count, _extract_summary_tags, _format_messages_for_summary, _split_messages_into_chunks, convert_tools_to_openai_schema, parse_tool_call_args, summarize_messages, ) class CalculatorInput(BaseModel)...
def test_valid_json_with_nested_values(self) -> None: args_dict, error = parse_tool_call_args( '{"query": "hello", "options": {"limit": 10}}', "search", "call_6" ) assert error is None assert args_dict == {"query": "hello", "options": {"limit": 10}}
test
0
{"function_name": "test_valid_json_with_nested_values", "class_name": "TestParseToolCallArgs", "qualname": "TestParseToolCallArgs.test_valid_json_with_nested_values", "file_path": "lib/crewai/tests/utilities/test_agent_utils.py", "repo_id": "crewAIInc/crewAI", "loc": 6, "tested_modules": ["__future__", "typing", "pydan...
jax-ml/jax:jax/_src/pallas/pipelining/schedulers.py:check_async_done
# Context: import operator import jax from jax import numpy as jnp from jax._src.pallas.pipelining import internal def compute_grid_indices(linear_index: jax.Array, grid_size: Sequence[int]): ... def increment_grid(indices: Sequence[int | jax.Array], grid: Sequence[int], dynamic: bool): ... class PipelineContext: ... ...
def check_async_done(stage: internal.PipelineStage, scoreboard: Scoreboard, num_itrs: int | jax.Array, current_stage_counter: int | jax.Array, dynamic=False) -> bool | jax.Array: """Returns whether the async done stage can run.""" a...
function_simple
1
{"cognitive_complexity": 5, "loc": 34, "code_loc": 22, "docstring_loc": 1, "function_name": "check_async_done", "class_name": null, "qualname": "check_async_done", "file_path": "jax/_src/pallas/pipelining/schedulers.py", "repo_id": "jax-ml/jax", "has_docstring": true, "runnable_level": "file_runnable"}
ray-project/ray:python/ray/llm/_internal/batch/processor/utils.py:extract_resource_kwargs
# Context: from typing import Any, Dict, Optional, Tuple, Union def get_value_or_fallback(value: Any, fallback: Any) -> Any: ... def normalize_cpu_stage_concurrency(concurrency: Optional[Union[int, Tuple[int, int]]]) -> Dict[str, int]: ... def build_cpu_stage_map_kwargs(stage_cfg: _StageConfigBase) -> Dict[str, Any]: ...
def extract_resource_kwargs( runtime_env: Optional[Dict[str, Any]], num_cpus: Optional[float], memory: Optional[float], ) -> Dict[str, Any]: """Extract non-None resource kwargs for map_batches.""" kwargs = {} if runtime_env is not None: kwargs["runtime_env"] = runtime_env if num_cpus...
function_simple
0
{"cognitive_complexity": 3, "loc": 14, "code_loc": 8, "docstring_loc": 1, "function_name": "extract_resource_kwargs", "class_name": null, "qualname": "extract_resource_kwargs", "file_path": "python/ray/llm/_internal/batch/processor/utils.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "slib_...
huggingface/diffusers:src/diffusers/modular_pipelines/components_manager.py:ComponentsManager.remove
# Context: import torch import gc class CustomOffloadHook(ModelHook): ... class UserCustomOffloadHook: ... def custom_offload_with_hook(model_id: str, model: torch.nn.Module, execution_device: str | int | torch.device, offload_strategy: 'AutoOffloadStrategy' | None): ... class AutoOffloadStrategy: ... def summarize_di...
def remove(self, component_id: str = None): """ Remove a component from the ComponentsManager. Args: component_id (str): The ID of the component to remove """ if component_id not in self.components: logger.warning(f"Component '{component_id}' not found in...
function_complex
1
{"cognitive_complexity": 12, "loc": 31, "code_loc": 20, "docstring_loc": 6, "function_name": "remove", "class_name": "ComponentsManager", "qualname": "ComponentsManager.remove", "file_path": "src/diffusers/modular_pipelines/components_manager.py", "repo_id": "huggingface/diffusers", "has_docstring": true, "runnable_lev...
apache/airflow:providers/google/src/airflow/providers/google/cloud/hooks/gen_ai.py:GenAIGenerativeModelHook.count_tokens
# Context: from airflow.providers.google.common.hooks.base_google import ( PROVIDE_PROJECT_ID, GoogleBaseAsyncHook, GoogleBaseHook, ) from google.genai.types import ( BatchJob, ContentListUnion, ContentListUnionDict, CountTokensConfigOrDict, CountTokensResponse, ...
def count_tokens( self, location: str, model: str, contents: ContentListUnion | ContentListUnionDict, config: CountTokensConfigOrDict | None = None, project_id: str = PROVIDE_PROJECT_ID, ) -> CountTokensResponse: """ Use Count Tokens API to calculate t...
function_simple
1
{"cognitive_complexity": 0, "loc": 29, "code_loc": 7, "docstring_loc": 13, "function_name": "count_tokens", "class_name": "GenAIGenerativeModelHook", "qualname": "GenAIGenerativeModelHook.count_tokens", "file_path": "providers/google/src/airflow/providers/google/cloud/hooks/gen_ai.py", "repo_id": "apache/airflow", "has...
vllm-project/vllm:tests/reasoning/test_gptoss_reasoning_parser.py:test_gptoss_is_reasoning_end
# Context: import pytest from vllm.reasoning import ReasoningParser from vllm.reasoning.gptoss_reasoning_parser import GptOssReasoningParser def gpt_oss_tokenizer(): ... # Task: Write a Python test function `test_gptoss_is_reasoning_end` to verify the behavior of `gptoss_is_reasoning_end`. Module under test: transfo...
def test_gptoss_is_reasoning_end( output, is_reasoning_end, gpt_oss_tokenizer, ): output = gpt_oss_tokenizer.tokenize(output) parser: ReasoningParser = GptOssReasoningParser(gpt_oss_tokenizer) # Test is_reasoning_end output_ids = gpt_oss_tokenizer.convert_tokens_to_ids(output) actual_is...
test
1
{"function_name": "test_gptoss_is_reasoning_end", "class_name": null, "qualname": "test_gptoss_is_reasoning_end", "file_path": "tests/reasoning/test_gptoss_reasoning_parser.py", "repo_id": "vllm-project/vllm", "loc": 12, "tested_modules": ["transformers", "vllm.reasoning", "vllm.reasoning.gptoss_reasoning_parser"], "ha...
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/rag/loaders/postgres_loader.py:PostgresLoader.load
# Context: from urllib.parse import urlparse from psycopg2 import Error, connect from psycopg2.extras import RealDictCursor from crewai_tools.rag.base_loader import BaseLoader, LoaderResult from crewai_tools.rag.source_content import SourceContent class PostgresLoader(BaseLoader): # Task: Write a Python method `load`...
def load(self, source: SourceContent, **kwargs) -> LoaderResult: # type: ignore[override] """Load content from a PostgreSQL database table. Args: source: SQL query (e.g., "SELECT * FROM table_name") **kwargs: Additional arguments including db_uri Returns: L...
function_complex
0
{"cognitive_complexity": 31, "loc": 86, "code_loc": 63, "docstring_loc": 9, "function_name": "load", "class_name": "PostgresLoader", "qualname": "PostgresLoader.load", "file_path": "lib/crewai-tools/src/crewai_tools/rag/loaders/postgres_loader.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_level":...
browser-use/browser-use:browser_use/code_use/utils.py:truncate_message_content
Write a Python function `truncate_message_content` to truncate message content to max_length characters for history. Parameters: content: str, max_length: int Returns: str
def truncate_message_content(content: str, max_length: int = 10000) -> str: """Truncate message content to max_length characters for history.""" if len(content) <= max_length: return content # Truncate and add marker return content[:max_length] + f'\n\n[... truncated {len(content) - max_length} characters for his...
function_simple
0
{"cognitive_complexity": 1, "loc": 6, "code_loc": 3, "docstring_loc": 1, "function_name": "truncate_message_content", "class_name": null, "qualname": "truncate_message_content", "file_path": "browser_use/code_use/utils.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "self_contained"}
ray-project/ray:python/ray/_common/tests/test_wait_for_condition.py:TestWaitForCondition.test_immediate_true_condition
# Context: from ray._common.test_utils import async_wait_for_condition, wait_for_condition class TestAsyncWaitForCondition: ... class TestEdgeCases: ... class TestWaitForCondition: def test_condition_becomes_true(self): ... def test_timeout_raises_runtime_error(self): ... def test_condition_with_kwargs(se...
def test_immediate_true_condition(self): """Test that function returns immediately when condition is already true.""" def always_true(): return True wait_for_condition(always_true, timeout=5)
test
0
{"function_name": "test_immediate_true_condition", "class_name": "TestWaitForCondition", "qualname": "TestWaitForCondition.test_immediate_true_condition", "file_path": "python/ray/_common/tests/test_wait_for_condition.py", "repo_id": "ray-project/ray", "loc": 7, "tested_modules": ["ray._common.test_utils"], "has_docstr...
ray-project/ray:python/ray/serve/tests/unit/test_grpc_replica_result.py:TestSeparateLoop.test_streaming_blocked
# Context: import asyncio import pytest class FakegRPCUnaryCall: ... class FakegRPCStreamCall: ... def create_asyncio_event_loop_in_thread(): ... class TestSameLoop: ... class TestSeparateLoop: async def make_fake_unary_request(self, data, loop: asyncio.AbstractEventLoop): ... async def make_fake_streaming_re...
async def test_streaming_blocked(self, create_asyncio_event_loop_in_thread): """Use threading event to block async generator, check everything works""" loop, event = create_asyncio_event_loop_in_thread fut = asyncio.run_coroutine_threadsafe( self.make_fake_streaming_request( ...
test
0
{"function_name": "test_streaming_blocked", "class_name": "TestSeparateLoop", "qualname": "TestSeparateLoop.test_streaming_blocked", "file_path": "python/ray/serve/tests/unit/test_grpc_replica_result.py", "repo_id": "ray-project/ray", "loc": 23, "tested_modules": ["ray", "ray._common.test_utils", "ray.serve._private.co...
ray-project/ray:python/ray/data/_internal/cluster_autoscaler/default_autoscaling_coordinator.py:handle_timeout_errors
# Context: import functools from typing import Callable, Dict, List, Optional import ray import inspect class OngoingRequest: ... class DefaultAutoscalingCoordinator(AutoscalingCoordinator): ... class _AutoscalingCoordinatorActor: ... def get_or_create_autoscaling_coordinator(): ... # Task: Write a Python function `h...
def handle_timeout_errors( failure_counter_attr: str, operation_name: str, requester_id_param: str = "requester_id", error_msg_suffix: Optional[str] = None, on_error_return: Optional[Callable] = None, ): """Decorator to handle GetTimeoutError with consecutive failure tracking. Args: ...
function_complex
0
{"cognitive_complexity": 23, "loc": 90, "code_loc": 48, "docstring_loc": 18, "function_name": "handle_timeout_errors", "class_name": null, "qualname": "handle_timeout_errors", "file_path": "python/ray/data/_internal/cluster_autoscaler/default_autoscaling_coordinator.py", "repo_id": "ray-project/ray", "has_docstring": t...
apache/airflow:providers/google/tests/unit/google/cloud/operators/test_cloud_logging_sink.py:TestCloudLoggingUpdateSinksOperator.test_update_sink_raises_not_found
# Context: from unittest import mock import pytest from google.api_core.exceptions import AlreadyExists, GoogleAPICallError, InvalidArgument, NotFound from airflow.providers.google.cloud.operators.cloud_logging_sink import ( CloudLoggingCreateSinkOperator, CloudLoggingDeleteSinkOperator, CloudLoggingListSin...
def test_update_sink_raises_not_found(self, hook_mock, sink_config, update_mask): hook_instance = hook_mock.return_value hook_instance.get_sink.side_effect = NotFound("not found") operator = CloudLoggingUpdateSinkOperator( task_id=TASK_ID, sink_name=SINK_NAME, ...
test
1
{"function_name": "test_update_sink_raises_not_found", "class_name": "TestCloudLoggingUpdateSinksOperator", "qualname": "TestCloudLoggingUpdateSinksOperator.test_update_sink_raises_not_found", "file_path": "providers/google/tests/unit/google/cloud/operators/test_cloud_logging_sink.py", "repo_id": "apache/airflow", "loc...
huggingface/diffusers:tests/pipelines/qwenimage/test_qwenimage_img2img.py:QwenImageImg2ImgPipelineFastTests.test_inference
# Context: class QwenImageImg2ImgPipelineFastTests(unittest.TestCase, PipelineTesterMixin): pipeline_class = QwenImageImg2ImgPipeline params = frozenset(["prompt", "image", "height", "width", "guidance_scale", "true_cfg_scale", "strength"]) batch_params = frozenset(["prompt", "image"]) image_params = f...
def test_inference(self): device = "cpu" components = self.get_dummy_components() pipe = self.pipeline_class(**components) pipe.to(device) pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(device) image = pipe(**inputs).images gen...
test
1
{"function_name": "test_inference", "class_name": "QwenImageImg2ImgPipelineFastTests", "qualname": "QwenImageImg2ImgPipelineFastTests.test_inference", "file_path": "tests/pipelines/qwenimage/test_qwenimage_img2img.py", "repo_id": "huggingface/diffusers", "loc": 12, "tested_modules": ["transformers", "diffusers", "testi...
browser-use/browser-use:tests/ci/infrastructure/test_registry_validation.py:TestType1Pattern.test_type1_with_param_model
# Context: from browser_use.agent.views import ActionResult from browser_use.browser import BrowserSession from browser_use.tools.registry.service import Registry from browser_use.tools.registry.views import ActionModel as BaseActionModel import inspect from browser_use.tools.registry.views import ActionModel class Te...
def test_type1_with_param_model(self): """Type 1: action(params: Model, special_args...) should work""" registry = Registry() class ClickAction(BaseActionModel): index: int delay: float = 0.0 @registry.action('Click element', param_model=ClickAction) async def click_element(params: ClickAction, browse...
test
0
{"function_name": "test_type1_with_param_model", "class_name": "TestType1Pattern", "qualname": "TestType1Pattern.test_type1_with_param_model", "file_path": "tests/ci/infrastructure/test_registry_validation.py", "repo_id": "browser-use/browser-use", "loc": 26, "tested_modules": ["pydantic", "browser_use.agent.views", "b...
langflow-ai/langflow:src/backend/tests/unit/api/v2/test_workflow.py:TestWorkflowBackgroundQueueing.test_background_execution_queue_exception
# Context: from unittest.mock import AsyncMock, MagicMock, patch from uuid import UUID, uuid4 from httpx import AsyncClient from langflow.services.database.models.flow.model import Flow from lfx.services.deps import session_scope class TestWorkflowDeveloperAPIProtection: ... class TestWorkflowErrorHandling: ... class ...
async def test_background_execution_queue_exception( self, client: AsyncClient, created_api_key, mock_settings_dev_api_enabled, # noqa: ARG002 ): """Test handling of exceptions during task queueing.""" flow_id = uuid4() async with session_scope() as session: ...
test
1
{"function_name": "test_background_execution_queue_exception", "class_name": "TestWorkflowBackgroundQueueing", "qualname": "TestWorkflowBackgroundQueueing.test_background_execution_queue_exception", "file_path": "src/backend/tests/unit/api/v2/test_workflow.py", "repo_id": "langflow-ai/langflow", "loc": 38, "tested_modu...
infiniflow/ragflow:tools/es-to-oceanbase-migration/src/es_ob_migration/migrator.py:ESToOceanBaseMigrator:class_doc
Write a class-level docstring for `ESToOceanBaseMigrator` which has methods: `__init__`, `migrate`, `_check_connections`, `_analyze_es_index`, `_migrate_data`.
RAGFlow-specific migration orchestrator. This migrator is designed specifically for RAGFlow's data structure, handling the fixed schema and vector embeddings correctly.
documentation
1
{"doc_type": "class", "class_name": "ESToOceanBaseMigrator", "file_path": "tools/es-to-oceanbase-migration/src/es_ob_migration/migrator.py", "repo_id": "infiniflow/ragflow", "char_length": 169, "methods": ["__init__", "migrate", "_check_connections", "_analyze_es_index", "_migrate_data", "get_schema_preview", "get_data...
ray-project/ray:doc/source/serve/tutorials/model_composition_recsys/content/serve_recommendation_pipeline.py:ItemRankingModel.rank_items
# Context: import asyncio from typing import List, Dict from ray import serve class UserFeatureExtractor: ... class RecommendationService: ... class ItemRankingModel: CANDIDATE_ITEMS = [f"item_{i}" for i in range(1000)] def __init__(self): # In production, this is your cloud storage path or model regi...
async def rank_items( self, user_features_batch: List[Dict[str, float]] ) -> List[List[Dict[str, any]]]: """Rank candidate items for a batch of users.""" # Simulate model inference time await asyncio.sleep(0.05) # In production, use vectorized batch inferenc...
function_simple
0
{"cognitive_complexity": 0, "loc": 12, "code_loc": 2, "docstring_loc": 1, "function_name": "rank_items", "class_name": "ItemRankingModel", "qualname": "ItemRankingModel.rank_items", "file_path": "doc/source/serve/tutorials/model_composition_recsys/content/serve_recommendation_pipeline.py", "repo_id": "ray-project/ray",...
google/langextract:langextract/resolver.py:Resolver.extract_ordered_extractions
# Context: from collections.abc import Iterator, Mapping, Sequence import operator from absl import logging from langextract.core import data from langextract.core import format_handler as fh class AbstractResolver(abc.ABC): ... class ResolverParsingError(exceptions.LangExtractError): ... class WordAligner: ... def _t...
def extract_ordered_extractions( self, extraction_data: Sequence[Mapping[str, fh.ExtractionValueType]], ) -> Sequence[data.Extraction]: """Extracts and orders extraction data based on their associated indexes. This function processes a list of dictionaries, each containing pairs of extraction...
function_complex
1
{"cognitive_complexity": 37, "loc": 100, "code_loc": 63, "docstring_loc": 23, "function_name": "extract_ordered_extractions", "class_name": "Resolver", "qualname": "Resolver.extract_ordered_extractions", "file_path": "langextract/resolver.py", "repo_id": "google/langextract", "has_docstring": true, "runnable_level": "p...
crewAIInc/crewAI:lib/crewai/src/crewai/hooks/wrappers.py:AfterToolCallHookMethod:class_doc
Write a class-level docstring for `AfterToolCallHookMethod` which has methods: `__init__`, `__call__`, `__get__`.
Wrapper for methods marked as after_tool_call hooks within @CrewBase classes.
documentation
0
{"doc_type": "class", "class_name": "AfterToolCallHookMethod", "file_path": "lib/crewai/src/crewai/hooks/wrappers.py", "repo_id": "crewAIInc/crewAI", "char_length": 77, "methods": ["__init__", "__call__", "__get__"]}
browser-use/browser-use:examples/features/add_image_context.py:module_doc
Write a module-level docstring for the Python module `add_image_context` which contains function `image_to_base64`, function `create_sample_images`.
Show how to use sample_images to add image context for your task
documentation
0
{"doc_type": "module", "module_name": "add_image_context", "file_path": "examples/features/add_image_context.py", "repo_id": "browser-use/browser-use", "char_length": 64}
unclecode/crawl4ai:deploy/docker/tests/test_security_fixes.py:TestURLValidation.test_raw_url_allowed_when_enabled
# Context: class TestHookBuiltins(unittest.TestCase): ... class TestHooksEnabled(unittest.TestCase): ... class TestURLValidation(unittest.TestCase): def setUp(self): ... def validate_url_scheme(self, url: str, allow_raw: bool) -> bool: ... def test_file_url_blocked(self): ... def test_file_url_blocked...
def test_raw_url_allowed_when_enabled(self): """raw: URLs must be allowed when allow_raw=True.""" self.assertTrue(self.validate_url_scheme("raw:<html></html>", allow_raw=True)) self.assertTrue(self.validate_url_scheme("raw://<html></html>", allow_raw=True))
test
1
{"function_name": "test_raw_url_allowed_when_enabled", "class_name": "TestURLValidation", "qualname": "TestURLValidation.test_raw_url_allowed_when_enabled", "file_path": "deploy/docker/tests/test_security_fixes.py", "repo_id": "unclecode/crawl4ai", "loc": 4, "tested_modules": [], "has_docstring": true, "runnable_level"...
fastapi/fastapi:tests/test_request_params/test_header/test_optional_list.py:test_optional_list_alias_and_validation_alias_schema
# Context: import pytest from inline_snapshot import snapshot async def read_optional_list_str(p: Annotated[list[str] | None, Header()]): ... class HeaderModelOptionalListStr(BaseModel): ... async def read_model_optional_list_str(p: Annotated[HeaderModelOptionalListStr, Header()]): ... def test_optional_list_str_schem...
def test_optional_list_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == snapshot( [ { "required": False, "schema": { "anyOf": [ {"items": {"type": "string"}, "type...
test
1
{"function_name": "test_optional_list_alias_and_validation_alias_schema", "class_name": null, "qualname": "test_optional_list_alias_and_validation_alias_schema", "file_path": "tests/test_request_params/test_header/test_optional_list.py", "repo_id": "fastapi/fastapi", "loc": 17, "tested_modules": ["typing", "fastapi", "...
binary-husky/gpt_academic:crazy_functions/review_fns/paper_processor/paper_llm_ranker.py:PaperLLMRanker.rank_papers
# Context: from typing import List, Dict from crazy_functions.review_fns.data_sources.base_source import PaperMetadata from crazy_functions.review_fns.query_analyzer import SearchCriteria class PaperLLMRanker: def __init__(self, llm_kwargs: Dict = None): self.ranker = BGELLMRanker(llm_kwargs=llm_kwargs) ...
def rank_papers( self, query: str, papers: List[PaperMetadata], search_criteria: SearchCriteria = None, top_k: int = 40, use_rerank: bool = False, pre_filter_ratio: float = 0.5, max_papers: int = 150 ) -> List[PaperMetadata]: """对论文进行重排序""" ...
function_complex
1
{"cognitive_complexity": 60, "loc": 163, "code_loc": 109, "docstring_loc": 1, "function_name": "rank_papers", "class_name": "PaperLLMRanker", "qualname": "PaperLLMRanker.rank_papers", "file_path": "crazy_functions/review_fns/paper_processor/paper_llm_ranker.py", "repo_id": "binary-husky/gpt_academic", "has_docstring": ...
ray-project/ray:python/ray/data/tests/datasource/test_turbopuffer_datasink.py:TestSerialization.test_preserves_namespace_column_configuration
# Context: import pickle def mock_turbopuffer_module(monkeypatch): ... def sink(): ... def mock_client(): ... def sample_table(): ... def make_sink(**kwargs) -> TurbopufferDatasink: ... class TestConstructorValidation: ... class TestClientInitialization: ... class TestArrowTablePreparation: ... class TestSingleNamespa...
def test_preserves_namespace_column_configuration(self, mock_turbopuffer_module): """namespace_column configuration survives pickle round-trip.""" sink = make_sink(namespace=None, namespace_column="tenant") pickled = pickle.dumps(sink) unpickled = pickle.loads(pickled) assert un...
test
0
{"function_name": "test_preserves_namespace_column_configuration", "class_name": "TestSerialization", "qualname": "TestSerialization.test_preserves_namespace_column_configuration", "file_path": "python/ray/data/tests/datasource/test_turbopuffer_datasink.py", "repo_id": "ray-project/ray", "loc": 9, "tested_modules": ["t...
langflow-ai/langflow:src/backend/tests/unit/test_build_component_index.py:TestBuildComponentIndexScript.test_build_script_creates_valid_structure
# Context: from pathlib import Path from unittest.mock import patch import pytest import sys class TestBuildComponentIndexScript: def test_build_script_minifies_json(self, tmp_path): ... def test_build_script_sha256_integrity(self): ... def test_build_script_handles_import_errors(self): ... # Task: Write ...
def test_build_script_creates_valid_structure(self): """Test that the build script creates a valid index structure.""" import importlib.util import sys # Get path to build script script_path = Path(__file__).parent.parent.parent.parent / "scripts" / "build_component_index.py" ...
test
1
{"function_name": "test_build_script_creates_valid_structure", "class_name": "TestBuildComponentIndexScript", "qualname": "TestBuildComponentIndexScript.test_build_script_creates_valid_structure", "file_path": "src/backend/tests/unit/test_build_component_index.py", "repo_id": "langflow-ai/langflow", "loc": 38, "tested_...
ray-project/ray:python/ray/train/v2/tests/test_config.py:test_scaling_config_validation
# Context: import pytest from ray.train import RunConfig, ScalingConfig def test_scaling_config_accelerator_type(): ... def test_scaling_config_tpu_min_workers_multiple(): ... def test_storage_filesystem_repr(): ... def test_scaling_config_default_workers(): ... # Task: Write a Python test function `test_scaling_conf...
def test_scaling_config_validation(): assert ScalingConfig( num_workers=2, use_gpu=True, resources_per_worker={"CPU": 1} ).total_resources == {"CPU": 2, "GPU": 2} with pytest.raises(ValueError, match="`use_gpu` is False but `GPU` was found in"): ScalingConfig(num_workers=2, use_gpu=False, r...
test
0
{"function_name": "test_scaling_config_validation", "class_name": null, "qualname": "test_scaling_config_validation", "file_path": "python/ray/train/v2/tests/test_config.py", "repo_id": "ray-project/ray", "loc": 30, "tested_modules": ["ray.train"], "has_docstring": false, "runnable_level": "plib_runnable"}
vllm-project/vllm:tests/distributed/test_weight_transfer.py:TestIPCWeightTransferUpdateInfoValidation.test_valid_update_info_from_pickled
# Context: import base64 import pickle import pytest import torch from torch.multiprocessing.reductions import reduce_tensor from vllm.distributed.weight_transfer.ipc_engine import ( IPCWeightTransferEngine, IPCWeightTransferInitInfo, IPCWeightTransferUpdateInfo, ) def create_mock_parallel_config(rank: int...
def test_valid_update_info_from_pickled(self): """Test creating IPCWeightTransferUpdateInfo from pickled handles.""" if torch.cuda.device_count() < 1: pytest.skip("Need at least 1 GPU for this test") dummy_tensor = torch.ones(10, 10, device="cuda:0") ipc_handle = reduce_tens...
test
1
{"function_name": "test_valid_update_info_from_pickled", "class_name": "TestIPCWeightTransferUpdateInfoValidation", "qualname": "TestIPCWeightTransferUpdateInfoValidation.test_valid_update_info_from_pickled", "file_path": "tests/distributed/test_weight_transfer.py", "repo_id": "vllm-project/vllm", "loc": 20, "tested_mo...
Comfy-Org/ComfyUI:comfy_api/latest/_ui.py:ImageSaveHelper._create_animated_png_metadata
# Context: import json from PIL.PngImagePlugin import PngInfo from comfy.cli_args import args from ._io import ComfyNode, FolderType, Image, _UIOutput class SavedResult(dict): ... class SavedImages(_UIOutput): ... class SavedAudios(_UIOutput): ... def _get_directory_by_folder_type(folder_type: FolderType) -> str: ... ...
def _create_animated_png_metadata(cls: type[ComfyNode] | None) -> PngInfo | None: """Creates a PngInfo object with prompt and extra_pnginfo for animated PNGs (APNG).""" if args.disable_metadata or cls is None or not cls.hidden: return None metadata = PngInfo() if cls.hidden.p...
function_complex
1
{"cognitive_complexity": 6, "loc": 23, "code_loc": 21, "docstring_loc": 1, "function_name": "_create_animated_png_metadata", "class_name": "ImageSaveHelper", "qualname": "ImageSaveHelper._create_animated_png_metadata", "file_path": "comfy_api/latest/_ui.py", "repo_id": "Comfy-Org/ComfyUI", "has_docstring": true, "runna...
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_connection.py:check_connection
# Context: import time from psycopg import Connection, sql from psycopg.rows import dict_row from ._shared import ( TOKEN_CREDENTIAL_SCOPE, BaseConnectionInfo, BasicAuth, Extension, get_username_password, ) class ConnectionInfo(BaseConnectionInfo): ... def create_extensions(required_extensions: lis...
def check_connection(conn: Connection, /, required_extensions: list[Extension] = []): """Check if the connection to Azure Database for PostgreSQL is valid and required extensions are installed. :param conn: Connection to the Azure Database for PostgreSQL. :type conn: Connection :param required_extensio...
function_complex
1
{"cognitive_complexity": 13, "loc": 55, "code_loc": 45, "docstring_loc": 8, "function_name": "check_connection", "class_name": null, "qualname": "check_connection", "file_path": "llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_connection....
github/spec-kit:src/specify_cli/extensions.py:version_satisfies
# Context: from packaging import version as pkg_version from packaging.specifiers import SpecifierSet, InvalidSpecifier class ExtensionError(Exception): ... class ValidationError(ExtensionError): ... class CompatibilityError(ExtensionError): ... class ExtensionManifest: ... class ExtensionRegistry: ... class Extension...
def version_satisfies(current: str, required: str) -> bool: """Check if current version satisfies required version specifier. Args: current: Current version (e.g., "0.1.5") required: Required version specifier (e.g., ">=0.1.0,<2.0.0") Returns: True if version satisfies requirement ...
function_simple
0
{"cognitive_complexity": 1, "loc": 16, "code_loc": 6, "docstring_loc": 9, "function_name": "version_satisfies", "class_name": null, "qualname": "version_satisfies", "file_path": "src/specify_cli/extensions.py", "repo_id": "github/spec-kit", "has_docstring": true, "runnable_level": "project_runnable"}
streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_websocket_test.py:TestStarletteSessionClientClientContext:class_doc
Write a class-level docstring for `TestStarletteSessionClientClientContext` which has methods: `test_client_context_returns_starlette_context`.
Tests for client_context property on StarletteSessionClient.
documentation
1
{"doc_type": "class", "class_name": "TestStarletteSessionClientClientContext", "file_path": "lib/tests/streamlit/web/server/starlette/starlette_websocket_test.py", "repo_id": "streamlit/streamlit", "char_length": 60, "methods": ["test_client_context_returns_starlette_context"]}
ray-project/ray:python/ray/data/stats.py:DatasetSummary._extract_column_from_table
# Context: from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union import pyarrow as pa class _DtypeAggregators: ... def _numerical_aggregators(column: str) -> List[AggregateFnV2]: ... def _temporal_aggregators(column: str) -> List[AggregateFnV2]: ... def _basic_aggregators(column: str) -> ...
def _extract_column_from_table( self, table: pa.Table, column: str ) -> Optional[dict]: """Extract a column from a PyArrow table if it exists. Args: table: PyArrow table to extract from column: Column name to extract Returns: DataFrame with 'stat...
function_simple
0
{"cognitive_complexity": 1, "loc": 17, "code_loc": 4, "docstring_loc": 9, "function_name": "_extract_column_from_table", "class_name": "DatasetSummary", "qualname": "DatasetSummary._extract_column_from_table", "file_path": "python/ray/data/stats.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level"...
vllm-project/vllm:vllm/model_executor/layers/fused_moe/config.py:_get_config_dtype_str
# Context: import torch def _quant_flags_to_group_shape(quant_dtype: torch.dtype | str | None, per_act_token_quant: bool, per_out_ch_quant: bool, block_shape: list[int] | None) -> tuple[GroupShape | None, GroupShape | None]: ... class RoutingMethodType(IntEnum): ... def get_routing_method_type(scoring_func: str, top_k...
def _get_config_dtype_str( dtype: torch.dtype, use_fp8_w8a8: bool = False, use_fp8_w8a16: bool = False, use_int8_w8a16: bool = False, use_int4_w4a16: bool = False, ocp_mx_scheme: str | None = None, ) -> str | None: """ Return a string used to construct the filename that contains the ...
function_complex
1
{"cognitive_complexity": 6, "loc": 31, "code_loc": 13, "docstring_loc": 5, "function_name": "_get_config_dtype_str", "class_name": null, "qualname": "_get_config_dtype_str", "file_path": "vllm/model_executor/layers/fused_moe/config.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "plib_runn...
RVC-Boss/GPT-SoVITS:GPT_SoVITS/eres2net/kaldi.py:_get_waveform_and_window_properties
# Context: from typing import Tuple from torch import Tensor def _get_epsilon(device, dtype): ... def _next_power_of_2(x: int) -> int: ... def _get_strided(waveform: Tensor, window_size: int, window_shift: int, snip_edges: bool) -> Tensor: ... def _feature_window_function(window_type: str, window_size: int, blackman_c...
def _get_waveform_and_window_properties( waveform: Tensor, channel: int, sample_frequency: float, frame_shift: float, frame_length: float, round_to_power_of_two: bool, preemphasis_coefficient: float, ) -> Tuple[Tensor, int, int, int]: r"""Gets the waveform and window properties""" ch...
function_simple
1
{"cognitive_complexity": 1, "loc": 27, "code_loc": 16, "docstring_loc": 1, "function_name": "_get_waveform_and_window_properties", "class_name": null, "qualname": "_get_waveform_and_window_properties", "file_path": "GPT_SoVITS/eres2net/kaldi.py", "repo_id": "RVC-Boss/GPT-SoVITS", "has_docstring": true, "runnable_level"...
keras-team/keras:keras/src/layers/pooling/adaptive_pooling1d_test.py:AdaptivePooling1DLayerTest.test_average_pooling_get_config
# Context: from keras.src import layers class AdaptivePooling1DLayerTest(testing.TestCase): def _run_layer_test(self, layer_class, x_np, output_size, data_format): ... def test_average_pooling_basic_shapes(self): ... def test_max_pooling_basic_shapes(self): ... def test_average_pooling_channels_last(se...
def test_average_pooling_get_config(self): """Test get_config() serialization for AdaptiveAveragePooling1D.""" layer = layers.AdaptiveAveragePooling1D( output_size=32, data_format="channels_first" ) config = layer.get_config() self.assertEqual(config["output_size"], (...
test
1
{"function_name": "test_average_pooling_get_config", "class_name": "AdaptivePooling1DLayerTest", "qualname": "AdaptivePooling1DLayerTest.test_average_pooling_get_config", "file_path": "keras/src/layers/pooling/adaptive_pooling1d_test.py", "repo_id": "keras-team/keras", "loc": 8, "tested_modules": ["keras.src", "keras.s...
langflow-ai/langflow:src/backend/tests/unit/core/test_celeryconfig.py:TestCeleryConfigStructure.test_result_backend_contains_host
# Context: from langflow.core import celeryconfig class TestCeleryConfigAcceptContent: ... class TestCeleryConfigVariables: ... class TestCeleryConfigStructure: def test_broker_url_contains_protocol(self): ... def test_result_backend_contains_protocol(self): ... def test_broker_url_contains_host(self): .....
def test_result_backend_contains_host(self): """Test that result_backend contains a host component.""" result_backend = celeryconfig.result_backend # Remove protocol part if "://" in result_backend: host_part = result_backend.split("://")[1] assert len(host_part) ...
test
1
{"function_name": "test_result_backend_contains_host", "class_name": "TestCeleryConfigStructure", "qualname": "TestCeleryConfigStructure.test_result_backend_contains_host", "file_path": "src/backend/tests/unit/core/test_celeryconfig.py", "repo_id": "langflow-ai/langflow", "loc": 7, "tested_modules": ["langflow.core"], ...
ray-project/ray:python/ray/data/expressions.py:Expr.__or__
# Context: from typing import ( TYPE_CHECKING, Any, Callable, Dict, Generic, List, Optional, Tuple, Type, TypeVar, Union, ) class Operation(Enum): ... class _ExprVisitor(ABC, Generic[T]): ... class _PyArrowExpressionVisitor(_ExprVisitor['pyarrow.compute.Expression']): ... cl...
def __or__(self, other: Any) -> "Expr": """Logical OR operator (|).""" return self._bin(other, Operation.OR)
function_simple
0
{"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "__or__", "class_name": "Expr", "qualname": "Expr.__or__", "file_path": "python/ray/data/expressions.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "file_runnable"}
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/embedding_distance/base.py:_EmbeddingDistanceChainMixin._chebyshev_distance
# Context: from typing import Any from scipy.spatial.distance import chebyshev def _import_numpy() -> Any: ... def _check_numpy() -> bool: ... def _embedding_factory() -> Embeddings: ... class EmbeddingDistance(str, Enum): ... class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator): ... class P...
def _chebyshev_distance(a: Any, b: Any) -> Any: """Compute the Chebyshev distance between two vectors. Args: a (np.ndarray): The first vector. b (np.ndarray): The second vector. Returns: np.floating: The Chebyshev distance. """ try: ...
function_simple
1
{"cognitive_complexity": 3, "loc": 20, "code_loc": 8, "docstring_loc": 9, "function_name": "_chebyshev_distance", "class_name": "_EmbeddingDistanceChainMixin", "qualname": "_EmbeddingDistanceChainMixin._chebyshev_distance", "file_path": "libs/langchain/langchain_classic/evaluation/embedding_distance/base.py", "repo_id"...
ray-project/ray:python/ray/tune/tests/test_env_callbacks.py:test_no_env_variable
# Context: import os from ray.tune.constants import RAY_TUNE_CALLBACKS_ENV_VAR from ray.tune.utils.callback import Callback, _initialize_env_callbacks class MockCallback(Callback): ... def test_env_callbacks_loading(mock_import, env_value, expected_callback_count): ... def test_callback_loading_errors(mock_import, env...
def test_no_env_variable(): """Test that no callbacks are loaded when environment variable is not set.""" if RAY_TUNE_CALLBACKS_ENV_VAR in os.environ: del os.environ[RAY_TUNE_CALLBACKS_ENV_VAR] callbacks = _initialize_env_callbacks() assert len(callbacks) == 0
test
0
{"function_name": "test_no_env_variable", "class_name": null, "qualname": "test_no_env_variable", "file_path": "python/ray/tune/tests/test_env_callbacks.py", "repo_id": "ray-project/ray", "loc": 7, "tested_modules": ["ray.tune.constants", "ray.tune.utils.callback"], "has_docstring": true, "runnable_level": "plib_runnab...
crewAIInc/crewAI:lib/crewai/tests/rag/embeddings/test_backward_compatibility.py:TestLegacyConfigurationFormats.test_legacy_google_with_model_key
# Context: from crewai.rag.embeddings.providers.google.generative_ai import GenerativeAiProvider class TestGoogleProviderAlias: ... class TestModelKeyBackwardCompatibility: ... class TestTaskTypeConfiguration: ... class TestFactoryBackwardCompatibility: ... class TestDocumentationCodeSnippets: ... class TestLegacyCon...
def test_legacy_google_with_model_key(self): """Test legacy Google config using 'model' instead of 'model_name'.""" provider = GenerativeAiProvider( api_key="test-key", model="text-embedding-005", task_type="retrieval_document", ) assert provider.model...
test
0
{"function_name": "test_legacy_google_with_model_key", "class_name": "TestLegacyConfigurationFormats", "qualname": "TestLegacyConfigurationFormats.test_legacy_google_with_model_key", "file_path": "lib/crewai/tests/rag/embeddings/test_backward_compatibility.py", "repo_id": "crewAIInc/crewAI", "loc": 9, "tested_modules":...
binary-husky/gpt_academic:crazy_functions/review_fns/data_sources/pubmed_source.py:PubMedSource.get_latest_papers
# Context: from typing import List, Optional, Dict, Union from crazy_functions.review_fns.data_sources.base_source import DataSource, PaperMetadata async def example_usage(): ... class PubMedSource(DataSource): API_KEYS = [ def __init__(self, api_key: str = None): """初始化 Args: api...
async def get_latest_papers( self, days: int = 7, limit: int = 100 ) -> List[PaperMetadata]: """获取最新论文 Args: days: 最近几天的论文 limit: 返回结果数量限制 Returns: 最新论文列表 """ query = f"last {days} days[dp]" return await se...
function_simple
1
{"cognitive_complexity": 0, "loc": 16, "code_loc": 2, "docstring_loc": 9, "function_name": "get_latest_papers", "class_name": "PubMedSource", "qualname": "PubMedSource.get_latest_papers", "file_path": "crazy_functions/review_fns/data_sources/pubmed_source.py", "repo_id": "binary-husky/gpt_academic", "has_docstring": tr...
infiniflow/ragflow:test/testcases/test_web_api/test_kb_app/test_kb_tags_meta.py:TestKbTagsMeta.test_list_tags
# Context: import pytest from common import ( delete_knowledge_graph, kb_basic_info, kb_get_meta, kb_update_metadata_setting, knowledge_graph, list_tags, list_tags_from_kbs, rename_tags, rm_tags, update_chunk, ) def _wait_for_tag(auth, kb_id, tag, timeout): ... def _seed_tag(aut...
def test_list_tags(self, WebApiAuth, add_dataset): kb_id = add_dataset res = list_tags(WebApiAuth, kb_id) assert res["code"] == 0, res assert isinstance(res["data"], list), res
test
1
{"function_name": "test_list_tags", "class_name": "TestKbTagsMeta", "qualname": "TestKbTagsMeta.test_list_tags", "file_path": "test/testcases/test_web_api/test_kb_app/test_kb_tags_meta.py", "repo_id": "infiniflow/ragflow", "loc": 5, "tested_modules": ["common", "configs", "libs.auth", "utils"], "has_docstring": false, ...
ray-project/ray:python/ray/data/tests/test_map_batches.py:test_map_batches_combine_empty_blocks
# Context: import ray def process_timestamp_data(row): ... def process_timestamp_data_batch_arrow(batch: pa.Table) -> pa.Table: ... def process_timestamp_data_batch_pandas(batch: pd.DataFrame) -> pd.DataFrame: ... def test_map_batches_basic(ray_start_regular_shared, tmp_path, restore_data_context, target_max_block_siz...
def test_map_batches_combine_empty_blocks( ray_start_regular_shared, target_max_block_size_infinite_or_default ): xs = [x % 3 for x in list(range(100))] # ds1 has 1 block which contains 100 rows. ds1 = ray.data.from_items(xs).repartition(1).sort("item").map_batches(lambda x: x) assert ds1._block_nu...
test
0
{"function_name": "test_map_batches_combine_empty_blocks", "class_name": null, "qualname": "test_map_batches_combine_empty_blocks", "file_path": "python/ray/data/tests/test_map_batches.py", "repo_id": "ray-project/ray", "loc": 22, "tested_modules": ["typing", "ray.data._internal.arrow_ops.transform_pyarrow", "ray.data....
jax-ml/jax:tests/pallas/mgpu_examples_test.py:module_doc
Write a module-level docstring for the Python module `mgpu_examples_test` which contains class `TuningConfig`, function `matmul0`, function `matmul1`, function `matmul2`, function `matmul3`.
Tests for examples from Pallas:MGPU documentation.
documentation
1
{"doc_type": "module", "module_name": "mgpu_examples_test", "file_path": "tests/pallas/mgpu_examples_test.py", "repo_id": "jax-ml/jax", "char_length": 50}
langflow-ai/langflow:src/backend/tests/unit/components/processing/test_text_operations_component.py:TestTextOperationsExtract.test_extract_invalid_regex
# Context: import pytest from lfx.components.processing.text_operations import TextOperations class TestTextOperationsComponent(ComponentTestBaseWithoutClient): ... class TestTextOperationsWordCount: ... class TestTextOperationsCaseConversion: ... class TestTextOperationsReplace: ... class TestTextOperationsHead: ... ...
def test_extract_invalid_regex(self): """Test extraction with invalid regex raises ValueError (Bug #3 fix).""" component = TextOperations() component.extract_pattern = "[invalid" component.max_matches = 10 with pytest.raises(ValueError, match="Invalid regex pattern"): ...
test
1
{"function_name": "test_extract_invalid_regex", "class_name": "TestTextOperationsExtract", "qualname": "TestTextOperationsExtract.test_extract_invalid_regex", "file_path": "src/backend/tests/unit/components/processing/test_text_operations_component.py", "repo_id": "langflow-ai/langflow", "loc": 8, "tested_modules": ["l...
666ghj/BettaFish:ReportEngine/renderers/pdf_layout_optimizer.py:PDFLayoutOptimizer.__init__
# Context: from typing import Any, Dict, List, Optional, Tuple class KPICardLayout: ... class CalloutLayout: ... class TableLayout: ... class ChartLayout: ... class GridLayout: ... class DataBlockLayout: ... class PageLayout: ... class PDFLayoutConfig: ... class PDFLayoutOptimizer: CHAR_WIDTH_FACTOR = { def _...
def __init__(self, config: Optional[PDFLayoutConfig] = None): """ 初始化优化器 参数: config: 布局配置,如果为None则使用默认配置 """ self.config = config or self._create_default_config() self.optimization_log = []
function_simple
1
{"cognitive_complexity": 1, "loc": 9, "code_loc": 2, "docstring_loc": 6, "function_name": "__init__", "class_name": "PDFLayoutOptimizer", "qualname": "PDFLayoutOptimizer.__init__", "file_path": "ReportEngine/renderers/pdf_layout_optimizer.py", "repo_id": "666ghj/BettaFish", "has_docstring": true, "runnable_level": "fil...
crewAIInc/crewAI:lib/crewai/tests/llms/openai/test_openai.py:test_openai_get_client_params_with_env_var
# Context: import os from unittest.mock import patch, MagicMock from crewai.llms.providers.openai.completion import OpenAICompletion, ResponsesAPIResult from crewai.llms.providers.openai.completion import OpenAICompletion def test_openai_completion_is_used_when_openai_provider(): ... def test_openai_completion_is_used...
def test_openai_get_client_params_with_env_var(): """ Test that _get_client_params uses OPENAI_BASE_URL environment variable as fallback """ with patch.dict(os.environ, { "OPENAI_BASE_URL": "https://env.openai.com/v1", }): llm = OpenAICompletion(model="gpt-4o") client_params ...
test
0
{"function_name": "test_openai_get_client_params_with_env_var", "class_name": null, "qualname": "test_openai_get_client_params_with_env_var", "file_path": "lib/crewai/tests/llms/openai/test_openai.py", "repo_id": "crewAIInc/crewAI", "loc": 10, "tested_modules": ["typing", "crewai.llm", "crewai.llms.providers.openai.com...
vllm-project/vllm:tests/entrypoints/openai/test_completion_with_function_calling.py:test_named_tool_use
# Context: import json import jsonschema import openai # use the official client for correctness check import pytest def server(): ... async def client(server): ... async def test_function_tool_use(client: openai.AsyncOpenAI, model_name: str, stream: bool, tool_choice: str | dict, enable_thinking: bool): ... def k2_s...
async def test_named_tool_use( client: openai.AsyncOpenAI, sample_json_schema, ): messages = [ {"role": "system", "content": "you are a helpful assistant"}, { "role": "user", "content": ( "Give an example JSON for an employee profile using the specifie...
test
1
{"function_name": "test_named_tool_use", "class_name": null, "qualname": "test_named_tool_use", "file_path": "tests/entrypoints/openai/test_completion_with_function_calling.py", "repo_id": "vllm-project/vllm", "loc": 75, "tested_modules": ["utils"], "has_docstring": false, "runnable_level": "project_runnable"}
exo-explore/exo:src/exo/utils/info_gatherer/info_gatherer.py:_get_bridge_members
# Context: import anyio from loguru import logger async def _get_thunderbolt_devices() -> set[str] | None: ... async def _get_bridge_services() -> dict[str, str] | None: ... async def _find_thunderbolt_bridge(bridge_services: dict[str, str], thunderbolt_devices: set[str]) -> str | None: ... async def _is_service_enabl...
async def _get_bridge_members(bridge_device: str) -> set[str]: """Get member interfaces of a bridge device via ifconfig.""" result = await anyio.run_process( ["ifconfig", bridge_device], check=False, ) if result.returncode != 0: logger.debug(f"ifconfig {bridge_device} failed with...
function_complex
0
{"cognitive_complexity": 7, "loc": 20, "code_loc": 16, "docstring_loc": 1, "function_name": "_get_bridge_members", "class_name": null, "qualname": "_get_bridge_members", "file_path": "src/exo/utils/info_gatherer/info_gatherer.py", "repo_id": "exo-explore/exo", "has_docstring": true, "runnable_level": "project_runnable"...
apache/airflow:task-sdk/tests/task_sdk/test_crypto.py:TestRealFernet.test_rotate_reencrypt_with_primary_key
# Context: from cryptography.fernet import Fernet from airflow.sdk.crypto import _NullFernet, _RealFernet, get_fernet from cryptography.fernet import MultiFernet class TestNullFernet: ... class TestGetFernet: ... class TestRealFernet: def test_encryption(self): ... # Task: Write a Python test method `test_rotate...
def test_rotate_reencrypt_with_primary_key(self): """rotate() should re-encrypt data with the primary key.""" from cryptography.fernet import MultiFernet key1 = Fernet.generate_key() key2 = Fernet.generate_key() # encrypt with key1 only encrypted_with_key1 = Fernet(key1...
test
1
{"function_name": "test_rotate_reencrypt_with_primary_key", "class_name": "TestRealFernet", "qualname": "TestRealFernet.test_rotate_reencrypt_with_primary_key", "file_path": "task-sdk/tests/task_sdk/test_crypto.py", "repo_id": "apache/airflow", "loc": 20, "tested_modules": ["__future__", "cryptography.fernet", "airflow...
Comfy-Org/ComfyUI:tests-unit/comfy_api_test/input_impl_test.py:test_container_to_output_format_empty_string
# Context: from comfy_api.input_impl.video_types import ( container_to_output_format, get_open_write_kwargs, ) def test_container_to_output_format_none(): ... def test_container_to_output_format_comma_separated(): ... def test_container_to_output_format_single(): ... def test_get_open_write_kwargs_filepath_no_...
def test_container_to_output_format_empty_string(): """Test that an empty string input returns None. `None` arg allows default auto-detection.""" assert container_to_output_format("") is None
test
1
{"function_name": "test_container_to_output_format_empty_string", "class_name": null, "qualname": "test_container_to_output_format_empty_string", "file_path": "tests-unit/comfy_api_test/input_impl_test.py", "repo_id": "Comfy-Org/ComfyUI", "loc": 3, "tested_modules": ["comfy_api.input_impl.video_types", "comfy_api.util"...
google/langextract:tests/provider_schema_test.py:ProviderSchemaDiscoveryTest:class_doc
Write a class-level docstring for `ProviderSchemaDiscoveryTest` (inherits from absltest.TestCase) which has methods: `test_gemini_returns_gemini_schema`, `test_ollama_returns_format_mode_schema`, `test_openai_returns_none`.
Tests for provider schema discovery via get_schema_class().
documentation
1
{"doc_type": "class", "class_name": "ProviderSchemaDiscoveryTest", "file_path": "tests/provider_schema_test.py", "repo_id": "google/langextract", "char_length": 59, "methods": ["test_gemini_returns_gemini_schema", "test_ollama_returns_format_mode_schema", "test_openai_returns_none"]}
apache/airflow:providers/openlineage/tests/unit/openlineage/utils/test_sql_hook_lineage.py:TestGetHookConnId.test_returns_none_when_nothing_available
# Context: from unittest import mock from airflow.providers.openlineage.utils.sql_hook_lineage import ( _create_ol_event_pair, _get_hook_conn_id, _resolve_namespace, emit_lineage_from_sql_extras, ) def _make_extra(sql, job_id, hook, default_db): ... class TestResolveNamespace: ... class TestCreateOlEve...
def test_returns_none_when_nothing_available(self): hook = mock.MagicMock(spec=[]) assert _get_hook_conn_id(hook) is None
test
1
{"function_name": "test_returns_none_when_nothing_available", "class_name": "TestGetHookConnId", "qualname": "TestGetHookConnId.test_returns_none_when_nothing_available", "file_path": "providers/openlineage/tests/unit/openlineage/utils/test_sql_hook_lineage.py", "repo_id": "apache/airflow", "loc": 3, "tested_modules": ...
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/tavily_extractor_tool/tavily_extractor_tool.py:TavilyExtractorTool._arun
# Context: import json class TavilyExtractorToolSchema(BaseModel): ... class TavilyExtractorTool(BaseTool): model_config = ConfigDict(arbitrary_types_allowed=True) def __init__(self, **kwargs: Any): """Initializes the TavilyExtractorTool. Args: **kwargs: Additional keyword argumen...
async def _arun( self, urls: list[str] | str, ) -> str: """Asynchronously extracts content from the given URL(s). Args: urls: The URL(s) to extract data from. Returns: A JSON string containing the extracted data. """ if not self.async...
function_simple
0
{"cognitive_complexity": 1, "loc": 24, "code_loc": 11, "docstring_loc": 8, "function_name": "_arun", "class_name": "TavilyExtractorTool", "qualname": "TavilyExtractorTool._arun", "file_path": "lib/crewai-tools/src/crewai_tools/tools/tavily_extractor_tool/tavily_extractor_tool.py", "repo_id": "crewAIInc/crewAI", "has_do...
ray-project/ray:python/ray/data/_internal/datasource/databricks_credentials.py:module_doc
Write a module-level docstring for the Python module `databricks_credentials` which contains class `DatabricksCredentialProvider`, class `StaticCredentialProvider`, class `EnvironmentCredentialProvider`, function `resolve_credential_provider`, function `build_headers`.
Databricks credential providers for Ray Data. This module provides credential abstraction for Databricks authentication, supporting static tokens with extensibility for future credential sources.
documentation
0
{"doc_type": "module", "module_name": "databricks_credentials", "file_path": "python/ray/data/_internal/datasource/databricks_credentials.py", "repo_id": "ray-project/ray", "char_length": 196}
huggingface/transformers:src/transformers/models/qwen3_vl/modular_qwen3_vl.py:Qwen3VLForConditionalGeneration.forward
# Context: import torch from ...cache_utils import Cache, DynamicCache from ...processing_utils import ProcessingKwargs, Unpack from ..qwen2_vl.modeling_qwen2_vl import ( PatchEmbed, Qwen2VLModel, Qwen2VLModelOutputWithPast, Qwen2VLPreTrainedModel, TransformersKwargs, VisionAttention, Vision...
def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None =...
function_simple
0
{"cognitive_complexity": 2, "loc": 97, "code_loc": 28, "docstring_loc": 46, "function_name": "forward", "class_name": "Qwen3VLForConditionalGeneration", "qualname": "Qwen3VLForConditionalGeneration.forward", "file_path": "src/transformers/models/qwen3_vl/modular_qwen3_vl.py", "repo_id": "huggingface/transformers", "has...
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/aio/_connection.py:AsyncConnectionInfo:class_doc
Write a class-level docstring for `AsyncConnectionInfo` (inherits from BaseConnectionInfo) which has methods: various methods.
Base connection information for Azure Database for PostgreSQL connections. :param host: Hostname of the Azure Database for PostgreSQL server. :type host: str | None :param dbname: Name of the database to connect to. :type dbname: str :param port: Port number for the connection. :type port: int :param credentials: Cred...
documentation
1
{"doc_type": "class", "class_name": "AsyncConnectionInfo", "file_path": "llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/aio/_connection.py", "repo_id": "run-llama/llama_index", "char_length": 467, "methods": []}
browser-use/browser-use:tests/ci/test_agent_planning.py:test_flash_mode_schema_excludes_plan_fields
# Context: from browser_use.agent.views import ( AgentOutput, PlanItem, ) from browser_use.tools.service import Tools def _make_agent_output(**overrides) -> AgentOutput: ... def _make_agent(browser_session, mock_llm, **kwargs): ... async def test_plan_generation_from_plan_update(browser_session, mock_llm): ... async...
async def test_flash_mode_schema_excludes_plan_fields(): tools = Tools() ActionModel = tools.registry.create_action_model() FlashOutput = AgentOutput.type_with_custom_actions_flash_mode(ActionModel) schema = FlashOutput.model_json_schema() assert 'current_plan_item' not in schema['properties'] assert 'plan_updat...
test
0
{"function_name": "test_flash_mode_schema_excludes_plan_fields", "class_name": null, "qualname": "test_flash_mode_schema_excludes_plan_fields", "file_path": "tests/ci/test_agent_planning.py", "repo_id": "browser-use/browser-use", "loc": 9, "tested_modules": ["browser_use.agent.views", "browser_use.tools.service", "brow...
vllm-project/vllm:vllm/model_executor/offloader/prefetch.py:module_doc
Write a module-level docstring for the Python module `prefetch` which contains class `ParamInfo`, class `StaticBufferPool`, class `PrefetchOffloader`, class `_ModuleOffloader`, class `_BaseParamOffloader`.
Prefetch-based CPU offloading with async prefetching. Uses static buffers and event-based stream forking for torch.compile + CUDA graph compatibility. Events allow the copy stream to join CUDA graph captures, ensuring H2D copies are properly captured.
documentation
1
{"doc_type": "module", "module_name": "prefetch", "file_path": "vllm/model_executor/offloader/prefetch.py", "repo_id": "vllm-project/vllm", "char_length": 252}
google/langextract:langextract/data_lib.py:enum_asdict_factory
# Context: import dataclasses import enum import numbers from typing import Any, Iterable, Mapping def annotated_document_to_dict(adoc: data.AnnotatedDocument | None) -> dict[str, Any]: ... def dict_to_annotated_document(adoc_dic: Mapping[str, Any]) -> data.AnnotatedDocument: ... # Task: Write a Python function `enum...
def enum_asdict_factory(items: Iterable[tuple[str, Any]]) -> dict[str, Any]: """Custom dict_factory for dataclasses.asdict. Recursively converts dataclass instances, converts enum values to their underlying values, converts integral numeric types to int, and skips any field whose name starts with an underscore...
function_complex
1
{"cognitive_complexity": 9, "loc": 28, "code_loc": 13, "docstring_loc": 13, "function_name": "enum_asdict_factory", "class_name": null, "qualname": "enum_asdict_factory", "file_path": "langextract/data_lib.py", "repo_id": "google/langextract", "has_docstring": true, "runnable_level": "slib_runnable"}
apache/airflow:airflow-core/src/airflow/executors/workloads/callback.py:module_doc
Write a module-level docstring for the Python module `callback` which contains class `CallbackFetchMethod`, class `CallbackDTO`, class `ExecuteCallback`, function `execute_callback_workload`.
Callback workload schemas for executor communication.
documentation
1
{"doc_type": "module", "module_name": "callback", "file_path": "airflow-core/src/airflow/executors/workloads/callback.py", "repo_id": "apache/airflow", "char_length": 53}
vllm-project/vllm:tests/v1/kv_connector/unit/test_decode_bench_connector.py:test_decode_bench_connector_partial_block
# Context: class DecodeBenchTestRunner: ... def test_decode_bench_connector_basic(): ... def test_decode_bench_connector_no_refill(): ... def test_decode_bench_connector_single_token(): ... def test_decode_bench_connector_two_tokens(): ... def test_decode_bench_connector_large_context(): ... def test_decode_bench_conn...
def test_decode_bench_connector_partial_block(): """Test DecodeBenchConnector with partial block filling.""" block_size = 16 num_gpu_blocks = 100 runner = DecodeBenchTestRunner(block_size=block_size, num_gpu_blocks=num_gpu_blocks) # Create a request that doesn't align to block boundaries # e.g...
test
1
{"function_name": "test_decode_bench_connector_partial_block", "class_name": null, "qualname": "test_decode_bench_connector_partial_block", "file_path": "tests/v1/kv_connector/unit/test_decode_bench_connector.py", "repo_id": "vllm-project/vllm", "loc": 33, "tested_modules": ["vllm", "vllm.config", "vllm.distributed.kv_...
github/spec-kit:tests/test_ai_skills.py:TestNewProjectCommandSkip.test_new_project_commands_removed_after_skills_succeed
# Context: from unittest.mock import patch from specify_cli import ( _get_skills_dir, install_ai_skills, AGENT_SKILLS_DIR_OVERRIDES, DEFAULT_SKILLS_DIR, SKILL_DESCRIPTIONS, AGENT_CONFIG, app, ) from typer.testing import CliRunner def temp_dir(): ... def project_dir(temp_dir): ... def templa...
def test_new_project_commands_removed_after_skills_succeed(self, tmp_path): """For new projects, commands should be removed when skills succeed.""" from typer.testing import CliRunner runner = CliRunner() target = tmp_path / "new-proj" def fake_download(project_path, *args, **k...
test
0
{"function_name": "test_new_project_commands_removed_after_skills_succeed", "class_name": "TestNewProjectCommandSkip", "qualname": "TestNewProjectCommandSkip.test_new_project_commands_removed_after_skills_succeed", "file_path": "tests/test_ai_skills.py", "repo_id": "github/spec-kit", "loc": 24, "tested_modules": ["path...
infiniflow/ragflow:test/unit_test/common/test_string_utils.py:TestRemoveRedundantSpaces.test_currency_symbols
# Context: import pytest from common.string_utils import remove_redundant_spaces, clean_markdown_block class TestCleanMarkdownBlock: ... class TestRemoveRedundantSpaces: def test_remove_spaces_before_commas(self): ... def test_remove_spaces_before_periods(self): ... def test_remove_spaces_before_exclamati...
def test_currency_symbols(self): """Test currency symbols""" input_text = "Price : € 100 , £ 50 , ¥ 1000 ." expected = "Price: €100, £50, ¥1000." assert remove_redundant_spaces(input_text) == expected
test
1
{"function_name": "test_currency_symbols", "class_name": "TestRemoveRedundantSpaces", "qualname": "TestRemoveRedundantSpaces.test_currency_symbols", "file_path": "test/unit_test/common/test_string_utils.py", "repo_id": "infiniflow/ragflow", "loc": 5, "tested_modules": ["common.string_utils"], "has_docstring": true, "ru...
langchain-ai/langchain:libs/partners/openrouter/langchain_openrouter/chat_models.py:ChatOpenRouter.lc_secrets
Write a Python method `lc_secrets` for the class `ChatOpenRouter` to a map of constructor argument names to secret ids. Returns: dict[str, str]
def lc_secrets(self) -> dict[str, str]: """A map of constructor argument names to secret ids.""" return {"openrouter_api_key": "OPENROUTER_API_KEY"}
function_simple
1
{"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "lc_secrets", "class_name": "ChatOpenRouter", "qualname": "ChatOpenRouter.lc_secrets", "file_path": "libs/partners/openrouter/langchain_openrouter/chat_models.py", "repo_id": "langchain-ai/langchain", "has_docstring": true, "runna...
langflow-ai/langflow:src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py:TestCometAPIComponent.test_build_model_integration
# Context: import os import pytest from langchain_openai import ChatOpenAI from lfx.components.cometapi.cometapi import CometAPIComponent from pydantic.v1 import SecretStr class TestCometAPIComponent(ComponentTestBaseWithoutClient): def component_class(self): ... def default_kwargs(self): ... def file_name...
def test_build_model_integration(self): """Integration test with real API key (if available).""" component = CometAPIComponent() component.api_key = SecretStr(os.getenv("COMETAPI_KEY")) component.model_name = "gpt-4o-mini" component.temperature = 0.2 component.max_tokens ...
test
1
{"function_name": "test_build_model_integration", "class_name": "TestCometAPIComponent", "qualname": "TestCometAPIComponent.test_build_model_integration", "file_path": "src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py", "repo_id": "langflow-ai/langflow", "loc": 13, "tested_modules": ["langc...
sansan0/TrendRadar:trendradar/crawler/fetcher.py:DataFetcher.fetch_data
# Context: import json import random import time from typing import Dict, List, Tuple, Optional, Union import requests class DataFetcher: DEFAULT_API_URL = "https://newsnow.busiyi.world/api/s" DEFAULT_HEADERS = { def __init__( self, proxy_url: Optional[str] = None, api_url: Optional...
def fetch_data( self, id_info: Union[str, Tuple[str, str]], max_retries: int = 2, min_retry_wait: int = 3, max_retry_wait: int = 5, ) -> Tuple[Optional[str], str, str]: """ 获取指定ID数据,支持重试 Args: id_info: 平台ID 或 (平台ID, 别名) 元组 max_...
function_complex
1
{"cognitive_complexity": 15, "loc": 66, "code_loc": 39, "docstring_loc": 12, "function_name": "fetch_data", "class_name": "DataFetcher", "qualname": "DataFetcher.fetch_data", "file_path": "trendradar/crawler/fetcher.py", "repo_id": "sansan0/TrendRadar", "has_docstring": true, "runnable_level": "class_runnable"}
exo-explore/exo:packaging/dmg/generate-background.py:draw_arrow
# Context: import math from PIL import Image, ImageDraw def generate_background(output_path: str) -> None: ... # Task: Write a Python function `draw_arrow` to draw a hand-drawn-style curved arrow from app icon toward Applications. Parameters: draw: ImageDraw.ImageDraw Returns: None
def draw_arrow(draw: ImageDraw.ImageDraw) -> None: """Draw a hand-drawn-style curved arrow from app icon toward Applications.""" color = (30, 30, 30) line_width = 8 # Compute bezier curve points for a gentle upward arc points: list[tuple[float, float]] = [] steps = 80 for i in range(steps +...
function_simple
0
{"cognitive_complexity": 2, "loc": 38, "code_loc": 26, "docstring_loc": 1, "function_name": "draw_arrow", "class_name": null, "qualname": "draw_arrow", "file_path": "packaging/dmg/generate-background.py", "repo_id": "exo-explore/exo", "has_docstring": true, "runnable_level": "project_runnable"}
ray-project/ray:doc/source/llm/doc_code/serve/qwen/qwen_example.py:module_doc
Write a module-level docstring for the Python module `qwen_example` which contains function `_non_blocking_serve_run`, function `_testing_build_openai_app`.
This file serves as a documentation example and CI test. Structure: 1. Monkeypatch setup: Ensures serve.run is non-blocking and removes accelerator requirements for CI testing. 2. Docs example (between __qwen_example_start/end__): Embedded in Sphinx docs via literalinclude. 3. Test validation (deployment status pollin...
documentation
0
{"doc_type": "module", "module_name": "qwen_example", "file_path": "doc/source/llm/doc_code/serve/qwen/qwen_example.py", "repo_id": "ray-project/ray", "char_length": 332}
langflow-ai/langflow:src/backend/tests/unit/api/v1/test_mcp_projects.py:test_update_project_mcp_settings_empty_settings
# Context: from httpx import AsyncClient def test_args_reference_urls_filters_strings_only(args, urls, expected): ... def test_args_reference_urls_matches_non_last_string_argument(): ... def mock_project(active_user): ... def mock_flow(active_user, mock_project): ... def mock_project_mcp_server(): ... class AsyncConte...
async def test_update_project_mcp_settings_empty_settings(client: AsyncClient, user_test_project, logged_in_headers): """Test updating MCP settings with empty settings list.""" # Use real database objects instead of mocks to avoid the coroutine issue # Empty settings list json_payload = { "sett...
test
1
{"function_name": "test_update_project_mcp_settings_empty_settings", "class_name": null, "qualname": "test_update_project_mcp_settings_empty_settings", "file_path": "src/backend/tests/unit/api/v1/test_mcp_projects.py", "repo_id": "langflow-ai/langflow", "loc": 25, "tested_modules": ["contextlib", "types", "uuid", "fast...
run-llama/llama_index:llama-index-core/llama_index/core/memory/memory.py:Memory.aput_messages
# Context: from typing import ( Any, Callable, Dict, List, Optional, Tuple, Union, TypeVar, Generic, cast, ) from llama_index.core.base.llms.types import ( ChatMessage, ContentBlock, TextBlock, AudioBlock, ImageBlock, VideoBlock, DocumentBlock, Cac...
async def aput_messages(self, messages: List[ChatMessage]) -> None: """Add a list of messages to the chat store and process waterfall logic if needed.""" # Add the messages to the chat store await self.sql_store.add_messages( self.session_id, messages, status=MessageStatus.ACTIVE ...
function_simple
1
{"cognitive_complexity": 0, "loc": 9, "code_loc": 4, "docstring_loc": 1, "function_name": "aput_messages", "class_name": "Memory", "qualname": "Memory.aput_messages", "file_path": "llama-index-core/llama_index/core/memory/memory.py", "repo_id": "run-llama/llama_index", "has_docstring": true, "runnable_level": "project_...
langchain-ai/langchain:libs/langchain/langchain_classic/agents/mrkl/base.py:ChainConfig:class_doc
Write a class-level docstring for `ChainConfig` (inherits from NamedTuple) which has methods: various methods.
Configuration for a chain to use in MRKL system. Args: action_name: Name of the action. action: Action function to call. action_description: Description of the action.
documentation
1
{"doc_type": "class", "class_name": "ChainConfig", "file_path": "libs/langchain/langchain_classic/agents/mrkl/base.py", "repo_id": "langchain-ai/langchain", "char_length": 180, "methods": []}