prefix
stringlengths
32
355
suffix
stringlengths
35
312
prefix_tokens
int64
50
50
suffix_tokens
int64
50
50
sample_id
stringlengths
40
202
category
stringclasses
5 values
is_canary
bool
1 class
canary_values
stringclasses
1 value
token_offset
int64
0
1.42k
.get_document_hash("test_doc_id") assert doc_hash == "test_doc_hash" # Test updating hash ds.set_document_hash("test_doc_id", "test_doc
_hash_new") doc_hash = ds.get_document_hash("test_doc_id") assert doc_hash == "test_doc_hash_new" # Test getting non-existent doc_hash
50
50
run-llama/llama_index:llama-index-integrations/storage/docstore/llama-index-storage-docstore-gel/tests/test_gel.py:test_gel_docstore_hash
test
false
[]
74
none") def add_kernel(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: out = torch.empty_like(x) for tile in hl.tile(x.size()): out
[tile] = x[tile] + y[tile] return out # Create test tensors x = torch.randn(1024, device="cuda", dtype=torch.float32) y = torch.randn(1024,
50
50
vllm-project/vllm:tests/kernels/helion/test_helion_available.py:test_helion_kernel_compilation_smoke
test
false
[]
41
llm_bash_chain(config: dict, **kwargs: Any) -> Any: """Load LLM Bash chain from config dict.""" msg = ( "LLMBash Chain is not available through LangChain anymore.
" "The relevant code can be found in langchain_experimental, " "but it is not appropriate for production usage due to security " "concerns. Please refer to langchain-experimental repository for more details." )
50
50
langchain-ai/langchain:libs/langchain/langchain_classic/chains/loading.py:_load_llm_bash_chain
function_simple
false
[]
4
done then sleep and retry, - when command done then return the output. :param ssh_conn_id: connection id from airflow Connections from where all the required parameters can be fetched like username and password, though priority
is given to the params passed during init. :param shell_id: The shell id on the remote machine. :param command_id: The command id executed on the remote machine. :param output_encoding: the encoding used
50
50
apache/airflow:providers/microsoft/winrm/src/airflow/providers/microsoft/winrm/triggers/winrm.py:WinRMCommandOutputTrigger:class_doc
documentation
false
[]
65
connection information for Azure Database for PostgreSQL connections. :param host: Hostname of the Azure Database for PostgreSQL server. :type host: str | None :param dbname: Name of the database to connect to. :type dbname
: str :param port: Port number for the connection. :type port: int :param credentials: Credentials for authentication. :type credentials: BasicAuth | AsyncTokenCredential :param sslmode: SSL mode for the connection
50
50
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/aio/_connection.py:AsyncConnectionInfo:class_doc
documentation
false
[]
1
def tracing_service(self): """Lazily initialize tracing service only when accessed.""" if self._tracing_service is None: from lfx.services.deps import get_tracing_service try: self._tracing
_service = get_tracing_service() except Exception: # noqa: BLE001 # Broad exception is intentional - we want to gracefully handle any service initialization error self._tracing_service = None return self
50
50
langflow-ai/langflow:src/lfx/src/lfx/custom/custom_component/custom_component.py:CustomComponent.tracing_service
function_simple
false
[]
0
POSITORY, timeout=5) accessible = response.status_code == 200 if accessible: logger.debug_once("NVIDIA artifactory is accessible") else: logger.warning_once( "N
VIDIA artifactory returned failed status code: %d", response.status_code, ) return accessible except Exception as e: logger.warning_once("Failed to connect to NVIDIA artifactory: %
50
50
vllm-project/vllm:vllm/utils/flashinfer.py:has_nvidia_artifactory
function_simple
false
[]
129
["chapterList", "chapterPlan", "sections"], "totalWords": ["total_words", "wordCount", "totalWordCount"], } for missing_key in missing_keys: if missing_key in key_
aliases: for alias in key_aliases[missing_key]: if alias in data: logger.info( f"{context_name} 找到键'{missing_key}'的别名'{alias}'
50
50
666ghj/BettaFish:ReportEngine/utils/json_parser.py:RobustJSONParser._try_recover_missing_keys
function_complex
false
[]
217
hyphens, and underscores.""" team_name = _extract_team_name(args) # Check if team with this name already exists if session.scalar(select(Team).where(Team.name == team_name)):
raise SystemExit(f"Team with name '{team_name}' already exists") # Create new team (UUID will be auto-generated by the database) new_team = Team(name=team_name) try:
50
50
apache/airflow:airflow-core/src/airflow/cli/commands/team_command.py:team_create
function_simple
false
[]
35
into 5D tensor (batch_size, channels, 1, height, width) Components: pachifier (`QwenImagePachifier`) Inputs: height (`int`): The height in pixels of the generated
image. width (`int`): The width in pixels of the generated image. latents (`Tensor`): The latents to decode, can be generated in the denoise step. Outputs: latents (`Tensor
50
50
huggingface/diffusers:src/diffusers/modular_pipelines/qwenimage/decoders.py:QwenImageAfterDenoiseStep:class_doc
documentation
false
[]
22
combines a FusedMoEPrepareAndFinalize instance and a FusedMoEPermuteExpertsUnpermute to provide an interface that is compatible with the `fused_experts` function in fused_moe
.py. It takes care of managing any required scratch space. Note: Instances of this class should only be used for a single model layer due to any layer specific state that may be used by the component objects.
50
50
vllm-project/vllm:vllm/model_executor/layers/fused_moe/modular_kernel.py:FusedMoEModularKernel:class_doc
documentation
false
[]
2
{ 或 [ start_brace = text.find("{") start_bracket = text.find("[") if start_brace == -1 and start_bracket == -1: return text # 确定
起始位置 if start_brace == -1: start = start_bracket opener = "[" closer = "]" elif start_bracket == -1: start = start_brace opener = "{
50
50
666ghj/BettaFish:ReportEngine/utils/json_parser.py:RobustJSONParser._extract_first_json_structure
function_complex
false
[]
151
in new_urls: if url not in crawled_urls_phase2: crawled_urls_phase2.append(url) strategy2 = BFSDeepCrawlStrategy( max_depth=2
, max_pages=10, resume_state=saved_state, # Resume from checkpoint! on_state_change=track_resumed_crawl, ) config2 = CrawlerRunConfig(
50
50
unclecode/crawl4ai:docs/examples/deep_crawl_crash_recovery.py:example_crash_and_resume
function_complex
false
[]
630
feature encoding processes to capture long-range dependencies with precise positional information. This module includes the original implementation along with simplified and other variants. Papers / References: - Coordinate Attention: `Coordinate Attention for E
fficient Mobile Network Design` - https://arxiv.org/abs/2103.02907 - Efficient Local Attention: `Rethinking Local Perception in Lightweight Vision Transformer` - https://arxiv.org/
50
50
huggingface/pytorch-image-models:timm/layers/coord_attn.py:module_doc
documentation
false
[]
20
eduplication works via a two-level indirection: 1. `submodule_bytes` maps "{submod_name}_{shape}" -> SHA256 hash 2. `submodule_bytes_store` maps SHA256 hash -> actual bytes
When inserting, we compute the SHA256 hash of the bytes. If the hash already exists in `submodule_bytes_store`, we reuse the existing entry rather than storing duplicate bytes. This is common because submodules often
50
50
vllm-project/vllm:vllm/compilation/caching.py:StandaloneCompiledArtifacts:class_doc
documentation
false
[]
16
_enable_task(self, **kwargs) -> str: """Enable a task""" task_id = kwargs.get("task_id") if not task_id: return "错误: 缺少�
�务ID (task_id)" task = self.task_store.get_task(task_id) if not task: return f"错误: 任务 '{task_id}' 不存
50
50
zhayujie/chatgpt-on-wechat:agent/tools/scheduler/scheduler_tool.py:SchedulerTool._enable_task
function_simple
false
[]
1
return lock object or None.""" lock = RedisDistributedLock( lock_key, timeout=cls.LOCK_TIMEOUT_SECS, blocking_timeout=cls.LOCK_BLOCKING_TIMEOUT_SECS, ) for idx
in range(cls.LOCK_RETRY_ATTEMPTS): if lock.acquire(): return lock if idx < cls.LOCK_RETRY_ATTEMPTS - 1: time.sleep(cls.LOCK_RETRY_S
50
50
infiniflow/ragflow:api/apps/services/canvas_replica_service.py:CanvasReplicaService._acquire_lock_with_retry
function_simple
false
[]
29
): Context description for logging (e.g., "Vector store - Insert"). """ for success_message in response: if "success" not in success_message: logger.error(f"Query execution status is absent on
action: [{context}]") break if success_message["success"] is not True: logger.error(f"Abnormal response status on action: [{context}] with message: [{success_message['success']}] ")
50
50
mem0ai/mem0:mem0/vector_stores/neptune_analytics.py:NeptuneAnalyticsVector._process_success_message
function_simple
false
[]
74
"""使用 ReportEngine 的 LLM 修复词云""" try: from ReportEngine.llms import LLMClient client = LLMClient( api_key=settings.REPORT_ENGINE
_API_KEY, base_url=settings.REPORT_ENGINE_BASE_URL, model_name=settings.REPORT_ENGINE_MODEL_NAME or "gpt-4", ) prompt = build_wordcloud
50
50
666ghj/BettaFish:ReportEngine/utils/chart_repair_api.py:repair_wordcloud_with_report_engine
function_simple
false
[]
37
The script colocates the training and inference workloads onto the same GPU using Ray. The example performs the following steps: * Request a placement group of 1 GPU. * Place the inference model on the above GPU using
the placement group. * Place and load the training model on the same GPU using the placement group. * Generate text from a list of prompts using the inference engine. * Update the weights of the training model and broadcast the updated weights
50
50
vllm-project/vllm:examples/offline_inference/new_weight_syncing/rlhf_ipc.py:module_doc
documentation
false
[]
33
_class: The model class to test - pretrained_model_name_or_path: Hub repository ID for the pretrained model - pretrained_model_kwargs: (Optional) Dict of kwargs to pass to from_
pretrained (e.g., {"subfolder": "transformer"}) Expected methods to be implemented by subclasses: - get_dummy_inputs(): Returns dict of inputs to pass to the model forward pass Optional class attributes:
50
50
huggingface/diffusers:tests/models/testing_utils/quantization.py:BitsAndBytesTesterMixin:class_doc
documentation
false
[]
21
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #
http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS,
50
50
cat1_canary:canary_0030_email:freq3:rep0
license
false
[]
19
, we'll test with any job_id # The endpoint should return 501 regardless of whether the job exists headers = {"x-api-key": created_api_key.api_key} response = await client.get(
"api/v2/workflows?job_id=550e8400-e29b-41d4-a716-446655440002", headers=headers, ) assert response.status_code ==
50
50
langflow-ai/langflow:src/backend/tests/unit/api/v2/test_workflow.py:TestWorkflowDeveloperAPIProtection.test_get_workflow_allowed_when_dev_api_enabled_job_exists
test
false
[]
85
def trace_component( self, component: Component, trace_name: str, inputs: dict[str, Any], metadata: dict[str, Any] | None = None, ): """Trace a component
(minimal implementation). Args: component: Component to trace trace_name: Trace name inputs: Input data metadata: Metadata """ logger.debug(f"Tracing component: {trace_name}") yield self
50
50
langflow-ai/langflow:src/lfx/src/lfx/services/tracing/service.py:TracingService.trace_component
function_simple
false
[]
1
the lora-test will fail due to CUDA OOM. llm = vllm.LLM( MODEL_PATH, max_model_len=1024, enable_lora=True,
max_loras=4, enforce_eager=True, trust_remote_code=True, enable_chunked_prefill=True, ) generate_and_test(llm, deepseekv2_
50
50
vllm-project/vllm:tests/lora/test_deepseekv2_tp.py:test_deepseekv2_lora
test
false
[]
48
AX Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at #
# https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS,
50
50
jax-ml/jax:tests/filecheck/jax_mlir_ext.filecheck.py:license_header
license
false
[]
6
DX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Licensed under the Apache License, Version 2.0 (the "License"); # you may
not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable
50
50
vllm-project/vllm:vllm/model_executor/models/flex_olmo.py:license_header
license
false
[]
2
_decodes_and_prefills_uniform_all_ones(): query_lens = [1, 1, 1] num_decodes, num_prefills, num_decode_tokens, num_prefill
_tokens = ( apply_split_decodes_and_prefills(query_lens, 1, True) ) assert num_decodes == 3 assert num_prefills == 0 assert num_decode
50
50
vllm-project/vllm:tests/v1/attention/test_attention_splitting.py:test_split_decodes_and_prefills_uniform_all_ones
test
false
[]
4
itectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you
may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by
50
50
vllm-project/vllm:vllm/model_executor/models/glm_ocr.py:license_header
license
false
[]
186
2018 The JAX Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License
at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS
50
50
jax-ml/jax:tests/custom_api_test.py:license_header
license
false
[]
2
析JSON try: result = json.loads(cleaned_output) logger.info("JSON解析成功") except JSONDecodeError as e: logger.error(f"JSON解析
失败: {str(e)}") # 尝试修复JSON fixed_json = fix_incomplete_json(cleaned_output) if fixed_json: try: result =
50
50
666ghj/BettaFish:MediaEngine/nodes/summary_node.py:FirstSummaryNode.process_output
function_complex
false
[]
168
, "collection_name": INDEX_NAME, "embedding_model_dims": EMBEDDING_DIMS, "distance_metric": "cosine", "region_name": REGION, }, }
} try: memory = Memory.from_config(config) assert memory.vector_store is not None assert isinstance(memory.vector_store, S3Vectors) assert isinstance(memory.config.vector_
50
50
mem0ai/mem0:tests/vector_stores/test_s3_vectors.py:test_memory_initialization_with_config
test
false
[]
120
# "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0
# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See
50
50
cat1_canary:canary_0035_email:freq3:rep2
license
false
[]
62
/DeepSeek-OCR-2/blob/main/DeepSeek-OCR2-master/DeepSeek-OCR2-vllm/deepencoderv2/qwen2_d2e.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree.
50
50
vllm-project/vllm:vllm/model_executor/models/deepencoder2.py:license_header
license
false
[]
47
') == 'GLSLShader': widgets = node.get('widgets_values', []) if len(widgets) > 0 and widgets[0] != shader_code: widgets[0] = shader_code modified = True
logger.info(" Patched: %s (node %d)", json_path.name, node_id) patched += 1 if modified: with open(json_path, 'w') as f: json
50
50
Comfy-Org/ComfyUI:blueprints/.glsl/update_blueprints.py:patch_shaders
function_complex
false
[]
427
' in model_name: if '16k' in model_name: return 16000 else: return 4000 # DeepSeek elif 'deepseek' in model_name: return 64000 # Ge
mini models elif 'gemini' in model_name: if '2.0' in model_name or 'exp' in model_name: return 2000000 # Gemini 2.0: 2M tokens else
50
50
zhayujie/chatgpt-on-wechat:agent/protocol/agent.py:Agent._get_model_context_window
function_complex
false
[]
280
step. will resize the image to the given height and width. Components: image_processor (`VaeImageProcessor`) Inputs: image (`Image | list`): Reference image(s) for denoising. Can be a
single image or list of images. height (`int`, *optional*): The height in pixels of the generated image. width (`int`, *optional*): The width in pixels of the generated image. Outputs: processed
50
50
huggingface/diffusers:src/diffusers/modular_pipelines/qwenimage/encoders.py:QwenImageProcessImagesInputStep:class_doc
documentation
false
[]
3
fall within start/end thinking markers. Uses a depth counter so nested spans are handled safely and stray end tokens do not drive the counter negative. """ count = 0 depth = 0 for token_id in
token_ids: if token_id == self.start_token_id: depth += 1 continue if token_id == self.end_token_id: if depth > 0: depth -= 1 continue
50
50
vllm-project/vllm:vllm/reasoning/basic_parsers.py:BaseThinkingReasoningParser.count_reasoning_tokens
function_complex
false
[]
26
, device=None, dtype=None, ): """ Args: r: Initial value of the pooling parameter. Higher = closer to max pooling. r_learnable: If True, r is a learn
able parameter. """ super().__init__() if r_learnable: self.r = nn.Parameter(torch.tensor(r, device=device, dtype=dtype)) else: self.register_buffer('
50
50
huggingface/pytorch-image-models:timm/layers/other_pool.py:LsePlus1d.__init__
function_simple
false
[]
25
just text, no tags).""" html = "Just plain text, no HTML tags" async with AsyncWebCrawler() as crawler: config = CrawlerRunConfig(js_code="document.body.innerHTML += '<div id
=\"injected\">Injected</div>'") result = await crawler.arun(f"raw:{html}", config=config) assert result.success # Browser should wrap it in proper HTML assert "Injected" in
50
50
unclecode/crawl4ai:tests/test_raw_html_edge_cases.py:test_raw_html_minimal
test
false
[]
16
heads to use for multi-head attention. out_channels (`int`, defaults to `16`): The number of channels in the output. text_embed_dim (`int`, defaults to `1472`): Input dimension of text
embeddings from the text encoder. time_embed_dim (`int`, defaults to `512`): Output dimension of timestep embeddings. condition_dim (`int`, defaults to `256`): The embedding dimension of the input S
50
50
huggingface/diffusers:src/diffusers/models/transformers/transformer_glm_image.py:GlmImageTransformer2DModel:class_doc
documentation
false
[]
113
_params.attn_out_w, b=None) if self.tp_size > 1: dist.all_reduce(hidden_states, group=self._base_mp_group) # Post-at
tn norm + residual add _, hidden_states = self.norm(hidden_states, None, cur_params.post_attn_norm_gamma, beta=None) residual.add_(hidden_states) # M
50
50
deepspeedai/DeepSpeed:deepspeed/inference/v2/model_implementations/exaone4/model.py:Exaone4InferenceModel._forward_transformer
function_simple
false
[]
262
_default(self): config_keys = ["default"] input_tensor = torch.randn(32, 4096, dtype=torch.bfloat16, device="cuda") scale = torch.tensor([0.5], dtype
=torch.float32, device="cuda") args = (input_tensor, scale) selected_key = pick_silu_mul_fp8_config(args, config_keys) assert selected_key == "
50
50
vllm-project/vllm:tests/kernels/helion/test_silu_mul_fp8.py:TestSiluMulFp8ConfigPicker.test_config_picker_fallback_to_default
test
false
[]
11
. [START redis_message_queue_provider_description] * It uses ``redis+pubsub`` as scheme for identifying Redis queues. * For parameter definitions take a look at :class:`~airflow.providers.redis.
triggers.redis_await_message.AwaitMessageTrigger`. .. code-block:: python from airflow.providers.common.messaging.triggers.msg_queue import MessageQueueTrigger from airflow.sdk import Asset, AssetWatch
50
50
apache/airflow:providers/redis/src/airflow/providers/redis/queues/redis.py:RedisPubSubMessageQueueProvider:class_doc
documentation
false
[]
8
num_inference_steps` and `sigmas` must be `None`. sigmas (`list[float]`, *optional*): Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas`
is passed, `num_inference_steps` and `timesteps` must be `None`. Returns: `tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and
50
50
huggingface/diffusers:src/diffusers/pipelines/qwenimage/pipeline_qwenimage.py:retrieve_timesteps
function_complex
false
[]
250
[0, 8, 3, 1, 6, 4, 2, 5, 7, 9] abort_order_copy = abort_order.copy() def abort_request(): if not abort_order: return
req = requests[abort_order.pop(0)] scheduler.finish_requests(req.request_id, RequestStatus.FINISHED_ABORTED) while sched_outputs: # Abort a scheduled request. abort_
50
50
vllm-project/vllm:tests/v1/core/test_async_scheduler.py:test_abort
test
false
[]
93
, "timestamp": datetime.now().isoformat() } except httpx.TimeoutException: return { "source": source, "status": "timeout", "error": f"请求超时:
{source}({url})", "timestamp": datetime.now().isoformat() } except httpx.HTTPStatusError as e: return { "source": source, "status": "http_error", "
50
50
666ghj/BettaFish:MindSpider/BroadTopicExtraction/get_today_news.py:NewsCollector.fetch_news
function_simple
false
[]
276
# Copyright Philip Brown, ppbrown@github # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may
obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is
50
50
huggingface/diffusers:examples/community/pipeline_stable_diffusion_xl_t5.py:license_header
license
false
[]
0
posture: * `HostExecutionPolicy` – full host access; best for trusted environments where the agent already runs inside a container or VM that provides isolation. * `CodexSandboxExecutionPolicy` – reuses the
Codex CLI sandbox for additional syscall/filesystem restrictions when the CLI is available. * `DockerExecutionPolicy` – launches a separate Docker container for each agent run, providing harder isolation, optional read-only root filesystems
50
50
langchain-ai/langchain:libs/langchain_v1/langchain/agents/middleware/shell_tool.py:ShellToolMiddleware:class_doc
documentation
false
[]
36
. height (`int`, *optional*): The height in pixels of the generated image. width (`int`, *optional*): The width in pixels of the generated image. padding_mask_crop (`int`, *optional
*): Padding for mask cropping in inpainting. generator (`Generator`, *optional*): Torch generator for deterministic generation. Outputs: processed_image (`Tensor`): The processed image processed_mask_
50
50
huggingface/diffusers:src/diffusers/modular_pipelines/qwenimage/modular_blocks_qwenimage.py:QwenImageInpaintVaeEncoderStep:class_doc
documentation
false
[]
133
's explore different ways to match URLs with configs.\n") # Test URLs we'll use throughout test_urls = [ "https://example.com/report.pdf", "https://example.com/data.json
", "https://example.com/blog/post-1", "https://example.com/article/news", "https://api.example.com/v1/users", "https://example.com/
50
50
unclecode/crawl4ai:docs/examples/demo_multi_config_clean.py:demo_part1_pattern_matching
function_simple
false
[]
44
) under one # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses
this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at #
50
50
apache/airflow:dev/prune_old_dirs.py:license_header
license
false
[]
18
, test_client, as_user ): mgr = MagicMock() mgr.is_authorized_custom_view.return_value = False mock_get_auth_manager.return_value = mgr with as_user
(): resp = test_client.patch("/fab/v1/users/alice", json={"last_name": "Updated"}) assert resp.status_code == 403 mock_users.update_user.assert_not_
50
50
apache/airflow:providers/fab/tests/unit/fab/auth_manager/api_fastapi/routes/test_users.py:TestUsers.test_update_user_forbidden
test
false
[]
31
""" Get the DDP configuration for the consumer. This method is used to get the DDP configuration for the consumer. """ return { "dp_size": self.dp_size, "tp_size": self
.tp_size, "pp_size": self.pp_size, "dp_rank": self.dp_rank, "tp_rank": self.tp_rank, "pp_rank": self.pp
50
50
hpcaitech/ColossalAI:applications/ColossalChat/coati/distributed/zero_bubble/consumer.py:BaseConsumer.get_ddp_config
function_simple
false
[]
18
summarize. """ if not messages_to_summarize: return "No previous conversation history." trimmed_messages = self._trim_messages_for_summary(messages_to_summarize) if not trimmed_messages:
return "Previous conversation was too long to summarize." # Format messages to avoid token inflation from metadata when str() is called on # message objects formatted_messages = get_buffer_string(trimmed_messages)
50
50
langchain-ai/langchain:libs/langchain_v1/langchain/agents/middleware/summarization.py:SummarizationMiddleware._acreate_summary
function_simple
false
[]
45
�录入口对象 root_path: 根路径 Returns: FileInfo: 文件信息对象 """ try: stats = entry.stat()
# 使用缓存的文件状态 return FileInfo( path=entry.path, rel_path=os.path.relpath(entry.path, root_path), size=stats.st_size /
50
50
binary-husky/gpt_academic:crazy_functions/doc_fns/text_content_loader.py:TextContentLoader._create_file_info
function_simple
false
[]
48
the classification loss. Args: model: The model to train criterion: Loss function (e.g., CrossEntropyLoss) device: Device for task tensors/buffers dtype: Dtype for task tensors/buffers
verbose: Enable info logging Example: >>> task = ClassificationTask(model, nn.CrossEntropyLoss(), device=torch.device('cuda')) >>> result = task(input, target) >>> result['loss'].backward
50
50
huggingface/pytorch-image-models:timm/task/classification.py:ClassificationTask:class_doc
documentation
false
[]
21
�。 """ if not inlines or len(inlines) != 1: return False first = inlines[0] if not isinstance(first, dict): return False text = first.get("text", "") if
not isinstance(text, str): return False text = text.strip() if not text.startswith("{") or not text.endswith("}"): return False # 检测典型的元
50
50
666ghj/BettaFish:ReportEngine/renderers/html_renderer.py:HTMLRenderer._is_metadata_paragraph
function_complex
false
[]
141
_message(error_msg: str) -> str: """Truncate long error messages, preserving meaningful content.""" if len(error_msg) <= MAX_ERROR_MESSAGE_LENGTH: return error_msg if ":"
in error_msg: for part in error_msg.split(":"): stripped = part.strip() if MIN_MEANINGFUL_PART_LENGTH < len(stripped) < MAX_ERROR_MESSAGE_LENGTH:
50
50
langflow-ai/langflow:src/backend/base/langflow/agentic/helpers/error_handling.py:_truncate_error_message
function_complex
false
[]
5
results immediately. Instead we reduce at the once at the end of the MoE op. (Refer to DeepSeekV2MoE module) With EP and all2all kernels - this is no longer viable as all
GPU ranks in DP, produce the complete set of hidden_states. Therefore it is required that we reduce the shared_experts output early. """ assert self.quant_method is not None return (
50
50
vllm-project/vllm:vllm/model_executor/layers/fused_moe/runner/default_moe_runner.py:DefaultMoERunner.must_reduce_shared_expert_outputs
function_simple
false
[]
78
- path: Matches server.baseUrlPath for proper scoping """ cookie_secret = get_cookie_secret() signed_value = create_signed_value(cookie_secret, cookie_name, serialized_value)
cookie_payload = signed_value.decode("utf-8") response.set_cookie( cookie_name, cookie_payload, httponly=True, samesite="lax", path=_get_cookie
50
50
streamlit/streamlit:lib/streamlit/web/server/starlette/starlette_auth_routes.py:_set_single_cookie
function_simple
false
[]
132
Shared typing utilities for the `st.components.v2` API. This module exposes common, user-facing argument types and callable signatures used by the bidirectional component API. Import these types to annotate code that constructs kwargs
dictionaries for components, or when authoring wrappers/utilities around `st.components.v2.component`. The goal is to keep the public argument surface documented in one place and reusable across both the user-facing factory in
50
50
streamlit/streamlit:lib/streamlit/components/v2/types.py:module_doc
documentation
false
[]
0
angExtract provider plugin with all boilerplate code. This script automates steps 1-6 of the provider creation checklist: 1. Setup Package Structure 2. Configure Entry Point 3. Implement Provider 4. Add Schema
Support (optional) 5. Create and run tests 6. Generate documentation For detailed documentation, see: https://github.com/google/langextract/blob/main/langextract/providers/README
50
50
google/langextract:scripts/create_provider_plugin.py:module_doc
documentation
false
[]
4
:raises RuntimeError: If file transfer fails """ logger = logger or logging.getLogger(__name__) if not os.path.exists(local_path): raise FileNotFoundError(f"Local file does not exist: {local
_path}") sftp = None try: sftp = ssh_client.open_sftp() sftp.put(local_path, remote_path) logger.info("Successfully transferred file from %s to
50
50
apache/airflow:providers/teradata/src/airflow/providers/teradata/utils/tpt_util.py:transfer_file_sftp
function_simple
false
[]
106
_queue_over_limit(memory): """Test queue management when over token limit.""" # Set up a case where we're over the token limit chat_messages = [ ChatMessage(role="user", content="x
" * 500), ChatMessage(role="assistant", content="y " * 500), ChatMessage(role="user", content="z " * 500), ] # This will exceed the token limit and flush 700 tokens
50
50
run-llama/llama_index:llama-index-core/tests/memory/test_memory_base.py:test_manage_queue_over_limit
test
false
[]
5
for a key.""" with self._session() as session: stmt = ( insert(self._table_class) .values( key=bindparam("key"), value=cast(bindparam("value"), ARRAY
(JSONB)) ) .on_conflict_do_update( index_elements=["key"], set_={"value": cast(bindparam("value"), ARRAY(JSONB))}, ) ) params
50
50
run-llama/llama_index:llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-yugabytedb/llama_index/storage/chat_store/yugabytedb/base.py:YugabyteDBChatStore.add_message
function_simple
false
[]
25
LLM project # Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary
rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is
50
50
vllm-project/vllm:vllm/model_executor/models/radio.py:license_header
license
false
[]
27
>>> # 指定日期 >>> result = tools.get_news_by_date( ... date_range="昨天", ... platforms=['zhihu'], ... limit=20 ...
) >>> print(result['total']) 20 """ try: # 参数验证 - 默认今天 if date_range is None: date_range = "�
50
50
sansan0/TrendRadar:mcp_server/tools/data_query.py:DataQueryTools.get_news_by_date
function_complex
false
[]
358
Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org
/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
50
50
huggingface/diffusers:src/diffusers/pipelines/ltx2/latent_upsampler.py:license_header
license
false
[]
26
License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # adapted from https://huggingface.co/OpenGVLab/InternVL2-4
B/blob/main/modeling_intern_vit.py # -------------------------------------------------------- # InternVL # Copyright (c) 2023 OpenGVLab # Licensed under The MIT License [see LICENSE for details] #
50
50
vllm-project/vllm:vllm/model_executor/models/interns1_vit.py:license_header
license
false
[]
4
server_url": f"http://localhost:{test_port}", "oauth_client_id": "test", "oauth_client_secret": "test", "oauth_auth_url": "http://test",
"oauth_token_url": "http://test", } with ( patch.object(mcp_service, "_is_port_available") as mock_port_check, patch.object(mcp_service
50
50
langflow-ai/langflow:src/lfx/tests/unit/services/settings/test_mcp_composer.py:TestPortChangeHandling.test_port_in_use_by_own_project_triggers_kill
test
false
[]
134
and current rate limit status. The debug_info typically contains: - retry_after: Seconds to wait before retrying - limit: Current rate limit - remaining: Remaining requests in current window - reset_time
: When the rate limit window resets Example: raise RateLimitError( message="Rate limit exceeded", error_code="RATE_001", suggestion="Please wait before making more requests", debug_info={"
50
50
mem0ai/mem0:mem0/exceptions.py:RateLimitError:class_doc
documentation
false
[]
29
and The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may
obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is
50
50
huggingface/diffusers:src/diffusers/pipelines/flux2/image_processor.py:license_header
license
false
[]
11
calls.""" if not isinstance(message, AIMessage): msg = f"Expected an AI message got {type(message)}" raise TypeError(msg) actions: list = [] if message.tool_calls:
tool_calls = message.tool_calls else: if not message.additional_kwargs.get("tool_calls"): return AgentFinish( return_values={"output": message.content}, log=str(message
50
50
langchain-ai/langchain:libs/langchain/langchain_classic/agents/output_parsers/tools.py:parse_ai_message_to_tool_action
function_complex
false
[]
42
], runtime: Runtime) -> None: assert runtime is not None def wrap_model_call( self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse], ) -> ModelCallResult:
assert request.runtime is not None return handler(request) def after_model(self, state: AgentState[Any], runtime: Runtime) -> None: assert runtime is not None agent = create_agent(model=
50
50
langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_framework.py:test_runtime_injected_into_middleware
test
false
[]
48
�periods + day_plans + week_map)解析当前时间应执行的行为。 支持: - 预设模板 + 自定
义模式 - 跨日时间段(如 22:00-07:00) - 每天 / 每周差异化配
50
50
sansan0/TrendRadar:trendradar/core/scheduler.py:Scheduler:class_doc
documentation
false
[]
21
(manifest1, package_root) # Check first registration component = setup["component_manager"].get("test_package.component") assert component.html_content is None # Register updated version js_file.write
_text("console.log('updated');") manifest2 = ComponentManifest( name="test_package", version="2.0.0", components=[ ComponentConfig( name="component", ) ],
50
50
streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_registry.py:test_register_from_manifest_overwrites_existing
test
false
[]
145
= { "conditions": [ {"name": "status", "comparison_operator": "is", "value": "active"}, {"name": "status", "comparison_operator": "is", "value": "pending"}
], "logical_operator": "or" } result = get_metadata_filter_expression(filter_dict) assert "JSON_EXTRACT(metadata, '$.status')" in result assert " or " in result.
50
50
infiniflow/ragflow:test/unit_test/utils/test_ob_conn.py:TestGetMetadataFilterExpression.test_multiple_conditions_with_or
test
false
[]
26
_layers, num_physical_experts) ep_size = ep_group.size() assert num_physical_experts == ep_size * num_local_physical_experts first_layer_
weights = list(expert_weights[0]) # Buffers to hold the expert weights during the exchange. # NOTE: Currently we assume the same weights across different layers # have the same shape. weights_buffer
50
50
vllm-project/vllm:vllm/distributed/eplb/rebalance_execute.py:rearrange_expert_weights_inplace
function_complex
false
[]
594
# Execute simple code result = provider.execute_code(instance_id=instance.instance_id, code="console.log('Hello from JavaScript!');", language="javascript", timeout=30) assert result.exit_code
== 0 assert "Hello from JavaScript!" in result.stdout # Clean up provider.destroy_instance(instance.instance_id) except Exception as e: pytest.skip(f"JavaScript execution test failed: {str
50
50
infiniflow/ragflow:agent/sandbox/tests/test_aliyun_codeinterpreter_integration.py:TestAliyunCodeInterpreterIntegration.test_execute_javascript_code
test
false
[]
41
`target_token` argument, the corresponding row of `logits` will not be modified. A batch is constructed with `temperature=0.0` and 50% of requests specifying `target_token`, and for these requests
- and *only* these requests - we expect the `target_token` to be decoded in each step, yielding an output similar to that shown below: Generated Outputs: ------------------------------------------------------------ Prompt: 'Hello, my
50
50
vllm-project/vllm:examples/offline_inference/logits_processor/custom_req.py:module_doc
documentation
false
[]
176
regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0 LogCosh https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine
-learners-should-know-4fb140e9d4b0 L_inf_norm https://medium.com/@montjoile/l0-norm-l1-norm-l2-norm-
50
50
deepfakes/faceswap:plugins/train/train_config.py:Loss:class_doc
documentation
false
[]
62
") and name not in params_dict: return False param = params_dict[name] weight_loader = getattr(param, "weight_loader", default_weight_loader) if shard_id is None:
weight_loader(param, tensor) elif isinstance(shard_id, int): weight_loader(param, tensor, shard_id) else: # Expert param: (expert_id, shard_id)
50
50
vllm-project/vllm:vllm/model_executor/models/bailing_moe_linear.py:load_param
function_complex
false
[]
62
specific queries from Databricks's query history API.""" token = hook._get_token(raise_error=True) # https://docs.databricks.com/api/azure/workspace/queryhistory/list
response = requests.get( url=f"https://{hook.host}/api/2.0/sql/history/queries", headers={"Authorization": f"Bearer {token}"}, data=json.dumps({"
50
50
apache/airflow:providers/databricks/src/airflow/providers/databricks/utils/openlineage.py:_run_api_call
function_simple
false
[]
42
: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set
as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity
50
50
apache/airflow:providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/experiment_service.py:CreateExperimentRunOperator:class_doc
documentation
false
[]
179
server behavior covering: - Health endpoints (/_stcore/health, /_stcore/script-health-check) - Metrics endpoint (/_stcore/metrics) - Host config endpoint (/_stcore
/host-config) - Media endpoint with range requests (/media/*) - File upload endpoint (/_stcore/upload_file/*) - CORS headers - XSRF cookie handling - Static file serving (
50
50
streamlit/streamlit:e2e_playwright/web_server_test.py:module_doc
documentation
false
[]
16
required OAuth field is missing or empty """ if auth_config.get("auth_type") != "oauth": return required_fields = [ "oauth_host", "oauth_port", "oauth_server
_url", "oauth_auth_url", "oauth_token_url", "oauth_client_id", "oauth_client_secret", ] missing_fields = [] empty_fields = []
50
50
langflow-ai/langflow:src/lfx/src/lfx/services/mcp_composer/service.py:MCPComposerService._validate_oauth_settings
function_complex
false
[]
50
works correctly with array access patterns.""" editor.create_artifact(name="John", age=30, tags=["python", "developer"]) # Valid array operations should work patch = JsonPatch( operations=[ PatchOperation(op
="replace", path="/tags/0", value="rust"), PatchOperation(op="add", path="/tags/-", value="expert"), ] ) result = editor.apply_patch(patch) assert result["
50
50
run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-artifact-editor/tests/test_artifact_editor.py:test_validation_with_array_access
test
false
[]
23
1 VLLM_ALLOW_INSECURE_SERIALIZATION=1 vllm serve facebook/opt-125m --enforce-eager --weight-transfer-config '{"backend": "ipc"}' --load-format dummy
--gpu-memory-utilization 0.5 Then run this script: $ python rlhf_http_ipc.py The example performs the following steps: * Load the training model on GPU 0 (same GPU
50
50
vllm-project/vllm:examples/online_serving/new_weight_syncing/rlhf_http_ipc.py:module_doc
documentation
false
[]
211
u channel: for scheduled tasks, send as new message (no msg_id to reply to) # Use chat_id for groups, open_id for private chats context["receive_id_type"] = "chat_id
" if is_group else "open_id" # Keep isgroup as is, but set msg to None (no original message to reply to) # Feishu channel will detect this and send as new message instead of reply
50
50
zhayujie/chatgpt-on-wechat:agent/tools/scheduler/integration.py:_execute_send_message
function_complex
false
[]
277
defaults to `in_channels`. dropout (`float`, defaults to `0.0`): Dropout rate. eps (`float`, defaults to `1e-6`): Epsilon value for normalization layers. elementwise_aff
ine (`bool`, defaults to `False`): Whether to enable elementwise affinity in the normalization layers. non_linearity (`str`, defaults to `"swish"`): Activation function to use. conv_shortcut (bool, defaults to
50
50
huggingface/diffusers:src/diffusers/models/autoencoders/autoencoder_kl_ltx2.py:LTX2VideoResnetBlock3d:class_doc
documentation
false
[]
55
(`int`): The number of channels in the input and output. num_attention_heads (`int`): The number of heads to use for multi-head attention. attention_head_dim (`int`): The number of channels
in each head. qk_norm (`str`, defaults to `"rms_norm"`): The normalization layer to use. activation_fn (`str`, defaults to `"gelu-approximate"`): Activation function to use in
50
50
huggingface/diffusers:src/diffusers/models/transformers/transformer_ltx2.py:LTX2VideoTransformerBlock:class_doc
documentation
false
[]
36
top_p: Nucleus sampling parameter, defaults to 0.1 top_k: Top-k sampling parameter, defaults to 1 enable_vision: Enable vision capabilities, defaults to False vision_details:
Vision detail level, defaults to "auto" http_client_proxies: HTTP client proxy settings, defaults to None ollama_base_url: Ollama base URL, defaults to None """ # Initialize base
50
50
mem0ai/mem0:mem0/configs/llms/ollama.py:OllamaConfig.__init__
function_simple
false
[]
202
float): Timeout for each request. callback_manager (Optional[CallbackManager]): Callback manager for logging. default_headers (Optional[Dict[str, str]]): Default headers for API requests. Examples: ```python
from llama_index.embeddings.baseten import BasetenEmbedding # Using dedicated endpoint # You can find the model_id by in the Baseten dashboard here: https://app.baseten.co/overview embed_
50
50
run-llama/llama_index:llama-index-integrations/embeddings/llama-index-embeddings-baseten/llama_index/embeddings/baseten/base.py:BasetenEmbedding:class_doc
documentation
false
[]
106
_embeddings_config: Optional. Config for batch job creation. :param wait_until_complete: Optional. Await job completion. :param retrieve_result: Optional. Push the result to XCom. If the input_source
is inline, this pushes the execution result. If a file name is specified, this pushes the output file path. :param polling_interval: Optional. The interval, in seconds, to poll the job status. :param
50
50
apache/airflow:providers/google/src/airflow/providers/google/cloud/operators/gen_ai.py:GenAIGeminiCreateEmbeddingsBatchJobOperator:class_doc
documentation
false
[]
164
(excluded_paths=[]) record = logging.LogRecord( name="uvicorn.access", level=logging.INFO, pathname="", lineno=0, msg='%s - "%s %s HTTP/%s
" %d', args=("127.0.0.1:12345", "GET", "/v1/completions", "1.1", 200), exc_info=None, ) assert filter.filter(record)
50
50
vllm-project/vllm:tests/test_access_log_filter.py:TestUvicornAccessLogFilter.test_filter_allows_all_when_no_excluded_paths
test
false
[]
42
validation while still producing the correct JSON payload. When no file blocks are detected the original dicts are returned unchanged so the normal (validated) code path is preserved. Args: message_dicts: Message dicts produced by `_convert_
message_to_dict`. Returns: The original list when no file blocks are present, or a list of SDK Pydantic model instances otherwise. """ if not _has_file_content_blocks(message_dicts
50
50
langchain-ai/langchain:libs/partners/openrouter/langchain_openrouter/chat_models.py:_wrap_messages_for_sdk
function_simple
false
[]
127
this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or
agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and
50
50
vllm-project/vllm:vllm/model_executor/models/hunyuan_vision.py:license_header
license
false
[]
193
parameter or database hook. Normalizes SQLAlchemy dialect names to sqlglot equivalents (e.g. ``postgresql`` → ``postgres``). """ raw = self.dialect if not raw and self.db_hook
and hasattr(self.db_hook, "dialect_name"): raw = self.db_hook.dialect_name if raw: return _SQLALCHEMY_TO_SQLGLOT_DIALECT.get
50
50
apache/airflow:providers/common/ai/src/airflow/providers/common/ai/operators/llm_sql.py:LLMSQLQueryOperator._resolved_dialect
function_simple
false
[]
22
delta_with_reasoning(self): """Test ChatCompletionDelta with Reasoning object""" reasoning = Reasoning("I need to think about this...", status="thinking") delta = ChatCompletionDelta.
model_construct(reasoning) # Check the delta structure self.assertEqual(delta.role, "assistant") self.assertIsNone(delta.content) self.assertEqual(delta.reasoning, "I need to think about
50
50
xtekky/gpt4free:etc/unittest/test_reasoning_standardization.py:TestReasoningFieldStandardization.test_streaming_delta_with_reasoning
test
false
[]
5