sample_id string | instruction string | completion string | category string | label int64 | metadata string |
|---|---|---|---|---|---|
666ghj/BettaFish:ReportEngine/utils/chart_review_service.py:ChartReviewService._save_ir_to_file | # Context:
import json
from pathlib import Path
from typing import Any, Dict, List, Optional
from loguru import logger
class ReviewStats: ...
def get_chart_review_service() -> ChartReviewService: ...
def review_document_charts(document_ir: Dict[str, Any], ir_file_path: Optional[str | Path], reset_stats: bool, save_on_... | def _save_ir_to_file(self, document_ir: Dict[str, Any], file_path: str | Path) -> None:
"""保存 IR 到文件(移除内部元数据后)"""
try:
path = Path(file_path)
path.parent.mkdir(parents=True, exist_ok=True)
# 移除内部元数据键,保持 IR 文件干净
cleaned_ir = self._strip_internal_metadata(d... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 16, "code_loc": 11, "docstring_loc": 1, "function_name": "_save_ir_to_file", "class_name": "ChartReviewService", "qualname": "ChartReviewService._save_ir_to_file", "file_path": "ReportEngine/utils/chart_review_service.py", "repo_id": "666ghj/BettaFish", "has_docstring": true, "runnabl... |
docling-project/docling:tests/test_backend_image_native.py:test_num_pages_multipage | # Context:
def _make_png_stream(width: int, height: int, color) -> DocumentStream: ...
def _make_multipage_tiff_stream(num_pages: int, size) -> DocumentStream: ...
def test_docs_builder_uses_image_backend_for_image_stream(): ...
def test_docs_builder_multipage_tiff_counts_frames(): ...
def test_converter_default_maps_... | def test_num_pages_multipage():
"""Test page count for multi-page TIFF."""
stream = _make_multipage_tiff_stream(num_pages=5, size=(64, 64))
doc_backend = _get_backend_from_stream(stream)
assert doc_backend.page_count() == 5 | test | 1 | {"function_name": "test_num_pages_multipage", "class_name": null, "qualname": "test_num_pages_multipage", "file_path": "tests/test_backend_image_native.py", "repo_id": "docling-project/docling", "loc": 5, "tested_modules": ["io", "pathlib", "docling_core.types.doc", "PIL", "docling.backend.image_backend"], "has_docstri... |
huggingface/transformers:tests/models/jais2/test_modeling_jais2.py:Jais2IntegrationTest.test_model_generation | # Context:
from transformers import AutoTokenizer, is_torch_available
import torch
from transformers import (
Jais2Config,
Jais2ForCausalLM,
Jais2Model,
)
class Jais2ModelTester(CausalLMModelTester): ...
class Jais2ModelTest(CausalLMModelTest, unittest.TestCase): ...
class Jais2Integration... | def test_model_generation(self):
tokenizer = AutoTokenizer.from_pretrained("inceptionai/Jais-2-8B-Chat")
model = Jais2ForCausalLM.from_pretrained(
"inceptionai/Jais-2-8B-Chat", torch_dtype=torch.float16, device_map="auto"
)
input_text = "Simply put, the theory of relativity s... | test | 0 | {"function_name": "test_model_generation", "class_name": "Jais2IntegrationTest", "qualname": "Jais2IntegrationTest.test_model_generation", "file_path": "tests/models/jais2/test_modeling_jais2.py", "repo_id": "huggingface/transformers", "loc": 14, "tested_modules": ["transformers", "transformers.testing_utils", "causal_... |
langflow-ai/langflow:src/backend/tests/unit/agentic/utils/test_template_search.py:TestEdgeCases.test_very_long_query | # Context:
from langflow.agentic.utils import (
get_all_tags,
get_template_by_id,
get_templates_count,
list_templates,
)
class TestListTemplates: ...
class TestGetTemplateById: ...
class TestGetAllTags: ...
class TestGetTemplatesCount: ...
class TestTemplateStructure: ...
class TestSearchFunctionality:... | def test_very_long_query(self):
"""Test handling of very long query strings."""
long_query = "a" * 10000
results = list_templates(query=long_query)
# Very long query unlikely to match
assert len(results) == 0 | test | 1 | {"function_name": "test_very_long_query", "class_name": "TestEdgeCases", "qualname": "TestEdgeCases.test_very_long_query", "file_path": "src/backend/tests/unit/agentic/utils/test_template_search.py", "repo_id": "langflow-ai/langflow", "loc": 6, "tested_modules": ["langflow.agentic.utils"], "has_docstring": true, "runna... |
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_base.py:BaseAzurePGVectorStore._dedup_results | # Context:
from typing import Any
class BaseAzurePGVectorStore(BaseModel):
model_config = ConfigDict(
def verify_and_init_store(self) -> Self: ...
def _delete_rows_from_table(self, ids: list[str] | None, **kwargs) -> bool | None: ...
def _similarity_search_by_vector_with_distance(self, embedding: list[... | def _dedup_results(
self, results: list[tuple[dict, float, Any]]
) -> list[tuple[dict, float, Any]]:
"""Deduplicate search results by document id, preserving order.
Accepts a list of tuples (document_dict, score, optional_embedding) where
document_dict contains at least the id colum... | function_complex | 1 | {"cognitive_complexity": 12, "loc": 27, "code_loc": 13, "docstring_loc": 6, "function_name": "_dedup_results", "class_name": "BaseAzurePGVectorStore", "qualname": "BaseAzurePGVectorStore._dedup_results", "file_path": "llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_st... |
ray-project/ray:python/ray/serve/tests/unit/test_deployment_rank_manager.py:TestDeploymentRankManagerMultiNode.test_recover_rank_multiple_nodes | # Context:
from ray.serve._private.deployment_state import DeploymentRankManager
from ray.serve.schema import ReplicaRank
def rank_manager() -> DeploymentRankManager: ...
class MockDeploymentReplica: ...
class TestDeploymentRankManager: ...
class TestDeploymentRankManagerEdgeCases: ...
class TestDeploymentRankManagerE... | def test_recover_rank_multiple_nodes(self):
"""Test recovering ranks for replicas on different nodes."""
rank_manager = DeploymentRankManager()
# Recover replicas on different nodes
rank_manager.recover_rank(
"r1", "node_1", ReplicaRank(rank=0, node_rank=0, local_rank=0)
... | test | 0 | {"function_name": "test_recover_rank_multiple_nodes", "class_name": "TestDeploymentRankManagerMultiNode", "qualname": "TestDeploymentRankManagerMultiNode.test_recover_rank_multiple_nodes", "file_path": "python/ray/serve/tests/unit/test_deployment_rank_manager.py", "repo_id": "ray-project/ray", "loc": 25, "tested_module... |
browser-use/browser-use:tests/ci/evaluate_tasks.py:module_doc | Write a module-level docstring for the Python module `evaluate_tasks` which contains class `JudgeResponse`. | Runs all agent tasks in parallel (up to 10 at a time) using separate subprocesses.
Each task gets its own Python process, preventing browser session interference.
Fails with exit code 1 if 0% of tasks pass. | documentation | 0 | {"doc_type": "module", "module_name": "evaluate_tasks", "file_path": "tests/ci/evaluate_tasks.py", "repo_id": "browser-use/browser-use", "char_length": 206} |
ray-project/ray:ci/raydepsets/cli.py:DependencySetManager.execute_pre_hook | # Context:
import shlex
import subprocess
import click
def cli(): ...
def build(config_path: str, workspace_dir: Optional[str], name: Optional[str], uv_cache_dir: Optional[str], check: Optional[bool], all_configs: Optional[bool]): ...
def _get_bytes(packages: List[str]) -> bytes: ...
def _get_depset(depsets: List[Deps... | def execute_pre_hook(self, pre_hook: str):
"""Execute a pre-hook shell command."""
status = subprocess.run(
shlex.split(pre_hook),
cwd=self.workspace.dir,
capture_output=True,
)
if status.returncode != 0:
raise RuntimeError(
... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 13, "code_loc": 11, "docstring_loc": 1, "function_name": "execute_pre_hook", "class_name": "DependencySetManager", "qualname": "DependencySetManager.execute_pre_hook", "file_path": "ci/raydepsets/cli.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "class_ru... |
crewAIInc/crewAI:lib/crewai-tools/tests/adapters/mcp_adapter_test.py:test_filter_with_nonexistent_tool | # Context:
from crewai_tools import MCPServerAdapter
from mcp import StdioServerParameters
def echo_server_script(): ...
def echo_server_sse_script(): ...
def echo_sse_server(echo_server_sse_script): ...
def test_context_manager_syntax(echo_server_script): ...
def test_context_manager_syntax_sse(echo_sse_server): ...
... | def test_filter_with_nonexistent_tool(echo_server_script):
serverparams = StdioServerParameters(
command="uv", args=["run", "python", "-c", echo_server_script]
)
# Include a tool that doesn't exist
with MCPServerAdapter(serverparams, "echo_tool", "nonexistent_tool") as tools:
# Only echo... | test | 0 | {"function_name": "test_filter_with_nonexistent_tool", "class_name": null, "qualname": "test_filter_with_nonexistent_tool", "file_path": "lib/crewai-tools/tests/adapters/mcp_adapter_test.py", "repo_id": "crewAIInc/crewAI", "loc": 9, "tested_modules": ["textwrap", "crewai_tools", "crewai_tools.adapters.tool_collection",... |
browser-use/browser-use:browser_use/dom/enhanced_snapshot.py:module_doc | Write a module-level docstring for the Python module `enhanced_snapshot` which contains function `_parse_rare_boolean_data`, function `_parse_computed_styles`, function `build_snapshot_lookup`. | Enhanced snapshot processing for browser-use DOM tree extraction.
This module provides stateless functions for parsing Chrome DevTools Protocol (CDP) DOMSnapshot data
to extract visibility, clickability, cursor styles, and other layout information. | documentation | 0 | {"doc_type": "module", "module_name": "enhanced_snapshot", "file_path": "browser_use/dom/enhanced_snapshot.py", "repo_id": "browser-use/browser-use", "char_length": 249} |
browser-use/browser-use:browser_use/code_use/notebook_export.py:export_to_ipynb | # Context:
import json
import re
from pathlib import Path
from browser_use.code_use.service import CodeAgent
from .views import CellType, NotebookExport
def session_to_python_script(agent: CodeAgent) -> str: ...
# Task:
Write a Python function `export_to_ipynb` to export a NotebookSession to a Jupyter notebook (.ipyn... | def export_to_ipynb(agent: CodeAgent, output_path: str | Path) -> Path:
"""
Export a NotebookSession to a Jupyter notebook (.ipynb) file.
Now includes JavaScript code blocks that were stored in the namespace.
Args:
session: The NotebookSession to export
output_path: Path where to save the notebook file
agent... | function_complex | 0 | {"cognitive_complexity": 24, "loc": 163, "code_loc": 106, "docstring_loc": 19, "function_name": "export_to_ipynb", "class_name": null, "qualname": "export_to_ipynb", "file_path": "browser_use/code_use/notebook_export.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "project_runnable"} |
infiniflow/ragflow:test/testcases/test_web_api/test_dialog_app/test_update_dialog.py:TestDialogUpdate.test_update_icon | # Context:
import pytest
from common import update_dialog
class TestAuthorization: ...
class TestDialogUpdate:
def test_update_name(self, WebApiAuth, add_dialog_func): ...
def test_update_description(self, WebApiAuth, add_dialog_func): ...
def test_update_prompt_config(self, WebApiAuth, add_dialog_func): ... | def test_update_icon(self, WebApiAuth, add_dialog_func):
_, dialog_id = add_dialog_func
new_icon = "🚀"
payload = {"dialog_id": dialog_id, "icon": new_icon, "prompt_config": {"system": "You are a helpful assistant.", "parameters": []}}
res = update_dialog(WebApiAuth, payload)
ass... | test | 1 | {"function_name": "test_update_icon", "class_name": "TestDialogUpdate", "qualname": "TestDialogUpdate.test_update_icon", "file_path": "test/testcases/test_web_api/test_dialog_app/test_update_dialog.py", "repo_id": "infiniflow/ragflow", "loc": 7, "tested_modules": ["common", "configs", "libs.auth"], "has_docstring": fal... |
streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_routes_test.py:TestWithBase.test_explicit_none_base_url_uses_config | # Context:
from streamlit.web.server.starlette.starlette_routes import (
_ensure_xsrf_cookie,
_set_cors_headers,
_set_unquoted_cookie,
_with_base,
)
from tests.testutil import patch_config_options
class TestSetCorsHeaders: ...
class TestEnsureXsrfCookie: ...
class TestSetUnquotedCookie: ...
class Test... | def test_explicit_none_base_url_uses_config(self) -> None:
"""Test that explicit None uses config."""
result = _with_base("_stcore/health", base_url=None)
assert result == "/fromconfig/_stcore/health" | test | 1 | {"function_name": "test_explicit_none_base_url_uses_config", "class_name": "TestWithBase", "qualname": "TestWithBase.test_explicit_none_base_url_uses_config", "file_path": "lib/tests/streamlit/web/server/starlette/starlette_routes_test.py", "repo_id": "streamlit/streamlit", "loc": 5, "tested_modules": ["__future__", "s... |
vllm-project/vllm:tests/entrypoints/llm/test_mm_embeds_only.py:test_generate_with_embedding | # Context:
import pytest
from vllm import LLM, SamplingParams
from vllm.assets.image import ImageAsset
def llm(): ...
def test_raw_image_rejected(llm: LLM): ...
def test_text_only_prompt(llm: LLM): ...
# Task:
Write a Python test function `test_generate_with_embedding` to pre-computed embedding produces tokens withou... | def test_generate_with_embedding(llm: LLM):
"""Pre-computed embedding produces tokens without hanging."""
embedding = ImageAsset("stop_sign").image_embeds
outputs = llm.generate(
{"prompt": PROMPT, "multi_modal_data": {"image": embedding}},
sampling_params=SamplingParams(max_tokens=32, tempe... | test | 1 | {"function_name": "test_generate_with_embedding", "class_name": null, "qualname": "test_generate_with_embedding", "file_path": "tests/entrypoints/llm/test_mm_embeds_only.py", "repo_id": "vllm-project/vllm", "loc": 9, "tested_modules": ["vllm", "vllm.assets.image", "vllm.distributed"], "has_docstring": true, "runnable_l... |
infiniflow/ragflow:test/testcases/test_web_api/test_user_app/test_user_app_unit.py:test_tenant_info_and_set_tenant_info_exception_matrix_unit | # Context:
import pytest
class _DummyManager: ...
class _AwaitableValue: ...
class _Args(dict): ...
class _DummyResponse: ...
class _DummyHTTPResponse: ...
class _DummyRedis: ...
class _DummyUser: ...
class _Field: ...
def _run(coro): ...
def _set_request_json(monkeypatch, module, payload): ...
def _set_request_args(m... | def test_tenant_info_and_set_tenant_info_exception_matrix_unit(monkeypatch):
module = _load_user_app(monkeypatch)
monkeypatch.setattr(module.TenantService, "get_info_by", lambda _uid: [])
res = _run(module.tenant_info())
assert res["code"] == module.RetCode.DATA_ERROR, res
assert "Tenant not found"... | test | 1 | {"function_name": "test_tenant_info_and_set_tenant_info_exception_matrix_unit", "class_name": null, "qualname": "test_tenant_info_and_set_tenant_info_exception_matrix_unit", "file_path": "test/testcases/test_web_api/test_user_app/test_user_app_unit.py", "repo_id": "infiniflow/ragflow", "loc": 29, "tested_modules": ["pa... |
hiyouga/LlamaFactory:tests_v1/core/utils/test_rendering.py:test_chatml_parse | # Context:
from transformers import AutoTokenizer
from llamafactory.v1.core.utils.rendering import Renderer
from llamafactory.v1.utils.types import Processor
def _get_input_ids(inputs: list | dict) -> list: ...
def test_chatml_rendering(): ...
def test_chatml_rendering_remote(num_samples: int): ...
def test_qwen3_noth... | def test_chatml_parse():
tokenizer: Processor = AutoTokenizer.from_pretrained("llamafactory/tiny-random-qwen3")
renderer = Renderer(template="chatml", processor=tokenizer)
generated_text = "LLM stands for Large Language Model."
parsed_message = renderer.parse_message(generated_text)
assert parsed_me... | test | 1 | {"function_name": "test_chatml_parse", "class_name": null, "qualname": "test_chatml_parse", "file_path": "tests_v1/core/utils/test_rendering.py", "repo_id": "hiyouga/LlamaFactory", "loc": 6, "tested_modules": ["transformers", "llamafactory.v1.config", "llamafactory.v1.core.data_engine", "llamafactory.v1.core.utils.rend... |
apache/airflow:dev/breeze/tests/test_ui_commands.py:TestCompareKeys.test_compare_keys_with_extra | # Context:
import json
from airflow_breeze.commands.ui_commands import (
LocaleFiles,
LocaleKeySet,
LocaleSummary,
compare_keys,
expand_plural_keys,
flatten_keys,
get_plural_base,
)
import airflow_breeze.commands.ui_commands as ui_commands
class TestPluralHandling: ...
class TestFlattenKeys... | def test_compare_keys_with_extra(self, tmp_path):
en_dir = tmp_path / "en"
en_dir.mkdir()
de_dir = tmp_path / "de"
de_dir.mkdir()
en_data = {"greeting": "Hello"}
de_data = {"greeting": "Hallo", "extra": "Extra"}
(en_dir / "test.json").write_text(json.dumps(en_da... | test | 1 | {"function_name": "test_compare_keys_with_extra", "class_name": "TestCompareKeys", "qualname": "TestCompareKeys.test_compare_keys_with_extra", "file_path": "dev/breeze/tests/test_ui_commands.py", "repo_id": "apache/airflow", "loc": 28, "tested_modules": ["__future__", "airflow_breeze.commands.ui_commands", "airflow_bre... |
huggingface/transformers:tests/models/ernie4_5_vl_moe/test_video_processing_ernie4_5_vl_moe.py:Ernie4_5_VLMoeVideoProcessingTest.test_call_numpy | # Context:
class Ernie4_5_VLMoeVideoProcessingTester: ...
class Ernie4_5_VLMoeVideoProcessingTest(VideoProcessingTestMixin, unittest.TestCase):
fast_video_processing_class = Ernie4_5_VLMoeVideoProcessor if is_torchvision_available() else None
input_name = "pixel_values_videos"
def setUp(self): ...
def... | def test_call_numpy(self):
for video_processing_class in self.video_processor_list:
video_processing = video_processing_class(**self.video_processor_dict)
video_inputs = self.video_processor_tester.prepare_video_inputs(
equal_resolution=False, return_tensors="np"
... | test | 0 | {"function_name": "test_call_numpy", "class_name": "Ernie4_5_VLMoeVideoProcessingTest", "qualname": "Ernie4_5_VLMoeVideoProcessingTest.test_call_numpy", "file_path": "tests/models/ernie4_5_vl_moe/test_video_processing_ernie4_5_vl_moe.py", "repo_id": "huggingface/transformers", "loc": 19, "tested_modules": ["transformer... |
Zie619/n8n-workflows:workflow_db.py:WorkflowDatabase.get_service_categories | # Context:
from typing import Dict, List, Any, Optional, Tuple
def main(): ...
class WorkflowDatabase:
def __init__(self, db_path: str = None):
# Use environment variable if no path provided
if db_path is None:
db_path = os.environ.get("WORKFLOW_DB_PATH", "workflows.db")
self.d... | def get_service_categories(self) -> Dict[str, List[str]]:
"""Get service categories for enhanced filtering."""
return {
"messaging": [
"Telegram",
"Discord",
"Slack",
"WhatsApp",
"Mattermost",
"Mi... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 56, "code_loc": 54, "docstring_loc": 1, "function_name": "get_service_categories", "class_name": "WorkflowDatabase", "qualname": "WorkflowDatabase.get_service_categories", "file_path": "workflow_db.py", "repo_id": "Zie619/n8n-workflows", "has_docstring": true, "runnable_level": "slib_... |
docling-project/docling:docling/datamodel/stage_model_specs.py:StageModelPreset.supported_engines | # Context:
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Set
from docling.models.inference_engines.vlm.base import VlmEngineType
class EngineModelConfig(BaseModel): ...
class ApiModelConfig(BaseModel): ...
class VlmModelSpec(BaseModel): ...
class ObjectDetectionModelSpec(BaseModel): ...
class ... | def supported_engines(self) -> Set[VlmEngineType]:
"""Get supported engines from model spec."""
if self.model_spec.supported_engines is None:
return set(VlmEngineType)
return self.model_spec.supported_engines | function_simple | 1 | {"cognitive_complexity": 1, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "supported_engines", "class_name": "StageModelPreset", "qualname": "StageModelPreset.supported_engines", "file_path": "docling/datamodel/stage_model_specs.py", "repo_id": "docling-project/docling", "has_docstring": true, "runnable... |
browser-use/browser-use:tests/ci/security/test_ip_blocking.py:TestIsIPAddressHelper.test_invalid_ip_detection | # Context:
from bubus import EventBus
from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.browser.watchdogs.security_watchdog import SecurityWatchdog
class TestIPv4Blocking: ...
class TestIPv6Blocking: ...
class TestDomainNamesStillAllowed: ...
class TestIPBlockingWithAllowedDomains: ...
cl... | def test_invalid_ip_detection(self):
"""Test that non-IP strings are correctly identified as not IPs."""
browser_profile = BrowserProfile(block_ip_addresses=True, headless=True, user_data_dir=None)
browser_session = BrowserSession(browser_profile=browser_profile)
event_bus = EventBus()
watchdog = SecurityWatc... | test | 0 | {"function_name": "test_invalid_ip_detection", "class_name": "TestIsIPAddressHelper", "qualname": "TestIsIPAddressHelper.test_invalid_ip_detection", "file_path": "tests/ci/security/test_ip_blocking.py", "repo_id": "browser-use/browser-use", "loc": 22, "tested_modules": ["bubus", "browser_use.browser", "browser_use.brow... |
huggingface/transformers:tests/models/audioflamingo3/test_modeling_audioflamingo3.py:module_doc | Write a module-level docstring for the Python module `test_modeling_audioflamingo3` which contains class `AudioFlamingo3ModelTester`, class `AudioFlamingo3ForConditionalGenerationModelTest`, class `AudioFlamingo3ForConditionalGenerationIntegrationTest`. | Testing suite for the PyTorch AudioFlamingo3 model. | documentation | 0 | {"doc_type": "module", "module_name": "test_modeling_audioflamingo3", "file_path": "tests/models/audioflamingo3/test_modeling_audioflamingo3.py", "repo_id": "huggingface/transformers", "char_length": 51} |
ray-project/ray:python/ray/dashboard/modules/aggregator/publisher/async_publisher_client.py:AsyncHttpPublisherClient:class_doc | Write a class-level docstring for `AsyncHttpPublisherClient` (inherits from PublisherClientInterface) which has methods: `__init__`, `publish`, `_send_http_request`, `close`, `set_session`. | Client for publishing ray event batches to an external HTTP service. | documentation | 0 | {"doc_type": "class", "class_name": "AsyncHttpPublisherClient", "file_path": "python/ray/dashboard/modules/aggregator/publisher/async_publisher_client.py", "repo_id": "ray-project/ray", "char_length": 68, "methods": ["__init__", "publish", "_send_http_request", "close", "set_session"]} |
ray-project/ray:doc/source/serve/tutorials/video-analysis/app.py:parse_s3_uri | # Context:
from urllib.parse import urlparse
class AnalyzeRequest(BaseModel): ...
class TagResult(BaseModel): ...
class CaptionResult(BaseModel): ...
class TimingResult(BaseModel): ...
class SceneChange(BaseModel): ...
class ChunkResult(BaseModel): ...
class AnalyzeResponse(BaseModel): ...
class VideoAnalyzer: ...
# ... | def parse_s3_uri(s3_uri: str) -> tuple[str, str]:
"""Parse s3://bucket/key into (bucket, key)."""
parsed = urlparse(s3_uri)
if parsed.scheme != "s3":
raise ValueError(f"Invalid S3 URI: {s3_uri}")
bucket = parsed.netloc
key = parsed.path.lstrip("/")
return bucket, key | function_simple | 0 | {"cognitive_complexity": 1, "loc": 8, "code_loc": 6, "docstring_loc": 1, "function_name": "parse_s3_uri", "class_name": null, "qualname": "parse_s3_uri", "file_path": "doc/source/serve/tutorials/video-analysis/app.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "slib_runnable"} |
ray-project/ray:python/ray/train/v2/tests/test_torch_gpu.py:test_torch_trainer_cuda_initialization | # Context:
from typing import List
import torch
import ray
from ray.train import RunConfig, ScalingConfig
from ray.train.torch import TorchTrainer
from ray.train.v2._internal.execution.callback import WorkerGroupCallback
from ray.train.v2._internal.execution.worker_group import Worker
def test_torch_get_devices(ray_st... | def test_torch_trainer_cuda_initialization(ray_start_4_cpus_2_gpus):
"""Test that Torch CUDA initialization works with TorchTrainer.
This test verifies that PyTorch can properly initialize CUDA on multiple
workers before the training context is set up, ensuring that GPU resources
are available and acce... | test | 0 | {"function_name": "test_torch_trainer_cuda_initialization", "class_name": null, "qualname": "test_torch_trainer_cuda_initialization", "file_path": "python/ray/train/v2/tests/test_torch_gpu.py", "repo_id": "ray-project/ray", "loc": 46, "tested_modules": ["typing", "torch.nn.parallel", "torch.utils.data", "ray.train", "r... |
huggingface/transformers:src/transformers/models/vjepa2/modeling_vjepa2.py:drop_path | # Context:
import torch
class VJEPA2WithMaskedInputPredictorOutput(ModelOutput): ...
class VJEPA2WithMaskedInputModelOutput(ModelOutput): ...
class VJEPA2PatchEmbeddings3D(nn.Module): ...
class VJEPA2Embeddings(nn.Module): ...
def eager_attention_forward(module: nn.Module, query: torch.Tensor, key: torch.Tensor, value... | def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
"""
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
if drop_prob == 0.0 or not training:
return input
keep_prob = 1 - drop_prob
shape = (input... | function_simple | 0 | {"cognitive_complexity": 2, "loc": 13, "code_loc": 8, "docstring_loc": 4, "function_name": "drop_path", "class_name": null, "qualname": "drop_path", "file_path": "src/transformers/models/vjepa2/modeling_vjepa2.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_level": "plib_runnable"} |
langflow-ai/langflow:src/backend/tests/unit/base/tools/test_run_flow.py:TestRunFlowBaseComponentFlowRetrieval.test_get_graph_uses_cache_when_available_and_up_to_date | # Context:
from unittest.mock import AsyncMock, MagicMock, Mock, PropertyMock, patch
from uuid import uuid4
import pytest
from lfx.base.tools.run_flow import RunFlowBaseComponent
from lfx.graph.graph.base import Graph
def mock_shared_cache(): ...
class TestRunFlowBaseComponentInitialization: ...
class TestRunFlowBaseC... | async def test_get_graph_uses_cache_when_available_and_up_to_date(self):
"""Test that get_graph returns cached graph when available and up-to-date."""
component = RunFlowBaseComponent()
component._user_id = str(uuid4())
component.cache_flow = True
flow_id = str(uuid4())
u... | test | 1 | {"function_name": "test_get_graph_uses_cache_when_available_and_up_to_date", "class_name": "TestRunFlowBaseComponentFlowRetrieval", "qualname": "TestRunFlowBaseComponentFlowRetrieval.test_get_graph_uses_cache_when_available_and_up_to_date", "file_path": "src/backend/tests/unit/base/tools/test_run_flow.py", "repo_id": "... |
crewAIInc/crewAI:lib/crewai/src/crewai/memory/encoding_flow.py:EncodingFlow._apply_defaults | # Context:
class ItemState(BaseModel): ...
class EncodingState(BaseModel): ...
class EncodingFlow(Flow[EncodingState]):
initial_state = EncodingState
def __init__(
self,
storage: Any,
llm: Any,
embedder: Any,
config: MemoryConfig | None = None,
) -> None:
su... | def _apply_defaults(self, item: ItemState) -> None:
"""Apply caller values with config defaults (fast path)."""
item.resolved_scope = item.scope or "/"
item.resolved_categories = item.categories or []
item.resolved_metadata = item.metadata or {}
item.resolved_importance = (
... | function_simple | 0 | {"cognitive_complexity": 4, "loc": 12, "code_loc": 10, "docstring_loc": 1, "function_name": "_apply_defaults", "class_name": "EncodingFlow", "qualname": "EncodingFlow._apply_defaults", "file_path": "lib/crewai/src/crewai/memory/encoding_flow.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_level": "... |
huggingface/transformers:src/transformers/models/glm4v/image_processing_glm4v.py:Glm4vImageProcessorKwargs:class_doc | Write a class-level docstring for `Glm4vImageProcessorKwargs` (inherits from ImagesKwargs) which has methods: various methods. | patch_size (`int`, *optional*, defaults to 14):
The spatial patch size of the vision encoder.
temporal_patch_size (`int`, *optional*, defaults to 2):
The temporal patch size of the vision encoder.
merge_size (`int`, *optional*, defaults to 2):
The merge size of the vision encoder to llm encoder. | documentation | 0 | {"doc_type": "class", "class_name": "Glm4vImageProcessorKwargs", "file_path": "src/transformers/models/glm4v/image_processing_glm4v.py", "repo_id": "huggingface/transformers", "char_length": 308, "methods": []} |
ray-project/ray:release/train_tests/benchmark/image_classification/s3_url/imagenet.py:_list_files_for_label | # Context:
from typing import Callable, Dict, List, Optional, Tuple
import boto3
def _get_class_labels(bucket: str, prefix: str) -> List[str]: ...
def _list_s3_image_files_cached(data_dir: str) -> Tuple[Tuple[str, str], ...]: ...
def list_s3_image_files(data_dir: str) -> List[Dict[str, str]]: ...
def get_process_batch... | def _list_files_for_label(
bucket: str, prefix: str, label: str
) -> List[Tuple[str, str]]:
"""Ray task to list all image files for a specific label.
Args:
bucket: S3 bucket name
prefix: S3 prefix (parent directory)
label: Class label (subdirectory name)
Returns:
List o... | function_complex | 0 | {"cognitive_complexity": 7, "loc": 28, "code_loc": 11, "docstring_loc": 10, "function_name": "_list_files_for_label", "class_name": null, "qualname": "_list_files_for_label", "file_path": "release/train_tests/benchmark/image_classification/s3_url/imagenet.py", "repo_id": "ray-project/ray", "has_docstring": true, "runna... |
crewAIInc/crewAI:lib/crewai/tests/llms/openai/test_openai.py:test_openai_responses_api_with_structured_output | # Context:
import pytest
from crewai.llms.providers.openai.completion import OpenAICompletion, ResponsesAPIResult
from crewai.llms.providers.openai.completion import OpenAICompletion
from pydantic import BaseModel
from pydantic import BaseModel, Field
def test_openai_completion_is_used_when_openai_provider(): ...
def ... | def test_openai_responses_api_with_structured_output():
"""Test Responses API with structured output using Pydantic model."""
from pydantic import BaseModel, Field
class MathAnswer(BaseModel):
"""Structured math answer."""
result: int = Field(description="The numerical result")
exp... | test | 0 | {"function_name": "test_openai_responses_api_with_structured_output", "class_name": null, "qualname": "test_openai_responses_api_with_structured_output", "file_path": "lib/crewai/tests/llms/openai/test_openai.py", "repo_id": "crewAIInc/crewAI", "loc": 19, "tested_modules": ["typing", "crewai.llm", "crewai.llms.provider... |
docling-project/docling:tests/test_asr_pipeline.py:test_mlx_run_success_and_failure | # Context:
from unittest.mock import Mock, patch
from docling.datamodel.base_models import ConversionStatus, InputFormat
from docling.datamodel.document import ConversionResult, InputDocument
from docling.backend.noop_backend import NoOpBackend
from docling.datamodel.base_models import InputFormat
from docling.datamode... | def test_mlx_run_success_and_failure(tmp_path):
"""Cover _MlxWhisperModel.run success and failure paths."""
from docling.backend.noop_backend import NoOpBackend
from docling.datamodel.accelerator_options import (
AcceleratorDevice,
AcceleratorOptions,
)
from docling.datamodel.documen... | test | 1 | {"function_name": "test_mlx_run_success_and_failure", "class_name": null, "qualname": "test_mlx_run_success_and_failure", "file_path": "tests/test_asr_pipeline.py", "repo_id": "docling-project/docling", "loc": 58, "tested_modules": ["pathlib", "docling.datamodel", "docling.datamodel.base_models", "docling.datamodel.doc... |
infiniflow/ragflow:test/testcases/test_web_api/test_kb_app/test_create_kb.py:TestCapability.test_create_kb_concurrent | # Context:
from concurrent.futures import ThreadPoolExecutor, as_completed
import pytest
from common import create_kb
class TestAuthorization: ...
class TestDatasetCreate: ...
class TestCapability:
def test_create_kb_1k(self, WebApiAuth): ...
# Task:
Write a Python test method `test_create_kb_concurrent` in test... | def test_create_kb_concurrent(self, WebApiAuth):
count = 100
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(create_kb, WebApiAuth, {"name": f"dataset_{i}"}) for i in range(count)]
responses = list(as_completed(futures))
assert len(responses) ==... | test | 1 | {"function_name": "test_create_kb_concurrent", "class_name": "TestCapability", "qualname": "TestCapability.test_create_kb_concurrent", "file_path": "test/testcases/test_web_api/test_kb_app/test_create_kb.py", "repo_id": "infiniflow/ragflow", "loc": 7, "tested_modules": ["concurrent.futures", "common", "configs", "hypot... |
apache/airflow:airflow-core/tests/unit/dag_processing/test_dagbag.py:TestDagBag.test_task_cluster_policy_violation | # Context:
import os
from unittest.mock import patch
from airflow.dag_processing.dagbag import (
BundleDagBag,
DagBag,
_capture_with_reraise,
_validate_executor_fields,
)
from unit import cluster_policies
from unit.models import TEST_DAGS_FOLDER
def db_clean_up(): ...
class TestValidateExecutorFields: ... | def test_task_cluster_policy_violation(self):
"""
test that file processing results in import error when task does not
obey cluster policy.
"""
dag_file = os.path.join(TEST_DAGS_FOLDER, "test_missing_owner.py")
dag_id = "test_missing_owner"
err_cls_name = "Airflow... | test | 1 | {"function_name": "test_task_cluster_policy_violation", "class_name": "TestDagBag", "qualname": "TestDagBag.test_task_cluster_policy_violation", "file_path": "airflow-core/tests/unit/dag_processing/test_dagbag.py", "repo_id": "apache/airflow", "loc": 19, "tested_modules": ["__future__", "copy", "datetime", "sqlalchemy"... |
vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/lmcache_mp_connector.py:LMCacheMPConnector.start_load_kv | # Context:
from typing import TYPE_CHECKING, Any, Literal
import torch
def reformat_block_ids(block_ids: tuple[list[int], ...] | None) -> list[int]: ...
def extract_world_size_and_kv_rank(world_size: int, rank: int, vllm_config: VllmConfig) -> tuple[int, int]: ...
def create_scheduler_adapter(server_url: str, zmq_cont... | def start_load_kv(self, forward_context: "ForwardContext", **kwargs: Any) -> None:
"""
Start loading the KV cache from the connector to vLLM's paged
KV buffer. This is called from the forward context before the
forward pass to enable async loading during model execution.
Args:
... | function_simple | 1 | {"cognitive_complexity": 4, "loc": 35, "code_loc": 15, "docstring_loc": 14, "function_name": "start_load_kv", "class_name": "LMCacheMPConnector", "qualname": "LMCacheMPConnector.start_load_kv", "file_path": "vllm/distributed/kv_transfer/kv_connector/v1/lmcache_mp_connector.py", "repo_id": "vllm-project/vllm", "has_docs... |
apache/airflow:providers/google/tests/unit/google/cloud/triggers/test_gen_ai.py:TestGenAIGeminiCreateEmbeddingsBatchJobTrigger.test_run_loop_return_success_event | # Context:
from unittest import mock
import pytest
from airflow.providers.google.cloud.hooks.gen_ai import BatchJobStatus
from airflow.triggers.base import TriggerEvent
def create_batch_job_trigger(mock_conn): ...
def create_embeddings_batch_job_trigger(mock_conn): ...
class TestGenAIGeminiCreateBatchJobTrigger: ...
... | async def test_run_loop_return_success_event(
self, mock_job_status, mock_create_embeddings_batch_job, create_embeddings_batch_job_trigger
):
test_job_model_dump = {"id": "test_job_id", "status": "succeeded"}
mock_job_status.return_value.state.name = BatchJobStatus.SUCCEEDED.value
mo... | test | 1 | {"function_name": "test_run_loop_return_success_event", "class_name": "TestGenAIGeminiCreateEmbeddingsBatchJobTrigger", "qualname": "TestGenAIGeminiCreateEmbeddingsBatchJobTrigger.test_run_loop_return_success_event", "file_path": "providers/google/tests/unit/google/cloud/triggers/test_gen_ai.py", "repo_id": "apache/air... |
ray-project/ray:python/ray/_common/tests/test_ray_option_utils.py:TestOptionValidation.test_validate_resource_quantity | # Context:
from unittest.mock import patch
from ray._common.ray_option_utils import (
Option,
_check_deprecate_placement_group,
_counting_option,
_resource_option,
_validate_resource_quantity,
_validate_resources,
update_options,
validate_actor_options,
validate_task_options,
)
clas... | def test_validate_resource_quantity(self, mock_get_manager, mock_get_all_names):
# Valid cases
assert _validate_resource_quantity("CPU", 1) is None
assert _validate_resource_quantity("memory", 0) is None
assert _validate_resource_quantity("custom", 0.5) is None
# Invalid cases
... | test | 0 | {"function_name": "test_validate_resource_quantity", "class_name": "TestOptionValidation", "qualname": "TestOptionValidation.test_validate_resource_quantity", "file_path": "python/ray/_common/tests/test_ray_option_utils.py", "repo_id": "ray-project/ray", "loc": 31, "tested_modules": ["ray._common.ray_option_utils", "ra... |
langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/middleware_typing/test_middleware_type_errors.py:test_backwards_compat_with_context_schema | # Context:
from langchain.agents import create_agent
from tests.unit_tests.agents.model import FakeToolCallingModel
class UserContext(TypedDict): ...
class SessionContext(TypedDict): ...
class AnalysisResult(BaseModel): ...
class SummaryResult(BaseModel): ...
class WrongContextFieldsMiddleware(AgentMiddleware[AgentSta... | def test_backwards_compat_with_context_schema() -> None:
# TYPE ERROR: BackwardsCompatibleMiddleware is AgentMiddleware[..., None]
# but context_schema=UserContext expects AgentMiddleware[..., UserContext]
fake_model = FakeToolCallingModel()
_agent = create_agent( # type: ignore[misc]
model=fak... | test | 1 | {"function_name": "test_backwards_compat_with_context_schema", "class_name": null, "qualname": "test_backwards_compat_with_context_schema", "file_path": "libs/langchain_v1/tests/unit_tests/agents/middleware_typing/test_middleware_type_errors.py", "repo_id": "langchain-ai/langchain", "loc": 9, "tested_modules": ["__futu... |
streamlit/streamlit:lib/tests/streamlit/components/v2/bidi_component/test_serialization.py:test_serde_deserialize_with_defaults_partial_state | # Context:
import json
from streamlit.components.v2.bidi_component.serialization import (
BidiComponentSerde,
_extract_dataframes_from_dict,
deserialize_trigger_list,
handle_deserialize,
serialize_mixed_data,
)
def test_handle_deserialize(): ...
def test_deserialize_trigger_list(): ...
def test_ser... | def test_serde_deserialize_with_defaults_partial_state():
"""Test that defaults are applied only for missing keys."""
defaults = {"count": 0, "message": "hello", "enabled": True}
serde = BidiComponentSerde(default=defaults)
# Deserialize partial state
partial_state = {"count": 5, "message": "custom... | test | 1 | {"function_name": "test_serde_deserialize_with_defaults_partial_state", "class_name": null, "qualname": "test_serde_deserialize_with_defaults_partial_state", "file_path": "lib/tests/streamlit/components/v2/bidi_component/test_serialization.py", "repo_id": "streamlit/streamlit", "loc": 13, "tested_modules": ["__future__... |
langflow-ai/langflow:src/backend/tests/unit/utils/test_data_structure.py:TestAnalyzeValue.test_error_handling | # Context:
from langflow.utils.data_structure import (
analyze_value,
get_data_structure,
get_sample_values,
get_type_str,
infer_list_type,
)
class TestInferListType: ...
class TestGetTypeStr: ...
class TestGetDataStructure: ...
class TestGetSampleValues: ...
class TestIntegrationScenarios: ...
cl... | def test_error_handling(self):
"""Test error handling in analysis."""
# Create an object that raises exception on access
class ProblematicClass:
def __getitem__(self, key):
msg = "Access error"
raise RuntimeError(msg)
problematic = Problemati... | test | 1 | {"function_name": "test_error_handling", "class_name": "TestAnalyzeValue", "qualname": "TestAnalyzeValue.test_error_handling", "file_path": "src/backend/tests/unit/utils/test_data_structure.py", "repo_id": "langflow-ai/langflow", "loc": 13, "tested_modules": ["langflow.schema.data", "langflow.utils.data_structure"], "h... |
apache/airflow:providers/fab/tests/unit/fab/auth_manager/api_fastapi/routes/test_roles.py:TestRoles.test_patch_role_validation_404_empty_name | # Context:
from contextlib import nullcontext as _noop_cm
from unittest.mock import ANY, MagicMock, patch
from fastapi import HTTPException, status
class TestRoles:
def test_create_role(self, mock_get_application_builder, mock_get_auth_manager, mock_roles, test_client, as_user): ...
def test_create_role_forbid... | def test_patch_role_validation_404_empty_name(
self, mock_get_application_builder, mock_get_auth_manager, mock_roles, test_client, as_user
):
mgr = MagicMock()
mgr.is_authorized_custom_view.return_value = True
mock_get_auth_manager.return_value = mgr
mock_roles.patch_role.sid... | test | 1 | {"function_name": "test_patch_role_validation_404_empty_name", "class_name": "TestRoles", "qualname": "TestRoles.test_patch_role_validation_404_empty_name", "file_path": "providers/fab/tests/unit/fab/auth_manager/api_fastapi/routes/test_roles.py", "repo_id": "apache/airflow", "loc": 14, "tested_modules": ["__future__",... |
langflow-ai/langflow:src/lfx/tests/unit/services/test_edge_cases.py:TestServiceLifecycle.test_service_teardown_called | # Context:
import pytest
from lfx.services.base import Service
from lfx.services.schema import ServiceType
class MockSessionService(Service): ...
def clean_manager(): ...
class TestCircularDependencyDetection: ...
class TestConfigParsingEdgeCases: ...
class TestServiceRegistrationEdgeCases: ...
class TestDependencyInj... | async def test_service_teardown_called(self, clean_manager):
"""Test that teardown is called on services."""
teardown_called = []
class TeardownTrackingService(Service):
name = "tracking_service"
def __init__(self):
super().__init__()
sel... | test | 1 | {"function_name": "test_service_teardown_called", "class_name": "TestServiceLifecycle", "qualname": "TestServiceLifecycle.test_service_teardown_called", "file_path": "src/lfx/tests/unit/services/test_edge_cases.py", "repo_id": "langflow-ai/langflow", "loc": 24, "tested_modules": ["lfx.services.base", "lfx.services.mana... |
langflow-ai/langflow:src/backend/base/langflow/agentic/flows/translation_flow.py:get_graph | # Context:
from lfx.components.input_output import ChatInput, ChatOutput
from lfx.components.models import LanguageModelComponent
from lfx.graph import Graph
def _build_model_config(provider: str, model_name: str) -> list[dict]: ...
# Task:
Write a Python function `get_graph` to create and return the TranslationFlow ... | def get_graph(
provider: str | None = None,
model_name: str | None = None,
api_key_var: str | None = None,
) -> Graph:
"""Create and return the TranslationFlow graph.
Args:
provider: Model provider (e.g., "OpenAI", "Anthropic"). Defaults to OpenAI.
model_name: Model name (e.g., "gpt... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 57, "code_loc": 28, "docstring_loc": 10, "function_name": "get_graph", "class_name": null, "qualname": "get_graph", "file_path": "src/backend/base/langflow/agentic/flows/translation_flow.py", "repo_id": "langflow-ai/langflow", "has_docstring": true, "runnable_level": "project_runnable... |
crewAIInc/crewAI:lib/crewai/tests/test_flow_ask.py:TestConsoleProviderInput.test_console_provider_non_verbose | # Context:
from unittest.mock import MagicMock, patch
from crewai.flow.async_feedback.providers import ConsoleProvider
from crewai.events.event_listener import event_listener
class MockInputProvider: ...
class SlowMockProvider: ...
class TestAskBasic: ...
class TestAskTimeout: ...
class TestProviderResolution: ...
cla... | def test_console_provider_non_verbose(self) -> None:
"""ConsoleProvider in non-verbose mode uses plain input."""
from crewai.events.event_listener import event_listener
mock_formatter = MagicMock()
mock_formatter.console = MagicMock()
provider = ConsoleProvider(verbose=False)
... | test | 0 | {"function_name": "test_console_provider_non_verbose", "class_name": "TestConsoleProviderInput", "qualname": "TestConsoleProviderInput.test_console_provider_non_verbose", "file_path": "lib/crewai/tests/test_flow_ask.py", "repo_id": "crewAIInc/crewAI", "loc": 17, "tested_modules": ["__future__", "datetime", "typing", "c... |
unclecode/crawl4ai:docs/examples/url_seeder/url_seeder_quick_demo.py:module_doc | Write a module-level docstring for the Python module `url_seeder_quick_demo` which contains various utilities. | 🚀 URL Seeder + AsyncWebCrawler = Magic!
Quick demo showing discovery → filter → crawl pipeline
Note: Uses context manager for automatic cleanup of resources. | documentation | 1 | {"doc_type": "module", "module_name": "url_seeder_quick_demo", "file_path": "docs/examples/url_seeder/url_seeder_quick_demo.py", "repo_id": "unclecode/crawl4ai", "char_length": 158} |
ray-project/ray:rllib/offline/tests/test_offline_rl_stateful.py:OfflineRLStatefulTest.test_training_with_recorded_states_on_single_episode_and_evaluate | # Context:
import numpy as np
from ray.rllib.core.learner.training_data import TrainingData
from ray.rllib.env import INPUT_ENV_SPACES
from ray.rllib.env.single_agent_episode import SingleAgentEpisode
from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch
import msgpack
import msgpack_numpy as mnp
clas... | def test_training_with_recorded_states_on_single_episode_and_evaluate(self):
"""Trains on a single episode from the recorded dataset and evaluates.
Uses recorded states for training.
"""
# Load these packages inline.
import msgpack
import msgpack_numpy as mnp
# ... | test | 0 | {"function_name": "test_training_with_recorded_states_on_single_episode_and_evaluate", "class_name": "OfflineRLStatefulTest", "qualname": "OfflineRLStatefulTest.test_training_with_recorded_states_on_single_episode_and_evaluate", "file_path": "rllib/offline/tests/test_offline_rl_stateful.py", "repo_id": "ray-project/ray... |
huggingface/diffusers:src/diffusers/models/autoencoders/autoencoder_kl_hunyuanimage.py:AutoencoderKLHunyuanImage.tiled_decode | # Context:
import torch
from .vae import AutoencoderMixin, DecoderOutput, DiagonalGaussianDistribution
class HunyuanImageResnetBlock(nn.Module): ...
class HunyuanImageAttentionBlock(nn.Module): ...
class HunyuanImageDownsample(nn.Module): ...
class HunyuanImageUpsample(nn.Module): ...
class HunyuanImageMidBlock(nn.Mod... | def tiled_decode(self, z: torch.Tensor, return_dict: bool = True) -> DecoderOutput | torch.Tensor:
"""
Decode latent using spatial tiling strategy.
Args:
z (`torch.Tensor`): Latent tensor of shape (B, C, H, W).
return_dict (`bool`, *optional*, defaults to `True`):
... | function_complex | 1 | {"cognitive_complexity": 13, "loc": 43, "code_loc": 26, "docstring_loc": 13, "function_name": "tiled_decode", "class_name": "AutoencoderKLHunyuanImage", "qualname": "AutoencoderKLHunyuanImage.tiled_decode", "file_path": "src/diffusers/models/autoencoders/autoencoder_kl_hunyuanimage.py", "repo_id": "huggingface/diffuser... |
langflow-ai/langflow:src/backend/tests/unit/utils/test_schemas.py:TestChatOutputResponse.test_chat_response_with_list_message | # Context:
from langflow.utils.schemas import ChatOutputResponse, ContainsEnumMeta, DataOutputResponse, File
class TestFile: ...
class TestDataOutputResponse: ...
class TestContainsEnumMeta: ...
class TestChatOutputResponse:
def test_basic_chat_response_creation(self): ...
def test_chat_response_with_all_fiel... | def test_chat_response_with_list_message(self):
"""Test chat response with list message."""
message_list = ["Hello", {"type": "text", "content": "world"}]
response = ChatOutputResponse(
message=message_list,
sender="Human", # Use non-AI sender to avoid message validatio... | test | 1 | {"function_name": "test_chat_response_with_list_message", "class_name": "TestChatOutputResponse", "qualname": "TestChatOutputResponse.test_chat_response_with_list_message", "file_path": "src/backend/tests/unit/utils/test_schemas.py", "repo_id": "langflow-ai/langflow", "loc": 11, "tested_modules": ["langflow.utils.schem... |
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/social_media_service.py:SocialMediaService.get_trending_topics | # Context:
from typing import List, Optional, Dict, Any
from fastapi import HTTPException
from services.db_service import social_media_db
class SocialMediaService:
async def get_posts(self, page: int, per_page: int, platform: Optional[str], user_handle: Optional[str], sentiment: Optional[str], category: Optional[s... | async def get_trending_topics(
self,
date_from: Optional[str] = None,
date_to: Optional[str] = None,
limit: int = 10
) -> List[Dict[str, Any]]:
"""Get trending topics with sentiment breakdown."""
try:
query_parts = [
"""
WI... | function_complex | 0 | {"cognitive_complexity": 21, "loc": 63, "code_loc": 56, "docstring_loc": 1, "function_name": "get_trending_topics", "class_name": "SocialMediaService", "qualname": "SocialMediaService.get_trending_topics", "file_path": "advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/social_media_service... |
google/langextract:langextract/prompt_validation.py:handle_alignment_report | # Context:
from absl import logging
class PromptValidationLevel(enum.Enum): ...
class _IssueKind(enum.Enum): ...
class ValidationIssue: ...
class ValidationReport: ...
class PromptAlignmentError(RuntimeError): ...
class AlignmentPolicy: ...
def _preview(s: str, n: int) -> str: ...
def validate_prompt_alignment(example... | def handle_alignment_report(
report: ValidationReport,
level: PromptValidationLevel,
*,
strict_non_exact: bool = False,
) -> None:
"""Log or raise based on validation level.
Args:
report: The validation report to handle.
level: The validation level determining behavior.
strict_non_exact... | function_complex | 1 | {"cognitive_complexity": 11, "loc": 47, "code_loc": 28, "docstring_loc": 10, "function_name": "handle_alignment_report", "class_name": null, "qualname": "handle_alignment_report", "file_path": "langextract/prompt_validation.py", "repo_id": "google/langextract", "has_docstring": true, "runnable_level": "project_runnable... |
infiniflow/ragflow:common/data_source/google_util/util_threadpool_concurrency.py:ThreadSafeDict.setdefault | # Context:
class ThreadSafeDict(MutableMapping[KT, VT]):
def __init__(self, input_dict: dict[KT, VT] | None = None) -> None:
self._dict: dict[KT, VT] = input_dict or {}
self.lock = threading.Lock()
def __getitem__(self, key: KT) -> VT: ...
def __setitem__(self, key: KT, value: VT) -> None: ... | def setdefault(self, key: KT, default: VT) -> VT:
"""Set a default value if key is missing, atomically."""
with self.lock:
return self._dict.setdefault(key, default) | function_simple | 1 | {"cognitive_complexity": 0, "loc": 4, "code_loc": 2, "docstring_loc": 1, "function_name": "setdefault", "class_name": "ThreadSafeDict", "qualname": "ThreadSafeDict.setdefault", "file_path": "common/data_source/google_util/util_threadpool_concurrency.py", "repo_id": "infiniflow/ragflow", "has_docstring": true, "runnable... |
vllm-project/vllm:tests/v1/worker/test_gpu_profiler.py:test_mixed_delay_and_stop | # Context:
class ConcreteWorkerProfiler(WorkerProfiler): ...
def default_profiler_config(): ...
def test_immediate_start_stop(default_profiler_config): ...
def test_delayed_start(default_profiler_config): ...
def test_max_iterations(default_profiler_config): ...
def test_delayed_start_and_max_iters(default_profiler_co... | def test_mixed_delay_and_stop(default_profiler_config):
"""Test manual stop during the delay period."""
default_profiler_config.delay_iterations = 5
profiler = ConcreteWorkerProfiler(default_profiler_config)
profiler.start()
profiler.step()
profiler.step()
# User cancels before delay finis... | test | 1 | {"function_name": "test_mixed_delay_and_stop", "class_name": null, "qualname": "test_mixed_delay_and_stop", "file_path": "tests/v1/worker/test_gpu_profiler.py", "repo_id": "vllm-project/vllm", "loc": 19, "tested_modules": ["vllm.config", "vllm.config.profiler", "vllm.profiler.wrapper"], "has_docstring": true, "runnable... |
browser-use/browser-use:examples/integrations/gmail_2fa_integration.py:GmailGrantManager.check_credentials_exist | # Context:
async def main(): ...
class GmailGrantManager:
def __init__(self):
self.config_dir = CONFIG.BROWSER_USE_CONFIG_DIR
self.credentials_file = self.config_dir / 'gmail_credentials.json'
self.token_file = self.config_dir / 'gmail_token.json'
print(f'GmailGrantManager initialized with config_dir: {self.... | def check_credentials_exist(self) -> bool:
"""Check if OAuth credentials file exists."""
return self.credentials_file.exists() | function_simple | 0 | {"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "check_credentials_exist", "class_name": "GmailGrantManager", "qualname": "GmailGrantManager.check_credentials_exist", "file_path": "examples/integrations/gmail_2fa_integration.py", "repo_id": "browser-use/browser-use", "has_docst... |
crewAIInc/crewAI:lib/crewai/tests/test_async_human_feedback.py:TestSQLitePendingFeedback.test_load_nonexistent_pending_feedback | # Context:
import os
import tempfile
from crewai.flow.persistence import SQLiteFlowPersistence
class TestPendingFeedbackContext: ...
class TestHumanFeedbackPending: ...
class TestHumanFeedbackProvider: ...
class TestConsoleProvider: ...
class TestCustomAsyncProvider: ...
class TestFlowResumeWithFeedback: ...
class Tes... | def test_load_nonexistent_pending_feedback(self) -> None:
"""Test loading pending feedback that doesn't exist."""
with tempfile.TemporaryDirectory() as tmpdir:
db_path = os.path.join(tmpdir, "test_flows.db")
persistence = SQLiteFlowPersistence(db_path)
result = persi... | test | 0 | {"function_name": "test_load_nonexistent_pending_feedback", "class_name": "TestSQLitePendingFeedback", "qualname": "TestSQLitePendingFeedback.test_load_nonexistent_pending_feedback", "file_path": "lib/crewai/tests/test_async_human_feedback.py", "repo_id": "crewAIInc/crewAI", "loc": 8, "tested_modules": ["__future__", "... |
apache/airflow:providers/google/tests/unit/google/cloud/operators/test_gen_ai.py:TestGenAIGeminiCreateEmbeddingsBatchJobOperator.test_execute_exception_error_raises_airflow_exception | # Context:
from unittest import mock
import pytest
from airflow.exceptions import AirflowException
from airflow.providers.google.cloud.operators.gen_ai import (
GenAICountTokensOperator,
GenAICreateCachedContentOperator,
GenAIGeminiCancelBatchJobOperator,
GenAIGeminiCreateBatchJobOperator,
GenAIGemi... | def test_execute_exception_error_raises_airflow_exception(self, mock_hook):
op = GenAIGeminiCreateEmbeddingsBatchJobOperator(
task_id=TASK_ID,
project_id=GCP_PROJECT,
location=GCP_LOCATION,
input_source=TEST_EMBEDDINGS_JOB_INLINED_REQUESTS,
model=EMBED... | test | 1 | {"function_name": "test_execute_exception_error_raises_airflow_exception", "class_name": "TestGenAIGeminiCreateEmbeddingsBatchJobOperator", "qualname": "TestGenAIGeminiCreateEmbeddingsBatchJobOperator.test_execute_exception_error_raises_airflow_exception", "file_path": "providers/google/tests/unit/google/cloud/operator... |
google/langextract:langextract/annotation.py:_emit_docs_iter | # Context:
from collections.abc import Iterable, Iterator
from langextract.core import data
def _merge_non_overlapping_extractions(all_extractions: list[Iterable[data.Extraction]]) -> list[data.Extraction]: ...
def _extractions_overlap(extraction1: data.Extraction, extraction2: data.Extraction) -> bool: ...
def _docum... | def _emit_docs_iter(
keep_last_doc: bool,
) -> Iterator[data.AnnotatedDocument]:
"""Yields documents that are guaranteed complete.
Args:
keep_last_doc: If True, retains the most recently started document
for additional extractions. If False, emits all remaining documents.
... | function_simple | 1 | {"cognitive_complexity": 2, "loc": 21, "code_loc": 12, "docstring_loc": 6, "function_name": "_emit_docs_iter", "class_name": null, "qualname": "_emit_docs_iter", "file_path": "langextract/annotation.py", "repo_id": "google/langextract", "has_docstring": true, "runnable_level": "project_runnable"} |
crewAIInc/crewAI:lib/crewai/tests/llms/test_tool_call_streaming.py:TestAnthropicToolCallStreaming:class_doc | Write a class-level docstring for `TestAnthropicToolCallStreaming` which has methods: `test_anthropic_streaming_emits_tool_call_events`. | Tests for Anthropic provider tool call streaming events. | documentation | 0 | {"doc_type": "class", "class_name": "TestAnthropicToolCallStreaming", "file_path": "lib/crewai/tests/llms/test_tool_call_streaming.py", "repo_id": "crewAIInc/crewAI", "char_length": 56, "methods": ["test_anthropic_streaming_emits_tool_call_events"]} |
ray-project/ray:python/ray/data/tests/datasource/test_databricks_credentials.py:TestCredentialProviderSerialization.test_provider_is_picklable | # Context:
import os
from unittest import mock
import pytest
from ray.data._internal.datasource.databricks_credentials import (
DatabricksCredentialProvider,
EnvironmentCredentialProvider,
StaticCredentialProvider,
resolve_credential_provider,
)
import pickle
class TestDatabricksCredentialProvider: ...... | def test_provider_is_picklable(self, provider_type, expected_token, expected_host):
"""Verify credential providers can be pickled and unpickled."""
import pickle
with mock.patch.dict(
os.environ,
{"DATABRICKS_TOKEN": expected_token, "DATABRICKS_HOST": expected_host},
... | test | 0 | {"function_name": "test_provider_is_picklable", "class_name": "TestCredentialProviderSerialization", "qualname": "TestCredentialProviderSerialization.test_provider_is_picklable", "file_path": "python/ray/data/tests/datasource/test_databricks_credentials.py", "repo_id": "ray-project/ray", "loc": 19, "tested_modules": ["... |
langflow-ai/langflow:src/backend/tests/integration/test_openai_responses_extended.py:test_openai_responses_concurrent_requests | # Context:
import asyncio
import pytest
from httpx import AsyncClient
def load_env_vars(): ...
async def create_global_variable(client: AsyncClient, headers, name, value, variable_type): ...
async def load_and_prepare_flow(client: AsyncClient, created_api_key): ...
async def load_and_prepare_agent_flow(client: AsyncCl... | async def test_openai_responses_concurrent_requests(client: AsyncClient, created_api_key):
"""Test handling of concurrent requests to the same flow."""
flow, headers = await load_and_prepare_flow(client, created_api_key)
# Create multiple concurrent requests
payloads = [{"model": flow["id"], "input": f... | test | 1 | {"function_name": "test_openai_responses_concurrent_requests", "class_name": null, "qualname": "test_openai_responses_concurrent_requests", "file_path": "src/backend/tests/integration/test_openai_responses_extended.py", "repo_id": "langflow-ai/langflow", "loc": 26, "tested_modules": ["dotenv", "httpx", "lfx.log.logger"... |
Shubhamsaboo/awesome-llm-apps:ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/agent.py:show_streaming_features | Write a Python function `show_streaming_features` to display information about streaming voice features. | def show_streaming_features():
"""Display information about streaming voice features."""
print("🌊 Streaming Voice Features:")
print("=" * 40)
print()
print("✨ Real-time Features:")
print(" • Continuous audio input processing")
print(" • Automatic speech activity detection")
print(" •... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 25, "code_loc": 23, "docstring_loc": 1, "function_name": "show_streaming_features", "class_name": null, "qualname": "show_streaming_features", "file_path": "ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/agent.py", "repo_id": "Shubhamsaboo/awesome-llm-apps",... |
ray-project/ray:ci/raydepsets/tests/test_cli.py:TestCli.test_execute_single_depset | # Context:
import tempfile
from ci.raydepsets.tests.utils import (
append_to_file,
copy_data_to_tmpdir,
replace_in_file,
save_file_as,
save_packages_to_file,
write_to_config_file,
)
def _create_test_manager(tmpdir: str, config_path: Optional[str], check: bool, build_all_configs: Optional[bool])... | def test_execute_single_depset(self):
with tempfile.TemporaryDirectory() as tmpdir:
copy_data_to_tmpdir(tmpdir)
manager = _create_test_manager(tmpdir)
manager.execute(single_depset_name="general_depset__py311_cpu")
assert (
manager.build_graph.node... | test | 0 | {"function_name": "test_execute_single_depset", "class_name": "TestCli", "qualname": "TestCli.test_execute_single_depset", "file_path": "ci/raydepsets/tests/test_cli.py", "repo_id": "ray-project/ray", "loc": 10, "tested_modules": ["pathlib", "typing", "click.testing", "networkx", "ci.raydepsets.cli"], "has_docstring": ... |
zhayujie/chatgpt-on-wechat:common/cloud_client.py:CloudClient.on_skill | # Context:
from common.log import logger
def start(channel, channel_mgr): ...
def _build_config(): ...
class CloudClient(LinkAIClient):
def __init__(self, api_key: str, channel, host: str = ""):
super().__init__(api_key, host)
self.channel = channel
self.client_type = channel.channel_type
... | def on_skill(self, data: dict) -> dict:
"""
Handle SKILL messages from the cloud console.
Delegates to SkillService.dispatch for the actual operations.
:param data: message data with 'action', 'clientId', 'payload'
:return: response dict
"""
action = data.get("ac... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 17, "code_loc": 7, "docstring_loc": 7, "function_name": "on_skill", "class_name": "CloudClient", "qualname": "CloudClient.on_skill", "file_path": "common/cloud_client.py", "repo_id": "zhayujie/chatgpt-on-wechat", "has_docstring": true, "runnable_level": "project_runnable"} |
huggingface/transformers:tests/models/flex_olmo/test_modeling_flex_olmo.py:FlexOlmoIntegrationTest.test_model_7b_greedy_generation | # Context:
from transformers.models.auto.tokenization_auto import AutoTokenizer
from transformers import (
FlexOlmoForCausalLM,
FlexOlmoModel,
)
class FlexOlmoModelTester(CausalLMModelTester): ...
class FlexOlmoModelTest(CausalLMModelTest, unittest.TestCase): ...
class FlexOlmoIntegrationTest(unit... | def test_model_7b_greedy_generation(self):
EXPECTED_TEXT_COMPLETION = """Simply put, the theory of relativity states that 1) the laws of physics are the same in all inertial frames of reference, and 2) the speed of light is constant in all inertial frames of reference. The first statement is called the principl... | test | 0 | {"function_name": "test_model_7b_greedy_generation", "class_name": "FlexOlmoIntegrationTest", "qualname": "FlexOlmoIntegrationTest.test_model_7b_greedy_generation", "file_path": "tests/models/flex_olmo/test_modeling_flex_olmo.py", "repo_id": "huggingface/transformers", "loc": 11, "tested_modules": ["transformers", "tra... |
huggingface/pytorch-image-models:timm/optim/muon.py:_single_tensor_muon | # Context:
from typing import List, Mapping, Optional, Sequence, Tuple, Union
import torch
def scale_eps_for_ns(eps: float, shape: Tuple[int, ...]) -> float: ...
def zeropower_via_newtonschulz(G: torch.Tensor, steps: int, coefficients: List[Tuple[float, float, float]], eps: float, safety_factor: float, dtype: torch.dt... | def _single_tensor_muon(
params: List[torch.Tensor],
grads: List[torch.Tensor],
momentum_bufs: List[torch.Tensor],
*,
lr: float,
weight_decay: float,
momentum: float,
nesterov: bool,
ns_steps: int,
ns_coefficients: NSCoeff,
eps: flo... | function_complex | 1 | {"cognitive_complexity": 15, "loc": 67, "code_loc": 30, "docstring_loc": 1, "function_name": "_single_tensor_muon", "class_name": null, "qualname": "_single_tensor_muon", "file_path": "timm/optim/muon.py", "repo_id": "huggingface/pytorch-image-models", "has_docstring": true, "runnable_level": "file_runnable"} |
fastapi/fastapi:tests/test_tutorial/test_stream_data/test_tutorial002.py:test_stream_image | # Context:
import pytest
from fastapi.testclient import TestClient
def get_mod(request: pytest.FixtureRequest): ...
def get_client(mod): ...
def test_openapi_schema(client: TestClient): ...
# Task:
Write a Python test function `test_stream_image` to verify the behavior of `stream_image`.
Module under test: fastapi.t... | def test_stream_image(mod, client: TestClient, path: str):
response = client.get(path)
assert response.status_code == 200
assert response.headers["content-type"] == "image/png"
assert response.content == mod.binary_image | test | 1 | {"function_name": "test_stream_image", "class_name": null, "qualname": "test_stream_image", "file_path": "tests/test_tutorial/test_stream_data/test_tutorial002.py", "repo_id": "fastapi/fastapi", "loc": 5, "tested_modules": ["fastapi.testclient", "inline_snapshot"], "has_docstring": false, "runnable_level": "project_run... |
apache/airflow:providers/informatica/tests/unit/informatica/hooks/test_edc.py:test_config_property_and_build_connection_config | # Context:
from unittest.mock import MagicMock, patch
def hook(): ...
def test_get_conn_headers_and_verify(mock_get_conn, mock_get_connection, hook): ...
def test_build_url(hook): ...
def test_request_success_and_error(mock_get_conn, hook): ...
def test_encode_id(hook): ...
def test_get_object(mock_request, hook): ...... | def test_config_property_and_build_connection_config(mock_get_connection, hook):
"""Test config property and _build_connection_config method."""
mock_conn = MagicMock()
mock_conn.host = "testhost"
mock_conn.schema = "https"
mock_conn.port = 443
mock_conn.login = "user"
mock_conn.password = "... | test | 1 | {"function_name": "test_config_property_and_build_connection_config", "class_name": null, "qualname": "test_config_property_and_build_connection_config", "file_path": "providers/informatica/tests/unit/informatica/hooks/test_edc.py", "repo_id": "apache/airflow", "loc": 25, "tested_modules": ["__future__", "airflow.provi... |
browser-use/browser-use:browser_use/mcp/server.py:BrowserUseServer._close_session | # Context:
def _configure_mcp_server_logging(): ...
def _ensure_all_loggers_use_stderr(): ...
def get_parent_process_cmdline() -> str | None: ...
async def main(session_timeout_minutes: int): ...
class BrowserUseServer:
def __init__(self, session_timeout_minutes: int = 10):
# Ensure all logging goes to stderr (in ... | async def _close_session(self, session_id: str) -> str:
"""Close a specific browser session."""
if session_id not in self.active_sessions:
return f'Session {session_id} not found'
session_data = self.active_sessions[session_id]
session = session_data['session']
try:
# Close the session
if hasattr(s... | function_complex | 0 | {"cognitive_complexity": 8, "loc": 26, "code_loc": 16, "docstring_loc": 1, "function_name": "_close_session", "class_name": "BrowserUseServer", "qualname": "BrowserUseServer._close_session", "file_path": "browser_use/mcp/server.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "class_r... |
huggingface/transformers:src/transformers/models/idefics3/image_processing_idefics3_fast.py:_resize_output_size_rescale_to_max_len | Write a Python function `_resize_output_size_rescale_to_max_len` to get the output size of the image after resizing given a dictionary specifying the max and min sizes.
Parameters: height: int, width: int, min_len: int | None, max_len: int | None
Returns: tuple[int, int] | def _resize_output_size_rescale_to_max_len(
height: int, width: int, min_len: int | None = 1, max_len: int | None = None
) -> tuple[int, int]:
"""
Get the output size of the image after resizing given a dictionary specifying the max and min sizes.
Args:
height (`int`):
Height of the ... | function_complex | 0 | {"cognitive_complexity": 7, "loc": 35, "code_loc": 15, "docstring_loc": 14, "function_name": "_resize_output_size_rescale_to_max_len", "class_name": null, "qualname": "_resize_output_size_rescale_to_max_len", "file_path": "src/transformers/models/idefics3/image_processing_idefics3_fast.py", "repo_id": "huggingface/tran... |
huggingface/pytorch-image-models:timm/models/csatv2.py:LearnableDct2d.init_non_persistent_buffers | # Context:
def _zigzag_permutation(rows: int, cols: int) -> List[int]: ...
def _dct_kernel_type_2(kernel_size: int, orthonormal: bool, device, dtype) -> torch.Tensor: ...
def _dct_kernel_type_3(kernel_size: int, orthonormal: bool, device, dtype) -> torch.Tensor: ...
class Dct1d(nn.Module): ...
class Dct2d(nn.Module): ... | def init_non_persistent_buffers(self) -> None:
"""Initialize non-persistent buffers."""
self._init_buffers() | function_simple | 1 | {"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "init_non_persistent_buffers", "class_name": "LearnableDct2d", "qualname": "LearnableDct2d.init_non_persistent_buffers", "file_path": "timm/models/csatv2.py", "repo_id": "huggingface/pytorch-image-models", "has_docstring": true, "... |
infiniflow/ragflow:test/testcases/test_web_api/test_search_app/test_search_crud.py:TestSearchCrud.test_create_and_rm | # Context:
import pytest
from common import search_create, search_detail, search_list, search_rm, search_update
def _search_name(prefix): ...
def _find_tenant_id(WebApiAuth, search_id): ...
def search_app(WebApiAuth): ...
class TestAuthorization: ...
class TestSearchCrud:
def test_list(self, WebApiAuth, search_ap... | def test_create_and_rm(self, WebApiAuth):
name = _search_name("create")
create_res = search_create(WebApiAuth, {"name": name, "description": "test search"})
assert create_res["code"] == 0, create_res
search_id = create_res["data"]["search_id"]
rm_res = search_rm(WebApiAuth, {"se... | test | 1 | {"function_name": "test_create_and_rm", "class_name": "TestSearchCrud", "qualname": "TestSearchCrud.test_create_and_rm", "file_path": "test/testcases/test_web_api/test_search_app/test_search_crud.py", "repo_id": "infiniflow/ragflow", "loc": 9, "tested_modules": ["common", "configs", "libs.auth"], "has_docstring": false... |
unclecode/crawl4ai:crawl4ai/async_crawler_strategy.back.py:AsyncPlaywrightCrawlerStrategy.export_storage_state | # Context:
class AsyncCrawlerStrategy(ABC): ...
class HTTPCrawlerError(Exception): ...
class ConnectionTimeoutError(HTTPCrawlerError): ...
class HTTPStatusError(HTTPCrawlerError): ...
class AsyncHTTPCrawlerStrategy(AsyncCrawlerStrategy): ...
class AsyncPlaywrightCrawlerStrategy(AsyncCrawlerStrategy):
def __init__... | async def export_storage_state(self, path: str = None) -> dict:
"""
Exports the current storage state (cookies, localStorage, sessionStorage)
to a JSON file at the specified path.
Args:
path (str): The path to save the storage state JSON file
Returns:
di... | function_simple | 1 | {"cognitive_complexity": 2, "loc": 24, "code_loc": 13, "docstring_loc": 10, "function_name": "export_storage_state", "class_name": "AsyncPlaywrightCrawlerStrategy", "qualname": "AsyncPlaywrightCrawlerStrategy.export_storage_state", "file_path": "crawl4ai/async_crawler_strategy.back.py", "repo_id": "unclecode/crawl4ai",... |
langflow-ai/langflow:src/lfx/src/lfx/components/processing/text_operations.py:TextOperations._text_to_dataframe | # Context:
import pandas as pd
from lfx.schema.dataframe import DataFrame
class TextOperations(Component):
display_name = "Text Operations"
description = "Perform various text processing operations including text-to-DataFrame conversion."
icon = "type"
name = "TextOperations"
inputs = [
outputs... | def _text_to_dataframe(self, text: str) -> DataFrame:
"""Convert markdown-style table text to DataFrame."""
lines = [line.strip() for line in text.strip().split("\n") if line.strip()]
if not lines:
return DataFrame(pd.DataFrame())
separator = getattr(self, "table_separator",... | function_simple | 1 | {"cognitive_complexity": 2, "loc": 18, "code_loc": 12, "docstring_loc": 1, "function_name": "_text_to_dataframe", "class_name": "TextOperations", "qualname": "TextOperations._text_to_dataframe", "file_path": "src/lfx/src/lfx/components/processing/text_operations.py", "repo_id": "langflow-ai/langflow", "has_docstring": ... |
google/langextract:langextract/prompting.py:read_prompt_template_structured_from_file | # Context:
import json
import pathlib
import pydantic
import yaml
from langextract.core import data
class PromptBuilderError(exceptions.LangExtractError): ...
class ParseError(PromptBuilderError): ...
class PromptTemplateStructured: ...
class QAPromptGenerator: ...
class PromptBuilder: ...
class ContextAwarePromptBuil... | def read_prompt_template_structured_from_file(
prompt_path: str,
format_type: data.FormatType = data.FormatType.YAML,
) -> PromptTemplateStructured:
"""Reads a structured prompt template from a file.
Args:
prompt_path: Path to a file containing PromptTemplateStructured data.
format_type: The format... | function_simple | 1 | {"cognitive_complexity": 5, "loc": 30, "code_loc": 14, "docstring_loc": 12, "function_name": "read_prompt_template_structured_from_file", "class_name": null, "qualname": "read_prompt_template_structured_from_file", "file_path": "langextract/prompting.py", "repo_id": "google/langextract", "has_docstring": true, "runnabl... |
crewAIInc/crewAI:lib/crewai/tests/utilities/test_pydantic_schema_utils.py:TestBuildRichFieldDescription.test_combined_constraints | # Context:
from crewai.utilities.pydantic_schema_utils import (
build_rich_field_description,
convert_oneof_to_anyof,
create_model_from_schema,
ensure_all_properties_required,
ensure_type_in_schemas,
force_additional_properties_false,
resolve_refs,
strip_null_from_types,
strip_unsupp... | def test_combined_constraints(self) -> None:
desc = build_rich_field_description({
"description": "A score",
"minimum": 0,
"maximum": 10,
"format": "int32",
})
assert desc.startswith("A score")
assert "Minimum: 0" in desc
assert "Ma... | test | 0 | {"function_name": "test_combined_constraints", "class_name": "TestBuildRichFieldDescription", "qualname": "TestBuildRichFieldDescription.test_combined_constraints", "file_path": "lib/crewai/tests/utilities/test_pydantic_schema_utils.py", "repo_id": "crewAIInc/crewAI", "loc": 11, "tested_modules": ["__future__", "copy",... |
unclecode/crawl4ai:tests/test_raw_html_browser.py:test_screenshot_on_raw_html | # Context:
import pytest
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
async def test_raw_html_fast_path(): ...
async def test_js_code_on_raw_html(): ...
async def test_js_code_adds_element_to_raw_html(): ...
async def test_process_in_browser_flag(): ...
async def test_raw_prefix_variations(): ...
async def t... | async def test_screenshot_on_raw_html():
"""Test that screenshots work on raw: HTML."""
html = "<html><body><h1 style='color:red;font-size:48px;'>Screenshot Test</h1></body></html>"
async with AsyncWebCrawler() as crawler:
config = CrawlerRunConfig(screenshot=True)
result = await crawler.ar... | test | 1 | {"function_name": "test_screenshot_on_raw_html", "class_name": null, "qualname": "test_screenshot_on_raw_html", "file_path": "tests/test_raw_html_browser.py", "repo_id": "unclecode/crawl4ai", "loc": 11, "tested_modules": ["crawl4ai"], "has_docstring": true, "runnable_level": "project_runnable"} |
langflow-ai/langflow:src/backend/tests/unit/api/v2/test_converters.py:TestParseFlatInputs.test_parse_flat_inputs_with_session_id | # Context:
from langflow.api.v2.converters import (
_build_metadata_for_non_output,
_extract_file_path,
_extract_model_source,
_extract_nested_value,
_extract_text_from_message,
_get_raw_content,
_simplify_output_content,
create_error_response,
create_job_response,
parse_flat_inp... | def test_parse_flat_inputs_with_session_id(self):
"""Test parsing with session_id extraction."""
inputs = {
"ChatInput-abc.input_value": "hello",
"ChatInput-abc.session_id": "session-123",
"LLM-xyz.temperature": 0.7,
}
tweaks, session_id = parse_flat_i... | test | 1 | {"function_name": "test_parse_flat_inputs_with_session_id", "class_name": "TestParseFlatInputs", "qualname": "TestParseFlatInputs.test_parse_flat_inputs_with_session_id", "file_path": "src/backend/tests/unit/api/v2/test_converters.py", "repo_id": "langflow-ai/langflow", "loc": 14, "tested_modules": ["__future__", "typi... |
ray-project/ray:python/ray/dashboard/tests/test_dashboard_auth.py:test_authentication_mode_endpoint_with_token_auth | # Context:
import requests
def test_dashboard_request_requires_auth_with_valid_token(setup_cluster_with_token_auth): ...
def test_dashboard_request_requires_auth_missing_token(setup_cluster_with_token_auth): ...
def test_dashboard_request_requires_auth_invalid_token(setup_cluster_with_token_auth): ...
def test_dashboa... | def test_authentication_mode_endpoint_with_token_auth(setup_cluster_with_token_auth):
"""Test authentication_mode endpoint returns 'token' when auth is enabled."""
cluster_info = setup_cluster_with_token_auth
# This endpoint should be accessible WITHOUT authentication
response = requests.get(f"{cluste... | test | 0 | {"function_name": "test_authentication_mode_endpoint_with_token_auth", "class_name": null, "qualname": "test_authentication_mode_endpoint_with_token_auth", "file_path": "python/ray/dashboard/tests/test_dashboard_auth.py", "repo_id": "ray-project/ray", "loc": 10, "tested_modules": [], "has_docstring": true, "runnable_le... |
langflow-ai/langflow:src/lfx/src/lfx/services/manager.py:ServiceManager.register_factories | # Context:
from lfx.log.logger import logger
from lfx.services.factory import ServiceFactory
class NoFactoryRegisteredError(Exception): ...
class NoServiceRegisteredError(Exception): ...
def get_service_manager() -> ServiceManager: ...
class ServiceManager:
def __init__(self) -> None:
"""Initialize the se... | def register_factories(self, factories: list[ServiceFactory] | None = None) -> None:
"""Register all available service factories."""
if factories is None:
return
for factory in factories:
try:
self.register_factory(factory)
except Exception: #... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 10, "code_loc": 8, "docstring_loc": 1, "function_name": "register_factories", "class_name": "ServiceManager", "qualname": "ServiceManager.register_factories", "file_path": "src/lfx/src/lfx/services/manager.py", "repo_id": "langflow-ai/langflow", "has_docstring": true, "runnable_level"... |
browser-use/browser-use:browser_use/browser/watchdogs/dom_watchdog.py:DOMWatchdog._get_page_info | # Context:
import asyncio
from browser_use.browser.views import BrowserStateSummary, NetworkRequest, PageInfo, PaginationButton
from browser_use.browser.views import BrowserStateSummary, PageInfo
from browser_use.browser.views import PageInfo
class DOMWatchdog(BaseWatchdog):
LISTENS_TO = [TabCreatedEvent, BrowserS... | async def _get_page_info(self) -> 'PageInfo':
"""Get comprehensive page information using a single CDP call.
TODO: should we make this an event as well?
Returns:
PageInfo with all viewport, page dimensions, and scroll information
"""
from browser_use.browser.views import PageInfo
# get_or_create_cdp_... | function_simple | 0 | {"cognitive_complexity": 5, "loc": 71, "code_loc": 40, "docstring_loc": 7, "function_name": "_get_page_info", "class_name": "DOMWatchdog", "qualname": "DOMWatchdog._get_page_info", "file_path": "browser_use/browser/watchdogs/dom_watchdog.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level"... |
crewAIInc/crewAI:lib/crewai/tests/project/test_callback_with_taskoutput.py:test_callback_decorator_with_taskoutput_integration | # Context:
from unittest.mock import MagicMock, patch
from crewai import Agent, Crew, Task
from crewai.project import CrewBase, callback, task
from crewai.tasks.task_output import TaskOutput
def test_callback_decorator_with_taskoutput() -> None: ...
# Task:
Write a Python test function `test_callback_decorator_with_t... | def test_callback_decorator_with_taskoutput_integration() -> None:
"""Integration test for callback with actual task execution."""
@CrewBase
class TestCrew:
"""Test crew with callback integration."""
callback_called = False
received_output: TaskOutput | None = None
@callba... | test | 0 | {"function_name": "test_callback_decorator_with_taskoutput_integration", "class_name": null, "qualname": "test_callback_decorator_with_taskoutput_integration", "file_path": "lib/crewai/tests/project/test_callback_with_taskoutput.py", "repo_id": "crewAIInc/crewAI", "loc": 43, "tested_modules": ["crewai", "crewai.project... |
vllm-project/vllm:tests/distributed/test_shm_buffer.py:TestSingleWriterShmRingBuffer.test_buffer_opening | # Context:
from vllm.distributed.device_communicators.shm_object_storage import (
SingleWriterShmRingBuffer,
)
def main(): ...
class TestSingleWriterShmRingBuffer(unittest.TestCase):
def setUp(self): ...
def tearDown(self): ...
def test_buffer_access(self): ...
def test_memory_error_on_full_buffer... | def test_buffer_opening(self):
"""Test opening an existing buffer"""
# First create a buffer
self.ring_buffer = SingleWriterShmRingBuffer(
data_buffer_size=self.buffer_size, create=True
)
# Then open it with another instance
reader_buffer = SingleWriterShmRin... | test | 1 | {"function_name": "test_buffer_opening", "class_name": "TestSingleWriterShmRingBuffer", "qualname": "TestSingleWriterShmRingBuffer.test_buffer_opening", "file_path": "tests/distributed/test_shm_buffer.py", "repo_id": "vllm-project/vllm", "loc": 13, "tested_modules": ["vllm.distributed.device_communicators.shm_object_st... |
infiniflow/ragflow:common/data_source/connector_runner.py:ConnectorRunner:class_doc | Write a class-level docstring for `ConnectorRunner` (inherits from Generic[CT]) which has methods: `__init__`, `run`. | Handles:
- Batching
- Additional exception logging
- Combining different connector types to a single interface | documentation | 1 | {"doc_type": "class", "class_name": "ConnectorRunner", "file_path": "common/data_source/connector_runner.py", "repo_id": "infiniflow/ragflow", "char_length": 122, "methods": ["__init__", "run"]} |
langflow-ai/langflow:src/lfx/src/lfx/services/mcp_composer/service.py:MCPComposerService._is_port_available | # Context:
import socket
import errno
class MCPComposerError(Exception): ...
class MCPComposerPortError(MCPComposerError): ...
class MCPComposerConfigError(MCPComposerError): ...
class MCPComposerDisabledError(MCPComposerError): ...
class MCPComposerStartupError(MCPComposerError): ...
def require_composer_enabled(func... | def _is_port_available(self, port: int, host: str = "localhost") -> bool:
"""Check if a port is available by trying to bind to it.
Args:
port: Port number to check
host: Host to check (default: localhost)
Returns:
True if port is available (not in use), Fals... | function_complex | 1 | {"cognitive_complexity": 9, "loc": 49, "code_loc": 18, "docstring_loc": 12, "function_name": "_is_port_available", "class_name": "MCPComposerService", "qualname": "MCPComposerService._is_port_available", "file_path": "src/lfx/src/lfx/services/mcp_composer/service.py", "repo_id": "langflow-ai/langflow", "has_docstring":... |
huggingface/diffusers:tests/hooks/test_mag_cache.py:MagCacheTests.test_mag_cache_reset | # Context:
import numpy as np
import torch
from diffusers import MagCacheConfig, apply_mag_cache
class DummyBlock(torch.nn.Module): ...
class DummyTransformer(ModelMixin): ...
class TupleOutputBlock(torch.nn.Module): ...
class TupleTransformer(ModelMixin): ...
class MagCacheTests(unittest.TestCase):
def setUp(sel... | def test_mag_cache_reset(self):
"""Test that state resets correctly after num_inference_steps."""
model = DummyTransformer()
config = MagCacheConfig(
threshold=100.0, num_inference_steps=2, retention_ratio=0.0, mag_ratios=np.array([1.0, 1.0])
)
apply_mag_cache(model, ... | test | 1 | {"function_name": "test_mag_cache_reset", "class_name": "MagCacheTests", "qualname": "MagCacheTests.test_mag_cache_reset", "file_path": "tests/hooks/test_mag_cache.py", "repo_id": "huggingface/diffusers", "loc": 20, "tested_modules": ["diffusers", "diffusers.hooks._helpers", "diffusers.models", "diffusers.utils"], "has... |
run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_browser.py:TestAgentCoreBrowserToolSpec.test_get_elements | # Context:
from unittest.mock import patch, MagicMock
from llama_index.tools.aws_bedrock_agentcore import AgentCoreBrowserToolSpec
class TestGetAwsRegion: ...
class TestBrowserUtils: ...
class TestAgentCoreBrowserToolSpec:
def test_init(self, mock_browser_session_manager): ...
def test_init_default_region(sel... | def test_get_elements(self, mock_get_current_page):
mock_session_manager = MagicMock()
mock_browser = MagicMock()
mock_page = MagicMock()
mock_element1 = MagicMock()
mock_element2 = MagicMock()
mock_session_manager.get_sync_browser.return_value = mock_browser
moc... | test | 1 | {"function_name": "test_get_elements", "class_name": "TestAgentCoreBrowserToolSpec", "qualname": "TestAgentCoreBrowserToolSpec.test_get_elements", "file_path": "llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_browser.py", "repo_id": "run-llama/llama_index", "loc": 37, "tested_modules":... |
infiniflow/ragflow:tools/es-to-oceanbase-migration/tests/test_schema.py:TestVectorFieldPattern.test_invalid_patterns | # Context:
from es_ob_migration.schema import (
RAGFlowSchemaConverter,
RAGFlowDataConverter,
RAGFLOW_COLUMNS,
ARRAY_COLUMNS,
JSON_COLUMNS,
VECTOR_FIELD_PATTERN,
FTS_COLUMNS_ORIGIN,
FTS_COLUMNS_TKS,
)
class TestRAGFlowSchemaConverter: ...
class TestRAGFlowDataConverter: ...
class TestCo... | def test_invalid_patterns(self):
"""Test invalid vector field patterns."""
invalid_names = [
"q_vec",
"768_vec",
"q_768",
"vector_768",
"content_with_weight",
]
for name in invalid_names:
match = VECTOR_FIEL... | test | 1 | {"function_name": "test_invalid_patterns", "class_name": "TestVectorFieldPattern", "qualname": "TestVectorFieldPattern.test_invalid_patterns", "file_path": "tools/es-to-oceanbase-migration/tests/test_schema.py", "repo_id": "infiniflow/ragflow", "loc": 13, "tested_modules": ["es_ob_migration.schema"], "has_docstring": t... |
unclecode/crawl4ai:docs/examples/deep_crawl_crash_recovery.py:example_export_state | # Context:
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
from crawl4ai.deep_crawling import BFSDeepCrawlStrategy
async def save_state_to_file(state: Dict[str, Any]) -> None: ...
def load_state_from_file() -> Dict[str, Any] | None: ...
async def example_basic_state_persistence(): ...
async def example_crash_an... | async def example_export_state():
"""
Example 3: Manual state export using export_state().
If you don't need real-time persistence, you can export
the state manually after the crawl completes.
"""
print("\n" + "=" * 60)
print("Example 3: Manual State Export")
print("=" * 60)
strate... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 31, "code_loc": 16, "docstring_loc": 6, "function_name": "example_export_state", "class_name": null, "qualname": "example_export_state", "file_path": "docs/examples/deep_crawl_crash_recovery.py", "repo_id": "unclecode/crawl4ai", "has_docstring": true, "runnable_level": "project_runnab... |
vllm-project/vllm:vllm/model_executor/layers/quantization/utils/flashinfer_utils.py:register_scales_for_trtllm_fp8_per_tensor_moe | # Context:
import torch
class FlashinferMoeBackend(Enum): ...
def activation_to_flashinfer_int(activation: MoEActivation) -> int: ...
def swap_w13_to_w31(x: torch.Tensor) -> torch.Tensor: ...
def rotate_weights_for_fi_trtllm_fp8_per_tensor_moe(gemm1_weights: torch.Tensor, gemm2_weights: torch.Tensor, is_gated_activati... | def register_scales_for_trtllm_fp8_per_tensor_moe(
layer: torch.nn.Module,
w13_scale: torch.Tensor,
w13_input_scale: torch.Tensor,
w2_scale: torch.Tensor,
w2_input_scale: torch.Tensor,
) -> None:
"""Register necessary scales for FlashInfer TRTLLM FP8 MoE kernel"""
g1_alphas, g2_alphas = make... | function_simple | 1 | {"cognitive_complexity": 2, "loc": 24, "code_loc": 15, "docstring_loc": 1, "function_name": "register_scales_for_trtllm_fp8_per_tensor_moe", "class_name": null, "qualname": "register_scales_for_trtllm_fp8_per_tensor_moe", "file_path": "vllm/model_executor/layers/quantization/utils/flashinfer_utils.py", "repo_id": "vllm... |
crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/gemini/completion.py:GeminiCompletion._format_messages_for_gemini | # Context:
import base64
import json
from typing import TYPE_CHECKING, Any, Literal, cast
from crewai.utilities.types import LLMMessage
from google.genai import types
class GeminiCompletion(BaseLLM):
def __init__(
self,
model: str = "gemini-2.0-flash-001",
api_key: str | None = None,
... | def _format_messages_for_gemini(
self, messages: str | list[LLMMessage]
) -> tuple[list[types.Content], str | None]:
"""Format messages for Gemini API.
Gemini has specific requirements:
- System messages are separate system_instruction
- Content is organized as Content objec... | function_complex | 0 | {"cognitive_complexity": 79, "loc": 123, "code_loc": 88, "docstring_loc": 13, "function_name": "_format_messages_for_gemini", "class_name": "GeminiCompletion", "qualname": "GeminiCompletion._format_messages_for_gemini", "file_path": "lib/crewai/src/crewai/llms/providers/gemini/completion.py", "repo_id": "crewAIInc/crew... |
geekcomputers/Python:bank_managment_system/QTFrontend.py:create_page_with_header | # Context:
from PyQt5 import QtCore, QtGui, QtWidgets
def create_styled_frame(parent, min_size, style): ...
def create_styled_label(parent, text, font_size, bold, style): ...
def create_styled_button(parent, text, min_size): ...
def create_input_field(parent, label_text, min_label_size): ...
def create_input_field_V(p... | def create_page_with_header(parent, title_text):
"""Create a page with a styled header and return the page + main layout."""
page = QtWidgets.QWidget(parent)
main_layout = QtWidgets.QVBoxLayout(page)
main_layout.setContentsMargins(20, 20, 20, 20)
main_layout.setSpacing(20)
header_frame = create... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 16, "code_loc": 12, "docstring_loc": 1, "function_name": "create_page_with_header", "class_name": null, "qualname": "create_page_with_header", "file_path": "bank_managment_system/QTFrontend.py", "repo_id": "geekcomputers/Python", "has_docstring": true, "runnable_level": "project_runna... |
Zie619/n8n-workflows:api_server.py:module_doc | Write a module-level docstring for the Python module `api_server` which contains function `check_rate_limit`, function `validate_filename`, class `WorkflowSummary`, class `SearchResponse`, class `StatsResponse`. | FastAPI Server for N8N Workflow Documentation
High-performance API with sub-100ms response times. | documentation | 0 | {"doc_type": "module", "module_name": "api_server", "file_path": "api_server.py", "repo_id": "Zie619/n8n-workflows", "char_length": 97} |
browser-use/browser-use:browser_use/browser/watchdogs/local_browser_watchdog.py:LocalBrowserWatchdog.browser_pid | # Context:
class LocalBrowserWatchdog(BaseWatchdog):
async def on_BrowserLaunchEvent(self, event: BrowserLaunchEvent) -> BrowserLaunchResult: ...
async def on_BrowserKillEvent(self, event: BrowserKillEvent) -> None: ...
async def on_BrowserStopEvent(self, event: BrowserStopEvent) -> None: ...
async def... | def browser_pid(self) -> int | None:
"""Get the browser process ID."""
if self._subprocess:
return self._subprocess.pid
return None | function_simple | 0 | {"cognitive_complexity": 1, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "browser_pid", "class_name": "LocalBrowserWatchdog", "qualname": "LocalBrowserWatchdog.browser_pid", "file_path": "browser_use/browser/watchdogs/local_browser_watchdog.py", "repo_id": "browser-use/browser-use", "has_docstring": tr... |
apache/airflow:airflow-core/src/airflow/utils/dag_version_inflation_checker.py:DagTaskDetector.is_dag_constructor | # Context:
import ast
class DagVersionInflationCheckLevel(Enum): ...
class DagVersionInflationCheckResult: ...
class RuntimeVaryingValueWarning: ...
class WarningContext(str, Enum): ...
class RuntimeVaryingValueAnalyzer: ...
class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor): ...
def check_dag_file_stability(fil... | def is_dag_constructor(self, node: ast.Call) -> bool:
"""Check if a call is a Dag constructor."""
if not isinstance(node.func, ast.Name):
return False
func_name = node.func.id
# "from airflow import DAG" form or "from airflow.decorator import dag"
if func_name in se... | function_complex | 1 | {"cognitive_complexity": 6, "loc": 14, "code_loc": 8, "docstring_loc": 1, "function_name": "is_dag_constructor", "class_name": "DagTaskDetector", "qualname": "DagTaskDetector.is_dag_constructor", "file_path": "airflow-core/src/airflow/utils/dag_version_inflation_checker.py", "repo_id": "apache/airflow", "has_docstring"... |
browser-use/browser-use:tests/ci/test_coordinate_clicking.py:TestCoordinateClickingTools.test_default_uses_index_only_action | # Context:
from browser_use.tools.service import Tools
from browser_use.tools.views import ClickElementAction, ClickElementActionIndexOnly
class TestCoordinateClickingModelDetection: ...
class TestCoordinateClickingWithPassedTools: ...
class TestCoordinateClickingTools:
def test_default_coordinate_clicking_disabl... | def test_default_uses_index_only_action(self):
"""Default Tools should use ClickElementActionIndexOnly."""
tools = Tools()
click_action = tools.registry.registry.actions.get('click')
assert click_action is not None
assert click_action.param_model == ClickElementActionIndexOnly | test | 0 | {"function_name": "test_default_uses_index_only_action", "class_name": "TestCoordinateClickingTools", "qualname": "TestCoordinateClickingTools.test_default_uses_index_only_action", "file_path": "tests/ci/test_coordinate_clicking.py", "repo_id": "browser-use/browser-use", "loc": 7, "tested_modules": ["browser_use.tools.... |
streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_routes_test.py:TestSetCorsHeaders.test_no_header_when_origin_not_allowed | # Context:
import asyncio
from unittest.mock import MagicMock, patch
from streamlit.web.server.starlette.starlette_routes import (
_ensure_xsrf_cookie,
_set_cors_headers,
_set_unquoted_cookie,
_with_base,
)
from tests.testutil import patch_config_options
class TestWithBase: ...
class TestEnsureXsrfCook... | def test_no_header_when_origin_not_allowed(self) -> None:
"""Test that no header is set when origin is not in allowed list."""
request = MagicMock()
request.headers = MagicMock()
# This origin won't be in any allowed list by default
request.headers.get.return_value = "http://rand... | test | 1 | {"function_name": "test_no_header_when_origin_not_allowed", "class_name": "TestSetCorsHeaders", "qualname": "TestSetCorsHeaders.test_no_header_when_origin_not_allowed", "file_path": "lib/tests/streamlit/web/server/starlette/starlette_routes_test.py", "repo_id": "streamlit/streamlit", "loc": 12, "tested_modules": ["__fu... |
langflow-ai/langflow:src/backend/tests/unit/utils/test_validate.py:TestCreateClass.test_handles_class_with_imports | # Context:
from lfx.custom.validate import (
_create_langflow_execution_context,
add_type_ignores,
build_class_constructor,
compile_class_code,
create_class,
create_function,
create_type_ignore_class,
eval_function,
execute_function,
extract_class_code,
extract_class_name,
... | def test_handles_class_with_imports(self):
"""Test creation of class that uses imports."""
code = """
import json
class JsonHandler:
def __init__(self):
self.data = {}
def to_json(self):
return json.dumps(self.data)
"""
cls = create_class(code, "JsonHandler")
in... | test | 1 | {"function_name": "test_handles_class_with_imports", "class_name": "TestCreateClass", "qualname": "TestCreateClass.test_handles_class_with_imports", "file_path": "src/backend/tests/unit/utils/test_validate.py", "repo_id": "langflow-ai/langflow", "loc": 15, "tested_modules": ["lfx.custom.validate", "pydantic_core"], "ha... |
streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_app_test.py:test_static_files_apply_cache_headers | # Context:
from http import HTTPStatus
from pathlib import Path
import pytest
from starlette.testclient import TestClient
from streamlit import file_util
from streamlit.web.server.routes import STATIC_ASSET_CACHE_MAX_AGE_SECONDS
from streamlit.web.server.starlette.starlette_app import (
_RESERVED_ROUTE_PREFIXES,
... | def test_static_files_apply_cache_headers(tmp_path: Path) -> None:
"""Ensure hashed static assets receive long-lived cache headers."""
component_dir = tmp_path / "component"
component_dir.mkdir()
(component_dir / "index.html").write_text("component")
static_dir = tmp_path / "static"
static_dir.... | test | 1 | {"function_name": "test_static_files_apply_cache_headers", "class_name": null, "qualname": "test_static_files_apply_cache_headers", "file_path": "lib/tests/streamlit/web/server/starlette/starlette_app_test.py", "repo_id": "streamlit/streamlit", "loc": 26, "tested_modules": ["__future__", "contextlib", "http", "pathlib"... |
ray-project/ray:python/ray/data/_internal/datasource/databricks_credentials.py:request_with_401_retry | # Context:
from typing import Callable, Optional
import requests
class DatabricksCredentialProvider(ABC): ...
class StaticCredentialProvider(DatabricksCredentialProvider): ...
class EnvironmentCredentialProvider(DatabricksCredentialProvider): ...
def resolve_credential_provider(credential_provider: Optional[Databricks... | def request_with_401_retry(
request_fn: Callable[..., requests.Response],
url: str,
credential_provider: DatabricksCredentialProvider,
**kwargs,
) -> requests.Response:
"""Make an HTTP request with one retry on 401 after invalidating credentials.
Args:
request_fn: Request function (e.g.... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 26, "code_loc": 7, "docstring_loc": 11, "function_name": "request_with_401_retry", "class_name": null, "qualname": "request_with_401_retry", "file_path": "python/ray/data/_internal/datasource/databricks_credentials.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_le... |
browser-use/browser-use:browser_use/code_use/views.py:CodeAgentHistoryList.screenshot_paths | # Context:
class CellType(str, Enum): ...
class ExecutionStatus(str, Enum): ...
class CodeCell(BaseModel): ...
class NotebookSession(BaseModel): ...
class NotebookExport(BaseModel): ...
class CodeAgentModelOutput(BaseModel): ...
class CodeAgentResult(BaseModel): ...
class CodeAgentState(BaseModel): ...
class CodeAgent... | def screenshot_paths(self, n_last: int | None = None, return_none_if_not_screenshot: bool = True) -> list[str | None]:
"""Get all screenshot paths from history."""
if n_last == 0:
return []
if n_last is None:
if return_none_if_not_screenshot:
return [h.state.screenshot_path if h.state.screenshot_path is... | function_complex | 0 | {"cognitive_complexity": 9, "loc": 17, "code_loc": 15, "docstring_loc": 1, "function_name": "screenshot_paths", "class_name": "CodeAgentHistoryList", "qualname": "CodeAgentHistoryList.screenshot_paths", "file_path": "browser_use/code_use/views.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_... |
huggingface/transformers:tests/models/edgetam_video/test_modeling_edgetam_video.py:EdgeTamVideoModelIntegrationTest.test_inference_mask_generation_video_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 Ed... | def test_inference_mask_generation_video_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_id = 1 # give a unique id to each ... | test | 0 | {"function_name": "test_inference_mask_generation_video_multi_points", "class_name": "EdgeTamVideoModelIntegrationTest", "qualname": "EdgeTamVideoModelIntegrationTest.test_inference_mask_generation_video_multi_points", "file_path": "tests/models/edgetam_video/test_modeling_edgetam_video.py", "repo_id": "huggingface/tra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.