sample_id string | instruction string | completion string | category string | label int64 | metadata string |
|---|---|---|---|---|---|
unclecode/crawl4ai:crawl4ai/script/c4a_result.py:ErrorDetail.to_json | # Context:
import json
class ErrorType(Enum): ...
class Severity(Enum): ...
class Suggestion: ...
class WarningDetail: ...
class CompilationResult: ...
class ValidationResult: ...
class ErrorDetail:
def to_dict(self) -> dict: ...
def formatted_message(self) -> str: ...
def simple_message(self) -> str: ...... | def to_json(self) -> str:
"""Convert to JSON string"""
return json.dumps(self.to_dict(), indent=2) | function_simple | 1 | {"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "to_json", "class_name": "ErrorDetail", "qualname": "ErrorDetail.to_json", "file_path": "crawl4ai/script/c4a_result.py", "repo_id": "unclecode/crawl4ai", "has_docstring": true, "runnable_level": "class_runnable"} |
run-llama/llama_index:llama-index-core/tests/agent/workflow/test_agent_with_structured_output.py:test_astructured_fn_agent | # Context:
import pytest
from llama_index.core.agent.workflow import (
AgentWorkflow,
AgentOutput,
AgentStreamStructuredOutput,
)
from llama_index.core.agent.workflow import FunctionAgent
class TestLLM(LLM): ...
class Structure(BaseModel): ...
def function_agent_output_cls(): ...
def structured_function_fn... | async def test_astructured_fn_agent(function_agent_astruct_fn: FunctionAgent):
"""Test single agent with state management."""
handler = function_agent_astruct_fn.run(user_msg="test")
async for event in handler.stream_events():
if isinstance(event, AgentStreamStructuredOutput):
streaming_... | test | 1 | {"function_name": "test_astructured_fn_agent", "class_name": null, "qualname": "test_astructured_fn_agent", "file_path": "llama-index-core/tests/agent/workflow/test_agent_with_structured_output.py", "repo_id": "run-llama/llama_index", "loc": 12, "tested_modules": ["typing", "typing_extensions", "pydantic", "llama_index... |
ray-project/ray:python/ray/data/checkpoint/checkpoint_filter.py:CheckpointLoader.__init__ | # Context:
from typing import List, Optional
import pyarrow
from ray.data.datasource import PathPartitionFilter
class CheckpointFilter(abc.ABC): ...
def _combine_chunks(ckpt_block: pyarrow.Table) -> pyarrow.Table: ...
class IdColumnCheckpointLoader(CheckpointLoader): ...
class BatchBasedCheckpointFilter(CheckpointFilt... | def __init__(
self,
checkpoint_path: str,
filesystem: pyarrow.fs.FileSystem,
id_column: str,
checkpoint_path_partition_filter: Optional[PathPartitionFilter] = None,
):
"""Initialize the CheckpointLoader.
Args:
checkpoint_path: The path to the chec... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 20, "code_loc": 4, "docstring_loc": 9, "function_name": "__init__", "class_name": "CheckpointLoader", "qualname": "CheckpointLoader.__init__", "file_path": "python/ray/data/checkpoint/checkpoint_filter.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "projec... |
unclecode/crawl4ai:tests/deep_crawling/test_deep_crawl_resume.py:TestDFSRegressions:class_doc | Write a class-level docstring for `TestDFSRegressions` which has methods: `test_inherits_bfs_params`, `test_dfs_seen_initialized`. | Ensure DFS works identically when new params not used. | documentation | 1 | {"doc_type": "class", "class_name": "TestDFSRegressions", "file_path": "tests/deep_crawling/test_deep_crawl_resume.py", "repo_id": "unclecode/crawl4ai", "char_length": 54, "methods": ["test_inherits_bfs_params", "test_dfs_seen_initialized"]} |
huggingface/transformers:src/transformers/models/pix2struct/image_processing_pix2struct_fast.py:Pix2StructImageProcessorFast.preprocess | # Context:
from ...image_processing_utils import BatchFeature, get_size_dict
from ...image_utils import ChannelDimension, ImageInput, SizeDict
from ...processing_utils import Unpack
from .image_processing_pix2struct import Pix2StructImageProcessorKwargs, render_text
def torch_extract_patches(image_tensor, patch_height... | def preprocess(
self,
images: ImageInput,
header_text: str | list[str] | None = None,
**kwargs: Unpack[Pix2StructImageProcessorKwargs],
) -> BatchFeature:
r"""
header_text (`Union[str, list[str]]`, *optional*):
Text to render as a header. Only has an effec... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 11, "code_loc": 1, "docstring_loc": 4, "function_name": "preprocess", "class_name": "Pix2StructImageProcessorFast", "qualname": "Pix2StructImageProcessorFast.preprocess", "file_path": "src/transformers/models/pix2struct/image_processing_pix2struct_fast.py", "repo_id": "huggingface/tra... |
crewAIInc/crewAI:lib/crewai-files/tests/test_upload_cache.py:TestCachedUpload.test_is_expired_no_expiry | # Context:
from datetime import datetime, timedelta, timezone
from crewai_files.cache.upload_cache import CachedUpload, UploadCache
class TestUploadCache: ...
class TestCachedUpload:
def test_cached_upload_creation(self): ...
def test_is_expired_false(self): ...
def test_is_expired_true(self): ...
# Task... | def test_is_expired_no_expiry(self):
"""Test is_expired returns False when no expiry set."""
cached = CachedUpload(
file_id="file-123",
provider="anthropic",
file_uri=None,
content_type="image/png",
uploaded_at=datetime.now(timezone.utc),
... | test | 0 | {"function_name": "test_is_expired_no_expiry", "class_name": "TestCachedUpload", "qualname": "TestCachedUpload.test_is_expired_no_expiry", "file_path": "lib/crewai-files/tests/test_upload_cache.py", "repo_id": "crewAIInc/crewAI", "loc": 12, "tested_modules": ["datetime", "crewai_files", "crewai_files.cache.upload_cache... |
infiniflow/ragflow:test/testcases/test_sdk_api/test_agent_management/test_agent_crud_unit.py:test_delete_agent_success_and_error | # Context:
import pytest
from ragflow_sdk import RAGFlow
class _DummyResponse: ...
def auth(): ...
def set_tenant_info(): ...
def test_list_agents_success_and_error(monkeypatch): ...
def test_create_agent_payload_and_error(monkeypatch): ...
def test_update_agent_payload_matrix_and_error(monkeypatch): ...
def test_agen... | def test_delete_agent_success_and_error(monkeypatch):
client = RAGFlow("token", "http://localhost:9380")
calls = []
def _ok_delete(path, json):
calls.append((path, json))
return _DummyResponse({"code": 0, "message": "ok"})
monkeypatch.setattr(client, "delete", _ok_delete)
client.de... | test | 1 | {"function_name": "test_delete_agent_success_and_error", "class_name": null, "qualname": "test_delete_agent_success_and_error", "file_path": "test/testcases/test_sdk_api/test_agent_management/test_agent_crud_unit.py", "repo_id": "infiniflow/ragflow", "loc": 16, "tested_modules": ["ragflow_sdk", "ragflow_sdk.modules.age... |
crewAIInc/crewAI:lib/crewai-files/tests/test_file_url.py:TestNormalizeSource.test_normalize_file_url_passthrough | # Context:
from crewai_files import FileBytes, FileUrl, ImageFile
from crewai_files.core.sources import FilePath, _normalize_source
class TestFileUrl: ...
class TestResolverUrlHandling: ...
class TestImageFileWithUrl: ...
class TestNormalizeSource:
def test_normalize_url_string(self): ...
def test_normalize_h... | def test_normalize_file_url_passthrough(self):
"""Test that FileUrl instances pass through unchanged."""
original = FileUrl(url="https://example.com/image.png")
result = _normalize_source(original)
assert result is original | test | 0 | {"function_name": "test_normalize_file_url_passthrough", "class_name": "TestNormalizeSource", "qualname": "TestNormalizeSource.test_normalize_file_url_passthrough", "file_path": "lib/crewai-files/tests/test_file_url.py", "repo_id": "crewAIInc/crewAI", "loc": 6, "tested_modules": ["crewai_files", "crewai_files.core.reso... |
crewAIInc/crewAI:lib/crewai/tests/utilities/test_files.py:TestFilePath.test_raises_for_missing_file | # Context:
from pathlib import Path
import pytest
from crewai_files import (
AudioFile,
File,
FileBytes,
FilePath,
FileSource,
FileStream,
ImageFile,
PDFFile,
TextFile,
VideoFile,
normalize_input_files,
wrap_file_source,
)
class TestDetectContentType: ...
class TestFileB... | def test_raises_for_missing_file(self, tmp_path: Path) -> None:
"""Test that FilePath raises for non-existent files."""
with pytest.raises(ValueError, match="File not found"):
FilePath(path=tmp_path / "nonexistent.txt") | test | 0 | {"function_name": "test_raises_for_missing_file", "class_name": "TestFilePath", "qualname": "TestFilePath.test_raises_for_missing_file", "file_path": "lib/crewai/tests/utilities/test_files.py", "repo_id": "crewAIInc/crewAI", "loc": 4, "tested_modules": ["pathlib", "crewai_files", "crewai_files.core.sources"], "has_docs... |
vllm-project/vllm:vllm/v1/core/kv_cache_coordinator.py:KVCacheCoordinator:class_doc | Write a class-level docstring for `KVCacheCoordinator` (inherits from ABC) which has methods: `__init__`, `get_num_blocks_to_allocate`, `allocate_new_computed_blocks`, `allocate_new_blocks`, `cache_blocks`. | Coordinate the KV cache of different KV cache groups. | documentation | 1 | {"doc_type": "class", "class_name": "KVCacheCoordinator", "file_path": "vllm/v1/core/kv_cache_coordinator.py", "repo_id": "vllm-project/vllm", "char_length": 53, "methods": ["__init__", "get_num_blocks_to_allocate", "allocate_new_computed_blocks", "allocate_new_blocks", "cache_blocks", "free", "get_num_common_prefix_bl... |
browser-use/browser-use:tests/ci/browser/test_navigation.py:TestNavigationEdgeCases.test_recovery_after_navigation_error | # Context:
import asyncio
import pytest
from browser_use.agent.service import Agent
from tests.ci.conftest import create_mock_llm
def http_server(): ...
def base_url(http_server): ...
async def browser_session(): ...
class TestNavigationEdgeCases:
async def test_broken_page_navigation(self, browser_session, base_... | async def test_recovery_after_navigation_error(self, browser_session, base_url):
"""Test that agent can recover and navigate to valid page after encountering error."""
actions = [
f"""
{{
"thinking": "First, I'll try the broken page",
"evaluation_previous_goal": "Starting task",
"memory": "Naviga... | test | 0 | {"function_name": "test_recovery_after_navigation_error", "class_name": "TestNavigationEdgeCases", "qualname": "TestNavigationEdgeCases.test_recovery_after_navigation_error", "file_path": "tests/ci/browser/test_navigation.py", "repo_id": "browser-use/browser-use", "loc": 74, "tested_modules": ["werkzeug", "browser_use.... |
ManimCommunity/manim:scripts/release.py:get_release_body | # Context:
def run_gh(args: Sequence[str], check: bool, suppress_errors: bool) -> subprocess.CompletedProcess[str]: ...
def get_release_tags() -> list[str]: ...
def get_release_date(tag: str) -> str | None: ...
def generate_release_notes(head_tag: str, base_tag: str) -> str: ...
def normalize_tag(tag: str) -> str: ...... | def get_release_body(tag: str) -> str | None:
"""Get the release body for a published release."""
result = run_gh(
["release", "view", tag, "--repo", REPO, "--json", "body", "--jq", ".body"],
check=False,
suppress_errors=True,
)
if result.returncode != 0:
return None
... | function_simple | 1 | {"cognitive_complexity": 2, "loc": 10, "code_loc": 8, "docstring_loc": 1, "function_name": "get_release_body", "class_name": null, "qualname": "get_release_body", "file_path": "scripts/release.py", "repo_id": "ManimCommunity/manim", "has_docstring": true, "runnable_level": "file_runnable"} |
browser-use/browser-use:tests/ci/test_coordinate_clicking.py:TestCoordinateClickingTools.test_default_click_schema_has_only_index | # Context:
from browser_use.tools.service import Tools
class TestCoordinateClickingModelDetection: ...
class TestCoordinateClickingWithPassedTools: ...
class TestCoordinateClickingTools:
def test_default_coordinate_clicking_disabled(self): ...
def test_default_uses_index_only_action(self): ...
def test_en... | def test_default_click_schema_has_only_index(self):
"""Default click action schema should only have index property."""
tools = Tools()
click_action = tools.registry.registry.actions.get('click')
assert click_action is not None
schema = click_action.param_model.model_json_schema()
assert 'index' in schema[... | test | 0 | {"function_name": "test_default_click_schema_has_only_index", "class_name": "TestCoordinateClickingTools", "qualname": "TestCoordinateClickingTools.test_default_click_schema_has_only_index", "file_path": "tests/ci/test_coordinate_clicking.py", "repo_id": "browser-use/browser-use", "loc": 11, "tested_modules": ["browser... |
ray-project/ray:python/ray/data/tests/expressions/test_predicate.py:module_doc | Write a module-level docstring for the Python module `test_predicate` which contains class `TestPredicateIntegration`. | Integration tests for predicate expression operations.
These tests require Ray and test end-to-end predicate expression evaluation. | documentation | 0 | {"doc_type": "module", "module_name": "test_predicate", "file_path": "python/ray/data/tests/expressions/test_predicate.py", "repo_id": "ray-project/ray", "char_length": 132} |
huggingface/transformers:tests/models/deepseek_vl_hybrid/test_modeling_deepseek_vl_hybrid.py:DeepseekVLHybridIntegrationTest.test_model_text_generation | # Context:
from transformers import (
AutoProcessor,
DeepseekVLHybridConfig,
DeepseekVLHybridForConditionalGeneration,
DeepseekVLHybridModel,
is_torch_available,
)
from transformers.testing_utils import (
require_torch,
require_torch_accelerator,
slow,
torch_device,
)
class Deepseek... | def test_model_text_generation(self):
model = DeepseekVLHybridForConditionalGeneration.from_pretrained(
self.model_id, dtype="auto", device_map="auto"
)
model.to(torch_device)
model.eval()
processor = AutoProcessor.from_pretrained(self.model_id)
messages = [
... | test | 0 | {"function_name": "test_model_text_generation", "class_name": "DeepseekVLHybridIntegrationTest", "qualname": "DeepseekVLHybridIntegrationTest.test_model_text_generation", "file_path": "tests/models/deepseek_vl_hybrid/test_modeling_deepseek_vl_hybrid.py", "repo_id": "huggingface/transformers", "loc": 33, "tested_modules... |
apache/airflow:providers/common/sql/src/airflow/providers/common/sql/decorators/analytics.py:_AnalyticsDecoratedOperator.execute | # Context:
from typing import TYPE_CHECKING, Any, ClassVar
from airflow.providers.common.compat.sdk import (
AIRFLOW_V_3_0_PLUS,
DecoratedOperator,
TaskDecorator,
context_merge,
task_decorator_factory,
)
from airflow.providers.common.sql.operators.analytics import AnalyticsOperator
from airflow.util... | def execute(self, context: Context) -> Any:
"""
Build the SQL and execute the generated query (or queries).
:param context: Airflow context.
:return: Any
"""
context_merge(context, self.op_kwargs)
kwargs = determine_kwargs(self.python_callable, self.op_args, cont... | function_complex | 1 | {"cognitive_complexity": 11, "loc": 33, "code_loc": 18, "docstring_loc": 6, "function_name": "execute", "class_name": "_AnalyticsDecoratedOperator", "qualname": "_AnalyticsDecoratedOperator.execute", "file_path": "providers/common/sql/src/airflow/providers/common/sql/decorators/analytics.py", "repo_id": "apache/airflow... |
666ghj/BettaFish:MindSpider/schema/db_manager.py:DatabaseManager.show_recent_data | # Context:
from sqlalchemy import create_engine, text, inspect
from datetime import datetime, timedelta
from loguru import logger
from datetime import date, timedelta
def main(): ...
class DatabaseManager:
def __init__(self):
self.engine: Engine = None
self.connect()
def connect(self): ...
... | def show_recent_data(self, days=7):
"""显示最近几天的数据"""
data_recent_message = ""
data_recent_message += "\n" + "=" * 60
data_recent_message += "最近" + str(days) + "天的数据"
data_recent_message += "=" * 60
from datetime import date, timedelta
start_date = date.tod... | function_complex | 1 | {"cognitive_complexity": 6, "loc": 51, "code_loc": 45, "docstring_loc": 1, "function_name": "show_recent_data", "class_name": "DatabaseManager", "qualname": "DatabaseManager.show_recent_data", "file_path": "MindSpider/schema/db_manager.py", "repo_id": "666ghj/BettaFish", "has_docstring": true, "runnable_level": "class_... |
ray-project/ray:python/ray/serve/tests/test_deploy_app_2.py:test_deploy_one_app_failed | # Context:
import httpx
from ray import serve
from ray._common.test_utils import SignalActor, wait_for_condition
from ray.serve.schema import (
ApplicationStatus,
ServeApplicationSchema,
ServeDeploySchema,
ServeInstanceDetails,
)
def check_log_file(log_file: str, expected_regex: list): ...
def check_de... | def test_deploy_one_app_failed(serve_instance):
"""Deploy two applications with separate runtime envs."""
client = serve_instance
world_import_path = "ray.serve.tests.test_config_files.world.DagNode"
fail_import_path = "ray.serve.tests.test_config_files.fail.node"
config_template = {
"applic... | test | 0 | {"function_name": "test_deploy_one_app_failed", "class_name": null, "qualname": "test_deploy_one_app_failed", "file_path": "python/ray/serve/tests/test_deploy_app_2.py", "repo_id": "ray-project/ray", "loc": 37, "tested_modules": ["copy", "functools", "typing", "ray", "ray._common.test_utils"], "has_docstring": true, "r... |
apache/airflow:devel-common/src/tests_common/test_utils/dag.py:sync_dags_to_db | # Context:
from collections.abc import Collection, Sequence
from airflow.utils.session import NEW_SESSION, provide_session
from tests_common.test_utils.compat import DagSerialization, SerializedDAG
from sqlalchemy.orm import Session
from airflow.sdk import DAG
from airflow.models.dagbundle import DagBundleModel
from ai... | def sync_dags_to_db(
dags: Collection[DAG],
bundle_name: str = "testing",
session: Session = NEW_SESSION,
) -> Sequence[SerializedDAG]:
"""
Sync dags into the database.
This serializes dags and saves the results to the database. The serialized
(scheduler-oeirnted) dags are returned. If the ... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 28, "code_loc": 13, "docstring_loc": 7, "function_name": "sync_dags_to_db", "class_name": null, "qualname": "sync_dags_to_db", "file_path": "devel-common/src/tests_common/test_utils/dag.py", "repo_id": "apache/airflow", "has_docstring": true, "runnable_level": "project_runnable"} |
langchain-ai/langchain:libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py:ToolCallLimitMiddleware.__init__ | # Context:
class ToolCallLimitState(AgentState[ResponseT]): ...
def _build_tool_message_content(tool_name: str | None) -> str: ...
def _build_final_ai_message_content(thread_count: int, run_count: int, thread_limit: int | None, run_limit: int | None, tool_name: str | None) -> str: ...
class ToolCallLimitExceededError(... | def __init__(
self,
*,
tool_name: str | None = None,
thread_limit: int | None = None,
run_limit: int | None = None,
exit_behavior: ExitBehavior = "continue",
) -> None:
"""Initialize the tool call limit middleware.
Args:
tool_name: Name of... | function_simple | 1 | {"cognitive_complexity": 5, "loc": 53, "code_loc": 18, "docstring_loc": 23, "function_name": "__init__", "class_name": "ToolCallLimitMiddleware", "qualname": "ToolCallLimitMiddleware.__init__", "file_path": "libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py", "repo_id": "langchain-ai/langchain", "has_doc... |
browser-use/browser-use:tests/ci/test_variable_detection.py:test_detect_country_from_attributes | # Context:
from browser_use.agent.variable_detector import (
_detect_from_attributes,
_detect_from_value_pattern,
_detect_variable_type,
_ensure_unique_name,
detect_variables_in_history,
)
def create_test_element(attributes: dict[str, str] | None) -> DOMInteractedElement: ...
def create_mock_history(actions_with_... | def test_detect_country_from_attributes():
"""Test country detection from element attributes"""
attributes = {'name': 'country', 'id': 'country-select'}
result = _detect_from_attributes(attributes)
assert result is not None
var_name, var_format = result
assert var_name == 'country'
assert var_format is None | test | 0 | {"function_name": "test_detect_country_from_attributes", "class_name": null, "qualname": "test_detect_country_from_attributes", "file_path": "tests/ci/test_variable_detection.py", "repo_id": "browser-use/browser-use", "loc": 9, "tested_modules": ["browser_use.agent.variable_detector", "browser_use.agent.views", "browse... |
run-llama/llama_index:llama-index-integrations/readers/llama-index-readers-web/tests/test_firecrawl_web_reader.py:test_search_mode_with_sdk_object_lists | # Context:
from llama_index.readers.web.firecrawl_web.base import FireCrawlWebReader
def _install_fake_firecrawl(FirecrawlClass) -> None: ...
class _Link: ...
class _MapResponse: ...
def test_class_name_returns_expected(): ...
def test_init_uses_api_key_and_url(): ...
def test_scrape_mode_with_dict_response_includes_t... | def test_search_mode_with_sdk_object_lists():
class Item:
def __init__(self, url: str, title: str, description: str) -> None:
self.url = url
self.title = title
self.description = description
self.rank = 7
class SearchResp:
def __init__(self):
... | test | 1 | {"function_name": "test_search_mode_with_sdk_object_lists", "class_name": null, "qualname": "test_search_mode_with_sdk_object_lists", "file_path": "llama-index-integrations/readers/llama-index-readers-web/tests/test_firecrawl_web_reader.py", "repo_id": "run-llama/llama_index", "loc": 28, "tested_modules": ["llama_index... |
huggingface/transformers:src/transformers/models/superglue/image_processing_superglue_fast.py:is_grayscale | # Context:
import torch
def _is_valid_image(image): ...
def flatten_pair_images(images): ...
def convert_to_grayscale(image: 'torch.Tensor') -> 'torch.Tensor': ...
class SuperGlueImageProcessorFast(BaseImageProcessorFast): ...
# Task:
Write a Python function `is_grayscale` to checks if an image is grayscale (all RGB ... | def is_grayscale(
image: "torch.Tensor",
):
"""Checks if an image is grayscale (all RGB channels are identical)."""
if image.ndim < 3 or image.shape[0 if image.ndim == 3 else 1] == 1:
return True
return torch.all(image[..., 0, :, :] == image[..., 1, :, :]) and torch.all(
image[..., 1, :,... | function_simple | 0 | {"cognitive_complexity": 3, "loc": 9, "code_loc": 5, "docstring_loc": 1, "function_name": "is_grayscale", "class_name": null, "qualname": "is_grayscale", "file_path": "src/transformers/models/superglue/image_processing_superglue_fast.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_level": "... |
docling-project/docling:docling/datamodel/vlm_engine_options.py:ApiVlmEngineOptions.__init__ | # Context:
from docling.models.inference_engines.vlm.base import (
BaseVlmEngineOptions,
VlmEngineType,
)
class AutoInlineVlmEngineOptions(BaseVlmEngineOptions): ...
class TransformersVlmEngineOptions(BaseVlmEngineOptions): ...
class MlxVlmEngineOptions(BaseVlmEngineOptions): ...
class VllmVlmEngineOptions(Bas... | def __init__(self, **data):
"""Initialize with default URLs based on engine type."""
if "engine_type" in data and "url" not in data:
engine_type = data["engine_type"]
if engine_type == VlmEngineType.API_OLLAMA:
data["url"] = "http://localhost:11434/v1/chat/complet... | function_complex | 1 | {"cognitive_complexity": 6, "loc": 12, "code_loc": 9, "docstring_loc": 1, "function_name": "__init__", "class_name": "ApiVlmEngineOptions", "qualname": "ApiVlmEngineOptions.__init__", "file_path": "docling/datamodel/vlm_engine_options.py", "repo_id": "docling-project/docling", "has_docstring": true, "runnable_level": "... |
Comfy-Org/ComfyUI:comfy_api_nodes/util/upload_helpers.py:upload_3d_model_to_comfyapi | # Context:
import uuid
from comfy_api.latest import IO, Input, Types
class UploadRequest(BaseModel): ...
class UploadResponse(BaseModel): ...
async def upload_images_to_comfyapi(cls: type[IO.ComfyNode], image: torch.Tensor | list[torch.Tensor], max_images: int, mime_type: str | None, wait_label: str | None, show_batch... | async def upload_3d_model_to_comfyapi(
cls: type[IO.ComfyNode],
model_3d: Types.File3D,
file_format: str,
) -> str:
"""Uploads a 3D model file to ComfyUI API and returns its download URL."""
return await upload_file_to_comfyapi(
cls,
model_3d.get_data(),
f"{uuid.uuid4()}.{fil... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 12, "code_loc": 6, "docstring_loc": 1, "function_name": "upload_3d_model_to_comfyapi", "class_name": null, "qualname": "upload_3d_model_to_comfyapi", "file_path": "comfy_api_nodes/util/upload_helpers.py", "repo_id": "Comfy-Org/ComfyUI", "has_docstring": true, "runnable_level": "projec... |
ray-project/ray:python/ray/data/tests/unit/test_concurrency_solver.py:TestAllocateResources.test_two_ops_different_resource_requirements | # Context:
from ray.data._internal.cluster_autoscaler.concurrency_solver import (
allocate_resources,
compute_optimal_throughput,
)
from ray.data._internal.execution.interfaces import ExecutionResources
class TestComputeOptimalThroughput: ...
class TestAllocateResources:
def test_empty_rates(self): ...
... | def test_two_ops_different_resource_requirements(self):
result = allocate_resources(
1.0,
rates={"A": 1.0, "B": 1.0},
resource_requirements={
"A": ExecutionResources(cpu=1),
"B": ExecutionResources(cpu=2),
},
)
asser... | test | 0 | {"function_name": "test_two_ops_different_resource_requirements", "class_name": "TestAllocateResources", "qualname": "TestAllocateResources.test_two_ops_different_resource_requirements", "file_path": "python/ray/data/tests/unit/test_concurrency_solver.py", "repo_id": "ray-project/ray", "loc": 11, "tested_modules": ["ra... |
browser-use/browser-use:browser_use/tools/extraction/schema_utils.py:schema_dict_to_pydantic_model | # Context:
from pydantic import BaseModel, ConfigDict, Field, create_model
class _StrictBase(BaseModel): ...
def _check_unsupported(schema: dict) -> None: ...
def _resolve_type(schema: dict, name: str) -> Any: ...
def _build_model(schema: dict, name: str) -> type[BaseModel]: ...
# Task:
Write a Python function `schem... | def schema_dict_to_pydantic_model(schema: dict) -> type[BaseModel]:
"""Convert a JSON Schema dict to a runtime Pydantic model.
The schema must be ``{"type": "object", "properties": {...}, ...}``.
Unsupported keywords ($ref, allOf, anyOf, oneOf, etc.) raise ValueError.
Returns:
A dynamically-created Pydantic Bas... | function_simple | 0 | {"cognitive_complexity": 2, "loc": 24, "code_loc": 9, "docstring_loc": 11, "function_name": "schema_dict_to_pydantic_model", "class_name": null, "qualname": "schema_dict_to_pydantic_model", "file_path": "browser_use/tools/extraction/schema_utils.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnabl... |
vllm-project/vllm:vllm/model_executor/layers/rotary_embedding/xdrope.py:XDRotaryEmbedding.forward_cuda | # Context:
import torch
class XDRotaryEmbedding(DynamicNTKAlphaRotaryEmbedding):
def __init__(
self,
head_size: int,
rotary_dim: int,
max_position_embeddings: int,
base: float,
is_neox_style: bool,
scaling_alpha: float,
dtype: torch.dtype,
xdr... | def forward_cuda(
self,
positions: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor | None = None,
offsets: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""PyTorch-native implementation equivalent to forward().
Args:
... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 50, "code_loc": 32, "docstring_loc": 8, "function_name": "forward_cuda", "class_name": "XDRotaryEmbedding", "qualname": "XDRotaryEmbedding.forward_cuda", "file_path": "vllm/model_executor/layers/rotary_embedding/xdrope.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runna... |
vllm-project/vllm:vllm/logprobs.py:FlatLogprobs.append | # Context:
class Logprob: ...
def create_prompt_logprobs(flat_logprobs: bool) -> PromptLogprobs: ...
def create_sample_logprobs(flat_logprobs: bool) -> SampleLogprobs: ...
def append_logprobs_for_next_position(request_logprobs: PromptLogprobs | SampleLogprobs, token_ids: list[int], logprobs: list[float], decoded_token... | def append(self, logprobs_one_position: LogprobsOnePosition | None) -> None:
"""Appends the container with logprobs for the next position"""
self.start_indices.append(len(self.logprobs))
if logprobs_one_position:
for token_id, logprob in logprobs_one_position.items():
... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 10, "code_loc": 8, "docstring_loc": 1, "function_name": "append", "class_name": "FlatLogprobs", "qualname": "FlatLogprobs.append", "file_path": "vllm/logprobs.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "file_runnable"} |
crewAIInc/crewAI:lib/crewai/tests/llms/test_multimodal.py:TestBedrockMultimodal.test_supports_multimodal_claude3 | # Context:
from crewai.llm import LLM
def mock_api_keys(): ...
class TestLiteLLMMultimodal: ...
class TestAnthropicMultimodal: ...
class TestOpenAIMultimodal: ...
class TestGeminiMultimodal: ...
class TestAzureMultimodal: ...
class TestBaseLLMMultimodal: ...
class TestMultipleFilesFormatting: ...
class TestBedrockMul... | def test_supports_multimodal_claude3(self) -> None:
"""Test Bedrock Claude 3 supports multimodal."""
llm = LLM(model="bedrock/anthropic.claude-3-sonnet")
assert llm.supports_multimodal() is True | test | 0 | {"function_name": "test_supports_multimodal_claude3", "class_name": "TestBedrockMultimodal", "qualname": "TestBedrockMultimodal.test_supports_multimodal_claude3", "file_path": "lib/crewai/tests/llms/test_multimodal.py", "repo_id": "crewAIInc/crewAI", "loc": 4, "tested_modules": ["crewai.llm", "crewai_files", "crewai.ll... |
apache/airflow:shared/secrets_backend/tests/secrets_backend/test_base.py:TestBaseSecretsBackend.test_get_variable_not_implemented | # Context:
import pytest
from airflow_shared.secrets_backend.base import BaseSecretsBackend
class MockConnection: ...
class _TestBackend(BaseSecretsBackend): ...
class TestBaseSecretsBackend:
def test_build_path_with_separator(self, prefix, secret_id, sep, expected): ...
def test_get_conn_value_not_implemente... | def test_get_variable_not_implemented(self):
backend = BaseSecretsBackend()
with pytest.raises(NotImplementedError):
backend.get_variable("test_var") | test | 1 | {"function_name": "test_get_variable_not_implemented", "class_name": "TestBaseSecretsBackend", "qualname": "TestBaseSecretsBackend.test_get_variable_not_implemented", "file_path": "shared/secrets_backend/tests/secrets_backend/test_base.py", "repo_id": "apache/airflow", "loc": 4, "tested_modules": ["__future__", "airflo... |
huggingface/diffusers:src/diffusers/models/transformers/transformer_chroma.py:ChromaAdaLayerNormZeroSinglePruned:class_doc | Write a class-level docstring for `ChromaAdaLayerNormZeroSinglePruned` (inherits from nn.Module) which has methods: `__init__`, `forward`. | Norm layer adaptive layer norm zero (adaLN-Zero).
Parameters:
embedding_dim (`int`): The size of each embedding vector.
num_embeddings (`int`): The size of the embeddings dictionary. | documentation | 1 | {"doc_type": "class", "class_name": "ChromaAdaLayerNormZeroSinglePruned", "file_path": "src/diffusers/models/transformers/transformer_chroma.py", "repo_id": "huggingface/diffusers", "char_length": 191, "methods": ["__init__", "forward"]} |
huggingface/transformers:tests/models/dinov3_vit/test_modeling_dinov3_vit.py:Dinov3ModelTest:class_doc | Write a class-level docstring for `Dinov3ModelTest` (inherits from ModelTesterMixin, PipelineTesterMixin, unittest.TestCase) which has methods: `setUp`, `test_backbone`, `test_config`, `test_inputs_embeds`, `test_model_get_set_embeddings`. | Here we also overwrite some of the tests of test_modeling_common.py, as Dinov3 does not use input_ids, inputs_embeds,
attention_mask and seq_length. | documentation | 0 | {"doc_type": "class", "class_name": "Dinov3ModelTest", "file_path": "tests/models/dinov3_vit/test_modeling_dinov3_vit.py", "repo_id": "huggingface/transformers", "char_length": 148, "methods": ["setUp", "test_backbone", "test_config", "test_inputs_embeds", "test_model_get_set_embeddings", "test_model", "test_feed_forwa... |
langchain-ai/langchain:libs/partners/anthropic/tests/unit_tests/middleware/test_file_search.py:TestFilesystemGrepSearch.test_grep_invalid_regex | # Context:
from langchain_anthropic.middleware.anthropic_tools import AnthropicToolsState
from langchain_anthropic.middleware.file_search import (
StateFileSearchMiddleware,
)
class TestSearchMiddlewareInitialization: ...
class TestGlobSearch: ...
class TestGrepSearch: ...
class TestSearchWithDifferentBackends: ..... | def test_grep_invalid_regex(self) -> None:
"""Test grep with invalid regex pattern."""
middleware = StateFileSearchMiddleware()
state: AnthropicToolsState = {
"messages": [],
"text_editor_files": {},
}
result = middleware._handle_grep_search(
... | test | 1 | {"function_name": "test_grep_invalid_regex", "class_name": "TestFilesystemGrepSearch", "qualname": "TestFilesystemGrepSearch.test_grep_invalid_regex", "file_path": "libs/partners/anthropic/tests/unit_tests/middleware/test_file_search.py", "repo_id": "langchain-ai/langchain", "loc": 19, "tested_modules": ["langchain_ant... |
vllm-project/vllm:vllm/kernels/helion/register.py:PresetConfigSearch:class_doc | Write a class-level docstring for `PresetConfigSearch` (inherits from BaseAutotuner) which has methods: `__init__`, `autotune`. | Custom autotuner that uses a preset config selector instead of autotuning. | documentation | 1 | {"doc_type": "class", "class_name": "PresetConfigSearch", "file_path": "vllm/kernels/helion/register.py", "repo_id": "vllm-project/vllm", "char_length": 74, "methods": ["__init__", "autotune"]} |
gradio-app/gradio:gradio/media.py:module_doc | Write a module-level docstring for the Python module `media` which contains function `_get_media_path`, function `get_image`, function `get_video`, function `get_audio`, function `get_model3d`. | Media Registry for Gradio Demos
This module provides a centralized way to access media files.
Usage:
from gradio.media import get_image, get_video, get_audio, get_model3d, get_file
# Get specific media files
cheetah_img = get_image("cheetah1.jpg")
world_video = get_video("world.mp4")
cantina_audi... | documentation | 1 | {"doc_type": "module", "module_name": "media", "file_path": "gradio/media.py", "repo_id": "gradio-app/gradio", "char_length": 559} |
apache/airflow:providers/apache/impala/tests/unit/apache/impala/hooks/test_impala_sql.py:test_get_url | # Context:
import json
from unittest.mock import MagicMock, patch
from sqlalchemy.engine.url import make_url
def mock_connection(create_connection_without_db) -> Connection: ...
def impala_hook() -> ImpalaHook: ...
def get_cursor_descriptions(fields: list[str]) -> list[tuple[str]]: ...
def test_sqlalchemy_url_property... | def test_get_url(impala_hook, mock_connection):
"""Ensure get_uri() returns correct formatted URI for Impala connection"""
mock_connection.host = "impala.company.com"
mock_connection.port = 21050
mock_connection.login = "user"
mock_connection.password = "secret"
mock_connection.schema = "analyt... | test | 1 | {"function_name": "test_get_url", "class_name": null, "qualname": "test_get_url", "file_path": "providers/apache/impala/tests/unit/apache/impala/hooks/test_impala_sql.py", "repo_id": "apache/airflow", "loc": 16, "tested_modules": ["__future__", "sqlalchemy.engine.url", "airflow.models", "airflow.providers.apache.impala... |
ray-project/ray:python/ray/_private/authentication/grpc_authentication_server_interceptor.py:AsyncAuthenticationServerInterceptor.intercept_service | # Context:
from typing import Awaitable, Callable
import grpc
def _authenticate_request(metadata: tuple) -> bool: ...
class SyncAuthenticationServerInterceptor(grpc.ServerInterceptor): ...
class AsyncAuthenticationServerInterceptor(aiogrpc.ServerInterceptor):
# Task:
Write a Python async method `intercept_service` f... | async def intercept_service(
self,
continuation: Callable[
[grpc.HandlerCallDetails], Awaitable[grpc.RpcMethodHandler]
],
handler_call_details: grpc.HandlerCallDetails,
) -> grpc.RpcMethodHandler:
"""Intercept service calls to validate authentication.
Thi... | function_complex | 0 | {"cognitive_complexity": 10, "loc": 94, "code_loc": 60, "docstring_loc": 5, "function_name": "intercept_service", "class_name": "AsyncAuthenticationServerInterceptor", "qualname": "AsyncAuthenticationServerInterceptor.intercept_service", "file_path": "python/ray/_private/authentication/grpc_authentication_server_interc... |
ray-project/ray:release/ray_release/tests/test_byod_build_context.py:test_decode_build_context | # Context:
from ray_release.byod.build_context import (
_INSTALL_PYTHON_DEPS_SCRIPT,
build_context_digest,
decode_build_context,
encode_build_context,
fill_build_context_dir,
make_build_context,
)
def test_make_build_context() -> None: ...
def test_make_build_context_partial() -> None: ...
def ... | def test_decode_build_context() -> None:
data = '{"envs":{"FOO":"bar"},"post_build_script":"build.sh"}'
ctx = decode_build_context(data)
assert ctx["envs"] == {"FOO": "bar"}
assert ctx["post_build_script"] == "build.sh" | test | 0 | {"function_name": "test_decode_build_context", "class_name": null, "qualname": "test_decode_build_context", "file_path": "release/ray_release/tests/test_byod_build_context.py", "repo_id": "ray-project/ray", "loc": 6, "tested_modules": ["ray_release.byod.build_context"], "has_docstring": false, "runnable_level": "projec... |
huggingface/transformers:tests/trainer/test_trainer_checkpointing.py:JITCheckpointTest.test_jit_checkpoint_callback_on_epoch_end | # Context:
from unittest.mock import Mock, patch
from transformers.trainer_jit_checkpoint import CheckpointManager, JITCheckpointCallback
class TrainerCheckpointSaveTest(TestCasePlus, TrainerIntegrationCommon): ...
class TrainerResumeTrainingTest(TestCasePlus, TrainerIntegrationCommon): ...
class TrainerAutoBatchSizeT... | def test_jit_checkpoint_callback_on_epoch_end(self):
"""Test callback behavior at epoch end."""
trainer = self.get_trainer()
callback = JITCheckpointCallback()
callback.set_trainer(trainer)
# Mock control object
control = Mock()
control.should_save = True
... | test | 0 | {"function_name": "test_jit_checkpoint_callback_on_epoch_end", "class_name": "JITCheckpointTest", "qualname": "JITCheckpointTest.test_jit_checkpoint_callback_on_epoch_end", "file_path": "tests/trainer/test_trainer_checkpointing.py", "repo_id": "huggingface/transformers", "loc": 31, "tested_modules": ["pathlib", "typing... |
crewAIInc/crewAI:lib/crewai/src/crewai/a2a/updates/push_notifications/handler.py:PushNotificationHandler.execute | # Context:
from a2a.client import Client
from a2a.client.errors import A2AClientHTTPError
from a2a.types import (
AgentCard,
Message,
Part,
Role,
TaskState,
TextPart,
)
from typing_extensions import Unpack
from crewai.a2a.task_helpers import (
TaskStateResult,
process_task_state,
sen... | async def execute(
client: Client,
message: Message,
new_messages: list[Message],
agent_card: AgentCard,
**kwargs: Unpack[PushNotificationHandlerKwargs],
) -> TaskStateResult:
"""Execute A2A delegation using push notifications for updates.
Args:
c... | function_complex | 0 | {"cognitive_complexity": 10, "loc": 180, "code_loc": 145, "docstring_loc": 15, "function_name": "execute", "class_name": "PushNotificationHandler", "qualname": "PushNotificationHandler.execute", "file_path": "lib/crewai/src/crewai/a2a/updates/push_notifications/handler.py", "repo_id": "crewAIInc/crewAI", "has_docstring... |
streamlit/streamlit:e2e_playwright/st_navigation_expanded_test.py:module_doc | Write a module-level docstring for the Python module `st_navigation_expanded_test` which contains function `test_expanded_int_shows_limited_pages_with_view_more_button`, function `test_expanded_int_view_button_expands_to_show_all_pages`, function `test_expanded_int_view_button_can_collapse_again`. | E2E tests for st.navigation with expanded parameter. | documentation | 1 | {"doc_type": "module", "module_name": "st_navigation_expanded_test", "file_path": "e2e_playwright/st_navigation_expanded_test.py", "repo_id": "streamlit/streamlit", "char_length": 52} |
sansan0/TrendRadar:mcp_server/tools/storage_sync.py:StorageSyncTools.__init__ | # Context:
from pathlib import Path
class StorageSyncTools:
def _load_config(self) -> dict: ...
def _get_storage_config(self) -> dict: ...
def _get_remote_config(self) -> dict: ...
def _has_remote_config(self) -> bool: ...
def _get_remote_backend(self): ...
def _get_local_data_dir(self) -> Path... | def __init__(self, project_root: str = None):
"""
初始化存储同步工具
Args:
project_root: 项目根目录
"""
if project_root:
self.project_root = Path(project_root)
else:
current_file = Path(__file__)
self.project_root = current_file.parent.p... | function_simple | 1 | {"cognitive_complexity": 2, "loc": 15, "code_loc": 7, "docstring_loc": 6, "function_name": "__init__", "class_name": "StorageSyncTools", "qualname": "StorageSyncTools.__init__", "file_path": "mcp_server/tools/storage_sync.py", "repo_id": "sansan0/TrendRadar", "has_docstring": true, "runnable_level": "class_runnable"} |
run-llama/llama_index:llama-index-integrations/embeddings/llama-index-embeddings-heroku/tests/test_heroku_embeddings.py:TestHerokuEmbedding.test_get_query_embedding | # Context:
from unittest.mock import MagicMock, patch
from llama_index.embeddings.heroku.base import HerokuEmbedding
def fixture_heroku_embedding() -> HerokuEmbedding: ...
def fixture_mock_response() -> MagicMock: ...
class TestHerokuEmbedding:
def test_class_name(self, heroku_embedding: HerokuEmbedding) -> None:... | def test_get_query_embedding(self, heroku_embedding: HerokuEmbedding) -> None:
"""Test query embedding."""
with patch.object(
heroku_embedding, "_get_text_embedding", return_value=[0.1, 0.2, 0.3]
):
embedding = heroku_embedding.get_query_embedding("test query")
... | test | 1 | {"function_name": "test_get_query_embedding", "class_name": "TestHerokuEmbedding", "qualname": "TestHerokuEmbedding.test_get_query_embedding", "file_path": "llama-index-integrations/embeddings/llama-index-embeddings-heroku/tests/test_heroku_embeddings.py", "repo_id": "run-llama/llama_index", "loc": 7, "tested_modules":... |
docling-project/docling:tests/test_asr_mlx_whisper.py:TestMlxWhisperIntegration.test_mlx_whisper_options_creation | # Context:
from docling.datamodel.accelerator_options import AcceleratorDevice, AcceleratorOptions
from docling.datamodel.pipeline_options_asr_model import (
InferenceAsrFramework,
InlineAsrMlxWhisperOptions,
)
class TestMlxWhisperIntegration:
def test_whisper_models_auto_select_mlx(self): ...
def test... | def test_mlx_whisper_options_creation(self):
"""Test that MLX Whisper options are created correctly."""
options = InlineAsrMlxWhisperOptions(
repo_id="mlx-community/whisper-tiny-mlx",
language="en",
task="transcribe",
)
assert options.inference_framew... | test | 1 | {"function_name": "test_mlx_whisper_options_creation", "class_name": "TestMlxWhisperIntegration", "qualname": "TestMlxWhisperIntegration.test_mlx_whisper_options_creation", "file_path": "tests/test_asr_mlx_whisper.py", "repo_id": "docling-project/docling", "loc": 14, "tested_modules": ["pathlib", "docling.datamodel.acc... |
infiniflow/ragflow:agent/sandbox/providers/e2b.py:E2BProvider.execute_code | # Context:
from .base import SandboxProvider, SandboxInstance, ExecutionResult
class E2BProvider(SandboxProvider):
def __init__(self):
self.api_key: str = ""
self.region: str = "us"
self.timeout: int = 30
self._initialized: bool = False
def initialize(self, config: Dict[str, Any... | def execute_code(
self,
instance_id: str,
code: str,
language: str,
timeout: int = 10
) -> ExecutionResult:
"""
Execute code in the E2B instance.
Args:
instance_id: ID of the sandbox instance
code: Source code to execute
... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 34, "code_loc": 7, "docstring_loc": 16, "function_name": "execute_code", "class_name": "E2BProvider", "qualname": "E2BProvider.execute_code", "file_path": "agent/sandbox/providers/e2b.py", "repo_id": "infiniflow/ragflow", "has_docstring": true, "runnable_level": "project_runnable"} |
ray-project/ray:python/ray/data/tests/test_with_column.py:test_with_column_mixed_udf_and_regular_expressions | # Context:
import pandas as pd
import pyarrow as pa
import pyarrow.compute as pc
import pytest
from pkg_resources import parse_version
import ray
from ray.data._internal.utils.arrow_utils import get_pyarrow_version
from ray.data.datatype import DataType
from ray.data.expressions import col, lit, udf
def test_with_colu... | def test_with_column_mixed_udf_and_regular_expressions(
ray_start_regular_shared, target_max_block_size_infinite_or_default
):
"""Test mixing UDF expressions and regular expressions in with_column operations."""
ds = ray.data.range(5)
# Define a UDF for testing
@udf(DataType.int64())
def multip... | test | 0 | {"function_name": "test_with_column_mixed_udf_and_regular_expressions", "class_name": null, "qualname": "test_with_column_mixed_udf_and_regular_expressions", "file_path": "python/ray/data/tests/test_with_column.py", "repo_id": "ray-project/ray", "loc": 37, "tested_modules": ["pkg_resources", "ray.data._internal.util", ... |
ray-project/ray:python/ray/llm/tests/serve/gpu/deployments/llm/vllm/test_config_congruence.py:test_vllm_config_ray_serve_vs_cli_comparison | # Context:
from unittest.mock import MagicMock, patch
import pytest
from vllm.platforms.interface import DeviceCapability
def setup_placement_group_cleanup(): ...
def deep_compare(dict1: Any, dict2: Any) -> bool: ...
async def normalize_parallel_config(config_dict: Dict[str, Any]) -> None: ...
def get_config_differenc... | async def test_vllm_config_ray_serve_vs_cli_comparison(
gpu_type: str, capability: DeviceCapability
):
with patch(
"vllm.platforms.cuda.NvmlCudaPlatform.get_device_capability",
return_value=capability,
):
ray_vllm_config = await get_ray_serve_llm_vllm_config()
cli_vllm_config... | test | 0 | {"function_name": "test_vllm_config_ray_serve_vs_cli_comparison", "class_name": null, "qualname": "test_vllm_config_ray_serve_vs_cli_comparison", "file_path": "python/ray/llm/tests/serve/gpu/deployments/llm/vllm/test_config_congruence.py", "repo_id": "ray-project/ray", "loc": 31, "tested_modules": ["typing", "vllm.conf... |
vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/vllm_v1_adapter.py:LMCacheConnectorV1Impl.start_load_kv | # Context:
import torch
class LoadSpec: ...
class SaveSpec: ...
class DisaggSpec: ...
def extract_request_configs(sampling_params: SamplingParams) -> dict | None: ...
class RequestTracker: ...
class ReqMeta: ...
def need_gpu_interm_buffer(lmcache_config: LMCacheEngineConfig): ...
def _calculate_mtp_layers(vllm_config,... | def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None:
"""Start loading the KV cache from the connector buffer to vLLM's
paged KV buffer.
Args:
forward_context (ForwardContext): the forward context.
Note:
The number of elements in kv_cache... | function_complex | 1 | {"cognitive_complexity": 18, "loc": 108, "code_loc": 78, "docstring_loc": 10, "function_name": "start_load_kv", "class_name": "LMCacheConnectorV1Impl", "qualname": "LMCacheConnectorV1Impl.start_load_kv", "file_path": "vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/vllm_v1_adapter.py", "repo_id": "vllm... |
browser-use/browser-use:browser_use/llm/oci_raw/chat.py:ChatOCIRaw._make_request | # Context:
import asyncio
from oci.generative_ai_inference.models import (
BaseChatRequest,
ChatDetails,
CohereChatRequest,
GenericChatRequest,
OnDemandServingMode,
)
from browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError
from browser_use.llm.messages import BaseMessage
from .serializer imp... | async def _make_request(self, messages: list[BaseMessage]):
"""Make async request to OCI API using proper OCI SDK models."""
# Create chat request based on provider type
if self._uses_cohere_format():
# Cohere models use CohereChatRequest with single message string
message_text = OCIRawMessageSerializer.se... | function_complex | 0 | {"cognitive_complexity": 11, "loc": 65, "code_loc": 43, "docstring_loc": 1, "function_name": "_make_request", "class_name": "ChatOCIRaw", "qualname": "ChatOCIRaw._make_request", "file_path": "browser_use/llm/oci_raw/chat.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "project_runnab... |
ray-project/ray:python/ray/tests/test_symmetric_run.py:test_symmetric_run_worker_node_behavior | # Context:
from unittest.mock import MagicMock, patch
from click.testing import CliRunner
from ray.scripts.symmetric_run import symmetric_run
def _setup_mock_network_utils(curr_ip, head_ip): ...
def cleanup_ray(): ...
def test_symmetric_run_basic_interface(monkeypatch, cleanup_ray): ...
def test_symmetric_run_arg_vali... | def test_symmetric_run_worker_node_behavior(monkeypatch, cleanup_ray):
"""Test symmetric_run behavior when not on the head node."""
from ray.scripts.symmetric_run import symmetric_run
runner = CliRunner()
with patch("subprocess.run") as mock_run:
mock_run.return_value.returncode = 0
w... | test | 0 | {"function_name": "test_symmetric_run_worker_node_behavior", "class_name": null, "qualname": "test_symmetric_run_worker_node_behavior", "file_path": "python/ray/tests/test_symmetric_run.py", "repo_id": "ray-project/ray", "loc": 45, "tested_modules": ["contextlib", "click.testing", "ray.scripts.symmetric_run", "ray.scri... |
docling-project/docling:tests/test_backend_image_native.py:test_crop_page_image_scaled | # Context:
from docling_core.types.doc import BoundingBox, CoordOrigin
from docling.backend.image_backend import ImageDocumentBackend, _ImagePageBackend
def _make_png_stream(width: int, height: int, color) -> DocumentStream: ...
def _make_multipage_tiff_stream(num_pages: int, size) -> DocumentStream: ...
def test_docs... | def test_crop_page_image_scaled():
"""Test cropping and scaling page image."""
width, height = 200, 150
scale = 0.5
stream = _make_png_stream(width=width, height=height)
doc_backend = _get_backend_from_stream(stream)
page_backend: _ImagePageBackend = doc_backend.load_page(0)
cropbox = Bound... | test | 1 | {"function_name": "test_crop_page_image_scaled", "class_name": null, "qualname": "test_crop_page_image_scaled", "file_path": "tests/test_backend_image_native.py", "repo_id": "docling-project/docling", "loc": 12, "tested_modules": ["io", "pathlib", "docling_core.types.doc", "PIL", "docling.backend.image_backend"], "has_... |
browser-use/browser-use:tests/ci/browser/test_navigation_slow_pages.py:TestHeavyPageNavigation.test_slow_server_response_completes | # Context:
import asyncio
import time
from browser_use.agent.service import Agent
from tests.ci.conftest import create_mock_llm
def heavy_page_server(): ...
def heavy_base_url(heavy_page_server): ...
async def browser_session(): ...
def _nav_actions(url: str, msg: str) -> list[str]: ...
class TestHeavyPageNavigation:... | async def test_slow_server_response_completes(self, browser_session, heavy_base_url):
"""Navigation succeeds even when server takes 6s to respond."""
url = f'{heavy_base_url}/slow-server-pdp'
agent = Agent(
task=f'Navigate to {url}',
llm=create_mock_llm(actions=_nav_actions(url)),
browser_session=browser... | test | 0 | {"function_name": "test_slow_server_response_completes", "class_name": "TestHeavyPageNavigation", "qualname": "TestHeavyPageNavigation.test_slow_server_response_completes", "file_path": "tests/ci/browser/test_navigation_slow_pages.py", "repo_id": "browser-use/browser-use", "loc": 13, "tested_modules": ["werkzeug", "bro... |
ray-project/ray:python/ray/data/tests/unit/test_transform_pyarrow.py:test_nested_struct_with_mixed_tensor_types | # Context:
import pyarrow as pa
import pytest
from ray.data._internal.arrow_ops.transform_pyarrow import (
MIN_PYARROW_VERSION_TYPE_PROMOTION,
_align_struct_fields,
concat,
hash_partition,
shuffle,
try_combine_chunked_columns,
unify_schemas,
)
from ray.data._internal.tensor_extensions.arrow ... | def test_nested_struct_with_mixed_tensor_types(
nested_struct_with_mixed_tensor_types_blocks,
nested_struct_with_mixed_tensor_types_expected,
):
"""Test nested structs with mixed tensor types at different levels."""
t1, t2 = nested_struct_with_mixed_tensor_types_blocks
t3 = concat([t1, t2])
as... | test | 0 | {"function_name": "test_nested_struct_with_mixed_tensor_types", "class_name": null, "qualname": "test_nested_struct_with_mixed_tensor_types", "file_path": "python/ray/data/tests/unit/test_transform_pyarrow.py", "repo_id": "ray-project/ray", "loc": 29, "tested_modules": ["typing", "ray.data._internal.arrow_ops.transform... |
Comfy-Org/ComfyUI:comfy_extras/nodes_dataset.py:ImageGridNode:class_doc | Write a class-level docstring for `ImageGridNode` (inherits from ImageProcessingNode) which has methods: `_group_process`. | Combine multiple images into a single grid/collage. | documentation | 1 | {"doc_type": "class", "class_name": "ImageGridNode", "file_path": "comfy_extras/nodes_dataset.py", "repo_id": "Comfy-Org/ComfyUI", "char_length": 51, "methods": ["_group_process"]} |
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/brave_search_tool/brave_search_tool.py:BraveSearchTool:class_doc | Write a class-level docstring for `BraveSearchTool` (inherits from BaseTool) which has methods: `__init__`, `_run`. | A tool that performs web searches using the Brave Search API. | documentation | 0 | {"doc_type": "class", "class_name": "BraveSearchTool", "file_path": "lib/crewai-tools/src/crewai_tools/tools/brave_search_tool/brave_search_tool.py", "repo_id": "crewAIInc/crewAI", "char_length": 61, "methods": ["__init__", "_run"]} |
streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_app_test.py:test_websocket_rejects_auth_cookie_without_valid_xsrf | # Context:
import json
from pathlib import Path
import pytest
from starlette.testclient import TestClient
from streamlit import file_util
from streamlit.web.server.starlette import starlette_app_utils
from streamlit.web.server.starlette.starlette_app import (
_RESERVED_ROUTE_PREFIXES,
App,
create_starlette_... | def test_websocket_rejects_auth_cookie_without_valid_xsrf(tmp_path: Path) -> None:
"""Test that auth cookies are not parsed without valid XSRF token."""
component_dir = tmp_path / "component"
component_dir.mkdir()
(component_dir / "index.html").write_text("component")
static_dir = tmp_path / "stati... | test | 1 | {"function_name": "test_websocket_rejects_auth_cookie_without_valid_xsrf", "class_name": null, "qualname": "test_websocket_rejects_auth_cookie_without_valid_xsrf", "file_path": "lib/tests/streamlit/web/server/starlette/starlette_app_test.py", "repo_id": "streamlit/streamlit", "loc": 46, "tested_modules": ["__future__",... |
ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/llm/test_llm_server.py:TestLLMServer.test_embedding_llm_server | # Context:
from typing import AsyncGenerator, Optional
import pytest
from ray.llm.tests.serve.utils.testing_utils import LLMResponseValidator
def serve_handle(mock_llm_config, stream_batching_interval_ms): ...
def multiplexed_serve_handle(mock_llm_config, stream_batching_interval_ms): ...
async def count_tpot_ms_from_... | async def test_embedding_llm_server(
self,
serve_handle,
mock_llm_config,
mock_embedding_request,
dimensions: Optional[int],
):
"""Test embedding API from LLMServer perspective."""
# Create embedding request
request = mock_embedding_request
p... | test | 0 | {"function_name": "test_embedding_llm_server", "class_name": "TestLLMServer", "qualname": "TestLLMServer.test_embedding_llm_server", "file_path": "python/ray/llm/tests/serve/cpu/deployments/llm/test_llm_server.py", "repo_id": "ray-project/ray", "loc": 27, "tested_modules": ["typing", "ray", "ray.llm._internal.serve.cor... |
ansible/ansible:test/units/_internal/_errors/test_alarm_timeout.py:test_alarm_timeout_bad_values | # Context:
import typing as t
import pytest
from ansible._internal._errors import _alarm_timeout
def assert_sigalrm_state() -> t.Iterator[None]: ...
def test_alarm_timeout_success(timeout: int | None) -> None: ...
def test_alarm_timeout_timeout() -> None: ...
def test_alarm_timeout_bad_state() -> None: ...
def test_al... | def test_alarm_timeout_bad_values(timeout: t.Any, expected_error_type: type[Exception], expected_error_pattern: str) -> None:
"""Validate behavior for invalid inputs."""
ran = False
with pytest.raises(expected_error_type, match=expected_error_pattern):
with _alarm_timeout.AnsibleTimeoutError.alarm_... | test | 1 | {"function_name": "test_alarm_timeout_bad_values", "class_name": null, "qualname": "test_alarm_timeout_bad_values", "file_path": "test/units/_internal/_errors/test_alarm_timeout.py", "repo_id": "ansible/ansible", "loc": 9, "tested_modules": ["__future__", "ansible._internal._errors", "ansible._internal._errors._alarm_t... |
run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_code_interpreter_spec.py:test_class | # Context:
from llama_index.core.tools.tool_spec.base import BaseToolSpec
from llama_index.tools.aws_bedrock_agentcore import AgentCoreCodeInterpreterToolSpec
# Task:
Write a Python test function `test_class` to verify the behavior of `class`.
Module under test: llama_index.core.tools.tool_spec.base, llama_index.tool... | def test_class():
names_of_base_classes = [
b.__name__ for b in AgentCoreCodeInterpreterToolSpec.__mro__
]
assert BaseToolSpec.__name__ in names_of_base_classes | test | 1 | {"function_name": "test_class", "class_name": null, "qualname": "test_class", "file_path": "llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_code_interpreter_spec.py", "repo_id": "run-llama/llama_index", "loc": 5, "tested_modules": ["llama_index.core.tools.tool_spec.base", "llama_index.... |
langflow-ai/langflow:src/backend/tests/unit/agentic/services/helpers/test_intent_classification.py:module_doc | Write a module-level docstring for the Python module `test_intent_classification` which contains class `TestClassifyIntent`, class `TestIntentResult`. | Tests for intent classification helper.
Tests the classify_intent function that translates text and
classifies user intent as component generation or question. | documentation | 1 | {"doc_type": "module", "module_name": "test_intent_classification", "file_path": "src/backend/tests/unit/agentic/services/helpers/test_intent_classification.py", "repo_id": "langflow-ai/langflow", "char_length": 160} |
crewAIInc/crewAI:lib/crewai/src/crewai/events/types/a2a_events.py:A2AServerTaskCanceledEvent:class_doc | Write a class-level docstring for `A2AServerTaskCanceledEvent` (inherits from A2AEventBase) which has methods: various methods. | Event emitted when an A2A server task execution is canceled.
Attributes:
task_id: A2A task ID for this execution.
context_id: A2A context ID grouping related tasks.
metadata: Custom A2A metadata key-value pairs. | documentation | 0 | {"doc_type": "class", "class_name": "A2AServerTaskCanceledEvent", "file_path": "lib/crewai/src/crewai/events/types/a2a_events.py", "repo_id": "crewAIInc/crewAI", "char_length": 224, "methods": []} |
ray-project/ray:python/ray/data/tests/unit/expressions/test_core.py:TestStarExpr.test_star_creation | # Context:
from ray.data.expressions import (
BinaryExpr,
ColumnExpr,
Expr,
LiteralExpr,
Operation,
StarExpr,
UDFExpr,
UnaryExpr,
col,
download,
lit,
star,
udf,
)
class TestColumnExpr: ...
class TestLiteralExpr: ...
class TestBinaryExpr: ...
class TestUnaryExpr: ...
... | def test_star_creation(self):
"""Test that star() creates a StarExpr."""
expr = star()
assert isinstance(expr, StarExpr) | test | 0 | {"function_name": "test_star_creation", "class_name": "TestStarExpr", "qualname": "TestStarExpr.test_star_creation", "file_path": "python/ray/data/tests/unit/expressions/test_core.py", "repo_id": "ray-project/ray", "loc": 4, "tested_modules": ["ray.data._internal.planner.plan_expression.expression_visitors", "ray.data.... |
streamlit/streamlit:lib/streamlit/web/server/starlette/starlette_routes.py:create_script_health_routes | # Context:
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute
from streamlit.runtime import Runtime
from starlette.responses import PlainTextResponse, Response
from starlette.routing import Route
from starlette.responses import FileResponse, Response
... | def create_script_health_routes(
runtime: Runtime, base_url: str | None
) -> list[BaseRoute]:
"""Create script health check route handlers."""
from starlette.responses import PlainTextResponse, Response
from starlette.routing import Route
async def _script_health_endpoint(request: Request) -> Plain... | function_simple | 1 | {"cognitive_complexity": 2, "loc": 34, "code_loc": 27, "docstring_loc": 1, "function_name": "create_script_health_routes", "class_name": null, "qualname": "create_script_health_routes", "file_path": "lib/streamlit/web/server/starlette/starlette_routes.py", "repo_id": "streamlit/streamlit", "has_docstring": true, "runna... |
langflow-ai/langflow:src/backend/tests/unit/groq/test_groq_constants.py:TestBackwardCompatibility.test_no_duplicates_in_groq_models_detailed | # Context:
from lfx.base.models.groq_constants import GROQ_MODELS_DETAILED
from lfx.base.models.groq_constants import GROQ_MODELS_DETAILED, GROQ_PRODUCTION_MODELS
from lfx.base.models.groq_constants import DEPRECATED_GROQ_MODELS, GROQ_MODELS_DETAILED
from lfx.base.models.groq_constants import GROQ_MODELS_DETAILED, UNSU... | def test_no_duplicates_in_groq_models_detailed(self):
"""Test that GROQ_MODELS_DETAILED has no duplicate model names."""
from lfx.base.models.groq_constants import GROQ_MODELS_DETAILED
model_names = [model["name"] for model in GROQ_MODELS_DETAILED]
assert len(model_names) == len(set(mod... | test | 1 | {"function_name": "test_no_duplicates_in_groq_models_detailed", "class_name": "TestBackwardCompatibility", "qualname": "TestBackwardCompatibility.test_no_duplicates_in_groq_models_detailed", "file_path": "src/backend/tests/unit/groq/test_groq_constants.py", "repo_id": "langflow-ai/langflow", "loc": 6, "tested_modules":... |
apache/airflow:providers/teradata/tests/unit/teradata/hooks/test_ttu.py:TestTtuHook.test_hook_context_manager | # Context:
from unittest import mock
from airflow.providers.teradata.hooks.ttu import TtuHook
class TestTtuHook:
def test_get_conn_with_valid_params(self, mock_get_connection): ...
def test_get_conn_missing_params(self, mock_get_connection): ...
def test_close_conn_subprocess_running(self, mock_get_connect... | def test_hook_context_manager(self, mock_enter, mock_exit):
# Setup
hook = TtuHook()
mock_enter.return_value = hook
# Execute
with hook as h:
assert h == hook
# Assert
mock_exit.assert_called_once()
# Ensure the exit method was called with th... | test | 1 | {"function_name": "test_hook_context_manager", "class_name": "TestTtuHook", "qualname": "TestTtuHook.test_hook_context_manager", "file_path": "providers/teradata/tests/unit/teradata/hooks/test_ttu.py", "repo_id": "apache/airflow", "loc": 18, "tested_modules": ["__future__", "airflow.providers.common.compat.sdk", "airfl... |
crewAIInc/crewAI:lib/crewai-tools/tests/tools/brightdata_webunlocker_tool_test.py:test_run_success_html | # Context:
from unittest.mock import Mock, patch
from crewai_tools.tools.brightdata_tool.brightdata_unlocker import (
BrightDataWebUnlockerTool,
)
def test_run_success_json(mock_post): ...
def test_run_http_error(mock_post): ...
# Task:
Write a Python test function `test_run_success_html` to verify the behavior o... | def test_run_success_html(mock_post):
mock_response = Mock()
mock_response.status_code = 200
mock_response.text = "<html><body>Test</body></html>"
mock_response.raise_for_status = Mock()
mock_post.return_value = mock_response
tool = BrightDataWebUnlockerTool()
tool._run(url="https://example... | test | 0 | {"function_name": "test_run_success_html", "class_name": null, "qualname": "test_run_success_html", "file_path": "lib/crewai-tools/tests/tools/brightdata_webunlocker_tool_test.py", "repo_id": "crewAIInc/crewAI", "loc": 9, "tested_modules": ["crewai_tools.tools.brightdata_tool.brightdata_unlocker"], "has_docstring": fal... |
browser-use/browser-use:tests/ci/test_fallback_llm.py:TestFallbackLLMParameter.test_public_properties | # Context:
from browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError
from browser_use import Agent
def create_mock_llm(model_name: str, should_fail: bool, fail_with: type[Exception] | None, fail_status_code: int, fail_message: str) -> BaseChatModel: ...
class TestFallbackLLMSwitching: ...
class Te... | def test_public_properties(self):
"""Test the public properties for fallback status."""
from browser_use import Agent
primary = create_mock_llm('primary-model')
fallback = create_mock_llm('fallback-model')
agent = Agent(task='Test task', llm=primary, fallback_llm=fallback)
# Before fallback
assert agen... | test | 0 | {"function_name": "test_public_properties", "class_name": "TestFallbackLLMParameter", "qualname": "TestFallbackLLMParameter.test_public_properties", "file_path": "tests/ci/test_fallback_llm.py", "repo_id": "browser-use/browser-use", "loc": 20, "tested_modules": ["browser_use.agent.views", "browser_use.llm", "browser_us... |
vllm-project/vllm:vllm/utils/gc_utils.py:_compute_detailed_type | # Context:
from contextlib import suppress
from typing import Any
class GCDebugConfig: ...
class GCDebugger: ...
def freeze_gc_heap() -> None: ...
def maybe_attach_gc_debug_callback() -> None: ...
def _compute_top_gc_collected_objects(objects: list[Any], top: int) -> str: ...
# Task:
Write a Python function `_compute... | def _compute_detailed_type(o: Any) -> str:
"""
Detailed object type.
TODO(Jialin): Further enhance the detailed type with element types for
easier debugging. We tried but occasionally it would run into signals
which kills the engine.
"""
size_str: str = ""
# Object doesn't support len()... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 14, "code_loc": 4, "docstring_loc": 7, "function_name": "_compute_detailed_type", "class_name": null, "qualname": "_compute_detailed_type", "file_path": "vllm/utils/gc_utils.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "slib_runnable"} |
langflow-ai/langflow:src/lfx/tests/unit/inputs/test_model_input_fixes.py:TestModelInputPortVisibility.test_default_language_model_input_types | # Context:
from lfx.inputs.inputs import ModelInput
class TestModelInputValueNormalization: ...
class TestUnifiedModelsDefaults: ...
class TestModelInputRefreshButton: ...
class TestModelInputEmbeddingType: ...
class TestModelInputPortVisibility:
def test_default_embedding_model_input_types(self): ...
def tes... | def test_default_language_model_input_types(self):
"""By default, ModelInput should have input_types=['LanguageModel'] for language models."""
model_input = ModelInput(name="test_model")
assert model_input.input_types == ["LanguageModel"] | test | 1 | {"function_name": "test_default_language_model_input_types", "class_name": "TestModelInputPortVisibility", "qualname": "TestModelInputPortVisibility.test_default_language_model_input_types", "file_path": "src/lfx/tests/unit/inputs/test_model_input_fixes.py", "repo_id": "langflow-ai/langflow", "loc": 4, "tested_modules"... |
crewAIInc/crewAI:lib/crewai/tests/cli/triggers/test_main.py:TestTriggersCommand.test_execute_with_trigger_invalid_format | # Context:
from unittest.mock import Mock, patch
class TestTriggersCommand(unittest.TestCase):
def setUp(self, mock_plus_api, mock_get_auth_token): ...
def test_list_triggers_success(self, mock_console_print): ...
def test_list_triggers_no_apps(self, mock_console_print): ...
def test_list_triggers_api_... | def test_execute_with_trigger_invalid_format(self, mock_console_print):
with self.assertRaises(SystemExit):
self.triggers_command.execute_with_trigger("invalid-format")
mock_console_print.assert_called_with(
"[bold red]Error: Trigger must be in format 'app_slug/trigger_slug'[/bo... | test | 0 | {"function_name": "test_execute_with_trigger_invalid_format", "class_name": "TestTriggersCommand", "qualname": "TestTriggersCommand.test_execute_with_trigger_invalid_format", "file_path": "lib/crewai/tests/cli/triggers/test_main.py", "repo_id": "crewAIInc/crewAI", "loc": 7, "tested_modules": ["crewai.cli.triggers.main"... |
ray-project/ray:release/ray_release/tests/test_custom_byod_build_init_helper.py:test_get_step_name | # Context:
from ray_release.custom_byod_build_init_helper import (
_get_step_name,
create_custom_build_yaml,
generate_custom_build_step_key,
get_prerequisite_step,
)
def test_create_custom_build_yaml(mock_get_images_from_tests): ...
def test_get_prerequisite_step(): ...
# Task:
Write a Python test fun... | def test_get_step_name():
test_names = [
"test_1",
"test_2",
"test_3",
]
assert (
_get_step_name(
"ray-project/ray-ml:a1b2c3d4-py39-cpu-abcdef123456789abc123456789",
"abc123",
test_names,
)
== ":tapioca: build custom: ray-ml... | test | 0 | {"function_name": "test_get_step_name", "class_name": null, "qualname": "test_get_step_name", "file_path": "release/ray_release/tests/test_custom_byod_build_init_helper.py", "repo_id": "ray-project/ray", "loc": 14, "tested_modules": ["ray_release.bazel", "ray_release.configs.global_config", "ray_release.custom_byod_bui... |
langflow-ai/langflow:src/backend/base/langflow/api/v2/workflow.py:check_developer_api_enabled | # Context:
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, status
from lfx.services.deps import get_settings_service, injectable_session_scope_readonly
async def execute_workflow(workflow_request: WorkflowExecutionRequest, background_tasks: BackgroundTasks, http_request: Request... | def check_developer_api_enabled() -> None:
"""Check if developer API is enabled.
This dependency function protects all workflow endpoints by verifying that
the developer API feature is enabled in the application settings.
Raises:
HTTPException: 403 Forbidden if developer_api_enabled setting is... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 22, "code_loc": 10, "docstring_loc": 11, "function_name": "check_developer_api_enabled", "class_name": null, "qualname": "check_developer_api_enabled", "file_path": "src/backend/base/langflow/api/v2/workflow.py", "repo_id": "langflow-ai/langflow", "has_docstring": true, "runnable_leve... |
crewAIInc/crewAI:lib/crewai/tests/utilities/test_prompts_no_thought_leakage.py:TestNoThoughtLeakagePatterns.test_no_job_depends_on_it_in_native_task | # Context:
from unittest.mock import MagicMock
from crewai.utilities.prompts import Prompts
class TestNoToolsPromptGeneration: ...
class TestRealLLMNoThoughtLeakage: ...
class TestNoThoughtLeakagePatterns:
def test_no_job_depends_on_it_in_no_tools(self) -> None: ...
# Task:
Write a Python test method `test_no_jo... | def test_no_job_depends_on_it_in_native_task(self) -> None:
"""Test that 'your job depends on it' is not in native task prompts."""
mock_agent = MagicMock()
mock_agent.role = "Test"
mock_agent.goal = "Test"
mock_agent.backstory = "Test"
prompts = Prompts(
has... | test | 0 | {"function_name": "test_no_job_depends_on_it_in_native_task", "class_name": "TestNoThoughtLeakagePatterns", "qualname": "TestNoThoughtLeakagePatterns.test_no_job_depends_on_it_in_native_task", "file_path": "lib/crewai/tests/utilities/test_prompts_no_thought_leakage.py", "repo_id": "crewAIInc/crewAI", "loc": 18, "tested... |
crewAIInc/crewAI:lib/crewai/tests/llms/hooks/test_unsupported_providers.py:TestBedrockProviderInterceptor.test_bedrock_without_interceptor_works | # Context:
from crewai.llm import LLM
def setup_provider_api_keys(monkeypatch): ...
class DummyInterceptor(BaseInterceptor[httpx.Request, httpx.Response]): ...
class TestAzureProviderInterceptor: ...
class TestGeminiProviderInterceptor: ...
class TestUnsupportedProviderMessages: ...
class TestProviderSupportMatrix: ..... | def test_bedrock_without_interceptor_works(self) -> None:
"""Test that Bedrock LLM works without interceptor."""
llm = LLM(
model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
aws_access_key_id="test-access-key",
aws_secret_access_key="test-secret-key",
... | test | 0 | {"function_name": "test_bedrock_without_interceptor_works", "class_name": "TestBedrockProviderInterceptor", "qualname": "TestBedrockProviderInterceptor.test_bedrock_without_interceptor_works", "file_path": "lib/crewai/tests/llms/hooks/test_unsupported_providers.py", "repo_id": "crewAIInc/crewAI", "loc": 11, "tested_mod... |
vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/nixl_connector.py:NixlConnectorWorker._pop_done_transfers | # Context:
class NixlAgentMetadata: ...
class NixlHandshakePayload(KVConnectorHandshakeMetadata): ...
def compute_nixl_compatibility_hash(vllm_config: VllmConfig, attn_backend_name: str, cross_layers_blocks: bool) -> str: ...
class RemoteMeta: ...
class ReqMeta: ...
class NixlConnectorMetadata(KVConnectorMetadata): ..... | def _pop_done_transfers(self, transfers: dict[str, list[int]]) -> set[str]:
"""
Pop completed xfers by checking for DONE state.
Args:
transfers: dict of req_id -> list[running_xfer]
Returns:
set of req_ids that have all done xfers
"""
done_req_ids:... | function_complex | 1 | {"cognitive_complexity": 13, "loc": 46, "code_loc": 35, "docstring_loc": 7, "function_name": "_pop_done_transfers", "class_name": "NixlConnectorWorker", "qualname": "NixlConnectorWorker._pop_done_transfers", "file_path": "vllm/distributed/kv_transfer/kv_connector/v1/nixl_connector.py", "repo_id": "vllm-project/vllm", "... |
google/langextract:langextract/prompting.py:ContextAwarePromptBuilder._build_effective_context | # Context:
class PromptBuilderError(exceptions.LangExtractError): ...
class ParseError(PromptBuilderError): ...
class PromptTemplateStructured: ...
def read_prompt_template_structured_from_file(prompt_path: str, format_type: data.FormatType) -> PromptTemplateStructured: ...
class QAPromptGenerator: ...
class PromptBui... | def _build_effective_context(
self,
document_id: str,
additional_context: str | None,
) -> str | None:
"""Combines previous chunk context with any additional context.
Args:
document_id: Identifier for the source document.
additional_context: Optional additional context from the ... | function_simple | 1 | {"cognitive_complexity": 4, "loc": 25, "code_loc": 8, "docstring_loc": 9, "function_name": "_build_effective_context", "class_name": "ContextAwarePromptBuilder", "qualname": "ContextAwarePromptBuilder._build_effective_context", "file_path": "langextract/prompting.py", "repo_id": "google/langextract", "has_docstring": t... |
666ghj/BettaFish:ReportEngine/ir/validator.py:IRValidator._validate_block | # Context:
from typing import Any, Dict, List, Tuple
from .schema import (
ALLOWED_BLOCK_TYPES,
ALLOWED_INLINE_MARKS,
ENGINE_AGENT_TITLES,
IR_VERSION,
)
class IRValidator:
def __init__(self, schema_version: str = IR_VERSION):
"""记录当前Schema版本,便于未来多版本并存"""
self.schema_version = schema... | def _validate_block(self, block: Any, path: str, errors: List[str]):
"""根据block类型调用不同的校验器"""
if not isinstance(block, dict):
errors.append(f"{path} 必须是对象")
return
block_type = block.get("type")
if block_type not in ALLOWED_BLOCK_TYPES:
errors.append(f... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 14, "code_loc": 10, "docstring_loc": 1, "function_name": "_validate_block", "class_name": "IRValidator", "qualname": "IRValidator._validate_block", "file_path": "ReportEngine/ir/validator.py", "repo_id": "666ghj/BettaFish", "has_docstring": true, "runnable_level": "project_runnable"} |
run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-serpex/tests/test_serpex.py:test_search_no_results | # Context:
from unittest.mock import MagicMock, patch
from llama_index.tools.serpex import SerpexToolSpec
def test_serpex_init_with_key(): ...
def test_serpex_init_with_custom_engine(): ...
def test_serpex_init_without_key(): ...
def test_search(mock_get): ...
def test_search_with_engine(mock_get): ...
def test_search... | def test_search_no_results(mock_get):
"""Test search with no results."""
mock_response = MagicMock()
mock_response.json.return_value = {
"results": [],
"metadata": {
"number_of_results": 0,
"response_time": 50,
},
}
mock_response.raise_for_status = Mag... | test | 1 | {"function_name": "test_search_no_results", "class_name": null, "qualname": "test_search_no_results", "file_path": "llama-index-integrations/tools/llama-index-tools-serpex/tests/test_serpex.py", "repo_id": "run-llama/llama_index", "loc": 17, "tested_modules": ["llama_index.tools.serpex"], "has_docstring": true, "runnab... |
huggingface/transformers:src/transformers/models/sam3/modeling_sam3.py:Sam3DotProductScoring._pool_text_features | # Context:
import torch
class Sam3VisionEncoderOutput(BaseModelOutputWithPooling): ...
class Sam3GeometryEncoderOutput(ModelOutput): ...
class Sam3DETREncoderOutput(ModelOutput): ...
class Sam3DETRDecoderOutput(ModelOutput): ...
class Sam3MaskDecoderOutput(ModelOutput): ...
class Sam3ImageSegmentationOutput(ModelOutpu... | def _pool_text_features(self, text_features: torch.Tensor, text_mask: torch.Tensor | None) -> torch.Tensor:
"""
Mean pool text features, accounting for padding.
Args:
text_features: [batch_size, seq_len, hidden_size]
text_mask: [batch_size, seq_len] where True indicates ... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 24, "code_loc": 6, "docstring_loc": 10, "function_name": "_pool_text_features", "class_name": "Sam3DotProductScoring", "qualname": "Sam3DotProductScoring._pool_text_features", "file_path": "src/transformers/models/sam3/modeling_sam3.py", "repo_id": "huggingface/transformers", "has_doc... |
browser-use/browser-use:browser_use/actor/page.py:Page.mouse | # Context:
from .mouse import Mouse
class Page:
def __init__(
self, browser_session: 'BrowserSession', target_id: str, session_id: str | None = None, llm: 'BaseChatModel | None' = None
):
self._browser_session = browser_session
self._client = browser_session.cdp_client
self._target_id = target_id
self._ses... | async def mouse(self) -> 'Mouse':
"""Get the mouse interface for this target."""
if not self._mouse:
session_id = await self._ensure_session()
from .mouse import Mouse
self._mouse = Mouse(self._browser_session, session_id, self._target_id)
return self._mouse | function_simple | 0 | {"cognitive_complexity": 1, "loc": 8, "code_loc": 5, "docstring_loc": 1, "function_name": "mouse", "class_name": "Page", "qualname": "Page.mouse", "file_path": "browser_use/actor/page.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "project_runnable"} |
browser-use/browser-use:tests/ci/test_action_loop_detection.py:test_navigate_different_domain_different_hash | # 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_navigate_different_domain_different_hash():
"""Navigate to different domains produces different hashes."""
h1 = compute_action_hash('navigate', {'url': 'https://example.com/page1'})
h2 = compute_action_hash('navigate', {'url': 'https://other.com/page1'})
assert h1 != h2 | test | 0 | {"function_name": "test_navigate_different_domain_different_hash", "class_name": null, "qualname": "test_navigate_different_domain_different_hash", "file_path": "tests/ci/test_action_loop_detection.py", "repo_id": "browser-use/browser-use", "loc": 5, "tested_modules": ["browser_use.agent.service", "browser_use.agent.vi... |
fastapi/fastapi:tests/test_request_params/test_header/test_optional_list.py:test_optional_list_validation_alias_by_name | # Context:
import pytest
from fastapi.testclient import TestClient
async def read_optional_list_str(p: Annotated[list[str] | None, Header()]): ...
class HeaderModelOptionalListStr(BaseModel): ...
async def read_model_optional_list_str(p: Annotated[HeaderModelOptionalListStr, Header()]): ...
def test_optional_list_str_... | def test_optional_list_validation_alias_by_name(path: str):
client = TestClient(app)
response = client.get(path, headers=[("p", "hello"), ("p", "world")])
assert response.status_code == 200
assert response.json() == {"p": None} | test | 1 | {"function_name": "test_optional_list_validation_alias_by_name", "class_name": null, "qualname": "test_optional_list_validation_alias_by_name", "file_path": "tests/test_request_params/test_header/test_optional_list.py", "repo_id": "fastapi/fastapi", "loc": 5, "tested_modules": ["typing", "fastapi", "fastapi.testclient"... |
crewAIInc/crewAI:lib/crewai/src/crewai/a2a/errors.py:A2APollingTimeoutError:class_doc | Write a class-level docstring for `A2APollingTimeoutError` (inherits from A2AClientTimeoutError) which has methods: various methods. | Raised when polling exceeds the configured timeout. | documentation | 0 | {"doc_type": "class", "class_name": "A2APollingTimeoutError", "file_path": "lib/crewai/src/crewai/a2a/errors.py", "repo_id": "crewAIInc/crewAI", "char_length": 51, "methods": []} |
langchain-ai/langchain:libs/partners/anthropic/tests/unit_tests/middleware/test_anthropic_tools.py:TestPathValidation.test_basic_path_normalization | # Context:
from langchain_anthropic.middleware.anthropic_tools import (
AnthropicToolsState,
StateClaudeMemoryMiddleware,
StateClaudeTextEditorMiddleware,
_validate_path,
)
class TestTextEditorMiddleware: ...
class TestMemoryMiddleware: ...
class TestFileOperations: ...
class TestSystemMessageHandling:... | def test_basic_path_normalization(self) -> None:
"""Test basic path normalization."""
assert _validate_path("/foo/bar") == "/foo/bar"
assert _validate_path("foo/bar") == "/foo/bar"
assert _validate_path("/foo//bar") == "/foo/bar"
assert _validate_path("/foo/./bar") == "/foo/bar" | test | 1 | {"function_name": "test_basic_path_normalization", "class_name": "TestPathValidation", "qualname": "TestPathValidation.test_basic_path_normalization", "file_path": "libs/partners/anthropic/tests/unit_tests/middleware/test_anthropic_tools.py", "repo_id": "langchain-ai/langchain", "loc": 6, "tested_modules": ["langchain_... |
crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/gemini/completion.py:GeminiCompletion.get_file_uploader | # Context:
from typing import TYPE_CHECKING, Any, Literal, cast
from crewai_files.uploaders.gemini import GeminiFileUploader
class GeminiCompletion(BaseLLM):
def __init__(
self,
model: str = "gemini-2.0-flash-001",
api_key: str | None = None,
project: str | None = None,
loca... | def get_file_uploader(self) -> Any:
"""Get a Gemini file uploader using this LLM's client.
Returns:
GeminiFileUploader instance with pre-configured client.
"""
try:
from crewai_files.uploaders.gemini import GeminiFileUploader
return GeminiFileUploade... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 12, "code_loc": 5, "docstring_loc": 5, "function_name": "get_file_uploader", "class_name": "GeminiCompletion", "qualname": "GeminiCompletion.get_file_uploader", "file_path": "lib/crewai/src/crewai/llms/providers/gemini/completion.py", "repo_id": "crewAIInc/crewAI", "has_docstring": tr... |
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/adapters/enterprise_adapter.py:EnterpriseActionTool._create_field_definition | # Context:
from typing import Any, Literal, Optional, Union, _SpecialForm, cast, get_origin
from pydantic import Field, create_model
def get_enterprise_api_base_url() -> str: ...
class EnterpriseActionKitToolAdapter: ...
class EnterpriseActionTool(BaseTool):
def __init__(
self,
name: str,
... | def _create_field_definition(
self, field_type: type[Any] | _SpecialForm, is_required: bool, description: str
) -> tuple:
"""Create Pydantic field definition based on type and requirement."""
if is_required:
return (field_type, Field(description=description))
if get_origi... | function_simple | 0 | {"cognitive_complexity": 2, "loc": 12, "code_loc": 8, "docstring_loc": 1, "function_name": "_create_field_definition", "class_name": "EnterpriseActionTool", "qualname": "EnterpriseActionTool._create_field_definition", "file_path": "lib/crewai-tools/src/crewai_tools/adapters/enterprise_adapter.py", "repo_id": "crewAIInc... |
ray-project/ray:python/ray/data/tests/test_join.py:test_anti_join_multi_key | # Context:
import pandas as pd
import pytest
import ray
from ray.data._internal.util import MiB, rows_same
from ray.data.context import DataContext
from ray.data.dataset import Dataset
from ray.data._internal.util import MiB
def test_simple_inner_join(ray_start_regular_shared_2_cpus, num_rows_left: int, num_rows_right... | def test_anti_join_multi_key(
ray_start_regular_shared_2_cpus,
join_type,
):
"""Test anti-join with multiple join keys"""
DataContext.get_current().target_max_block_size = 1 * MiB
# Create left dataset using ray.data.range for consistency
left_ds = ray.data.range(32).map(
lambda row: {
... | test | 0 | {"function_name": "test_anti_join_multi_key", "class_name": null, "qualname": "test_anti_join_multi_key", "file_path": "python/ray/data/tests/test_join.py", "repo_id": "ray-project/ray", "loc": 62, "tested_modules": ["typing", "packaging.version", "ray.data._internal.logical.operators", "ray.data._internal.util", "ray.... |
vllm-project/vllm:tests/models/language/pooling/test_mm_classifier_conversion.py:test_idefics_multimodal | # Context:
def update_config(config): ...
def test_gemma_multimodal(vllm_runner) -> None: ...
# Task:
Write a Python test function `test_idefics_multimodal` to verify the behavior of `idefics_multimodal`.
Module under test: vllm.config.pooler | def test_idefics_multimodal(
vllm_runner,
) -> None:
prompts = [
"Hello, my name is",
"The president of the United States is",
"The capital of France is",
"The future of AI is",
]
with vllm_runner(
model_name="HuggingFaceM4/Idefics3-8B-Llama3",
runner="po... | test | 1 | {"function_name": "test_idefics_multimodal", "class_name": null, "qualname": "test_idefics_multimodal", "file_path": "tests/models/language/pooling/test_mm_classifier_conversion.py", "repo_id": "vllm-project/vllm", "loc": 25, "tested_modules": ["vllm.config.pooler"], "has_docstring": false, "runnable_level": "project_r... |
crewAIInc/crewAI:lib/crewai/tests/hooks/test_human_approval.py:TestLLMHookHumanInput.test_request_human_input_pauses_and_resumes_live_updates | # Context:
from unittest.mock import Mock, patch
from crewai.hooks.llm_hooks import LLMCallHookContext
def mock_executor(): ...
def mock_tool(): ...
def mock_agent(): ...
def mock_task(): ...
class TestToolHookHumanInput: ...
class TestApprovalHookIntegration: ...
class TestCostControlApproval: ...
class TestLLMHookH... | def test_request_human_input_pauses_and_resumes_live_updates(
self, mock_event_listener, mock_input, mock_executor
):
"""Test that live updates are paused and resumed."""
mock_formatter = Mock()
mock_event_listener.formatter = mock_formatter
context = LLMCallHookContext(exec... | test | 0 | {"function_name": "test_request_human_input_pauses_and_resumes_live_updates", "class_name": "TestLLMHookHumanInput", "qualname": "TestLLMHookHumanInput.test_request_human_input_pauses_and_resumes_live_updates", "file_path": "lib/crewai/tests/hooks/test_human_approval.py", "repo_id": "crewAIInc/crewAI", "loc": 16, "test... |
infiniflow/ragflow:common/data_source/utils.py:run_with_timeout | # Context:
import contextvars
from collections.abc import Callable, Generator, Iterator, Mapping, Sequence
from typing import IO, Any, Generic, Iterable, Optional, Protocol, TypeVar, cast
def datetime_from_string(datetime_string: str) -> datetime: ...
def is_valid_image_type(mime_type: str) -> bool: ...
def _handle_ht... | def run_with_timeout(timeout: float, func: Callable[..., R], *args: Any, **kwargs: Any) -> R:
"""
Executes a function with a timeout. If the function doesn't complete within the specified
timeout, raises TimeoutError.
"""
context = contextvars.copy_context()
task = TimeoutThread(timeout, context... | function_simple | 1 | {"cognitive_complexity": 2, "loc": 16, "code_loc": 9, "docstring_loc": 4, "function_name": "run_with_timeout", "class_name": null, "qualname": "run_with_timeout", "file_path": "common/data_source/utils.py", "repo_id": "infiniflow/ragflow", "has_docstring": true, "runnable_level": "file_runnable"} |
run-llama/llama_index:llama-index-integrations/agent/llama-index-agent-agentmesh/llama_index/agent/agentmesh/trust.py:DelegationChain.add_delegation | # Context:
import json
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional
from llama_index.agent.agentmesh.identity import CMVKIdentity, CMVKSignature
class TrustPolicy: ...
class TrustVerificationResult: ...
class TrustedAgentCard: ...
class TrustHandshake: ...
class Deleg... | def add_delegation(
self,
delegatee: TrustedAgentCard,
capabilities: List[str],
expires_in_hours: Optional[int] = None,
delegator_identity: Optional[CMVKIdentity] = None,
) -> Delegation:
"""Add a delegation to the chain."""
if not delegatee.identity:
... | function_simple | 1 | {"cognitive_complexity": 4, "loc": 41, "code_loc": 27, "docstring_loc": 1, "function_name": "add_delegation", "class_name": "DelegationChain", "qualname": "DelegationChain.add_delegation", "file_path": "llama-index-integrations/agent/llama-index-agent-agentmesh/llama_index/agent/agentmesh/trust.py", "repo_id": "run-lla... |
ray-project/ray:release/nightly_tests/dataset/model_inference_pipeline_benchmark.py:module_doc | Write a module-level docstring for the Python module `model_inference_pipeline_benchmark` which contains class `WorkerConfig`, class `PipelineConfig`, function `parse_args`, function `preprocessing_task_pandas`, class `InferenceActor`. | Model Inference Pipeline Benchmark
This benchmark mimics a production ML inference pipeline with the following structure:
1. Read parquet data with configurable columns
2. Preprocessing with map_batches (CPU tasks) using Pandas
3. Inference with map_batches using actors (GPU) with concurrency control
4. Consume output... | documentation | 0 | {"doc_type": "module", "module_name": "model_inference_pipeline_benchmark", "file_path": "release/nightly_tests/dataset/model_inference_pipeline_benchmark.py", "repo_id": "ray-project/ray", "char_length": 501} |
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/common/ikeys.py:IPublicKey.IsValidPoint | # Context:
from .ipoint import IPoint
class IPrivateKey(ABC): ...
class IPublicKey(ABC):
def FromBytes(cls, key_bytes: bytes) -> IPublicKey: ...
def FromPoint(cls, key_point: IPoint) -> IPublicKey: ...
def CurveType() -> EllipticCurveTypes: ...
def IsValidBytes(cls, key_bytes: bytes) -> bool: ...
... | def IsValidPoint(cls,
key_point: IPoint) -> bool:
"""
Return if the specified point represents a valid public key.
Args:
key_point (IPoint object): Key point
Returns:
bool: True if valid, false otherwise
"""
try:
... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 16, "code_loc": 5, "docstring_loc": 9, "function_name": "IsValidPoint", "class_name": "IPublicKey", "qualname": "IPublicKey.IsValidPoint", "file_path": "python/ccxt/static_dependencies/bip/ecc/common/ikeys.py", "repo_id": "ccxt/ccxt", "has_docstring": true, "runnable_level": "project_... |
huggingface/transformers:tests/models/sam2_video/test_modeling_sam2_video.py:Sam2VideoModelIntegrationTest.test_inference_mask_generation_video_multi_objects_multi_points | # Context:
from transformers.testing_utils import (
backend_empty_cache,
is_torch_bf16_available_on_device,
is_torch_fp16_available_on_device,
slow,
torch_device,
)
import torch
def prepare_image(): ...
def prepare_groceries_image(): ...
def prepare_dog_img(): ...
def prepare_video(): ...
class Sa... | def test_inference_mask_generation_video_multi_objects_multi_points(self):
raw_video = prepare_video()
inference_session = self.processor.init_video_session(video=raw_video, inference_device=torch_device)
ann_frame_idx = 0 # the frame index we interact with
ann_obj_ids = [2, 3] # give ... | test | 0 | {"function_name": "test_inference_mask_generation_video_multi_objects_multi_points", "class_name": "Sam2VideoModelIntegrationTest", "qualname": "Sam2VideoModelIntegrationTest.test_inference_mask_generation_video_multi_objects_multi_points", "file_path": "tests/models/sam2_video/test_modeling_sam2_video.py", "repo_id": ... |
Textualize/textual:src/textual/compose.py:compose | # Context:
from textual.app import App, ComposeResult
from textual.widget import Widget
from textual.widget import MountError, Widget
# Task:
Write a Python function `compose` to compose child widgets from a generator in the same way as [compose][textual.widget.Widget.compose].
Parameters: node: App | Widget, compose... | def compose(
node: App | Widget, compose_result: ComposeResult | None = None
) -> list[Widget]:
"""Compose child widgets from a generator in the same way as [compose][textual.widget.Widget.compose].
Example:
```python
def on_key(self, event:events.Key) -> None:
def add_... | function_complex | 1 | {"cognitive_complexity": 34, "loc": 88, "code_loc": 56, "docstring_loc": 23, "function_name": "compose", "class_name": null, "qualname": "compose", "file_path": "src/textual/compose.py", "repo_id": "Textualize/textual", "has_docstring": true, "runnable_level": "project_runnable"} |
vllm-project/vllm:tests/kernels/test_fla_layernorm_guard.py:test_layer_norm_fwd_with_groups | # Context:
import pytest
import torch
from vllm.model_executor.layers.fla.ops.layernorm_guard import (
layer_norm_fwd,
layernorm_fn,
rms_norm_ref,
)
from vllm.utils.torch_utils import set_random_seed
def layer_norm_ref(x, weight, bias, z, eps, group_size, norm_before_gate, is_rms_norm): ...
def test_layer_... | def test_layer_norm_fwd_with_groups(
num_tokens: int,
hidden_size: int,
group_size: int,
dtype: torch.dtype,
is_rms_norm: bool,
) -> None:
"""Test layer norm forward pass with group normalization."""
if hidden_size % group_size != 0:
pytest.skip(
f"hidden_size {hidden_siz... | test | 1 | {"function_name": "test_layer_norm_fwd_with_groups", "class_name": null, "qualname": "test_layer_norm_fwd_with_groups", "file_path": "tests/kernels/test_fla_layernorm_guard.py", "repo_id": "vllm-project/vllm", "loc": 43, "tested_modules": ["vllm.model_executor.layers.fla.ops.layernorm_guard", "vllm.utils.torch_utils", ... |
langflow-ai/langflow:src/backend/tests/unit/test_auth_jwt_algorithms.py:TestJWTKeyHelpers.test_verification_and_signing_keys_work_together_rs256 | # Context:
import tempfile
import jwt
from langflow.services.auth.utils import get_jwt_verification_key
from langflow.services.auth.utils import JWTKeyError, get_jwt_verification_key
from langflow.services.auth.utils import get_jwt_signing_key
from langflow.services.auth.utils import get_jwt_signing_key, get_jwt_verifi... | def test_verification_and_signing_keys_work_together_rs256(self):
"""Verification and signing keys should work together for RS256."""
from langflow.services.auth.utils import get_jwt_signing_key, get_jwt_verification_key
with tempfile.TemporaryDirectory() as tmpdir:
mock_service = s... | test | 1 | {"function_name": "test_verification_and_signing_keys_work_together_rs256", "class_name": "TestJWTKeyHelpers", "qualname": "TestJWTKeyHelpers.test_verification_and_signing_keys_work_together_rs256", "file_path": "src/backend/tests/unit/test_auth_jwt_algorithms.py", "repo_id": "langflow-ai/langflow", "loc": 19, "tested_... |
sansan0/TrendRadar:mcp_server/server.py:get_system_status | # 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 get_system_status() -> str:
"""
获取系统运行状态和健康检查信息
返回系统版本、数据统计、缓存状态等信息
Returns:
JSON格式的系统状态信息
"""
tools = _get_tools()
result = await asyncio.to_thread(tools['system'].get_system_status)
return json.dumps(result, ensure_ascii=False, indent=2) | function_simple | 1 | {"cognitive_complexity": 0, "loc": 12, "code_loc": 3, "docstring_loc": 8, "function_name": "get_system_status", "class_name": null, "qualname": "get_system_status", "file_path": "mcp_server/server.py", "repo_id": "sansan0/TrendRadar", "has_docstring": true, "runnable_level": "file_runnable"} |
hiyouga/LlamaFactory:src/llamafactory/v1/utils/helper.py:set_seed | # Context:
from transformers import set_seed as hf_set_seed
def is_tokenizer(processor: Processor) -> bool: ...
def get_tokenizer(processor: Processor) -> PreTrainedTokenizer: ...
def _pad_and_truncate(tensor: Tensor, max_seqlen: int, pad_value: int) -> Tensor: ...
def pad_and_truncate(samples: list[ModelInput], max_s... | def set_seed(seed: int) -> None:
"""Set seed for reproducibility.
Args:
seed: Random seed.
"""
hf_set_seed(seed) | function_simple | 1 | {"cognitive_complexity": 0, "loc": 7, "code_loc": 1, "docstring_loc": 5, "function_name": "set_seed", "class_name": null, "qualname": "set_seed", "file_path": "src/llamafactory/v1/utils/helper.py", "repo_id": "hiyouga/LlamaFactory", "has_docstring": true, "runnable_level": "plib_runnable"} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.