input string | label int64 | category string | sample_id string |
|---|---|---|---|
self) -> Dict[str, Any]:
"""获取图谱概览(用于提示词)"""
stats = self.get_stats()
# 获取各类型节点的样例
section_titles = [n.name for n in self.get_nodes_by_type('section')][:10]
search_queries = [n.get('query_text', n.name)
for n in self.get_nodes_by_type('search_qu... | 1 | function_simple | 666ghj/BettaFish:ReportEngine/graphrag/graph_storage.py:Graph.get_summary |
#<replica_id>`, or the
# proxy's actor name, with the format `SERVE_PROXY_ACTOR-<node_id>`.
# Special characters in the names are converted to comply with haproxy
# config's allowed characters, e.g. `#` -> `-`.
return [
ServerConfig(
name=self.get_safe_name(ta... | 0 | function_simple | ray-project/ray:python/ray/serve/_private/haproxy.py:HAProxyManager._targets_to_servers |
tag}>\s*(.*?)(?=<|$)" # 部分闭合
]
# 3. 尝试所有模式
for pattern in patterns:
match = re.search(pattern, text, re.IGNORECASE | re.DOTALL)
if match:
content = match.group(1).strip()
if content: # 确保提取的内容不为空
return content
... | 1 | function_complex | binary-husky/gpt_academic:crazy_functions/review_fns/query_analyzer.py:QueryAnalyzer._extract_tag |
events() -> None:
for i in range(10):
event = ShutdownTestEvent(type=f"event_{i}")
bus.emit("source", event)
time.sleep(0.01)
def set_shutdown_flag() -> None:
time.sleep(0.05)
bus._shutting_down = True
emit_thread = th... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/utilities/events/test_shutdown.py:test_concurrent_access_during_shutdown_flag |
colors.append(
"red" if rate < 0.1 else "orange" if rate < 0.2 else "green"
)
else:
token_rates.append(0)
colors.append("gray")
ax.bar(languages, token_rates, color=colors, alpha=0.7)
ax.set_xlabel("Language")
ax.set_ylabel("Tokens per Character")
ax.set_title("... | 1 | function_complex | google/langextract:benchmarks/plotting.py:_plot_token_rate_by_language |
variables."""
component = PromptComponent()
new_node = {
"template": {
"template": {"value": "Hello {name} and {greeting}!"},
},
"custom_fields": {},
}
current_node = {
"template": {"template": {"value": ""}},
}
... | 1 | test | langflow-ai/langflow:src/lfx/tests/unit/components/test_prompt_component.py:TestPromptComponent.test_update_frontend_node_creates_variable_fields |
models_with_multiple_audios(
vllm_runner,
audio_assets: AudioTestAssets,
dtype: str,
max_tokens: int,
num_logprobs: int,
) -> None:
vllm_prompt = _get_prompt(audio_assets, MULTI_AUDIO_PROMPT)
run_multi_audio_test(
vllm_runner,
[(vllm_prompt, [a.audio_and_sample_rate for a in ... | 1 | test | vllm-project/vllm:tests/models/multimodal/generation/test_voxtral.py:test_models_with_multiple_audios |
bounding box
- TOP: top of the bounding box
- RIGHT: right of the bounding box
- BOTTOM: bottom of the bounding box
Return [0,0,0,0] for an empty mask. For input shape channel_1 x channel_2 x ... x height x width, the output shape
is channel_1 x channel_2 x ... x 4.
Args:
... | 0 | function_simple | huggingface/transformers:src/transformers/models/sam/image_processing_sam_fast.py:_batched_mask_to_box |
not found.
"""
try:
from aiter import QuantType
except ImportError:
return None
if not isinstance(quant_type_str, str):
return None
name = quant_type_str.strip().lower()
mapping = {
"no": QuantType.No,
"per_te... | 1 | function_simple | vllm-project/vllm:vllm/_aiter_ops.py:rocm_aiter_ops.get_aiter_quant_type |
if match:
name = re.sub(k, v, name)
break
else:
raise ValueError(f"Cannot remap {name}")
# Remapping scale names. We could do this in the regex above but it
# would triple the number of lines for most layers.
if name.endswith(".qscal... | 1 | function_simple | vllm-project/vllm:vllm/model_executor/models/mistral_large_3.py:MistralLarge3ForCausalLM._remap_mistral_to_ds |
"""Test updating settings from YAML config."""
mock_service = Mock()
mock_settings = Mock()
# Create an async mock
async def async_update_from_yaml(*_args, **_kwargs):
return None
mock_settings.update_from_yaml = Mock(side_effect=async_update_from_yaml)
... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/utils/test_util.py:TestUpdateSettings.test_update_settings_from_yaml |
"enable_ray_event": True,
},
)
cluster.wait_for_nodes()
ray.init(address=cluster.address)
wait_for_dashboard_agent_available(cluster)
# Submit a ray job
@ray.remote
def f():
return 1
ray.get(f.remote())
# Check that a driver job event with the correct j... | 0 | test | ray-project/ray:python/ray/dashboard/modules/aggregator/tests/test_ray_job_events.py:test_ray_job_events |
ard1},
)
bound_instance = BoundInstance(
instance=instance, bound_runner_id=RUNNER_1_ID, bound_node_id=NODE_A
)
local_runner = FakeRunnerSupervisor(
bound_instance=bound_instance, status=RunnerReady()
)
runners = {RUNNER_1_ID: local_runner}
instances = {INSTANCE_1_ID: instan... | 0 | test | exo-explore/exo:src/exo/worker/tests/unittests/test_plan/test_task_forwarding.py:test_plan_forwards_pending_chat_completion_when_runner_ready |
if self._extraction_in_progress:
return False
self._extraction_in_progress = True
try:
# Try multiple extraction methods
extracted_tokens = await self._extract_from_chat_page()
if not extracted_tokens:
extracted_tokens =... | 1 | function_complex | xtekky/gpt4free:g4f/Provider/yupp/token_extractor.py:TokenExtractor._attempt_extraction |
print(f"Text {i+1}: {text[:50]}...")
print(f" Embedding dimension: {len(embedding)}")
print(f" First 5 values: {embedding[:5]}")
print()
# Get embeddings for all texts at once asynchronously
print("Getting batch embeddings asynchronously...")
all_embedd... | 1 | function_complex | run-llama/llama_index:llama-index-integrations/embeddings/llama-index-embeddings-heroku/examples/async_usage.py:main |
they need individual interaction)
if child_tag in ['input', 'select', 'textarea', 'label']:
return False
# 2. Keep if child is also a propagating element
# (might have stopPropagation, e.g., button in button)
if self._is_propagating_element(child_attributes):
return False
# 3. Keep if has explicit onc... | 0 | function_complex | browser-use/browser-use:browser_use/dom/serializer/serializer.py:DOMTreeSerializer._should_exclude_child |
format=InputFormat.LATEX,
backend=LatexDocumentBackend,
filename="test.tex",
)
backend = LatexDocumentBackend(in_doc=in_doc, path_or_stream=BytesIO(latex_content))
doc = backend.convert()
formulas = [t for t in doc.texts if t.label == DocItemLabel.FORMULA]
assert len(formulas) >=... | 1 | test | docling-project/docling:tests/test_backend_latex.py:test_latex_math_parsing |
params={"url": url, "error": str(e)}, tag="URL_SEED")
return
else:
import xml.etree.ElementTree as ET
try:
root = ET.fromstring(data)
for elem in root.iter():
if '}' in elem.tag:
elem.t... | 1 | function_complex | unclecode/crawl4ai:crawl4ai/async_url_seeder.py:AsyncUrlSeeder._iter_sitemap_content |
Args:
screenshot_b64: Base64 encoded screenshot
selector_map: Map of interactive elements with their positions
device_pixel_ratio: Device pixel ratio for scaling coordinates
viewport_offset_x: X offset for viewport positioning
viewport_offset_y: Y offset for viewport positioning
Returns:
... | 0 | function_complex | browser-use/browser-use:browser_use/browser/python_highlights.py:create_highlighted_screenshot |
shapes = result.spatial_shapes.tolist()
square_shape, landscape_shape, portrait_shape = shapes
# Square: height == width
self.assertEqual(square_shape[0], square_shape[1], "Square image should have equal spatial dimensions")
# Landscape: width > height
self.assertGreater(l... | 0 | test | huggingface/transformers:tests/models/lfm2_vl/test_image_processing_lfm2_vl.py:Lfm2VlImageProcessingTest.test_batch_mixed_aspect_ratios |
_and_inputs_for_common()
layers_type = ["preactivation", "bottleneck"]
for model_class in self.all_model_classes:
for layer_type in layers_type:
config.layer_type = layer_type
inputs_dict["output_hidden_states"] = True
check_hidden_states_outpu... | 0 | test | huggingface/transformers:tests/models/hgnet_v2/test_modeling_hgnet_v2.py:HGNetV2ForImageClassificationTest.test_hidden_states_output |
add_missing_tag_for_asset_id(sess, asset_id=aid, origin="automatic")
for s in states:
if s["exists"]:
survivors.add(os.path.abspath(s["fp"]))
if stale_state_ids:
sess.execute(sqlalchemy.delete(AssetCacheState).where(AssetCacheState.id... | 1 | function_complex | Comfy-Org/ComfyUI:app/assets/scanner.py:_fast_db_consistency_pass |
:
logger.warning(
"Invalid parameters: ssh_client=%s, remote_file_path=%s", bool(ssh_client), remote_file_path
)
return
try:
# Detect remote OS once
remote_os = get_remote_os(ssh_client, logger)
if remote_os == "windows":
_set_windows_file_pe... | 1 | function_complex | apache/airflow:providers/teradata/src/airflow/providers/teradata/utils/tpt_util.py:set_remote_file_permissions |
": "Hi there"},
}
},
]
}
]
# Second call returns user message
mock_events_2 = [
{
"payload": [
{"blob": json.dumps({})},
{
"convers... | 1 | test | run-llama/llama_index:llama-index-integrations/memory/llama-index-memory-bedrock-agentcore/tests/test_agentcore_memory.py:TestBaseAgentCoreMemoryMethods.test_list_events_with_pagination |
test_download_expression_structural_equality(self):
"""Test structural equality comparison for download expressions."""
# Same expressions should be equal
expr1 = download("uri")
expr2 = download("uri")
assert expr1.structurally_equals(expr2)
assert expr2.structurally_eq... | 0 | test | ray-project/ray:python/ray/data/tests/test_download_expression.py:TestDownloadExpressionStructure.test_download_expression_structural_equality |
_drop_index_error_handling(valkey_db, mock_valkey_client):
"""Test error handling when dropping an index."""
# Reset the mock to clear previous calls
mock_valkey_client.execute_command.reset_mock()
# Test 1: Real error (not "Unknown index name") should raise
mock_valkey_client.execute_command.side_... | 1 | test | mem0ai/mem0:tests/vector_stores/test_valkey.py:test_drop_index_error_handling |
if isinstance(message.content, str):
# String content: only cache if it's the only/last block (no tool calls)
blocks.append(
TextBlockParam(
text=message.content,
type='text',
cache_control=AnthropicMessageSerializer._serialize_cache_control(
message.cache and not messa... | 0 | function_complex | browser-use/browser-use:browser_use/llm/anthropic/serializer.py:AnthropicMessageSerializer.serialize |
template_markdown: 完整的模板Markdown文本。
返回:
list[TemplateSection]: 解析后的章节序列;如解析失败则返回单章兜底结构。
"""
sections = parse_template_sections(template_markdown)
if sections:
return sections
logger.warning("模板未解析出章节,使用默认章节骨架")
fallback = TemplateSection(
... | 1 | function_simple | 666ghj/BettaFish:ReportEngine/agent.py:ReportAgent._slice_template |
while tg:
if tg.node_id in graph_unsorted:
break
tg = tg.parent_group
if tg:
# We are already going to visit that TG
break
else:
del ... | 1 | function_complex | apache/airflow:airflow-core/src/airflow/serialization/definitions/taskgroup.py:SerializedTaskGroup.topological_sort |
ensor", "torch.Tensor"]:
"""
Pad an image to the specified size and create the corresponding pixel mask.
"""
original_size = image.shape[-2:]
padding_bottom = padded_size[0] - original_size[0]
padding_right = padded_size[1] - original_size[1]
if padding_bottom < ... | 0 | function_simple | huggingface/transformers:src/transformers/models/idefics2/image_processing_idefics2_fast.py:Idefics2ImageProcessorFast.pad |
downstream_op, downstream_op_state = self._mock_operator()
op.output_dependencies = [downstream_op]
topology = {op: op_state, downstream_op: downstream_op_state}
context = self._create_context(backpressure_ratio=2.0)
rm = self._mock_resource_manager()
# Utilized budget fra... | 0 | test | ray-project/ray:python/ray/data/tests/test_downstream_capacity_backpressure_policy.py:TestDownstreamCapacityBackpressurePolicy.test_backpressure_triggered_high_queue_ratio |
call(
func: Callable[[LLMCallHookContext], str | None] | None = None,
*,
agents: list[str] | None = None,
) -> (
Callable[[LLMCallHookContext], str | None]
| Callable[
[Callable[[LLMCallHookContext], str | None]],
Callable[[LLMCallHookContext], str | None],
]
):
"""Decorator ... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/hooks/decorators.py:after_llm_call |
1})
o4 = LimitOperator(1, o3, DataContext.get_current())
# Mock min_max_resource_requirements to return default unbounded behavior
for op in [o2, o3]:
op.min_max_resource_requirements = MagicMock(
return_value=(ExecutionResources.zero(), ExecutionResources.inf())
... | 0 | test | ray-project/ray:python/ray/data/tests/test_reservation_based_resource_allocator.py:TestReservationOpResourceAllocator.test_basic |
FlowBaseComponent()
frontend_node = {
"template": {"flow_name_selected": {"selected_metadata": {"id": "flow_id", "updated_at": "timestamp"}}}
}
mock_graph = MagicMock(spec=Graph)
mock_output = MagicMock(spec=Output)
mock_output.model_dump.return_value = {"name": "outp... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/base/tools/test_run_flow.py:TestRunFlowBaseComponentUpdateOutputs.test_update_outputs_with_flow_name_selected |
# Sleep for 3 seconds, longer than HAProxy's 2s timeout
# Use regular time.sleep (not async) to avoid event loop issues
time.sleep(3)
return "This should not be reached"
serve.run(TimeoutDeployment.bind(), name="timeout_app", route_prefix="/test")
url = get_applicat... | 0 | test | ray-project/ray:python/ray/serve/tests/test_haproxy.py:test_504_error_translated_to_500 |
interface.print_user_message(examples[example_name]["text"])
chat.append({"role": "user", "content": examples[example_name]["text"]})
else:
example_error = (
f"Example {example_name} not found in list of available examples: {list(examples.key... | 0 | function_complex | huggingface/transformers:src/transformers/cli/chat.py:Chat.handle_non_exit_user_commands |
_if_haproxy_enabled, serve_instance
):
"""Each replica's gRPC `ListApplications` method should only report the
single application that replica is serving.
"""
@serve.deployment
class D1:
def __call__(self, *args):
return "D1"
@serve.deployment
class D2:
def __ca... | 0 | test | ray-project/ray:python/ray/serve/tests/test_direct_ingress.py:test_grpc_list_applications_endpoint |
_supervisor_comms.send.return_value = XComSequenceIndexResult(root="some-value")
xcom = resolve_xcom_backend()
assert xcom.__name__ == "CustomXCom"
monkeypatch.setattr(airflow.sdk.execution_time.xcom, "XCom", xcom)
assert lazy_sequence[4] == "Made with CustomXCom: some-value"
mock_supervisor_comms... | 1 | test | apache/airflow:task-sdk/tests/task_sdk/execution_time/test_lazy_sequence.py:test_getitem_calls_correct_deserialise |
do_code_enrichment=True,
do_formula_enrichment=True,
code_formula_options=code_formula_options,
)
# Create converter with the configured options
converter = DocumentConverter(
format_options={
InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)
... | 1 | function_simple | docling-project/docling:docs/examples/code_formula_granite_docling.py:extract_with_preset |
=0, local_rank=2)
)
rank_manager.recover_rank(
"r3", "node_1", ReplicaRank(rank=11, node_rank=0, local_rank=3)
)
rank_manager.recover_rank(
"r4", "node_1", ReplicaRank(rank=15, node_rank=0, local_rank=4)
)
rank_manager.check_rank_consistency_and_r... | 0 | test | ray-project/ray:python/ray/serve/tests/unit/test_deployment_rank_manager.py:TestDeploymentRankManagerEdgeCases.test_reassignment_preserves_target_ranks_exactly |
1,)`):
The cumulative sequence lengths of each image or video feature.
position_embeddings (`tuple(torch.Tensor, torch.Tensor)` of shape `(num_patches, head_dim // 2)`):
The cosine and sine position embeddings for vision attention.
"""
residual = hidden_states
h... | 0 | function_simple | huggingface/transformers:src/transformers/models/glm_image/modular_glm_image.py:GlmImageVisionBlock.forward |
document blocks).
Returns:
Content block dict or None if not supported.
"""
content_type = file.content_type
if isinstance(resolved, FileReference):
if not resolved.file_uri:
raise ValueError("Bedrock requires file_uri for FileReference (S3 URI)... | 0 | function_complex | crewAIInc/crewAI:lib/crewai-files/src/crewai_files/formatting/bedrock.py:BedrockFormatter.format_block |
ip_extraction(self):
"""Test automatic IP extraction from server URL."""
test_cases = [
("http://192.168.1.1:8080", "192.168.1.1"),
("https://10.0.0.1:3128", "10.0.0.1"),
("192.168.1.100:8080", "192.168.1.100"),
("proxy.example.com:8080", "proxy.example.co... | 1 | test | unclecode/crawl4ai:tests/proxy/test_proxy_config.py:TestProxyConfig.test_proxy_config_object_ip_extraction |
:
"""Test that all block translators implemented in langchain-core are registered.
If this test fails, it is likely that a block translator is implemented but not
registered on import. Check that the provider is included in
`langchain_core.messages.block_translators.__init__._register_translators`.
... | 1 | test | langchain-ai/langchain:libs/core/tests/unit_tests/messages/block_translators/test_registration.py:test_all_providers_registered |
:
{"code": some_arbitrary_text_with_unescaped_quotes}
As Groq may not escape quotes in the executed tools, e.g.:
```
'{"code": "import math; print("The square root of 101 is: "); print(math.sqrt(101))"}'
```
""" # noqa: E501
m = re.fullmatch(r'\s*\{\s*"code"\s*:\s*"(.*)"\s*\}\s*', s, flags... | 1 | function_simple | langchain-ai/langchain:libs/core/langchain_core/messages/block_translators/groq.py:_parse_code_json |
use.skill_cli.sessions import SessionInfo
httpserver.expect_request('/').respond_with_data(
'<html><body><button>Click me</button></body></html>',
content_type='text/html',
)
session = BrowserSession(headless=True)
await session.start()
try:
from browser_use.browser.events import NavigateToUrlEvent... | 0 | test | browser-use/browser-use:tests/ci/test_cli_coordinate_click.py:TestClickCommandHandler.test_coordinate_click_handler |
to relative path from repository root if needed
if file_path.startswith(ROOT):
file_path = file_path[len(ROOT) :].lstrip("/")
# Construct the raw GitHub URL for the file
url = f"{GITHUB_RAW_URL}/{file_path}"
try:
# Make a HEAD request to check if file exists (more efficient than GET)
... | 0 | function_simple | huggingface/transformers:utils/add_dates.py:check_file_exists_on_github |
: tuple[type, ...],
namespace: dict[str, Any],
**kwargs: Any,
) -> type[CrewClass]:
"""Create crew class with configuration and method injection.
Args:
name: Class name.
bases: Base classes.
namespace: Class namespace dictionary.
**kwa... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/project/crew_base.py:CrewBaseMeta.__new__ |
-1"
serve._run(
Deployment1.options(name="deployment-1").bind(),
name="app-1",
route_prefix="/app-1",
_blocking=False,
)
def _func():
http_ports = get_http_ports("/app-1", first_only=False)
grpc_ports = get_grpc_ports("/app-1", first_only=False)
asse... | 0 | test | ray-project/ray:python/ray/serve/tests/test_direct_ingress.py:test_some_replicas_not_running |
': char,
'key': char,
},
session_id=session_id,
)
# Step 3: Send keyUp event (NO text parameter)
await cdp_client.send.Input.dispatchKeyEvent(
params={
'type': 'keyUp',
'key': base_key,
'code': key_code,
'modifiers': modifiers,
'windowsVirtualK... | 0 | function_complex | browser-use/browser-use:browser_use/actor/element.py:Element.fill |
def unregister_after_tool_call_hook(
hook: AfterToolCallHookType | AfterToolCallHookCallable,
) -> bool:
"""Unregister a specific global after_tool_call hook.
Args:
hook: The hook function to remove
Returns:
True if the hook was found and removed, False otherwise
Example:
... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/hooks/tool_hooks.py:unregister_after_tool_call_hook |
# retrieve the correct sequences each
audios = []
# TODO: see above, dac doesn't work in batches yet
with torch.no_grad():
for i in range(start_of_generation_idx.shape[0]):
output_i = output_sequences[i, :, start_of_generation_idx[i] : end_of_generation_idx[i]]... | 0 | function_complex | huggingface/transformers:src/transformers/models/dia/processing_dia.py:DiaProcessor.batch_decode |
)
module.request = SimpleNamespace(args={"doc_id": "doc-1"}, headers={})
payload = {
"id": "root",
"children": [
{"id": "dup"},
{"id": "dup", "children": [{"id": "dup"}]},
],
}
class _SRes:
ids = ["bad-json", "mind-map"]
field = {
... | 1 | test | infiniflow/ragflow:test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py:test_knowledge_graph_repeat_deal_matrix_unit |
**kwargs: Additional keyword arguments (not used).
Returns:
The evaluation results containing the score.
"""
if self.ignore_case:
prediction = prediction.lower()
reference = reference.lower()
if self.ignore_punctuation:
prediction = pre... | 1 | function_simple | langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/exact_match/base.py:ExactMatchStringEvaluator._evaluate_strings |
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate whether output A is preferred to output B.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second... | 1 | function_simple | langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/comparison/eval_chain.py:PairwiseStringEvalChain._evaluate_string_pairs |
tool with multiple injected and non-injected parameters.
Args:
query: The search query string.
limit: Maximum number of results to return.
state: The graph state (injected).
store: The persistent store (injected).
runtime: The tool runtime context (i... | 1 | test | langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/test_create_agent_tool_validation.py:test_create_agent_error_content_with_multiple_params |
url = FileUrl(url="https://example.com/image.png")
mock_response = MagicMock()
mock_response.content = b"async fake content"
mock_response.headers = {"content-type": "image/png"}
mock_response.raise_for_status = MagicMock()
mock_client = MagicMock()
mock_client.get... | 0 | test | crewAIInc/crewAI:lib/crewai-files/tests/test_file_url.py:TestFileUrl.test_aread_fetches_content |
iation internally.
args: List of argument expressions (positional arguments)
kwargs: Dictionary of keyword argument expressions
Example:
>>> from ray.data.expressions import col, udf
>>> import pyarrow as pa
>>> import pyarrow.compute as pc
>>> from ray.data.datatype import DataType
>>>
... | 0 | documentation | ray-project/ray:python/ray/data/expressions.py:UDFExpr:class_doc |
*):
The width in pixels of the generated image.
image_latents (`Tensor`):
image latents used to guide the image generation. Can be generated from vae_encoder step.
latents (`Tensor`, *optional*):
Pre-generated noisy latents for image generation.
generator (`Generator`, *o... | 1 | documentation | huggingface/diffusers:src/diffusers/modular_pipelines/qwenimage/modular_blocks_qwenimage_edit_plus.py:QwenImageEditPlusCoreDenoiseStep:class_doc |
ensor:
"""
Args:
hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
The final hidden states of the model.
grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
The temporal, height and width of feature shape of each image i... | 0 | function_simple | huggingface/transformers:src/transformers/models/qwen3_5/modular_qwen3_5.py:Qwen3_5VisionModel.forward |
def cleanup_session_files(session: str) -> None:
"""Remove session socket, PID, lock, and metadata files."""
sock_path = get_socket_path(session)
pid_path = get_pid_path(session)
lock_path = get_lock_path(session)
meta_path = Path(tempfile.gettempdir()) / f'browser-use-{session}.meta'
# Remove socket file (Unix ... | 0 | function_simple | browser-use/browser-use:browser_use/skill_cli/utils.py:cleanup_session_files |
If False, cancel all pending tasks immediately.
"""
if wait:
self.flush()
with self._rwlock.w_locked():
self._shutting_down = True
loop = getattr(self, "_loop", None)
if loop is None or loop.is_closed():
return
if wai... | 0 | function_complex | crewAIInc/crewAI:lib/crewai/src/crewai/events/event_bus.py:CrewAIEventsBus.shutdown |
ex.submit(_one_completion, client,
[{"role": "user", "content": prompt}], 0.9)
for _ in range(3)
]
for fut in cf.as_completed(futures):
candidates.append(fut.result())
# Synthesize candidates
candidate_texts = []
for i, c in enumer... | 0 | function_simple | Shubhamsaboo/awesome-llm-apps:advanced_llm_apps/gpt_oss_critique_improvement_loop/streamlit_app.py:generate_initial_answer |
# audio chunk
53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 78, # audio_eos + vision_eos
79, 80, # text
]],
[[
0, 1, # text
... | 0 | test | huggingface/transformers:tests/models/qwen3_omni_moe/test_modeling_qwen3_omni_moe.py:Qwen3OmniMoeThinkerForConditionalGenerationModelTest.test_get_rope_index_video_with_audio |
server = self._create_server()
mock_socket = mock.MagicMock(spec=socket.socket)
async def test_cancellation() -> None:
with (
patch(
"streamlit.web.server.starlette.starlette_server._bind_socket",
return_value=mock_socket,
... | 1 | test | streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_server_test.py:TestServerLifecycle.test_no_deadlock_on_task_cancellation |
)
pieces.append(toks.astype(np.int32, copy=False))
all_tokens = (
pieces[0].astype(np.int32, copy=False)
if len(pieces) == 1
else np.concatenate(pieces, axis=0).astype(np.int32, copy=False)
)
required_tokens = num_samples * sequence_length
if all_tokens.size < requi... | 1 | function_complex | keras-team/keras:keras/src/quantizers/gptq_core.py:get_dataloader |
print("=" * 60)
try:
scheduler = ctx.create_scheduler()
schedule = scheduler.resolve()
now = ctx.get_time()
date_str = ctx.format_date()
print(f"\n⏰ 当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')} ({ctx.timezone})")
print(f"📅 当前日期: {date_str}")
print(f"\n📋... | 1 | function_complex | sansan0/TrendRadar:trendradar/__main__.py:_handle_status_commands |
attention_kwargs.copy() if joint_attention_kwargs is not None else {}
if encoder_hidden_states_mask is not None:
# Build joint mask: [text_mask, all_ones_for_image]
batch_size, image_seq_len = hidden_states.shape[:2]
image_mask = torch.ones((batch_size, image_seq_len), dtype=... | 1 | function_complex | huggingface/diffusers:src/diffusers/models/controlnets/controlnet_qwenimage.py:QwenImageControlNetModel.forward |
api_key: API key for Gemini service.
vertexai: Whether to use Vertex AI instead of API key authentication.
credentials: Optional Google auth credentials for Vertex AI.
project: Google Cloud project ID for Vertex AI.
location: Vertex AI location (e.g., 'global', 'us-central1').
http_o... | 1 | function_complex | google/langextract:langextract/providers/gemini.py:GeminiLanguageModel.__init__ |
response")
# Get user info
email = None
async with session.get(
"https://www.googleapis.com/oauth2/v1/userinfo?alt=json",
headers={"Authorization": f"Bearer {access_token}"}
) as resp:
if resp.ok:
... | 1 | function_complex | xtekky/gpt4free:g4f/Provider/needs_auth/GeminiCLI.py:GeminiCLI.exchange_code_for_tokens |
# Use alias.asname if present, else alias.name
name = alias.asname if alias.asname else alias.name
type_checking_names.add(name)
elif isinstance(stmt, ast.Import):
# import X as Y or import X.Y as Z
... | 1 | function_complex | apache/airflow:scripts/ci/prek/check_common_compat_lazy_imports.py:extract_type_checking_names |
return {
"workflows": workflows,
"total": len(workflows),
"limit": limit,
"offset": offset,
"response_time_ms": round(response_time, 2),
"timestamp": datetime.now().isoformat(),
... | 0 | function_simple | Zie619/n8n-workflows:src/enhanced_api.py:get_workflows_enhanced |
Dict[str, Any]]): Additional parameters to pass to Spider API.
These override any parameters set by the LLM.
log_failures (bool): If True, logs errors. Defaults to True.
**kwargs: Additional arguments passed to BaseTool.
Raises:
ImportError: If spider-client ... | 0 | function_simple | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/spider_tool/spider_tool.py:SpiderTool.__init__ |
# Analyze the export
await analyze_knowledge_base(kb_path)
# Import and extend
await import_and_continue()
# Demonstrate sharing
await share_knowledge_bases()
print("\n" + "="*60)
print("All examples completed successfully!")
p... | 1 | function_simple | unclecode/crawl4ai:docs/examples/adaptive_crawling/export_import_kb.py:main |
state_dict_keys: dict | None = None):
"""
This function should be applied only once, on the concatenated keys to efficiently rename using
the key mappings.
"""
output_dict = {}
if state_dict_keys is not None:
old_text = "\n".join(state_dict_keys)
new_text = old_text
for p... | 0 | function_complex | huggingface/transformers:src/transformers/models/dinov3_convnext/convert_dinov3_convnext_to_hf.py:convert_old_keys_to_new_keys |
"""Positionally encode points that are normalized to [0,1]."""
coordinates = input_coords.clone()
if input_shape is not None:
coordinates[:, :, :, 0] = coordinates[:, :, :, 0] / input_shape[1]
coordinates[:, :, :, 1] = coordinates[:, :, :, 1] / input_shape[0]
coord... | 0 | function_simple | huggingface/transformers:src/transformers/models/sam2/modular_sam2.py:Sam2PositionalEmbedding.forward |
"""Test handler with multiple dependencies."""
execution_order = []
with crewai_event_bus.scoped_handlers():
@crewai_event_bus.on(DependsTestEvent)
def setup_a(source, event: DependsTestEvent):
execution_order.append("setup_a")
@crewai_event_bus.on(DependsTestEvent)
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/events/test_depends.py:test_multiple_dependencies |
cnow() + timedelta(seconds=0.1),
poke_interval=5,
**default_trigger_args,
)
mock_supervisor_comms.send.return_value = HITLDetailResponse(
response_received=False,
responded_by_user=None,
responded_at=None,
chosen_options=None,
... | 1 | test | apache/airflow:providers/standard/tests/unit/standard/triggers/test_hitl.py:TestHITLTrigger.test_run_fallback_to_default_due_to_timeout |
["started"].agent_role == agent.role
assert events["started"].task_id == str(task.id)
assert events["started"].iteration == 1
assert events["failed"].agent_id == str(agent.id)
assert events["failed"].agent_role == agent.role
assert events["failed"].task_id ==... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/experimental/evaluation/test_agent_evaluator.py:TestAgentEvaluator.test_failed_evaluation |
self.text_encoder.dtype
prompt = [prompt] if isinstance(prompt, str) else prompt
batch_size = len(prompt)
if getattr(self, "tokenizer", None) is not None:
# Gemma expects left padding for chat-style prompts
self.tokenizer.padding_side = "left"
if self.token... | 1 | function_complex | huggingface/diffusers:src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py:LTX2ImageToVideoPipeline._get_gemma_prompt_embeds |
# apply sigmoid on the raw mask logits to turn them into range (0, 1)
mask_for_mem = torch.sigmoid(pred_masks_high_res)
# apply scale and bias terms to the sigmoid probabilities
mask_for_mem = mask_for_mem * self.config.sigmoid_scale_for_mem_enc
mask_for_mem = mask_for_mem + self.c... | 0 | function_simple | huggingface/transformers:src/transformers/models/edgetam_video/modular_edgetam_video.py:EdgeTamVideoModel._encode_new_memory |
:
# Prefetch mode
start = time.time()
prefetch_config = CrawlerRunConfig(prefetch=True)
await crawler.arun(TEST_DOMAIN, config=prefetch_config)
prefetch_time = time.time() - start
# Full mode
start = time.time()
full_config... | 1 | test | unclecode/crawl4ai:tests/test_prefetch_integration.py:TestPrefetchPerformance.test_prefetch_returns_quickly |
lora_id=None,
medium="GPU",
lora_name=None,
)
events2.add_events([event2])
output2 = KVConnectorOutput(kv_cache_events=events2)
mock_connector.update_connector_output(output2)
# Third update
events3 = LMCacheKVEvents(num_workers=1)
event... | 1 | test | vllm-project/vllm:tests/v1/kv_connector/unit/test_lmcache_connector.py:TestUpdateConnectorOutput.test_multiple_updates |
history (type-safe access)
errors: list[str] = []
for step in self.complete_history:
for result in step.result:
if result.error:
errors.append(result.error)
# Determine success from task completion status (type-safe)
is_done = self._is_task_done()
task_success: Any = self.namespace.get('_task_suc... | 0 | function_complex | browser-use/browser-use:browser_use/code_use/service.py:CodeAgent._log_agent_event |
particularly the American Revolution), extravagant spending by the monarchy, and inefficient taxation.
2. **Social Inequality**: The rigid class system (the Ancien Régime) favored the nobility and clergy while the majority of the population (the Third Estate) bore the brunt of taxation and had limited right... | 0 | test | huggingface/transformers:tests/models/falcon_h1/test_modeling_falcon_h1.py:FalconH1ModelIntegrationTest.test_falcon_h1_hard |
model.eval()
inputs = self._prepare_for_class(inputs_dict, model_class)
input_ids = inputs["input_ids"]
del inputs["input_ids"]
del inputs["pixel_values"]
del inputs["pixel_values_videos"]
inputs_embeds = model.get_input_embeddings()(input_... | 0 | test | huggingface/transformers:tests/models/perception_lm/test_modeling_perception_lm.py:PerceptionLMForConditionalGenerationModelTest.test_inputs_embeds_matches_input_ids |
start: Start datetime for filtering
end: End datetime for filtering
Returns:
List of tuples containing (file_path, file_info)
"""
if self.client is None:
raise ConnectorMissingCredentialError("WebDAV client not initialized")
fi... | 1 | function_complex | infiniflow/ragflow:common/data_source/webdav_connector.py:WebDAVConnector._list_files_recursive |
size: SizeDict,
interpolation: Optional["tvF.InterpolationMode"] = None,
antialias: bool = True,
**kwargs,
) -> "torch.Tensor":
"""
Resize an image to the specified size.
Args:
image (`torch.Tensor`):
Image to resize.
size (`... | 0 | function_simple | huggingface/transformers:src/transformers/models/tvp/image_processing_tvp_fast.py:TvpImageProcessorFast.resize |
By default (when `tools=None`), all tools are emulated. You can specify which
tools to emulate by passing a list of tool names or `BaseTool` instances.
Examples:
!!! example "Emulate all tools (default behavior)"
```python
from langchain.agents.middleware import LLMToolEmulator
middlewar... | 1 | documentation | langchain-ai/langchain:libs/langchain_v1/langchain/agents/middleware/tool_emulator.py:LLMToolEmulator:class_doc |
= True
config.output_attentions = self.has_attentions
for k in config.sub_configs:
getattr(config, k).output_attentions = self.has_attentions
# force eager attention to support output attentions
config._attn_implementation = "eager"
# no need to test all models as... | 0 | test | huggingface/transformers:tests/models/video_llama_3/test_modeling_video_llama_3.py:VideoLlama3VisionModelTest.test_retain_grad_hidden_states_attentions |
test_async_get_connection_uses_cache(self):
"""Test that _async_get_connection uses cache when connection is cached."""
from airflow.sdk.execution_time.context import _async_get_connection
conn_id = "test_conn"
uri = "postgres://user:pass@host:5432/db"
SecretCache.save_connect... | 1 | test | apache/airflow:task-sdk/tests/task_sdk/execution_time/test_context_cache.py:TestAsyncConnectionCache.test_async_get_connection_uses_cache |
"""Test execution when tracing=False explicitly set."""
with pytest.MonkeyPatch.context() as mp:
mp.setenv("CREWAI_DISABLE_TELEMETRY", "false")
agent = Agent(
role="Test Agent",
goal="Test goal",
backstory="Test backstory",
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/tracing/test_trace_enable_disable.py:TestTraceEnableDisable.test_no_http_calls_when_disabled_via_tracing_false |
) -> None:
"""Test that expired items are removed when accessing the cache."""
_STARLETTE_AUTH_CACHE._cache.clear()
current_time = 1000.0
monkeypatch.setattr(starlette_auth_routes.time, "time", lambda: current_time)
_STARLETTE_AUTH_CACHE._cache["key1"] = ("value1", 1500.0)
... | 1 | test | streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_auth_routes_test.py:TestAsyncAuthCacheExpiration.test_expired_items_are_evicted_on_get |
nodes( # type: ignore[override]
self,
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
**delete_kwargs: Any,
) -> None:
"""Async wrapper around :meth:`delete_nodes`."""
await self._ainitialize()
if not node_ids:
re... | 1 | function_simple | run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-volcenginemysql/llama_index/vector_stores/volcengine_mysql/base.py:VolcengineMySQLVectorStore.adelete_nodes |
SourceHandle:
name = "item"
source_handle = SourceHandle()
target_id = "component_a"
class MockVertex:
outgoing_edges = [MockEdge()]
id = "loop"
class MockGraph:
successor_map = {"component_a": []}
result = get_loop... | 1 | test | langflow-ai/langflow:src/lfx/tests/unit/components/flow_controls/test_loop_events.py:TestGetLoopBodyVertices.test_returns_empty_set_when_no_feedback_vertex |
"""Extract page metadata"""
print("[HOOK] Extracting metadata")
metadata = await page.evaluate('''() => {
const getMeta = (name) => {
const el = document.querySelector(`meta[name="${name}"], meta[property="${name}"]`);
return el ? el.getAttribute('content') : null;
};
... | 1 | function_simple | unclecode/crawl4ai:docs/examples/docker_client_hooks_example.py:extract_metadata_hook |
_scrolls_all_execute(self, browser_session, base_url, tools):
"""Multiple scroll actions should all execute."""
await tools.navigate(url=f'{base_url}/static', new_tab=False, browser_session=browser_session)
await asyncio.sleep(0.5)
ActionModel = tools.registry.create_action_model()
actions = [
ActionModel... | 0 | test | browser-use/browser-use:tests/ci/test_multi_act_guards.py:TestSafeChain.test_multiple_scrolls_all_execute |
manager.register_from_manifest(manifest, package_root)
comp_name = "pkg.slider"
# Existing definition with html to be preserved during recompute
manager.register(BidiComponentDefinition(name=comp_name, html="<p>orig</p>"))
# Record API inputs as globs resolved relative to asset_dir
manager.rec... | 1 | test | streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_manager.py:test_on_components_changed_preserves_html_and_resolves_assets |
_list_enumerate():
"""Test enumerate list environment"""
latex_content = b"""
\\documentclass{article}
\\begin{document}
\\begin{enumerate}
\\item Alpha
\\item Beta
\\end{enumerate}
\\end{document}
"""
in_doc = InputDocument(
path_or_stream=BytesIO(latex_content),
... | 1 | test | docling-project/docling:tests/test_backend_latex.py:test_latex_list_enumerate |
if job.state.name == BatchJobStatus.SUCCEEDED.value:
self.log.info("Job execution completed")
yield TriggerEvent(
{
"status": "success",
"message": "Job completed",
"job":... | 1 | function_complex | apache/airflow:providers/google/src/airflow/providers/google/cloud/triggers/gen_ai.py:GenAIGeminiCreateEmbeddingsBatchJobTrigger.run |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.