Dataset Viewer
Auto-converted to Parquet Duplicate
input
string
label
int64
category
string
sample_id
string
self._access_token is None or self._token_expires_at is None or time.time() >= self._token_expires_at ): async with self._lock: if ( self._access_token is None or self._token_expires_at is None or time.time() >= self._token_expires_at ): await self._fetch_token(client) if self._access_token
0
function_complex
crewAIInc/crewAI:lib/crewai/src/crewai/a2a/auth/client_schemes.py:OAuth2ClientCredentials.apply_auth
| None = None, **kwargs: Unpack[SegformerImageProcessorKwargs], ) -> BatchFeature: """ Preprocess image-like inputs. """ images = self._prepare_image_like_inputs( images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device ) images_kwargs = kwargs.copy() images_kwargs["do_reduce_labels"] = False batch_feature = self._preprocess(images, **images_kwargs) if segmentation_maps is not None: processed_segmentation_maps = self._
0
function_simple
huggingface/transformers:src/transformers/models/segformer/modular_segformer.py:SegformerImageProcessorFast._preprocess_image_like_inputs
"""Emit LLM call completed event.""" from crewai.utilities.serialization import to_serializable crewai_event_bus.emit( self, event=LLMCallCompletedEvent( messages=to_serializable(messages), response=to_serializable(response), call_type=call_type, from_task=from_task, from_agent=from_agent, model=self.model, call_id=get_current_call_id
0
function_simple
crewAIInc/crewAI:lib/crewai/src/crewai/llms/base_llm.py:BaseLLM._emit_call_completed_event
用于处理 inlineRun 类型的外层 marks。 """ if not isinstance(mark, dict): return text mtype = mark.get("type") if mtype == "bold": return f"**{text}**" elif mtype == "italic": return f"*{text}*" elif mtype == "underline": return f"__{text}__" elif mtype == "strike": return f"~~{text}~~" elif mtype == "code":
1
function_complex
666ghj/BettaFish:ReportEngine/renderers/markdown_renderer.py:MarkdownRenderer._apply_mark
""" Simple test that checks if the quantized model is working properly after being saved and loaded """ with tempfile.TemporaryDirectory() as tmpdirname: self.quantized_model.save_pretrained(tmpdirname) model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.
0
test
huggingface/transformers:tests/quantization/fp_quant_integration/test_fp_quant.py:FPQuantBaseTest.test_save_pretrained
( response.iter_bytes(1) ) # Read 1 byte, then exit - connection closes # Run many times to hit the race (disconnect arrives before request_task exits) num_requests = 500 with ThreadPoolExecutor(max_workers=10) as executor: futures = [ executor.submit(_request_then_close_immediately) for _ in range(num_requests) ] for f in as_completed(futures): f.result() # First assert all requests were processed def check_request_count_and_no_499_errors(): check_sum_met
0
test
ray-project/ray:python/ray/serve/tests/test_metrics_haproxy.py:test_no_499_misclassification_after_successful_response
still_applied_to_regular_responses(): """ Test that stop words ARE still applied for regular (non-structured) responses. This ensures the fix didn't break normal stop word behavior. """ # Create OpenAI completion instance with stop words configured llm = OpenAICompletion( model="gpt-4o", stop=["Observation:", "Final Answer:"], ) # Response that contains a stop word - should be truncated response_with_stop_word = "I need to search for more information.\n\nAction: search\nObservation: Found results" # Test the _apply_stop_words method directly result = llm._apply_stop_words(response_with_stop_word) # Response should be truncated at the stop word assert "Observation:" not in result assert "Found results" not in result
0
test
crewAIInc/crewAI:lib/crewai/tests/llms/openai/test_openai.py:test_openai_stop_words_still_applied_to_regular_responses
large payloads.""" @serve.deployment class LargePayloadHandler: def __call__(self, request): # Return a large response (1MB) large_data = "x" * (1024 * 1024) # 1MB string return {"data": large_data, "size": len(large_data)} serve.run(LargePayloadHandler.bind()) response = requests.get( "https://localhost:8000/LargePayloadHandler", verify=False ) assert response.status_code == 200 data = response.json() assert data
0
test
ray-project/ray:python/ray/serve/tests/test_https_proxy.py:TestHTTPSProxy.test_https_large_payload
batch, grad_value in zip(data_loader, normal_gradients): run_model_step(model, batch[0], batch[1], grad_value) expected_loss_scale *= 2 assert loss_scaler.cur_scale == expected_loss_scale assert loss_scaler.cur_iter == expected_iteration # Run model with overflows to decrease scale overflow_gradients = [float('inf')] expected_iteration += len(overflow_gradients) data_loader = random_dataloader(model=model, total_samples=len(overflow_gradients),
1
test
deepspeedai/DeepSpeed:tests/unit/runtime/half_precision/test_zero_optim_overflow.py:TestZeROFloat16.test_some_overflow
3ForConditionalGeneration.from_pretrained( "lkhl/VideoLLaMA3-2B-Image-HF", dtype=torch.bfloat16, device_map=torch_device ) text = self.processor.apply_chat_template(self.messages, tokenize=False, add_generation_prompt=True) messages2 = [ {"role": "user", "content": [{"type": "text", "text": "What is relativity?"}]}, ] text2 = self.processor.apply_chat_template(messages2, tokenize=False, add_generation_prompt=True) inputs = self.processor( text=[text, text2], images=[self.image], padding=True, padding_side="left",
0
test
huggingface/transformers:tests/models/video_llama_3/test_modeling_video_llama_3.py:VideoLlama3IntegrationTest.test_small_model_integration_test_batch_wo_image
device, rank, dtype, seed=42 + i, lr=lr,
1
test
deepspeedai/DeepSpeed:tests/unit/v1/zero/test_zero_user_backward.py:TestZeroUserBackwardMultipleEngines.test_multiple_engines_combined_loss
**ray.get(client._controller.get_serve_instance_details.remote()) ) proxy_actor_ids = {proxy.actor_id for _, proxy in serve_details.proxies.items()} assert len(proxy_actor_ids) == 3 # Start a long-running request in background to test draining behavior request_result = [] def make_blocking_request(): try: response = httpx.get("http://localhost:8000/", timeout=5) request_result.append(("success", response.status_code)) except Exception as e: request_result.append(("error", str(e))) request_thread = threading.Thread(target=make_blocking_request) request_thread.start()
0
test
ray-project/ray:python/ray/serve/tests/test_haproxy.py:test_drain_and_undrain_haproxy_manager
heads ) num_key_value_heads = ( text_config.num_attention_heads if getattr(text_config, "num_key_value_heads", None) is None else text_config.num_key_value_heads ) num_hidden_layers = text_config.num_hidden_layers inputs_embeds = model.get_input_embeddings()(input_ids) outputs = model.generate(inputs_embeds=inputs_embeds, **generation_kwargs, **inputs_dict) #
0
test
huggingface/transformers:tests/models/gemma3n/test_modeling_gemma3n.py:Gemma3nTextModelTest.test_generate_from_inputs_embeds_with_static_cache
MagicMock() var1.name = "WATSONX_APIKEY" var1.type = "Credential" var2 = MagicMock() var2.name = "WATSONX_PROJECT_ID" var2.type = "Credential" var3 = MagicMock() var3.name = "WATSONX_URL" var3.type = "Credential" mock_variables = [var1, var2, var3] with patch("langflow.agentic.services.provider_service.get_variable_service") as mock_get_service: from langflow.services.variable.service import DatabaseVariableService mock_service =
1
test
langflow-ai/langflow:src/backend/tests/unit/agentic/services/test_provider_service_multi.py:TestGetEnabledProvidersForUserMulti.test_should_enable_provider_when_all_required_vars_present
shape, expected_shape) # Confirm out_indices was propagated to backbone self.assertEqual(len(model.model.backbone.intermediate_channel_sizes), 3) else: # Confirm out_indices was propagated to backbone self.assertEqual(len(model.backbone.intermediate_channel_sizes), 3) self.assertTrue(outputs) # These kwargs are all removed and are supported only for BC # In new models we have only `backbone_config`. Let's test that there is no regression
0
test
huggingface/transformers:tests/models/d_fine/test_modeling_d_fine.py:DFineModelTest.test_backbone_selection
model_eager = model_eager.eval().to(torch_device) self.assertTrue(model_eager.config._attn_implementation == "eager") self.assertTrue(model_eager.language_model.config._attn_implementation == "eager") self.assertTrue(model_eager.audio_tower.config._attn_implementation == "eager") for _, submodule in model_eager.named_modules(): class_name = submodule.__class__.__name__ if "SdpaAttention" in class_name or "Sdpa
0
test
huggingface/transformers:tests/models/glmasr/test_modeling_glmasr.py:GlmAsrForConditionalGenerationModelTest.test_sdpa_can_dispatch_composite_models
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values self.assertEqual( tuple(encoded_images.shape), (1, image_processing.max_num_patches, 3 * image_processing.encoder_patch_size**2), ) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values self.assertEqual( tuple(encoded_images.shape), ( self.image_processor_tester.batch_size, image_processing.max_num
0
test
huggingface/transformers:tests/models/lfm2_vl/test_image_processing_lfm2_vl.py:Lfm2VlImageProcessingTest.test_call_pytorch
single_image_embeds = ip_adapter_image_embeds elif ip_adapter_image is not None: single_image_embeds = self.encode_image(ip_adapter_image, device) if do_classifier_free_guidance: single_negative_image_embeds = torch.zeros_like(single_image_embeds) else: raise ValueError("Neither `ip_adapter_image_embeds` or `ip_adapter_image_embeds` were provided.") image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0) if do_classifier_free_guid
1
function_complex
huggingface/diffusers:examples/community/pipeline_stable_diffusion_3_instruct_pix2pix.py:StableDiffusion3InstructPix2PixPipeline.prepare_ip_adapter_image_embeds
_weights, block_size ): """Test that grouped and per-channel have different scale shapes.""" input_dim, output_dim = 100, 256 layer = layers.ReversibleEmbedding( input_dim=input_dim, output_dim=output_dim, tie_weights=tie_weights ) layer.build() config = Int4QuantizationConfig(block_size=block_size) layer.quantize("int4", config=config) if block_size is None or block_size == -1: # Per-channel expected_scale_shape = (input_dim,) expected_reverse_scale_shape = (input_dim,)
1
test
keras-team/keras:keras/src/layers/core/reversible_embedding_test.py:ReversibleEmbeddingTest.test_int4_grouped_vs_perchannel_scale_shapes
maintain the aspect ratio. interpolation: `tvF.InterpolationMode` filter to use when resizing the image e.g. `tvF.InterpolationMode.BICUBIC`. Returns: `torch.Tensor`: The resized image. """ if not size.longest_edge: raise ValueError(f"The `size` dictionary must contain the key `longest_edge`. Got {size.keys()}") input_size = image.shape[-2:] output_height, output_width = self._get_preprocess_shape(input_size, size.longest_edge) return super().resize(
0
function_simple
huggingface/transformers:src/transformers/models/sam/image_processing_sam_fast.py:SamImageProcessorFast.resize
] ): """Decorator to register a function as a before_tool_call hook. Example: Simple usage:: @before_tool_call def log_all_tools(context): print(f"Tool: {context.tool_name}") return None With tool filter:: @before_tool_call(tools=["delete_file", "execute_code"]) def approve_dangerous(context): response = context.request_human_input(prompt="Approve?") return None if response == "yes" else False
0
function_simple
crewAIInc/crewAI:lib/crewai/src/crewai/hooks/decorators.py:before_tool_call
, conda=conda_name) runtime_env = RuntimeEnv(pip=pip_packages) runtime_env["conda"] = conda_name with pytest.raises(ValueError): runtime_env.serialize() # Test the interface related to container container_init = { "image": "anyscale/ray-ml:nightly-py38-cpu", "run_options": ["--cap-drop SYS_ADMIN", "--log-level=debug"], } update_container = {"image": "test_modify"} runtime_env = RuntimeEnv(container=container_init) runtime_env_dict = runtime_env.to_dict() assert runtime_env.has_py_container() assert runtime_env.py_container_image() == container_init["image"] assert runtime_
0
test
ray-project/ray:python/ray/tests/unit/test_runtime_env.py:test_runtime_env_interface
class MyModel(PreTrainedModel): def __init__(self, config): super().__init__(config) self.layer = None @auto_docstring def forward(self, input_ids, scale_factor: float = 1.0): ''' Example: ``
0
test
huggingface/transformers:tests/utils/test_auto_docstring.py:TestCheckDocstrings.test_multi_item_file_processing
size (C = W+L+R), max_span_plus_1 (F_span = L+R+1). Returns: Tensor of shape [B, N, U, W, C]. """ # term_bd_before_shift shape: [B, N, U, W, F_span] # Target shape after shift: [B, N, U, W, C] # Padding amount for the last dimension (F_span) to become (C + 1) # C = key_context_size # F_span = max_span_plus_1 pad_amount_last_dim = (key_context_size + 1) - max_span_plus_1 # PyTorch F.pad expects (pad_left, pad_right, pad_top, pad
0
function_simple
huggingface/transformers:src/transformers/models/gemma3n/modular_gemma3n.py:Gemma3nAudioRelativePositionEmbedding._relative_shift
): The scheduler to get timesteps from. num_inference_steps (`int`): The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps` must be `None`. device (`str` or `torch.device`, *optional*): The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. timesteps (`list[int]`, *optional*): Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed, `num_inference_steps` and `sigmas` must be `None`.
1
function_complex
huggingface/diffusers:src/diffusers/pipelines/sana/pipeline_sana_sprint_img2img.py:retrieve_timesteps
name=None, type_="STRING", value="cfo@company.com" ), bigquery.ArrayQueryParameter( name="node_ids", array_type="STRING", values=["node1", "node2"] ), bigquery.ScalarQueryParameter("top_k", "INTEGER", 5), bigquery.ScalarQueryParameter("distance_type", "STRING", "EUCLIDEAN"), ] assert isinstance(job_config, bigquery.QueryJobConfig) assert job_config.query_parameters == expected_query_params # And the actual SQL query should match the expected SQL query expected_query = f""" SELECT base.node_id AS node_id,
1
test
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-bigquery/tests/test_vector_search.py:test_query_vector_store_with_filters_generates_correct_sql_and_params
Line one\nLine two\nLine three\nLine four\nLine five" text = TextFile(source=content.encode(), filename="lines.txt") result = list( chunk_text(text, max_chars=25, overlap_chars=0, split_on_newlines=True) ) # Should split at newline boundaries for chunk in result: chunk_text_content = chunk.read().decode() # Chunks should end at newlines (except possibly the last) if chunk != result[-1]: assert ( chunk_text_content.endswith("\n
0
test
crewAIInc/crewAI:lib/crewai-files/tests/processing/test_transformers.py:TestChunkText.test_chunk_prefers_newline_boundaries
self): docs = render_chart( values={ "airflowVersion": "3.0.0", "ingress": { "apiServer": { "enabled": True, "tls": {"enabled": True, "secretName": "oldsecret"}, "hosts": [ {"name": "*.a-host", "tls": {"enabled": True, "secretName": "newsecret
1
test
apache/airflow:helm-tests/tests/helm_tests/apiserver/test_ingress_apiserver.py:TestIngressAPIServer.test_should_ingress_hosts_objs_have_priority_over_host
batch_tokens num_pages = self.cache.num_blocks * self.cache.block_size pin_memory = self.device.type == "cpu" # Small inputs are allocated as slices in a larget tensor aligned to 128 bytes (32 * 4b). This reduces the # reduces fragmentation, so it lowers the number of D2H transfers and speeds up transfers. bulk_size = aligned_divide(max_batch_tokens + 1, 1, 32) self._bulk_input_tensor = torch.empty( (7, bulk_size), dtype=torch.int32, device=self.device, pin_memory=pin_memory ) self.input_ids = self._bulk_input_tensor[0, :max_batch_tokens]
0
function_complex
huggingface/transformers:src/transformers/generation/continuous_batching/input_outputs.py:ContinuousBatchingIOs._setup_static_tensors
Update the podcast language with the specified language code. This ensures the language is properly tracked for generating content and audio. Args: agent: The agent instance language_code: The language code (e.g., 'en', 'es', 'fr', etc..) Returns: Confirmation message """ from services.internal_session_service import SessionService session_id = agent.session_id session = SessionService.get_session(session_id) session_state = session["state"] language_name = "English" for lang in session_state.get("available_languages", []): if lang.get("code") == language_code: language_name = lang.get("name") break session_state["selected_
0
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/session_state_manager.py:update_language
-Configure MCP servers disabled, skipping starter project MCP configuration") return await logger.adebug( f"Auto-configure settings: add_projects_to_mcp_servers=" f"{settings_service.settings.add_projects_to_mcp_servers}, " f"create_starter_projects={settings_service.settings.create_starter_projects}, " f"update_starter_projects={settings_service.settings.update_starter_projects}" ) try: # Get all users in the system users = (await session.exec(select(User))).all() await logger.adebug(f"Found {len(users)} users in the system") if not users: await logger.adebug("
1
function_complex
langflow-ai/langflow:src/backend/base/langflow/api/utils/mcp/config_utils.py:auto_configure_starter_projects_mcp
Corresponds to the ``--preview`` CLI option. :param fast: True to enable fast mode. Corresponds to the ``--fast`` CLI option. :param python_variant: The Python variant to use. Corresponds to the ``--pyi`` CLI option if this is "pyi". Otherwise, corresponds to the ``--target-version`` CLI option. :param diff: True to enable diff mode. Corresponds to the ``--diff`` CLI option. :param headers: A dictionary of additional custom headers to send with the request. """ self.url = url self.headers = _DEFAULT_HEADERS.copy()
1
function_complex
psf/black:src/blackd/client.py:BlackDClient.__init__
msg) if term.lower() != self.lookup_str: self.lookup_str = term.lower() self.lookup_index = 0 else: self.lookup_index += 1 lookups = [p for p in self._paragraphs if self.lookup_str in p.lower()] if len(lookups) == 0: return "No Results" if self.lookup_index >= len(lookups): return "No More Results" result_prefix = f"(Result {self.lookup_index + 1}/{len(lookups)})" return f"{result_prefix} {lookups[self
1
function_simple
langchain-ai/langchain:libs/langchain/langchain_classic/agents/react/base.py:DocstoreExplorer.lookup
Dict[str, Any]) -> Dict[str, Any]: """Transform request for AI Gateway format.""" # Extract headers and body headers = kwargs.get("headers", {}) json_data = kwargs.get("json", {}) # Get endpoint from URL endpoint = self.provider_config.transform_endpoint(url) # Pass the original request body directly to AI Gateway # AI Gateway handles provider-specific format differences internally return { "provider": self.provider_config.name, "endpoint": endpoint, "headers": headers, "query": json_data,
1
function_simple
run-llama/llama_index:llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/llama_index/llms/cloudflare_ai_gateway/base.py:AIGatewayClientWrapper._transform_request
_session) # Verify we're on the second page second_url = await browser_session.get_current_page_url() print(f'Second page URL: {second_url}') assert f'{base_url}/page2' in second_url # Execute go back action result = await tools.go_back(browser_session=browser_session) # Verify the result assert isinstance(result, ActionResult) assert result.extracted_content is not None assert 'Navigated back' in result.extracted_content # Add another delay to allow the navigation to complete await asyncio.sleep(1) # Verify we're back on a different page than before final_url = await browser_session.get_current_page_url() print(f'Final page URL after going back: {final_url}') # Try to verify we're back on the first page, but don't fail the test if not assert f'{
0
test
browser-use/browser-use:tests/ci/test_tools.py:TestToolsIntegration.test_go_back_action
input_tensor = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype) # Create a random permutation map dst2src_map = torch.randperm(num_tokens, device="cuda", dtype=torch.int32) # Test shuffle_rows output = shuffle_rows(input_tensor, dst2src_map) # Check output shape and properties assert output.shape == (num_tokens, hidden_size) assert output.dtype == dtype assert output.device == input_tensor.device # Verify that each output row matches the corresponding input row for i in range(num_tokens): src_idx = dst2src_map[i].item() torch.testing.assert_close( output[i], input_tensor[src
1
test
vllm-project/vllm:tests/kernels/test_shuffle_rows.py:test_shuffle_rows_random_permutation
timeout=30 ) # Check that model parameters are stored on the LLM instance assert llm.temperature == 0.7 assert llm.max_tokens == 1000 assert llm.top_p == 0.5 # Check that client parameters are properly configured assert llm.client.max_retries == 3 assert llm.client.timeout == 30 # Test that parameters are properly used in API calls with patch.object(llm.client.chat.completions, 'create') as mock_create: mock_create.return_value = MagicMock( choices=[MagicMock(message=MagicMock(content="test response", tool_calls=None))], usage=MagicMock(prompt_tokens=10, completion_tokens=20, total_tokens=30)
0
test
crewAIInc/crewAI:lib/crewai/tests/llms/openai/test_openai.py:test_openai_client_setup_with_extra_arguments
= layers.Dense(32, activation="relu", name="shared_layer")(inputs) output1 = layers.Dense(1, activation="sigmoid", name="output_1")(x) output2 = layers.Dense(2, activation="softmax", name="output_2")(x) model = models.Model( inputs=inputs, outputs=[output1, output2], name="multi_output_model" ) temp_filepath = os.path.join( self.get_temp_dir(), "multi_output_model.tflite" ) # Export the model model.export(temp_filepath, format="litert") self.assertTrue(os.path.exists
1
test
keras-team/keras:keras/src/export/litert_test.py:ExportLitertTest.test_signature_def_with_multi_output_model
with_models_ollama): """Test that each model maintains its own dimension.""" embeddings_list = [embeddings_with_models_openai, embeddings_with_models_ollama] for emb_wrapper in embeddings_list: if isinstance(emb_wrapper, EmbeddingsWithModels): for model_instance in emb_wrapper.available_models.values(): # Each model should have consistent dimensions vec1 = model_instance.embed_query("test1") vec2 = model_instance.embed_query("test2") assert
1
test
langflow-ai/langflow:src/backend/tests/unit/components/vectorstores/test_opensearch_multimodal.py:TestOpenSearchMultimodalIntegration.test_embedding_dimension_consistency
. Args: a2a_task: A2A Task object default: Default message if no error found Returns: Error message string """ if a2a_task.status and a2a_task.status.message: msg = a2a_task.status.message if msg: for part in msg.parts: if part.root.kind == "text": return str(part.root.text) return str(msg) if a2a_task.history: for history_msg in reversed(a2a_task.history): for part in
0
function_complex
crewAIInc/crewAI:lib/crewai/src/crewai/a2a/task_helpers.py:extract_error_message
def _attempt_json_repair(self, text: str) -> str | None: """使用可选的json_repair库进一步修复复杂语法错误""" if not _json_repair_fn: return None try: fixed = _json_repair_fn(text) except Exception as exc: # pragma: no cover - 库级故障 logger.warning(f"json_repair 修复章节JSON失败: {exc}") return None if fixed == text: return None logger.warning("�
1
function_simple
666ghj/BettaFish:ReportEngine/nodes/chapter_generation_node.py:ChapterGenerationNode._attempt_json_repair
examples, ddp_world_size): conversation = task[idx] tokens = tokenizer.render_for_completion(conversation) prefix_length = len(tokens) # Generate k samples using batched generation inside the Engine assert num_samples <= args.device_batch_size # usually this is true. we can add a loop if not... generated_token_sequences, masks = engine.generate_batch( tokens, num_samples=num_samples, max_tokens=max_completion_tokens, temperature=temperature, top_k=top_k )
0
function_simple
karpathy/nanochat:scripts/chat_rl.py:run_gsm8k_eval
if collection not in self.collections: logger.warning(f"Collection '{collection}' not found in ComponentsManager") return if component_id not in self.collections[collection]: logger.warning(f"Component '{component_id}' not found in collection '{collection}'") return # remove from the collection self.collections[collection].remove(component_id) # check if this component is in any other collection comp_colls = [coll for coll, comps in self.collections.items() if component_id in comps] if not comp_colls: # only if no other collection contains this component, remove it logger.warning(f
1
function_simple
huggingface/diffusers:src/diffusers/modular_pipelines/components_manager.py:ComponentsManager.remove_from_collection
def is_sleeping( self, model: str = Query(..., description="The model ID to check") ) -> IsSleepingResponse: """Check if the engine is sleeping for the specified model. This checks the sleep status across all replicas. Returns True if ANY replica is sleeping (uses logical OR across replicas). Args: model: The model ID to check. Returns: IsSleepingResponse with is_sleeping boolean. """ results = await self._broadcast_to_replicas(model, "is_sleeping") is_sleeping_result = any(results) if results else False return IsSleepingResponse(is_sleeping=is_sleeping_
0
function_simple
ray-project/ray:python/ray/llm/_internal/serve/core/ingress/mixins/sleepable.py:SleepableIngressMixin.is_sleeping
user="test_user", password="test_pass", host="localhost", port=5432, diskann=False, hnsw=False, minconn=1, maxconn=4, sslmode="require", connection_string=connection_string ) # Verify ConnectionPool was called with the connection string including sslmode expected_conn_string = f"{connection_string} sslmode=require" mock_connection_pool.assert_called_
1
test
mem0ai/mem0:tests/vector_stores/test_pgvector.py:TestPGVector.test_connection_string_with_sslmode_psycopg3
s3_path = "flow_123/data.csv" component.set_attributes( { "model": model_value, "path": s3_path, "agent_type": "openai-tools", "input_value": "test", } ) csv_content = b"col1,col2\n1,2\n3,4" # Mock S3 storage and read operations - real temp file creation and cleanup with ( patch("lfx.components.langchain_utilities.
1
test
langflow-ai/langflow:src/lfx/tests/unit/components/langchain_utilities/test_csv_agent.py:TestCSVAgentComponent.test_get_local_path_with_s3_file
: Tuple of (pos_x, pos_y) positional embeddings """ x_embed = x * self.scale y_embed = y * self.scale dim_t = torch.arange(self.num_pos_feats, dtype=torch.int64, device=x.device).to(x.dtype) dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) pos_x = x_embed[:, None] / dim_t pos_y = y_embed[:, None] / dim_t pos_x = torch.stack((pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2).flatten(1)
0
function_simple
huggingface/transformers:src/transformers/models/sam3/modeling_sam3.py:Sam3SinePositionEmbedding.encode_1d_positions
"""Test that when variable not found in db and env var doesn't exist. The field is set to None. """ # Make sure env var doesn't exist if "NONEXISTENT_KEY" in os.environ: del os.environ["NONEXISTENT_KEY"] # Create mock custom component custom_component = MagicMock() # Change this error message to avoid triggering re-raise custom_component.get_variable = AsyncMock(side_effect=ValueError("Database connection failed")) # Set up params params = {"api_key": "NONEXISTENT_KEY"} load_from_db_fields = ["api_key"] # Call the function with fallback enabled with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter
1
test
langflow-ai/langflow:src/backend/tests/unit/interface/initialize/test_loading.py:test_update_params_sets_none_when_no_env_var_and_fallback_enabled
s continue normalized_node = {} for media_type, items in node_outputs.items(): if media_type == 'animated' or not isinstance(items, list): normalized_node[media_type] = items continue normalized_items = [] for item in items: if item is None: continue norm = normalize_output_item(item) normalized_items.append(norm if norm is not None else item)
1
function_complex
Comfy-Org/ComfyUI:comfy_execution/jobs.py:normalize_outputs
path (str or Bip32Path object): Path Returns: Bip32Base object: Bip32Base object Raises: Bip32KeyError: If the index results in an invalid key Bip32PathError: If the path is not valid ValueError: If the path is a master path and the key is a child key """ path = self.__GetPath(path) if self.Depth() > 0 and path.IsAbsolute(): raise ValueError("Absolute paths can only be derived from a master key, not child ones") bip32_obj = self # Derive children keys for
1
function_simple
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/base/bip32_base.py:Bip32Base.DerivePath
This provider blocks execution and waits for console input from the user. It serves two purposes: - **Feedback** (``request_feedback``): Used by ``@human_feedback`` to display method output and collect review feedback. - **Input** (``request_input``): Used by ``Flow.ask()`` to prompt the user with a question and collect a response. This is the default provider used when no custom provider is specified in the ``@human_feedback`` decorator or on the Flow's ``input_provider``. Example (feedback): ```python from crewai.flow.async_feedback import ConsoleProvider @human_feedback( message="Review this:", provider=ConsoleProvider(), ) def my_method(self): return "Content to review" ``` Example (input): ```python from crewai.flow import Flow
0
documentation
crewAIInc/crewAI:lib/crewai/src/crewai/flow/async_feedback/providers.py:ConsoleProvider:class_doc
points.openai.responses.context.logger.error") as mock_log: context = HarmonyContext(messages=[], available_tools=["browser"]) # First turn mock_output1 = create_mock_request_output( prompt_token_ids=list(range(10)), # 10 tokens output_token_ids=[1, 2, 3, 4, 5], # 5 tokens ) context.append_output(mock_output1) # Second turn with fewer new tokens than previous output # This could happen in edge cases with aggressive caching mock_output2 = create_mock_request_output( prompt_token_ids=list(range(12)), # 12 tokens (only 2
1
test
vllm-project/vllm:tests/entrypoints/test_context.py:test_negative_tool_tokens_edge_case
, mock_get_connection, mock_connection_minimal): mock_get_connection.return_value = mock_connection_minimal mock_fs_instance = MagicMock() mock_msgdrivefs.return_value = mock_fs_instance storage_options = {"drive_id": "storage_drive_id", "scope": "custom.scope"} result = get_fs("msgraph_minimal", storage_options=storage_options) expected_oauth2_params = { "client_id": "test_client_id", "client_secret": "test_client_secret", "tenant_id": "test_tenant_id", "scope": "custom.scope",
1
test
apache/airflow:providers/microsoft/azure/tests/unit/microsoft/azure/fs/test_msgraph.py:TestMSGraphFS.test_get_fs_with_storage_options
that empty feedback without default uses first outcome.""" class FallbackFlow(Flow): @start() @human_feedback( message="Review:", emit=["first", "second", "third"], llm="gpt-4o-mini", # No default_outcome specified ) def review(self): return "content" flow = FallbackFlow() with patch.object(flow, "_request_human_feedback", return_value=""):
0
test
crewAIInc/crewAI:lib/crewai/tests/test_human_feedback_integration.py:TestEdgeCases.test_empty_feedback_first_outcome_fallback
input_path, ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, ) expected_output = os.path.join( os.path.dirname(output_path), os.path.splitext(os.path.basename(input_path))[0] + ".pdf", ) if expected_output != output_path:
1
function_simple
docling-project/docling:docling/backend/docx/drawingml/utils.py:get_docx_to_pdf_converter
ryable if attempt < self.max_retries - 1: delay = min(self.retry_base_delay * (2**attempt), self.retry_max_delay) jitter = random.uniform(0, delay * 0.1) total_delay = delay + jitter error_type = 'timeout' if isinstance(e, httpx.TimeoutException) else 'connection error' logger.warning( f'⚠️ Got {error_type}, retrying in {total_delay:.1f}s... (attempt {attempt + 1}/{self.max_retries})' ) await asyncio.sleep(total_delay) continue # Exhausted retries if isinstance(e, httpx.TimeoutException): raise ValueError(f'Request timed out
0
function_complex
browser-use/browser-use:browser_use/llm/browser_use/chat.py:ChatBrowserUse.ainvoke
f'backendNodeId={node.original_node.backend_node_id} {attr_str}' ) else: logger.debug( f'🔍 SKIPPING interactive <{node.original_node.tag_name}> (no snapshot_node, not in shadow DOM): ' f'backendNodeId={node.original_node.backend_node_id} {attr_str}' ) # EXCEPTION: File inputs are often hidden with opacity:0 but are still functional # Bootstrap and other frameworks use this pattern with custom-styled file pickers is_file_input = ( node.original_node.tag_name and node.original_node.tag_name.lower() == 'input' and node.original_node.attributes and node.original_node.attributes.get('
0
function_complex
browser-use/browser-use:browser_use/dom/serializer/serializer.py:DOMTreeSerializer._assign_interactive_indices_and_mark_new_nodes
ize_vectorx_index_import_error(self): import builtins original_import = builtins.__import__ def mock_import(name, *args, **kwargs): if name == "vecx.vectorx": raise ImportError("No module named vecx.vectorx") return original_import(name, *args, **kwargs) builtins.__import__ = mock_import with pytest.raises(ImportError): VectorXVectorStore._initialize_vectorx_index( api_token="token", encryption_key="key", index_name="idx", dimension=2 )
1
test
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-vectorx/tests/test_vector_stores_vectorx.py:TestVectorXAdvanced.test_initialize_vectorx_index_import_error
class__.__name__ op_name = _format_op_name(op) tb_str = "".join(traceback.format_exception(type(e), e, e.__traceback__)) if isinstance(extras, tuple) and len(extras) == 2: length, target_keys = extras descriptor = f"{op_name} " if op_name else "" loading_info.conversion_errors[first_target_key] = ( f"{tb_str}{e}\nError: {descriptor}on tensors destined for {target_keys}. Ckpt contains: {length}" ) elif isinstance(extras, str):
0
function_complex
huggingface/transformers:src/transformers/core_model_loading.py:log_conversion_errors
tree.add_tenants(["tenant_1"], 0) tree.insert("hello", "tenant_1", 1) hello_node = tree.root.edge_label_to_child["h"] assert hello_node.tenant_to_last_access_time == {"tenant_1": 1} assert tree.tenant_to_char_count == {"tenant_1": 5} assert tree.root.edge_label_to_child == {"h": hello_node} removed_chars = tree._remove_tenant_single_node("tenant_1", hello_node) assert removed_chars == 5 assert hello_node.tenant_to_last_access_time == {} assert tree.tenant_to_char_count == {"tenant_1": 0}
0
test
ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py:TestPrefixTreeRemove.test_remove_single_leaf_node_pruned
pad_dims = (0, pad_width) logits = nn.functional.pad(logits, pad_dims, value=-float("inf")) padded_logits.append(logits) # Stack along new dim=0 (categorical dimension). # Shape: (num_components, B, T, max_K) or (num_components, B, max_K) stacked = torch.stack(padded_logits, dim=0) # Move categorical dim (0) to last if needed, and take argmax. if is_recurrent: # Current shape is (num_components, B, T, K) and we want to have # (
0
function_simple
ray-project/ray:rllib/core/distribution/torch/torch_distribution.py:TorchMultiCategorical.to_deterministic
, match="`use_gpu` is False but `GPU` was found in"): ScalingConfig(num_workers=2, use_gpu=False, resources_per_worker={"GPU": 1}) with pytest.raises(ValueError, match="Cannot specify both"): ScalingConfig(num_workers=2, use_gpu=True, use_tpu=True) with pytest.raises( ValueError, match=( "If `label_selector` is a list, it must be the same length as " "`max_workers`" ), ): ScalingConfig(num_workers=2, label_selector=[{"subcluster": "my_subcluster"}]) with pytest.raises(
0
test
ray-project/ray:python/ray/train/v2/tests/test_config.py:test_scaling_config_validation
ises_error_when_default_invalid( self, mocker: MockerFixture, valid_choices: set[str], ) -> None: """Test that function raises ValueError when default value is not in choices.""" mocker.patch.dict("os.environ", {}, clear=True) with pytest.raises(ValueError) as exc_info: get_choice_from_env("TEST_ENV", valid_choices, default="invalid_default") error_msg = str(exc_info.value) assert ( "Environment variable 'TEST_ENV' has invalid value 'invalid_default'" in error_msg
1
test
paperless-ngx/paperless-ngx:src/paperless/tests/settings/test_environment_parsers.py:TestGetEnvChoice.test_raises_error_when_default_invalid
37813758850098, -9.995306968688965, -10.06312370300293, -10.039563179016113, -10.00948715209961, -10.04725170135498, -10.08010196685791, -10.043283462524414, -10.06112289428711, -9.989591598510742, -10.034473419189453, -9.958343505859375, -9.956878662109375, -10.006301879882812, -10.032047271728516, -9.969188690185547, -10.00571060180664, -10.043065071105957, -9.983331680297852, -9.988570213317871, -9.9
0
test
huggingface/transformers:tests/models/moonshine_streaming/test_modeling_moonshine_streaming.py:MoonshineStreamingModelIntegrationTests.test_medium_logits_single
WorkflowValidationError: If flow validation fails """ try: return await asyncio.wait_for( execute_sync_workflow( workflow_request=workflow_request, flow=flow, job_id=job_id, api_key_user=api_key_user, background_tasks=background_tasks, http_request=http_request, ), timeout=EXECUTION_TIMEOUT, )
1
function_simple
langflow-ai/langflow:src/backend/base/langflow/api/v2/workflow.py:execute_sync_workflow_with_timeout
=True) # Mock context to capture stream events mock_context = AsyncMock(spec=Context) mock_context.is_running = True # Required for event writing stream_events = [] def capture_event(event): stream_events.append(event) mock_context.write_event_to_stream.side_effect = capture_event # Call the streaming method await agent._get_streaming_response( mock_context, [ChatMessage(role="user", content="test")] ) # Verify AgentStream events contain thinking_delta agent_streams = [event for event in stream_events if isinstance(event, AgentStream)] assert len(agent_streams) == 3 # 3 deltas from mock # Check that thinking deltas are passed through correctly assert agent_streams[0].thinking_delta ==
1
test
run-llama/llama_index:llama-index-core/tests/agent/workflow/test_thinking_delta.py:test_react_agent_comprehensive_thinking_streaming
defaults["python"] in cfg["python"], ( f"{image_type}: default python '{defaults['python']}' " f"not in supported {cfg['python']}" ) assert defaults["gpu_platform"] in cfg["platforms"], ( f"{image_type}: default gpu_platform '{defaults['gpu_platform']}' " f"not in supported {cfg['platforms']}" ) assert defaults["architecture"] in cfg["architectures"], ( f"{image_type}: default architecture '{defaults['architecture']}' " f"not in supported {cfg['architectures']}"
0
test
ray-project/ray:ci/ray_ci/test_supported_images.py:TestRayImagesSchema.test_defaults_in_supported
_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.eval_on_selector_all.return_value = [] tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.extract_hyperlinks(thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.eval_on_selector_all.assert_called_once() mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "No hyperlinks found
1
test
run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_browser.py:TestAgentCoreBrowserToolSpec.test_extract_hyperlinks_no_links
multi-mask outputs (based on output token 1~3) the mask with the highest predicted IoU score. This is intended to ensure a valid mask for both clicking and tracking. """ # The best mask from multimask output tokens (1~3) multimask_logits = all_mask_logits[:, :, 1:, :, :] multimask_iou_scores = all_iou_scores[:, :, 1:] best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1) # [B, P] best_scores_inds_expanded = best_scores_inds.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1) best_scores_inds_expanded = best_sc
0
function_simple
huggingface/transformers:src/transformers/models/sam2/modular_sam2.py:Sam2MaskDecoder._dynamic_multimask_via_stability
child): """Extract structured reference info from PubMed XML""" def safe_find(path): node = child for p in path.split("/"): if node is None: return None node = node.find(p) return node.text if node is not None and node.text else None title = safe_find("MedlineCitation/Article/ArticleTitle") or "No title" abstract = safe_find("MedlineCitation/Article/Abstract/AbstractText") or "No abstract available" journal = safe_find("MedlineCitation/Article/Journal/Title") or "Unknown Journal"
1
function_complex
infiniflow/ragflow:agent/tools/pubmed.py:PubMed._format_pubmed_content
_multiple_errors_do_not_crash_with_fail_on_rank_error_false(self): """Test that multiple consecutive errors don't crash when fail_on_rank_error=False.""" rank_manager = DeploymentRankManager(fail_on_rank_error=False) # Multiple errors in a row should all return safe defaults result1 = rank_manager.get_replica_rank("nonexistent1") result2 = rank_manager.get_replica_rank("nonexistent2") result3 = rank_manager.release_rank("nonexistent3") assert result1 is not None assert result2 is not None assert result3 is None # And normal operations should still work after errors rank = rank_manager.assign_rank("
0
test
ray-project/ray:python/ray/serve/tests/unit/test_deployment_rank_manager.py:TestDeploymentRankManagerErrorHandling.test_multiple_errors_do_not_crash_with_fail_on_rank_error_false
ify embeddings endpoint works with single and batch inputs.""" # Single input emb_resp = sglang_embedding_client.embeddings.create( model=RAY_MODEL_ID, input="Hello world", ) assert emb_resp.data assert len(emb_resp.data) == 1 assert emb_resp.data[0].embedding assert len(emb_resp.data[0].embedding) > 0 assert emb_resp.usage.prompt_tokens > 0 # Batch input emb_batch_resp = sglang_embedding_client.embeddings.create( model=RAY_MODEL_ID, input=["Hello world", "How are you"], ) assert len(emb_batch_resp.data) == 2 assert emb_batch
0
test
ray-project/ray:release/llm_tests/serve/test_llm_serve_sglang.py:test_sglang_embeddings
"""Test local file processing with captured_console initialization""" with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False) as f: f.write("<html><body><h1>Local File Test</h1></body></html>") temp_file = f.name try: async with AsyncWebCrawler() as crawler: result = await crawler.arun(f"file://{temp_file}") assert result.success assert "Local File Test" in result.markdown finally: os.unlink
1
test
unclecode/crawl4ai:tests/releases/test_release_0.7.0.py:TestCrawl4AIv070.test_local_file_processing
enable_remote_services: bool, artifacts_path: Optional[Union[Path, str]], options: CodeFormulaVlmOptions, accelerator_options: AcceleratorOptions, ): """Initialize the code/formula extraction stage. Args: enabled: Whether this stage is enabled artifacts_path: Path to model artifacts (optional) options: Configuration options including model spec and runtime options accelerator_options: Hardware acceleration options """ self.enabled = enabled self.options = options self.engine: Optional[BaseVlmEngine] = None if self.enabled
1
function_simple
docling-project/docling:docling/models/stages/code_formula/code_formula_vlm_model.py:CodeFormulaVlmModel.__init__
"""Poll cache for cancellation flag.""" while True: if await cache.get(f"cancel:{task_id}"): return True await asyncio.sleep(0.1) async def watch_for_cancel() -> bool: """Watch for cancellation events via pub/sub or polling.""" if isinstance(cache, SimpleMemoryCache): return await poll_for_cancel() try: client = cache.client pubsub = client.pubsub
0
function_complex
crewAIInc/crewAI:lib/crewai/src/crewai/a2a/utils/task.py:wrapper
large_node_spec: 1, # 1 existing large node (6 CPUs) small_node_spec: 0, # 0 existing small nodes } autoscaler = DefaultClusterAutoscalerV2( resource_manager=MagicMock(), resource_limits=resource_limits, execution_id="test_execution_id", cluster_scaling_up_delta=2, resource_utilization_calculator=StubUtilizationGauge(utilization), cluster_scaling_up_util_threshold=scale_up_threshold, min_gap_between_autoscaling_
0
test
ray-project/ray:python/ray/data/tests/test_default_cluster_autoscaler_v2.py:TestClusterAutoscaling.test_try_scale_up_existing_nodes_prioritized_over_delta
scale_eps: bool, ) -> None: """Functional API that performs Muon algorithm computation.""" _single_tensor_muon( params, grads, momentum_bufs, lr=lr, weight_decay=weight_decay, momentum=momentum, nesterov=nesterov, ns_steps=ns_steps, ns_coefficients=ns_coefficients, eps=eps, safety_factor=safety_factor, adjust_lr_fn=adjust_lr_fn, conv_mode=conv_mode, normalize_spatial=normalize_sp
1
function_simple
huggingface/pytorch-image-models:timm/optim/muon.py:muon
pace should be skipped.""" content = dedent("""\ <?xml version="1.0" encoding="UTF-8"?> <html> <body> <div class='ocr_page' title='bbox 0 0 1000 500'> <p class='ocr_par'> <span class='ocr_line' title='bbox 100 100 900 150'> <span class='ocrx_word' title='bbox 100 100 200 150'> </span>
1
test
ocrmypdf/OCRmyPDF:tests/test_hocr_parser.py:TestHocrParserEdgeCases.test_whitespace_only_word
-> bool: """Async delete an uploaded file from Gemini. Args: file_id: The file name/ID to delete. Returns: True if deletion was successful, False otherwise. """ try: client = self._get_client() await client.aio.files.delete(name=file_id) logger.info(f"Deleted Gemini file: {file_id}") return True except Exception as e: logger.warning(f"Failed to delete Gemini file {file_id}: {e}") return False
0
function_simple
crewAIInc/crewAI:lib/crewai-files/src/crewai_files/uploaders/gemini.py:GeminiFileUploader.adelete
"name": "Jira", "id": "jira", "version": "1.0.0", "description": "Jira", "tags": ["issue-tracking", "jira"], }, "linear": { "name": "Linear", "id": "linear", "version":
0
test
github/spec-kit:tests/test_extensions.py:TestExtensionCatalog.test_search_by_tag
(`List[str]`, *optional*): The list of inputs accepted by the forward pass of the model (like `"token_type_ids"` or `"attention_mask"`). Default value is picked from the class attribute of the same name. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`): Whether or not the model should clean up the spaces that were added when splitting the input text during the tokenization process. kwargs (additional keyword arguments, *optional*): Not supported by `MistralCommonBackend.from_pretrained`. Will raise an error if
0
function_simple
huggingface/transformers:src/transformers/tokenization_mistral_common.py:MistralCommonBackend.from_pretrained
to_landmarks, batch_src_points=None, batch_dst_points=kwargs["batch_dst_points"]) warp_mock = mocker.patch(f"{MODULE_PREFIX}.ImageAugmentation._random_warp") warp_lm_mock = mocker.patch(f"{MODULE_PREFIX}.ImageAugmentation._random_warp_landmarks") get_instance(batch_size, size).warp(batch, to_landmarks, **kwargs) if to_landmarks
1
test
deepfakes/faceswap:tests/lib/training/augmentation_test.py:test_image_augmentation_warp
with mock.patch("airflow.providers.edge3.models.db.inspect", return_value=mock_inspector): # Mock the migration context mock_version_table = mock.MagicMock() mock_version_table.name = "alembic_version_edge3" mock_migration_ctx = mock.MagicMock() mock_migration_ctx._version = mock_version_table with mock.patch.object(manager, "_get_migration_ctx", return_value=mock_migration_ctx): # Mock the drop methods on the actual table objects with (
1
test
apache/airflow:providers/edge3/tests/unit/edge3/models/test_db.py:TestEdgeDBManager.test_drop_tables_only_drops_edge_tables
151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655] # fmt: skip self.assertListEqual(expected_input_ids, inputs.input_ids[0].tolist()[:17]) expected_pixel_slice = torch.tensor( [ [-0.0902, -0.0824, -0.0824], [-0.2627, -0.2627, -0.2627], [-0.0824, -0.0902, -0.0902], [-0.0118, -0.0510,
0
test
huggingface/transformers:tests/models/qwen3_vl_moe/test_modeling_qwen3_vl_moe.py:Qwen3VLMoeIntegrationTest.test_small_model_integration_test
ock() mock_cdp_client.send.Target.getTargets = AsyncMock(return_value={'targetInfos': []}) mock_cdp_client.send.Target.createTarget = AsyncMock(return_value={'targetId': 'test-target-id'}) with patch('browser_use.browser.session_manager.SessionManager') as mock_session_manager_class: mock_session_manager = MagicMock() mock_session_manager_class.return_value = mock_session_manager mock_session_manager.start_monitoring = AsyncMock() mock_session_manager.get_all_page_targets = MagicMock(return_value=[]) try: await session.connect() except Exception: pass # Verify CDPClient was called with None for additional_headers call_kwargs = mock_cdp_client_
0
test
browser-use/browser-use:tests/ci/browser/test_cdp_headers.py:test_cdp_client_no_headers_when_none
处理新的WebSocket连接请求,接收初始消息并建立持久连接。 参数: websocket: WebSocket连接对象 """ try: await websocket.accept() logger.info(f"WebSocket connection established: {websocket.client.host}:{websocket.client.port}") msg: UserInterfaceMsg = UserInterfaceMsg.
1
function_simple
binary-husky/gpt_academic:shared_utils/fastapi_stream_server.py:main
_ids: torch.Tensor | None = None, task_type_ids: torch.Tensor | None = None, position_ids: torch.Tensor | None = None, inputs_embeds: torch.Tensor | None = None, labels: torch.Tensor | None = None, next_sentence_label: torch.Tensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor] | ErnieForPreTrainingOutput: r""" task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Task type embedding is a special embedding to represent the characteristic of different tasks, such as
0
function_simple
huggingface/transformers:src/transformers/models/ernie/modular_ernie.py:ErnieForPreTraining.forward
async def test_find_validation_error_with_context(): """Test that find_validation_error searches __context__ chain.""" import pydantic from langflow.api.v1.mcp import find_validation_error # Create a pydantic ValidationError by catching it validation_error = None try: class TestModel(pydantic.BaseModel): required_field: str TestModel() except pydantic.ValidationError as e: validation_error = e assert validation_error is not None # Wrap it using __context__ instead of __cause__ nested_error = ValueError("Wrapper") nested_error.__context__ = validation_error found = find_validation_error(nested_error) assert found is validation_error
1
test
langflow-ai/langflow:src/backend/tests/unit/api/v1/test_mcp.py:test_find_validation_error_with_context
expected_css_url: str, expected_js_url: str, ) -> None: """Verify that asset URL overrides take precedence over default filenames.""" caller_dir = tmp_path / "caller" caller_file = caller_dir / "fakecaller.py" css_file = caller_dir / "style.css" js_file = caller_dir / "main.js" _mk_file(caller_file) _mk_file(css_file) _mk_file(js_file) d = BidiComponentDefinition( name="c", css=os.fspath(css_file), js=os.fspath(js_file), **overrides, ) assert d.css_url == expected_css_url
1
test
streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_registry.py:test_asset_url_overrides_and_defaults
word = OcrElement( ocr_class=OcrClass.WORD, text="Caption", bbox=BoundingBox(left=100, top=300, right=200, bottom=350), ) caption = OcrElement( ocr_class=OcrClass.CAPTION, bbox=BoundingBox(left=100, top=300, right=900, bottom=350), baseline=Baseline(slope=0.0, intercept=0), children=[word], ) paragraph = OcrElement( ocr_class=
1
test
ocrmypdf/OCRmyPDF:tests/test_pdf_renderer.py:TestFpdf2PdfRendererLineTypes.test_caption_line
= BrowserProfile(**profile_data) # Create browser session self.browser_session = BrowserSession(browser_profile=profile) await self.browser_session.start() # Track the session for management self._track_session(self.browser_session) # Create tools for direct actions self.tools = Tools() # Initialize LLM from config llm_config = get_default_llm(self.config) base_url = llm_config.get('base_url', None) kwargs = {} if base_url: kwargs['base_url'] = base_url if api_key := llm_config.get('api_key'): self.llm = ChatOpenAI( model=llm_config.get('model', 'gpt-o4-mini'), api_key=api_key, temperature=llm_config.get('temperature
0
function_simple
browser-use/browser-use:browser_use/mcp/server.py:BrowserUseServer._init_browser_session
PC handler for adding events to the event aggregator. Receives events from the request and adds them to the event buffer. """ if not self._event_processing_enabled: return events_event_aggregator_service_pb2.AddEventsReply() received_count = len(request.events_data.events) failed_count = 0 events_data = request.events_data if PUBLISH_EVENTS_TO_GCS: self._task_metadata_buffer.merge(events_data.task_events_metadata) for event in events_data.events: try: await self._event_buffer.add_event(event)
0
function_complex
ray-project/ray:python/ray/dashboard/modules/aggregator/aggregator_agent.py:AggregatorAgent.AddEvents
_auth_manager body = types.SimpleNamespace( name="editor", permissions=[ types.SimpleNamespace( action=types.SimpleNamespace(name="can_edit"), resource=types.SimpleNamespace(name="DAG"), ) ], ) out = FABAuthManagerRoles.patch_role(body=body, name="viewer") assert out.name == "editor" assert out.permissions assert out.permissions[0].action.name
1
test
apache/airflow:providers/fab/tests/unit/fab/auth_manager/api_fastapi/services/test_roles.py:TestRolesService.test_patch_role_rename_success
: if any branch consumes, the whole does elif ttype == sre_parse.BRANCH: _, branches = tval if any(subpattern_consumes(br) for br in branches): return True # grouped subpattern: recurse into its contents elif ttype == sre_parse.SUBPATTERN and subpattern_consumes(tval[3]): return True # No consumers, return False return False tokens = parsed.data if hasattr(parsed, "data") else parsed for ttype, tval in tokens:
1
function_complex
vllm-project/vllm:vllm/v1/structured_output/backend_outlines.py:_prefix_needs_context
" yield "data:" + json.dumps({"event": "node_finished", "data": {"component_id": "c1"}}) yield "data:" + json.dumps({"event": "other", "data": {}}) yield "data:" + json.dumps({"event": "message", "data": {"content": "hello"}}) monkeypatch.setattr(module, "agent_completion", _agent_stream) monkeypatch.setattr(module, "get_request_json", lambda: _AwaitableValue({"stream": True, "return_trace": True})) resp = _run(inspect.unwrap(module.agent_completions)("tenant-1", "agent-1")) chunks = _run(_collect_stream(resp.body)) assert resp.headers.get("Content-Type") == "text/event-stream; charset=utf-8" assert any
1
test
infiniflow/ragflow:test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py:test_agent_completions_stream_and_nonstream_unit
# To be filled by cloud handler browser_session_cdp_url='', # To be filled by cloud handler browser_state={ 'viewport': agent.browser_profile.viewport if agent.browser_profile else {'width': 1280, 'height': 720}, 'user_agent': agent.browser_profile.user_agent if agent.browser_profile else None, 'headless': agent.browser_profile.headless if agent.browser_profile else True, 'initial_url': None, # Will be updated during execution 'final_url': None, # Will be updated during execution 'total_pages_visited': 0, # Will be updated during execution 'session_duration_seconds': 0, # Will be updated during execution }, browser_session_data={ 'cookies': [], 'secrets': {}, # TODO: send secrets
0
function_simple
browser-use/browser-use:browser_use/agent/cloud_events.py:CreateAgentSessionEvent.from_agent
, Image.Image, str, ImageBlock], **kwargs: Any, ) -> List[NodeWithScore]: """ Query a multimodal table. Args: query (Union[ImageDocument, Image.Image, str, ImageBlock]): An ImageDocument or an ImageBlock, a PIL Image or a string representing an image URL. """ if isinstance(query, (ImageBlock, ImageDocument)): image_buffer = query.resolve_image() image_query = Image.open(image_buffer) elif isinstance(query, Image.Image): image_query = query elif isinstance(query, str): image_bytes = httpx.get(query).content image_query = Image.open(io.BytesIO(image_bytes)) else:
1
function_simple
run-llama/llama_index:llama-index-integrations/indices/llama-index-indices-managed-lancedb/llama_index/indices/managed/lancedb/utils.py:query_multimodal
start_regular_shared, dataset_format): """Test list.sort() sorts each list with custom options.""" data = [ {"items": [3, 1, 2]}, {"items": [None, 4, 2]}, ] ds = _create_dataset(data, dataset_format) method = col("items").list.sort(order="descending", null_placement="at_start") result = ds.with_column("sorted", method).to_pandas() expected = pd.DataFrame( { "items": [[3, 1, 2], [None, 4, 2]],
0
test
ray-project/ray:python/ray/data/tests/expressions/test_namespace_list.py:TestListNamespace.test_list_sort
self._create_file(temp_directory, "test.txt", "Sample") loader = DirectoryLoader() result = loader.load(SourceContent(temp_directory)) metadata = result.metadata expected_keys = { "format", "directory_path", "total_files", "processed_files", "errors", "file_details", "error_details", } assert expected_keys.issubset(metadata) assert all( k in metadata["file_details"][0]
0
test
crewAIInc/crewAI:lib/crewai-tools/tests/rag/test_directory_loader.py:TestDirectoryLoader.test_metadata_structure
use encoder_decoder for sequence classification. When set to False, only encoder is used. """ if is_encoder_decoder is not None: config.is_encoder_decoder = is_encoder_decoder super().__init__(config) self.num_labels = config.num_labels if config.is_encoder_decoder: self.model = T5GemmaModel(config) else: self.model = T5GemmaEncoderModel(config) hidden_size = config.encoder.hidden_size if config.is_encoder_decoder: hidden_size = config.decoder
0
function_simple
huggingface/transformers:src/transformers/models/t5gemma/modular_t5gemma.py:T5GemmaForSequenceClassification.__init__
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
51