input string | label int64 | category string | sample_id string |
|---|---|---|---|
"role": "assistant",
"content": '{"location": "SF"}',
},
"finish_reason": "stop",
"index": 0,
}
],
}
)
with pytest.warns(match="Defaulting to 'json_sche... | 1 | test | langchain-ai/langchain:libs/partners/openrouter/tests/unit_tests/test_chat_models.py:TestStructuredOutputIntegration.test_response_format_json_mode_falls_back_to_json_schema_in_sdk |
lines.append(f" Seller countered: ${r.seller_counter:,}")
elif r.seller_action == "reject":
lines.append(f" Seller rejected the offer")
elif r.seller_action == "walk":
lines.append(f" Seller walked away!")
if r.s... | 0 | function_complex | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agents/orchestrator.py:NegotiationState.get_negotiation_history |
case_id or error_message)
"""
try:
case_id = get_uuid()
case = {
"id": case_id,
"dataset_id": dataset_id,
"question": question,
"reference_answer": reference_answer,
"relevant_doc_ids": relevant_doc_... | 1 | function_simple | infiniflow/ragflow:api/db/services/evaluation_service.py:EvaluationService.add_test_case |
# Use MCAP's built-in filtering for topics and time range
messages = reader.iter_messages(
topics=list(self._topics) if self._topics else None,
start_time=self._time_range.start_time if self._time_range else None,
end_time=self._time_range.end_time if self._time_ran... | 0 | function_simple | ray-project/ray:python/ray/data/_internal/datasource/mcap_datasource.py:MCAPDatasource._read_stream |
= "large.bin"
data = b"X" * (1024 * 1024) # 1 MB
try:
await s3_storage_service.save_file(test_flow_id, file_name, data)
# Verify size
size = await s3_storage_service.get_file_size(test_flow_id, file_name)
assert size == 1024 * 1024
# Verif... | 1 | test | langflow-ai/langflow:src/backend/tests/integration/storage/test_s3_storage_service.py:TestS3StorageServiceFileOperations.test_save_large_file |
'button': 'left',
'clickCount': 1,
},
session_id=cdp_session.session_id,
)
await cdp_session.cdp_client.send.Input.dispatchMouseEvent(
params={
'type': 'mouseReleased',
'x': click_x,
'y': click_y,
'button': 'left',
'clickCount': 1,
},
session_i... | 0 | function_simple | browser-use/browser-use:browser_use/browser/watchdogs/default_action_watchdog.py:DefaultActionWatchdog._focus_element_simple |
admin_password = os.environ.get("ADMIN_PASSWORD", secrets.token_urlsafe(16))
password_hash = self.hash_password(admin_password)
cursor.execute(
"""
INSERT INTO users (username, email, full_name, password_hash, role)
VALUES (?, ?, ?, ?, ?)
... | 0 | function_simple | Zie619/n8n-workflows:src/user_management.py:UserManager.create_default_admin |
virtual_scroll_config=virtual_config,
cache_mode=CacheMode.BYPASS
)
# TIP: Set headless=False to watch the scrolling happen!
browser_config = BrowserConfig(
headless=False,
viewport={"width": 1280, "height": 800}
)
... | 1 | function_complex | unclecode/crawl4ai:docs/examples/virtual_scroll_example.py:example_twitter_like_virtual_scroll |
# Clean HTML tags from summary (simple approach)
if summary:
import re
summary = re.sub(r'<[^>]+>', '', summary)[:500]
signal = {
"id": entry.get("id", entry.link),
... | 0 | function_complex | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/devpulse_ai/adapters/medium.py:fetch_medium_blogs |
will fail because ANY of the common characters
# will trigger early termination before min_tokens=50 is reached
# It's virtually impossible to generate 50 tokens without hitting
# at least one of: e, a, i, o, u, space, t, n, s, r
finish_reason = (
outputs[0].outputs[0].finish_reason if outputs[... | 1 | test | vllm-project/vllm:tests/v1/e2e/test_min_tokens.py:test_min_tokens_stop_strings_guaranteed_early_trigger |
= None):
"""Convert image to content dictionary.
Args:
flow_id: Optional flow ID to prepend to the path if it doesn't contain one
"""
if not self.path:
msg = "Image path is not set."
raise ValueError(msg)
# If the path doesn't contain a "/" ... | 1 | function_simple | langflow-ai/langflow:src/lfx/src/lfx/schema/image.py:Image.to_content_dict |
, "Missing 'description' in frontmatter"
# Extract name for validation
name = frontmatter.get('name', '')
if not isinstance(name, str):
return False, f"Name must be a string, got {type(name).__name__}"
name = name.strip()
if name:
# Check naming convention (hyphen-case: lowercase wi... | 1 | function_complex | zhayujie/chatgpt-on-wechat:skills/skill-creator/scripts/quick_validate.py:validate_skill |
str):
"""Check if a raw version string indicates a custom or source build.
Must operate on the raw string from importlib_version(), not the parsed
Version object, since our custom Version() strips local identifiers.
Standard PyTorch releases use: +cu124, +rocm6.3, +cpu, +xpu
Source/custom builds us... | 0 | function_simple | unslothai/unsloth:unsloth/import_fixes.py:_is_custom_torch_build |
],
type=pa.struct(
[
pa.field("name", pa.string()),
pa.field(
"address",
pa.struct(
[
| 0 | test | ray-project/ray:python/ray/data/tests/expressions/test_namespace_struct.py:TestStructNamespace.test_struct_nested_bracket |
TODO: Technically, assistant_response should be a Message (either a string or a list of parts)
We can handle this later possibly. For now just assume string.
"""
assert isinstance(assistant_response, str), "Assuming simple string response for now"
# First extract the ground truth ... | 0 | function_simple | karpathy/nanochat:tasks/gsm8k.py:GSM8K.evaluate |
the token count of the formatted prompt stays below what
`count_tokens_approximately` estimates for the raw messages.
"""
# Create messages with metadata that would inflate str() representation
messages: list[AnyMessage] = [
HumanMessage(content="What is the weather in NYC?"),
AIMessage... | 1 | test | langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py:test_create_summary_uses_get_buffer_string_format |
}
for tenant in ["tenant_1", "tenant_2", "tenant_3"]:
assert tree.tenant_to_lru_tail.get(tenant) == tree.root
assert tree.root.tenant_to_newer_node.get(tenant) is None
assert tree.root.tenant_to_older_node.get(tenant) is None
assert tree.root.tenant_to_last_acc... | 0 | test | ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py:TestPrefixTreeInitialization.test_add_multiple_tenants |
def test_chunk_unicode_text(self):
text = textwrap.dedent("""\
Chief Complaint:
‘swelling of tongue and difficulty breathing and swallowing’
History of Present Illness:
77 y o woman in NAD with a h/o CAD, DM2, asthma and HTN on altace.""")
tokenized_text = tokenizer.tokenize(text)
chunk_iter... | 1 | test | google/langextract:tests/chunking_test.py:ChunkIteratorTest.test_chunk_unicode_text |
with patch("click.confirm", return_value=False) as mock_confirm:
with pytest.raises(
ImportError, match="The 'couchbase' package is required"
):
CouchbaseFTSVectorSearchTool(
cluster=MagicMock(),
bucket_name="b",
... | 0 | test | crewAIInc/crewAI:lib/crewai-tools/tests/tools/couchbase_tool_test.py:test_initialization_couchbase_unavailable |
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
for image in image_inputs:
self.assertIsInstance(image, np.ndarray)
# Test not batched input
encoded_images = image_processing(image_inputs[0], return_tenso... | 0 | test | huggingface/transformers:tests/models/phi4_multimodal/test_image_processing_phi4_multimodal.py:Phi4MultimodalImageProcessingTest.test_call_numpy |
with self._rwlock.w_locked():
if event_type in self._sync_handlers:
existing_sync = self._sync_handlers[event_type]
if handler in existing_sync:
self._sync_handlers[event_type] = existing_sync - {handler}
if not self._sync_handlers[... | 0 | function_complex | crewAIInc/crewAI:lib/crewai/src/crewai/events/event_bus.py:CrewAIEventsBus.off |
project_id=GCP_PROJECT,
location=GCP_LOCATION,
input_source=TEST_EMBEDDINGS_JOB_INLINED_REQUESTS,
model=EMBEDDING_MODEL,
gemini_api_key=TEST_GEMINI_API_KEY,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
wait_until_... | 1 | test | apache/airflow:providers/google/tests/unit/google/cloud/operators/test_gen_ai.py:TestGenAIGeminiCreateEmbeddingsBatchJobOperator.test_execute |
outputs.append(output_)
except ValidationError as e:
msg = f"Invalid output: {e}"
raise ValueError(msg) from e
else:
outputs = self.outputs
for output in outputs:
if output.name is None:
msg = "Ou... | 1 | function_complex | langflow-ai/langflow:src/lfx/src/lfx/custom/custom_component/component.py:Component.map_outputs |
self.video_processor_tester.prepare_video_inputs(
equal_resolution=False, return_tensors="np"
)
video_inputs_nested = [list(video) for video in video_inputs]
video_metadata = self.video_processor_tester.prepare_video_metadata(video_inputs)
# Test not ba... | 0 | test | huggingface/transformers:tests/models/glm46v/test_video_processing_glm46v.py:Glm46VVideoProcessingTest.test_nested_input |
ryMiddleware(
max_retries=3,
initial_delay=0.1,
backoff_factor=2.0,
jitter=False,
)
agent = create_agent(
model=model,
tools=[],
middleware=[retry],
checkpointer=InMemorySaver(),
)
start_time = time.time()
result = agent.invoke(
... | 1 | test | langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_retry.py:test_model_retry_backoff_timing |
image_processing = self.fast_image_processing_class(
do_image_splitting=True,
use_thumbnail=True,
min_tiles=2,
max_tiles=10,
tile_size=512,
)
# Create a landscape image (1920x1080, ~16:9 aspect ratio)
landscape_image = Image.new... | 0 | test | huggingface/transformers:tests/models/lfm2_vl/test_image_processing_lfm2_vl.py:Lfm2VlImageProcessingTest.test_landscape_image_aspect_ratio |
"type": "input_audio",
"input_audio": {
"data": row["audio_data"],
"format": "wav",
},
},
],
},
],
"sampling_params": {
"temperature": 0.... | 0 | function_simple | ray-project/ray:doc/source/data/doc_code/working-with-llms/omni_audio_example.py:audio_preprocess |
Checks the response from vector operations (insert/update) to ensure they
completed successfully. Logs errors if operations fail.
Args:
response: Response from Neptune Analytics vector operation.
context (str): Context description for logging (e.g., "Vector store - Ins... | 1 | function_simple | mem0ai/mem0:mem0/vector_stores/neptune_analytics.py:NeptuneAnalyticsVector._process_success_message |
{
"origin": "http://localhost",
"is_logged_in": True,
"email": "test@test.com",
}
)
signed_cookie = starlette_app_utils.create_signed_value(
"test-secret", "_streamlit_user", cookie_payload
)
result = _... | 1 | test | streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_websocket_test.py:TestParseUserCookieSigned.test_parses_valid_cookie |
async def list_tools(self):
if self.should_fail:
msg = "Connection failed"
raise Exception(msg) # noqa: TRY002
class MockResponse:
def __init__(self):
self.tools = ["tool1", "tool2"]
return MockResponse()
# ... | 1 | test | langflow-ai/langflow:src/backend/tests/integration/components/mcp/test_mcp_memory_leak.py:test_session_manager_connectivity_validation |
os.path.join(tmpdir, "build2.sh"), "w") as f:
f.write("echo world")
ctx1 = make_build_context(
base_dir=tmpdir,
post_build_script="build.sh",
)
ctx2 = make_build_context(
base_dir=tmpdir,
post_build_script="build2.sh",
)
... | 0 | test | ray-project/ray:release/ray_release/tests/test_byod_build_context.py:test_build_context_digest |
# Add small delay to increase chance of race conditions
time.sleep(0.01)
setup["component_manager"].register_from_manifest(manifest, package_root)
results.append(thread_id)
except Exception as e:
errors.append(e)
# Create multiple threads
threads ... | 1 | test | streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_registry.py:test_register_from_manifest_thread_safety |
_packed_info_from_kwargs(
kwargs: dict,
device: torch.device,
) -> Optional[Tuple[torch.Tensor, torch.Tensor, int]]:
"""Return packed sequence metadata expected by the attention kernels."""
seq_lengths = kwargs.get("packed_seq_lengths")
if seq_lengths is None:
return None
lengths = seq... | 0 | function_simple | unslothai/unsloth:unsloth/utils/packing.py:get_packed_info_from_kwargs |
"""Generate summary for the given messages.
Args:
messages_to_summarize: Messages to summarize.
"""
if not messages_to_summarize:
return "No previous conversation history."
trimmed_messages = self._trim_messages_for_summary(messages_to_summarize)
if ... | 1 | function_simple | langchain-ai/langchain:libs/langchain_v1/langchain/agents/middleware/summarization.py:SummarizationMiddleware._create_summary |
)
console.print("\nAuthenticating with GitHub...")
subprocess.run(
["gh", "auth", "login"], # noqa: S607
check=True,
)
console.print("[green]✓[/green] GitHub... | 0 | function_complex | crewAIInc/crewAI:lib/devtools/src/crewai_devtools/cli.py:check_gh_installed |
)
# Store original method to call for non-failing requests
original_preprocess = EngineCore.preprocess_add_request
# Monkeypatch to make preprocess_add_request raise an exception
# only for requests with "FAIL" in the first token
def conditional_failing_preprocess(self, request: EngineCoreReque... | 1 | test | vllm-project/vllm:tests/v1/engine/test_preprocess_error_handling.py:test_preprocess_error_handling |
# noqa: S310 - test controlled
urllib.request.Request(
_agent_url(agent_address, "/get_or_create_runtime_env"),
data=request.SerializeToString(),
headers={"Content-Type": "application/octet-stream"},
method="POST",
),
t... | 0 | test | ray-project/ray:python/ray/tests/test_runtime_env_agent_auth.py:test_runtime_env_agent_requires_auth_missing_token |
if self.user_dockerfile_path and os.path.exists(self.user_dockerfile_path):
dockerfile_path = self.user_dockerfile_path
else:
package_path = self._get_installed_package_path()
dockerfile_path = os.path.join(
package_path, "tools/code... | 0 | function_complex | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/code_interpreter_tool/code_interpreter_tool.py:CodeInterpreterTool._verify_docker_image |
Args:
api_key (str): iGPT API key. See https://docs.igpt.ai for details.
user (str): User identifier for the connected mailbox.
Example:
.. code-block:: python
from llama_index.tools.igpt_email import IGPTEmailToolSpec
from llama_index.core.agent.workflow import FunctionAgent
from... | 1 | documentation | run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-igpt-email/llama_index/tools/igpt_email/base.py:IGPTEmailToolSpec:class_doc |
"""Pull new requests from the input queue and add to waiting list."""
while not self.input_queue.empty():
try:
state = self.input_queue.get_nowait()
if state is None: # Sentinel value
continue
self.scheduler.add_waiting_reques... | 0 | function_complex | huggingface/transformers:src/transformers/generation/continuous_batching/continuous_api.py:ContinuousBatchProcessor._get_new_requests |
post:
mock_response = mock.Mock(spec=["status_code", "json"])
mock_response.status_code = 200
mock_response.json.return_value = {"response": '{"extractions": []}'}
mock_post.return_value = mock_response
model = ollama.OllamaLanguageModel(model_id="gemma2:2b", format="yaml")
list(mo... | 1 | test | google/langextract:tests/provider_schema_test.py:OllamaYAMLOverrideTest.test_ollama_yaml_format_in_request_payload |
.anthropic import Anthropic
# Create real LLM instances
openai_llm = OpenAI(
model="gpt-4o-mini",
api_key="invalid-openai-key", # Invalid key to simulate OpenAI failure
)
anthropic_llm = Anthropic(
model="claude-3-5-sonnet-20241022",
api_key=os.getenv("ANTHROPIC_API_KE... | 1 | test | run-llama/llama_index:llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/tests/test_cloudflare_ai_gateway.py:test_cloudflare_ai_gateway_fallback_when_openai_fails |
# noqa: ARG001
return mock_user
with (
patch("langflow.services.auth.utils.get_auth_service", return_value=mock_auth_service),
patch("langflow.services.auth.service.get_user_by_id", side_effect=mock_get_user_by_id),
):
token = cr... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/test_auth_jwt_algorithms.py:TestTokenVerification.test_verify_hs256_token_success |
norm(np.array(left_eye_upper_lid) - np.array(left_eye_lower_lid))
right_eye_opening = np.linalg.norm(np.array(right_eye_upper_lid) - np.array(right_eye_lower_lid))
eye_opening_avg = (left_eye_opening + right_eye_opening) / 2
# Simple heuristic: if eyes are wide open, as... | 0 | function_complex | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/tools/facial_expression_tool.py:analyze_facial_expressions |
projections
qkv_fused: Whether to use fused QKV projection (single linear) or separate projections
num_prefix_tokens: Number of reg/cls tokens at the beginning of the sequence that
should not have position embeddings applied
attn_drop: Dropout rate for attention weig... | 1 | function_complex | huggingface/pytorch-image-models:timm/layers/attention.py:AttentionRope.__init__ |
use_cache (`bool`, *optional*):
Whether to use caching for convolution states.
"""
if use_cache and padding_cache is None:
per_layer_padding = [self.decoder.stem.conv.causal_padding]
per_layer_in_channels = [self.decoder.stem.conv.conv.in_channels]
per_la... | 0 | function_simple | huggingface/transformers:src/transformers/models/vibevoice_acoustic_tokenizer/modular_vibevoice_acoustic_tokenizer.py:VibeVoiceAcousticTokenizerModel.decode |
""
expanded_nodes = {
"1": {
"id": "1",
"type": "genericNode",
"data": {
"type": "ChatInput",
"node": SAMPLE_COMPONENTS["inputs"]["ChatInput"],
},
},
"2": {
... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/test_expand_flow.py:TestExpandEdge.test_expand_edge_id_uniqueness |
qdrant"],
provider_config: dict[str, Any],
embedding_function: EmbeddingFunction[Any] | None,
) -> Any:
"""Instantiate provider config with optional embedding_function injected."""
if provider == "chromadb":
from crewai.rag.chromadb.config import ChromaDBConfig
... | 0 | function_complex | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/rag/rag_tool.py:RagTool._create_provider_config |
, name="st_pdf-height_default")
# Get the actual slider element
slider_element = height_slider.get_by_role("slider")
expect(slider_element).to_be_visible()
# Move slider to minimum (200px) using proper e2e slider interaction
slider_element.hover()
app.mouse.down()
# Move mouse far to the ... | 1 | test | streamlit/streamlit:e2e_playwright/custom_components/pdf_component_test.py:test_st_pdf_different_heights_snapshots |
custom_build_jobs_output_file,
"--test-jobs-output-file",
test_jobs_output_file,
],
catch_exceptions=False,
)
with open(
os.path.join(_bazel_workspace_dir, custom_build_jobs_output_file), "r"
) as f:
custom_build_jobs = yaml.safe_load(f)
... | 0 | test | ray-project/ray:release/ray_release/tests/test_custom_image_build_and_test_init.py:test_custom_image_build_and_test_init_with_block_step |
string with proper type discrimination
Args:
event_json: JSON string from SSE stream
Returns:
Typed SSEEvent with appropriate data model
Raises:
json.JSONDecodeError: If JSON is malformed
ValueError: If event type is invalid
"""
raw_data = json.loads(event_json)
event_type = SSEE... | 0 | function_simple | browser-use/browser-use:browser_use/sandbox/views.py:SSEEvent.from_json |
# then other environment can also terminate causing greater than the number of episodes requested
assert metrics[NUM_EPISODES] >= num_episodes
assert metrics[NUM_EPISODES_LIFETIME] >= num_episodes
episode_num_timesteps = sum(len(eps) for eps in episodes)
# As some sub-environmen... | 0 | test | ray-project/ray:rllib/env/tests/test_env_runner.py:TestEnvRunnerMetrics.test_metrics_after_sampling_episodes |
types": [
{
"hook-class-name": "airflow.providers.sftp.hooks.sftp.SFTPHook",
"connection-type": "sftp",
}
],
},
)
providers_manager._discover_hooks()
... | 1 | test | apache/airflow:task-sdk/tests/task_sdk/test_providers_manager_runtime.py:TestProvidersManagerRuntime.test_warning_logs_not_generated |
self._log("info", "Starting URL seeding for {count} domains...",
params={"count": len(domains)}, tag="URL_SEED")
# Ensure seeder's logger verbose matches the config's verbose if it's set
if self.logger and hasattr(self.logger, 'verbose') and config.verbose is not None:
s... | 1 | function_simple | unclecode/crawl4ai:crawl4ai/async_url_seeder.py:AsyncUrlSeeder.many_urls |
_factor is None and rope_parameters_alpha is None:
raise ValueError("`rope_parameters`'s factor or alpha field must be have one, got both of none")
if rope_parameters_factor is not None:
if not isinstance(rope_parameters_factor, float) or rope_parameters_factor <= 1.0:
ra... | 0 | function_complex | huggingface/transformers:src/transformers/models/hunyuan_v1_moe/configuration_hunyuan_v1_moe.py:HunYuanMoEV1Config._rope_parameters_validation |
flow DAG that demonstrates using Google Cloud Pub/Sub with MessageQueueTrigger
and Asset Watchers for event-driven workflows.
This example shows how to create a DAG that triggers when messages arrive in a
Google Cloud Pub/Sub subscription using Asset Watchers.
Prerequisites
-------------
Before running this example,... | 1 | documentation | apache/airflow:providers/google/tests/system/google/event_scheduling/example_event_schedule_pubsub.py:module_doc |
Args:
result: The text potentially containing JSON.
Returns:
Extracted JSON string if found and valid, otherwise the original result.
"""
if not isinstance(result, str):
return str(result)
if valid := BaseConverterAdapter._validate_json(res... | 0 | function_complex | crewAIInc/crewAI:lib/crewai/src/crewai/agents/agent_adapters/base_converter_adapter.py:BaseConverterAdapter._extract_json_from_text |
)
# Release signal and test scale down when CPU usage < 30
signal.send.remote()
wait_for_condition(lambda: ray.get(signal.cur_num_waiters.remote()) == 0)
signal = SignalActor.remote()
# Reset CPU usage to low value by creating new deployment instance
# This simulates... | 0 | test | ray-project/ray:python/ray/serve/tests/test_custom_autoscaling_metrics.py:TestCustomServeMetrics.test_max_cpu_usage_autoscaling_policy |
"config": {"azure_arm_parameters": {"vmSize": "Standard_D2s_v3"}},
"expected_zones": ["1", "2", "3"],
"expected_source": "provider availability_zone",
},
]
for i, test_case in enumerate(test_cases):
with self.subTest(case=i):
... | 0 | test | ray-project/ray:python/ray/tests/test_autoscaler_azure.py:TestAzureAvailabilityZonePrecedence.test_complex_override_scenario |
goes faster than the uploads.
hub_always_push=True,
save_strategy="epoch",
)
trainer.train()
commits = list_repo_commits(f"{USER}/{output_dir_name}", token=self._token)
commits = [c.title for c in commits]
... | 0 | test | huggingface/transformers:tests/trainer/test_trainer_checkpointing.py:TrainerIntegrationWithHubTester.test_push_to_hub_with_saves_each_epoch |
"_connect"):
store = AlibabaCloudMySQLVectorStore(
table_name="test_table",
host="localhost",
port=3306,
user="test_user",
password="test_password",
database="test_db",
perform_setup=False, # Do... | 1 | test | run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-alibabacloud-mysql/tests/test_alibabacloud_mysql.py:test_drop |
mock_prepare.return_value = {"CustomComponent": type("CustomComponent", (), {})}
with patch("lfx.custom.validate.extract_class_code") as mock_extract:
mock_extract.return_value = Mock()
with patch("lfx.custom.validate.compile_class_code") as mock_compile:
... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/utils/test_validate.py:TestCreateClass.test_replaces_legacy_imports |
self.num_heads, self.head_dim).transpose(1, 2)
values = values.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
self.config._attn_implementation, eager_attention_forward
)
att... | 0 | function_simple | huggingface/transformers:src/transformers/models/vjepa2/modeling_vjepa2.py:VJEPA2PoolerSelfAttention.forward |
_query_with_local_csv(self, mock_get_conn):
mock_get_conn.return_value = None
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("name,age\nAlice,30\nBob,25\n")
csv_path = f.name
try:
engine = DataFusionEngine()
... | 1 | test | apache/airflow:providers/common/sql/tests/unit/common/sql/datafusion/test_engine.py:TestDataFusionEngine.test_execute_query_with_local_csv |
_url, count):
"""Test /crawl endpoint."""
url = f"{base_url}/crawl"
results = []
payload = {
"urls": ["https://httpbin.org/html"],
"browser_config": {},
"crawler_config": {}
}
for _ in range(count):
start = time.time()
try:
resp = await client.... | 1 | test | unclecode/crawl4ai:deploy/docker/tests/test_6_multi_endpoint.py:test_crawl |
regular_shared_2_cpus,
restore_data_context,
disable_fallback_to_object_extension,
):
context = DataContext.get_current()
context.shuffle_strategy = ShuffleStrategy.HASH_SHUFFLE
context.hash_shuffle_operator_actor_num_cpus_override = 0.001
ds = ray.data.range(20, override_num_blocks=10)
as... | 0 | test | ray-project/ray:python/ray/data/tests/test_repartition_e2e.py:test_key_based_repartition_shuffle |
"enable_access_log": enable_access_log,
}
config = ServeDeploySchema.parse_obj(config_dict)
client.deploy_apps(config)
wait_for_condition(
lambda: httpx.post("http://localhost:8000/app1").status_code == 200
)
resp = httpx.get("http://127.0.0.1:8000/app1")
... | 0 | test | ray-project/ray:python/ray/serve/tests/test_deploy_app_2.py:TestDeploywithLoggingConfig.test_access_log |
"transfer_duration": [2.0],
"post_duration": [0.2],
"bytes_transferred": [2048],
"num_descriptors": [20],
"num_failed_transfers": [],
"num_failed_notifications": [],
... | 1 | test | vllm-project/vllm:tests/v1/kv_connector/unit/test_multi_connector.py:TestMultiConnectorStats.test_aggregate_same_connector |
set_random_seed(42)
device = torch.device("cuda:0")
hidden_size = shape[-1]
# Create inputs
x = torch.randn(*shape, dtype=dtype, device=device)
weight = torch.randn(hidden_size, dtype=dtype, device=device)
bias = torch.randn(hidden_size, dtype=dtype, device=device)
eps = 1e-6
# Ru... | 1 | test | vllm-project/vllm:tests/kernels/test_fla_layernorm_guard.py:test_multidimensional_input |
_config_and_inputs_for_common()
config.num_labels = 3
config.problem_type = "single_label_classification"
input_ids = input_dict["input_ids"]
attention_mask = input_ids.ne(1).to(torch_device)
sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequ... | 0 | test | huggingface/transformers:tests/models/doge/test_modeling_doge.py:DogeModelTest.test_doge_sequence_classification_model_for_single_label |
"""Default marking should work independently of deprecated filtering."""
providers_normal = get_unified_models_detailed(include_deprecated=False)
providers_with_deprecated = get_unified_models_detailed(include_deprecated=True)
# Both should have defaults marked
for provider_data in... | 1 | test | langflow-ai/langflow:src/lfx/tests/unit/inputs/test_model_input_fixes.py:TestUnifiedModelsDefaults.test_defaults_not_affected_by_deprecated_filter |
LLM自行发挥)。
返回:
dict: 结构体字段与LLM返回一致,方便直接替换。
"""
logger.info("未找到合适模板,使用空模板让LLM自行发挥")
return {
'template_name': '自由发挥模板',
'template_content': '',
'selection_reason': '未找到合适的� | 1 | function_simple | 666ghj/BettaFish:ReportEngine/nodes/template_selection_node.py:TemplateSelectionNode._get_fallback_template |
gunicorn_app import AirflowGunicornApp
def mock_init(self, options):
pass # Do nothing, we'll set up state manually
with mock.patch.object(AirflowGunicornApp, "__init__", mock_init):
app = AirflowGunicornApp.__new__(AirflowGunicornApp)
with mock.patch("airflow.api... | 1 | test | apache/airflow:airflow-core/tests/unit/cli/commands/test_gunicorn_monitor.py:TestAirflowGunicornApp.test_run_uses_airflow_arbiter |
= "expired_token"
post_call_count = [0]
post_headers_captured = []
def post_side_effect(url, headers=None, **kwargs):
post_call_count[0] += 1
post_headers_captured.append(headers.get("Authorization", ""))
if post_call_count[0] == 1:
return M... | 0 | test | ray-project/ray:python/ray/data/tests/datasource/test_uc_datasource.py:TestUnityCatalogConnector401Retry.test_401_during_get_creds |
_different_options(self):
"""Test that the widget ID changes when options change."""
with patch(
"streamlit.elements.lib.utils._register_element_id",
return_value=MagicMock(),
):
st.feedback("thumbs", key="feedback_key_1")
proto1 = self.get_delta_f... | 1 | test | streamlit/streamlit:lib/tests/streamlit/elements/feedback_test.py:TestFeedbackStableId.test_id_changes_with_different_options |
exist
"""
try:
fs, path = PyArrowFileSystem.get_fs_and_path(object_uri)
# Check if file exists
if not fs.get_file_info(path).type == pa_fs.FileType.File:
logger.info(f"URI {object_uri} does not exist.")
return None
# Read... | 0 | function_simple | ray-project/ray:python/ray/llm/_internal/common/utils/cloud_filesystem/pyarrow_filesystem.py:PyArrowFileSystem.get_file |
all_providers:
provider = provider_data["provider"]
models = provider_data["models"]
# Check models after first 5
if len(models) > 5:
for i in range(5, len(models)):
model = models[i]
# These should not have defaul... | 1 | test | langflow-ai/langflow:src/lfx/tests/unit/inputs/test_model_input_fixes.py:TestUnifiedModelsDefaults.test_models_after_five_not_default |
ECASE):
var_name = match.group(1).upper()
return var_name in os.environ
# Pattern: "env.VAR_NAME == 'value'" or "env.VAR_NAME != 'value'"
if match := re.match(r'env\.([A-Z0-9_]+)\s*(==|!=)\s*["\']([^"\']+)["\']', condition, re.IGNORECASE):
var_name = match.group(1).u... | 0 | function_complex | github/spec-kit:src/specify_cli/extensions.py:HookExecutor._evaluate_condition |
"airflowVersion": "3.0.0",
"apiServer": {
"apiServerConfig": "CSRF_ENABLED = True # {{ .Release.Name }}",
"configMapAnnotations": {"test_annotation": "test_annotation_value"},
},
},
show_only=["templates/co... | 1 | test | apache/airflow:helm-tests/tests/helm_tests/apiserver/test_apiserver.py:TestAPIServerDeployment.test_should_add_annotations_to_api_server_configmap |
audio_labels_expanded[:, :, codebook_idx]
codebook_losses.append(
self.loss_function(codebook_logits, codebook_labels, self.config.codebook_size, **kwargs)
)
loss = sum(codebook_losses)
if labels is not None:
if self.text_lm_head is ... | 0 | function_complex | huggingface/transformers:src/transformers/models/higgs_audio_v2/modular_higgs_audio_v2.py:HiggsAudioV2ForConditionalGeneration.forward |
, "delete_by_ids", lambda _ids: False)
res = _run(module.rm.__wrapped__())
assert "Failed to delete MCP servers" in res["message"]
_set_request_json(monkeypatch, module, {"mcp_ids": ["a", "b"]})
monkeypatch.setattr(module.MCPServerService, "delete_by_ids", lambda _ids: True)
res = _run(module.rm.__... | 1 | test | infiniflow/ragflow:test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py:test_rm_failure_success_and_exception |
for num_images_per_prompt in num_images_per_prompts:
inputs = self.get_dummy_inputs(torch_device)
for key in inputs.keys():
if key in self.batch_params:
inputs[key] = batch_size * [inputs[key]]
images = pipe(**inputs, num... | 1 | test | huggingface/diffusers:tests/pipelines/z_image/test_z_image.py:ZImagePipelineFastTests.test_num_images_per_prompt |
):
"""Test that both agent_id and run_id are properly integrated into user identity"""
graph_memory_path = 'mem0/memory/graph_memory.py'
# Check if file exists before reading
if not os.path.exists(graph_memory_path):
# Skip test if file doesn't exist (e.g., in CI env... | 1 | test | mem0ai/mem0:tests/memory/test_neo4j_cypher_syntax.py:TestNeo4jCypherSyntaxFix.test_user_identity_integration |
# Works for Python >= 3.14 with torch >= 2.10
if self.options.compile_model:
if sys.version_info < (3, 14):
self._model = torch.compile(self._model) # type: ignore[arg-type,assignment]
_log.debug("Model compiled with torch.compile()")
... | 1 | function_complex | docling-project/docling:docling/models/inference_engines/object_detection/transformers_engine.py:TransformersObjectDetectionEngine.initialize |
{
"prompt_tokens": 100,
"completion_tokens": 50,
"total_tokens": 150,
"prompt_tokens_details": {"cached_tokens": 20},
"completion_tokens_details": {"reasoning_tokens": 10},
}
)
assert "input_token_details... | 1 | test | langchain-ai/langchain:libs/partners/openrouter/tests/unit_tests/test_chat_models.py:TestUsageMetadata.test_token_details |
'provider': 'openai/text-embedding-3-small',
'api_token': os.getenv('OPENAI_API_KEY'),
'embedding_model': 'text-embedding-3-small'
}
if not config.embedding_llm_config['api_token']:
console.print("[yellow]Skipping OpenAI embedding test - no API key[/yellow]")
return... | 1 | test | unclecode/crawl4ai:tests/adaptive/test_embedding_strategy.py:test_custom_embedding_provider |
10_000.0}
config.rope_parameters = {"sliding_attention": rope_params, "full_attention": rope_params}
yarn_scaling_rope = rope_class(config=config).to(torch_device)
yarn_cos_short, yarn_sin_short = yarn_scaling_rope(x, position_ids_short, layer_type="sliding_attention")
yarn_cos_long, ya... | 0 | test | huggingface/transformers:tests/models/gemma3n/test_modeling_gemma3n.py:Gemma3nTextModelTest.test_model_rope_scaling_frequencies |
_instance
component = component_class()
component.set_attributes(default_kwargs)
model = component.build_model()
mock_chat_openai.assert_called_once_with(
model="gpt-4o-mini",
api_key="test-cometapi-key",
max_tokens=1000,
temperature=0.7,... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py:TestCometAPIComponent.test_build_model_success |
"html_content": "Hello {{ var_name }}",
"cc": ["cc@{{ var_domain }}"],
"bcc": ["bcc@{{ var_domain }}"],
"reply_to": "reply@{{ var_domain }}",
}
notifier = SesNotifier(**templated_params)
with mock.patch("airflow.providers.amazon.aws.notifications.ses... | 1 | test | apache/airflow:providers/amazon/tests/unit/amazon/aws/notifications/test_ses.py:TestSesNotifier.test_ses_notifier_templated |
task(
self, isaacus_embedding: IsaacusEmbedding, mock_response: MagicMock
) -> None:
"""Test that get_query_embedding uses retrieval/query task."""
with patch.object(
isaacus_embedding._client.embeddings, "create", return_value=mock_response
) as mock_create:
... | 1 | test | run-llama/llama_index:llama-index-integrations/embeddings/llama-index-embeddings-isaacus/tests/test_isaacus_embeddings.py:TestIsaacusEmbedding.test_get_query_embedding_uses_retrieval_query_task |
gate: bool,
group_size: int | None,
norm_before_gate: bool,
):
"""Test that RMSNormGated.forward_native preserves input dtype."""
if group_size is not None and hidden_size % group_size != 0:
pytest.skip(
f"hidden_size {hidden_size} not divisible by group_size {group_size}"
)
... | 1 | test | vllm-project/vllm:tests/kernels/test_fla_layernorm_guard.py:test_rmsnorm_gated_forward_native_dtype |
_router_allows_non_conflicting_prefix(self):
"""include_router with distinct prefix succeeds and reserves new paths."""
app = FastAPI()
@app.get("/health")
def health():
return "ok"
reserved = _get_route_keys(app)
wrapper = _PluginAppWrapper(app, reserved)
... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/test_plugin_routes.py:TestPluginAppWrapper.test_include_router_allows_non_conflicting_prefix |
multi_input = columns and (isinstance(columns[0], (list, tuple)))
if not multi_input and column_dtypes and not isinstance(column_dtypes, torch.dtype):
raise TypeError(
"If `columns` is a list of strings, "
"`column_dtypes` must be None or a single `torch.dtype`."
f"G... | 0 | function_complex | ray-project/ray:python/ray/data/util/torch_utils.py:convert_pandas_to_torch_tensor |
"""
B, T_max, H, D = 2, 64, 4, 32
T_prefill = 32 # Enough tokens to exceed window
window = 8 # Window SMALLER than cache size
k_init = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
v_init = torch.randn(B, T_prefill, H, D, device=self.DEVICE,... | 0 | test | karpathy/nanochat:tests/test_attention_fallback.py:TestFA3VsSDPA.test_kvcache_single_token_sliding_window |
"""Test that source is included in log context when provided."""
mock_platform.return_value = "Windows"
mock_policy = MagicMock()
mock_get_policy.return_value = mock_policy
result = configure_windows_postgres_event_loop(source="test_source")
assert result is True
... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/test_windows_postgres_helper.py:TestWindowsPostgresHelper.test_logging_includes_source_when_provided |
(token=self._token) as tmp_repo:
with tempfile.TemporaryDirectory() as tmp_dir:
output_dir_name = tmp_repo.repo_name
trainer = get_regression_trainer(
output_dir=os.path.join(tmp_dir, output_dir_name),
push_to_hub=True,
... | 0 | test | huggingface/transformers:tests/trainer/test_trainer_checkpointing.py:TrainerIntegrationWithHubTester.test_push_to_hub_tags |
try:
# Try to parse as complete JSON object
obj_data = json.loads(obj_str)
items.append(obj_data)
except (json.JSONDecodeError, SyntaxError):
# Try to repair and parse
try:
repaired = _repair_incompl... | 1 | function_simple | run-llama/llama_index:llama-index-core/llama_index/core/program/streaming_utils.py:_parse_partial_list_items |
choices from printable chars.
Parameters
----------
password : str
The password to guess.
Returns
-------
str
The correctly guessed password.
Example:
>>> random.seed(1)
>>> guess_password_simulation("abc") # doctest: +ELLIPSIS
'abc'
"""
chars_list: L... | 1 | function_simple | geekcomputers/Python:password guessing.py:guess_password_simulation |
description="Say 'complete' and nothing else.",
expected_output="The word complete.",
agent=agent,
)
class SimpleFlow(Flow):
@start()
async def run_crew(self):
c = Crew(agents=[agent], tasks=[task], verbose=False)
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/events/test_event_ordering.py:TestFlowWithCrewEventOrdering.test_flow_events_have_ids |
:
"""Test that cookie value is set without URL encoding or quoting."""
response = Response()
cookie_value = "2|abcd1234|efgh5678|1234567890"
_set_unquoted_cookie(response, "test_cookie", cookie_value, secure=False)
cookie_headers = [
value.decode("latin-1")
... | 1 | test | streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_routes_test.py:TestSetUnquotedCookie.test_sets_cookie_without_quoting |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.