sample_id string | instruction string | completion string | category string | label int64 | metadata string |
|---|---|---|---|---|---|
run-llama/llama_index:llama-index-core/llama_index/core/chat_engine/multi_modal_context.py:MultiModalContextChatEngine.from_defaults | # Context:
from typing import Any, List, Optional, Sequence, Tuple, Union
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
ChatResponseAsyncGen,
ChatResponseGen,
MessageRole,
)
from llama_index.core.llms import LLM, TextBlock, ChatMessage, ImageBlock
from llama_index.core.po... | def from_defaults(
cls,
retriever: BaseRetriever,
chat_history: Optional[List[ChatMessage]] = None,
memory: Optional[BaseMemory] = None,
system_prompt: Optional[str] = None,
node_postprocessors: Optional[List[BaseNodePostprocessor]] = None,
context_template: Optio... | function_simple | 1 | {"cognitive_complexity": 5, "loc": 32, "code_loc": 17, "docstring_loc": 1, "function_name": "from_defaults", "class_name": "MultiModalContextChatEngine", "qualname": "MultiModalContextChatEngine.from_defaults", "file_path": "llama-index-core/llama_index/core/chat_engine/multi_modal_context.py", "repo_id": "run-llama/ll... |
huggingface/transformers:src/transformers/models/xlm_roberta_xl/modular_xlm_roberta_xl.py:license_header | Add a Apache-2.0 license header comment for the project 'transformers', authored by The Google AI Language Team Authors and The HuggingFace Inc, year 2018. | # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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.
# coding=utf-8
# Copyright 2022 The H... | license | 0 | {"license_type": "Apache-2.0", "author": "The Google AI Language Team Authors and The HuggingFace Inc", "year": "2018", "source": "header", "repo_id": "huggingface/transformers"} |
ray-project/ray:python/ray/serve/tests/test_direct_ingress.py:test_get_serve_instance_details_json_serializable | # Context:
import json
import pytest
import ray
from ray import serve
from ray.serve._private.constants import (
DEFAULT_AUTOSCALING_POLICY_NAME,
HEALTHY_MESSAGE,
RAY_SERVE_DIRECT_INGRESS_MAX_HTTP_PORT,
RAY_SERVE_DIRECT_INGRESS_MIN_GRPC_PORT,
RAY_SERVE_DIRECT_INGRESS_MIN_HTTP_PORT,
RAY_SERVE_DIR... | def test_get_serve_instance_details_json_serializable(
_skip_if_ff_not_enabled, serve_instance, policy_name
):
"""Test the result from get_serve_instance_details is json serializable."""
controller = _get_global_client()._controller
autoscaling_config = {
"min_replicas": 1,
"max_replic... | test | 0 | {"function_name": "test_get_serve_instance_details_json_serializable", "class_name": null, "qualname": "test_get_serve_instance_details_json_serializable", "file_path": "python/ray/serve/tests/test_direct_ingress.py", "repo_id": "ray-project/ray", "loc": 196, "tested_modules": ["concurrent.futures", "typing", "uuid", "... |
ray-project/ray:python/ray/train/lint/check_circular_imports.py:expand_to_include_reexports | # Context:
from typing import Dict, List, Optional, Set, Tuple
def find_train_packages(base_train_dir: Path, patch_train_dir: Path) -> None: ...
def is_train_package(module_str: str) -> bool: ...
def get_base_dir() -> Path: ...
def get_base_train_dir() -> Path: ...
def does_overlap(main_module: str, module: str) -> bo... | def expand_to_include_reexports(import_map: Dict[str, List[Import]]) -> None:
"""
Expands the set of imports for a given import map to include the modules resulting from reexports.
So if in the base train module, there is "from x import a, b" and x is a package, then this function
will explore the __ini... | function_complex | 0 | {"cognitive_complexity": 6, "loc": 26, "code_loc": 15, "docstring_loc": 5, "function_name": "expand_to_include_reexports", "class_name": null, "qualname": "expand_to_include_reexports", "file_path": "python/ray/train/lint/check_circular_imports.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level":... |
Comfy-Org/ComfyUI:tests-unit/prompt_server_test/system_user_endpoint_test.py:TestSystemUserEndpointBlocking.test_userdata_post_blocks_system_user | # Context:
import pytest
from unittest.mock import patch
def mock_user_directory(tmp_path): ...
def user_manager_multi_user(mock_user_directory): ...
def app_multi_user(user_manager_multi_user): ...
class TestSystemUserCreationBlocking: ...
class TestPublicUserStillWorks: ...
class TestCustomNodeScenario: ...
class Te... | async def test_userdata_post_blocks_system_user(
self, aiohttp_client, app_multi_user, mock_user_directory
):
"""
POST /userdata with System User header should be blocked.
"""
client = await aiohttp_client(app_multi_user)
with patch('app.user_manager.args') as mock_a... | test | 1 | {"function_name": "test_userdata_post_blocks_system_user", "class_name": "TestSystemUserEndpointBlocking", "qualname": "TestSystemUserEndpointBlocking.test_userdata_post_blocks_system_user", "file_path": "tests-unit/prompt_server_test/system_user_endpoint_test.py", "repo_id": "Comfy-Org/ComfyUI", "loc": 21, "tested_mod... |
ray-project/ray:release/nightly_tests/dataset/training_ingest_benchmark.py:BaseDataLoader.__init__ | # Context:
from typing import Dict, List, Optional
from dataset_benchmark_util import IMAGENET_WNID_TO_ID
class BenchmarkConfig: ...
class S3ParquetDataLoader(BaseDataLoader): ...
class S3UrlImageDataLoader(BaseDataLoader): ...
class S3ReadImagesDataLoader(BaseDataLoader): ...
def create_data_loader(data_loader: str, ... | def __init__(self, data_dir: str, label_to_id_map: Dict[str, int] = None):
"""Initialize the data loader.
Args:
data_dir: Path to data directory
label_to_id_map: Mapping from label strings to integer IDs
"""
self.data_dir = data_dir
self.label_to_id_map =... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 9, "code_loc": 2, "docstring_loc": 6, "function_name": "__init__", "class_name": "BaseDataLoader", "qualname": "BaseDataLoader.__init__", "file_path": "release/nightly_tests/dataset/training_ingest_benchmark.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "... |
crewAIInc/crewAI:lib/crewai/tests/utilities/test_pydantic_schema_utils.py:TestBuildRichFieldDescription.test_min_max_length | # Context:
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_from_types,
strip_unsupp... | def test_min_max_length(self) -> None:
desc = build_rich_field_description({"minLength": 1, "maxLength": 255})
assert "Min length: 1" in desc
assert "Max length: 255" in desc | test | 0 | {"function_name": "test_min_max_length", "class_name": "TestBuildRichFieldDescription", "qualname": "TestBuildRichFieldDescription.test_min_max_length", "file_path": "lib/crewai/tests/utilities/test_pydantic_schema_utils.py", "repo_id": "crewAIInc/crewAI", "loc": 4, "tested_modules": ["__future__", "copy", "typing", "p... |
ray-project/ray:python/ray/dashboard/tests/test_dashboard_auth.py:test_dashboard_request_requires_auth_invalid_token | # Context:
import requests
def test_dashboard_request_requires_auth_with_valid_token(setup_cluster_with_token_auth): ...
def test_dashboard_request_requires_auth_missing_token(setup_cluster_with_token_auth): ...
def test_dashboard_request_with_ray_auth_header(setup_cluster_with_token_auth): ...
def test_authorization_... | def test_dashboard_request_requires_auth_invalid_token(setup_cluster_with_token_auth):
"""Test that requests fail with invalid token when auth is enabled."""
cluster_info = setup_cluster_with_token_auth
headers = {"Authorization": "Bearer wrong_token_00000000000000000000000000000000"}
response = reque... | test | 0 | {"function_name": "test_dashboard_request_requires_auth_invalid_token", "class_name": null, "qualname": "test_dashboard_request_requires_auth_invalid_token", "file_path": "python/ray/dashboard/tests/test_dashboard_auth.py", "repo_id": "ray-project/ray", "loc": 13, "tested_modules": [], "has_docstring": true, "runnable_... |
ray-project/ray:doc/source/train/tutorials/ci/py_scripts/04b_tabular_workload_pattern.py:_dmat_from_arrow | # Context:
import numpy as np
import xgboost as xgb
import pyarrow as pa
def _arrow_table_from_shard(name: str) -> pa.Table: ...
def train_func(config): ...
class XGBPredictor: ...
# Task:
Write a Python function `_dmat_from_arrow` to build XGBoost DMatrix from pyarrow.Table with explicit feature_names.
Parameters: ... | def _dmat_from_arrow(table: pa.Table, feature_cols, label_col: str):
"""Build XGBoost DMatrix from pyarrow.Table with explicit feature_names."""
X = np.column_stack([table[c].to_numpy(zero_copy_only=False) for c in feature_cols])
y = table[label_col].to_numpy(zero_copy_only=False)
return xgb.DMatrix(X, ... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "_dmat_from_arrow", "class_name": null, "qualname": "_dmat_from_arrow", "file_path": "doc/source/train/tutorials/ci/py_scripts/04b_tabular_workload_pattern.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level"... |
vllm-project/vllm:tests/entrypoints/openai/tool_parsers/test_hunyuan_a13b_tool_parser.py:test_hunyuan_a13b_tool_parser_streaming | # Context:
from unittest.mock import MagicMock
import pytest
from tests.entrypoints.openai.tool_parsers.utils import (
run_tool_extraction,
run_tool_extraction_streaming,
)
from vllm.tool_parsers import ToolParser, ToolParserManager
def make_tool_call(name, arguments): ...
def test_hunyuan_a13b_tool_parser_ext... | def test_hunyuan_a13b_tool_parser_streaming(model_deltas, expected_tool_calls):
mock_tokenizer = MagicMock()
tool_parser: ToolParser = ToolParserManager.get_tool_parser("hunyuan_a13b")(
mock_tokenizer
)
reconstructor = run_tool_extraction_streaming(
tool_parser, model_deltas, assert_one... | test | 1 | {"function_name": "test_hunyuan_a13b_tool_parser_streaming", "class_name": null, "qualname": "test_hunyuan_a13b_tool_parser_streaming", "file_path": "tests/entrypoints/openai/tool_parsers/test_hunyuan_a13b_tool_parser.py", "repo_id": "vllm-project/vllm", "loc": 15, "tested_modules": ["tests.entrypoints.openai.tool_pars... |
zhayujie/chatgpt-on-wechat:agent/tools/scheduler/scheduler_tool.py:module_doc | Write a module-level docstring for the Python module `scheduler_tool` which contains class `SchedulerTool`. | Scheduler tool for creating and managing scheduled tasks | documentation | 1 | {"doc_type": "module", "module_name": "scheduler_tool", "file_path": "agent/tools/scheduler/scheduler_tool.py", "repo_id": "zhayujie/chatgpt-on-wechat", "char_length": 56} |
infiniflow/ragflow:test/testcases/test_sdk_api/test_chat_assistant_management/test_delete_chat_assistants.py:TestChatAssistantsDelete.test_repeated_deletion | # Context:
import pytest
class TestChatAssistantsDelete:
def test_basic_scenarios(self, client, add_chat_assistants_func, payload, expected_message, remaining): ...
def test_delete_chats_nonzero_response_raises(self, client, monkeypatch): ...
def test_delete_partial_invalid_id(self, client, add_chat_assist... | def test_repeated_deletion(self, client, add_chat_assistants_func):
_, _, chat_assistants = add_chat_assistants_func
chat_ids = [chat.id for chat in chat_assistants]
client.delete_chats(ids=chat_ids)
with pytest.raises(Exception) as exception_info:
client.delete_chats(ids=ch... | test | 1 | {"function_name": "test_repeated_deletion", "class_name": "TestChatAssistantsDelete", "qualname": "TestChatAssistantsDelete.test_repeated_deletion", "file_path": "test/testcases/test_sdk_api/test_chat_assistant_management/test_delete_chat_assistants.py", "repo_id": "infiniflow/ragflow", "loc": 8, "tested_modules": ["co... |
crewAIInc/crewAI:lib/crewai/tests/cli/authentication/providers/test_keycloak.py:TestKeycloakProvider.test_get_token_url_with_different_domain | # Context:
from crewai.cli.authentication.main import Oauth2Settings
from crewai.cli.authentication.providers.keycloak import KeycloakProvider
class TestKeycloakProvider:
def setup_method(self): ...
def test_initialization_with_valid_settings(self): ...
def test_get_authorize_url(self): ...
def test_ge... | def test_get_token_url_with_different_domain(self):
settings = Oauth2Settings(
provider="keycloak",
domain="sso.enterprise.com",
client_id="test-client",
audience="test-audience",
extra={
"realm": "enterprise-realm"
}
... | test | 0 | {"function_name": "test_get_token_url_with_different_domain", "class_name": "TestKeycloakProvider", "qualname": "TestKeycloakProvider.test_get_token_url_with_different_domain", "file_path": "lib/crewai/tests/cli/authentication/providers/test_keycloak.py", "repo_id": "crewAIInc/crewAI", "loc": 13, "tested_modules": ["cr... |
crewAIInc/crewAI:lib/crewai/tests/utilities/test_pydantic_schema_utils.py:TestRequiredOptional.test_required_field_has_no_default | # Context:
import pytest
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_from_types,
... | def test_required_field_has_no_default(self) -> None:
schema = {
"type": "object",
"properties": {"name": {"type": "string"}},
"required": ["name"],
}
Model = create_model_from_schema(schema)
with pytest.raises(Exception):
Model() | test | 0 | {"function_name": "test_required_field_has_no_default", "class_name": "TestRequiredOptional", "qualname": "TestRequiredOptional.test_required_field_has_no_default", "file_path": "lib/crewai/tests/utilities/test_pydantic_schema_utils.py", "repo_id": "crewAIInc/crewAI", "loc": 9, "tested_modules": ["__future__", "copy", ... |
crewAIInc/crewAI:lib/crewai/tests/test_human_feedback_decorator.py:TestHumanFeedbackLearn.test_learn_true_empty_feedback_does_not_store | # Context:
from unittest.mock import MagicMock, patch
from crewai.flow import Flow, human_feedback, listen, start
class TestHumanFeedbackValidation: ...
class TestHumanFeedbackConfig: ...
class TestHumanFeedbackResult: ...
class TestDecoratorAttributePreservation: ...
class TestAsyncSupport: ...
class TestHumanFeedbac... | def test_learn_true_empty_feedback_does_not_store(self):
"""When learn=True but feedback is empty, no lessons are stored."""
class LearnFlow(Flow):
@start()
@human_feedback(message="Review:", llm="gpt-4o-mini", learn=True)
def produce(self):
return "o... | test | 0 | {"function_name": "test_learn_true_empty_feedback_does_not_store", "class_name": "TestHumanFeedbackLearn", "qualname": "TestHumanFeedbackLearn.test_learn_true_empty_feedback_does_not_store", "file_path": "lib/crewai/tests/test_human_feedback_decorator.py", "repo_id": "crewAIInc/crewAI", "loc": 20, "tested_modules": ["_... |
browser-use/browser-use:tests/ci/test_cli_headed_flag.py:test_headed_flag_with_session | # Context:
from browser_use.skill_cli.main import build_parser
def test_headed_flag_before_open_subcommand(): ...
def test_headed_flag_default_is_false(): ...
def test_headed_flag_with_browser_mode(): ...
# Task:
Write a Python test function `test_headed_flag_with_session` to test that --headed works with other globa... | def test_headed_flag_with_session():
"""Test that --headed works with other global flags like -s/--session."""
parser = build_parser()
args = parser.parse_args(['--headed', '-s', 'mysession', 'open', 'http://example.com'])
assert args.headed is True
assert args.session == 'mysession'
assert args.url == 'http://e... | test | 0 | {"function_name": "test_headed_flag_with_session", "class_name": null, "qualname": "test_headed_flag_with_session", "file_path": "tests/ci/test_cli_headed_flag.py", "repo_id": "browser-use/browser-use", "loc": 8, "tested_modules": ["browser_use.skill_cli.main"], "has_docstring": true, "runnable_level": "project_runnabl... |
xtekky/gpt4free:g4f/Provider/qwen/cookie_generator.py:refresh_cookies | # Context:
from g4f import debug
import asyncio
def lzw_compress(data: Optional[str], bits: int, char_func: Callable[[int], str]) -> str: ...
def custom_encode(data: Optional[str], url_safe: bool) -> str: ...
def random_hash() -> int: ...
def generate_device_id() -> str: ...
def parse_real_data(real_data: str) -> List... | async def refresh_cookies():
"""Refresh SSXMOD cookies (async wrapper)."""
global _current_cookies
try:
# generate_cookies() is CPU-bound sync; run it off the event loop.
result = await asyncio.to_thread(generate_cookies)
async with _lock:
_current_cookies = {
... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 18, "code_loc": 13, "docstring_loc": 1, "function_name": "refresh_cookies", "class_name": null, "qualname": "refresh_cookies", "file_path": "g4f/Provider/qwen/cookie_generator.py", "repo_id": "xtekky/gpt4free", "has_docstring": true, "runnable_level": "project_runnable"} |
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/invoke_crewai_automation_tool/invoke_crewai_automation_tool.py:InvokeCrewAIAutomationTool:class_doc | Write a class-level docstring for `InvokeCrewAIAutomationTool` (inherits from BaseTool) which has methods: `__init__`, `_kickoff_crew`, `_get_crew_status`, `_run`. | A CrewAI tool for invoking external crew/flows APIs.
This tool provides CrewAI Platform API integration with external crew services, supporting:
- Dynamic input schema configuration
- Automatic polling for task completion
- Bearer token authentication
- Comprehensive error handling
Example:
Basic usage:
>>> t... | documentation | 0 | {"doc_type": "class", "class_name": "InvokeCrewAIAutomationTool", "file_path": "lib/crewai-tools/src/crewai_tools/tools/invoke_crewai_automation_tool/invoke_crewai_automation_tool.py", "repo_id": "crewAIInc/crewAI", "char_length": 1650, "methods": ["__init__", "_kickoff_crew", "_get_crew_status", "_run"]} |
crewAIInc/crewAI:lib/crewai/src/crewai/a2a/config.py:A2AClientConfig:class_doc | Write a class-level docstring for `A2AClientConfig` (inherits from BaseModel) which has methods: `_migrate_deprecated_transport_fields`. | Configuration for connecting to remote A2A agents.
Attributes:
endpoint: A2A agent endpoint URL.
auth: Authentication scheme.
timeout: Request timeout in seconds.
max_turns: Maximum conversation turns with A2A agent.
response_model: Optional Pydantic model for structured A2A agent responses.
fa... | documentation | 0 | {"doc_type": "class", "class_name": "A2AClientConfig", "file_path": "lib/crewai/src/crewai/a2a/config.py", "repo_id": "crewAIInc/crewAI", "char_length": 874, "methods": ["_migrate_deprecated_transport_fields"]} |
ray-project/ray:python/ray/llm/tests/common/cloud/test_utils.py:TestRemoteObjectCacheDecorator.test_expiration | # Context:
import asyncio
import pytest
from ray.llm._internal.common.utils.cloud_utils import (
CloudObjectCache,
is_remote_path,
remote_object_cache,
)
class MockSyncFetcher: ...
class MockAsyncFetcher: ...
class TestCloudObjectCache: ...
class TestIsRemotePath: ...
class TestRemoteObjectCacheDecorator:... | async def test_expiration(self):
"""Test cache expiration for both missing and existing objects."""
call_count = 0
MISSING = object()
@remote_object_cache(
max_size=2,
missing_expire_seconds=1, # 1 second to expire missing object
exists_expire_second... | test | 0 | {"function_name": "test_expiration", "class_name": "TestRemoteObjectCacheDecorator", "qualname": "TestRemoteObjectCacheDecorator.test_expiration", "file_path": "python/ray/llm/tests/common/cloud/test_utils.py", "repo_id": "ray-project/ray", "loc": 41, "tested_modules": ["ray.llm._internal.common.utils.cloud_utils"], "h... |
huggingface/diffusers:src/diffusers/pipelines/qwenimage/pipeline_qwenimage_controlnet.py:license_header | Add a Apache-2.0 license header comment for the project 'diffusers', authored by Qwen-Image Team, InstantX Team and The HuggingFace Team, year 2025. | # Copyright 2025 Qwen-Image Team, InstantX Team and The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | license | 1 | {"license_type": "Apache-2.0", "author": "Qwen-Image Team, InstantX Team and The HuggingFace Team", "year": "2025", "source": "header", "repo_id": "huggingface/diffusers"} |
browser-use/browser-use:browser_use/skills/service.py:module_doc | Write a module-level docstring for the Python module `service` which contains class `SkillService`. | Skills service for fetching and executing skills from the Browser Use API | documentation | 0 | {"doc_type": "module", "module_name": "service", "file_path": "browser_use/skills/service.py", "repo_id": "browser-use/browser-use", "char_length": 73} |
infiniflow/ragflow:test/testcases/test_web_api/test_chunk_app/test_retrieval_chunks.py:TestChunksRetrieval.test_keyword | # Context:
import pytest
from common import retrieval_chunks
class TestAuthorization: ...
class TestChunksRetrieval:
def test_basic_scenarios(self, WebApiAuth, add_chunks, payload, expected_code, expected_page_size, expected_message): ...
def test_page(self, WebApiAuth, add_chunks, payload, expected_code, exp... | def test_keyword(self, WebApiAuth, add_chunks, payload, expected_code, expected_page_size, expected_message):
dataset_id, _, _ = add_chunks
payload.update({"question": "chunk test", "kb_id": [dataset_id]})
res = retrieval_chunks(WebApiAuth, payload)
assert res["code"] == expected_code, r... | test | 1 | {"function_name": "test_keyword", "class_name": "TestChunksRetrieval", "qualname": "TestChunksRetrieval.test_keyword", "file_path": "test/testcases/test_web_api/test_chunk_app/test_retrieval_chunks.py", "repo_id": "infiniflow/ragflow", "loc": 9, "tested_modules": ["concurrent.futures", "common", "configs", "libs.auth"]... |
crewAIInc/crewAI:lib/crewai-tools/tests/tools/tool_collection_test.py:TestToolCollection.test_access_by_index | # Context:
class TestToolCollection(unittest.TestCase):
def setUp(self): ...
def _create_mock_tool(self, name, description): ...
def test_initialization(self): ...
def test_empty_initialization(self): ...
def test_initialization_with_none(self): ...
def test_access_by_name(self): ...
def te... | def test_access_by_index(self):
self.assertEqual(self.tools[0], self.search_tool)
self.assertEqual(self.tools[1], self.calculator_tool)
self.assertEqual(self.tools[2], self.translator_tool) | test | 0 | {"function_name": "test_access_by_index", "class_name": "TestToolCollection", "qualname": "TestToolCollection.test_access_by_index", "file_path": "lib/crewai-tools/tests/tools/tool_collection_test.py", "repo_id": "crewAIInc/crewAI", "loc": 4, "tested_modules": ["crewai.tools", "crewai_tools.adapters.tool_collection"], ... |
browser-use/browser-use:tests/ci/test_structured_extraction.py:TestSchemaDictToPydanticModel.test_rejects_ref | # Context:
import pytest
from browser_use.tools.extraction.schema_utils import schema_dict_to_pydantic_model
class TestExtractionResult: ...
def _make_extraction_llm(structured_response: dict | None, freetext_response: str) -> BaseChatModel: ...
async def browser_session(): ...
def http_server(): ...
def base_url(http... | def test_rejects_ref(self):
schema = {
'type': 'object',
'properties': {'item': {'$ref': '#/$defs/Item'}},
'$defs': {'Item': {'type': 'object', 'properties': {'name': {'type': 'string'}}}},
}
with pytest.raises(ValueError, match='Unsupported JSON Schema keyword'):
schema_dict_to_pydantic_model(schema) | test | 0 | {"function_name": "test_rejects_ref", "class_name": "TestSchemaDictToPydanticModel", "qualname": "TestSchemaDictToPydanticModel.test_rejects_ref", "file_path": "tests/ci/test_structured_extraction.py", "repo_id": "browser-use/browser-use", "loc": 8, "tested_modules": ["pydantic", "browser_use.agent.views", "browser_use... |
ray-project/ray:ci/ray_ci/ray_image.py:RayImage.wanda_image_name | # Context:
class RayImageError(Exception): ...
class RayImage:
def __post_init__(self): ...
def arch_suffix(self) -> str: ...
def repo(self) -> str: ...
def variation_suffix(self) -> str: ...
def validate(self) -> None: ...
# Task:
Write a Python method `wanda_image_name` for the class `RayImage`... | def wanda_image_name(self) -> str:
"""Wanda output image name (without registry prefix)."""
if self.platform == "cpu":
return f"{self.image_type}-py{self.python_version}-cpu{self.arch_suffix}"
return f"{self.image_type}-py{self.python_version}-{self.platform}{self.arch_suffix}" | function_simple | 0 | {"cognitive_complexity": 1, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "wanda_image_name", "class_name": "RayImage", "qualname": "RayImage.wanda_image_name", "file_path": "ci/ray_ci/ray_image.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "class_runnable"} |
infiniflow/ragflow:common/data_source/confluence_connector.py:ConfluenceConnector._fetch_page_attachments | # Context:
import logging
from pathlib import Path
from typing import Any, cast, Iterator, Callable, Generator
from common.data_source.config import INDEX_BATCH_SIZE, DocumentSource, CONTINUE_ON_CONNECTOR_FAILURE, \
CONFLUENCE_CONNECTOR_LABELS_TO_SKIP, CONFLUENCE_TIMEZONE_OFFSET, CONFLUENCE_CONNECTOR_USER_PROFILES_... | def _fetch_page_attachments(
self,
page: dict[str, Any],
start: SecondsSinceUnixEpoch | None = None,
end: SecondsSinceUnixEpoch | None = None,
) -> tuple[list[Document], list[ConnectorFailure]]:
"""
Inline attachments are added directly to the document as text or imag... | function_complex | 1 | {"cognitive_complexity": 58, "loc": 167, "code_loc": 128, "docstring_loc": 5, "function_name": "_fetch_page_attachments", "class_name": "ConfluenceConnector", "qualname": "ConfluenceConnector._fetch_page_attachments", "file_path": "common/data_source/confluence_connector.py", "repo_id": "infiniflow/ragflow", "has_docst... |
ray-project/ray:python/ray/llm/_internal/batch/benchmark/benchmark_processor.py:_build_serve_deployment_config | # Context:
from ray.data.llm import (
ChatTemplateStageConfig,
DetokenizeStageConfig,
ServeDeploymentProcessorConfig,
TokenizerStageConfig,
build_processor,
vLLMEngineProcessorConfig,
)
from ray.serve.llm.openai_api_models import CompletionRequest
class Mode(Enum): ...
def build_vllm_engine_kwa... | def _build_serve_deployment_config(
batch_size: int,
concurrency: int,
deployment_name: str = None,
app_name: str = None,
) -> ServeDeploymentProcessorConfig:
"""Helper to create ServeDeploymentProcessorConfig."""
return ServeDeploymentProcessorConfig(
deployment_name=deployment_name,
... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 16, "code_loc": 9, "docstring_loc": 1, "function_name": "_build_serve_deployment_config", "class_name": null, "qualname": "_build_serve_deployment_config", "file_path": "python/ray/llm/_internal/batch/benchmark/benchmark_processor.py", "repo_id": "ray-project/ray", "has_docstring": tr... |
langflow-ai/langflow:src/backend/tests/unit/components/processing/test_type_converter_component.py:TestTypeConverterComponent.test_dataframe_to_data | # Context:
import pandas as pd
from lfx.schema.data import Data
from lfx.schema.dataframe import DataFrame
class TestTypeConverterComponent(ComponentTestBaseWithoutClient):
def component_class(self): ...
def file_names_mapping(self): ...
def test_message_to_message(self, component_class): ...
def test_... | def test_dataframe_to_data(self, component_class):
"""Test converting DataFrame to Data."""
df_data = pd.DataFrame({"col1": ["Hello"]})
component = component_class(input_data=DataFrame(data=df_data), output_type="Data")
result = component.convert_to_data()
assert isinstance(resul... | test | 1 | {"function_name": "test_dataframe_to_data", "class_name": "TestTypeConverterComponent", "qualname": "TestTypeConverterComponent.test_dataframe_to_data", "file_path": "src/backend/tests/unit/components/processing/test_type_converter_component.py", "repo_id": "langflow-ai/langflow", "loc": 7, "tested_modules": ["io", "lf... |
apache/airflow:providers/ssh/tests/unit/ssh/hooks/test_ssh_async.py:TestSSHHookAsync.test_parse_extras_host_key | # Context:
from unittest import mock
from airflow.providers.ssh.hooks.ssh import SSHHookAsync
class TestSSHHookAsync:
def test_init_with_conn_id(self): ...
def test_init_with_overrides(self): ...
def test_init_default_known_hosts(self): ...
def test_parse_extras_key_file(self): ...
def test_parse_e... | def test_parse_extras_host_key(self):
"""Test parsing host_key from connection extras."""
hook = SSHHookAsync(ssh_conn_id="test_conn")
mock_conn = mock.MagicMock()
mock_conn.extra_dejson = {"host_key": "ssh-rsa AAAAB3...", "no_host_key_check": "false"}
mock_conn.host = "test.host... | test | 1 | {"function_name": "test_parse_extras_host_key", "class_name": "TestSSHHookAsync", "qualname": "TestSSHHookAsync.test_parse_extras_host_key", "file_path": "providers/ssh/tests/unit/ssh/hooks/test_ssh_async.py", "repo_id": "apache/airflow", "loc": 9, "tested_modules": ["__future__", "airflow.providers.ssh.hooks.ssh"], "h... |
browser-use/browser-use:browser_use/browser/session.py:BrowserSession.get_target_id_from_tab_id | # Context:
from cdp_use.cdp.target import SessionID, TargetID
class Target(BaseModel): ...
class CDPSession(BaseModel): ...
class BrowserSession(BaseModel):
model_config = ConfigDict(
def __init__(
self,
*,
# Cloud browser params - use these for cloud mode
cloud_profile_id: UUID | str | None = None,
cl... | async def get_target_id_from_tab_id(self, tab_id: str) -> TargetID:
"""Get the full-length TargetID from the truncated 4-char tab_id using SessionManager."""
if not self.session_manager:
raise RuntimeError('SessionManager not initialized')
for full_target_id in self.session_manager.get_all_target_ids():
if... | function_complex | 0 | {"cognitive_complexity": 7, "loc": 14, "code_loc": 8, "docstring_loc": 1, "function_name": "get_target_id_from_tab_id", "class_name": "BrowserSession", "qualname": "BrowserSession.get_target_id_from_tab_id", "file_path": "browser_use/browser/session.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "run... |
crewAIInc/crewAI:lib/crewai/tests/a2a/utils/test_task.py:TestExecute.test_emits_completed_event | # Context:
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from crewai.a2a.utils.task import cancel, cancellable, execute
def mock_agent() -> MagicMock: ...
def mock_task(mock_context: MagicMock) -> MagicMock: ...
def mock_context() -> MagicMock: ...
def mock_event_queue() -> AsyncMock: ...
async d... | async def test_emits_completed_event(
self,
mock_agent: MagicMock,
mock_context: MagicMock,
mock_event_queue: AsyncMock,
mock_task: MagicMock,
) -> None:
"""Execute emits A2AServerTaskCompletedEvent on success."""
with (
patch("crewai.a2a.utils.tas... | test | 0 | {"function_name": "test_emits_completed_event", "class_name": "TestExecute", "qualname": "TestExecute.test_emits_completed_event", "file_path": "lib/crewai/tests/a2a/utils/test_task.py", "repo_id": "crewAIInc/crewAI", "loc": 20, "tested_modules": ["__future__", "typing", "a2a.server.agent_execution", "a2a.server.events... |
ray-project/ray:python/ray/data/tests/test_default_cluster_autoscaler_v2.py:TestClusterAutoscaling.test_get_node_resource_spec_and_count_from_zero | # Context:
from unittest.mock import MagicMock, patch
from ray.core.generated import autoscaler_pb2
from ray.data._internal.cluster_autoscaler.default_cluster_autoscaler_v2 import (
DefaultClusterAutoscalerV2,
_get_node_resource_spec_and_count,
_NodeResourceSpec,
)
class StubUtilizationGauge(ResourceUtiliz... | def test_get_node_resource_spec_and_count_from_zero(self):
"""Test that get_node_resource_spec_and_count can discover node types
from cluster config even when there are zero worker nodes."""
# Simulate a cluster with only head node (no worker nodes)
node_table = [
{
... | test | 0 | {"function_name": "test_get_node_resource_spec_and_count_from_zero", "class_name": "TestClusterAutoscaling", "qualname": "TestClusterAutoscaling.test_get_node_resource_spec_and_count_from_zero", "file_path": "python/ray/data/tests/test_default_cluster_autoscaler_v2.py", "repo_id": "ray-project/ray", "loc": 41, "tested_... |
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/blake2.py:Blake2b.QuickDigest | # Context:
import hashlib
from typing import Union
from ..misc import AlgoUtils
class _Blake2bWithSpecificSize(ABC): ...
class Blake2b32(_Blake2bWithSpecificSize): ...
class Blake2b40(_Blake2bWithSpecificSize): ...
class Blake2b160(_Blake2bWithSpecificSize): ...
class Blake2b224(_Blake2bWithSpecificSize): ...
class Bl... | def QuickDigest(data: Union[bytes, str],
digest_size: int,
key: Union[bytes, str] = b"",
salt: Union[bytes, str] = b"") -> bytes:
"""
Compute the digest (quick version).
Args:
data (str or bytes) : Data
... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 20, "code_loc": 4, "docstring_loc": 12, "function_name": "QuickDigest", "class_name": "Blake2b", "qualname": "Blake2b.QuickDigest", "file_path": "python/ccxt/static_dependencies/bip/utils/crypto/blake2.py", "repo_id": "ccxt/ccxt", "has_docstring": true, "runnable_level": "project_runn... |
langchain-ai/langchain:libs/partners/anthropic/tests/unit_tests/middleware/test_prompt_caching.py:TestCollectCodeExecutionToolIds.test_no_code_execution_calls | # Context:
from langchain_anthropic.chat_models import (
ChatAnthropic,
_collect_code_execution_tool_ids,
_is_code_execution_related_block,
)
class FakeToolCallingModel(BaseChatModel): ...
def test_anthropic_prompt_caching_middleware_initialization() -> None: ...
def test_anthropic_prompt_caching_middlewar... | def test_no_code_execution_calls(self) -> None:
"""Test messages without any code_execution calls."""
messages = [
{
"role": "user",
"content": [{"type": "text", "text": "Hello"}],
},
{
"role": "assistant",
... | test | 1 | {"function_name": "test_no_code_execution_calls", "class_name": "TestCollectCodeExecutionToolIds", "qualname": "TestCollectCodeExecutionToolIds.test_no_code_execution_calls", "file_path": "libs/partners/anthropic/tests/unit_tests/middleware/test_prompt_caching.py", "repo_id": "langchain-ai/langchain", "loc": 21, "teste... |
ray-project/ray:rllib/examples/envs/classes/multi_agent/footsies/test/footsies_suppress_unity_logs.py:TestFootsies.test_default_supress_output_mode | # Context:
import os
import time
from pathlib import Path
def _create_env(config_overrides): ...
def capture_stdout_stderr(): ...
class TestFootsies(unittest.TestCase):
def test_enable_output_mode(self): ...
# Task:
Write a Python test method `test_default_supress_output_mode` in test class `TestFootsies` to ver... | def test_default_supress_output_mode(self):
with capture_stdout_stderr() as log_path:
env = _create_env({})
time.sleep(2) # Give Unity time to write output
env.close()
# Give a bit more time for any buffered output to be written
time.sleep(0.5)
... | test | 0 | {"function_name": "test_default_supress_output_mode", "class_name": "TestFootsies", "qualname": "TestFootsies.test_default_supress_output_mode", "file_path": "rllib/examples/envs/classes/multi_agent/footsies/test/footsies_suppress_unity_logs.py", "repo_id": "ray-project/ray", "loc": 21, "tested_modules": ["contextlib",... |
huggingface/diffusers:src/diffusers/pipelines/hunyuan_video1_5/pipeline_hunyuan_video1_5_image2video.py:HunyuanVideo15ImageToVideoPipeline.prepare_cond_latents_and_mask | # Context:
import PIL
import torch
def format_text_input(prompt: list[str], system_message: str) -> list[dict[str, Any]]: ...
def extract_glyph_texts(prompt: str) -> list[str]: ...
def retrieve_latents(encoder_output: torch.Tensor, generator: torch.Generator | None, sample_mode: str): ...
def retrieve_timesteps(schedu... | def prepare_cond_latents_and_mask(
self,
latents: torch.Tensor,
image: PIL.Image.Image,
batch_size: int,
height: int,
width: int,
dtype: torch.dtype,
device: torch.device,
):
"""
Prepare conditional latents and mask for t2v generation.
... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 39, "code_loc": 15, "docstring_loc": 9, "function_name": "prepare_cond_latents_and_mask", "class_name": "HunyuanVideo15ImageToVideoPipeline", "qualname": "HunyuanVideo15ImageToVideoPipeline.prepare_cond_latents_and_mask", "file_path": "src/diffusers/pipelines/hunyuan_video1_5/pipeline... |
vllm-project/vllm:vllm/model_executor/layers/quantization/utils/nvfp4_utils.py:prepare_weights_for_nvfp4_flashinfer_trtllm | # Context:
import torch
from flashinfer import shuffle_matrix_a, shuffle_matrix_sf_a
class NvFp4LinearBackend(Enum): ...
def select_nvfp4_linear_backend() -> NvFp4LinearBackend: ...
def prepare_weights_for_nvfp4_cutlass(weight: torch.Tensor, weight_scale: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, int]: ...
de... | def prepare_weights_for_nvfp4_flashinfer_trtllm(
weight: torch.Tensor,
weight_scale: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Prepare weights and scales for FlashInfer TRTLLM FP4 GEMM."""
from flashinfer import shuffle_matrix_a, shuffle_matrix_sf_a
epilogue_tile_m = 128
shuffled... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 16, "code_loc": 9, "docstring_loc": 1, "function_name": "prepare_weights_for_nvfp4_flashinfer_trtllm", "class_name": null, "qualname": "prepare_weights_for_nvfp4_flashinfer_trtllm", "file_path": "vllm/model_executor/layers/quantization/utils/nvfp4_utils.py", "repo_id": "vllm-project/v... |
ray-project/ray:python/ray/data/_internal/execution/operators/hash_shuffle.py:ShuffleAggregation.is_compacting | Write a Python method `is_compacting` for the class `ShuffleAggregation` to returns whether this aggregation is capable of compacting partial. | def is_compacting(cls):
"""Returns whether this aggregation is capable of compacting partial
partition's shards list.
"""
return False | function_simple | 0 | {"cognitive_complexity": 0, "loc": 5, "code_loc": 1, "docstring_loc": 3, "function_name": "is_compacting", "class_name": "ShuffleAggregation", "qualname": "ShuffleAggregation.is_compacting", "file_path": "python/ray/data/_internal/execution/operators/hash_shuffle.py", "repo_id": "ray-project/ray", "has_docstring": true... |
vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/offloading_connector.py:OffloadingConnectorScheduler.request_finished | # Context:
from typing import Any
from vllm.v1.request import Request
class OffloadingOperationMetrics: ...
class OffloadingConnectorStats(KVConnectorStats): ...
class OffloadingConnectorMetadata(KVConnectorMetadata): ...
class OffloadingConnector(KVConnectorBase_V1): ...
class OffloadingConnectorWorker: ...
class Off... | def request_finished(
self,
request: Request,
block_ids: list[int],
) -> tuple[bool, dict[str, Any] | None]:
"""
Called when a request has finished, before its blocks are freed.
Returns:
True if the request is being saved/sent asynchronously and blocks
... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 22, "code_loc": 6, "docstring_loc": 10, "function_name": "request_finished", "class_name": "OffloadingConnectorScheduler", "qualname": "OffloadingConnectorScheduler.request_finished", "file_path": "vllm/distributed/kv_transfer/kv_connector/v1/offloading_connector.py", "repo_id": "vllm... |
apache/airflow:providers/redis/tests/unit/redis/triggers/test_redis_await_message.py:TestAwaitMessageTrigger.test_trigger_serialization | # Context:
from airflow.providers.redis.triggers.redis_await_message import AwaitMessageTrigger
class TestAwaitMessageTrigger:
async def test_trigger_run_succeed(self, mock_redis_conn): ...
async def test_trigger_run_succeed_with_bytes(self, mock_redis_conn): ...
async def test_trigger_run_fail(self, mock_... | def test_trigger_serialization(self):
trigger = AwaitMessageTrigger(
channels=["test_channel"],
redis_conn_id="redis_default",
poll_interval=30,
)
assert isinstance(trigger, AwaitMessageTrigger)
classpath, kwargs = trigger.serialize()
assert... | test | 1 | {"function_name": "test_trigger_serialization", "class_name": "TestAwaitMessageTrigger", "qualname": "TestAwaitMessageTrigger.test_trigger_serialization", "file_path": "providers/redis/tests/unit/redis/triggers/test_redis_await_message.py", "repo_id": "apache/airflow", "loc": 17, "tested_modules": ["__future__", "airfl... |
infiniflow/ragflow:common/data_source/utils.py:make_paginated_slack_api_call | # Context:
from collections.abc import Callable, Generator, Iterator, Mapping, Sequence
from typing import IO, Any, Generic, Iterable, Optional, Protocol, TypeVar, cast
from slack_sdk.web import SlackResponse
def datetime_from_string(datetime_string: str) -> datetime: ...
def is_valid_image_type(mime_type: str) -> boo... | def make_paginated_slack_api_call(call: Callable[..., SlackResponse], **kwargs: Any) -> Generator[dict[str, Any], None, None]:
"""Make paginated Slack API call"""
return _make_slack_api_call_paginated(call)(**kwargs) | function_simple | 1 | {"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "make_paginated_slack_api_call", "class_name": null, "qualname": "make_paginated_slack_api_call", "file_path": "common/data_source/utils.py", "repo_id": "infiniflow/ragflow", "has_docstring": true, "runnable_level": "project_runna... |
ray-project/ray:python/ray/llm/tests/batch/gpu/stages/test_serve_deployment_stage.py:test_serve_deployment_invalid_method | # Context:
import pytest
from ray.llm._internal.batch.stages.serve_deployment_stage import (
ServeDeploymentStageUDF,
)
from ray.serve.llm.openai_api_models import ChatCompletionRequest, CompletionRequest
def mock_serve_deployment_handle(): ...
async def test_serve_deployment_udf_methods(mock_serve_deployment_hand... | async def test_serve_deployment_invalid_method(mock_serve_deployment_handle):
"""Test that invalid method raises error at runtime."""
# Set up the mock to simulate a method that doesn't exist
mock_serve_deployment_handle.invalid_method = None
udf = ServeDeploymentStageUDF(
data_column="__data",... | test | 0 | {"function_name": "test_serve_deployment_invalid_method", "class_name": null, "qualname": "test_serve_deployment_invalid_method", "file_path": "python/ray/llm/tests/batch/gpu/stages/test_serve_deployment_stage.py", "repo_id": "ray-project/ray", "loc": 30, "tested_modules": ["ray.exceptions", "ray.llm._internal.batch.st... |
ray-project/ray:python/ray/data/util/data_batch_conversion.py:_unwrap_ndarray_object_type_if_needed | # Context:
import numpy as np
def _lazy_import_pandas(): ...
class BatchFormat(str, Enum): ...
def _convert_batch_type_to_pandas(data: DataBatchType, cast_tensor_columns: bool) -> 'pd.DataFrame': ...
def _convert_pandas_to_batch_type(data: 'pd.DataFrame', type: BatchFormat, cast_tensor_columns: bool) -> DataBatchType:... | def _unwrap_ndarray_object_type_if_needed(arr: np.ndarray) -> np.ndarray:
"""Unwrap an object-dtyped NumPy ndarray containing ndarray pointers into a single
contiguous ndarray, if needed/possible.
"""
if arr.dtype.type is np.object_:
try:
# Try to convert the NumPy ndarray to a non-o... | function_simple | 0 | {"cognitive_complexity": 2, "loc": 12, "code_loc": 6, "docstring_loc": 3, "function_name": "_unwrap_ndarray_object_type_if_needed", "class_name": null, "qualname": "_unwrap_ndarray_object_type_if_needed", "file_path": "python/ray/data/util/data_batch_conversion.py", "repo_id": "ray-project/ray", "has_docstring": true, ... |
huggingface/transformers:src/transformers/masking_utils.py:sliding_window_causal_mask_function | # Context:
from collections.abc import Callable
def and_masks(*mask_functions) -> Callable: ...
def or_masks(*mask_functions) -> Callable: ...
def causal_mask_function(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: ...
def bidirectional_mask_function(batch_idx: int, head_idx: int, q_idx: int, kv_idx:... | def sliding_window_causal_mask_function(sliding_window: int) -> Callable:
"""
This return the mask_function function to create a sliding window mask.
"""
return and_masks(sliding_window_overlay(sliding_window), causal_mask_function) | function_simple | 0 | {"cognitive_complexity": 0, "loc": 5, "code_loc": 1, "docstring_loc": 3, "function_name": "sliding_window_causal_mask_function", "class_name": null, "qualname": "sliding_window_causal_mask_function", "file_path": "src/transformers/masking_utils.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnabl... |
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/serper_dev_tool/serper_dev_tool.py:SerperDevTool._make_api_request | # Context:
import json
import os
from typing import Any, TypedDict
import requests
class KnowledgeGraph(TypedDict): ...
class Sitelink(TypedDict): ...
class OrganicResult(TypedDict): ...
class PeopleAlsoAskResult(TypedDict): ...
class RelatedSearchResult(TypedDict): ...
class NewsResult(TypedDict): ...
class SearchPar... | def _make_api_request(self, search_query: str, search_type: str) -> dict[str, Any]:
"""Make API request to Serper."""
search_url = self._get_search_url(search_type)
payload = {"q": search_query, "num": self.n_results}
if self.country != "":
payload["gl"] = self.country
... | function_complex | 0 | {"cognitive_complexity": 14, "loc": 45, "code_loc": 40, "docstring_loc": 1, "function_name": "_make_api_request", "class_name": "SerperDevTool", "qualname": "SerperDevTool._make_api_request", "file_path": "lib/crewai-tools/src/crewai_tools/tools/serper_dev_tool/serper_dev_tool.py", "repo_id": "crewAIInc/crewAI", "has_d... |
ray-project/ray:ci/ray_ci/test_ray_image.py:TestValidateInvalid.test_invalid_platform_for_ray_llm | # Context:
import pytest
from ci.ray_ci.ray_image import IMAGE_TYPE_CONFIG, RayImage, RayImageError
class TestWandaImageName: ...
class TestArchSuffix: ...
class TestRepo: ...
class TestVariationSuffix: ...
class TestValidateValid: ...
class TestImageTypeConfig: ...
class TestValidateInvalid:
def test_unknown_ima... | def test_invalid_platform_for_ray_llm(self):
with pytest.raises(RayImageError, match="Invalid platform cpu for ray-llm"):
RayImage("ray-llm", "3.11", "cpu").validate() | test | 0 | {"function_name": "test_invalid_platform_for_ray_llm", "class_name": "TestValidateInvalid", "qualname": "TestValidateInvalid.test_invalid_platform_for_ray_llm", "file_path": "ci/ray_ci/test_ray_image.py", "repo_id": "ray-project/ray", "loc": 3, "tested_modules": ["ci.ray_ci.configs", "ci.ray_ci.docker_container", "ci.r... |
huggingface/transformers:tests/models/vaultgemma/test_modeling_vaultgemma.py:VaultGemmaIntegrationTest.test_export_static_cache | # Context:
import pytest
from packaging import version
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
DynamicCache,
is_torch_available,
pipeline,
)
from transformers.generation.configuration_utils import GenerationConfig
from transformers.testing_utils import (
Expectations,
... | def test_export_static_cache(self):
if version.parse(torch.__version__) < version.parse("2.5.0"):
self.skipTest(reason="This test requires torch >= 2.5 to run.")
from transformers.integrations.executorch import (
TorchExportableModuleWithStaticCache,
)
model_id ... | test | 0 | {"function_name": "test_export_static_cache", "class_name": "VaultGemmaIntegrationTest", "qualname": "VaultGemmaIntegrationTest.test_export_static_cache", "file_path": "tests/models/vaultgemma/test_modeling_vaultgemma.py", "repo_id": "huggingface/transformers", "loc": 60, "tested_modules": ["packaging", "parameterized"... |
vllm-project/vllm:vllm/model_executor/models/molmo2.py:Molmo2VisionBlock:class_doc | Write a class-level docstring for `Molmo2VisionBlock` (inherits from nn.Module) which has methods: `__init__`, `forward`. | Residual attention block used in Vision Transformer. | documentation | 1 | {"doc_type": "class", "class_name": "Molmo2VisionBlock", "file_path": "vllm/model_executor/models/molmo2.py", "repo_id": "vllm-project/vllm", "char_length": 52, "methods": ["__init__", "forward"]} |
ray-project/ray:release/train_tests/benchmark/runner.py:TrainLoopRunner._train_epoch | # Context:
import pprint
class VanillaTorchRunner(TrainLoopRunner): ...
class TrainLoopRunner:
def __init__(self, factory: BenchmarkFactory):
self.factory = factory
self.benchmark_config = factory.benchmark_config
self._setup()
# Training progress state.
self._train_batch... | def _train_epoch(self):
"""Subclasses can override the entrire `_train_epoch` method for more training
logic customization."""
if ray.train.get_context().get_world_rank() == 0:
logger.info(f"Training starting @ epoch={self._train_epoch_idx}")
train_dataloader = self.factory.... | function_complex | 0 | {"cognitive_complexity": 16, "loc": 46, "code_loc": 30, "docstring_loc": 2, "function_name": "_train_epoch", "class_name": "TrainLoopRunner", "qualname": "TrainLoopRunner._train_epoch", "file_path": "release/train_tests/benchmark/runner.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "file_r... |
666ghj/BettaFish:MediaEngine/state/state.py:State.save_to_file | # Context:
class Search: ...
class Research: ...
class Paragraph: ...
class State:
def add_paragraph(self, title: str, content: str) -> int: ...
def get_paragraph(self, index: int) -> Optional[Paragraph]: ...
def get_completed_paragraphs_count(self) -> int: ...
def get_total_paragraphs_count(self) -> ... | def save_to_file(self, filepath: str):
"""保存状态到文件"""
with open(filepath, 'w', encoding='utf-8') as f:
f.write(self.to_json()) | function_simple | 1 | {"cognitive_complexity": 0, "loc": 4, "code_loc": 2, "docstring_loc": 1, "function_name": "save_to_file", "class_name": "State", "qualname": "State.save_to_file", "file_path": "MediaEngine/state/state.py", "repo_id": "666ghj/BettaFish", "has_docstring": true, "runnable_level": "class_runnable"} |
langflow-ai/langflow:src/backend/tests/unit/utils/test_mcp_cleanup.py:TestTryTerminateMcpProcess.test_terminates_mcp_proxy_process | # 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_terminates_mcp_proxy_process(self):
"""Test termination of mcp-proxy process."""
mock_psutil = MagicMock()
mock_psutil.NoSuchProcess = Exception
mock_psutil.AccessDenied = Exception
mock_psutil.ZombieProcess = Exception
mock_psutil.TimeoutExpired = Exceptio... | test | 1 | {"function_name": "test_terminates_mcp_proxy_process", "class_name": "TestTryTerminateMcpProcess", "qualname": "TestTryTerminateMcpProcess.test_terminates_mcp_proxy_process", "file_path": "src/backend/tests/unit/utils/test_mcp_cleanup.py", "repo_id": "langflow-ai/langflow", "loc": 17, "tested_modules": ["langflow.utils... |
crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/anthropic/completion.py:AnthropicCompletion.call | # Context:
import logging
from typing import TYPE_CHECKING, Any, Final, Literal, TypeGuard, cast
from pydantic import BaseModel
from crewai.llms.base_llm import BaseLLM, llm_call_context
from crewai.utilities.types import LLMMessage
def _supports_native_structured_outputs(model: str) -> bool: ...
def _is_pydantic_mode... | def call(
self,
messages: str | list[LLMMessage],
tools: list[dict[str, Any]] | None = None,
callbacks: list[Any] | None = None,
available_functions: dict[str, Any] | None = None,
from_task: Any | None = None,
from_agent: Any | None = None,
response_model:... | function_complex | 0 | {"cognitive_complexity": 8, "loc": 77, "code_loc": 43, "docstring_loc": 13, "function_name": "call", "class_name": "AnthropicCompletion", "qualname": "AnthropicCompletion.call", "file_path": "lib/crewai/src/crewai/llms/providers/anthropic/completion.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_l... |
ray-project/ray:doc/source/ray-overview/examples/e2e-timeseries/e2e_timeseries/model.py:DLinear.forward | # Context:
import torch
class moving_avg(nn.Module): ...
class series_decomp(nn.Module): ...
class DLinear(nn.Module):
def __init__(self, configs: Dict[str, Any]):
super().__init__()
self.seq_len: int = configs["seq_len"]
self.pred_len: int = configs["pred_len"]
self.decompsition ... | def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass for the DLinear model.
Args:
x (torch.Tensor): Input tensor. Can be 2D [Batch, SeqLen] (interpreted as 1 channel)
or 3D [Batch, SeqLen, Channels].
Returns:
torch.T... | function_simple | 0 | {"cognitive_complexity": 4, "loc": 46, "code_loc": 26, "docstring_loc": 10, "function_name": "forward", "class_name": "DLinear", "qualname": "DLinear.forward", "file_path": "doc/source/ray-overview/examples/e2e-timeseries/e2e_timeseries/model.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "... |
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/hyperbrowser_load_tool/hyperbrowser_load_tool.py:HyperbrowserLoadTool:class_doc | Write a class-level docstring for `HyperbrowserLoadTool` (inherits from BaseTool) which has methods: `__init__`, `_prepare_params`, `_extract_content`, `_run`. | HyperbrowserLoadTool.
Scrape or crawl web pages and load the contents with optional parameters for configuring content extraction.
Requires the `hyperbrowser` package.
Get your API Key from https://app.hyperbrowser.ai/
Args:
api_key: The Hyperbrowser API key, can be set as an environment variable `HYPERBROWSER_AP... | documentation | 0 | {"doc_type": "class", "class_name": "HyperbrowserLoadTool", "file_path": "lib/crewai-tools/src/crewai_tools/tools/hyperbrowser_load_tool/hyperbrowser_load_tool.py", "repo_id": "crewAIInc/crewAI", "char_length": 345, "methods": ["__init__", "_prepare_params", "_extract_content", "_run"]} |
ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/llm/vllm/kv_transfer_backends/test_registry.py:TestComponentRegistry.test_register_and_get_direct_class | # Context:
from ray.llm._internal.serve.utils.registry import ComponentRegistry, get_registry
class TestComponentRegistry:
def test_register_and_get_module_path(self): ...
def test_get_nonexistent_component_raises(self): ...
def test_invalid_string_format_raises(self): ...
def test_double_registration_... | def test_register_and_get_direct_class(self):
"""Test registering and retrieving a class directly."""
registry = ComponentRegistry("test_category")
test_class = type("TestClass", (), {})
registry.register("test_component", test_class)
assert registry.contains("test_component")
... | test | 0 | {"function_name": "test_register_and_get_direct_class", "class_name": "TestComponentRegistry", "qualname": "TestComponentRegistry.test_register_and_get_direct_class", "file_path": "python/ray/llm/tests/serve/cpu/deployments/llm/vllm/kv_transfer_backends/test_registry.py", "repo_id": "ray-project/ray", "loc": 9, "tested... |
scrapy/scrapy:tests/test_downloader_handlers_http_base.py:TestHttpBase.test_timeout_download_from_spider_nodata_rcvd | # Context:
import sys
import pytest
from scrapy.exceptions import (
CannotResolveHostError,
DownloadCancelledError,
DownloadConnectionRefusedError,
DownloadFailedError,
DownloadTimeoutError,
ResponseDataLossError,
StopDownload,
UnsupportedURLSchemeError,
)
from scrapy.http import Headers... | async def test_timeout_download_from_spider_nodata_rcvd(
self, mockserver: MockServer, reactor_pytest: str
) -> None:
if reactor_pytest == "asyncio" and sys.platform == "win32":
# https://twistedmatrix.com/trac/ticket/10279
pytest.skip(
"This test produces Dir... | test | 1 | {"function_name": "test_timeout_download_from_spider_nodata_rcvd", "class_name": "TestHttpBase", "qualname": "TestHttpBase.test_timeout_download_from_spider_nodata_rcvd", "file_path": "tests/test_downloader_handlers_http_base.py", "repo_id": "scrapy/scrapy", "loc": 16, "tested_modules": ["__future__", "abc", "contextli... |
vllm-project/vllm:benchmarks/benchmark_topk_topp.py:print_summary_table | # Context:
class BenchmarkConfig: ...
def calculate_ops_pct(k_values: torch.Tensor | None, p_values: torch.Tensor | None, vocab_size: int, batch_size: int) -> float: ...
def create_logits(batch_size: int, vocab_size: int, device: str) -> torch.Tensor: ...
def measure_memory() -> tuple[int, int]: ...
def reset_memory_s... | def print_summary_table(results: list[dict]):
"""Print a summary table of results."""
print()
print("=" * 130)
print("SUMMARY TABLE")
print("=" * 130)
print()
# Header
header = (
f"{'Scenario':<40} {'Batch':>6} {'Vocab':>7} {'Ops%':>6} "
f"{'Triton (ms)':>12} {'PyTorch (... | function_complex | 1 | {"cognitive_complexity": 6, "loc": 39, "code_loc": 29, "docstring_loc": 1, "function_name": "print_summary_table", "class_name": null, "qualname": "print_summary_table", "file_path": "benchmarks/benchmark_topk_topp.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "file_runnable"} |
browser-use/browser-use:tests/ci/test_action_loop_detection.py:test_detector_window_slides | # Context:
from browser_use.agent.views import (
ActionLoopDetector,
PageFingerprint,
compute_action_hash,
)
def _get_context_messages(agent: Agent) -> list[str]: ...
def test_search_normalization_ignores_keyword_order(): ...
def test_search_normalization_ignores_case(): ...
def test_search_normalization_ignores_pu... | def test_detector_window_slides():
"""Old actions fall out of the window."""
detector = ActionLoopDetector(window_size=10)
# Fill window with repeated actions
for _ in range(5):
detector.record_action('click', {'index': 7})
assert detector.max_repetition_count == 5
# Push them out with diverse actions
for i i... | test | 0 | {"function_name": "test_detector_window_slides", "class_name": null, "qualname": "test_detector_window_slides", "file_path": "tests/ci/test_action_loop_detection.py", "repo_id": "browser-use/browser-use", "loc": 14, "tested_modules": ["browser_use.agent.service", "browser_use.agent.views", "browser_use.llm.messages", "... |
docling-project/docling:docling/models/inference_engines/vlm/api_openai_compatible_engine.py:ApiVlmEngine.cleanup | # Context:
class ApiVlmEngine(BaseVlmEngine):
def __init__(
self,
enable_remote_services: bool,
options: ApiVlmEngineOptions,
model_config: Optional["EngineModelConfig"] = None,
):
"""Initialize the API engine.
Args:
options: API-specific runtime opt... | def cleanup(self) -> None:
"""Clean up API runtime resources.
For API runtimes, there's nothing to clean up.
"""
_log.info("API runtime cleaned up") | function_simple | 1 | {"cognitive_complexity": 0, "loc": 6, "code_loc": 1, "docstring_loc": 4, "function_name": "cleanup", "class_name": "ApiVlmEngine", "qualname": "ApiVlmEngine.cleanup", "file_path": "docling/models/inference_engines/vlm/api_openai_compatible_engine.py", "repo_id": "docling-project/docling", "has_docstring": true, "runnab... |
crewAIInc/crewAI:lib/crewai-files/tests/test_file_url.py:TestFileUrl.test_invalid_url_scheme_raises | # Context:
from crewai_files import FileBytes, FileUrl, ImageFile
import pytest
class TestNormalizeSource: ...
class TestResolverUrlHandling: ...
class TestImageFileWithUrl: ...
class TestFileUrl:
def test_create_file_url(self): ...
def test_create_file_url_with_filename(self): ...
def test_invalid_url_sc... | def test_invalid_url_scheme_raises(self):
"""Test that non-http(s) URLs raise ValueError."""
with pytest.raises(ValueError, match="Invalid URL scheme"):
FileUrl(url="ftp://example.com/file.txt") | test | 0 | {"function_name": "test_invalid_url_scheme_raises", "class_name": "TestFileUrl", "qualname": "TestFileUrl.test_invalid_url_scheme_raises", "file_path": "lib/crewai-files/tests/test_file_url.py", "repo_id": "crewAIInc/crewAI", "loc": 4, "tested_modules": ["crewai_files", "crewai_files.core.resolved", "crewai_files.core.... |
ray-project/ray:python/ray/tests/test_tpu.py:test_get_current_node_labels_env_only | # Context:
from ray._private.accelerators import TPUAcceleratorManager, tpu
def test_get_current_pod_name_smoke(): ...
def test_empty_get_current_pod_name_returns_none(): ...
def test_worker_count(mock_glob, test_case): ...
def test_num_tpu_chips(mock_glob): ...
def test_is_valid_tpu_accelerator_topology(_mock_glob, t... | def test_get_current_node_labels_env_only(monkeypatch):
# Simulate GKE TPU environment variables
monkeypatch.setenv("TPU_NAME", "tpu-worker-group-2")
monkeypatch.setenv("TPU_WORKER_ID", "0")
monkeypatch.setenv("TPU_ACCELERATOR_TYPE", "v6e-16")
monkeypatch.setenv("TPU_TOPOLOGY", "4x4")
tpu_label... | test | 0 | {"function_name": "test_get_current_node_labels_env_only", "class_name": null, "qualname": "test_get_current_node_labels_env_only", "file_path": "python/ray/tests/test_tpu.py", "repo_id": "ray-project/ray", "loc": 13, "tested_modules": ["ray._private.accelerators", "ray.util.tpu"], "has_docstring": false, "runnable_lev... |
huggingface/transformers:tests/models/ernie4_5_vl_moe/test_modeling_ernie4_5_vl_moe.py:Ernie4_5_VLMoeIntegrationTest.test_small_model_integration_test_batch_wo_image | # Context:
from transformers.testing_utils import (
Expectations,
cleanup,
require_deterministic_for_xpu,
require_torch,
require_torch_large_accelerator,
slow,
torch_device,
)
import torch
class Ernie4_5_VLMoeVisionText2TextModelTester: ...
class Ernie4_5_VLMoeModelTest(ModelTesterMixin, Ge... | def test_small_model_integration_test_batch_wo_image(self):
model = self.load_model("auto")
message_wo_image = [
{"role": "user", "content": [{"type": "text", "text": "Who are you?"}]},
]
batched_messages = [self.message, message_wo_image]
inputs = self.processor.appl... | test | 0 | {"function_name": "test_small_model_integration_test_batch_wo_image", "class_name": "Ernie4_5_VLMoeIntegrationTest", "qualname": "Ernie4_5_VLMoeIntegrationTest.test_small_model_integration_test_batch_wo_image", "file_path": "tests/models/ernie4_5_vl_moe/test_modeling_ernie4_5_vl_moe.py", "repo_id": "huggingface/transfo... |
huggingface/diffusers:src/diffusers/pipelines/ltx/pipeline_ltx_i2v_long_multi_prompt.py:linear_overlap_fuse | # Context:
import torch
def get_latent_coords(latent_num_frames, latent_height, latent_width, batch_size, device, rope_interpolation_scale, latent_idx): ...
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale): ...
def adain_normalize_latents(curr_latents: torch.Tensor, ref_latents: torch.Tensor | None,... | def linear_overlap_fuse(prev: torch.Tensor, new: torch.Tensor, overlap: int) -> torch.Tensor:
"""
Temporal linear crossfade between two latent clips over the overlap region.
Args:
prev: Tensor [B, C, F, H, W]. Previous output segment.
new: Tensor [B, C, F, H, W]. New segment to be appended.
... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 20, "code_loc": 8, "docstring_loc": 11, "function_name": "linear_overlap_fuse", "class_name": null, "qualname": "linear_overlap_fuse", "file_path": "src/diffusers/pipelines/ltx/pipeline_ltx_i2v_long_multi_prompt.py", "repo_id": "huggingface/diffusers", "has_docstring": true, "runnable... |
crewAIInc/crewAI:lib/crewai/tests/telemetry/test_execution_span_assignment.py:test_end_crew_receives_valid_execution_span | # Context:
import pytest
from crewai import Agent, Crew, Task
def cleanup_singletons(): ...
def test_crew_execution_span_assigned_on_kickoff(): ...
def test_crew_execution_span_not_set_when_share_crew_false(): ...
async def test_crew_execution_span_assigned_on_kickoff_async(): ...
def test_crew_execution_span_assigned... | def test_end_crew_receives_valid_execution_span():
"""Test that end_crew receives a valid execution span to close.
This verifies the complete lifecycle: span creation, assignment, and closure
without errors when end_crew() accesses crew._execution_span.
"""
agent = Agent(
role="test agent",... | test | 0 | {"function_name": "test_end_crew_receives_valid_execution_span", "class_name": null, "qualname": "test_end_crew_receives_valid_execution_span", "file_path": "lib/crewai/tests/telemetry/test_execution_span_assignment.py", "repo_id": "crewAIInc/crewAI", "loc": 27, "tested_modules": ["crewai", "crewai.events.event_bus", "... |
langflow-ai/langflow:src/backend/tests/unit/components/models_and_agents/test_conversation_context_ordering.py:TestALTKAgentContextOrdering.test_conversation_context_empty_history | # Context:
from lfx.base.agents.altk_base_agent import ALTKBaseAgentComponent
from lfx.schema.message import Message
class TestALTKAgentContextOrdering:
def test_conversation_context_chronological_order(self): ...
def test_conversation_context_no_current_input(self): ...
def test_conversation_context_singl... | def test_conversation_context_empty_history(self):
"""Test conversation context with empty chat history."""
current_input = Message(text="hello", sender="User", sender_name="User")
class TestAgent(ALTKBaseAgentComponent):
def __init__(self):
self.input_value = curren... | test | 1 | {"function_name": "test_conversation_context_empty_history", "class_name": "TestALTKAgentContextOrdering", "qualname": "TestALTKAgentContextOrdering.test_conversation_context_empty_history", "file_path": "src/backend/tests/unit/components/models_and_agents/test_conversation_context_ordering.py", "repo_id": "langflow-ai... |
huggingface/diffusers:src/diffusers/modular_pipelines/qwenimage/modular_pipeline.py:QwenImageEditModularPipeline:class_doc | Write a class-level docstring for `QwenImageEditModularPipeline` (inherits from ModularPipeline, QwenImageLoraLoaderMixin) which has methods: `default_height`, `default_width`, `default_sample_size`, `vae_scale_factor`, `num_channels_latents`. | A ModularPipeline for QwenImage-Edit.
> [!WARNING] > This is an experimental feature and is likely to change in the future. | documentation | 1 | {"doc_type": "class", "class_name": "QwenImageEditModularPipeline", "file_path": "src/diffusers/modular_pipelines/qwenimage/modular_pipeline.py", "repo_id": "huggingface/diffusers", "char_length": 124, "methods": ["default_height", "default_width", "default_sample_size", "vae_scale_factor", "num_channels_latents", "is_... |
ray-project/ray:release/nightly_tests/dataset/training_ingest_benchmark.py:S3ParquetDataLoader.create_dataset | # Context:
import io
from typing import Dict, List, Optional
import ray
from PIL import Image
class BenchmarkConfig: ...
class BaseDataLoader(ABC): ...
class S3UrlImageDataLoader(BaseDataLoader): ...
class S3ReadImagesDataLoader(BaseDataLoader): ...
def create_data_loader(data_loader: str, split: str) -> BaseDataLoade... | def create_dataset(
self,
transform_type: str,
batch_size: int,
num_batches: int,
num_image_columns: int,
) -> ray.data.Dataset:
"""Create dataset by applying map to the cached base dataset."""
limit = self.compute_limit(batch_size, num_batches)
transf... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 22, "code_loc": 10, "docstring_loc": 1, "function_name": "create_dataset", "class_name": "S3ParquetDataLoader", "qualname": "S3ParquetDataLoader.create_dataset", "file_path": "release/nightly_tests/dataset/training_ingest_benchmark.py", "repo_id": "ray-project/ray", "has_docstring": t... |
crewAIInc/crewAI:lib/crewai-files/src/crewai_files/core/types.py:BaseFile.filename | # Context:
class _FileSourceCoercer: ...
class ImageFile(BaseFile): ...
class PDFFile(BaseFile): ...
class TextFile(BaseFile): ...
class AudioFile(BaseFile): ...
class VideoFile(BaseFile): ...
class File(BaseFile): ...
class BaseFile(ABC, BaseModel):
def _file_source(self) -> FileSource: ...
def content_type(... | def filename(self) -> str | None:
"""Get the filename from the source."""
return self._file_source.filename | function_simple | 0 | {"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "filename", "class_name": "BaseFile", "qualname": "BaseFile.filename", "file_path": "lib/crewai-files/src/crewai_files/core/types.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_level": "class_runnable"} |
zhayujie/chatgpt-on-wechat:agent/skills/frontmatter.py:parse_frontmatter | # Context:
import re
import json
from typing import Dict, Any, Optional, List
import yaml
def parse_metadata(frontmatter: Dict[str, Any]) -> Optional[SkillMetadata]: ...
def _normalize_string_list(value: Any) -> List[str]: ...
def parse_boolean_value(value: Optional[str], default: bool) -> bool: ...
def get_frontmatte... | def parse_frontmatter(content: str) -> Dict[str, Any]:
"""
Parse YAML-style frontmatter from markdown content.
Returns a dictionary of frontmatter fields.
"""
frontmatter = {}
# Match frontmatter block between --- markers
match = re.match(r'^---\s*\n(.*?)\n---\s*\n', content, re.DO... | function_complex | 1 | {"cognitive_complexity": 18, "loc": 57, "code_loc": 34, "docstring_loc": 5, "function_name": "parse_frontmatter", "class_name": null, "qualname": "parse_frontmatter", "file_path": "agent/skills/frontmatter.py", "repo_id": "zhayujie/chatgpt-on-wechat", "has_docstring": true, "runnable_level": "plib_runnable"} |
unclecode/crawl4ai:tests/adaptive/test_embedding_strategy.py:module_doc | Write a module-level docstring for the Python module `test_embedding_strategy` which contains various utilities. | Test and demo script for Embedding-based Adaptive Crawler
This script demonstrates the embedding-based adaptive crawling
with semantic space coverage and gap-driven expansion. | documentation | 1 | {"doc_type": "module", "module_name": "test_embedding_strategy", "file_path": "tests/adaptive/test_embedding_strategy.py", "repo_id": "unclecode/crawl4ai", "char_length": 176} |
run-llama/llama_index:llama-index-instrumentation/src/llama_index_instrumentation/events/span.py:SpanDropEvent:class_doc | Write a class-level docstring for `SpanDropEvent` (inherits from BaseEvent) which has methods: `class_name`. | SpanDropEvent.
Args:
err_str (str): Error string. | documentation | 1 | {"doc_type": "class", "class_name": "SpanDropEvent", "file_path": "llama-index-instrumentation/src/llama_index_instrumentation/events/span.py", "repo_id": "run-llama/llama_index", "char_length": 54, "methods": ["class_name"]} |
infiniflow/ragflow:test/testcases/test_web_api/test_dialog_app/test_dialog_edge_cases.py:TestDialogEdgeCases.test_concurrent_dialog_operations | # Context:
import pytest
from common import create_dialog, delete_dialog, get_dialog, update_dialog
from concurrent.futures import ThreadPoolExecutor, as_completed
class TestDialogEdgeCases:
def test_create_dialog_with_tavily_api_key(self, WebApiAuth): ...
def test_create_dialog_with_different_embedding_models... | def test_concurrent_dialog_operations(self, WebApiAuth, add_dialog_func):
"""Test concurrent operations on the same dialog"""
from concurrent.futures import ThreadPoolExecutor, as_completed
_, dialog_id = add_dialog_func
def update_operation(i):
payload = {"dialog_id": dial... | test | 1 | {"function_name": "test_concurrent_dialog_operations", "class_name": "TestDialogEdgeCases", "qualname": "TestDialogEdgeCases.test_concurrent_dialog_operations", "file_path": "test/testcases/test_web_api/test_dialog_app/test_dialog_edge_cases.py", "repo_id": "infiniflow/ragflow", "loc": 20, "tested_modules": ["common", ... |
mem0ai/mem0:mem0/configs/llms/openai.py:OpenAIConfig:class_doc | Write a class-level docstring for `OpenAIConfig` (inherits from BaseLlmConfig) which has methods: `__init__`. | Configuration class for OpenAI and OpenRouter-specific parameters.
Inherits from BaseLlmConfig and adds OpenAI-specific settings. | documentation | 1 | {"doc_type": "class", "class_name": "OpenAIConfig", "file_path": "mem0/configs/llms/openai.py", "repo_id": "mem0ai/mem0", "char_length": 129, "methods": ["__init__"]} |
run-llama/llama_index:llama-index-core/tests/test_rate_limiter.py:test_embedding_without_rate_limiter_works | # Context:
from llama_index.core.embeddings.mock_embed_model import MockEmbedding
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_limiter() -> None: ...
def test_cust... | def test_embedding_without_rate_limiter_works() -> None:
from llama_index.core.embeddings.mock_embed_model import MockEmbedding
embed = MockEmbedding(embed_dim=8)
assert embed.rate_limiter is None
result = embed.get_text_embedding("test")
assert len(result) == 8 | test | 1 | {"function_name": "test_embedding_without_rate_limiter_works", "class_name": null, "qualname": "test_embedding_without_rate_limiter_works", "file_path": "llama-index-core/tests/test_rate_limiter.py", "repo_id": "run-llama/llama_index", "loc": 7, "tested_modules": ["llama_index.core.base.llms.types", "llama_index.core.l... |
huggingface/transformers:src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py:Ernie4_5_VLMoeModel.get_rope_index | # Context:
import itertools
import torch
class Ernie4_5_VLMoeVisionConfig(Qwen2VLVisionConfig): ...
class Ernie4_5_VLMoeTextConfig(Ernie4_5_MoeConfig, PreTrainedConfig): ...
class Ernie4_5_VLMoeConfig(PreTrainedConfig): ...
class Ernie4_5_VLMoeTextRotaryEmbedding(nn.Module): ...
def rotate_half_text(x): ...
def apply_... | def get_rope_index(
self,
input_ids: torch.LongTensor,
mm_token_type_ids: torch.IntTensor,
image_grid_thw: torch.LongTensor | None = None,
video_grid_thw: torch.LongTensor | None = None,
attention_mask: torch.Tensor | None = None,
**kwargs,
) -> tuple[torch.Te... | function_complex | 0 | {"cognitive_complexity": 20, "loc": 105, "code_loc": 50, "docstring_loc": 40, "function_name": "get_rope_index", "class_name": "Ernie4_5_VLMoeModel", "qualname": "Ernie4_5_VLMoeModel.get_rope_index", "file_path": "src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py", "repo_id": "huggingface/transformers"... |
Shubhamsaboo/awesome-llm-apps:ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/agent.py:StreamingWorkflowCallbacks:class_doc | Write a class-level docstring for `StreamingWorkflowCallbacks` (inherits from SingleAgentWorkflowCallbacks) which has methods: `__init__`, `on_run`, `on_tool_call`, `on_handoff`, `on_turn_start`. | Custom callbacks to monitor the streaming voice workflow. | documentation | 0 | {"doc_type": "class", "class_name": "StreamingWorkflowCallbacks", "file_path": "ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/agent.py", "repo_id": "Shubhamsaboo/awesome-llm-apps", "char_length": 57, "methods": ["__init__", "on_run", "on_tool_call", "on_handoff", "on_turn_start", "on_turn_en... |
crewAIInc/crewAI:lib/crewai-files/src/crewai_files/cache/upload_cache.py:get_upload_cache | # Context:
from typing import TYPE_CHECKING, Any
from crewai_files.core.constants import DEFAULT_MAX_CACHE_ENTRIES, DEFAULT_TTL_SECONDS
class CachedUpload: ...
def _make_key(file_hash: str, provider: str) -> str: ...
def _compute_file_hash_streaming(chunks: Iterator[bytes]) -> str: ...
def _compute_file_hash(file: Fil... | def get_upload_cache(
ttl: int = DEFAULT_TTL_SECONDS,
namespace: str = "crewai_uploads",
cache_type: str = "memory",
**cache_kwargs: Any,
) -> UploadCache:
"""Get or create the default upload cache.
Args:
ttl: Default TTL in seconds.
namespace: Cache namespace.
cache_typ... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 26, "code_loc": 9, "docstring_loc": 11, "function_name": "get_upload_cache", "class_name": null, "qualname": "get_upload_cache", "file_path": "lib/crewai-files/src/crewai_files/cache/upload_cache.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_level": "project_run... |
ray-project/ray:python/ray/_common/tests/test_signature.py:TestValidateArgs.test_valid_keyword_args | # Context:
from ray._common.signature import (
DUMMY_TYPE,
extract_signature,
flatten_args,
get_signature,
recover_args,
validate_args,
)
class TestGetSignature: ...
class TestExtractSignature: ...
class TestFlattenArgs: ...
class TestRecoverArgs: ...
class TestIntegration: ...
class TestValid... | def test_valid_keyword_args(self):
"""Test validation with valid keyword arguments."""
def test_func(a, b=20, c=30):
return a + b + c
params = extract_signature(test_func)
# Should not raise an exception
validate_args(params, (1,), {"b": 2})
validate_args(pa... | test | 0 | {"function_name": "test_valid_keyword_args", "class_name": "TestValidateArgs", "qualname": "TestValidateArgs.test_valid_keyword_args", "file_path": "python/ray/_common/tests/test_signature.py", "repo_id": "ray-project/ray", "loc": 11, "tested_modules": ["typing", "ray._common.signature"], "has_docstring": true, "runnab... |
browser-use/browser-use:browser_use/browser/watchdogs/default_action_watchdog.py:DefaultActionWatchdog._get_key_code_for_char | Write a Python method `_get_key_code_for_char` for the class `DefaultActionWatchdog` to get the proper key code for a character (like Playwright does).
Parameters: char: str
Returns: str | def _get_key_code_for_char(self, char: str) -> str:
"""Get the proper key code for a character (like Playwright does)."""
# Key code mapping for common characters (using proper base keys + modifiers)
key_codes = {
' ': 'Space',
'.': 'Period',
',': 'Comma',
'-': 'Minus',
'_': 'Minus', # Underscore ... | function_simple | 0 | {"cognitive_complexity": 3, "loc": 50, "code_loc": 39, "docstring_loc": 1, "function_name": "_get_key_code_for_char", "class_name": "DefaultActionWatchdog", "qualname": "DefaultActionWatchdog._get_key_code_for_char", "file_path": "browser_use/browser/watchdogs/default_action_watchdog.py", "repo_id": "browser-use/browse... |
apache/airflow:helm-tests/tests/helm_tests/dagprocessor/test_labels_deployment.py:TestDagProcessorDeployment.test_should_add_global_labels | # Context:
import jmespath
from chart_utils.helm_template_generator import render_chart
class TestDagProcessorDeployment:
AIRFLOW_VERSION = "3.0.0"
TEMPLATE_FILE = "templates/dag-processor/dag-processor-deployment.yaml"
def test_should_add_component_specific_labels(self): ...
def test_should_merge_glob... | def test_should_add_global_labels(self):
"""Test adding only .Values.labels."""
docs = render_chart(
values={
"airflowVersion": self.AIRFLOW_VERSION,
"labels": {"test_global_label": "test_global_label_value"},
},
show_only=[self.TEMPLAT... | test | 1 | {"function_name": "test_should_add_global_labels", "class_name": "TestDagProcessorDeployment", "qualname": "TestDagProcessorDeployment.test_should_add_global_labels", "file_path": "helm-tests/tests/helm_tests/dagprocessor/test_labels_deployment.py", "repo_id": "apache/airflow", "loc": 15, "tested_modules": ["__future__... |
apache/airflow:providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py:TestEcsExecutorTask.test_repr | # Context:
from airflow.providers.amazon.aws.executors.ecs.utils import (
AllEcsConfigKeys,
EcsExecutorException,
EcsExecutorTask,
EcsQueuedTask,
EcsTaskCollection,
EcsTaskInfo,
RunTaskKwargsConfigKeys,
_recursive_flatten_dict,
camelize_dict_keys,
parse_assign_public_ip,
)
class... | def test_repr(self):
"""Test __repr__ method."""
task = EcsExecutorTask(
task_arn="arn:aws:ecs:us-east-1:123456789012:task/test-task",
last_status="RUNNING",
desired_status="RUNNING",
containers=[{"name": "container1", "exit_code": 0}],
)
e... | test | 1 | {"function_name": "test_repr", "class_name": "TestEcsExecutorTask", "qualname": "TestEcsExecutorTask.test_repr", "file_path": "providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py", "repo_id": "apache/airflow", "loc": 10, "tested_modules": ["__future__", "airflow.models.taskinstance", "airflow.providers.a... |
unclecode/crawl4ai:tests/test_prefetch_mode.py:TestQuickExtractLinksEdgeCases.test_no_links_in_page | # Context:
from crawl4ai.utils import quick_extract_links
class TestQuickExtractLinks: ...
class TestQuickExtractLinksEdgeCases:
def test_links_in_nested_elements(self): ...
def test_link_with_nested_elements(self): ...
def test_protocol_relative_urls(self): ...
def test_whitespace_in_href(self): ...
... | def test_no_links_in_page(self):
"""Test page with no links."""
html = '''
<html>
<body>
<h1>No Links Here</h1>
<p>Just some text content.</p>
</body>
</html>
'''
result = quick_extract_links(html, "https://example.c... | test | 1 | {"function_name": "test_no_links_in_page", "class_name": "TestQuickExtractLinksEdgeCases", "qualname": "TestQuickExtractLinksEdgeCases.test_no_links_in_page", "file_path": "tests/test_prefetch_mode.py", "repo_id": "unclecode/crawl4ai", "loc": 14, "tested_modules": ["crawl4ai.utils"], "has_docstring": true, "runnable_le... |
vllm-project/vllm:tests/entrypoints/openai/test_completion_with_function_calling.py:test_no_args_tool_call | # Context:
import datetime
import openai # use the official client for correctness check
import pytest
def server(): ...
async def client(server): ...
async def test_function_tool_use(client: openai.AsyncOpenAI, model_name: str, stream: bool, tool_choice: str | dict, enable_thinking: bool): ...
def k2_server(): ...
a... | async def test_no_args_tool_call(
client: openai.AsyncOpenAI, model_name: str, arguments: str
):
# Step 1: Define a tool that requires no parameters
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get t... | test | 1 | {"function_name": "test_no_args_tool_call", "class_name": null, "qualname": "test_no_args_tool_call", "file_path": "tests/entrypoints/openai/test_completion_with_function_calling.py", "repo_id": "vllm-project/vllm", "loc": 58, "tested_modules": ["utils"], "has_docstring": false, "runnable_level": "project_runnable"} |
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/tavily_extractor_tool/tavily_extractor_tool.py:TavilyExtractorTool._run | # Context:
import json
class TavilyExtractorToolSchema(BaseModel): ...
class TavilyExtractorTool(BaseTool):
model_config = ConfigDict(arbitrary_types_allowed=True)
def __init__(self, **kwargs: Any):
"""Initializes the TavilyExtractorTool.
Args:
**kwargs: Additional keyword argumen... | def _run(
self,
urls: list[str] | str,
) -> str:
"""Synchronously extracts content from the given URL(s).
Args:
urls: The URL(s) to extract data from.
Returns:
A JSON string containing the extracted data.
"""
if not self.client:
... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 26, "code_loc": 13, "docstring_loc": 8, "function_name": "_run", "class_name": "TavilyExtractorTool", "qualname": "TavilyExtractorTool._run", "file_path": "lib/crewai-tools/src/crewai_tools/tools/tavily_extractor_tool/tavily_extractor_tool.py", "repo_id": "crewAIInc/crewAI", "has_docs... |
commaai/openpilot:selfdrive/ui/translations/potools.py:merge_po | # Context:
from pathlib import Path
class POEntry: ...
def _parse_quoted(s: str) -> str: ...
def parse_po(path: str | Path) -> tuple[POEntry | None, list[POEntry]]: ...
def _quote(s: str) -> str: ...
def write_po(path: str | Path, header: POEntry | None, entries: list[POEntry]) -> None: ...
def extract_strings(files: ... | def merge_po(po_path: str | Path, pot_path: str | Path) -> None:
"""Update a .po file with entries from a .pot template (replaces msgmerge --update)."""
po_header, po_entries = parse_po(po_path)
_, pot_entries = parse_po(pot_path)
existing = {e.msgid: e for e in po_entries}
merged = []
for pot_e in pot_en... | function_complex | 0 | {"cognitive_complexity": 7, "loc": 22, "code_loc": 17, "docstring_loc": 1, "function_name": "merge_po", "class_name": null, "qualname": "merge_po", "file_path": "selfdrive/ui/translations/potools.py", "repo_id": "commaai/openpilot", "has_docstring": true, "runnable_level": "file_runnable"} |
langflow-ai/langflow:src/lfx/src/lfx/utils/helpers.py:get_mime_type | # Context:
import mimetypes
from pathlib import Path
def build_content_type_from_extension(extension: str): ...
# Task:
Write a Python function `get_mime_type` to get the MIME type of a file based on its extension.
Parameters: file_path: str | Path
Returns: str | def get_mime_type(file_path: str | Path) -> str:
"""Get the MIME type of a file based on its extension.
Args:
file_path: Path to the file
Returns:
MIME type string (e.g., 'image/jpeg', 'image/png')
Raises:
ValueError: If MIME type cannot be determined
"""
mime_type, _ ... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 17, "code_loc": 5, "docstring_loc": 11, "function_name": "get_mime_type", "class_name": null, "qualname": "get_mime_type", "file_path": "src/lfx/src/lfx/utils/helpers.py", "repo_id": "langflow-ai/langflow", "has_docstring": true, "runnable_level": "slib_runnable"} |
sansan0/TrendRadar:mcp_server/server.py:read_article | # Context:
import asyncio
import json
def _get_tools(project_root: Optional[str]): ...
async def get_platforms_resource() -> str: ...
async def get_rss_feeds_resource() -> str: ...
async def get_available_dates_resource() -> str: ...
async def get_keywords_resource() -> str: ...
async def resolve_date_range(expression... | async def read_article(
url: str,
timeout: int = 30
) -> str:
"""
读取指定 URL 的文章内容,返回 LLM 友好的 Markdown 格式
通过 Jina AI Reader 将网页转换为干净的 Markdown,自动去除广告、导航栏等噪音内容。
适合用于:阅读新闻正文、获取文章详情、分析文章内容。
**典型使用流程:**
1. 先用 search_news(include_url=True) 搜索新闻获取链接
2. 再用 read_article(url=链接) 读取正文内容
3.... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 37, "code_loc": 7, "docstring_loc": 26, "function_name": "read_article", "class_name": null, "qualname": "read_article", "file_path": "mcp_server/server.py", "repo_id": "sansan0/TrendRadar", "has_docstring": true, "runnable_level": "file_runnable"} |
crewAIInc/crewAI:lib/devtools/src/crewai_devtools/cli.py:get_github_contributors | # Context:
import subprocess
from github import Github
def run_command(cmd: list[str], cwd: Path | None) -> str: ...
def check_gh_installed() -> None: ...
def check_git_clean() -> None: ...
def update_version_in_file(file_path: Path, new_version: str) -> bool: ...
def update_pyproject_dependencies(file_path: Path, new... | def get_github_contributors(commit_range: str) -> list[str]:
"""Get GitHub usernames from commit range using GitHub API.
Args:
commit_range: Git commit range (e.g., "abc123..HEAD").
Returns:
List of GitHub usernames sorted alphabetically.
"""
try:
# Get GitHub token from gh... | function_complex | 0 | {"cognitive_complexity": 46, "loc": 50, "code_loc": 34, "docstring_loc": 8, "function_name": "get_github_contributors", "class_name": null, "qualname": "get_github_contributors", "file_path": "lib/devtools/src/crewai_devtools/cli.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_level": "project_runn... |
ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/llm/vllm/kv_transfer_backends/test_lmcache_connector_v1.py:TestLMCacheConnectorV1Backend.test_setup_with_existing_port | # Context:
class TestLMCacheConnectorV1Backend:
def mock_lmcache_check(self): ...
def lmcache_backend_basic(self): ...
def lmcache_backend_with_extra(self): ...
def lmcache_backend_with_port(self): ...
def test_setup_basic_config(self, lmcache_backend_basic): ...
def test_setup_with_extra_confi... | def test_setup_with_existing_port(self, lmcache_backend_with_port):
"""Test setup with existing lmcache_rpc_port configuration."""
original_port = lmcache_backend_with_port.kv_transfer_config[
"kv_connector_extra_config"
]["lmcache_rpc_port"]
lmcache_backend_with_port.setup(... | test | 0 | {"function_name": "test_setup_with_existing_port", "class_name": "TestLMCacheConnectorV1Backend", "qualname": "TestLMCacheConnectorV1Backend.test_setup_with_existing_port", "file_path": "python/ray/llm/tests/serve/cpu/deployments/llm/vllm/kv_transfer_backends/test_lmcache_connector_v1.py", "repo_id": "ray-project/ray",... |
fastapi/fastapi:tests/test_dependency_paramless.py:test_get_credentials | # Context:
def process_auth(credentials: Annotated[str | None, Security(oauth2_scheme)], security_scopes: SecurityScopes): ...
def get_credentials(credentials: Annotated[dict, Security(process_auth, scopes=['a', 'b'])]): ...
def get_parameterless_with_scopes(): ...
def get_parameterless_without_scopes(): ...
def test_... | def test_get_credentials():
response = client.get("/get-credentials", headers={"authorization": "Bearer token"})
assert response.status_code == 200, response.text
assert response.json() == {"token": "token", "scopes": ["a", "b"]} | test | 1 | {"function_name": "test_get_credentials", "class_name": null, "qualname": "test_get_credentials", "file_path": "tests/test_dependency_paramless.py", "repo_id": "fastapi/fastapi", "loc": 4, "tested_modules": ["typing", "fastapi", "fastapi.security", "fastapi.testclient"], "has_docstring": false, "runnable_level": "file_... |
ray-project/ray:doc/source/ray-overview/examples/multi_agent_a2a/content/mcps/web_search_mcp_server.py:_http_get_text | # Context:
import httpx
def _get_robots_txt_url(url: str) -> str: ...
async def _check_may_fetch_url(url: str, user_agent: str) -> None: ...
def _extract_markdown_from_html(html: str) -> str: ...
def _truncate(content: str, max_length: int, start_index: int) -> tuple[str, str]: ...
async def brave_search(query: str, n... | async def _http_get_text(url: str, *, user_agent: str, timeout_s: float = 30.0, headers: dict | None = None) -> tuple[str, str]:
"""
Fetch URL. Returns (text, content_type).
"""
request_headers = {"User-Agent": user_agent}
if headers:
request_headers.update(headers)
async with httpx.Asyn... | function_simple | 0 | {"cognitive_complexity": 2, "loc": 11, "code_loc": 7, "docstring_loc": 3, "function_name": "_http_get_text", "class_name": null, "qualname": "_http_get_text", "file_path": "doc/source/ray-overview/examples/multi_agent_a2a/content/mcps/web_search_mcp_server.py", "repo_id": "ray-project/ray", "has_docstring": true, "runn... |
browser-use/browser-use:browser_use/llm/tests/test_anthropic_cache.py:TestAnthropicCache.test_cache_only_last_tool_call | # Context:
from browser_use.llm.anthropic.serializer import AnthropicMessageSerializer, NonSystemMessage
from browser_use.llm.messages import (
AssistantMessage,
BaseMessage,
ContentPartImageParam,
ContentPartTextParam,
Function,
ImageURL,
SystemMessage,
ToolCall,
UserMessage,
)
class TestAnthropicCache:
... | def test_cache_only_last_tool_call(self):
"""Test that only the LAST tool_use block gets cache_control."""
tool_calls = [
ToolCall(id='id1', function=Function(name='func1', arguments='{"arg": "1"}')),
ToolCall(id='id2', function=Function(name='func2', arguments='{"arg": "2"}')),
ToolCall(id='id3', function... | test | 0 | {"function_name": "test_cache_only_last_tool_call", "class_name": "TestAnthropicCache", "qualname": "TestAnthropicCache.test_cache_only_last_tool_call", "file_path": "browser_use/llm/tests/test_anthropic_cache.py", "repo_id": "browser-use/browser-use", "loc": 22, "tested_modules": ["typing", "browser_use.agent.service"... |
ray-project/ray:python/ray/serve/tests/unit/test_grpc_replica_result.py:TestSeparateLoop.test_streaming_sync | # Context:
import asyncio
from ray._common.test_utils import wait_for_condition
class FakegRPCUnaryCall: ...
class FakegRPCStreamCall: ...
def create_asyncio_event_loop_in_thread(): ...
class TestSameLoop: ...
class TestSeparateLoop:
async def make_fake_unary_request(self, data, loop: asyncio.AbstractEventLoop): ... | def test_streaming_sync(self, create_asyncio_event_loop_in_thread):
loop, _ = create_asyncio_event_loop_in_thread
# Instantiate gRPCReplicaResult with FakegRPCStreamCall. This needs
# to be run on the "other loop"
fut = asyncio.run_coroutine_threadsafe(
self.make_fake_stream... | test | 0 | {"function_name": "test_streaming_sync", "class_name": "TestSeparateLoop", "qualname": "TestSeparateLoop.test_streaming_sync", "file_path": "python/ray/serve/tests/unit/test_grpc_replica_result.py", "repo_id": "ray-project/ray", "loc": 18, "tested_modules": ["ray", "ray._common.test_utils", "ray.serve._private.common",... |
Comfy-Org/ComfyUI:tests-unit/assets_test/test_uploads.py:test_upload_models_unknown_category | # Context:
import json
import requests
def test_upload_ok_duplicate_reference(http: requests.Session, api_base: str, make_asset_bytes): ...
def test_upload_fastpath_from_existing_hash_no_file(http: requests.Session, api_base: str): ...
def test_upload_fastpath_with_known_hash_and_file(http: requests.Session, api_base:... | def test_upload_models_unknown_category(http: requests.Session, api_base: str):
files = {"file": ("m.safetensors", b"A" * 128, "application/octet-stream")}
form = {"tags": json.dumps(["models", "no_such_category", "unit-tests"]), "name": "m.safetensors"}
r = http.post(api_base + "/api/assets", data=form, fi... | test | 1 | {"function_name": "test_upload_models_unknown_category", "class_name": null, "qualname": "test_upload_models_unknown_category", "file_path": "tests-unit/assets_test/test_uploads.py", "repo_id": "Comfy-Org/ComfyUI", "loc": 8, "tested_modules": ["concurrent.futures"], "has_docstring": false, "runnable_level": "project_ru... |
crewAIInc/crewAI:lib/crewai/tests/events/test_event_ordering.py:TestTriggeredByEventId.test_exception_handling_triggered_by | # Context:
import pytest
from crewai.events.base_events import BaseEvent
from crewai.events.event_bus import crewai_event_bus
from crewai.events.types.flow_events import (
FlowFinishedEvent,
FlowStartedEvent,
MethodExecutionFinishedEvent,
MethodExecutionStartedEvent,
)
from crewai.flow.flow import Flow,... | async def test_exception_handling_triggered_by(self) -> None:
"""Events emitted after exception should still have correct triggered_by."""
from crewai.events.base_events import reset_emission_counter
from crewai.events.event_context import reset_last_event_id
from crewai.events.types.flo... | test | 0 | {"function_name": "test_exception_handling_triggered_by", "class_name": "TestTriggeredByEventId", "qualname": "TestTriggeredByEventId.test_exception_handling_triggered_by", "file_path": "lib/crewai/tests/events/test_event_ordering.py", "repo_id": "crewAIInc/crewAI", "loc": 47, "tested_modules": ["crewai.agent", "crewai... |
crewAIInc/crewAI:lib/crewai/tests/events/test_depends.py:module_doc | Write a module-level docstring for the Python module `test_depends` which contains class `DependsTestEvent`. | Tests for FastAPI-style dependency injection in event handlers. | documentation | 0 | {"doc_type": "module", "module_name": "test_depends", "file_path": "lib/crewai/tests/events/test_depends.py", "repo_id": "crewAIInc/crewAI", "char_length": 63} |
apache/airflow:providers/google/tests/unit/google/cloud/operators/test_gen_ai.py:TestGenAIGeminiCreateEmbeddingsBatchJobOperator.test__wait_until_complete_exception_raises_airflow_exception | # Context:
from unittest import mock
import pytest
from airflow.exceptions import AirflowException
from airflow.providers.google.cloud.operators.gen_ai import (
GenAICountTokensOperator,
GenAICreateCachedContentOperator,
GenAIGeminiCancelBatchJobOperator,
GenAIGeminiCreateBatchJobOperator,
GenAIGemi... | def test__wait_until_complete_exception_raises_airflow_exception(self, mock_hook):
op = GenAIGeminiCreateEmbeddingsBatchJobOperator(
task_id=TASK_ID,
project_id=GCP_PROJECT,
location=GCP_LOCATION,
input_source=TEST_EMBEDDINGS_JOB_INLINED_REQUESTS,
mode... | test | 1 | {"function_name": "test__wait_until_complete_exception_raises_airflow_exception", "class_name": "TestGenAIGeminiCreateEmbeddingsBatchJobOperator", "qualname": "TestGenAIGeminiCreateEmbeddingsBatchJobOperator.test__wait_until_complete_exception_raises_airflow_exception", "file_path": "providers/google/tests/unit/google/... |
github/spec-kit:src/specify_cli/extensions.py:ExtensionManager:class_doc | Write a class-level docstring for `ExtensionManager` which has methods: `__init__`, `check_compatibility`, `install_from_directory`, `install_from_zip`, `remove`. | Manages extension lifecycle: installation, removal, updates. | documentation | 0 | {"doc_type": "class", "class_name": "ExtensionManager", "file_path": "src/specify_cli/extensions.py", "repo_id": "github/spec-kit", "char_length": 60, "methods": ["__init__", "check_compatibility", "install_from_directory", "install_from_zip", "remove", "list_installed", "get_extension"]} |
paperless-ngx/paperless-ngx:src/documents/tests/test_api_document_versions.py:TestDocumentVersioningApi.test_root_endpoint_returns_403_when_user_lacks_permission | # Context:
from django.contrib.auth.models import Permission
from django.contrib.auth.models import User
from rest_framework import status
from documents.models import Document
class TestVersionAwareFilters(TestCase): ...
class TestDocumentVersioningApi(DirectoriesMixin, APITestCase):
def setUp(self) -> None: ...... | def test_root_endpoint_returns_403_when_user_lacks_permission(self) -> None:
owner = User.objects.create_user(username="owner")
viewer = User.objects.create_user(username="viewer")
viewer.user_permissions.add(
Permission.objects.get(codename="view_document"),
)
root =... | test | 1 | {"function_name": "test_root_endpoint_returns_403_when_user_lacks_permission", "class_name": "TestDocumentVersioningApi", "qualname": "TestDocumentVersioningApi.test_root_endpoint_returns_403_when_user_lacks_permission", "file_path": "src/documents/tests/test_api_document_versions.py", "repo_id": "paperless-ngx/paperle... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.