sample_id string | instruction string | completion string | category string | label int64 | metadata string |
|---|---|---|---|---|---|
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/multi_agent_trust_layer/multi_agent_trust_layer.py:MultiAgentPolicyEngine.add_role_policy | # Context:
from typing import Dict, Any, List, Optional, Set
class TrustLevel(Enum): ...
class AgentIdentity: ...
class TrustScore: ...
class DelegationScope: ...
class Delegation: ...
class AuditEntry: ...
class IdentityRegistry: ...
class TrustScoringEngine: ...
class DelegationManager: ...
class TrustLayer: ...
cla... | def add_role_policy(self, role: str, policy: Dict[str, Any]):
"""Add a policy for a specific role"""
self.role_policies[role] = policy | function_simple | 0 | {"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "add_role_policy", "class_name": "MultiAgentPolicyEngine", "qualname": "MultiAgentPolicyEngine.add_role_policy", "file_path": "advanced_ai_agents/multi_agent_apps/multi_agent_trust_layer/multi_agent_trust_layer.py", "repo_id": "Sh... |
666ghj/BettaFish:ReportEngine/utils/test_json_parser.py:module_doc | Write a module-level docstring for the Python module `test_json_parser` which contains class `TestRobustJSONParser`, function `run_manual_test`. | 测试RobustJSONParser的各种修复能力。
验证解析器能够处理:
1. 基本的markdown包裹
2. 思考内容清理
3. 缺少逗号的修复
4. 括号不平衡的修复
5. 控制字符转义
6. 尾随逗号移除 | documentation | 1 | {"doc_type": "module", "module_name": "test_json_parser", "file_path": "ReportEngine/utils/test_json_parser.py", "repo_id": "666ghj/BettaFish", "char_length": 108} |
ray-project/ray:python/ray/data/tests/test_ranker.py:module_doc | Write a module-level docstring for the Python module `test_ranker` which contains function `test_default_ranker`, class `IntRanker`, function `test_generic_types`. | Comprehensive tests for the generic ranker type system. | documentation | 0 | {"doc_type": "module", "module_name": "test_ranker", "file_path": "python/ray/data/tests/test_ranker.py", "repo_id": "ray-project/ray", "char_length": 55} |
infiniflow/ragflow:test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py:test_list_agent_session_projection_unit | # Context:
import inspect
from types import ModuleType, SimpleNamespace
import pytest
class _DummyManager: ...
class _AwaitableValue: ...
class _Args(dict): ...
class _StubHeaders: ...
class _StubResponse: ...
class _DummyUploadFile: ...
def _run(coro): ...
async def _collect_stream(body): ...
def auth(): ...
def set_... | def test_list_agent_session_projection_unit(monkeypatch):
module = _load_session_module(monkeypatch)
monkeypatch.setattr(module, "request", SimpleNamespace(args=_Args({})))
monkeypatch.setattr(module.UserCanvasService, "query", lambda **_kwargs: [SimpleNamespace(id="agent-1")])
conv_non_list_reference... | test | 1 | {"function_name": "test_list_agent_session_projection_unit", "class_name": null, "qualname": "test_list_agent_session_projection_unit", "file_path": "test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py", "repo_id": "infiniflow/ragflow", "loc": 46, "tested_modules": ["pathlib", "types"],... |
google/langextract:tests/test_live_api.py:TestLiveAPIOpenAI.test_medication_relationship_extraction | # Context:
import textwrap
import langextract as lx
def has_vertex_ai_credentials(): ...
def retry_on_transient_errors(max_retries, backoff_factor): ...
def add_delay_between_tests(): ...
def get_basic_medication_examples(): ...
def get_relationship_examples(): ...
def extract_by_class(result, extraction_class): ...
d... | def test_medication_relationship_extraction(self):
"""Test relationship extraction for medications with OpenAI."""
input_text = """
The patient was prescribed Lisinopril and Metformin last month.
He takes the Lisinopril 10mg daily for hypertension, but often misses
his Metformin 500mg dose which sho... | test | 1 | {"function_name": "test_medication_relationship_extraction", "class_name": "TestLiveAPIOpenAI", "qualname": "TestLiveAPIOpenAI.test_medication_relationship_extraction", "file_path": "tests/test_live_api.py", "repo_id": "google/langextract", "loc": 59, "tested_modules": ["typing", "langextract", "langextract.core", "lan... |
ray-project/ray:doc/source/ray-overview/examples/mcp-ray-serve/build-mcp-docker-image/weather.py:format_alert | Write a Python function `format_alert` to format an alert feature into a readable string.
Parameters: feature: dict
Returns: str | def format_alert(feature: dict) -> str:
"""Format an alert feature into a readable string."""
props = feature.get("properties", {})
return f"""
Event: {props.get('event', 'Unknown')}
Area: {props.get('areaDesc', 'Unknown')}
Severity: {props.get('severity', 'Unknown')}
Description: {props.get('description', ... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 10, "code_loc": 8, "docstring_loc": 1, "function_name": "format_alert", "class_name": null, "qualname": "format_alert", "file_path": "doc/source/ray-overview/examples/mcp-ray-serve/build-mcp-docker-image/weather.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level... |
apache/airflow:airflow-core/src/airflow/serialization/definitions/taskgroup.py:SerializedTaskGroup.iter_mapped_task_groups | # Context:
from collections.abc import Generator, Iterator
class SerializedMappedTaskGroup(SerializedTaskGroup): ...
class SerializedTaskGroup(DAGNode):
def __repr__(self) -> str: ...
def _iter_child(child): ...
def __iter__(self): ...
def group_id(self) -> str | None: ...
def label(self) -> str: ... | def iter_mapped_task_groups(self) -> Iterator[SerializedMappedTaskGroup]:
"""
Find mapped task groups in the hierarchy.
Groups are returned from the closest to the outmost. If *self* is a
mapped task group, it is returned first.
"""
group: SerializedTaskGroup | None = se... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 12, "code_loc": 5, "docstring_loc": 6, "function_name": "iter_mapped_task_groups", "class_name": "SerializedTaskGroup", "qualname": "SerializedTaskGroup.iter_mapped_task_groups", "file_path": "airflow-core/src/airflow/serialization/definitions/taskgroup.py", "repo_id": "apache/airflow... |
apache/airflow:airflow-core/tests/unit/timetables/test_partitioned_timetable.py:TestPartitionedAssetTimetable.test_serialize | # Context:
from airflow.partition_mappers.identity import IdentityMapper as IdentityMapper
from airflow.sdk import Asset
from airflow.serialization.encoders import ensure_serialized_asset
from airflow.serialization.enums import DagAttributeTypes
from airflow.timetables.simple import PartitionedAssetTimetable
class Key... | def test_serialize(self):
ser_asset = ensure_serialized_asset(Asset("test"))
timetable = PartitionedAssetTimetable(
assets=ser_asset, partition_mapper_config={ser_asset: IdentityMapper()}
)
assert timetable.serialize() == {
"asset_condition": {
"__... | test | 1 | {"function_name": "test_serialize", "class_name": "TestPartitionedAssetTimetable", "qualname": "TestPartitionedAssetTimetable.test_serialize", "file_path": "airflow-core/tests/unit/timetables/test_partitioned_timetable.py", "repo_id": "apache/airflow", "loc": 33, "tested_modules": ["__future__", "collections.abc", "con... |
vllm-project/vllm:tests/renderers/test_process_multi_modal_uuids.py:test_multi_modal_uuids_missing_modality_raises | # Context:
import pytest
from vllm.multimodal.parse import parse_mm_uuids
def _build_renderer(mm_cache_gb: float, enable_prefix_caching: bool) -> HfRenderer: ...
def test_multi_modal_uuids_length_mismatch_raises(): ...
def test_multi_modal_uuids_accepts_none_and_passes_through(mm_cache_gb: float, enable_prefix_caching... | def test_multi_modal_uuids_missing_modality_raises():
renderer = _build_renderer()
mm_data = {
"image": [cherry_pil_image],
"video": None,
}
# Only image uuids provided; video missing should raise
mm_uuids = {"image": ["hash_cherry"]}
mm_processor = renderer.get_mm_processor()... | test | 1 | {"function_name": "test_multi_modal_uuids_missing_modality_raises", "class_name": null, "qualname": "test_multi_modal_uuids_missing_modality_raises", "file_path": "tests/renderers/test_process_multi_modal_uuids.py", "repo_id": "vllm-project/vllm", "loc": 17, "tested_modules": ["vllm.assets.image", "vllm.assets.video", ... |
Comfy-Org/ComfyUI:comfy_api/latest/_io.py:ComfyTypeIO:class_doc | Write a class-level docstring for `ComfyTypeIO` (inherits from ComfyTypeI) which has methods: various methods. | ComfyType subclass that has default Input and Output classes; useful for types with both Inputs and Outputs. | documentation | 1 | {"doc_type": "class", "class_name": "ComfyTypeIO", "file_path": "comfy_api/latest/_io.py", "repo_id": "Comfy-Org/ComfyUI", "char_length": 108, "methods": []} |
apache/airflow:dev/breeze/src/airflow_breeze/utils/release_validator.py:ReleaseValidator:class_doc | Write a class-level docstring for `ReleaseValidator` (inherits from ABC) which has methods: `__init__`, `get_distribution_name`, `get_svn_directory`, `get_expected_files`, `build_packages`. | Base class for release validators with common functionality for PMC verification. | documentation | 1 | {"doc_type": "class", "class_name": "ReleaseValidator", "file_path": "dev/breeze/src/airflow_breeze/utils/release_validator.py", "repo_id": "apache/airflow", "char_length": 81, "methods": ["__init__", "get_distribution_name", "get_svn_directory", "get_expected_files", "build_packages", "validate_svn_files", "validate_r... |
infiniflow/ragflow:tools/es-to-oceanbase-migration/src/es_ob_migration/progress.py:ProgressManager.save_progress | # Context:
import json
from dataclasses import dataclass, field, asdict
from datetime import datetime
class MigrationProgress: ...
class ProgressManager:
def __init__(self, progress_dir: str = ".migration_progress"):
"""
Initialize progress manager.
Args:
progress_dir: Directo... | def save_progress(self, progress: MigrationProgress):
"""
Save progress to file.
Args:
progress: MigrationProgress instance
"""
progress.updated_at = datetime.utcnow().isoformat()
progress_file = self._get_progress_file(progress.es_index, progress.ob_table)
... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 16, "code_loc": 8, "docstring_loc": 6, "function_name": "save_progress", "class_name": "ProgressManager", "qualname": "ProgressManager.save_progress", "file_path": "tools/es-to-oceanbase-migration/src/es_ob_migration/progress.py", "repo_id": "infiniflow/ragflow", "has_docstring": true... |
unclecode/crawl4ai:test_webhook_implementation.py:test_imports | Write a Python test function `test_imports` to test that all webhook-related modules can be imported.
Module under test: datetime, webhook, schemas | def test_imports():
"""Test that all webhook-related modules can be imported"""
print("=" * 60)
print("TEST 1: Module Imports")
print("=" * 60)
try:
from webhook import WebhookDeliveryService
print("✅ webhook.WebhookDeliveryService imported successfully")
except Exception as e:
... | test | 1 | {"function_name": "test_imports", "class_name": null, "qualname": "test_imports", "file_path": "test_webhook_implementation.py", "repo_id": "unclecode/crawl4ai", "loc": 22, "tested_modules": ["datetime", "webhook", "schemas", "webhook", "schemas"], "has_docstring": true, "runnable_level": "self_contained"} |
crewAIInc/crewAI:lib/crewai/tests/llms/azure/test_azure.py:test_azure_token_usage_tracking | # Context:
from unittest.mock import patch, MagicMock, Mock
from crewai.llm import LLM
def mock_azure_credentials(): ...
def test_azure_completion_is_used_when_azure_provider(): ...
def test_azure_completion_is_used_when_azure_openai_provider(): ...
def test_azure_tool_use_conversation_flow(): ...
def test_azure_compl... | def test_azure_token_usage_tracking():
"""
Test that token usage is properly tracked for Azure responses
"""
llm = LLM(model="azure/gpt-4")
# Mock the Azure response with usage information
with patch.object(llm.client, 'complete') as mock_complete:
mock_message = MagicMock()
moc... | test | 0 | {"function_name": "test_azure_token_usage_tracking", "class_name": null, "qualname": "test_azure_token_usage_tracking", "file_path": "lib/crewai/tests/llms/azure/test_azure.py", "repo_id": "crewAIInc/crewAI", "loc": 34, "tested_modules": ["crewai.llm", "crewai.crew", "crewai.agent", "crewai.task", "crewai.llms.provider... |
langflow-ai/langflow:src/backend/tests/unit/utils/test_mcp_cleanup.py:TestTerminateOrphanedMcpProcesses.test_skips_non_orphaned_processes | # Context:
from unittest.mock import AsyncMock, MagicMock, patch
from langflow.utils.mcp_cleanup import (
_kill_mcp_processes,
_terminate_child_mcp_processes,
_terminate_orphaned_mcp_processes,
_try_terminate_mcp_process,
cleanup_mcp_sessions,
)
class TestCleanupMcpSessions: ...
class TestKillMcpPr... | async def test_skips_non_orphaned_processes(self):
"""Test that non-orphaned processes are skipped."""
mock_psutil = MagicMock()
mock_proc = MagicMock()
mock_proc.info = {
"pid": 12345,
"ppid": 1000, # Not orphaned
"cmdline": ["python", "mcp-server-f... | test | 1 | {"function_name": "test_skips_non_orphaned_processes", "class_name": "TestTerminateOrphanedMcpProcesses", "qualname": "TestTerminateOrphanedMcpProcesses.test_skips_non_orphaned_processes", "file_path": "src/backend/tests/unit/utils/test_mcp_cleanup.py", "repo_id": "langflow-ai/langflow", "loc": 24, "tested_modules": ["... |
infiniflow/ragflow:test/testcases/test_http_api/test_chat_assistant_management/test_list_chat_assistants.py:TestChatAssistantsList.test_desc_false_parse_branch_p2 | # Context:
import pytest
from common import delete_datasets, list_chat_assistants
from utils import is_sorted
class TestAuthorization: ...
class TestChatAssistantsList:
def test_default(self, HttpApiAuth): ...
def test_page(self, HttpApiAuth, params, expected_code, expected_page_size, expected_message): ...
... | def test_desc_false_parse_branch_p2(self, HttpApiAuth):
res = list_chat_assistants(HttpApiAuth, params={"desc": "False", "orderby": "create_time"})
assert res["code"] == 0
assert is_sorted(res["data"], "create_time", False) | test | 1 | {"function_name": "test_desc_false_parse_branch_p2", "class_name": "TestChatAssistantsList", "qualname": "TestChatAssistantsList.test_desc_false_parse_branch_p2", "file_path": "test/testcases/test_http_api/test_chat_assistant_management/test_list_chat_assistants.py", "repo_id": "infiniflow/ragflow", "loc": 4, "tested_m... |
huggingface/diffusers:src/diffusers/models/attention_dispatch.py:_maybe_pad_qkv_head | # Context:
import torch
import torch.distributed as dist
import torch.nn.functional as F
class AttentionBackendName(str, Enum): ...
class _AttentionBackendRegistry: ...
class _HubKernelConfig: ...
def attention_backend(backend: str | AttentionBackendName): ...
def dispatch_attention_fn(query: torch.Tensor, key: torch.... | def _maybe_pad_qkv_head(x: torch.Tensor, H: int, group: dist.ProcessGroup) -> tuple[torch.Tensor, int]:
r"""Maybe pad the head dimension to be divisible by world_size.
x: torch.Tensor, shape (B, S_LOCAL, H, D) H: int, original global head num return: tuple[torch.Tensor, int], padded
tensor (B, S_LOCAL, H + ... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 15, "code_loc": 8, "docstring_loc": 4, "function_name": "_maybe_pad_qkv_head", "class_name": null, "qualname": "_maybe_pad_qkv_head", "file_path": "src/diffusers/models/attention_dispatch.py", "repo_id": "huggingface/diffusers", "has_docstring": true, "runnable_level": "plib_runnable"... |
commaai/openpilot:selfdrive/controls/tests/test_torqued_lat_accel_offset.py:test_straight_road_roll_bias | # Context:
import numpy as np
def generate_inputs(torque_tune, la_err_std, input_noise_std): ...
def get_warmed_up_estimator(steer_torques, lat_accels): ...
def simulate_straight_road_msgs(est): ...
def test_estimated_offset(): ...
# Task:
Write a Python test function `test_straight_road_roll_bias` to verify the beha... | def test_straight_road_roll_bias():
steer_torques, lat_accels = generate_inputs(TORQUE_TUNE, la_err_std=LA_ERR_STD, input_noise_std=INPUT_NOISE_STD)
est = get_warmed_up_estimator(steer_torques, lat_accels)
simulate_straight_road_msgs(est)
msg = est.get_msg()
assert (msg.liveTorqueParameters.latAccelOffsetRaw ... | test | 0 | {"function_name": "test_straight_road_roll_bias", "class_name": null, "qualname": "test_straight_road_roll_bias", "file_path": "selfdrive/controls/tests/test_torqued_lat_accel_offset.py", "repo_id": "commaai/openpilot", "loc": 6, "tested_modules": ["cereal", "opendbc.car", "opendbc.car", "opendbc.car.lateral", "openpil... |
crewAIInc/crewAI:lib/crewai/tests/llms/anthropic/test_anthropic.py:test_anthropic_agent_kickoff_structured_output_with_tools | # Context:
import pytest
from crewai.llm import LLM
from crewai.agent import Agent
from crewai.tools import tool
from pydantic import BaseModel, Field
def mock_anthropic_api_key(): ...
def test_anthropic_completion_is_used_when_anthropic_provider(): ...
def test_anthropic_completion_is_used_when_claude_provider(): ...... | def test_anthropic_agent_kickoff_structured_output_with_tools():
"""
Test that agent kickoff returns structured output after using tools.
This tests post-tool-call structured output handling for Anthropic models.
"""
from pydantic import BaseModel, Field
from crewai.tools import tool
class ... | test | 0 | {"function_name": "test_anthropic_agent_kickoff_structured_output_with_tools", "class_name": null, "qualname": "test_anthropic_agent_kickoff_structured_output_with_tools", "file_path": "lib/crewai/tests/llms/anthropic/test_anthropic.py", "repo_id": "crewAIInc/crewAI", "loc": 39, "tested_modules": ["crewai.llm", "crewai... |
crewAIInc/crewAI:lib/crewai/tests/llms/hooks/test_anthropic_interceptor.py:TestMixedProviderInterceptors:class_doc | Write a class-level docstring for `TestMixedProviderInterceptors` which has methods: `test_openai_and_anthropic_different_interceptors`, `test_same_interceptor_different_providers`. | Test suite for using interceptors with different providers. | documentation | 0 | {"doc_type": "class", "class_name": "TestMixedProviderInterceptors", "file_path": "lib/crewai/tests/llms/hooks/test_anthropic_interceptor.py", "repo_id": "crewAIInc/crewAI", "char_length": 59, "methods": ["test_openai_and_anthropic_different_interceptors", "test_same_interceptor_different_providers"]} |
crewAIInc/crewAI:lib/crewai/tests/utilities/test_pydantic_schema_utils.py:TestEndToEndMCPSchema:class_doc | Write a class-level docstring for `TestEndToEndMCPSchema` which has methods: `test_model_creation`, `test_valid_input_accepted`, `test_invalid_enum_rejected`, `test_model_name_for_mcp_tool`, `test_enriched_descriptions_for_mcp`. | Realistic MCP tool schema exercising multiple features simultaneously. | documentation | 0 | {"doc_type": "class", "class_name": "TestEndToEndMCPSchema", "file_path": "lib/crewai/tests/utilities/test_pydantic_schema_utils.py", "repo_id": "crewAIInc/crewAI", "char_length": 70, "methods": ["test_model_creation", "test_valid_input_accepted", "test_invalid_enum_rejected", "test_model_name_for_mcp_tool", "test_enri... |
zhayujie/chatgpt-on-wechat:agent/tools/scheduler/task_store.py:TaskStore.load_tasks | # Context:
import json
import os
from typing import Dict, List, Optional
class TaskStore:
def __init__(self, store_path: str = None):
"""
Initialize task store
Args:
store_path: Path to tasks.json file. Defaults to ~/cow/scheduler/tasks.json
"""
if store... | def load_tasks(self) -> Dict[str, dict]:
"""
Load all tasks from storage
Returns:
Dictionary of task_id -> task_data
"""
with self.lock:
if not os.path.exists(self.store_path):
return {}
try:
... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 18, "code_loc": 10, "docstring_loc": 6, "function_name": "load_tasks", "class_name": "TaskStore", "qualname": "TaskStore.load_tasks", "file_path": "agent/tools/scheduler/task_store.py", "repo_id": "zhayujie/chatgpt-on-wechat", "has_docstring": true, "runnable_level": "class_runnable"} |
crewAIInc/crewAI:lib/crewai-tools/tests/test_generate_tool_specs.py:test_extract_init_params_schema | # Context:
class MockToolSchema(BaseModel): ...
class MockTool(BaseTool): ...
def extractor(): ...
def test_unwrap_schema(extractor): ...
def mock_tool_extractor(extractor): ...
def test_extract_basic_tool_info(mock_tool_extractor): ...
def test_extract_env_vars(mock_tool_extractor): ...
def test_extract_run_params_sc... | def test_extract_init_params_schema(mock_tool_extractor):
tool_info = mock_tool_extractor
init_params_schema = tool_info["init_params_schema"]
assert init_params_schema.keys() == {
"$defs",
"properties",
"title",
"type",
}
another_parameter = init_params_schema["pro... | test | 0 | {"function_name": "test_extract_init_params_schema", "class_name": null, "qualname": "test_extract_init_params_schema", "file_path": "lib/crewai-tools/tests/test_generate_tool_specs.py", "repo_id": "crewAIInc/crewAI", "loc": 24, "tested_modules": ["crewai.tools.base_tool", "crewai_tools.generate_tool_specs", "pydantic"... |
huggingface/transformers:src/transformers/generation/continuous_batching/cache.py:PagedAttentionMemoryHandler.compute_num_blocks | # Context:
from math import floor, gcd, sqrt
import torch
from .requests import RequestState, RequestStatus, get_device_and_memory_breakdown, logger
def group_layers_by_attn_type(config: PreTrainedConfig) -> tuple[list[list[int]], list[str]]: ...
class PagedAttentionCache: ...
class PagedAttentionMemoryHandler:
_... | def compute_num_blocks(
self,
max_batch_tokens: int,
max_memory_percent: float,
cache_dtype: torch.dtype = torch.float16,
) -> int:
"""Calculate number of cache blocks N given a fixed maximum token per token M. The formula for N is given by:
N = (available_memory - M... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 27, "code_loc": 13, "docstring_loc": 5, "function_name": "compute_num_blocks", "class_name": "PagedAttentionMemoryHandler", "qualname": "PagedAttentionMemoryHandler.compute_num_blocks", "file_path": "src/transformers/generation/continuous_batching/cache.py", "repo_id": "huggingface/tr... |
ray-project/ray:python/ray/serve/tests/test_tracing_utils.py:test_disable_tracing_exporter | # Context:
from ray.serve._private.common import ServeComponentType
from ray.serve._private.tracing_utils import (
DEFAULT_TRACING_EXPORTER_IMPORT_PATH,
TRACE_STACK,
_append_trace_stack,
_load_span_processors,
_validate_tracing_exporter,
_validate_tracing_exporter_processors,
set_trace_statu... | def test_disable_tracing_exporter():
"""Test that setting `tracing_exporter_import_path`
to an empty string disables tracing.
"""
is_tracing_setup_successful = setup_tracing(
component_type=ServeComponentType.REPLICA,
component_name="component_name",
component_id="component_id",
... | test | 0 | {"function_name": "test_disable_tracing_exporter", "class_name": null, "qualname": "test_disable_tracing_exporter", "file_path": "python/ray/serve/tests/test_tracing_utils.py", "repo_id": "ray-project/ray", "loc": 13, "tested_modules": ["pathlib", "threading", "typing", "starlette.requests", "starlette.responses"], "ha... |
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-bigquery/tests/test_get_nodes.py:test_get_nodes_with_filters_generates_correct_sql_and_params | # Context:
from google.cloud import bigquery
from llama_index.core.vector_stores import MetadataFilter, MetadataFilters
from llama_index.vector_stores.bigquery import BigQueryVectorStore
from sql_assertions import assert_equivalent_sql_statements
def test_get_nodes_constructs_nodes_from_valid_metadata_row(vector_store... | def test_get_nodes_with_filters_generates_correct_sql_and_params(
vector_store: BigQueryVectorStore,
):
"""It should execute a parameterized query to get nodes based on filter criteria"""
# Given filtering criteria
filters = MetadataFilters(
filters=[
MetadataFilter(key="author", val... | test | 1 | {"function_name": "test_get_nodes_with_filters_generates_correct_sql_and_params", "class_name": null, "qualname": "test_get_nodes_with_filters_generates_correct_sql_and_params", "file_path": "llama-index-integrations/vector_stores/llama-index-vector-stores-bigquery/tests/test_get_nodes.py", "repo_id": "run-llama/llama_... |
crewAIInc/crewAI:lib/crewai-tools/tests/tools/test_mongodb_vector_search_tool.py:test_provide_config | # Context:
from unittest.mock import patch
from crewai_tools import MongoDBVectorSearchConfig, MongoDBVectorSearchTool
def mongodb_vector_search_tool(): ...
def test_successful_query_execution(mongodb_vector_search_tool): ...
def test_cleanup_on_deletion(mongodb_vector_search_tool): ...
def test_create_search_index(mo... | def test_provide_config():
query_config = MongoDBVectorSearchConfig(limit=10)
tool = MongoDBVectorSearchTool(
connection_string="foo",
database_name="bar",
collection_name="test",
query_config=query_config,
vector_index_name="foo",
embedding_model="bar",
)
... | test | 0 | {"function_name": "test_provide_config", "class_name": null, "qualname": "test_provide_config", "file_path": "lib/crewai-tools/tests/tools/test_mongodb_vector_search_tool.py", "repo_id": "crewAIInc/crewAI", "loc": 18, "tested_modules": ["crewai_tools"], "has_docstring": false, "runnable_level": "project_runnable"} |
langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_dynamic_tools.py:MultipleDynamicToolsMiddleware:class_doc | Write a class-level docstring for `MultipleDynamicToolsMiddleware` (inherits from AgentMiddleware) which has methods: `wrap_model_call`, `awrap_model_call`, `_handle_tool`, `wrap_tool_call`, `awrap_tool_call`. | Middleware that dynamically adds multiple tools (sync and async). | documentation | 1 | {"doc_type": "class", "class_name": "MultipleDynamicToolsMiddleware", "file_path": "libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_dynamic_tools.py", "repo_id": "langchain-ai/langchain", "char_length": 65, "methods": ["wrap_model_call", "awrap_model_call", "_handle_tool", "wrap_tool_call", "awrap_tool_c... |
ray-project/ray:python/ray/data/namespace_expressions/arr_namespace.py:module_doc | Write a module-level docstring for the Python module `arr_namespace` which contains class `_ArrayNamespace`. | Array namespace for expression operations on array-typed columns. | documentation | 0 | {"doc_type": "module", "module_name": "arr_namespace", "file_path": "python/ray/data/namespace_expressions/arr_namespace.py", "repo_id": "ray-project/ray", "char_length": 65} |
huggingface/transformers:tests/models/solar_open/test_modeling_solar_open.py:SolarOpenModelTest.test_rope_parameters_partially_initialized | # Context:
from transformers import AutoTokenizer, SolarOpenConfig, SolarOpenForCausalLM, SolarOpenModel
class SolarOpenModelTester(CausalLMModelTester): ...
class SolarOpenIntegrationTest(unittest.TestCase): ...
class SolarOpenModelTest(CausalLMModelTest, unittest.TestCase):
model_tester_class = SolarOpenModelTe... | def test_rope_parameters_partially_initialized(self):
"""
Test for SolarOpenConfig when rope_parameters is partially initialized
"""
config = SolarOpenConfig(
rope_parameters={
"rope_type": "yarn",
"factor": 2.0,
"original_max_p... | test | 0 | {"function_name": "test_rope_parameters_partially_initialized", "class_name": "SolarOpenModelTest", "qualname": "SolarOpenModelTest.test_rope_parameters_partially_initialized", "file_path": "tests/models/solar_open/test_modeling_solar_open.py", "repo_id": "huggingface/transformers", "loc": 15, "tested_modules": ["trans... |
crewAIInc/crewAI:lib/crewai/tests/hooks/test_tool_hooks.py:TestToolHooksIntegration.test_hooks_with_validation_and_sanitization | # Context:
from crewai.hooks.tool_hooks import (
ToolCallHookContext,
get_after_tool_call_hooks,
get_before_tool_call_hooks,
register_after_tool_call_hook,
register_before_tool_call_hook,
)
def mock_tool(): ...
def mock_agent(): ...
def mock_task(): ...
def mock_crew(): ...
def clear_hooks(): ...
c... | def test_hooks_with_validation_and_sanitization(self, mock_tool):
"""Test a realistic scenario with validation and sanitization hooks."""
# Validation hook (before)
def validate_file_path(context):
if context.tool_name == "write_file":
file_path = context.tool_input.g... | test | 0 | {"function_name": "test_hooks_with_validation_and_sanitization", "class_name": "TestToolHooksIntegration", "qualname": "TestToolHooksIntegration.test_hooks_with_validation_and_sanitization", "file_path": "lib/crewai/tests/hooks/test_tool_hooks.py", "repo_id": "crewAIInc/crewAI", "loc": 53, "tested_modules": ["__future_... |
browser-use/browser-use:examples/features/add_image_context.py:main | # Context:
from browser_use import Agent
from browser_use.llm import ChatOpenAI
def image_to_base64(image_path: str) -> str: ...
def create_sample_images() -> list[ContentPartTextParam | ContentPartImageParam]: ...
# Task:
Write a Python async function `main` to main function to run the browser agent with image conte... | async def main() -> None:
"""
Main function to run the browser agent with image context.
"""
# Task configuration
task_str = 'goto https://www.google.com/ and click image button'
# Initialize the language model
model = ChatOpenAI(model='gpt-4.1')
# Create sample images for context
try:
sample_images = crea... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 21, "code_loc": 10, "docstring_loc": 3, "function_name": "main", "class_name": null, "qualname": "main", "file_path": "examples/features/add_image_context.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "project_runnable"} |
crewAIInc/crewAI:lib/crewai/tests/utilities/events/test_async_event_bus.py:module_doc | Write a module-level docstring for the Python module `test_async_event_bus` which contains class `AsyncTestEvent`. | Tests for async event handling in CrewAI event bus.
This module tests async handler registration, execution, and the aemit method. | documentation | 0 | {"doc_type": "module", "module_name": "test_async_event_bus", "file_path": "lib/crewai/tests/utilities/events/test_async_event_bus.py", "repo_id": "crewAIInc/crewAI", "char_length": 131} |
ray-project/ray:python/ray/tests/test_runtime_env_get_wheel_names.py:test_get_master_wheel_url | # Context:
import requests
import ray._private.ray_constants as ray_constants
from ray._private.utils import (
get_master_wheel_url,
get_release_wheel_url,
get_wheel_filename,
)
def test_get_wheel_filename(): ...
def test_get_release_wheel_url(): ...
# Task:
Write a Python test function `test_get_master_w... | def test_get_master_wheel_url():
"""Test the code that generates the filenames of `master` commit wheels."""
# NOTE: These should not be changed for releases.
ray_version = "3.0.0.dev0"
# This should be a commit for which wheels have already been built for
# all platforms and python versions at
... | test | 0 | {"function_name": "test_get_master_wheel_url", "class_name": null, "qualname": "test_get_master_wheel_url", "file_path": "python/ray/tests/test_runtime_env_get_wheel_names.py", "repo_id": "ray-project/ray", "loc": 17, "tested_modules": ["ray._private.utils"], "has_docstring": true, "runnable_level": "plib_runnable"} |
jax-ml/jax:jaxlib/tools/build_mosaic_wheel.py:license_header | Add a Apache-2.0 license header comment for the project 'jax', authored by The JAX Authors, year 2025. | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | license | 1 | {"license_type": "Apache-2.0", "author": "The JAX Authors", "year": "2025", "source": "header", "repo_id": "jax-ml/jax"} |
run-llama/llama_index:llama-index-core/tests/test_rate_limiter.py:test_llm_sync_complete_calls_acquire | # Context:
from unittest.mock import AsyncMock, MagicMock, patch
from llama_index.core.llms.mock import MockLLM
def test_base_rate_limiter_is_abstract() -> None: ...
def test_token_bucket_is_subclass_of_base() -> None: ...
def test_rate_limiter_alias_is_token_bucket() -> None: ...
def test_instance_is_base_rate_limite... | def test_llm_sync_complete_calls_acquire() -> None:
mock_limiter = MagicMock()
llm = MockLLM()
llm.rate_limiter = mock_limiter
llm.complete("hello")
mock_limiter.acquire.assert_called_once() | test | 1 | {"function_name": "test_llm_sync_complete_calls_acquire", "class_name": null, "qualname": "test_llm_sync_complete_calls_acquire", "file_path": "llama-index-core/tests/test_rate_limiter.py", "repo_id": "run-llama/llama_index", "loc": 6, "tested_modules": ["llama_index.core.base.llms.types", "llama_index.core.llms.mock",... |
deepspeedai/DeepSpeed:deepspeed/runtime/superoffload/superoffload_stage3.py:SuperOffloadOptimizer_Stage3.step | # Context:
import torch
class SuperOffloadOptimizer_Stage3(DeepSpeedZeroOptimizer_Stage3):
def __init__(
self,
module,
init_optimizer,
param_names,
timers,
ds_config,
**kwargs,
):
self.sub_group_to_param_num = {}
self.params_in_ipg_bucket... | def step(self, closure=None):
"""
Not supporting closure.
"""
# Wait for any pending asynchronous CPU optimizer operations
self._wait_for_async_operations()
self._pre_step()
self._partition_all_parameters()
if self._overflow_check_and_loss_scale_upda... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 43, "code_loc": 22, "docstring_loc": 3, "function_name": "step", "class_name": "SuperOffloadOptimizer_Stage3", "qualname": "SuperOffloadOptimizer_Stage3.step", "file_path": "deepspeed/runtime/superoffload/superoffload_stage3.py", "repo_id": "deepspeedai/DeepSpeed", "has_docstring": tr... |
vllm-project/vllm:vllm/v1/attention/backends/mamba_attn.py:BaseMambaAttentionMetadataBuilder.build | # Context:
from typing import Any, ClassVar, TypeVar
import torch
from vllm.v1.attention.backend import (
AttentionCGSupport,
AttentionMetadataBuilder,
CommonAttentionMetadata,
)
class BaseMambaAttentionMetadata: ...
class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
def __... | def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
*,
num_accepted_tokens: torch.Tensor | None = None,
**kwargs: Any,
) -> M:
"""
Default build implementation for Mamba-like attenti... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 16, "code_loc": 3, "docstring_loc": 4, "function_name": "build", "class_name": "BaseMambaAttentionMetadataBuilder", "qualname": "BaseMambaAttentionMetadataBuilder.build", "file_path": "vllm/v1/attention/backends/mamba_attn.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "r... |
crewAIInc/crewAI:lib/crewai-tools/tests/test_generate_tool_specs.py:test_save_to_json | # Context:
import json
class MockToolSchema(BaseModel): ...
class MockTool(BaseTool): ...
def extractor(): ...
def test_unwrap_schema(extractor): ...
def mock_tool_extractor(extractor): ...
def test_extract_basic_tool_info(mock_tool_extractor): ...
def test_extract_init_params_schema(mock_tool_extractor): ...
def test... | def test_save_to_json(extractor, tmp_path):
extractor.tools_spec = [
{
"name": "TestTool",
"humanized_name": "Test Tool",
"description": "A test tool",
"run_params_schema": [
{"name": "param1", "description": "Test parameter", "type": "str"}
... | test | 0 | {"function_name": "test_save_to_json", "class_name": null, "qualname": "test_save_to_json", "file_path": "lib/crewai-tools/tests/test_generate_tool_specs.py", "repo_id": "crewAIInc/crewAI", "loc": 24, "tested_modules": ["crewai.tools.base_tool", "crewai_tools.generate_tool_specs", "pydantic"], "has_docstring": false, "... |
exo-explore/exo:src/exo/worker/tests/unittests/test_runner/test_dsml_e2e.py:TestE2EEdgeCases.test_empty_model_response | # Context:
from exo.shared.types.worker.runner_response import (
GenerationResponse,
ToolCallResponse,
)
from exo.worker.runner.llm_inference.runner import parse_deepseek_v32
def _simulate_tokens(texts: list[str], finish_on_last: bool) -> Generator[GenerationResponse]: ...
class TestE2EStandardResponse: ...
cl... | def test_empty_model_response(self):
"""Model produces only EOS (empty response)."""
model_tokens = [""]
results = list(parse_deepseek_v32(_simulate_tokens(model_tokens)))
gen_results = [r for r in results if isinstance(r, GenerationResponse)]
assert len(gen_results) == 1
... | test | 0 | {"function_name": "test_empty_model_response", "class_name": "TestE2EEdgeCases", "qualname": "TestE2EEdgeCases.test_empty_model_response", "file_path": "src/exo/worker/tests/unittests/test_runner/test_dsml_e2e.py", "repo_id": "exo-explore/exo", "loc": 8, "tested_modules": ["collections.abc", "typing", "exo.shared.types... |
paperless-ngx/paperless-ngx:src/paperless/tests/settings/test_environment_parsers.py:TestGetEnvChoice.test_raises_error_when_env_value_invalid | # Context:
import pytest
from pytest_mock import MockerFixture
from paperless.settings.parsers import get_choice_from_env
class TestStringToBool: ...
class TestParseDictFromString: ...
class TestGetIntFromEnv: ...
class TestGetEnvChoice:
def valid_choices(self) -> set[str]: ...
def test_returns_valid_env_valu... | def test_raises_error_when_env_value_invalid(
self,
mocker: MockerFixture,
valid_choices: set[str],
) -> None:
"""Test that function raises ValueError when env value is not in choices."""
mocker.patch.dict("os.environ", {"TEST_ENV": "invalid_value"})
with pytest.rais... | test | 1 | {"function_name": "test_raises_error_when_env_value_invalid", "class_name": "TestGetEnvChoice", "qualname": "TestGetEnvChoice.test_raises_error_when_env_value_invalid", "file_path": "src/paperless/tests/settings/test_environment_parsers.py", "repo_id": "paperless-ngx/paperless-ngx", "loc": 20, "tested_modules": ["pathl... |
fastapi/fastapi:scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_lines_number_mismatch.py:test_lt | # Context:
from pathlib import Path
import pytest
from typer.testing import CliRunner
from scripts.translation_fixer import cli
def test_gt(runner: CliRunner, root_dir: Path, copy_test_files): ...
# Task:
Write a Python test function `test_lt` to verify the behavior of `lt`.
Module under test: pathlib, typer.testing... | def test_lt(runner: CliRunner, root_dir: Path, copy_test_files):
result = runner.invoke(
cli,
["fix-pages", "docs/lang/docs/doc.md"],
)
# assert result.exit_code == 1, result.output
fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8")
expected_content ... | test | 1 | {"function_name": "test_lt", "class_name": null, "qualname": "test_lt", "file_path": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_lines_number_mismatch.py", "repo_id": "fastapi/fastapi", "loc": 17, "tested_modules": ["pathlib", "typer.testing", "scripts.translation_fixer"], "has_docstring": f... |
crewAIInc/crewAI:lib/crewai/tests/utilities/test_pydantic_schema_utils.py:TestStripNullFromTypes.test_strips_null_from_anyof | # Context:
from copy import deepcopy
from crewai.utilities.pydantic_schema_utils import (
build_rich_field_description,
convert_oneof_to_anyof,
create_model_from_schema,
ensure_all_properties_required,
ensure_type_in_schemas,
force_additional_properties_false,
resolve_refs,
strip_null_fr... | def test_strips_null_from_anyof(self) -> None:
schema = {
"anyOf": [{"type": "string"}, {"type": "null"}],
}
result = strip_null_from_types(deepcopy(schema))
assert "anyOf" not in result
assert result["type"] == "string" | test | 0 | {"function_name": "test_strips_null_from_anyof", "class_name": "TestStripNullFromTypes", "qualname": "TestStripNullFromTypes.test_strips_null_from_anyof", "file_path": "lib/crewai/tests/utilities/test_pydantic_schema_utils.py", "repo_id": "crewAIInc/crewAI", "loc": 7, "tested_modules": ["__future__", "copy", "typing", ... |
paperless-ngx/paperless-ngx:src/documents/workflows/webhooks.py:WebhookTransport._format_ip_for_url | # Context:
import ipaddress
def send_webhook(url: str, data: str | dict, headers: dict, files: dict, as_json: bool): ...
class WebhookTransport(httpx.HTTPTransport):
def __init__(
self,
hostname: str,
*args,
allow_internal: bool = False,
**kwargs,
) -> None:
sup... | def _format_ip_for_url(self, ip: str) -> str:
"""
Format IP address for use in URL (wrap IPv6 in brackets)
"""
try:
ip_obj = ipaddress.ip_address(ip)
if ip_obj.version == 6:
return f"[{ip}]"
return ip
except ValueError:
... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 11, "code_loc": 7, "docstring_loc": 3, "function_name": "_format_ip_for_url", "class_name": "WebhookTransport", "qualname": "WebhookTransport._format_ip_for_url", "file_path": "src/documents/workflows/webhooks.py", "repo_id": "paperless-ngx/paperless-ngx", "has_docstring": true, "runn... |
browser-use/browser-use:browser_use/mcp/server.py:handle_call_tool | # Context:
import time
from typing import Any
from browser_use.telemetry import MCPServerTelemetryEvent, ProductTelemetry
from browser_use.utils import create_task_with_error_handling, get_browser_use_version
import mcp.types as types
def _configure_mcp_server_logging(): ...
def _ensure_all_loggers_use_stderr(): ...
d... | async def handle_call_tool(name: str, arguments: dict[str, Any] | None) -> list[types.TextContent | types.ImageContent]:
"""Handle tool execution."""
start_time = time.time()
error_msg = None
try:
result = await self._execute_tool(name, arguments or {})
if isinstance(result, list):
return resul... | function_simple | 0 | {"cognitive_complexity": 3, "loc": 25, "code_loc": 22, "docstring_loc": 1, "function_name": "handle_call_tool", "class_name": null, "qualname": "handle_call_tool", "file_path": "browser_use/mcp/server.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "project_runnable"} |
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/aws/bedrock/code_interpreter/code_interpreter_toolkit.py:ExecuteCommandTool:class_doc | Write a class-level docstring for `ExecuteCommandTool` (inherits from BaseTool) which has methods: `__init__`, `_run`, `_arun`. | Tool for running shell commands in the code interpreter environment. | documentation | 0 | {"doc_type": "class", "class_name": "ExecuteCommandTool", "file_path": "lib/crewai-tools/src/crewai_tools/aws/bedrock/code_interpreter/code_interpreter_toolkit.py", "repo_id": "crewAIInc/crewAI", "char_length": 68, "methods": ["__init__", "_run", "_arun"]} |
Zie619/n8n-workflows:run.py:start_server | # Context:
import os
import uvicorn
def print_banner(): ...
def check_requirements() -> bool: ...
def setup_directories(): ...
def setup_database(force_reindex: bool, skip_index: bool) -> str: ...
def main(): ...
# Task:
Write a Python function `start_server` to start the FastAPI server.
Parameters: host: str, port:... | def start_server(host: str = "127.0.0.1", port: int = 8000, reload: bool = False):
"""Start the FastAPI server."""
print(f"🌐 Starting server at http://{host}:{port}")
print(f"📊 API Documentation: http://{host}:{port}/docs")
print(f"🔍 Workflow Search: http://{host}:{port}/api/workflows")
print()
... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 23, "code_loc": 16, "docstring_loc": 1, "function_name": "start_server", "class_name": null, "qualname": "start_server", "file_path": "run.py", "repo_id": "Zie619/n8n-workflows", "has_docstring": true, "runnable_level": "plib_runnable"} |
ray-project/ray:python/ray/data/tests/test_issue_detection.py:TestHangingExecutionIssueDetector.test_hanging_detector_configuration | # Context:
from ray.data._internal.issue_detection.detectors.hanging_detector import (
DEFAULT_OP_TASK_STATS_MIN_COUNT,
DEFAULT_OP_TASK_STATS_STD_FACTOR,
HangingExecutionIssueDetector,
HangingExecutionIssueDetectorConfig,
)
from ray.data.context import DataContext
class FakeOpTask(OpTask): ...
class Fa... | def test_hanging_detector_configuration(self, restore_data_context):
"""Test hanging detector configuration and initialization."""
# Test default configuration from DataContext
ctx = DataContext.get_current()
default_config = ctx.issue_detectors_config.hanging_detector_config
ass... | test | 0 | {"function_name": "test_hanging_detector_configuration", "class_name": "TestHangingExecutionIssueDetector", "qualname": "TestHangingExecutionIssueDetector.test_hanging_detector_configuration", "file_path": "python/ray/data/tests/test_issue_detection.py", "repo_id": "ray-project/ray", "loc": 24, "tested_modules": ["ray.... |
langflow-ai/langflow:src/backend/tests/unit/agentic/helpers/test_error_handling.py:TestExtractFriendlyError.test_should_return_friendly_message_for_timeout_error | # Context:
from langflow.agentic.helpers.error_handling import (
ERROR_PATTERNS,
MAX_ERROR_MESSAGE_LENGTH,
MIN_MEANINGFUL_PART_LENGTH,
_truncate_error_message,
extract_friendly_error,
)
class TestTruncateErrorMessage: ...
class TestErrorPatterns: ...
class TestConstants: ...
class TestExtractFrien... | def test_should_return_friendly_message_for_timeout_error(self):
"""Should return user-friendly message for timeout errors."""
error_messages = [
"Request timeout",
"Connection timed out",
"Operation timed out after 30 seconds",
]
for error in error_m... | test | 1 | {"function_name": "test_should_return_friendly_message_for_timeout_error", "class_name": "TestExtractFriendlyError", "qualname": "TestExtractFriendlyError.test_should_return_friendly_message_for_timeout_error", "file_path": "src/backend/tests/unit/agentic/helpers/test_error_handling.py", "repo_id": "langflow-ai/langflo... |
huggingface/diffusers:tests/models/test_models_auto.py:TestAutoModel.test_load_from_model_index | # Context:
from transformers import CLIPTextModel, LongformerModel
from diffusers.models import AutoModel, UNet2DConditionModel
class TestAutoModelFromConfig(unittest.TestCase): ...
class TestRegisterForAutoClass(unittest.TestCase): ...
class TestAutoModel(unittest.TestCase):
def test_load_from_config_diffusers_w... | def test_load_from_model_index(self):
model = AutoModel.from_pretrained(
"hf-internal-testing/tiny-stable-diffusion-torch", subfolder="text_encoder", use_safetensors=False
)
assert isinstance(model, CLIPTextModel) | test | 1 | {"function_name": "test_load_from_model_index", "class_name": "TestAutoModel", "qualname": "TestAutoModel.test_load_from_model_index", "file_path": "tests/models/test_models_auto.py", "repo_id": "huggingface/diffusers", "loc": 5, "tested_modules": ["transformers", "diffusers", "diffusers.models", "diffusers.models.mode... |
langflow-ai/langflow:src/lfx/tests/unit/events/test_event_manager.py:TestEventManagerFactories.test_default_manager_event_execution | # Context:
from unittest.mock import MagicMock
from lfx.events.event_manager import (
EventManager,
create_default_event_manager,
create_stream_tokens_event_manager,
)
class TestEventManager: ...
class TestEventManagerAsync: ...
class TestEventManagerFactories:
def test_create_default_event_manager(se... | def test_default_manager_event_execution(self):
"""Test that events in default manager can be executed."""
queue = MagicMock()
manager = create_default_event_manager(queue)
# Test executing different events
test_events = [
("on_token", {"chunk": "test"}),
... | test | 1 | {"function_name": "test_default_manager_event_execution", "class_name": "TestEventManagerFactories", "qualname": "TestEventManagerFactories.test_default_manager_event_execution", "file_path": "src/lfx/tests/unit/events/test_event_manager.py", "repo_id": "langflow-ai/langflow", "loc": 18, "tested_modules": ["lfx.events.... |
huggingface/diffusers:src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2i.py:whitespace_clean | # Context:
import regex as re
def basic_clean(text): ...
def prompt_clean(text): ...
class Kandinsky5I2IPipeline(DiffusionPipeline, KandinskyLoraLoaderMixin): ...
# Task:
Write a Python function `whitespace_clean` to copied from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_w... | def whitespace_clean(text):
"""
Copied from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan.py
Normalize whitespace in text by replacing multiple spaces with single space.
"""
text = re.sub(r"\s+", " ", text)
text = text.strip()
return text | function_simple | 1 | {"cognitive_complexity": 0, "loc": 9, "code_loc": 3, "docstring_loc": 5, "function_name": "whitespace_clean", "class_name": null, "qualname": "whitespace_clean", "file_path": "src/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2i.py", "repo_id": "huggingface/diffusers", "has_docstring": true, "runnable_level": "pro... |
crewAIInc/crewAI:lib/crewai/tests/test_crew_multimodal.py:TestCrewMultimodalBedrock.test_pdf_file | # Context:
import pytest
from crewai import Agent, Crew, LLM, Task
from crewai_files import AudioFile, File, ImageFile, PDFFile, TextFile, VideoFile
def image_file() -> ImageFile: ...
def image_bytes() -> bytes: ...
def text_file() -> TextFile: ...
def text_bytes() -> bytes: ...
def pdf_file() -> PDFFile: ...
def vide... | def test_pdf_file(self, model: str, pdf_file: PDFFile) -> None:
"""Test crew can process a PDF file."""
llm = LLM(model=model)
crew = _create_analyst_crew(llm)
result = crew.kickoff(input_files={"document": pdf_file})
assert result.raw
assert len(result.raw) > 0 | test | 0 | {"function_name": "test_pdf_file", "class_name": "TestCrewMultimodalBedrock", "qualname": "TestCrewMultimodalBedrock.test_pdf_file", "file_path": "lib/crewai/tests/test_crew_multimodal.py", "repo_id": "crewAIInc/crewAI", "loc": 9, "tested_modules": ["pathlib", "crewai", "crewai_files"], "has_docstring": true, "runnable... |
apache/airflow:airflow-core/tests/unit/serialization/definitions/test_assets.py:test_asset_alias_as_expression | # Context:
from airflow.serialization.definitions.assets import (
SerializedAsset,
SerializedAssetAlias,
SerializedAssetAll,
SerializedAssetAny,
SerializedAssetUniqueKey,
)
def test_asset_iter_assets(): ...
def test_asset_iter_asset_aliases(): ...
class TestSerializedAssetUniqueKey: ...
# Task:
Wr... | def test_asset_alias_as_expression():
alias = SerializedAssetAlias(name="test_name", group="test")
assert alias.as_expression() == {"alias": {"name": "test_name", "group": "test"}} | test | 1 | {"function_name": "test_asset_alias_as_expression", "class_name": null, "qualname": "test_asset_alias_as_expression", "file_path": "airflow-core/tests/unit/serialization/definitions/test_assets.py", "repo_id": "apache/airflow", "loc": 3, "tested_modules": ["__future__", "airflow.api_fastapi.execution_api.datamodels.ass... |
mem0ai/mem0:mem0/vector_stores/neptune_analytics.py:NeptuneAnalyticsVector.get | # Context:
class OutputData(BaseModel): ...
class NeptuneAnalyticsVector(VectorStoreBase):
_COLLECTION_PREFIX = "MEM0_VECTOR_"
_FIELD_N = 'n'
_FIELD_ID = '~id'
_FIELD_PROP = '~properties'
_FIELD_SCORE = 'score'
_FIELD_LABEL = 'label'
_TIMEZONE = "UTC"
def __init__(
self,
... | def get(self, vector_id: str):
"""
Retrieve a vector by its ID.
Fetches the node data including metadata for the specified vector ID.
Args:
vector_id (str): ID of the vector to retrieve.
Returns:
OutputData: Vector data with ... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 24, "code_loc": 9, "docstring_loc": 11, "function_name": "get", "class_name": "NeptuneAnalyticsVector", "qualname": "NeptuneAnalyticsVector.get", "file_path": "mem0/vector_stores/neptune_analytics.py", "repo_id": "mem0ai/mem0", "has_docstring": true, "runnable_level": "class_runnable"... |
Shubhamsaboo/awesome-llm-apps:advanced_llm_apps/llm_optimization_tools/headroom_context_optimization/headroom_demo.py:module_doc | Write a module-level docstring for the Python module `headroom_demo` which contains function `generate_test_logs`, function `demo_without_headroom`, function `demo_with_headroom`, function `calculate_savings`, function `demo_langchain_integration`. | Headroom Context Optimization Demo
==================================
This demo shows how Headroom reduces token usage by 50-90% while preserving
accuracy. It recreates the "needle in haystack" test from the Headroom repo.
Run: python headroom_demo.py | documentation | 0 | {"doc_type": "module", "module_name": "headroom_demo", "file_path": "advanced_llm_apps/llm_optimization_tools/headroom_context_optimization/headroom_demo.py", "repo_id": "Shubhamsaboo/awesome-llm-apps", "char_length": 253} |
ansible/ansible:lib/ansible/_internal/_ssh/_agent_launch.py:launch_ssh_agent | # Context:
from ansible.errors import AnsibleError
def _launch_ssh_agent() -> None: ...
# Task:
Write a Python function `launch_ssh_agent` to if configured via `SSH_AGENT`, launch an ssh-agent for Ansible's use and/or verify access to an existing one.
Returns: None | def launch_ssh_agent() -> None:
"""If configured via `SSH_AGENT`, launch an ssh-agent for Ansible's use and/or verify access to an existing one."""
try:
_launch_ssh_agent()
except Exception as ex:
raise AnsibleError("Failed to launch ssh agent.") from ex | function_simple | 1 | {"cognitive_complexity": 1, "loc": 6, "code_loc": 4, "docstring_loc": 1, "function_name": "launch_ssh_agent", "class_name": null, "qualname": "launch_ssh_agent", "file_path": "lib/ansible/_internal/_ssh/_agent_launch.py", "repo_id": "ansible/ansible", "has_docstring": true, "runnable_level": "project_runnable"} |
langflow-ai/langflow:src/lfx/tests/unit/base/data/test_docling_utils.py:TestDocumentConverterCaching.test_cached_converter_function_exists | # Context:
from lfx.base.data.docling_utils import _get_cached_converter
class TestExtractDoclingDocuments: ...
class TestDocumentConverterCaching:
def test_cached_converter_cache_key(self): ...
def test_cached_converter_lru_eviction(self): ...
def test_cached_converter_performance_improvement(self): ...
... | def test_cached_converter_function_exists(self):
"""Test that _get_cached_converter function exists and is properly decorated."""
from lfx.base.data.docling_utils import _get_cached_converter
# Verify function exists
assert callable(_get_cached_converter)
# Verify it has cache_... | test | 1 | {"function_name": "test_cached_converter_function_exists", "class_name": "TestDocumentConverterCaching", "qualname": "TestDocumentConverterCaching.test_cached_converter_function_exists", "file_path": "src/lfx/tests/unit/base/data/test_docling_utils.py", "repo_id": "langflow-ai/langflow", "loc": 10, "tested_modules": ["... |
mem0ai/mem0:tests/vector_stores/test_valkey.py:test_delete | # Context:
def mock_valkey_client(): ...
def valkey_db(mock_valkey_client): ...
def test_search_filter_syntax(valkey_db, mock_valkey_client): ...
def test_search_without_filters(valkey_db, mock_valkey_client): ...
def test_insert(valkey_db, mock_valkey_client): ...
def test_insert_handles_missing_created_at(valkey_db,... | def test_delete(valkey_db, mock_valkey_client):
"""Test deleting a vector."""
# Call delete
valkey_db.delete("test_id")
# Check that delete was called with the correct key
mock_valkey_client.delete.assert_called_once_with("mem0:test_collection:test_id") | test | 1 | {"function_name": "test_delete", "class_name": null, "qualname": "test_delete", "file_path": "tests/vector_stores/test_valkey.py", "repo_id": "mem0ai/mem0", "loc": 7, "tested_modules": ["datetime", "valkey.exceptions", "mem0.vector_stores.valkey"], "has_docstring": true, "runnable_level": "file_runnable"} |
crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/anthropic/completion.py:AnthropicCompletion._extract_anthropic_token_usage | # Context:
from typing import TYPE_CHECKING, Any, Final, Literal, TypeGuard, cast
from anthropic.types import Message, TextBlock, ThinkingBlock, ToolUseBlock
from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
def _supports_native_structured_outputs(model: str) -> bool: ...
def _is_pydantic_m... | def _extract_anthropic_token_usage(
response: Message | BetaMessage,
) -> dict[str, Any]:
"""Extract token usage from Anthropic response."""
if hasattr(response, "usage") and response.usage:
usage = response.usage
input_tokens = getattr(usage, "input_tokens", 0)
... | function_simple | 0 | {"cognitive_complexity": 3, "loc": 16, "code_loc": 12, "docstring_loc": 1, "function_name": "_extract_anthropic_token_usage", "class_name": "AnthropicCompletion", "qualname": "AnthropicCompletion._extract_anthropic_token_usage", "file_path": "lib/crewai/src/crewai/llms/providers/anthropic/completion.py", "repo_id": "cr... |
karpathy/nanochat:nanochat/core_eval.py:forward_model | # Context:
import torch
def render_prompts_mc(item, continuation_delimiter, fewshot_examples): ...
def render_prompts_schema(item, continuation_delimiter, fewshot_examples): ...
def render_prompts_lm(item, continuation_delimiter, fewshot_examples): ...
def find_common_length(token_sequences, direction): ...
def stack_... | def forward_model(model, input_ids):
"""
Take BxT tensor of token ids, return BxT tensor of losses and argmax predictions.
The last column of losses is set to nan because we don't have autoregressive targets there.
"""
batch_size, seq_len = input_ids.size()
outputs = model(input_ids)
# Roll ... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 20, "code_loc": 11, "docstring_loc": 4, "function_name": "forward_model", "class_name": null, "qualname": "forward_model", "file_path": "nanochat/core_eval.py", "repo_id": "karpathy/nanochat", "has_docstring": true, "runnable_level": "plib_runnable"} |
crewAIInc/crewAI:lib/crewai/tests/llms/openai/test_openai.py:test_openai_responses_api_auto_chain_reasoning_adds_include | # Context:
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_when_no_provider_prefix(): ...
def test_openai_is_de... | def test_openai_responses_api_auto_chain_reasoning_adds_include():
"""Test that auto_chain_reasoning adds reasoning.encrypted_content to include."""
llm = OpenAICompletion(
model="gpt-4o",
api="responses",
auto_chain_reasoning=True,
)
params = llm._prepare_responses_params(messa... | test | 0 | {"function_name": "test_openai_responses_api_auto_chain_reasoning_adds_include", "class_name": null, "qualname": "test_openai_responses_api_auto_chain_reasoning_adds_include", "file_path": "lib/crewai/tests/llms/openai/test_openai.py", "repo_id": "crewAIInc/crewAI", "loc": 11, "tested_modules": ["typing", "crewai.llm",... |
crewAIInc/crewAI:lib/crewai/tests/utilities/test_files.py:TestGenericFile.test_file_read_text | # Context:
from crewai_files import (
AudioFile,
File,
FileBytes,
FilePath,
FileSource,
FileStream,
ImageFile,
PDFFile,
TextFile,
VideoFile,
normalize_input_files,
wrap_file_source,
)
class TestDetectContentType: ...
class TestFilePath: ...
class TestFileBytes: ...
class... | def test_file_read_text(self) -> None:
"""Test File.read_text method."""
f = File(source=b"Text content here")
assert f.read_text() == "Text content here" | test | 0 | {"function_name": "test_file_read_text", "class_name": "TestGenericFile", "qualname": "TestGenericFile.test_file_read_text", "file_path": "lib/crewai/tests/utilities/test_files.py", "repo_id": "crewAIInc/crewAI", "loc": 5, "tested_modules": ["pathlib", "crewai_files", "crewai_files.core.sources"], "has_docstring": true... |
ray-project/ray:release/ray_release/tests/test_custom_byod_build.py:test_custom_byod_build_with_env | # Context:
from unittest.mock import patch
from click.testing import CliRunner
from ray_release.scripts.custom_byod_build import main
def test_custom_byod_build(mock_build_anyscale_custom_byod_image): ...
def test_custom_byod_build_without_lock_file(mock_build_anyscale_custom_byod_image): ...
def test_custom_byod_buil... | def test_custom_byod_build_with_env(mock_build_anyscale_custom_byod_image):
mock_build_anyscale_custom_byod_image.return_value = None
runner = CliRunner()
result = runner.invoke(
main,
[
"--image-name",
"test-image",
"--base-image",
"test-base-... | test | 0 | {"function_name": "test_custom_byod_build_with_env", "class_name": null, "qualname": "test_custom_byod_build_with_env", "file_path": "release/ray_release/tests/test_custom_byod_build.py", "repo_id": "ray-project/ray", "loc": 21, "tested_modules": ["click.testing", "ray_release.scripts.custom_byod_build"], "has_docstrin... |
infiniflow/ragflow:test/unit_test/utils/test_oceanbase_health.py:TestOBConnectionPerformanceMetrics.test_get_performance_metrics_connection_error | # Context:
from unittest.mock import Mock, patch
class TestOceanBaseHealthCheck: ...
class TestOBConnectionPerformanceMetrics:
def _create_mock_connection(self): ...
def test_get_performance_metrics_success(self): ...
def test_get_storage_info_success(self): ...
def test_get_storage_info_fallback(self... | def test_get_performance_metrics_connection_error(self):
"""Test performance metrics when connection fails."""
# Create mock connection with actual methods
conn = self._create_mock_connection()
mock_client = Mock()
conn.client = mock_client
conn.uri = "localhost:2881"
... | test | 1 | {"function_name": "test_get_performance_metrics_connection_error", "class_name": "TestOBConnectionPerformanceMetrics", "qualname": "TestOBConnectionPerformanceMetrics.test_get_performance_metrics_connection_error", "file_path": "test/unit_test/utils/test_oceanbase_health.py", "repo_id": "infiniflow/ragflow", "loc": 15,... |
crewAIInc/crewAI:lib/crewai/src/crewai/a2a/utils/agent_card_signing.py:module_doc | Write a module-level docstring for the Python module `agent_card_signing` which contains function `_normalize_private_key`, function `_serialize_agent_card`, function `_base64url_encode`, function `sign_agent_card`, function `verify_agent_card_signature`. | AgentCard JWS signing utilities.
This module provides functions for signing and verifying AgentCards using
JSON Web Signatures (JWS) as per RFC 7515. Signed agent cards allow clients
to verify the authenticity and integrity of agent card information.
Example:
>>> from crewai.a2a.utils.agent_card_signing import si... | documentation | 0 | {"doc_type": "module", "module_name": "agent_card_signing", "file_path": "lib/crewai/src/crewai/a2a/utils/agent_card_signing.py", "repo_id": "crewAIInc/crewAI", "char_length": 490} |
langchain-ai/langchain:libs/partners/perplexity/tests/unit_tests/test_output_parsers.py:TestStripThinkTags.test_strip_think_tags_no_closing_tag | # Context:
from langchain_perplexity.output_parsers import (
ReasoningJsonOutputParser,
ReasoningStructuredOutputParser,
strip_think_tags,
)
class TestReasoningJsonOutputParser: ...
class MockPerson(BaseModel): ...
class MockCompany(BaseModel): ...
class TestReasoningStructuredOutputParser: ...
class Test... | def test_strip_think_tags_no_closing_tag(self) -> None:
"""Test handling of think tags without closing tag."""
text = "Hello <think>unclosed reasoning world"
result = strip_think_tags(text)
# Treats unclosed tag as literal text
assert result == "Hello <think>unclosed reasoning wo... | test | 1 | {"function_name": "test_strip_think_tags_no_closing_tag", "class_name": "TestStripThinkTags", "qualname": "TestStripThinkTags.test_strip_think_tags_no_closing_tag", "file_path": "libs/partners/perplexity/tests/unit_tests/test_output_parsers.py", "repo_id": "langchain-ai/langchain", "loc": 6, "tested_modules": ["langcha... |
infiniflow/ragflow:test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py:TestParserConfigBugFix.test_parser_config_with_both_fields | # Context:
import pytest
from ragflow_sdk import DataSet, RAGFlow
class TestAuthorization: ...
class TestCapability: ...
class TestDatasetCreate: ...
class TestParserConfigBugFix:
def test_parser_config_missing_raptor_and_graphrag(self, client): ...
def test_parser_config_with_only_raptor(self, client): ...
... | def test_parser_config_with_both_fields(self, client):
parser_config = DataSet.ParserConfig(client, {"chunk_token_num": 1024, "raptor": {"use_raptor": True}, "graphrag": {"use_graphrag": True}})
payload = {"name": "test_parser_config_both_fields_sdk", "parser_config": parser_config}
dataset = cl... | test | 1 | {"function_name": "test_parser_config_with_both_fields", "class_name": "TestParserConfigBugFix", "qualname": "TestParserConfigBugFix.test_parser_config_with_both_fields", "file_path": "test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py", "repo_id": "infiniflow/ragflow", "loc": 8, "tested_modules"... |
browser-use/browser-use:examples/sandbox/example.py:on_browser_ready | Write a Python function `on_browser_ready` to callback when browser session is created.
Parameters: data | def on_browser_ready(data):
"""Callback when browser session is created"""
print('\n🌐 Browser session created!')
print(f' Session ID: {data.session_id}')
print(f' Live view: {data.live_url}')
print(' Click the link above to watch the AI agent work!\n') | function_simple | 0 | {"cognitive_complexity": 0, "loc": 6, "code_loc": 4, "docstring_loc": 1, "function_name": "on_browser_ready", "class_name": null, "qualname": "on_browser_ready", "file_path": "examples/sandbox/example.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "self_contained"} |
ray-project/ray:python/ray/llm/tests/common/cloud/test_mirror_config.py:TestCloudMirrorConfig.test_valid_s3_uri | # Context:
from ray.llm._internal.common.utils.cloud_utils import (
CloudMirrorConfig,
LoraMirrorConfig,
)
class TestLoraMirrorConfig: ...
class TestCloudMirrorConfig:
def test_valid_gcs_uri(self): ...
def test_valid_abfss_uri(self): ...
def test_valid_azure_uri(self): ...
def test_none_uri(se... | def test_valid_s3_uri(self):
"""Test valid S3 URI."""
config = CloudMirrorConfig(bucket_uri="s3://my-bucket/path")
assert config.bucket_uri == "s3://my-bucket/path"
assert config.storage_type == "s3" | test | 0 | {"function_name": "test_valid_s3_uri", "class_name": "TestCloudMirrorConfig", "qualname": "TestCloudMirrorConfig.test_valid_s3_uri", "file_path": "python/ray/llm/tests/common/cloud/test_mirror_config.py", "repo_id": "ray-project/ray", "loc": 5, "tested_modules": ["ray.llm._internal.common.utils.cloud_utils"], "has_docs... |
apache/airflow:helm-tests/tests/helm_tests/redis/test_labels_service.py:TestRedisService.test_component_specific_labels_should_override_global_labels | # Context:
import jmespath
from chart_utils.helm_template_generator import render_chart
class TestRedisService:
AIRFLOW_EXECUTOR = "CeleryExecutor"
TEMPLATE_FILE = "templates/redis/redis-service.yaml"
def test_should_add_global_labels(self): ...
def test_should_add_component_specific_labels(self): ...
... | def test_component_specific_labels_should_override_global_labels(self):
"""Test that component-specific labels take precedence over global labels with the same key."""
docs = render_chart(
values={
"executor": self.AIRFLOW_EXECUTOR,
"redis": {
... | test | 1 | {"function_name": "test_component_specific_labels_should_override_global_labels", "class_name": "TestRedisService", "qualname": "TestRedisService.test_component_specific_labels_should_override_global_labels", "file_path": "helm-tests/tests/helm_tests/redis/test_labels_service.py", "repo_id": "apache/airflow", "loc": 16... |
apache/airflow:shared/configuration/tests/configuration/test_parser.py:TestAirflowConfigParser.test_deprecated_options_precedence | # Context:
from configparser import ConfigParser
class AirflowConfigParser(_SharedAirflowConfigParser): ...
class TestAirflowConfigParser:
def test_getboolean(self): ...
def test_getint(self): ...
def test_getfloat(self): ...
def test_getlist(self): ...
def test_getjson(self, config_str, expected)... | def test_deprecated_options_precedence(self):
"""Test that new option takes precedence over deprecated option"""
class TestParserWithDeprecated(AirflowConfigParser):
deprecated_options = {
("test", "new_key"): ("test", "old_key", "2.0.0"),
}
def __in... | test | 1 | {"function_name": "test_deprecated_options_precedence", "class_name": "TestAirflowConfigParser", "qualname": "TestAirflowConfigParser.test_deprecated_options_precedence", "file_path": "shared/configuration/tests/configuration/test_parser.py", "repo_id": "apache/airflow", "loc": 20, "tested_modules": ["__future__", "con... |
vllm-project/vllm:vllm/lora/ops/triton_ops/fused_moe_lora_fp8_op.py:_get_expert_id | # Context:
from vllm.triton_utils import tl, triton
def _get_lora_id(lora_ids, token_lora_mapping_ptr, lora_idx, pid_m, top_k_num, naive_block_assignment: tl.constexpr): ...
def _get_token_offs(sorted_token_ids_ptr, lora_id, pid_m, offs, stride_tl, max_loras, num_valid_tokens, naive_block_assignment: tl.constexpr, BLO... | def _get_expert_id(
expert_ids_ptr,
lora_id,
pid_m,
stride_el,
max_loras,
naive_block_assignment: tl.constexpr,
):
"""Returns expert_id"""
if naive_block_assignment:
return tl.load(expert_ids_ptr + pid_m)
else:
ind = lora_id * stride_el + pid_m
return tl.load(... | function_simple | 1 | {"cognitive_complexity": 2, "loc": 14, "code_loc": 5, "docstring_loc": 1, "function_name": "_get_expert_id", "class_name": null, "qualname": "_get_expert_id", "file_path": "vllm/lora/ops/triton_ops/fused_moe_lora_fp8_op.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "project_runnable"} |
ray-project/ray:python/ray/data/collate_fn.py:DefaultCollateFn.__init__ | # Context:
from concurrent.futures import ThreadPoolExecutor
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
List,
Mapping,
Optional,
Tuple,
TypeVar,
Union,
)
import torch
def _is_tensor(batch: Any) -> bool: ...
def _is_tensor_sequence(batch: Any) -> bool: ...
def _is_ne... | def __init__(
self,
dtypes: Optional[Union["torch.dtype", Dict[str, "torch.dtype"]]] = None,
device: Optional["TorchDeviceType"] = None,
pin_memory: bool = False,
num_workers: int = _DEFAULT_NUM_WORKERS,
):
"""Initialize the collate function.
Args:
... | function_simple | 0 | {"cognitive_complexity": 2, "loc": 29, "code_loc": 10, "docstring_loc": 11, "function_name": "__init__", "class_name": "DefaultCollateFn", "qualname": "DefaultCollateFn.__init__", "file_path": "python/ray/data/collate_fn.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "class_runnable"} |
exo-explore/exo:src/exo/master/placement_utils.py:get_mlx_jaccl_devices_matrix | # Context:
from exo.shared.topology import Topology
from exo.shared.types.common import Host, NodeId
from exo.shared.types.topology import Cycle, RDMAConnection, SocketConnection
def filter_cycles_by_memory(cycles: list[Cycle], node_memory: Mapping[NodeId, MemoryUsage], required_memory: Memory) -> list[Cycle]: ...
def... | def get_mlx_jaccl_devices_matrix(
selected_cycle: list[NodeId],
cycle_digraph: Topology,
) -> list[list[str | None]]:
"""Build connectivity matrix mapping device i to device j via RDMA interface names.
The matrix element [i][j] contains the interface name on device i that connects
to device j, or N... | function_complex | 0 | {"cognitive_complexity": 13, "loc": 30, "code_loc": 17, "docstring_loc": 6, "function_name": "get_mlx_jaccl_devices_matrix", "class_name": null, "qualname": "get_mlx_jaccl_devices_matrix", "file_path": "src/exo/master/placement_utils.py", "repo_id": "exo-explore/exo", "has_docstring": true, "runnable_level": "project_r... |
github/spec-kit:src/specify_cli/extensions.py:ExtensionManifest.__init__ | # Context:
from pathlib import Path
class ExtensionError(Exception): ...
class ValidationError(ExtensionError): ...
class CompatibilityError(ExtensionError): ...
class ExtensionRegistry: ...
class ExtensionManager: ...
def version_satisfies(current: str, required: str) -> bool: ...
class CommandRegistrar: ...
class Ex... | def __init__(self, manifest_path: Path):
"""Load and validate extension manifest.
Args:
manifest_path: Path to extension.yml file
Raises:
ValidationError: If manifest is invalid
"""
self.path = manifest_path
self.data = self._load_yaml(manifest_p... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 12, "code_loc": 3, "docstring_loc": 8, "function_name": "__init__", "class_name": "ExtensionManifest", "qualname": "ExtensionManifest.__init__", "file_path": "src/specify_cli/extensions.py", "repo_id": "github/spec-kit", "has_docstring": true, "runnable_level": "class_runnable"} |
infiniflow/ragflow:api/db/services/doc_metadata_service.py:DocMetadataService._drop_empty_metadata_table | # Context:
import logging
from common import settings
from common.doc_store.doc_store_base import OrderByExpr
class DocMetadataService:
def _get_doc_meta_index_name(tenant_id: str) -> str: ...
def _extract_metadata(flat_meta: Dict) -> Dict: ...
def _extract_doc_id(doc: Dict, hit: Dict) -> str: ...
def ... | def _drop_empty_metadata_table(cls, index_name: str, tenant_id: str) -> None:
"""
Check if metadata table is empty and drop it if so.
Uses optimized count query instead of full search.
This prevents accumulation of empty metadata tables.
Args:
index_name: Metadata ta... | function_complex | 1 | {"cognitive_complexity": 23, "loc": 84, "code_loc": 53, "docstring_loc": 9, "function_name": "_drop_empty_metadata_table", "class_name": "DocMetadataService", "qualname": "DocMetadataService._drop_empty_metadata_table", "file_path": "api/db/services/doc_metadata_service.py", "repo_id": "infiniflow/ragflow", "has_docstr... |
huggingface/transformers:tests/models/mm_grounding_dino/test_modeling_mm_grounding_dino.py:MMGroundingDinoModelIntegrationTests.test_inference_object_detection_head_equivalence_cpu_gpu | # Context:
from transformers.testing_utils import (
is_flaky,
require_timm,
require_torch,
require_torch_accelerator,
require_vision,
slow,
torch_device,
)
import torch
from transformers import MMGroundingDinoConfig, MMGroundingDinoForObjectDetection, MMGroundingDinoModel
def generate_fake_... | def test_inference_object_detection_head_equivalence_cpu_gpu(self):
processor = self.default_processor
image = prepare_img()
text = prepare_text()
encoding = processor(images=image, text=text, return_tensors="pt")
# 1. run model on CPU
model = MMGroundingDinoForObjectDet... | test | 0 | {"function_name": "test_inference_object_detection_head_equivalence_cpu_gpu", "class_name": "MMGroundingDinoModelIntegrationTests", "qualname": "MMGroundingDinoModelIntegrationTests.test_inference_object_detection_head_equivalence_cpu_gpu", "file_path": "tests/models/mm_grounding_dino/test_modeling_mm_grounding_dino.py... |
run-llama/llama_index:llama-index-integrations/memory/llama-index-memory-bedrock-agentcore/tests/test_agentcore_memory.py:TestBaseAgentCoreMemoryMethods.test_create_event_no_event_id | # Context:
import pytest
from llama_index.core.base.llms.types import ChatMessage, MessageRole
def mock_client(): ...
def memory_context(): ...
def memory(mock_client, memory_context): ...
class TestAgentCoreMemoryContext: ...
class TestAgentCoreMemory: ...
class TestIntegration: ...
class TestErrorHandling: ...
async... | def test_create_event_no_event_id(self, memory):
"""Test create_event raises error when no event ID is returned."""
memory._client.create_event.return_value = {"event": {"eventId": None}}
messages = [ChatMessage(role=MessageRole.USER, content="Hello")]
with pytest.raises(
Ru... | test | 1 | {"function_name": "test_create_event_no_event_id", "class_name": "TestBaseAgentCoreMemoryMethods", "qualname": "TestBaseAgentCoreMemoryMethods.test_create_event_no_event_id", "file_path": "llama-index-integrations/memory/llama-index-memory-bedrock-agentcore/tests/test_agentcore_memory.py", "repo_id": "run-llama/llama_i... |
langflow-ai/langflow:src/lfx/tests/unit/cli/test_serve_simple.py:test_serve_command_missing_api_key | # Context:
import json
import os
import tempfile
from pathlib import Path
from unittest.mock import patch
from typer.testing import CliRunner
from lfx.__main__ import app, main
from lfx.__main__ import app
def test_cli_imports(): ...
def test_serve_command_help(): ...
def test_serve_command_with_flow_json(): ...
def t... | def test_serve_command_missing_api_key():
"""Test that serve command fails without API key."""
from lfx.__main__ import app
# Create a temporary JSON flow file
flow_data = {
"data": {
"nodes": [],
"edges": [],
}
}
with tempfile.NamedTemporaryFile(mode="w... | test | 1 | {"function_name": "test_serve_command_missing_api_key", "class_name": null, "qualname": "test_serve_command_missing_api_key", "file_path": "src/lfx/tests/unit/cli/test_serve_simple.py", "repo_id": "langflow-ai/langflow", "loc": 27, "tested_modules": ["pathlib", "typer.testing", "lfx.__main__", "lfx.__main__", "lfx.__ma... |
huggingface/transformers:tests/models/vibevoice_acoustic_tokenizer/test_feature_extraction_vibevoice_acoustic_tokenizer.py:VibeVoiceAcousticTokenizerFeatureExtractionTest.test_call | # Context:
import numpy as np
import torch
def floats_list(shape, scale, rng, name): ...
class VibeVoiceAcousticTokenizerFeatureExtractionTester: ...
class VibeVoiceAcousticTokenizerFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase):
feature_extraction_class = VibeVoiceAcousticTokenizerF... | def test_call(self):
TOL = 1e-6
feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
sampling_rate = feature_extractor.sampling_rate
audio_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
np_audio_inputs = [np.... | test | 0 | {"function_name": "test_call", "class_name": "VibeVoiceAcousticTokenizerFeatureExtractionTest", "qualname": "VibeVoiceAcousticTokenizerFeatureExtractionTest.test_call", "file_path": "tests/models/vibevoice_acoustic_tokenizer/test_feature_extraction_vibevoice_acoustic_tokenizer.py", "repo_id": "huggingface/transformers"... |
ocrmypdf/OCRmyPDF:tests/test_pdf_renderer.py:TestFpdf2PdfRendererTextangle.test_rotated_text | # Context:
from ocrmypdf.fpdf_renderer import DebugRenderOptions, Fpdf2PdfRenderer
from ocrmypdf.helpers import check_pdf
from ocrmypdf.hocrtransform import (
Baseline,
BoundingBox,
OcrClass,
OcrElement,
)
def text_from_pdf(filename: Path) -> str: ...
def font_dir(): ...
def multi_font_manager(font_dir... | def test_rotated_text(self, tmp_path, multi_font_manager):
"""Test rendering rotated text."""
word = OcrElement(
ocr_class=OcrClass.WORD,
text="Rotated",
bbox=BoundingBox(left=100, top=100, right=200, bottom=150),
)
line = OcrElement(
ocr_c... | test | 1 | {"function_name": "test_rotated_text", "class_name": "TestFpdf2PdfRendererTextangle", "qualname": "TestFpdf2PdfRendererTextangle.test_rotated_text", "file_path": "tests/test_pdf_renderer.py", "repo_id": "ocrmypdf/OCRmyPDF", "loc": 36, "tested_modules": ["__future__", "io", "pathlib", "pdfminer.converter", "pdfminer.lay... |
langflow-ai/langflow:src/backend/tests/locust/langflow_locustfile.py:SustainedLoadUser:class_doc | Write a class-level docstring for `SustainedLoadUser` (inherits from BaseLangflowUser) which has methods: `steady_load`. | Maintains exactly 1 request/second for steady load testing. | documentation | 1 | {"doc_type": "class", "class_name": "SustainedLoadUser", "file_path": "src/backend/tests/locust/langflow_locustfile.py", "repo_id": "langflow-ai/langflow", "char_length": 59, "methods": ["steady_load"]} |
mem0ai/mem0:mem0/vector_stores/valkey.py:ValkeyDB.delete_col | # Context:
class OutputData(BaseModel): ...
class ValkeyDB(VectorStoreBase):
def __init__(
self,
valkey_url: str,
collection_name: str,
embedding_model_dims: int,
timezone: str = "UTC",
index_type: str = "hnsw",
hnsw_m: int = 16,
hnsw_ef_construction... | def delete_col(self):
"""
Delete the current collection (index).
"""
return self._drop_index(self.collection_name, log_level="info") | function_simple | 1 | {"cognitive_complexity": 0, "loc": 5, "code_loc": 1, "docstring_loc": 3, "function_name": "delete_col", "class_name": "ValkeyDB", "qualname": "ValkeyDB.delete_col", "file_path": "mem0/vector_stores/valkey.py", "repo_id": "mem0ai/mem0", "has_docstring": true, "runnable_level": "class_runnable"} |
streamlit/streamlit:e2e_playwright/st_plotly_chart_dimensions_test.py:test_plotly_stretch_width_fullscreen | # Context:
from playwright.sync_api import Page, expect
from e2e_playwright.conftest import ImageCompareFunction
def test_check_top_level_class(app: Page): ...
def test_plotly_dimensions(app: Page, assert_snapshot: ImageCompareFunction): ...
def test_plotly_content_width_fullscreen(themed_app: Page, assert_snapshot: I... | def test_plotly_stretch_width_fullscreen(
themed_app: Page, assert_snapshot: ImageCompareFunction
):
"""Test fullscreen behavior with width='stretch'."""
index = 1 # Second chart with width='stretch'
themed_app.get_by_test_id("stPlotlyChart").nth(index).hover()
fullscreen_button = themed_app.locato... | test | 1 | {"function_name": "test_plotly_stretch_width_fullscreen", "class_name": null, "qualname": "test_plotly_stretch_width_fullscreen", "file_path": "e2e_playwright/st_plotly_chart_dimensions_test.py", "repo_id": "streamlit/streamlit", "loc": 33, "tested_modules": ["playwright.sync_api", "e2e_playwright.conftest", "e2e_playw... |
ray-project/ray:python/ray/llm/_internal/batch/stages/serve_deployment_stage.py:ServeDeploymentStageUDF.__init__ | # Context:
from typing import Any, AsyncIterator, Dict, List, Optional, Tuple, Type
from ray import serve
class ServeDeploymentStage(StatefulStage): ...
class ServeDeploymentStageUDF(StatefulStageUDF):
def _prepare_request(self, row: Dict[str, Any]) -> Tuple[Dict[str, Any], Optional[Type[Any]], str]: ...
asyn... | def __init__(
self,
data_column: str,
expected_input_keys: List[str],
*,
deployment_name: str,
app_name: str,
dtype_mapping: Dict[str, Type[Any]],
should_continue_on_error: bool = False,
):
"""
Initialize the ServeDeploymentStageUDF.
... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 33, "code_loc": 7, "docstring_loc": 13, "function_name": "__init__", "class_name": "ServeDeploymentStageUDF", "qualname": "ServeDeploymentStageUDF.__init__", "file_path": "python/ray/llm/_internal/batch/stages/serve_deployment_stage.py", "repo_id": "ray-project/ray", "has_docstring": ... |
huggingface/transformers:tests/models/exaone_moe/test_modeling_exaone_moe.py:ExaoneMoeIntegrationTest.test_model_generation_beyond_sliding_window_flash | # Context:
from pytest import mark
import torch
class ExaoneMoeModelTester(CausalLMModelTester): ...
class ExaoneMoeModelTest(CausalLMModelTest, unittest.TestCase): ...
class ExaoneMoeIntegrationTest(unittest.TestCase):
TEST_MODEL_ID = "hf-internal-testing/EXAONE-MoE-Dummy-7B-A1B"
def setUpClass(cls): ...
... | def test_model_generation_beyond_sliding_window_flash(self):
EXPECTED_OUTPUT_TOKEN_IDS = [373, 686, 373, 115708, 373, 885]
input_ids = [72861, 2711] + [21605, 2711] * 2048
model = self.get_model()
model.set_attn_implementation("flash_attention_2")
input_ids = torch.tensor([input_... | test | 0 | {"function_name": "test_model_generation_beyond_sliding_window_flash", "class_name": "ExaoneMoeIntegrationTest", "qualname": "ExaoneMoeIntegrationTest.test_model_generation_beyond_sliding_window_flash", "file_path": "tests/models/exaone_moe/test_modeling_exaone_moe.py", "repo_id": "huggingface/transformers", "loc": 10,... |
ray-project/ray:python/ray/autoscaler/v2/instance_manager/subscribers/cloud_resource_monitor.py:CloudResourceMonitor.get_resource_availabilities | # Context:
from typing import Dict, List
from ray.autoscaler.v2.schema import NodeType
class CloudResourceMonitor(InstanceUpdatedSubscriber):
def __init__(
self,
) -> None:
self._last_unavailable_timestamp: Dict[NodeType, float] = {}
def allocation_timeout(self, failed_event: InstanceUpdate... | def get_resource_availabilities(self) -> Dict[NodeType, float]:
"""Calculate the availability scores of node types.
Higher values indicate a higher likelihood of resource allocation.
"""
resource_availability_scores: Dict[NodeType, float] = {}
if self._last_unavailable_timestamp:... | function_simple | 0 | {"cognitive_complexity": 3, "loc": 12, "code_loc": 8, "docstring_loc": 3, "function_name": "get_resource_availabilities", "class_name": "CloudResourceMonitor", "qualname": "CloudResourceMonitor.get_resource_availabilities", "file_path": "python/ray/autoscaler/v2/instance_manager/subscribers/cloud_resource_monitor.py", ... |
browser-use/browser-use:browser_use/skill_cli/commands/cloud_session.py:delete_session | # Context:
from browser_use.skill_cli.commands.utils import format_duration, get_sdk_client
def create_session(**kwargs) -> SessionItemView: ...
def list_sessions(limit: int, status: str | None) -> list[SessionItemView]: ...
def get_session(session_id: str) -> SessionView: ...
def stop_session(session_id: str) -> Sess... | def delete_session(session_id: str) -> None:
"""Delete a cloud session and all its tasks."""
get_sdk_client().sessions.delete_session(session_id) | function_simple | 0 | {"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "delete_session", "class_name": null, "qualname": "delete_session", "file_path": "browser_use/skill_cli/commands/cloud_session.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "project_runnable"} |
PaddlePaddle/PaddleOCR:paddleocr/_pipelines/ocr.py:license_header | Add a Apache-2.0 license header comment for the project 'PaddleOCR', authored by PaddlePaddle Authors, year 2025. | # Copyright (c) 2025 PaddlePaddle Authors. 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 appli... | license | 0 | {"license_type": "Apache-2.0", "author": "PaddlePaddle Authors", "year": "2025", "source": "header", "repo_id": "PaddlePaddle/PaddleOCR"} |
apache/airflow:task-sdk/tests/task_sdk/execution_time/test_context_cache.py:TestCacheDisabled.test_get_connection_no_cache_when_disabled | # Context:
from unittest.mock import AsyncMock, MagicMock, call, patch
from airflow.sdk.execution_time.comms import ConnectionResult, VariableResult
from airflow.sdk.execution_time.context import (
_delete_variable,
_get_connection,
_get_variable,
_set_variable,
)
from airflow.sdk.execution_time.secrets... | def test_get_connection_no_cache_when_disabled(self, mock_ensure_backends, mock_supervisor_comms):
"""Test that cache is not used when disabled."""
conn_id = "test_conn"
conn_result = ConnectionResult(conn_id=conn_id, conn_type="mysql", host="host")
mock_ensure_backends.return_value = [... | test | 1 | {"function_name": "test_get_connection_no_cache_when_disabled", "class_name": "TestCacheDisabled", "qualname": "TestCacheDisabled.test_get_connection_no_cache_when_disabled", "file_path": "task-sdk/tests/task_sdk/execution_time/test_context_cache.py", "repo_id": "apache/airflow", "loc": 19, "tested_modules": ["__future... |
google/langextract:tests/prompting_test.py:ContextAwarePromptBuilderTest.test_first_chunk_has_no_previous_context | # Context:
from langextract import prompting
class QAPromptGeneratorTest(parameterized.TestCase): ...
class PromptBuilderTest(absltest.TestCase): ...
class ContextAwarePromptBuilderTest(absltest.TestCase):
def _create_generator(self): ...
def test_context_window_chars_property(self): ...
def test_second_c... | def test_first_chunk_has_no_previous_context(self):
"""Verifies the first chunk does not include previous context."""
generator = self._create_generator()
builder = prompting.ContextAwarePromptBuilder(
generator, context_window_chars=50
)
context_prefix = prompting.ContextAwarePromptBuilder.... | test | 1 | {"function_name": "test_first_chunk_has_no_previous_context", "class_name": "ContextAwarePromptBuilderTest", "qualname": "ContextAwarePromptBuilderTest.test_first_chunk_has_no_previous_context", "file_path": "tests/prompting_test.py", "repo_id": "google/langextract", "loc": 15, "tested_modules": ["absl.testing", "absl.... |
ray-project/ray:python/ray/dashboard/modules/aggregator/tests/test_aggregator_agent.py:test_aggregator_agent_receive_empty_events | # Context:
import pytest
from ray.core.generated.events_event_aggregator_service_pb2 import (
AddEventsRequest,
RayEventsData,
TaskEventsMetadata,
)
def httpserver_listen_address(): ...
def fake_timestamp(): ...
def generate_event_export_env_vars(preserve_proto_field_name: Optional[bool], additional_env_va... | def test_aggregator_agent_receive_empty_events(
ray_start_cluster_head_with_env_vars,
httpserver,
):
cluster = ray_start_cluster_head_with_env_vars
stub = get_event_aggregator_grpc_stub(
cluster.gcs_address, cluster.head_node.node_id
)
httpserver.expect_request("/", method="POST").respon... | test | 0 | {"function_name": "test_aggregator_agent_receive_empty_events", "class_name": null, "qualname": "test_aggregator_agent_receive_empty_events", "file_path": "python/ray/dashboard/modules/aggregator/tests/test_aggregator_agent.py", "repo_id": "ray-project/ray", "loc": 18, "tested_modules": ["typing", "google.protobuf.time... |
apache/airflow:shared/module_loading/tests/module_loading/test_file_discovery.py:TestFindPathFromDirectory.test_find_path_from_directory_fails_on_recursive_link | # Context:
import os
from pathlib import Path
import pytest
from airflow_shared.module_loading import find_path_from_directory
class TestFindPathFromDirectory:
def test_dir(self, tmp_path): ...
def test_find_path_from_directory_respects_symlinks_regexp_ignore(self, test_dir): ...
def test_find_path_from_di... | def test_find_path_from_directory_fails_on_recursive_link(self, test_dir):
# add a recursive link
recursing_src = os.path.join(test_dir, "folder2", "recursor")
recursing_tgt = os.path.join(test_dir, "folder2")
os.mkdir(recursing_tgt)
os.symlink(recursing_tgt, recursing_src)
... | test | 1 | {"function_name": "test_find_path_from_directory_fails_on_recursive_link", "class_name": "TestFindPathFromDirectory", "qualname": "TestFindPathFromDirectory.test_find_path_from_directory_fails_on_recursive_link", "file_path": "shared/module_loading/tests/module_loading/test_file_discovery.py", "repo_id": "apache/airflo... |
exo-explore/exo:src/exo/master/tests/test_event_log.py:test_empty_log | # Context:
from pathlib import Path
from exo.master.event_log import DiskEventLog
def log_dir(tmp_path: Path) -> Path: ...
def test_append_and_read_back(log_dir: Path): ...
def test_read_range(log_dir: Path): ...
def test_read_range_bounds(log_dir: Path): ...
def _archives(log_dir: Path) -> list[Path]: ...
def test_ro... | def test_empty_log(log_dir: Path):
log = DiskEventLog(log_dir)
assert len(log) == 0
assert list(log.read_all()) == []
assert list(log.read_range(0, 10)) == []
log.close() | test | 0 | {"function_name": "test_empty_log", "class_name": null, "qualname": "test_empty_log", "file_path": "src/exo/master/tests/test_event_log.py", "repo_id": "exo-explore/exo", "loc": 6, "tested_modules": ["pathlib", "exo.master.event_log", "exo.shared.types.events"], "has_docstring": false, "runnable_level": "project_runnab... |
crewAIInc/crewAI:lib/crewai/tests/hooks/test_llm_hooks.py:TestAfterLLMCallHooks.test_after_hook_returns_none_keeps_original | # Context:
from crewai.hooks.llm_hooks import (
LLMCallHookContext,
get_after_llm_call_hooks,
get_before_llm_call_hooks,
register_after_llm_call_hook,
register_before_llm_call_hook,
)
def mock_executor(): ...
def clear_hooks(): ...
class TestLLMCallHookContext: ...
class TestBeforeLLMCallHooks: ...... | def test_after_hook_returns_none_keeps_original(self, mock_executor):
"""Test that returning None keeps the original response."""
original_response = "Original response"
def no_change_hook(context):
return None
context = LLMCallHookContext(executor=mock_executor, response=o... | test | 0 | {"function_name": "test_after_hook_returns_none_keeps_original", "class_name": "TestAfterLLMCallHooks", "qualname": "TestAfterLLMCallHooks.test_after_hook_returns_none_keeps_original", "file_path": "lib/crewai/tests/hooks/test_llm_hooks.py", "repo_id": "crewAIInc/crewAI", "loc": 12, "tested_modules": ["__future__", "cr... |
vllm-project/vllm:vllm/v1/core/sched/request_queue.py:PriorityRequestQueue.peek_request | # Context:
from vllm.v1.request import Request
class SchedulingPolicy(Enum): ...
class RequestQueue(ABC): ...
class FCFSRequestQueue(deque[Request], RequestQueue): ...
def create_request_queue(policy: SchedulingPolicy) -> RequestQueue: ...
class PriorityRequestQueue(RequestQueue):
def __init__(self) -> None:
... | def peek_request(self) -> Request:
"""Peek at the next request in the queue without removing it."""
if not self._heap:
raise IndexError("peek from empty heap")
return self._heap[0] | function_simple | 1 | {"cognitive_complexity": 1, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "peek_request", "class_name": "PriorityRequestQueue", "qualname": "PriorityRequestQueue.peek_request", "file_path": "vllm/v1/core/sched/request_queue.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "p... |
unclecode/crawl4ai:tests/cache_validation/test_real_domains.py:TestRealDomainsNoConditionalSupport.test_news_site_changes_frequently | # Context:
import pytest
from crawl4ai.cache_validator import CacheValidator, CacheValidationResult
class TestRealDomainsConditionalSupport: ...
class TestRealDomainsEdgeCases: ...
class TestRealDomainsHeadFingerprint: ...
class TestRealDomainsFetchHead: ...
class TestRealDomainsValidationCombinations: ...
class Test... | async def test_news_site_changes_frequently(self):
"""News sites change frequently - test that we can detect changes."""
url = "https://www.bbc.com/news"
async with CacheValidator(timeout=15.0) as validator:
head_html, etag, last_modified = await validator._fetch_head(url)
... | test | 1 | {"function_name": "test_news_site_changes_frequently", "class_name": "TestRealDomainsNoConditionalSupport", "qualname": "TestRealDomainsNoConditionalSupport.test_news_site_changes_frequently", "file_path": "tests/cache_validation/test_real_domains.py", "repo_id": "unclecode/crawl4ai", "loc": 18, "tested_modules": ["cra... |
jax-ml/jax:jax/_src/test_multiprocess.py:GracefulKiller:class_doc | Write a class-level docstring for `GracefulKiller` which has methods: `__init__`, `exit_gracefully`. | Add a signal handler that sets a flag if SIGINT or SIGTERM are caught. | documentation | 1 | {"doc_type": "class", "class_name": "GracefulKiller", "file_path": "jax/_src/test_multiprocess.py", "repo_id": "jax-ml/jax", "char_length": 70, "methods": ["__init__", "exit_gracefully"]} |
crewAIInc/crewAI:lib/crewai-tools/tests/tools/test_txt_search_tool_config.py:test_txt_search_tool_with_azure_config_without_env_vars | # Context:
from unittest.mock import MagicMock, Mock, patch
from crewai_tools.adapters.crewai_rag_adapter import CrewAIRagAdapter
from crewai_tools.tools.txt_search_tool.txt_search_tool import TXTSearchTool
def test_txt_search_tool_with_openai_config_without_env_vars(mock_create_client: Mock) -> None: ...
def test_txt... | def test_txt_search_tool_with_azure_config_without_env_vars(
mock_create_client: Mock,
) -> None:
"""Test TXTSearchTool accepts Azure config without requiring env vars."""
mock_embedding_func = MagicMock()
mock_embedding_func.return_value = [[0.1] * 1536]
mock_client = MagicMock()
mock_client.g... | test | 0 | {"function_name": "test_txt_search_tool_with_azure_config_without_env_vars", "class_name": null, "qualname": "test_txt_search_tool_with_azure_config_without_env_vars", "file_path": "lib/crewai-tools/tests/tools/test_txt_search_tool_config.py", "repo_id": "crewAIInc/crewAI", "loc": 35, "tested_modules": ["crewai_tools.a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.