{"input": "\"\"\"Tests for channel plugin discovery, merging, and config compatibility.\"\"\"\n\nfrom __future__ import annotations\n\nfrom types import SimpleNamespace\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom nanobot.bus.events import OutboundMessage\nfrom nanobot.bus.queue import MessageBus\nfrom nanobot.channels.base import BaseChannel\nfrom nanobot.channels.manager import ChannelManager\nfrom nanobot.config.schema import ChannelsConfig\n\n\n# ---------------------------------------------------------------------------\n# Helpers\n# ---------------------------------------------------------------------------\n\nclass _FakePlugin(BaseChannel):\n name = \"fakeplugin\"\n display_name = \"Fake Plugin\"\n\n async def start(self) -> None:\n pass\n\n async def stop(self) -> None:\n pass\n\n async def send(self, msg: OutboundMessage) -> None:\n pass\n\n\nclass _FakeTelegram(BaseChannel):\n \"\"\"Plugin that tries to shadow built-in telegram.\"\"\"\n name = \"telegram\"\n display_name = \"Fake Telegram\"\n\n async def start(self) -> None:\n pass\n\n async def stop(self) -> None:\n pass\n\n async def send(self, msg: OutboundMessage) -> None:\n pass\n\n\ndef _make_entry_point(name: str, cls: type):\n \"\"\"Create a mock entry point that returns *cls* on load().\"\"\"\n", "label": 0, "sample_id": "HKUDS/nanobot:tests/test_channel_plugins.py", "category": "unknown", "repo_id": "HKUDS/nanobot"} {"input": "#!/usr/bin/env python3\n\"\"\"\nSkill Initializer - Creates a new skill from template\n\nUsage:\n init_skill.py --path [--resources scripts,references,assets] [--examples]\n\nExamples:\n init_skill.py my-new-skill --path skills/public\n init_skill.py my-new-skill --path skills/public --resources scripts,references\n init_skill.py my-api-helper --path skills/private --resources scripts --examples\n init_skill.py custom-skill --path /custom/location\n\"\"\"\n\nimport argparse\nimport re\nimport sys\nfrom pathlib import Path\n\nMAX_SKILL_NAME_LENGTH = 64\nALLOWED_RESOURCES = {\"scripts\", \"references\", \"assets\"}\n\nSKILL_TEMPLATE = \"\"\"---\nname: {skill_name}\ndescription: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]\n---\n\n# {skill_title}\n\n## Overview\n\n[TODO: 1-2 sentences explaining what this skill enables]\n\n## Structuring This Skill\n\n[TODO: Choose the structure that best fits this skill's purpose. Common patterns:\n\n**1. Workflow-Based** (best for sequential processes)\n", "label": 0, "sample_id": "HKUDS/nanobot:nanobot/skills/skill-creator/scripts/init_skill.py", "category": "unknown", "repo_id": "HKUDS/nanobot"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import annotations\n\nfrom http.cookies import SimpleCookie\nfrom typing import TYPE_CHECKING, Any\n\nfrom starlette.applications import Starlette\nfrom starlette.middleware.sessions import SessionMiddleware\nfrom starlette.responses import PlainTextResponse, RedirectResponse\nfrom starlette.routing import Route\nfrom starlette.testclient import TestClient\n\nfrom streamlit.web.server.starlette import starlette_app_utils, starlette_auth_routes\nfrom streamlit.web.server.starlette.starlette_auth_routes import (\n ", "label": 1, "sample_id": "streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_auth_routes_test.py", "category": "test", "repo_id": "streamlit/streamlit"} {"input": "#!/usr/bin/env python3\n# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nPaddleOCR Text Recognition Caller\n\nSimple CLI wrapper for the PaddleOCR text recognition library.\n\nUsage:\n python scripts/paddleocr-text-recognition/ocr_caller.py --file-url \"URL\"\n python scripts/paddleocr-text-recognition/ocr_caller.py --file-path \"image.png\" --pretty\n\"\"\"\n\nimport argparse\nimport io\nimport json\nimport sys\nimport tempfile\nimport uuid\nfrom datetime import datetime\nfrom pathlib import Path\n\n# Fix Windows console encoding\nif sys.platform == \"win32", "label": 0, "sample_id": "PaddlePaddle/PaddleOCR:skills/paddleocr-text-recognition/scripts/ocr_caller.py", "category": "unknown", "repo_id": "PaddlePaddle/PaddleOCR"} {"input": "import os\nimport re\nfrom collections.abc import Iterable, Sequence\nfrom typing import Any\n\nfrom django.apps.config import AppConfig\nfrom django.conf import settings\nfrom django.core import checks\n\n\ndef check_required_settings(\n app_configs: Sequence[AppConfig] | None,\n databases: Sequence[str] | None,\n **kwargs: Any,\n) -> Iterable[checks.CheckMessage]:\n # These are the settings that we will check that the user has filled in for\n # production deployments before starting the app. It consists of a series\n # of pairs of (setting name, default value that it must be changed from)\n required_settings = [\n (\"EXTERNAL_HOST\", \"zulip.example.com\"),\n (\"ZULIP_ADMINISTRATOR\", \"zulip-admin@example.com\"),\n # SECRET_KEY doesn't really need to be here, in\n # that we set it automatically, but just in\n # case, it seems worth having in this list\n (\"SECRET_KEY\", \"\"),\n (\"AUTHENTICATION_BACKENDS\", ()),\n ]\n errors = []\n for setting_name, default in required_settings:\n if (\n hasattr(settings, setting_name)\n and getattr(settings, setting_name) != default\n ", "label": 1, "sample_id": "zulip/zulip:zerver/checks.py", "category": "function_complex", "repo_id": "zulip/zulip"} {"input": "\"\"\"\nBase classes for MLflow GenAI tools that can be used by judges.\n\nThis module provides the foundational interfaces for tools that judges can use\nto enhance their evaluation capabilities.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import Any\n\nfrom mlflow.entities.trace import Trace\nfrom mlflow.types.llm import ToolDefinition\nfrom mlflow.utils.annotations import experimental\n\n\n@experimental(version=\"3.4.0\")\nclass JudgeTool(ABC):\n \"\"\"\n Abstract base class for tools that can be used by MLflow judges.\n\n Tools provide additional capabilities to judges for analyzing traces,\n performing calculations, or accessing external data sources during evaluation.\n \"\"\"\n\n @property\n @abstractmethod\n def name(self) -> str:\n \"\"\"\n Return the unique name of the tool.\n\n Returns:\n Tool name used for registration and invocation\n \"\"\"\n\n @abstractmethod\n def get_definition(self) -> ToolDefinition:\n \"\"\"\n Get the tool definition in LiteLLM/OpenAI function calling format.\n\n Returns:\n ToolDefinition object containing the tool specification\n \"\"\"\n\n @abstractmethod\n def invoke(self, trace: Trace, **kwargs) -> Any:\n \"\"\"\n Invoke the tool with the provided trace and arguments.\n\n Args:\n trace", "label": 1, "sample_id": "mlflow/mlflow:mlflow/genai/judges/tools/base.py", "category": "documentation", "repo_id": "mlflow/mlflow"} {"input": "from typing import Any\n\n\ndef bubble_sort_iterative(collection: list[Any]) -> list[Any]:\n \"\"\"Pure implementation of bubble sort algorithm in Python\n\n :param collection: some mutable ordered collection with heterogeneous\n comparable items inside\n :return: the same collection ordered in ascending order\n\n Examples:\n >>> bubble_sort_iterative([0, 5, 2, 3, 2])\n [0, 2, 2, 3, 5]\n >>> bubble_sort_iterative([])\n []\n >>> bubble_sort_iterative([-2, -45, -5])\n [-45, -5, -2]\n >>> bubble_sort_iterative([-23, 0, 6, -4, 34])\n [-23, -4, 0, 6, 34]\n >>> bubble_sort_iterative([1, 2, 3, 4])\n [1, 2, 3, 4]\n >>> bubble_sort_iterative([3, 3, 3, 3])\n [3, 3, 3, 3]\n >>> bubble_sort_iterative([56])\n [56]\n >>> bubble", "label": 0, "sample_id": "TheAlgorithms/Python:sorts/bubble_sort.py", "category": "unknown", "repo_id": "TheAlgorithms/Python"} {"input": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\"\"\"\nEvaluate Transcription API correctness by computing Word Error Rate (WER)\non a given ASR dataset. When provided, it will also compare the WER against\na baseline.\nThis simulates real work usage of the API and makes sure that the frontend and\nAsyncLLMEngine are working correctly.\n\"\"\"\n\nimport asyncio\nimport io\nimport time\nfrom statistics import mean, median\n\nimport librosa\nimport pytest\nimport soundfile\nimport torch\nfrom datasets import load_dataset\nfrom evaluate import load\n\nfrom vllm.tokenizers import get_tokenizer\n\nfrom ....models.registry import HF_EXAMPLE_MODELS\nfrom ....utils import RemoteOpenAIServer\n\n\ndef to_bytes(y, sr):\n buffer = io.BytesIO()\n soundfile.write(buffer, y, sr, format=\"WAV\")\n buffer.seek(0)\n return buffer\n\n\nasync def transcribe_audio(client, tokenizer, y, sr):\n # Send loaded audio directly instead of loading from disk,\n # don't account for that time though\n with to_bytes(y, sr) as f:\n start_time = time.perf_counter()\n", "label": 0, "sample_id": "vllm-project/vllm:tests/entrypoints/openai/correctness/test_transcription_api_correctness.py", "category": "unknown", "repo_id": "vllm-project/vllm"} {"input": "# Copyright 2025 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport re\n\n# Get PR title from environment\npr_title = os.environ.get(\"PR_TITLE\", \"\").strip()\n\n# Define rules\nallowed_modules = [\"fsdp\", \"megatron\", \"veomni\", \"sglang\", \"vllm\", \"trtllm\", \"rollout\", \"trainer\"]\nallowed_modules += [\"tests\", \"training_utils\", \"recipe\", \"hardware\", \"deployment\"]\nallowed_modules += [\"ray\", \"worker\", \"single_controller\", \"misc\", \"docker\", \"ci\"]\nallowed_modules += [\"perf\", \"model\", \"", "label": 0, "sample_id": "verl-project/verl:tests/special_sanity/check_pr_title.py", "category": "unknown", "repo_id": "verl-project/verl"} {"input": "# Copyright 2023-present the HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport enum\nfrom typing import Optional\n\n\nclass PeftType(str, enum.Enum):\n \"\"\"\n Enum class for the different types of adapters in PEFT.\n \"\"\"\n\n PROMPT_TUNING = \"PROMPT_TUNING\"\n MULTITASK_PROMPT_TUNING = \"MULTITASK_PROMPT_TUNING\"\n P_TUNING = \"P_TUNING\"\n PREFIX_TUNING = \"PREFIX_TUNING\"\n LORA = \"LORA\"\n ADALORA = \"ADALORA\"\n BOFT = \"BOFT\"\n ADAPTION_PROMPT = \"AD", "label": 0, "sample_id": "huggingface/peft:src/peft/utils/peft_types.py", "category": "unknown", "repo_id": "huggingface/peft"} {"input": "#!/usr/bin/env python3\n\"\"\"Run trigger evaluation for a skill description.\n\nTests whether a skill's description causes Claude to trigger (read the skill)\nfor a set of queries. Outputs results as JSON.\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport select\nimport subprocess\nimport sys\nimport time\nimport uuid\nfrom concurrent.futures import ProcessPoolExecutor, as_completed\nfrom pathlib import Path\n\nfrom scripts.utils import parse_skill_md\n\n\ndef find_project_root() -> Path:\n \"\"\"Find the project root by walking up from cwd looking for .claude/.\n\n Mimics how Claude Code discovers its project root, so the command file\n we create ends up where claude -p will look for it.\n \"\"\"\n current = Path.cwd()\n for parent in [current, *current.parents]:\n if (parent / \".claude\").is_dir():\n return parent\n return current\n\n\ndef run_single_query(\n query: str,\n skill_name: str,\n skill_description: str,\n timeout: int,\n project_root: str,\n model: str | None = None,\n) -> bool:\n \"\"\"Run a single query and return whether the skill was triggered.\n\n Creates a command file in .claude", "label": 0, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/development/skill-creator/scripts/run_eval.py", "category": "unknown", "repo_id": "davila7/claude-code-templates"} {"input": "from __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections.abc import AsyncIterator, Callable, Iterator, Sequence\nfrom typing import Any, Generic, Literal, cast, overload\n\nfrom langchain_core.runnables import Runnable, RunnableConfig\nfrom langchain_core.runnables.graph import Graph as DrawableGraph\nfrom typing_extensions import Self\n\nfrom langgraph.types import (\n All,\n Command,\n GraphOutput,\n StateSnapshot,\n StateUpdate,\n StreamMode,\n StreamPart,\n)\nfrom langgraph.typing import ContextT, InputT, OutputT, StateT\n\n__all__ = (\"PregelProtocol\", \"StreamProtocol\")\n\n\nclass PregelProtocol(Runnable[InputT, Any], Generic[StateT, ContextT, InputT, OutputT]):\n @abstractmethod\n def with_config(\n self, config: RunnableConfig | None = None, **kwargs: Any\n ) -> Self: ...\n\n @abstractmethod\n def get_graph(\n self,\n config: RunnableConfig | None = None,\n *,\n xray: int | bool = False,\n ) -> DrawableGraph: ...\n\n @abstractmethod\n async def aget_graph(\n self,\n config: Runnable", "label": 0, "sample_id": "langchain-ai/langgraph:libs/langgraph/langgraph/pregel/protocol.py", "category": "unknown", "repo_id": "langchain-ai/langgraph"} {"input": "#!/usr/bin/env python3\n\"\"\"Fetch num_key_value_heads from HuggingFace config.json and update TOML model cards.\n\nUsage:\n # Update only cards missing num_key_value_heads\n uv run python scripts/fetch_kv_heads.py --missing\n\n # Update all cards (overwrite existing values)\n uv run python scripts/fetch_kv_heads.py --all\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport json\nimport sys\nimport urllib.request\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom pathlib import Path\n\nimport tomlkit\n\nCARDS_DIR = (\n Path(__file__).resolve().parent.parent / \"resources\" / \"inference_model_cards\"\n)\nMAX_WORKERS = 5\n\n\ndef fetch_kv_heads(model_id: str) -> int | None:\n \"\"\"Fetch num_key_value_heads from HuggingFace config.json.\"\"\"\n url = f\"https://huggingface.co/{model_id}/raw/main/config.json\"\n try:\n with urllib.request.urlopen(url, timeout=15) as resp:\n config = json.loads(resp.read())\n except Exception as e:\n print(f\" ERROR fetching {url}: {e}\", file=sys.stderr)\n return None\n\n for source in [config", "label": 0, "sample_id": "exo-explore/exo:scripts/fetch_kv_heads.py", "category": "unknown", "repo_id": "exo-explore/exo"} {"input": "\"\"\"\nFunctions related to generating headers and fingerprints generally\n\"\"\"\n\nfrom functools import lru_cache\nfrom platform import system as platform_system\n\nfrom browserforge.headers import Browser, HeaderGenerator\nfrom browserforge.headers.generator import SUPPORTED_OPERATING_SYSTEMS\n\nfrom scrapling.core._types import Dict, Literal, Tuple\n\n__OS_NAME__ = platform_system()\nOSName = Literal[\"linux\", \"macos\", \"windows\"]\n# Current versions hardcoded for now (Playwright doesn't allow to know the version of a browser without launching it)\nchromium_version = 145\nchrome_version = 145\n\n\n@lru_cache(1, typed=True)\ndef get_os_name() -> OSName | Tuple:\n \"\"\"Get the current OS name in the same format needed for browserforge, if the OS is Unknown, return None so browserforge uses all.\n\n :return: Current OS name or `None` otherwise\n \"\"\"\n match __OS_NAME__: # pragma: no cover\n case \"Linux\":\n return \"linux\"\n case \"Darwin\":\n return \"macos\"\n case \"Windows\":\n return \"windows\"\n case _:\n return SUPPORTED_OPERATING_SYSTEMS\n\n\ndef generate_headers(browser_mode: bool |", "label": 0, "sample_id": "D4Vinci/Scrapling:scrapling/engines/toolbelt/fingerprints.py", "category": "unknown", "repo_id": "D4Vinci/Scrapling"} {"input": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any, cast\n\nfrom lfx.graph.vertex.base import Vertex\nfrom lfx.log.logger import logger\nfrom lfx.processing.utils import validate_and_repair_json\nfrom pydantic import BaseModel\n\nfrom langflow.schema.graph import InputValue, Tweaks\nfrom langflow.schema.schema import INPUT_FIELD_NAME\nfrom langflow.services.deps import get_settings_service\n\nif TYPE_CHECKING:\n from lfx.events.event_manager import EventManager\n from lfx.graph.graph.base import Graph\n from lfx.graph.schema import RunOutputs\n from lfx.schema.schema import InputValueRequest\n\n\nclass Result(BaseModel):\n result: Any\n session_id: str\n\n\nasync def run_graph_internal(\n graph: Graph,\n flow_id: str,\n *,\n stream: bool = False,\n session_id: str | None = None,\n inputs: list[InputValueRequest] | None = None,\n outputs: list[str] | None = None,\n event_manager: EventManager | None = None,\n) -> tuple[list[RunOutputs], str]:\n \"\"\"Run the graph and generate the result.\"\"\"\n inputs = inputs or []\n effective_session_id = session_id", "label": 0, "sample_id": "langflow-ai/langflow:src/backend/base/langflow/processing/process.py", "category": "unknown", "repo_id": "langflow-ai/langflow"} {"input": "from __future__ import annotations\n\nimport warnings\nfrom abc import ABC, abstractmethod\n\nimport pytest\n\nimport scrapy\nfrom scrapy.exceptions import ScrapyDeprecationWarning\nfrom scrapy.extensions.feedexport import FeedExporter\nfrom scrapy.utils.test import get_crawler\n\n\nclass TestURIParams(ABC):\n spider_name = \"uri_params_spider\"\n deprecated_options = False\n\n @abstractmethod\n def build_settings(self, uri=\"file:///tmp/foobar\", uri_params=None):\n raise NotImplementedError\n\n def _crawler_feed_exporter(self, settings):\n if self.deprecated_options:\n with pytest.warns(\n ScrapyDeprecationWarning,\n match=\"The `FEED_URI` and `FEED_FORMAT` settings have been deprecated\",\n ):\n crawler = get_crawler(settings_dict=settings)\n else:\n crawler = get_crawler(settings_dict=settings)\n feed_exporter = crawler.get_extension(FeedExporter)\n return crawler, feed_exporter\n\n def test_default(self):\n settings = self.build_settings(\n uri=\"file:///tmp/%(name)s\",\n )\n crawler, feed_exporter = self._crawler_feed_exporter(settings)\n spider = scrapy.Spider(self.spider_name)\n spider.crawler =", "label": 0, "sample_id": "scrapy/scrapy:tests/test_feedexport_uri_params.py", "category": "unknown", "repo_id": "scrapy/scrapy"} {"input": "\"\"\"SSE Polling Demo Client\n\nDemonstrates the client-side auto-reconnect for SSE polling pattern.\n\nThis client connects to the SSE Polling Demo server and calls process_batch,\nwhich triggers periodic server-side stream closes. The client automatically\nreconnects using Last-Event-ID and resumes receiving messages.\n\nRun with:\n # First start the server:\n uv run mcp-sse-polling-demo --port 3000\n\n # Then run this client:\n uv run mcp-sse-polling-client --url http://localhost:3000/mcp\n\"\"\"\n\nimport asyncio\nimport logging\n\nimport click\nfrom mcp import ClientSession\nfrom mcp.client.streamable_http import streamable_http_client\n\n\nasync def run_demo(url: str, items: int, checkpoint_every: int) -> None:\n \"\"\"Run the SSE polling demo.\"\"\"\n print(f\"\\n{'=' * 60}\")\n print(\"SSE Polling Demo Client\")\n print(f\"{'=' * 60}\")\n print(f\"Server URL: {url}\")\n print(f\"Processing {items} items with checkpoints every {checkpoint_every}\")\n print(f\"{'=' * 60}\\n\")\n\n async with stream", "label": 1, "sample_id": "modelcontextprotocol/python-sdk:examples/clients/sse-polling-client/mcp_sse_polling_client/main.py", "category": "function_simple", "repo_id": "modelcontextprotocol/python-sdk"} {"input": "import abc\nimport contextlib\nimport datetime\nfrom collections.abc import AsyncIterator\nfrom typing import Literal, TypeVar\n\nimport httpx\nimport mcp.types\nfrom mcp import ClientSession\nfrom mcp.client.session import (\n ElicitationFnT,\n ListRootsFnT,\n LoggingFnT,\n MessageHandlerFnT,\n SamplingFnT,\n)\nfrom typing_extensions import TypedDict, Unpack\n\n# TypeVar for preserving specific ClientTransport subclass types\nClientTransportT = TypeVar(\"ClientTransportT\", bound=\"ClientTransport\")\n\n\nclass SessionKwargs(TypedDict, total=False):\n \"\"\"Keyword arguments for the MCP ClientSession constructor.\"\"\"\n\n read_timeout_seconds: datetime.timedelta | None\n sampling_callback: SamplingFnT | None\n sampling_capabilities: mcp.types.SamplingCapability | None\n list_roots_callback: ListRootsFnT | None\n logging_callback: LoggingFnT | None\n elicitation_callback: ElicitationFnT | None\n message_handler: MessageHandlerFnT | None\n client_info: mcp.types.Implementation | None\n\n\nclass ClientTransport(abc.ABC):\n \"\"\"\n Abstract base class for different MCP client transport mechanisms.\n\n A Transport", "label": 1, "sample_id": "PrefectHQ/fastmcp:src/fastmcp/client/transports/base.py", "category": "function_simple", "repo_id": "PrefectHQ/fastmcp"} {"input": "from django.utils.timezone import now as timezone_now\n\nfrom zerver.lib.timestamp import datetime_to_timestamp\nfrom zerver.models import UserProfile\nfrom zerver.models.devices import Device\nfrom zerver.tornado.django_api import send_event_on_commit\n\n\ndef do_register_push_device(\n user_profile: UserProfile,\n device: Device,\n *,\n token_kind: str,\n push_key_bytes: bytes,\n push_key_id: int,\n token_id_int: int,\n token_id_base64: str,\n) -> None:\n registered_at = timezone_now()\n device.push_key = push_key_bytes\n device.push_key_id = push_key_id\n device.pending_push_token_id = token_id_int\n device.push_token_kind = token_kind\n device.push_token_last_updated_timestamp = registered_at\n device.push_registration_error_code = None\n device.save(\n update_fields=[\n \"push_key\",\n \"push_key_id\",\n \"pending_push_token_id\",\n \"push_token_kind\",\n \"push_token_last_updated_timestamp\",\n \"push_registration_error_code\",\n ]\n )\n\n event = dict(\n type=\"device\",\n op=\"update\",\n device_id=device.id,\n push_key_id=device.push_key_id,\n ", "label": 1, "sample_id": "zulip/zulip:zerver/actions/push_notifications.py", "category": "function_simple", "repo_id": "zulip/zulip"} {"input": "\"\"\"Tool search — deferred tool discovery at runtime.\n\nContains:\n- DeferredToolRegistry: stores deferred tools and handles regex search\n- tool_search: the LangChain tool the agent calls to discover deferred tools\n\nThe agent sees deferred tool names in but cannot\ncall them until it fetches their full schema via the tool_search tool.\nSource-agnostic: no mention of MCP or tool origin.\n\"\"\"\n\nimport json\nimport logging\nimport re\nfrom dataclasses import dataclass\n\nfrom langchain.tools import BaseTool\nfrom langchain_core.tools import tool\nfrom langchain_core.utils.function_calling import convert_to_openai_function\n\nlogger = logging.getLogger(__name__)\n\nMAX_RESULTS = 5 # Max tools returned per search\n\n\n# ── Registry ──\n\n\n@dataclass\nclass DeferredToolEntry:\n \"\"\"Lightweight metadata for a deferred tool (no full schema in context).\"\"\"\n\n name: str\n description: str\n tool: BaseTool # Full tool object, returned only on search match\n\n\nclass DeferredToolRegistry:\n \"\"\"Registry of deferred tools, searchable by regex pattern.\"\"\"\n\n def __init__(self):\n self._entries: list[DeferredToolEntry] = []\n\n def register(self", "label": 0, "sample_id": "bytedance/deer-flow:backend/packages/harness/deerflow/tools/builtins/tool_search.py", "category": "unknown", "repo_id": "bytedance/deer-flow"} {"input": "#!/usr/bin/env python3\n\"\"\"\nQuick validation script for skills - minimal version\n\"\"\"\n\nimport sys\nimport os\nimport re\nimport yaml\nfrom pathlib import Path\n\ndef validate_skill(skill_path):\n \"\"\"Basic validation of a skill\"\"\"\n skill_path = Path(skill_path)\n\n # Check SKILL.md exists\n skill_md = skill_path / 'SKILL.md'\n if not skill_md.exists():\n return False, \"SKILL.md not found\"\n\n # Read and validate frontmatter\n content = skill_md.read_text()\n if not content.startswith('---'):\n return False, \"No YAML frontmatter found\"\n\n # Extract frontmatter\n match = re.match(r'^---\\n(.*?)\\n---', content, re.DOTALL)\n if not match:\n return False, \"Invalid frontmatter format\"\n\n frontmatter_text = match.group(1)\n\n # Parse YAML frontmatter\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n if not isinstance(frontmatter, dict):\n return False, \"Frontmatter must be a YAML dictionary\"\n except yaml.YAMLError as e:\n return False, f\"Invalid YAML in frontmatter: {e}\"\n\n # Define allowed properties", "label": 0, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/development/skill-creator/scripts/quick_validate.py", "category": "unknown", "repo_id": "davila7/claude-code-templates"} {"input": "import gradio as gr\n\nwith gr.Blocks() as demo:\n with gr.HTML(html_template='''\n \n

${form_name}

\n @children\n \n ''', css_template='''\n border: 2px solid gray;\n border-radius: 12px;\n padding: 20px;\n\n .maximize {\n position: absolute;\n top: 10px;\n right: 10px;\n background: none;\n border: none;\n z-index: 1000;\n }\n ''', js_on_load='''\n element.querySelector('.submit').addEventListener('click', () => {\n trigger('submit');\n });\n element.querySelector('.maximize').addEventListener('click', () => {\n element.requestFullscreen();\n });\n ''', form_name=\"Custom Form\") as form:\n name = gr.Textbox(label=\"Name\")\n email = gr.Textbox(label=\"Email\")\n\n output = gr.Textbox(label=\"Output\")\n \n form.submit(lambda name, email: f\"Name: {name}, Email: {email}\",", "label": 1, "sample_id": "gradio-app/gradio:demo/html_children/run.py", "category": "documentation", "repo_id": "gradio-app/gradio"} {"input": "from blake3 import blake3\nfrom typing import IO\nimport os\nimport asyncio\n\n\nDEFAULT_CHUNK = 8 * 1024 *1024 # 8MB\n\n# NOTE: this allows hashing different representations of a file-like object\ndef blake3_hash(\n fp: str | IO[bytes],\n chunk_size: int = DEFAULT_CHUNK,\n) -> str:\n \"\"\"\n Returns a BLAKE3 hex digest for ``fp``, which may be:\n - a filename (str/bytes) or PathLike\n - an open binary file object\n If ``fp`` is a file object, it must be opened in **binary** mode and support\n ``read``, ``seek``, and ``tell``. The function will seek to the start before\n reading and will attempt to restore the original position afterward.\n \"\"\"\n # duck typing to check if input is a file-like object\n if hasattr(fp, \"read\"):\n return _hash_file_obj(fp, chunk_size)\n\n with open(os.fspath(fp), \"rb\") as f:\n return _hash_file_obj(f, chunk_size)\n\n\nasync def blake3_hash_async(\n fp: str | IO[bytes],\n chunk", "label": 1, "sample_id": "Comfy-Org/ComfyUI:app/assets/hashing.py", "category": "function_complex", "repo_id": "Comfy-Org/ComfyUI"} {"input": "import re\nfrom pathlib import Path\n\nfrom fastapi import APIRouter, HTTPException\nfrom pydantic import BaseModel, constr\n\nfrom utils.function_catalog import get_function_catalog\nfrom utils.function_manager import FUNCTION_CALLING_DIR\n\nrouter = APIRouter()\n\n\nclass LocalToolCreateRequest(BaseModel):\n filename: constr(strip_whitespace=True, min_length=1, max_length=255)\n content: str\n overwrite: bool = False\n\n\n@router.get(\"/api/tools/local\")\ndef list_local_tools():\n catalog = get_function_catalog()\n metadata = catalog.list_metadata()\n tools = []\n for name, meta in metadata.items():\n tools.append(\n {\n \"name\": name,\n \"description\": meta.description,\n \"parameters\": meta.parameters_schema,\n \"module\": meta.module_name,\n \"file_path\": meta.file_path,\n }\n )\n tools.sort(key=lambda item: item[\"name\"])\n return {\n \"success\": True,\n \"count\": len(tools),\n \"tools\": tools,\n \"load_error\": str(catalog.load_error) if catalog.load_error else None,\n }\n\n\n@router.post(\"/api/tools/local\")\ndef create_local_tool(payload: LocalToolCreateRequest):\n raw_name =", "label": 0, "sample_id": "OpenBMB/ChatDev:server/routes/tools.py", "category": "unknown", "repo_id": "OpenBMB/ChatDev"} {"input": "# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.\n# SM120 (Blackwell GeForce / DGX Spark) forward pass.\n#\n# SM120 uses the same SM80-era MMA instructions (mma.sync.aligned.m16n8k16) but has\n# a smaller shared memory capacity (99 KB vs 163 KB on SM80). This module subclasses\n# FlashAttentionForwardSm80 and overrides the SMEM capacity check accordingly.\n\nimport cutlass\nimport cutlass.utils as utils_basic\n\nfrom flash_attn.cute.flash_fwd import FlashAttentionForwardSm80\n\n\nclass FlashAttentionForwardSm120(FlashAttentionForwardSm80):\n # Keep arch = 80 to use CpAsync code paths (no TMA for output).\n # The compilation target is determined by the GPU at compile time, not this field.\n arch = 80\n\n @staticmethod\n def can_implement(\n dtype,\n head_dim,\n head_dim_v,\n tile_m,\n tile_n,\n num_stages,\n num_threads", "label": 0, "sample_id": "Dao-AILab/flash-attention:flash_attn/cute/flash_fwd_sm120.py", "category": "unknown", "repo_id": "Dao-AILab/flash-attention"} {"input": "#! /usr/bin/env python3\nimport argparse\nimport os\nimport subprocess\nimport sys\n\n\ndef run(cmd, *, cwd=None, env=None, dry_run=True):\n \"\"\"Run a command with optional dry-run behavior.\"\"\"\n environ = os.environ.copy()\n if env:\n environ.update(env)\n if dry_run:\n print(\"[DRY RUN]\", \" \".join(cmd))\n else:\n print(\"[EXECUTE]\", \" \".join(cmd))\n try:\n result = subprocess.check_output(\n cmd, cwd=cwd, env=environ, stderr=subprocess.STDOUT\n )\n except subprocess.CalledProcessError as e:\n result = e.output\n print(\" [ERROR]\", result)\n raise\n else:\n print(\" [RESULT]\", result)\n return result.decode().strip()\n\n\ndef validate_env(checkout_dir):\n if not checkout_dir:\n sys.exit(\"Error: checkout directory not provided (--checkout-dir).\")\n if not os.path.exists(checkout_dir):\n sys.exit(f\"Error: checkout directory '{checkout_dir}' does not exist.\")\n if not os.path.isdir(checkout_dir):\n sys.exit(f\"Error: '{checkout_dir}' is not a directory.\")\n\n\ndef get_remote_branches", "label": 1, "sample_id": "django/django:scripts/archive_eol_stable_branches.py", "category": "function_complex", "repo_id": "django/django"} {"input": "#!/usr/bin/env python3\n\n__package__ = 'archivebox.cli'\n\nimport os\n\nimport rich_click as click\nfrom rich import print\n\nfrom archivebox.misc.util import docstring, enforce_types\n\n\n@enforce_types\ndef install(binaries: tuple[str, ...] = (), binproviders: str = '*', dry_run: bool = False) -> None:\n \"\"\"Detect and install ArchiveBox dependencies by running a dependency-check crawl\n\n Examples:\n archivebox install # Install all dependencies\n archivebox install wget curl # Install only wget and curl\n archivebox install --binproviders=pip yt-dlp # Install yt-dlp using only pip\n archivebox install --binproviders=brew,apt # Install all deps using only brew or apt\n \"\"\"\n\n from archivebox.config.permissions import IS_ROOT, ARCHIVEBOX_USER, ARCHIVEBOX_GROUP\n from archivebox.config.paths import ARCHIVE_DIR\n from archivebox.misc.logging import stderr\n from archivebox.cli.archivebox_init import init\n\n if not (os.access(ARCHIVE_DIR, os.R_OK) and ARCHIVE_DIR.is_dir()):\n init() # must init full index because we need a db to store Binary entries in\n\n", "label": 0, "sample_id": "ArchiveBox/ArchiveBox:archivebox/cli/archivebox_install.py", "category": "unknown", "repo_id": "ArchiveBox/ArchiveBox"} {"input": "from collections.abc import Generator\nfrom functools import cache\nfrom typing import Any\n\nfrom mlx_lm.models.deepseek_v32 import Model as DeepseekV32Model\nfrom mlx_lm.models.gpt_oss import Model as GptOssModel\nfrom mlx_lm.tokenizer_utils import TokenizerWrapper\nfrom openai_harmony import ( # pyright: ignore[reportMissingTypeStubs]\n HarmonyEncodingName,\n HarmonyError, # pyright: ignore[reportUnknownVariableType]\n Role,\n StreamableParser,\n load_harmony_encoding,\n)\n\nfrom exo.shared.types.api import ToolCallItem\nfrom exo.shared.types.common import ModelId\nfrom exo.shared.types.mlx import Model\nfrom exo.shared.types.worker.runner_response import GenerationResponse, ToolCallResponse\nfrom exo.worker.engines.mlx.utils_mlx import (\n detect_thinking_prompt_suffix,\n)\nfrom exo.worker.runner.bootstrap import logger\nfrom exo.worker.runner.llm_inference.tool_parsers import ToolParser\n\n\n@cache\ndef get_gpt_oss_encoding():\n encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)\n return encoding\n\n\ndef apply_all_parsers", "label": 0, "sample_id": "exo-explore/exo:src/exo/worker/runner/llm_inference/model_output_parsers.py", "category": "unknown", "repo_id": "exo-explore/exo"} {"input": "import math, os\nif __name__ == \"__main__\":\n os.environ[\"DEFAULT_FLOAT\"] = \"bfloat16\"\n os.environ[\"OPTIM_DTYPE\"] = \"bfloat16\"\n os.environ[\"DEV\"] = \"NULL\"\nfrom tinygrad import Tensor, nn, function, getenv, dtypes, TinyJit\nfrom tinygrad.helpers import Timing, colored, GlobalCounters\nfrom extra.models.llama import apply_rotary_emb, precompute_freqs_cis\n\ndef rmsnorm(x_in:Tensor, eps:float):\n x = x_in.float()\n x = x * (x.square().mean(-1, keepdim=True) + eps).rsqrt()\n return x.cast(x_in.dtype)\n\nclass FlatTransformer:\n def __init__(self, dim:int, hidden_dim:int, n_heads:int, n_layers:int, norm_eps:float, vocab_size:int, n_kv_heads:int|None=None,\n rope_theta:int=10000, max_context:int=1024):\n self.vocab_size = vocab_size\n self.n_layers = n_layers\n self.n_heads = n_heads\n self.n_kv_heads = n_kv_heads if n_kv_heads is not None", "label": 0, "sample_id": "tinygrad/tinygrad:examples/mlperf/models/flat_llama.py", "category": "unknown", "repo_id": "tinygrad/tinygrad"} {"input": "\"\"\"\nRecursive Language Model (RLM) module for DSPy.\n\nRLMs are an inference strategy where LLMs treat long contexts as part of an external\nenvironment rather than feeding them directly to the model. The LLM writes Python code\nto programmatically examine, decompose, and recursively call sub-LLMs over snippets.\n\nReference: \"Recursive Language Models\" (Zhang, Kraska, Khattab, 2025)\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport threading\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom contextlib import contextmanager\nfrom typing import TYPE_CHECKING, Any, Callable, Iterator\n\nimport pydantic\n\nimport dspy\nfrom dspy.adapters.types.tool import Tool\nfrom dspy.adapters.utils import parse_value, translate_field_type\nfrom dspy.primitives.code_interpreter import SIMPLE_TYPES, CodeInterpreter, CodeInterpreterError, FinalOutput\nfrom dspy.primitives.module import Module\nfrom dspy.primitives.prediction import Prediction\nfrom dspy.primitives.python_interpreter import PythonInterpreter\nfrom dspy.primitives.repl_types import REPLEntry, REPLHistory, REPLVariable\nfrom dspy.signatures.signature import ensure_signature\nfrom dspy.utils.annotation import", "label": 1, "sample_id": "stanfordnlp/dspy:dspy/predict/rlm.py", "category": "function_complex", "repo_id": "stanfordnlp/dspy"} {"input": "from __future__ import annotations\n\nfrom typing import Any\nfrom unittest import mock\n\nimport pytest\nfrom testfixtures import LogCapture\n\nfrom scrapy import signals\nfrom scrapy.crawler import Crawler\nfrom scrapy.http import Response, TextResponse, XmlResponse\nfrom scrapy.settings import Settings\nfrom scrapy.spiders import CSVFeedSpider, Spider, XMLFeedSpider\nfrom scrapy.spiders.init import InitSpider\nfrom scrapy.utils.test import get_crawler, get_reactor_settings\nfrom tests import get_testdata\nfrom tests.utils.decorators import coroutine_test, inline_callbacks_test\n\n\nclass TestSpider:\n spider_class = Spider\n\n def test_base_spider(self):\n spider = self.spider_class(\"example.com\")\n assert spider.name == \"example.com\"\n assert spider.start_urls == [] # pylint: disable=use-implicit-booleaness-not-comparison\n\n def test_spider_args(self):\n \"\"\"``__init__`` method arguments are assigned to spider attributes\"\"\"\n spider = self.spider_class(\"example.com\", foo=\"bar\")\n assert spider.foo == \"bar\"\n\n def test_spider_without_name(self):\n \"\"\"``__init__`` method arguments are assigned to spider attributes\"\"\"\n msg = \"must have a name\"\n ", "label": 0, "sample_id": "scrapy/scrapy:tests/test_spider.py", "category": "unknown", "repo_id": "scrapy/scrapy"} {"input": "#!/usr/bin/env python3\n\"\"\"\nShader Blueprint Updater\n\nSyncs GLSL shader files between this folder and blueprint JSON files.\n\nFile naming convention:\n {Blueprint Name}_{node_id}.frag\n\nUsage:\n python update_blueprints.py extract # Extract shaders from JSONs to here\n python update_blueprints.py patch # Patch shaders back into JSONs\n python update_blueprints.py # Same as patch (default)\n\"\"\"\n\nimport json\nimport logging\nimport sys\nimport re\nfrom pathlib import Path\n\nlogging.basicConfig(level=logging.INFO, format='%(message)s')\nlogger = logging.getLogger(__name__)\n\nGLSL_DIR = Path(__file__).parent\nBLUEPRINTS_DIR = GLSL_DIR.parent\n\n\ndef get_blueprint_files():\n \"\"\"Get all blueprint JSON files.\"\"\"\n return sorted(BLUEPRINTS_DIR.glob(\"*.json\"))\n\n\ndef sanitize_filename(name):\n \"\"\"Convert blueprint name to safe filename.\"\"\"\n return re.sub(r'[^\\w\\-]', '_', name)\n\n\ndef extract_shaders():\n \"\"\"Extract all shaders from blueprint JSONs to this folder.\"\"\"\n extracted = 0\n for json_path in get_blueprint_files():\n blueprint_name = json_path.stem\n\n try:\n with open(json_path, 'r') as", "label": 1, "sample_id": "Comfy-Org/ComfyUI:blueprints/.glsl/update_blueprints.py", "category": "function_complex", "repo_id": "Comfy-Org/ComfyUI"} {"input": "\"\"\"\nInteractive TemperatureGrid sensor visualization with keyboard teleop.\n\nA platform has a temperature grid sensor on its top surface. Move a \"hot\" pusher\nand drop objects onto the platform; the grid shows temperature (blue=cool, red=hot)\nfrom contact-based blending of each body's base_temperature and conductivity.\n\"\"\"\n\nimport argparse\nimport os\n\nimport numpy as np\n\nimport genesis as gs\nfrom genesis.utils.misc import tensor_to_array\nfrom genesis.vis.keybindings import Key, KeyAction, Keybind\n\n# Teleop\nKEY_DPOS = 0.08\nKEY_DPOS_Z = 0.01\nFORCE_SCALE = 100.0\nPUSHER_SIZE = 0.1\n\n# Temperature grid\nGRID_SIZE = (10, 10, 1)\n\n# Objects\nSANDBOX_SIZE = 1.5\nWALL_THICKNESS = 0.08\nWALL_HEIGHT = 0.3\nPLATFORM_HEIGHT = 0.1\nOBJ_Z = PLATFORM_HEIGHT * 1.4\nOBJ_SIZE = 0.1\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Interactive TemperatureGrid sensor visualization\")\n parser.add_argument(\"--vis\", \"-v\", action=\"", "label": 0, "sample_id": "Genesis-Embodied-AI/Genesis:examples/sensors/temperature_grid.py", "category": "unknown", "repo_id": "Genesis-Embodied-AI/Genesis"} {"input": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\n\nimport frappe\nfrom frappe import _, bold\nfrom frappe.model.document import Document\nfrom frappe.utils import (\n\tadd_days,\n\tcint,\n\tcomma_and,\n\tflt,\n\tformatdate,\n\tget_link_to_form,\n\tget_time,\n\tget_url_to_form,\n\tgetdate,\n\ttime_diff_in_hours,\n\ttime_diff_in_seconds,\n\tto_timedelta,\n)\nfrom frappe.utils.data import DateTimeLikeObject\n\nfrom erpnext.support.doctype.issue.issue import get_holidays\n\n\nclass WorkstationHolidayError(frappe.ValidationError):\n\tpass\n\n\nclass NotInWorkingHoursError(frappe.ValidationError):\n\tpass\n\n\nclass OverlapError(frappe.ValidationError):\n\tpass\n\n\nclass Workstation(Document):\n\t# begin: auto-generated types\n\t# This code is auto-generated. Do not modify anything in this block.\n\n\tfrom typing import TYPE_CHECKING\n\n\tif TYPE_CHECKING:\n\t\tfrom frappe.types import DF\n\n\t\tfrom erpnext.manufacturing.doctype.workstation_cost.workstation_cost import WorkstationCost\n\t\tfrom erpnext.manufacturing.doctype.workstation_working_hour.workstation_working_hour import", "label": 0, "sample_id": "frappe/erpnext:erpnext/manufacturing/doctype/workstation/workstation.py", "category": "unknown", "repo_id": "frappe/erpnext"} {"input": "\"\"\"Abstract base class for sandbox state persistence.\n\nThe state store handles cross-process persistence of thread_id → sandbox mappings,\nenabling different processes (gateway, langgraph, multiple workers) to find the same\nsandbox for a given thread.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom collections.abc import Generator\nfrom contextlib import contextmanager\n\nfrom .sandbox_info import SandboxInfo\n\n\nclass SandboxStateStore(ABC):\n \"\"\"Abstract base for persisting thread_id → sandbox mappings across processes.\n\n Implementations:\n - FileSandboxStateStore: JSON files + fcntl file locking (single-host)\n - TODO: RedisSandboxStateStore: Redis-based for distributed multi-host deployments\n \"\"\"\n\n @abstractmethod\n def save(self, thread_id: str, info: SandboxInfo) -> None:\n \"\"\"Save sandbox state for a thread.\n\n Args:\n thread_id: The thread ID.\n info: Sandbox metadata to persist.\n \"\"\"\n ...\n\n @abstractmethod\n def load(self, thread_id: str) -> SandboxInfo | None:\n \"\"\"Load sandbox state for a thread.\n\n Args:\n thread_id: The thread ID.\n\n Returns:\n SandboxInfo if found, None otherwise.\n", "label": 1, "sample_id": "bytedance/deer-flow:backend/src/community/aio_sandbox/state_store.py", "category": "documentation", "repo_id": "bytedance/deer-flow"} {"input": "import functools\nimport math\nimport operator\nimport re\nimport warnings\n\n\ndef _convert_conv_transpose_padding_args_from_keras_to_jax(\n kernel_size, stride, dilation_rate, padding, output_padding\n):\n \"\"\"Convert the padding arguments from Keras to the ones used by JAX.\n JAX starts with an shape of size `(input-1) * stride - kernel_size + 2`,\n then adds `left_pad` on the left, and `right_pad` on the right.\n In Keras, the `padding` argument determines a base shape, to which\n `output_padding` is added on the right. If `output_padding` is None, it will\n be given a default value.\n \"\"\"\n\n if padding.lower() not in {\"valid\", \"same\"}:\n raise ValueError(\n f\"The `padding` argument must be one of 'valid', 'same'. \"\n f\"Received: padding={padding}\"\n )\n kernel_size = (kernel_size - 1) * dilation_rate + 1\n\n if padding.lower() == \"valid\":\n # If output_padding is None, we fill it so that the shape of the output\n # is `(input-1)*s", "label": 0, "sample_id": "keras-team/keras:keras/src/backend/common/backend_utils.py", "category": "unknown", "repo_id": "keras-team/keras"} {"input": "\"\"\"Async client for managing recurrent runs (cron jobs) in LangGraph.\"\"\"\n\nfrom __future__ import annotations\n\nimport warnings\nfrom collections.abc import Mapping, Sequence\nfrom datetime import datetime\nfrom typing import Any\n\nfrom langgraph_sdk._async.http import HttpClient\nfrom langgraph_sdk.schema import (\n All,\n Config,\n Context,\n Cron,\n CronSelectField,\n CronSortBy,\n Durability,\n Input,\n OnCompletionBehavior,\n QueryParamTypes,\n Run,\n SortOrder,\n StreamMode,\n)\n\n\nclass CronClient:\n \"\"\"Client for managing recurrent runs (cron jobs) in LangGraph.\n\n A run is a single invocation of an assistant with optional input, config, and context.\n This client allows scheduling recurring runs to occur automatically.\n\n ???+ example \"Example Usage\"\n\n ```python\n client = get_client(url=\"http://localhost:2024\"))\n cron_job = await client.crons.create_for_thread(\n thread_id=\"thread_123\",\n assistant_id=\"asst_456\",\n schedule=\"0 9 * * *\",\n input={\"message\": \"Daily update\"}\n )\n ```\n\n !!! note \"Feature Availability\"\n\n The cr", "label": 1, "sample_id": "langchain-ai/langgraph:libs/sdk-py/langgraph_sdk/_async/cron.py", "category": "documentation", "repo_id": "langchain-ai/langgraph"} {"input": "# encoding:utf-8\n\nimport json\nimport time\n\nimport requests\nfrom models.bot import Bot\nfrom models.session_manager import SessionManager\nfrom bridge.context import ContextType\nfrom bridge.reply import Reply, ReplyType\nfrom common.log import logger\nfrom config import conf, load_config\nfrom .doubao_session import DoubaoSession\n\n\n# Doubao (火山方舟 / Volcengine Ark) API Bot\nclass DoubaoBot(Bot):\n def __init__(self):\n super().__init__()\n self.sessions = SessionManager(DoubaoSession, model=conf().get(\"model\") or \"doubao-seed-2-0-pro-260215\")\n model = conf().get(\"model\") or \"doubao-seed-2-0-pro-260215\"\n self.args = {\n \"model\": model,\n \"temperature\": conf().get(\"temperature\", 0.8),\n \"top_p\": conf().get(\"top_p\", 1.0),\n }\n self.api_key = conf().get(\"ark_api_key\")\n self.base_url = conf().get(\"ark_base_url\", \"https://ark.cn-beijing.volces.com/api/v", "label": 1, "sample_id": "zhayujie/chatgpt-on-wechat:models/doubao/doubao_bot.py", "category": "function_complex", "repo_id": "zhayujie/chatgpt-on-wechat"} {"input": "from __future__ import annotations\n\nimport bz2\nimport gzip\nimport lzma\nimport marshal\nimport pickle\nimport sys\nfrom io import BytesIO\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any\n\nimport pytest\n\nfrom scrapy.utils.test import get_crawler\nfrom tests.test_feedexport import TestFeedExportBase, path_to_url, printf_escape\nfrom tests.utils.decorators import coroutine_test\n\nif TYPE_CHECKING:\n from scrapy import Spider\n\n\nclass TestFeedPostProcessedExports(TestFeedExportBase):\n items = [{\"foo\": \"bar\"}]\n expected = b\"foo\\r\\nbar\\r\\n\"\n\n class MyPlugin1:\n def __init__(self, file, feed_options):\n self.file = file\n self.feed_options = feed_options\n self.char = self.feed_options.get(\"plugin1_char\", b\"\")\n\n def write(self, data):\n written_count = self.file.write(data)\n written_count += self.file.write(self.char)\n return written_count\n\n def close(self):\n self.file.close()\n\n def _named_tempfile(self, name) -> str:\n return str(Path(self.temp_dir, name))\n\n async def run_and_export(\n self, spider_cls: type[", "label": 0, "sample_id": "scrapy/scrapy:tests/test_feedexport_postprocess.py", "category": "unknown", "repo_id": "scrapy/scrapy"} {"input": "#!/usr/bin/env python\n\"\"\"\nExample script demonstrating the integration of MinerU parser with RAGAnything\n\nThis example shows how to:\n1. Process parsed documents with RAGAnything\n2. Perform multimodal queries on the processed documents\n3. Handle different types of content (text, images, tables)\n\"\"\"\n\nimport os\nimport argparse\nimport asyncio\nimport logging\nimport logging.config\nfrom pathlib import Path\n\n# Add project root directory to Python path\nimport sys\n\nsys.path.append(str(Path(__file__).parent.parent))\n\nfrom lightrag.llm.openai import openai_complete_if_cache, openai_embed\nfrom lightrag.utils import EmbeddingFunc, logger, set_verbose_debug\nfrom raganything import RAGAnything, RAGAnythingConfig\n\n\ndef configure_logging():\n \"\"\"Configure logging for the application\"\"\"\n # Get log directory path from environment variable or use current directory\n log_dir = os.getenv(\"LOG_DIR\", os.getcwd())\n log_file_path = os.path.abspath(os.path.join(log_dir, \"raganything_example.log\"))\n\n print(f\"\\nRAGAnything example log file: {log_file_path}\\n\")\n os.makedirs(os.path.dirname(log_dir), exist_ok=True)\n\n # Get log file max size and backup count", "label": 1, "sample_id": "HKUDS/LightRAG:examples/raganything_example.py", "category": "function_complex", "repo_id": "HKUDS/LightRAG"} {"input": "from django.db import NotSupportedError\nfrom django.db.models.expressions import Func\nfrom django.db.models.fields import UUIDField\n\n\nclass UUID4(Func):\n function = \"UUIDV4\"\n arity = 0\n output_field = UUIDField()\n\n def as_sql(self, compiler, connection, **extra_context):\n if connection.features.supports_uuid4_function:\n return super().as_sql(compiler, connection, **extra_context)\n raise NotSupportedError(\"UUID4 is not supported on this database backend.\")\n\n def as_postgresql(self, compiler, connection, **extra_context):\n if connection.features.is_postgresql_18:\n return self.as_sql(compiler, connection, **extra_context)\n return self.as_sql(\n compiler, connection, function=\"GEN_RANDOM_UUID\", **extra_context\n )\n\n def as_mysql(self, compiler, connection, **extra_context):\n if not connection.features.supports_uuid4_function:\n if connection.mysql_is_mariadb:\n raise NotSupportedError(\"UUID4 requires MariaDB version 11.7 or later.\")\n raise NotSupportedError(\"UUID4 is not supported on MySQL.\")\n return self.as_sql(compiler, connection, function=\"UUID_V4\", **extra", "label": 1, "sample_id": "django/django:django/db/models/functions/uuid.py", "category": "function_complex", "repo_id": "django/django"} {"input": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\"\"\"Integration tests for MCP tool support in the Responses API.\"\"\"\n\nfrom __future__ import annotations\n\nimport pytest\nimport pytest_asyncio\nfrom openai import OpenAI\nfrom openai_harmony import ToolDescription, ToolNamespaceConfig\n\nfrom tests.utils import RemoteOpenAIServer\nfrom vllm.entrypoints.mcp.tool_server import MCPToolServer\n\nfrom .conftest import (\n BASE_TEST_ENV,\n events_contain_type,\n log_response_diagnostics,\n retry_for_tool_call,\n retry_streaming_for,\n validate_streaming_event_stack,\n)\n\nMODEL_NAME = \"openai/gpt-oss-20b\"\n\n_BASE_SERVER_ARGS = [\n \"--enforce-eager\",\n \"--tool-server\",\n \"demo\",\n \"--max_model_len\",\n \"5000\",\n]\n\n_PYTHON_TOOL_INSTRUCTION = (\n \"You must use the Python tool to execute code. Never simulate execution.\"\n)\n\n\nclass TestMCPToolServerUnit:\n \"\"\"Test MCPToolServer.get_tool_description filtering logic.\n\n Note: The wildcard \"*\" is normalized to None by\n _extract_allowed_tools_from", "label": 0, "sample_id": "vllm-project/vllm:tests/entrypoints/openai/responses/test_mcp_tools.py", "category": "unknown", "repo_id": "vllm-project/vllm"} {"input": "import os\nfrom pathlib import Path\n\nimport pytest\n\nfrom solidlsp import SolidLanguageServer\nfrom solidlsp.ls_config import Language\nfrom solidlsp.ls_types import SymbolKind\nfrom solidlsp.ls_utils import SymbolUtils\n\n\n@pytest.mark.dart\nclass TestDartLanguageServer:\n @pytest.mark.parametrize(\"language_server\", [Language.DART], indirect=True)\n @pytest.mark.parametrize(\"repo_path\", [Language.DART], indirect=True)\n def test_ls_is_running(self, language_server: SolidLanguageServer, repo_path: Path) -> None:\n \"\"\"Test that the language server starts and stops successfully.\"\"\"\n # The fixture already handles start and stop\n assert language_server.is_running()\n assert Path(language_server.language_server.repository_root_path).resolve() == repo_path.resolve()\n\n @pytest.mark.parametrize(\"language_server\", [Language.DART], indirect=True)\n @pytest.mark.parametrize(\"repo_path\", [Language.DART], indirect=True)\n def test_find_definition_within_file(self, language_server: SolidLanguageServer, repo_path: Path) -> None:\n \"\"\"Test finding definition of a method within the same file.\"\"\"\n # In lib/main.dart:\n # Line 105: final result1 = calc.add", "label": 1, "sample_id": "oraios/serena:test/solidlsp/dart/test_dart_basic.py", "category": "test", "repo_id": "oraios/serena"} {"input": "from typing import Any\n\nfrom browser_use.llm.messages import (\n\tAssistantMessage,\n\tBaseMessage,\n\tContentPartImageParam,\n\tContentPartTextParam,\n\tSystemMessage,\n\tUserMessage,\n)\n\n\nclass LiteLLMMessageSerializer:\n\t@staticmethod\n\tdef _serialize_user_content(\n\t\tcontent: str | list[ContentPartTextParam | ContentPartImageParam],\n\t) -> str | list[dict[str, Any]]:\n\t\tif isinstance(content, str):\n\t\t\treturn content\n\n\t\tparts: list[dict[str, Any]] = []\n\t\tfor part in content:\n\t\t\tif part.type == 'text':\n\t\t\t\tparts.append(\n\t\t\t\t\t{\n\t\t\t\t\t\t'type': 'text',\n\t\t\t\t\t\t'text': part.text,\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\telif part.type == 'image_url':\n\t\t\t\tparts.append(\n\t\t\t\t\t{\n\t\t\t\t\t\t'type': 'image_url',\n\t\t\t\t\t\t'image_url': {\n\t\t\t\t\t\t\t'url': part.image_url.url,\n\t\t\t\t\t\t\t'detail': part.image_url.detail,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t)\n\t\treturn parts\n\n\t@staticmethod\n\tdef _serialize_system_content(\n\t\tcontent: str | list[ContentPartTextParam],\n\t) -> str | list[dict[str, Any]]:\n\t\tif isinstance(content,", "label": 0, "sample_id": "browser-use/browser-use:browser_use/llm/litellm/serializer.py", "category": "unknown", "repo_id": "browser-use/browser-use"} {"input": "\"\"\"\nTests for the Apache Iceberg format.\n\nTests in this file use a simple Iceberg catalog based on SQLite, with the same\ndata used for Parquet tests (``pandas/tests/io/data/parquet/simple.parquet``).\n\"\"\"\n\nimport collections\nimport importlib\nimport pathlib\n\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\nfrom pandas.io.iceberg import read_iceberg\n\npytestmark = pytest.mark.single_cpu\n\npyiceberg = pytest.importorskip(\"pyiceberg\")\npyiceberg_catalog = pytest.importorskip(\"pyiceberg.catalog\")\npq = pytest.importorskip(\"pyarrow.parquet\")\n\nCatalog = collections.namedtuple(\"Catalog\", [\"name\", \"uri\", \"warehouse\"])\n\n\n@pytest.fixture\ndef catalog(request, tmp_path):\n # the catalog stores the full path of data files, so the catalog needs to be\n # created dynamically, and not saved in pandas/tests/io/data as other formats\n uri = f\"sqlite:///{tmp_path}/catalog.sqlite\"\n warehouse = f\"file://{tmp_path}\"\n catalog_name = request.param if hasattr(request, \"param\") else None\n catalog = pyiceberg_catalog.load_catalog(\n catalog_name or \"default\",\n ", "label": 1, "sample_id": "pandas-dev/pandas:pandas/tests/io/test_iceberg.py", "category": "test", "repo_id": "pandas-dev/pandas"} {"input": "import argparse\nimport json\nfrom collections import defaultdict\n\nimport numpy as np\nfrom openai import OpenAI\n\nfrom mem0.memory.utils import extract_json\n\nclient = OpenAI()\n\nACCURACY_PROMPT = \"\"\"\nYour task is to label an answer to a question as ’CORRECT’ or ’WRONG’. You will be given the following data:\n (1) a question (posed by one user to another user), \n (2) a ’gold’ (ground truth) answer, \n (3) a generated answer\nwhich you will score as CORRECT/WRONG.\n\nThe point of the question is to ask about something one user should know about the other user based on their prior conversations.\nThe gold answer will usually be a concise and short answer that includes the referenced topic, for example:\nQuestion: Do you remember what I got the last time I went to Hawaii?\nGold answer: A shell necklace\nThe generated answer might be much longer, but you should be generous with your grading - as long as it touches on the same topic as the gold answer, it should be counted as CORRECT. \n\nFor time related questions, the gold answer will be a specific date, month, year, etc. The generated answer might be much longer", "label": 1, "sample_id": "mem0ai/mem0:evaluation/metrics/llm_judge.py", "category": "function_complex", "repo_id": "mem0ai/mem0"} {"input": "# coding=utf-8\n\"\"\"\n @project: maxkb\n @Author:虎\n @file: base_question_node.py\n @date:2024/6/4 14:30\n @desc:\n\"\"\"\nimport json\nimport re\nimport time\nfrom functools import reduce\nfrom typing import List, Dict\n\nfrom application.flow.i_step_node import NodeResult, INode\nfrom application.flow.step_node.ai_chat_step_node.i_chat_node import IChatNode\nfrom application.flow.tools import Reasoning, mcp_response_generator\nfrom application.models import Application, ApplicationApiKey, ApplicationAccessToken\nfrom common.exception.app_exception import AppApiException\nfrom common.utils.rsa_util import rsa_long_decrypt\nfrom common.utils.shared_resource_auth import filter_authorized_ids\nfrom common.utils.tool_code import ToolExecutor\nfrom django.db.models import QuerySet\nfrom django.utils.translation import gettext as _\nfrom langchain_core.messages import BaseMessage, AIMessage, HumanMessage, SystemMessage\nfrom models_provider.models import Model\nfrom models_provider.tools import get_model_credential, get_model_instance_by_model_workspace_id\nfrom tools.models import Tool\n\n\ndef _write_context(node_variable: Dict, workflow_variable: Dict, node: INode, workflow", "label": 0, "sample_id": "1Panel-dev/MaxKB:apps/application/flow/step_node/ai_chat_step_node/impl/base_chat_node.py", "category": "unknown", "repo_id": "1Panel-dev/MaxKB"} {"input": "\"\"\"Imports TreeNodes\"\"\"\n\nfrom algorithms.common.tree_node import TreeNode\n\n\nclass AvlTree:\n \"\"\"\n An avl tree.\n \"\"\"\n\n def __init__(self):\n # Root node of the tree.\n self.node = None\n self.height = -1\n self.balance = 0\n\n def insert(self, key):\n \"\"\"\n Insert new key into node\n \"\"\"\n # Create new node\n node = TreeNode(key)\n if not self.node:\n self.node = node\n self.node.left = AvlTree()\n self.node.right = AvlTree()\n elif key < self.node.val:\n self.node.left.insert(key)\n elif key > self.node.val:\n self.node.right.insert(key)\n self.re_balance()\n\n def re_balance(self):\n \"\"\"\n Re balance tree. After inserting or deleting a node,\n \"\"\"\n self.update_heights(recursive=False)\n self.update_balances(False)\n\n while self.balance < -1 or self.balance > 1:\n if self.balance > 1:\n if self.node.left.balance < 0:\n self.node.left.rotate_left()\n self.update_heights()\n self.update_balances()\n self.rotate_right()\n self.update_height", "label": 0, "sample_id": "keon/algorithms:algorithms/data_structures/avl_tree.py", "category": "unknown", "repo_id": "keon/algorithms"} {"input": "\"\"\"Task key management for SEP-1686 background tasks.\n\nTask keys encode security scoping and metadata in the Docket key format:\n `{session_id}:{client_task_id}:{task_type}:{component_identifier}`\n\nThis format provides:\n- Session-based security scoping (prevents cross-session access)\n- Task type identification (tool/prompt/resource)\n- Component identification (name or URI for result conversion)\n\"\"\"\n\nfrom urllib.parse import quote, unquote\n\n\ndef build_task_key(\n session_id: str,\n client_task_id: str,\n task_type: str,\n component_identifier: str,\n) -> str:\n \"\"\"Build Docket task key with embedded metadata.\n\n Format: `{session_id}:{client_task_id}:{task_type}:{component_identifier}`\n\n The component_identifier is URI-encoded to handle special characters (colons, slashes, etc.).\n\n Args:\n session_id: Session ID for security scoping\n client_task_id: Client-provided task ID\n task_type: Type of task (\"tool\", \"prompt\", \"resource\")\n component_identifier: Tool name, prompt name, or resource URI\n\n Returns:\n Encoded task key for Docket\n\n Examples:\n >>> build_task_key(\"session123\",", "label": 1, "sample_id": "PrefectHQ/fastmcp:src/fastmcp/server/tasks/keys.py", "category": "documentation", "repo_id": "PrefectHQ/fastmcp"} {"input": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\r\n# Copyright 2023-2024 SGLang Team\r\n# Copyright 2025 Search-R1 Contributors\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# Adapted from https://github.com/PeterGriffinJin/Search-R1/blob/main/verl/utils/reward_score/qa_em.py\r\n\r\nimport random\r\nimport re\r\nimport string\r\n\r\n\r\ndef normalize_answer(s):\r\n def remove_articles(text):\r\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\r\n\r\n def white_space_fix(text):\r\n return \" \".join(text.split())\r\n\r\n def remove_punc", "label": 1, "sample_id": "verl-project/verl:verl/utils/reward_score/search_r1_like_qa_em.py", "category": "license", "repo_id": "verl-project/verl"} {"input": "# SPDX-License-Identifier: AGPL-3.0-only\n# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0\n\n\"\"\"\nExport subprocess entry point.\n\nEach export session runs in a persistent subprocess (mp.get_context(\"spawn\")).\nThis gives us a clean Python interpreter with no stale module state —\nsolving the transformers version-switching problem completely.\n\nThe subprocess stays alive while a model is loaded, accepting commands\n(load, export_merged, export_base, export_gguf, export_lora, cleanup,\nshutdown) via mp.Queue.\n\nPattern follows core/inference/worker.py and core/training/worker.py.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport structlog\nfrom loggers import get_logger\nimport os\nimport sys\nimport time\nimport traceback\nfrom pathlib import Path\nfrom typing import Any\n\nlogger = get_logger(__name__)\n\n\ndef _activate_transformers_version(model_name: str) -> None:\n \"\"\"Activate the correct transformers version BEFORE any ML imports.\n\n If the model needs transformers 5.x, prepend the pre-installed .venv_t5/\n directory to sys.path. Otherwise do nothing (default 4.57.x", "label": 0, "sample_id": "unslothai/unsloth:studio/backend/core/export/worker.py", "category": "unknown", "repo_id": "unslothai/unsloth"} {"input": "import numpy as np\nimport torch\n\nimport genesis as gs\nimport genesis.utils.geom as gu\nimport genesis.utils.particle as pu\nfrom genesis.repr_base import RBC\n\n\nclass Emitter(RBC):\n \"\"\"\n A particle emitter for fluid or material simulation.\n\n The Emitter manages the generation of particles into the simulation domain, allowing directional or omnidirectional\n emissions with various droplet shapes. It supports resetting, shape-based emission, and spherical omni-emission.\n\n Parameters\n ----------\n max_particles : int\n The maximum number of particles that this emitter can handle.\n \"\"\"\n\n def __init__(self, max_particles):\n self._uid = gs.UID()\n self._entity = None\n\n self._max_particles = max_particles\n\n self._acc_droplet_len = 0.0 # accumulated droplet length to be emitted\n\n gs.logger.info(\n f\"Creating ~<{self.__repr_name__()}>~. id: ~~~<{self._uid}>~~~, max_particles: ~<{max_particles}>~.\"\n )\n\n def set_entity(self, entity):\n \"\"\"\n Assign an entity to the emitter and initialize relevant simulation and solver references.\n\n Parameters\n ----------\n entity", "label": 0, "sample_id": "Genesis-Embodied-AI/Genesis:genesis/engine/entities/emitter.py", "category": "unknown", "repo_id": "Genesis-Embodied-AI/Genesis"} {"input": "from strix.telemetry.flags import is_otel_enabled, is_posthog_enabled\n\n\ndef test_flags_fallback_to_strix_telemetry(monkeypatch) -> None:\n monkeypatch.delenv(\"STRIX_OTEL_TELEMETRY\", raising=False)\n monkeypatch.delenv(\"STRIX_POSTHOG_TELEMETRY\", raising=False)\n monkeypatch.setenv(\"STRIX_TELEMETRY\", \"0\")\n\n assert is_otel_enabled() is False\n assert is_posthog_enabled() is False\n\n\ndef test_otel_flag_overrides_global_telemetry(monkeypatch) -> None:\n monkeypatch.setenv(\"STRIX_TELEMETRY\", \"0\")\n monkeypatch.setenv(\"STRIX_OTEL_TELEMETRY\", \"1\")\n monkeypatch.delenv(\"STRIX_POSTHOG_TELEMETRY\", raising=False)\n\n assert is_otel_enabled() is True\n assert is_posthog_enabled() is False\n\n\ndef test_posthog_flag_overrides_global_telemetry(monkeypatch) -> None:\n monkeypatch.setenv(\"STRIX_TELEMETRY\", \"0\")\n monkeypatch.setenv(\"STRIX_POSTHOG_TELEMETRY\", \"1\")\n monkeypatch.del", "label": 0, "sample_id": "usestrix/strix:tests/telemetry/test_flags.py", "category": "unknown", "repo_id": "usestrix/strix"} {"input": "# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Adapted from: https://github.com/NVIDIA-NeMo/Curator/blob/main/nemo_curator/stages/deduplication/shuffle_utils/rapidsmpf_shuffler.py\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any, Literal\n\nif TYPE_CHECKING:\n from collections.abc import Iterator\n\n import pylibcudf as plc\n from rapidsmpf.shuffler import Shuffler\n\n\ndef align_down_to_256(value: int) -> int:\n return (value >> 8", "label": 0, "sample_id": "ray-project/ray:python/ray/data/_internal/gpu_shuffle/rapidsmpf_backend.py", "category": "unknown", "repo_id": "ray-project/ray"} {"input": "#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"SSH Remote Job Trigger for deferrable execution.\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nfrom collections.abc import AsyncIterator\nfrom typing import Any, Literal\n\nimport tenacity\n\nfrom airflow.providers.ssh.hooks.ssh import SSHHookAsync\nfrom airflow.providers.ssh.utils.remote_job import (\n build_posix_completion_check_command,\n build_posix_file_size_command,\n ", "label": 1, "sample_id": "apache/airflow:providers/ssh/src/airflow/providers/ssh/triggers/ssh_remote_job.py", "category": "function_complex", "repo_id": "apache/airflow"} {"input": "from typing import TYPE_CHECKING, Any, Optional\n\nimport litellm\nimport pydantic\n\nfrom dspy.adapters.types.base_type import Type\n\nif TYPE_CHECKING:\n from dspy.clients.lm import LM\n from dspy.signatures.signature import Signature\n\n\nclass Reasoning(Type):\n \"\"\"Reasoning type in DSPy.\n\n This type is useful when you want the DSPy output to include the reasoning of the LM. We build this type so that\n DSPy can support the reasoning model and non-reasoning model with the same code.\n\n This is a str-like type, you can convert a string directly to a Reasoning object, and from DSPy adapters'\n perspective, `Reasoning` is treated as a string.\n \"\"\"\n\n content: str\n\n def format(self):\n return f\"{self.content}\"\n\n @pydantic.model_validator(mode=\"before\")\n @classmethod\n def validate_input(cls, data: Any):\n if isinstance(data, cls):\n return data\n\n if isinstance(data, str):\n return {\"content\": data}\n\n if isinstance(data, dict):\n if \"content\" not in data:\n raise ValueError(\"`content` field is required for `dspy.Reasoning", "label": 1, "sample_id": "stanfordnlp/dspy:dspy/adapters/types/reasoning.py", "category": "function_complex", "repo_id": "stanfordnlp/dspy"} {"input": "\"\"\"Config flow for the Namecheap DynamicDNS integration.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Mapping\nimport logging\nfrom typing import Any\n\nfrom aiohttp import ClientError\nimport voluptuous as vol\n\nfrom homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult\nfrom homeassistant.const import CONF_DOMAIN, CONF_HOST, CONF_NAME, CONF_PASSWORD\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.helpers.aiohttp_client import async_get_clientsession\nfrom homeassistant.helpers.selector import (\n TextSelector,\n TextSelectorConfig,\n TextSelectorType,\n)\n\nfrom .const import DOMAIN\nfrom .helpers import AuthFailed, update_namecheapdns\nfrom .issue import deprecate_yaml_issue\n\n_LOGGER = logging.getLogger(__name__)\n\n\nSTEP_USER_DATA_SCHEMA = vol.Schema(\n {\n vol.Required(CONF_HOST, default=\"@\"): cv.string,\n vol.Required(CONF_DOMAIN): cv.string,\n vol.Required(CONF_PASSWORD): TextSelector(\n TextSelectorConfig(\n type=TextSelectorType.PASSWORD, autocomplete=\"current-password\"\n )\n ),\n }\n)\n\nSTEP_RECONFIGURE_DATA_SCHEMA = vol.Schema(\n {\n vol.Required(CONF_PASSWORD): TextSelector(\n TextSelectorConfig", "label": 1, "sample_id": "home-assistant/core:homeassistant/components/namecheapdns/config_flow.py", "category": "function_complex", "repo_id": "home-assistant/core"} {"input": "from __future__ import annotations\n\nimport argparse\nimport json\nimport os\nimport typing as t\n\nimport pytest\nimport pytest_mock\n\nif t.TYPE_CHECKING:\n from ansible_test._internal.ci.azp import AzurePipelinesChanges\n\n\ndef create_azure_pipelines_changes(mocker: pytest_mock.MockerFixture) -> AzurePipelinesChanges:\n \"\"\"Prepare an AzurePipelinesChanges instance for testing.\"\"\"\n from ansible_test._internal.ci.azp import AzurePipelinesChanges\n from ansible_test._internal.config import CommonConfig\n\n namespace = argparse.Namespace()\n namespace.color = False\n namespace.explain = False\n namespace.verbosity = False\n namespace.debug = False\n namespace.truncate = False\n namespace.redact = False\n namespace.display_traceback = False\n\n config = CommonConfig(namespace, 'sanity')\n\n env = dict(\n HOME=os.environ['HOME'],\n SYSTEM_COLLECTIONURI='https://dev.azure.com/ansible/',\n SYSTEM_TEAMPROJECT='ansible',\n BUILD_REPOSITORY_PROVIDER='GitHub',\n BUILD_SOURCEBRANCH='devel',\n BUILD_SOURCEBRANCHNAME='devel',\n )\n\n mocker.patch.dict(os.environ, env, clear=True)\n\n return AzurePipelinesChanges(config", "label": 1, "sample_id": "ansible/ansible:test/units/ansible_test/_internal/ci/test_azp.py", "category": "test", "repo_id": "ansible/ansible"} {"input": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\nfrom importlib.util import find_spec\n\nimport pytest\nimport torch\n\nimport vllm.envs as envs\nfrom tests.compile.backend import TestBackend\nfrom tests.utils import TestFP8Layer, has_module_attribute, multi_gpu_test\nfrom vllm._custom_ops import cutlass_scaled_fp4_mm, scaled_fp4_quant\nfrom vllm.compilation.passes.fusion.allreduce_rms_fusion import AllReduceFusionPass\nfrom vllm.compilation.passes.utility.fix_functionalization import (\n FixFunctionalizationPass,\n)\nfrom vllm.compilation.passes.utility.noop_elimination import NoOpEliminationPass\nfrom vllm.compilation.passes.utility.post_cleanup import PostCleanupPass\nfrom vllm.config import (\n CompilationConfig,\n CompilationMode,\n DeviceConfig,\n ModelConfig,\n PassConfig,\n VllmConfig,\n set_current_vllm_config,\n)\nfrom vllm.distributed import tensor_model_parallel_all_reduce\nfrom vllm.distributed.parallel_state import (\n init_distributed_environment,\n initialize_model_parallel,\n)\nfrom v", "label": 0, "sample_id": "vllm-project/vllm:tests/compile/passes/distributed/test_fusion_all_reduce.py", "category": "unknown", "repo_id": "vllm-project/vllm"} {"input": "import shutil\nfrom collections.abc import Generator\nfrom pathlib import Path\n\nimport pytest\n\nimport reflex as rx\nimport reflex.constants as constants\nfrom reflex.assets import remove_stale_external_asset_symlinks\n\n\n@pytest.fixture\ndef mock_asset_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:\n \"\"\"Create a mock asset file and patch the current working directory.\n\n Args:\n tmp_path: A temporary directory provided by pytest.\n monkeypatch: A pytest fixture for patching.\n\n Returns:\n The path to a tmp cwd that will be used for assets.\n \"\"\"\n # Create a temporary directory to act as the current working directory.\n mock_cwd = tmp_path / \"mock_asset_path\"\n mock_cwd.mkdir()\n monkeypatch.chdir(mock_cwd)\n\n return mock_cwd\n\n\ndef test_shared_asset(mock_asset_path: Path) -> None:\n \"\"\"Test shared assets.\"\"\"\n # The asset function copies a file to the app's external assets directory.\n asset = rx.asset(path=\"custom_script.js\", shared=True, subfolder=\"subfolder\")\n assert asset == \"/external/test_assets/subfolder/custom_script.js\"\n result_file = Path(\n mock_asset_path,\n \"assets\",\n \"", "label": 0, "sample_id": "reflex-dev/reflex:tests/units/assets/test_assets.py", "category": "unknown", "repo_id": "reflex-dev/reflex"} {"input": "\"\"\"\nAgentOS Demo\n\nPrerequisites:\nuv pip install -U fastapi uvicorn sqlalchemy pgvector psycopg openai ddgs\n\"\"\"\n\nfrom agno import __version__ as agno_version\nfrom agno.agent import Agent\nfrom agno.db.postgres import PostgresDb\nfrom agno.knowledge.knowledge import Knowledge\nfrom agno.models.openai import OpenAIChat\nfrom agno.os import AgentOS\nfrom agno.os.interfaces.a2a import A2A\nfrom agno.os.interfaces.agui import AGUI\nfrom agno.os.interfaces.slack import Slack\nfrom agno.os.interfaces.telegram import Telegram\nfrom agno.os.interfaces.whatsapp import Whatsapp\nfrom agno.registry import Registry\nfrom agno.team import Team\nfrom agno.tools.mcp import MCPTools\nfrom agno.vectordb.pgvector import PgVector\nfrom agno.workflow import Workflow\nfrom agno.workflow.step import Step\n\n# ---------------------------------------------------------------------------\n# Create Example\n# ---------------------------------------------------------------------------\n\n# Database connection\ndb_url = \"postgresql+psycopg://ai:ai@localhost:5532/ai\"\n\n# Create Postgres-backed memory store\ndb = PostgresDb(db_url=db_url)\n\n# Create Postgres-backed vector store\nvector_db = Pg", "label": 0, "sample_id": "agno-agi/agno:cookbook/05_agent_os/interfaces/all_interfaces.py", "category": "unknown", "repo_id": "agno-agi/agno"} {"input": "\"\"\"\nConstruct Tree from Preorder and Postorder Traversal\n\nGiven preorder and postorder traversals of a full binary tree, construct the\ntree and return its inorder traversal. A full binary tree has either zero or\ntwo children per node.\n\nReference: https://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees\n\nComplexity:\n Time: O(n^2) due to linear search in postorder array\n Space: O(n) for the constructed tree\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom algorithms.common.tree_node import TreeNode\n\npre_index = 0\n\n\ndef construct_tree_util(\n pre: list[int], post: list[int], low: int, high: int, size: int\n) -> TreeNode | None:\n \"\"\"Recursively construct a binary tree from preorder and postorder arrays.\n\n Uses a global pre_index to track the current position in the preorder\n array during recursive construction.\n\n Args:\n pre: The preorder traversal array.\n post: The postorder traversal array.\n low: The lower bound index in the postorder array.\n high: The upper bound index in the postorder array.\n size: The total number of elements.\n\n Returns:\n The root of the constructed subtree,", "label": 0, "sample_id": "keon/algorithms:algorithms/tree/construct_tree_postorder_preorder.py", "category": "unknown", "repo_id": "keon/algorithms"} {"input": "# Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of NVIDIA CORPORATION nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n", "label": 1, "sample_id": "FunAudioLLM/CosyVoice:runtime/triton_trtllm/model_repo/speaker_embedding/1/model.py", "category": "function_complex", "repo_id": "FunAudioLLM/CosyVoice"} {"input": "\"\"\"\nCopyright 2024, Zep Software, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport json\nimport logging\nfrom typing import Any, ClassVar\n\nfrom openai import AsyncAzureOpenAI, AsyncOpenAI\nfrom openai.types.chat import ChatCompletionMessageParam\nfrom pydantic import BaseModel\n\nfrom .config import DEFAULT_MAX_TOKENS, LLMConfig\nfrom .openai_base_client import BaseOpenAIClient\n\nlogger = logging.getLogger(__name__)\n\n\nclass AzureOpenAILLMClient(BaseOpenAIClient):\n \"\"\"Wrapper class for Azure OpenAI that implements the LLMClient interface.\n\n Supports both AsyncAzureOpenAI and AsyncOpenAI (with Azure v1 API endpoint).\n \"\"\"\n\n # Class-level constants\n MAX", "label": 1, "sample_id": "getzep/graphiti:graphiti_core/llm_client/azure_openai_client.py", "category": "function_complex", "repo_id": "getzep/graphiti"} {"input": "# flags: --minimum-version=3.14\nx = t\"foo\"\nx = t'foo {{ {2 + 2}bar {{ baz'\n\nx = t\"foo {f'abc'} bar\"\n\nx = t\"\"\"foo {{ a\n foo {2 + 2}bar {{ baz\n\n x = f\"foo {{ {\n 2 + 2 # comment\n }bar\"\n\n {{ baz\n\n }} buzz\n\n {print(\"abc\" + \"def\"\n)}\nabc\"\"\"\n\nt'{(abc:=10)}'\n\nt'''This is a really long string, but just make sure that you reflow tstrings {\n 2+2:d\n}'''\nt'This is a really long string, but just make sure that you reflow tstrings correctly {2+2:d}'\n\nt\"{ 2 + 2 = }\"\n\nt'{\nX\n!r\n}'\n\ntr'\\{{\\}}'\n\nt'''\n WITH {f'''\n {1}_cte AS ()'''}\n'''\n\n# output\nx = t\"foo\"\nx = t\"foo {{ {2 + 2}bar {{ baz\"\n\nx = t\"foo {f'", "label": 1, "sample_id": "psf/black:tests/data/cases/pep_750.py", "category": "test", "repo_id": "psf/black"} {"input": "import json\nimport os\nfrom itertools import islice\nfrom typing import Iterable\n\nimport pyarrow as pa\n\nimport datasets\nfrom datasets.builder import Key\n\n\nlogger = datasets.utils.logging.get_logger(__name__)\n\n\nclass Eval(datasets.GeneratorBasedBuilder):\n NUM_EXAMPLES_FOR_FEATURES_INFERENCE = 5\n\n def _info(self):\n return datasets.DatasetInfo()\n\n def _split_generators(self, dl_manager):\n \"\"\"We handle string, list and dicts in datafiles\"\"\"\n if not self.config.data_files:\n raise ValueError(f\"At least one data file must be specified, but got data_files={self.config.data_files}\")\n dl_manager.download_config.extract_on_the_fly = True\n base_data_files = dl_manager.download(self.config.data_files)\n extracted_data_files = dl_manager.extract(base_data_files)\n splits = []\n for split_name, logs in extracted_data_files.items():\n logs_files_iterables = [dl_manager.iter_files(log) for log in logs]\n splits.append(\n datasets.SplitGenerator(\n name=split_name,\n gen_kwargs={\n \"logs_files_iterables\": logs_files_iterables,\n \"base_files\": base_data_files[split_name],\n },\n )\n )\n if not", "label": 1, "sample_id": "huggingface/datasets:src/datasets/packaged_modules/eval/eval.py", "category": "function_complex", "repo_id": "huggingface/datasets"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Custom Components v2 manager and supporting orchestration.\n\nThis module composes the registry, manifest handling, and file watching\ncapabilities for Streamlit's Custom Components v2. It provides a unified\ninterface to register components from manifests or individual definitions, query\ncomponent metadata and asset paths, and react to on-disk changes by re-resolving\ncomponent definitions.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport threading\nfrom dataclasses import dataclass\nfrom typing import TYPE_CHECKING, Final\n\nfrom", "label": 1, "sample_id": "streamlit/streamlit:lib/streamlit/components/v2/component_manager.py", "category": "license", "repo_id": "streamlit/streamlit"} {"input": "from __future__ import annotations\n\nimport numpy as np\nimport numpy.typing as npt\n\nfrom supervision.detection.utils.iou_and_nms import box_iou_batch\n\n\ndef clip_boxes(\n xyxy: npt.NDArray[np.number],\n resolution_wh: tuple[int, int],\n) -> npt.NDArray[np.number]:\n \"\"\"\n Clips bounding boxes coordinates to fit within the frame resolution.\n\n Args:\n xyxy: A numpy array of shape `(N, 4)` where each\n row corresponds to a bounding box in\n the format `(x_min, y_min, x_max, y_max)`.\n resolution_wh: A tuple of the form\n `(width, height)` representing the resolution of the frame.\n\n Returns:\n A numpy array of shape `(N, 4)` where each row\n corresponds to a bounding box with coordinates clipped to fit\n within the frame resolution.\n\n Examples:\n ```pycon\n >>> import numpy as np\n >>> import supervision as sv\n >>> xyxy = np.array([\n ... [10, 20, 300, 200],\n ... [15, 25, 3", "label": 0, "sample_id": "roboflow/supervision:src/supervision/detection/utils/boxes.py", "category": "unknown", "repo_id": "roboflow/supervision"} {"input": "from typing import NotRequired, override\n\nfrom langchain.agents import AgentState\nfrom langchain.agents.middleware import AgentMiddleware\nfrom langgraph.runtime import Runtime\n\nfrom src.agents.thread_state import SandboxState, ThreadDataState\nfrom src.sandbox import get_sandbox_provider\n\n\nclass SandboxMiddlewareState(AgentState):\n \"\"\"Compatible with the `ThreadState` schema.\"\"\"\n\n sandbox: NotRequired[SandboxState | None]\n thread_data: NotRequired[ThreadDataState | None]\n\n\nclass SandboxMiddleware(AgentMiddleware[SandboxMiddlewareState]):\n \"\"\"Create a sandbox environment and assign it to an agent.\n\n Lifecycle Management:\n - With lazy_init=True (default): Sandbox is acquired on first tool call\n - With lazy_init=False: Sandbox is acquired on first agent invocation (before_agent)\n - Sandbox is reused across multiple turns within the same thread\n - Sandbox is NOT released after each agent call to avoid wasteful recreation\n - Cleanup happens at application shutdown via SandboxProvider.shutdown()\n \"\"\"\n\n state_schema = SandboxMiddlewareState\n\n def __init__(self, lazy_init: bool = True):\n \"\"\"Initialize sandbox middleware.\n\n Args:\n lazy_init: If True, defer sandbox acquisition until first tool call.\n If False", "label": 1, "sample_id": "bytedance/deer-flow:backend/src/sandbox/middleware.py", "category": "function_simple", "repo_id": "bytedance/deer-flow"} {"input": "import json\nimport sys\nimport types\nfrom pathlib import Path\nfrom typing import Any, ClassVar\n\nimport pytest\nfrom opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExportResult\n\nfrom strix.telemetry import tracer as tracer_module\nfrom strix.telemetry import utils as telemetry_utils\nfrom strix.telemetry.tracer import Tracer, set_global_tracer\n\n\ndef _load_events(events_path: Path) -> list[dict[str, Any]]:\n lines = events_path.read_text(encoding=\"utf-8\").splitlines()\n return [json.loads(line) for line in lines if line]\n\n\n@pytest.fixture(autouse=True)\ndef _reset_tracer_globals(monkeypatch) -> None:\n monkeypatch.setattr(tracer_module, \"_global_tracer\", None)\n monkeypatch.setattr(tracer_module, \"_OTEL_BOOTSTRAPPED\", False)\n monkeypatch.setattr(tracer_module, \"_OTEL_REMOTE_ENABLED\", False)\n telemetry_utils.reset_events_write_locks()\n monkeypatch.delenv(\"STRIX_TELEMETRY\", raising=False)\n monkeypatch.delenv(\"STRIX_OTEL_TELEMETRY\", raising=False)\n monkeypatch.delenv(\"STRIX_POSTHOG_TELEMETRY\",", "label": 0, "sample_id": "usestrix/strix:tests/telemetry/test_tracer.py", "category": "unknown", "repo_id": "usestrix/strix"} {"input": "# SPDX-License-Identifier: AGPL-3.0-only\n# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0\n\n\"\"\"\nAudio codec loading and decoding for TTS inference.\nSupports: SNAC (Orpheus), CSM (Sesame), BiCodec (Spark), DAC (OuteTTS)\n\"\"\"\n\nimport io\nimport re\nimport wave\nimport structlog\nfrom loggers import get_logger\nfrom typing import Optional, Tuple\n\nimport numpy as np\nimport torch\n\nlogger = get_logger(__name__)\n\n\ndef _numpy_to_wav_bytes(waveform: np.ndarray, sample_rate: int) -> bytes:\n \"\"\"Convert a float32 numpy waveform to WAV bytes (16-bit PCM).\"\"\"\n waveform = waveform.flatten()\n peak = max(abs(waveform.max()), abs(waveform.min()))\n if peak > 1.0:\n waveform = waveform / peak\n pcm = (waveform * 32767).astype(np.int16)\n\n buf = io.BytesIO()\n with wave.open(buf, \"wb\") as wf:\n wf.setnchannels(1)\n wf.set", "label": 0, "sample_id": "unslothai/unsloth:studio/backend/core/inference/audio_codecs.py", "category": "unknown", "repo_id": "unslothai/unsloth"} {"input": "from __future__ import annotations\n\nimport logging\nimport pickle\nimport re\nimport warnings\nfrom hashlib import sha256\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from collections.abc import Callable\n from collections.abc import Iterator\n from datetime import datetime\n\n from numpy import ndarray\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.core.cache import caches\n\nfrom documents.caching import CACHE_5_MINUTES\nfrom documents.caching import CACHE_50_MINUTES\nfrom documents.caching import CLASSIFIER_HASH_KEY\nfrom documents.caching import CLASSIFIER_MODIFIED_KEY\nfrom documents.caching import CLASSIFIER_VERSION_KEY\nfrom documents.caching import StoredLRUCache\nfrom documents.models import Document\nfrom documents.models import MatchingModel\n\nlogger = logging.getLogger(\"paperless.classifier\")\n\nADVANCED_TEXT_PROCESSING_ENABLED = (\n settings.NLTK_LANGUAGE is not None and settings.NLTK_ENABLED\n)\n\nread_cache = caches[\"read-cache\"]\n\n\nRE_DIGIT = re.compile(r\"\\d\")\nRE_WORD = re.compile(r\"\\b[\\w]+\\b\") # words that may contain digits\n\n\nclass IncompatibleClassifierVersionError(Exception):\n def __init__(", "label": 0, "sample_id": "paperless-ngx/paperless-ngx:src/documents/classifier.py", "category": "unknown", "repo_id": "paperless-ngx/paperless-ngx"} {"input": "from django import forms\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ObjectDoesNotExist, ValidationError\nfrom django.db import connection\nfrom django.db.models.signals import post_save\nfrom django.utils.translation import gettext_lazy as _\n\nfrom dcim.constants import LOCATION_SCOPE_TYPES\nfrom dcim.models import PortMapping, PortTemplateMapping, Site\nfrom utilities.forms import get_field_value\nfrom utilities.forms.fields import (\n ContentTypeChoiceField,\n CSVContentTypeField,\n DynamicModelChoiceField,\n)\nfrom utilities.forms.widgets import HTMXSelect\nfrom utilities.templatetags.builtins.filters import bettertitle\n\n__all__ = (\n 'FrontPortFormMixin',\n 'ScopedBulkEditForm',\n 'ScopedForm',\n 'ScopedImportForm',\n)\n\n\nclass ScopedForm(forms.Form):\n scope_type = ContentTypeChoiceField(\n queryset=ContentType.objects.filter(model__in=LOCATION_SCOPE_TYPES),\n widget=HTMXSelect(),\n required=False,\n label=_('Scope type')\n )\n scope = DynamicModelChoiceField(\n label=_('Scope'),\n queryset=Site.objects.none(), # Initial queryset\n required=False,\n disabled=True,\n selector=True\n )\n\n def __init__(self, *args, **kwargs", "label": 0, "sample_id": "netbox-community/netbox:netbox/dcim/forms/mixins.py", "category": "unknown", "repo_id": "netbox-community/netbox"} {"input": "# HumanEval/120\n# Loki Mode Multi-Agent Solution\n# Attempts: 1\n# Passed: True\n\ndef maximum(arr, k):\n \"\"\"\n Given an array arr of integers and a positive integer k, return a sorted list \n of length k with the maximum k numbers in arr.\n\n Example 1:\n\n Input: arr = [-3, -4, 5], k = 3\n Output: [-4, -3, 5]\n\n Example 2:\n\n Input: arr = [4, -4, 4], k = 2\n Output: [4, 4]\n\n Example 3:\n\n Input: arr = [-3, 2, 1, 2, -1, -2, 1], k = 1\n Output: [2]\n\n Note:\n 1. The length of the array will be in the range of [1, 1000].\n 2. The elements in the array will be in the range of [-1000, 1000].\n 3. 0 <= k <= len(arr)\n \"\"\"\n if k == 0:\n return []\n return sorted", "label": 1, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/humaneval-loki-solutions/120.py", "category": "documentation", "repo_id": "davila7/claude-code-templates"} {"input": "\"\"\"Anthropic prompt caching middleware.\n\nRequires:\n - `langchain`: For agent middleware framework\n - `langchain-anthropic`: For `ChatAnthropic` model (already a dependency)\n\"\"\"\n\nfrom collections.abc import Awaitable, Callable\nfrom typing import Literal\nfrom warnings import warn\n\nfrom langchain_anthropic.chat_models import ChatAnthropic\n\ntry:\n from langchain.agents.middleware.types import (\n AgentMiddleware,\n ModelCallResult,\n ModelRequest,\n ModelResponse,\n )\nexcept ImportError as e:\n msg = (\n \"AnthropicPromptCachingMiddleware requires 'langchain' to be installed. \"\n \"This middleware is designed for use with LangChain agents. \"\n \"Install it with: pip install langchain\"\n )\n raise ImportError(msg) from e\n\n\nclass AnthropicPromptCachingMiddleware(AgentMiddleware):\n \"\"\"Prompt Caching Middleware.\n\n Optimizes API usage by caching conversation prefixes for Anthropic models.\n\n Requires both `langchain` and `langchain-anthropic` packages to be installed.\n\n Learn more about Anthropic prompt caching\n [here](https://platform.claude.com/docs/en/build-with-claude/prompt-caching).\n \"\"\"\n\n def", "label": 1, "sample_id": "langchain-ai/langchain:libs/partners/anthropic/langchain_anthropic/middleware/prompt_caching.py", "category": "function_complex", "repo_id": "langchain-ai/langchain"} {"input": "from dataclasses import dataclass\nfrom itertools import product\nfrom operator import itemgetter\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_allclose\nfrom scipy.sparse import csc_array\nfrom scipy.special import xlogy\n\nfrom sklearn.metrics import mean_poisson_deviance\nfrom sklearn.tree import (\n DecisionTreeClassifier,\n DecisionTreeRegressor,\n ExtraTreeClassifier,\n ExtraTreeRegressor,\n)\nfrom sklearn.utils.stats import _weighted_percentile\n\nCLF_CRITERIONS = (\"gini\", \"log_loss\")\n\nREG_CRITERIONS = (\"squared_error\", \"absolute_error\", \"poisson\")\n\nCLF_TREES = {\n \"DecisionTreeClassifier\": DecisionTreeClassifier,\n \"ExtraTreeClassifier\": ExtraTreeClassifier,\n}\n\nREG_TREES = {\n \"DecisionTreeRegressor\": DecisionTreeRegressor,\n \"ExtraTreeRegressor\": ExtraTreeRegressor,\n}\n\n\n@dataclass\nclass NaiveSplitter:\n criterion: str\n n_classes: int = 0\n\n def compute_node_value_and_impurity(self, y, w):\n sum_weights = np.sum(w)\n if sum_weights < 1e-7:\n return np.nan, np.inf # invalid split\n if self.c", "label": 1, "sample_id": "scikit-learn/scikit-learn:sklearn/tree/tests/test_split.py", "category": "test", "repo_id": "scikit-learn/scikit-learn"} {"input": "\"\"\"Utils for built-in HTTP download handlers.\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import ABC\nfrom contextlib import contextmanager\nfrom typing import TYPE_CHECKING, Any\n\nfrom twisted.internet.defer import CancelledError\nfrom twisted.internet.error import ConnectionRefusedError as TxConnectionRefusedError\nfrom twisted.internet.error import DNSLookupError\nfrom twisted.internet.error import TimeoutError as TxTimeoutError\nfrom twisted.python.failure import Failure\nfrom twisted.web.client import ResponseFailed\nfrom twisted.web.error import SchemeNotSupported\n\nfrom scrapy import responsetypes\nfrom scrapy.core.downloader.handlers.base import BaseDownloadHandler\nfrom scrapy.exceptions import (\n CannotResolveHostError,\n DownloadCancelledError,\n DownloadConnectionRefusedError,\n DownloadFailedError,\n DownloadTimeoutError,\n StopDownload,\n UnsupportedURLSchemeError,\n)\nfrom scrapy.utils.log import logger\n\nif TYPE_CHECKING:\n from collections.abc import Iterator\n from ipaddress import IPv4Address, IPv6Address\n\n from twisted.internet.ssl import Certificate\n\n from scrapy import Request\n from scrapy.crawler import Crawler\n from scrapy.http import Headers, Response\n\n\nclass BaseHttpDownloadHandler(BaseDownloadHandler, ABC):\n \"\"\"Base class for built-in HTTP download", "label": 1, "sample_id": "scrapy/scrapy:scrapy/utils/_download_handlers.py", "category": "function_complex", "repo_id": "scrapy/scrapy"} {"input": "import os\nfrom pathlib import Path\n\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom inline_snapshot import snapshot\n\nfrom tests.utils import workdir_lock\n\n\n@pytest.fixture(scope=\"module\")\ndef client():\n static_dir: Path = Path(os.getcwd()) / \"static\"\n static_dir.mkdir(exist_ok=True)\n sample_file = static_dir / \"sample.txt\"\n sample_file.write_text(\"This is a sample static file.\")\n from docs_src.static_files.tutorial001_py310 import app\n\n with TestClient(app) as client:\n yield client\n sample_file.unlink()\n static_dir.rmdir()\n\n\n@workdir_lock\ndef test_static_files(client: TestClient):\n response = client.get(\"/static/sample.txt\")\n assert response.status_code == 200, response.text\n assert response.text == \"This is a sample static file.\"\n\n\n@workdir_lock\ndef test_static_files_not_found(client: TestClient):\n response = client.get(\"/static/non_existent_file.txt\")\n assert response.status_code == 404, response.text\n\n\n@workdir_lock\ndef test_openapi_schema(client: TestClient):\n response = client.get(\"/openapi.json\")\n assert response.status_code", "label": 1, "sample_id": "fastapi/fastapi:tests/test_tutorial/test_static_files/test_tutorial001.py", "category": "test", "repo_id": "fastapi/fastapi"} {"input": "## taken from: https://github.com/yarikoptic/nitest-balls1/blob/2cd07d86e2cc2d3c612d5d4d659daccd7a58f126/NIFTI/T1.nii.gz\n\nfrom pathlib import Path\n\nimport pyarrow as pa\nimport pytest\n\nfrom datasets import Dataset, Features, Nifti, load_dataset\nfrom src.datasets.features.nifti import encode_nibabel_image\n\nfrom ..utils import require_nibabel\n\n\n@require_nibabel\n@pytest.mark.parametrize(\"nifti_file\", [\"test_nifti.nii\", \"test_nifti.nii.gz\"])\n@pytest.mark.parametrize(\n \"build_example\",\n [\n lambda nifti_path: nifti_path,\n lambda nifti_path: Path(nifti_path),\n lambda nifti_path: open(nifti_path, \"rb\").read(),\n lambda nifti_path: {\"path\": nifti_path},\n lambda nifti_path: {\"path\": nifti_path, \"bytes\": None},\n lambda nifti_path: {\"path\": nifti_path, \"bytes\": open(nifti_path,", "label": 1, "sample_id": "huggingface/datasets:tests/features/test_nifti.py", "category": "test", "repo_id": "huggingface/datasets"} {"input": "#!/usr/bin/env python\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\nfrom collections.abc import Iterator\n\nimport torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass EpisodeAwareSampler:\n def __init__(\n self,\n dataset_from_indices: list[int],\n dataset_to_indices: list[int],\n episode_indices_to_use: list | None = None,\n drop_n_first_frames: int = 0,\n drop_n_last_frames: int = 0,\n shuffle: bool = False,\n ):\n \"\"\"Sampler that optionally incorporates episode boundary information.\n\n Args:\n dataset_from_indices: List", "label": 0, "sample_id": "huggingface/lerobot:src/lerobot/datasets/sampler.py", "category": "unknown", "repo_id": "huggingface/lerobot"} {"input": "import os\nimport time\nfrom dataclasses import dataclass\nfrom enum import Enum\n\nimport mlx.core as mx\nfrom anyio import WouldBlock\nfrom mlx_lm.tokenizer_utils import TokenizerWrapper\n\nfrom exo.shared.models.model_cards import ModelTask\nfrom exo.shared.types.chunks import (\n ErrorChunk,\n TokenChunk,\n ToolCallChunk,\n)\nfrom exo.shared.types.common import CommandId, ModelId\nfrom exo.shared.types.events import (\n ChunkGenerated,\n Event,\n RunnerStatusUpdated,\n TaskAcknowledged,\n TaskStatusUpdated,\n)\nfrom exo.shared.types.mlx import Model\nfrom exo.shared.types.tasks import (\n ConnectToGroup,\n LoadModel,\n Shutdown,\n StartWarmup,\n Task,\n TaskId,\n TaskStatus,\n TextGeneration,\n)\nfrom exo.shared.types.worker.instances import BoundInstance\nfrom exo.shared.types.worker.runner_response import (\n GenerationResponse,\n ToolCallResponse,\n)\nfrom exo.shared.types.worker.runners import (\n RunnerConnected,\n RunnerConnecting,\n RunnerFailed,\n RunnerIdle,\n RunnerLoaded,\n RunnerLoading,\n RunnerReady,\n RunnerRunning,\n RunnerShutdown,\n RunnerShuttingDown,\n RunnerStatus", "label": 0, "sample_id": "exo-explore/exo:src/exo/worker/runner/llm_inference/runner.py", "category": "unknown", "repo_id": "exo-explore/exo"} {"input": "\"\"\"\nTests for the pip binary provider plugin.\n\nTests cover:\n1. Hook script execution\n2. pip package detection\n3. Virtual environment handling\n4. JSONL output format\n\"\"\"\n\nimport json\nimport os\nimport subprocess\nimport sys\nimport tempfile\nfrom pathlib import Path\nfrom unittest.mock import patch, MagicMock\n\nimport pytest\nfrom django.test import TestCase\n\n\n# Get the path to the pip provider hook\nPLUGIN_DIR = Path(__file__).parent.parent\nINSTALL_HOOK = next(PLUGIN_DIR.glob('on_Binary__*_pip_install.py'), None)\n\n\nclass TestPipProviderHook(TestCase):\n \"\"\"Test the pip binary provider installation hook.\"\"\"\n\n def setUp(self):\n \"\"\"Set up test environment.\"\"\"\n self.temp_dir = tempfile.mkdtemp()\n self.output_dir = Path(self.temp_dir) / 'output'\n self.output_dir.mkdir()\n self.lib_dir = Path(self.temp_dir) / 'lib' / 'x86_64-linux'\n self.lib_dir.mkdir(parents=True, exist_ok=True)\n self.lib_dir = Path(self.temp_dir) / 'lib' / 'x86_64-linux'\n self.lib_dir.mkdir(parents=True, exist_ok=True)\n\n def tearDown(self):\n \"\"\"", "label": 1, "sample_id": "ArchiveBox/ArchiveBox:archivebox/plugins/pip/tests/test_pip_provider.py", "category": "test", "repo_id": "ArchiveBox/ArchiveBox"} {"input": "t = (\n {\"foo\": \"very long string\", \"bar\": \"another very long string\", \"baz\": \"we should run out of space by now\"}, # fmt: skip\n {\"foo\": \"bar\"},\n)\n\nt = (\n {\n \"foo\": \"very long string\",\n \"bar\": \"another very long string\",\n \"baz\": \"we should run out of space by now\",\n }, # fmt: skip\n {\"foo\": \"bar\"},\n)\n\n\nt = (\n {\"foo\": \"very long string\", \"bar\": \"another very long string\", \"baz\": \"we should run out of space by now\"}, # fmt: skip\n {\"foo\": \"bar\",},\n)\n\nt = (\n {\n \"foo\": \"very long string\",\n \"bar\": \"another very long string\",\n \"baz\": \"we should run out of space by now\",\n }, # fmt: skip\n {\"foo\": \"bar\",},\n)\n\n# output\nt = (\n {\"foo\": \"very long string\", \"bar\": \"another very long string\", \"baz\": \"we should run out of space by now\"}, # fmt: skip\n {\"foo\": \"bar\"},\n", "label": 1, "sample_id": "psf/black:tests/data/cases/fmtskip13.py", "category": "test", "repo_id": "psf/black"} {"input": "from pathlib import Path\n\nfrom lightrag.api.runtime_validation import (\n RuntimeEnvironment,\n validate_runtime_target,\n validate_runtime_target_from_env_file,\n)\n\n\ndef test_validate_runtime_target_skips_when_not_declared() -> None:\n is_valid, error_message = validate_runtime_target(None)\n\n assert is_valid is True\n assert error_message is None\n\n\ndef test_validate_runtime_target_accepts_host_on_host() -> None:\n is_valid, error_message = validate_runtime_target(\n \"host\",\n RuntimeEnvironment(\n in_container=False,\n in_docker=False,\n in_kubernetes=False,\n ),\n )\n\n assert is_valid is True\n assert error_message is None\n\n\ndef test_validate_runtime_target_rejects_host_in_container() -> None:\n is_valid, error_message = validate_runtime_target(\n \"host\",\n RuntimeEnvironment(\n in_container=True,\n in_docker=True,\n in_kubernetes=False,\n ),\n )\n\n assert is_valid is False\n assert \"\\n\" in error_message\n assert \"Configuration error in .env\" in error_message\n assert \"LIGHTRAG_RUNTIME_TARGET=host\" in error_message\n assert \"This value from .env\" in error_message\n assert", "label": 0, "sample_id": "HKUDS/LightRAG:tests/test_runtime_target_validation.py", "category": "unknown", "repo_id": "HKUDS/LightRAG"} {"input": "#!/usr/bin/env python3\n\"\"\" Default configurations for models \"\"\"\n\nimport gettext\nimport logging\nimport os\n\nfrom dataclasses import dataclass\n\nfrom lib.config import ConfigItem, FaceswapConfig, GlobalSection\nfrom plugins.plugin_loader import PluginLoader\nfrom plugins.train.trainer import trainer_config\n\n# LOCALES\n_LANG = gettext.translation(\"plugins.train._config\", localedir=\"locales\", fallback=True)\n_ = _LANG.gettext\n\nlogger = logging.getLogger(__name__)\n\n\n_ADDITIONAL_INFO = _(\"\\nNB: Unless specifically stated, values changed here will only take effect \"\n \"when creating a new model.\")\n\n\nclass _Config(FaceswapConfig):\n \"\"\" Config File for Models \"\"\"\n # pylint:disable=too-many-statements\n def set_defaults(self, helptext=\"\") -> None:\n \"\"\" Set the default values for config \"\"\"\n super().set_defaults(helptext=_(\"Options that apply to all models\") + _ADDITIONAL_INFO)\n self._defaults_from_plugin(os.path.dirname(__file__))\n\n train_helptext, section, train_opts = trainer_config.get_defaults()\n self.add_section(section, train_helptext)\n for k, v in train_opts.items():\n self.add_item", "label": 1, "sample_id": "deepfakes/faceswap:plugins/train/train_config.py", "category": "function_complex", "repo_id": "deepfakes/faceswap"} {"input": "\"\"\"\nThis file serves as a documentation example and CI test for autoscaling data parallel attention deployment.\n\nStructure:\n1. Monkeypatch setup: Ensures serve.run is non-blocking and removes accelerator requirements for CI testing.\n2. Docs example (between __dp_autoscaling_example_start/end__): Embedded in Sphinx docs via literalinclude.\n3. Test validation (deployment status polling + cleanup)\n\"\"\"\n\nimport time\nfrom ray import serve\nfrom ray.serve.schema import ApplicationStatus\nfrom ray.serve._private.constants import SERVE_DEFAULT_APP_NAME\nfrom ray.serve import llm\n\n_original_serve_run = serve.run\n_original_build_dp_openai_app = llm.build_dp_openai_app\n\n\ndef _non_blocking_serve_run(app, **kwargs):\n \"\"\"Forces blocking=False for testing\"\"\"\n kwargs[\"blocking\"] = False\n return _original_serve_run(app, **kwargs)\n\n\ndef _testing_build_dp_openai_app(builder_config, **kwargs):\n \"\"\"Removes accelerator requirements for testing\"\"\"\n if \"llm_config\" in builder_config:\n config = builder_config[\"llm_config\"]\n if hasattr(config, \"accelerator_type\") and config.accelerator_type is not None:\n config.accelerator_type = None\n return _original", "label": 0, "sample_id": "ray-project/ray:doc/source/llm/doc_code/serve/multi_gpu/dp_autoscaling_example.py", "category": "unknown", "repo_id": "ray-project/ray"} {"input": "\"\"\"File discovery and module import utilities for filesystem-based routing.\n\nThis module provides functions to:\n1. Discover Python files in a directory tree\n2. Import modules (as packages if __init__.py exists, else directly)\n3. Extract decorated components (Tool, Resource, Prompt objects) from imported modules\n\"\"\"\n\nfrom __future__ import annotations\n\nimport importlib.util\nimport sys\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom types import ModuleType\n\nfrom fastmcp.utilities.components import FastMCPComponent\nfrom fastmcp.utilities.logging import get_logger\n\nlogger = get_logger(__name__)\n\n\n@dataclass\nclass DiscoveryResult:\n \"\"\"Result of filesystem discovery.\"\"\"\n\n # Components are real objects (Tool, Resource, ResourceTemplate, Prompt)\n components: list[tuple[Path, FastMCPComponent]] = field(default_factory=list)\n failed_files: dict[Path, str] = field(default_factory=dict) # path -> error message\n\n\ndef discover_files(root: Path) -> list[Path]:\n \"\"\"Recursively discover all Python files under a directory.\n\n Excludes __init__.py files (they're for package structure, not components).\n\n Args:\n root: Root directory to scan.\n\n Returns", "label": 0, "sample_id": "PrefectHQ/fastmcp:src/fastmcp/server/providers/filesystem_discovery.py", "category": "unknown", "repo_id": "PrefectHQ/fastmcp"} {"input": "from typing import Annotated\n\nfrom annotated_doc import Doc\nfrom fastapi.openapi.models import APIKey, APIKeyIn\nfrom fastapi.security.base import SecurityBase\nfrom starlette.exceptions import HTTPException\nfrom starlette.requests import Request\nfrom starlette.status import HTTP_401_UNAUTHORIZED\n\n\nclass APIKeyBase(SecurityBase):\n model: APIKey\n\n def __init__(\n self,\n location: APIKeyIn,\n name: str,\n description: str | None,\n scheme_name: str | None,\n auto_error: bool,\n ):\n self.auto_error = auto_error\n\n self.model: APIKey = APIKey(\n **{\"in\": location}, # ty: ignore[invalid-argument-type]\n name=name,\n description=description,\n )\n self.scheme_name = scheme_name or self.__class__.__name__\n\n def make_not_authenticated_error(self) -> HTTPException:\n \"\"\"\n The WWW-Authenticate header is not standardized for API Key authentication but\n the HTTP specification requires that an error of 401 \"Unauthorized\" must\n include a WWW-Authenticate header.\n\n Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-", "label": 0, "sample_id": "fastapi/fastapi:fastapi/security/api_key.py", "category": "unknown", "repo_id": "fastapi/fastapi"} {"input": "from textual.app import App, ComposeResult\nfrom textual.containers import Grid\nfrom textual.widgets import Footer, Markdown, Placeholder\n\nHELP = \"\"\"\\\n## Breakpoints\n\nA demonstration of how to make an app respond to the dimensions of the terminal.\n\nTry resizing the terminal, then have a look at the source to see how it works!\n\"\"\"\n\n\nclass BreakpointApp(App):\n\n # A breakpoint consists of a width and a class name to set\n HORIZONTAL_BREAKPOINTS = [\n (0, \"-narrow\"),\n (40, \"-normal\"),\n (80, \"-wide\"),\n (120, \"-very-wide\"),\n ]\n\n CSS = \"\"\"\n Screen { \n Placeholder { padding: 2; }\n Grid { grid-rows: auto; height: auto; }\n # Change the styles according to the breakpoint classes\n &.-narrow {\n Grid { grid-size: 1; }\n }\n &.-normal {\n Grid { grid-size: 2; }\n }\n &.-wide {\n Grid { grid-size: 4; }\n }\n &.-very-wide {\n Grid { grid-size: 6; }\n }\n }\n \"\"\"\n\n def compose(self) ->", "label": 1, "sample_id": "Textualize/textual:examples/breakpoints.py", "category": "documentation", "repo_id": "Textualize/textual"} {"input": "\"\"\"\nGraph Traversal Algorithms\n\nProvides DFS and BFS traversal of a graph represented as an adjacency\ndictionary.\n\nComplexity:\n Time: O(V + E)\n Space: O(V)\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import deque\nfrom typing import Any\n\n\ndef dfs_traverse(graph: dict[Any, list[Any]], start: Any) -> set[Any]:\n \"\"\"Traverse the graph from *start* using iterative DFS.\n\n Args:\n graph: Adjacency list.\n start: Starting node.\n\n Returns:\n Set of visited nodes.\n\n Examples:\n >>> sorted(dfs_traverse({'a': ['b'], 'b': []}, 'a'))\n ['a', 'b']\n \"\"\"\n visited: set[Any] = set()\n stack = [start]\n while stack:\n node = stack.pop()\n if node not in visited:\n visited.add(node)\n for next_node in graph[node]:\n if next_node not in visited:\n stack.append(next_node)\n return visited\n\n\ndef bfs_traverse(graph: dict[Any, list[Any]], start: Any) -> set[Any]:\n \"\"\"Traverse the graph from *start* using BFS.\n\n Args:\n graph: Adjacency list.\n ", "label": 0, "sample_id": "keon/algorithms:algorithms/graph/traversal.py", "category": "unknown", "repo_id": "keon/algorithms"} {"input": "from typing_extensions import override\nfrom comfy_api.latest import ComfyExtension, io\n\n\nclass ColorToRGBInt(io.ComfyNode):\n @classmethod\n def define_schema(cls) -> io.Schema:\n return io.Schema(\n node_id=\"ColorToRGBInt\",\n display_name=\"Color to RGB Int\",\n category=\"utils\",\n description=\"Convert a color to a RGB integer value.\",\n inputs=[\n io.Color.Input(\"color\"),\n ],\n outputs=[\n io.Int.Output(display_name=\"rgb_int\"),\n ],\n )\n\n @classmethod\n def execute(\n cls,\n color: str,\n ) -> io.NodeOutput:\n # expect format #RRGGBB\n if len(color) != 7 or color[0] != \"#\":\n raise ValueError(\"Color must be in format #RRGGBB\")\n r = int(color[1:3], 16)\n g = int(color[3:5], 16)\n b = int(color[5:7], 16)\n return io.NodeOutput(r * 256 * 256 + g * 256 + b)\n\n\nclass ColorExtension(ComfyExtension):\n @override\n async", "label": 1, "sample_id": "Comfy-Org/ComfyUI:comfy_extras/nodes_color.py", "category": "function_simple", "repo_id": "Comfy-Org/ComfyUI"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, cast\n\nfrom streamlit.elements.lib.layout_utils import validate_width\nfrom streamlit.proto.Alert_pb2 import Alert as AlertProto\nfrom streamlit.proto.WidthConfig_pb2 import WidthConfig\nfrom streamlit.runtime.metrics_util import gather_metrics\nfrom streamlit.string_util import (\n clean_text,\n extract_leading_icon,\n validate_icon_or_emoji,\n)\n\nif TYPE_CHECKING:\n from streamlit.delta_generator import DeltaGenerator", "label": 0, "sample_id": "streamlit/streamlit:lib/streamlit/elements/alert.py", "category": "unknown", "repo_id": "streamlit/streamlit"} {"input": "\"\"\"\nEA-compatible analogue to np.putmask\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import (\n TYPE_CHECKING,\n Any,\n)\n\nimport numpy as np\n\nfrom pandas._libs import lib\n\nfrom pandas.core.dtypes.cast import infer_dtype_from\nfrom pandas.core.dtypes.common import is_list_like\n\nfrom pandas.core.arrays import ExtensionArray\n\nif TYPE_CHECKING:\n from pandas._typing import (\n ArrayLike,\n npt,\n )\n\n from pandas import MultiIndex\n\n\ndef putmask_inplace(values: ArrayLike, mask: npt.NDArray[np.bool_], value: Any) -> None:\n \"\"\"\n ExtensionArray-compatible implementation of np.putmask. The main\n difference is we do not handle repeating or truncating like numpy.\n\n Parameters\n ----------\n values: np.ndarray or ExtensionArray\n mask : np.ndarray[bool]\n We assume extract_bool_array has already been called.\n value : Any\n \"\"\"\n\n if (\n not isinstance(values, np.ndarray)\n or (values.dtype == object and not lib.is_scalar(value))\n # GH#43424: np.putmask raises TypeError if we cannot cast between types with\n # rule = \"safe\", a", "label": 0, "sample_id": "pandas-dev/pandas:pandas/core/array_algos/putmask.py", "category": "unknown", "repo_id": "pandas-dev/pandas"} {"input": "import math\n\nimport numpy as np\nimport torch\n\nimport genesis as gs\nfrom genesis.repr_base import RBC\nfrom genesis.constants import IMAGE_TYPE\nfrom genesis.utils.misc import qd_to_torch\n\nfrom .rasterizer_context import SegmentationColorMap\n\n# Optional imports for platform-specific functionality\ntry:\n from gs_madrona.renderer_gs import MadronaBatchRendererAdapter\n\n _MADRONA_AVAILABLE = True\nexcept ImportError:\n MadronaBatchRendererAdapter = None\n _MADRONA_AVAILABLE = False\n\n\ndef _transform_camera_quat(quat):\n # quat for Madrona needs to be transformed to y-forward\n w, x, y, z = torch.unbind(quat, dim=-1)\n return torch.stack([x + w, x - w, y - z, y + z], dim=-1) / math.sqrt(2.0)\n\n\ndef _make_tensor(data, *, dtype: torch.dtype = torch.float32):\n return torch.tensor(data, dtype=dtype, device=gs.device)\n\n\nclass GenesisGeomRetriever:\n def __init__(self, rigid_solver, seg_level):\n self.rigid_solver = rigid_solver\n self.seg_color", "label": 1, "sample_id": "Genesis-Embodied-AI/Genesis:genesis/vis/batch_renderer.py", "category": "function_complex", "repo_id": "Genesis-Embodied-AI/Genesis"} {"input": "import uuid\n\nfrom dash import Dash, Input, Output, callback_context, State, MATCH\n\nfrom dash_test_components import ComponentAsProp\n\nfrom dash.dcc import Checklist, Dropdown\nfrom dash.html import Button, Div, Span\n\nfrom flaky import flaky\n\n\ndef opt(u):\n return {\n \"label\": [\n Button(\n \"click me\", id={\"type\": \"button\", \"index\": u}, className=\"label-button\"\n ),\n Span(id={\"type\": \"text\", \"index\": u}, className=\"label-result\"),\n ],\n \"value\": u,\n }\n\n\ndef test_rdcap001_component_as_prop(dash_duo):\n app = Dash(__name__)\n\n content = [\n ComponentAsProp(\n element=Div(\n \"as-props\",\n id=\"as-props\",\n )\n ),\n ComponentAsProp(\n id=\"clicker-container\", element=Button(\"click-me\", id=\"clicker\")\n ),\n ComponentAsProp(\n id=\"nested-output-container\",\n element=Div(id=\"nested-output\"),\n ),\n Div(\n [\n Button(\"click-nested\", id=\"send-nested\"),\n Div(id=\"output-from-prop\"),\n ]\n ),\n ", "label": 0, "sample_id": "plotly/dash:tests/integration/renderer/test_component_as_prop.py", "category": "unknown", "repo_id": "plotly/dash"} {"input": "# Copyright The Lightning AI team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom unittest.mock import patch\n\nimport pytest\nimport torch\n\nfrom lightning.pytorch import Trainer\nfrom lightning.pytorch.callbacks import ModelSummary, ProgressBar, RichModelSummary, RichProgressBar, TQDMProgressBar\nfrom lightning.pytorch.demos.boring_classes import BoringModel\n\n\nclass TestRichIntegration:\n @patch(\"lightning.pytorch.trainer.connectors.callback_connector._RICH_AVAILABLE\", False)\n def test_no_rich_defaults_tqdm_and_model_summary(self, tmp_path):\n trainer = Trainer(default_root_dir=tmp_path, logger=False, enable_checkpointing=False)\n assert any(isinstance(cb, TQDMProgressBar)", "label": 1, "sample_id": "Lightning-AI/pytorch-lightning:tests/tests_pytorch/trainer/connectors/test_rich_integration.py", "category": "test", "repo_id": "Lightning-AI/pytorch-lightning"} {"input": "#!/usr/bin/env python3\n\"\"\"Improve a skill description based on eval results.\n\nTakes eval results (from run_eval.py) and generates an improved description\nby calling `claude -p` as a subprocess (same auth pattern as run_eval.py —\nuses the session's Claude Code auth, no separate ANTHROPIC_API_KEY needed).\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport re\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nfrom scripts.utils import parse_skill_md\n\n\ndef _call_claude(prompt: str, model: str | None, timeout: int = 300) -> str:\n \"\"\"Run `claude -p` with the prompt on stdin and return the text response.\n\n Prompt goes over stdin (not argv) because it embeds the full SKILL.md\n body and can easily exceed comfortable argv length.\n \"\"\"\n cmd = [\"claude\", \"-p\", \"--output-format\", \"text\"]\n if model:\n cmd.extend([\"--model\", model])\n\n # Remove CLAUDECODE env var to allow nesting claude -p inside a\n # Claude Code session. The guard is for interactive terminal conflicts;\n # programmatic subprocess usage is safe.", "label": 0, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/development/skill-creator/scripts/improve_description.py", "category": "unknown", "repo_id": "davila7/claude-code-templates"} {"input": "#!/usr/bin/env python3\n\n\"\"\"\narchivebox crawl [args...] [--filters]\n\nManage Crawl records.\n\nActions:\n create - Create Crawl jobs from URLs\n list - List Crawls as JSONL (with optional filters)\n update - Update Crawls from stdin JSONL\n delete - Delete Crawls from stdin JSONL\n\nExamples:\n # Create\n archivebox crawl create https://example.com https://foo.com --depth=1\n archivebox crawl create --tag=news https://example.com\n\n # List with filters\n archivebox crawl list --status=queued\n archivebox crawl list --urls__icontains=example.com\n\n # Update\n archivebox crawl list --status=started | archivebox crawl update --status=queued\n\n # Delete\n archivebox crawl list --urls__icontains=spam.com | archivebox crawl delete --yes\n\n # Full pipeline\n archivebox crawl create https://example.com | archivebox snapshot create | archivebox run\n\"\"\"\n\n__package__ = 'archivebox.cli'\n__command__ = 'archivebox crawl'\n\nimport sys\nfrom typing import Optional, Iterable\n\nimport rich_click as click\nfrom rich import print as r", "label": 1, "sample_id": "ArchiveBox/ArchiveBox:archivebox/cli/archivebox_crawl.py", "category": "function_complex", "repo_id": "ArchiveBox/ArchiveBox"} {"input": "\"\"\"Code copied from Django Software Foundation (https://djangoproject.com/) which is licensed under the BSD 3-Clause.\n\nOriginal code: https://github.com/django/django/blob/001c2f546b4053acb04f16d6b704f7b4fbca1c45/django/core/handlers/asgi.py\n\nModifications: we added a fix for a memory leak\n(https://code.djangoproject.com/ticket/36700).\n\nCopyright (c) Django Software Foundation and individual contributors.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n 3. Neither the name of Django nor the names of its contributors may be used\n to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED", "label": 1, "sample_id": "saleor/saleor:saleor/asgi/asgi_handler.py", "category": "function_complex", "repo_id": "saleor/saleor"} {"input": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\nimport weakref\n\nimport pytest\n\nfrom tests.entrypoints.openai.chat_completion.test_vision import TEST_IMAGE_ASSETS\nfrom vllm import LLM\nfrom vllm.distributed import cleanup_dist_env_and_memory\nfrom vllm.sampling_params import SamplingParams\n\n\n@pytest.fixture(scope=\"function\")\ndef text_llm():\n # pytest caches the fixture so we use weakref.proxy to\n # enable garbage collection\n llm = LLM(model=\"meta-llama/Llama-3.2-1B-Instruct\", enforce_eager=True, seed=0)\n\n yield weakref.proxy(llm)\n\n del llm\n\n cleanup_dist_env_and_memory()\n\n\n@pytest.fixture(scope=\"function\")\ndef llm_for_failure_test():\n \"\"\"\n Fixture for testing issue #26081.\n Uses a small max_model_len to easily trigger length errors.\n \"\"\"\n # pytest caches the fixture so we use weakref.proxy to\n # enable garbage collection\n llm = LLM(\n model=\"meta-llama/Llama-3.2-1B-Instruct\",\n ", "label": 0, "sample_id": "vllm-project/vllm:tests/entrypoints/llm/test_chat.py", "category": "unknown", "repo_id": "vllm-project/vllm"} {"input": "import math\nfrom dataclasses import dataclass\nfrom typing import Any\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import CrossEntropyLoss\nfrom transformers import AutoConfig\nfrom transformers.activations import ACT2FN\nfrom transformers.cache_utils import (\n Cache,\n DynamicCache,\n StaticCache,\n)\nfrom transformers.generation import GenerationMixin\nfrom transformers.modeling_attn_mask_utils import AttentionMaskConverter\nfrom transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput\nfrom transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS\nfrom transformers.modeling_utils import PreTrainedModel\nfrom transformers.utils import (\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n is_flash_attn_2_available,\n is_flash_attn_greater_or_equal_2_10,\n is_torchdynamo_compiling,\n logging,\n replace_return_docstrings,\n)\n\nfrom .configuration_qwen2_5_vl import Qwen2_5_VLConfig, Qwen2_5_VLVisionConfig\n\n\n# TODO(Steven): SlidingWindowCache was removed in transformers v5. Define a placeholder so isinstance checks\n# always return False (which is the correct behavior", "label": 1, "sample_id": "huggingface/lerobot:src/lerobot/policies/wall_x/qwen_model/qwen2_5_vl_moe.py", "category": "function_complex", "repo_id": "huggingface/lerobot"} {"input": "\"\"\"Anthropic content block formatter.\"\"\"\n\nfrom __future__ import annotations\n\nimport base64\nfrom typing import Any\n\nfrom crewai_files.core.resolved import (\n FileReference,\n InlineBase64,\n InlineBytes,\n ResolvedFileType,\n UrlReference,\n)\nfrom crewai_files.core.types import FileInput\n\n\nclass AnthropicFormatter:\n \"\"\"Formats resolved files into Anthropic content blocks.\"\"\"\n\n def format_block(\n self,\n file: FileInput,\n resolved: ResolvedFileType,\n ) -> dict[str, Any] | None:\n \"\"\"Format a resolved file into an Anthropic content block.\n\n Args:\n file: Original file input with metadata.\n resolved: Resolved file.\n\n Returns:\n Content block dict or None if not supported.\n \"\"\"\n content_type = file.content_type\n block_type = self._get_block_type(content_type)\n if block_type is None:\n return None\n\n if isinstance(resolved, FileReference):\n return {\n \"type\": block_type,\n \"source\": {\n \"type\": \"file\",\n \"file_id\": resolved.file_id,\n },\n \"cache_control\": {\"type\": \"ephemeral\"},\n }\n\n if isinstance(resolved,", "label": 1, "sample_id": "crewAIInc/crewAI:lib/crewai-files/src/crewai_files/formatting/anthropic.py", "category": "function_simple", "repo_id": "crewAIInc/crewAI"} {"input": "from __future__ import annotations\n\nfrom typing_extensions import TypeVar\n\nfrom langgraph._internal._typing import StateLike\n\n__all__ = (\n \"StateT\",\n \"StateT_co\",\n \"StateT_contra\",\n \"InputT\",\n \"OutputT\",\n \"ContextT\",\n)\n\nStateT = TypeVar(\"StateT\", bound=StateLike)\n\"\"\"Type variable used to represent the state in a graph.\"\"\"\n\nStateT_co = TypeVar(\"StateT_co\", bound=StateLike, covariant=True)\n\nStateT_contra = TypeVar(\"StateT_contra\", bound=StateLike, contravariant=True)\n\nContextT = TypeVar(\"ContextT\", bound=StateLike | None, default=None)\n\"\"\"Type variable used to represent graph run scoped context.\n\nDefaults to `None`.\n\"\"\"\n\nContextT_contra = TypeVar(\n \"ContextT_contra\", bound=StateLike | None, contravariant=True, default=None\n)\n\nInputT = TypeVar(\"InputT\", bound=StateLike, default=StateT)\n\"\"\"Type variable used to represent the input to a `StateGraph`.\n\nDefaults to `StateT`.\n\"\"\"\n\nOutputT = TypeVar(\"OutputT\", bound=StateLike, default=", "label": 1, "sample_id": "langchain-ai/langgraph:libs/langgraph/langgraph/typing.py", "category": "function_simple", "repo_id": "langchain-ai/langgraph"} {"input": "# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nfrom __future__ import annotations\n\nfrom typing import Any, List, Iterable, cast\nfrom typing_extensions import Literal\n\nimport httpx\n\nfrom ... import _legacy_response\nfrom ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given\nfrom ..._utils import maybe_transform, async_maybe_transform\nfrom ..._compat import cached_property\nfrom ..._resource import SyncAPIResource, AsyncAPIResource\nfrom ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper\nfrom ...pagination import SyncConversationCursorPage, AsyncConversationCursorPage\nfrom ..._base_client import AsyncPaginator, make_request_options\nfrom ...types.conversations import item_list_params, item_create_params, item_retrieve_params\nfrom ...types.conversations.conversation import Conversation\nfrom ...types.responses.response_includable import ResponseIncludable\nfrom ...types.conversations.conversation_item import ConversationItem\nfrom ...types.responses.response_input_item_param import ResponseInputItemParam\nfrom ...types.conversations.conversation_item_list import ConversationItemList\n\n__all__ = [\"Items\", \"AsyncItems\"]\n\n\nclass Items(SyncAPIResource):\n ", "label": 1, "sample_id": "openai/openai-python:src/openai/resources/conversations/items.py", "category": "function_complex", "repo_id": "openai/openai-python"} {"input": "# coding=utf-8\nfrom typing import Dict\n\nfrom django.utils.translation import gettext_lazy as _, gettext\n\nfrom common import forms\nfrom common.exception.app_exception import AppApiException\nfrom common.forms import BaseForm, TooltipLabel\nfrom models_provider.base_model_provider import BaseModelCredential, ValidCode\nfrom common.utils.logger import maxkb_logger\n\nclass RegoloTTIModelParams(BaseForm):\n size = forms.SingleSelect(\n TooltipLabel(_('Image size'),\n _('The image generation endpoint allows you to create raw images based on text prompts. ')),\n required=True,\n default_value='1024x1024',\n option_list=[\n {'value': '1024x1024', 'label': '1024x1024'},\n {'value': '1024x1792', 'label': '1024x1792'},\n {'value': '1792x1024', 'label': '1792x1024'},\n ],\n text_field='label',\n value_field='value'\n )\n\n quality = forms.SingleSelect(\n TooltipLabel(_('Picture quality'), _(''' \nBy default", "label": 1, "sample_id": "1Panel-dev/MaxKB:apps/models_provider/impl/regolo_model_provider/credential/tti.py", "category": "function_simple", "repo_id": "1Panel-dev/MaxKB"} {"input": "# /// script\n# dependencies = [\"anthropic\", \"fastmcp\", \"rich\"]\n# ///\n\"\"\"\nSimple Text Sampling\n\nDemonstrates the basic MCP sampling flow where a server tool requests\nan LLM completion from the client.\n\nRun:\n uv run examples/sampling/text.py\n\"\"\"\n\nimport asyncio\n\nfrom rich.console import Console\nfrom rich.panel import Panel\n\nfrom fastmcp import Client, Context, FastMCP\nfrom fastmcp.client.sampling import SamplingMessage, SamplingParams\nfrom fastmcp.client.sampling.handlers.anthropic import AnthropicSamplingHandler\n\nconsole = Console()\n\n\n# Create a wrapper handler that logs when the LLM is called\nclass LoggingAnthropicHandler(AnthropicSamplingHandler):\n async def __call__(\n self, messages: list[SamplingMessage], params: SamplingParams, context\n ): # type: ignore[override]\n console.print(\" [bold blue]SAMPLING[/] Calling Claude API...\")\n result = await super().__call__(messages, params, context)\n console.print(\" [bold blue]SAMPLING[/] Response received\")\n return result\n\n\n# Create the MCP server\nmcp = FastMCP(\"Haiku Generator\")\n\n\n@mcp.tool\nasync", "label": 1, "sample_id": "PrefectHQ/fastmcp:examples/sampling/text.py", "category": "function_simple", "repo_id": "PrefectHQ/fastmcp"} {"input": "#!/usr/bin/env python\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom dataclasses import dataclass, field\n\nfrom lerobot.datasets.transforms import ImageTransformsConfig\nfrom lerobot.datasets.video_utils import get_safe_default_codec\n\n\n@dataclass\nclass DatasetConfig:\n # You may provide a list of datasets here. `train.py` creates them all and concatenates them. Note: only data\n # keys common between the datasets are kept. Each dataset gets and additional transform that inserts the\n # \"dataset_index\" into the returned item. The index mapping is made according to the order in which the", "label": 0, "sample_id": "huggingface/lerobot:src/lerobot/configs/default.py", "category": "unknown", "repo_id": "huggingface/lerobot"} {"input": "\"\"\"\nConfiguration objects for language servers\n\"\"\"\n\nimport fnmatch\nfrom collections.abc import Iterable\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import TYPE_CHECKING, Self\n\nif TYPE_CHECKING:\n from solidlsp import SolidLanguageServer\n\n\nclass FilenameMatcher:\n def __init__(self, *patterns: str) -> None:\n \"\"\"\n :param patterns: fnmatch-compatible patterns\n \"\"\"\n self.patterns = patterns\n\n def is_relevant_filename(self, fn: str) -> bool:\n for pattern in self.patterns:\n if fnmatch.fnmatch(fn, pattern):\n return True\n return False\n\n\nclass Language(str, Enum):\n \"\"\"\n Enumeration of language servers supported by SolidLSP.\n \"\"\"\n\n CSHARP = \"csharp\"\n PYTHON = \"python\"\n RUST = \"rust\"\n JAVA = \"java\"\n KOTLIN = \"kotlin\"\n TYPESCRIPT = \"typescript\"\n GO = \"go\"\n RUBY = \"ruby\"\n DART = \"dart\"\n CPP = \"cpp\"\n CPP_CCLS = \"cpp_ccls\"\n PHP = \"php\"\n R = \"r\"\n PERL =", "label": 0, "sample_id": "oraios/serena:src/solidlsp/ls_config.py", "category": "unknown", "repo_id": "oraios/serena"} {"input": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload\nfrom datetime import date, datetime\nfrom typing_extensions import Self, Literal, TypedDict\n\nimport pydantic\nfrom pydantic.fields import FieldInfo\n\nfrom ._types import IncEx, StrBytesIntFloat\n\n_T = TypeVar(\"_T\")\n_ModelT = TypeVar(\"_ModelT\", bound=pydantic.BaseModel)\n\n# --------------- Pydantic v2, v3 compatibility ---------------\n\n# Pyright incorrectly reports some of our functions as overriding a method when they don't\n# pyright: reportIncompatibleMethodOverride=false\n\nPYDANTIC_V1 = pydantic.VERSION.startswith(\"1.\")\n\nif TYPE_CHECKING:\n\n def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001\n ...\n\n def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001\n ...\n\n def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001\n ...\n\n def is_union(tp: type[Any] | None) -> bool", "label": 0, "sample_id": "openai/openai-python:src/openai/_compat.py", "category": "unknown", "repo_id": "openai/openai-python"} {"input": "from typing import Callable, TypedDict, Optional, List, Tuple\n\nProgressCallback = Optional[Callable[[float], None]]\n\ntry:\n from typing import NotRequired\nexcept ImportError:\n from typing_extensions import NotRequired\n\n\nclass SingleWordSegment(TypedDict):\n \"\"\"\n A single word of a speech.\n \"\"\"\n word: str\n start: float\n end: float\n score: float\n\nclass SingleCharSegment(TypedDict):\n \"\"\"\n A single char of a speech.\n \"\"\"\n char: str\n start: float\n end: float\n score: float\n\n\nclass SingleSegment(TypedDict):\n \"\"\"\n A single segment (up to multiple sentences) of a speech.\n \"\"\"\n\n start: float\n end: float\n text: str\n avg_logprob: NotRequired[float]\n\n\nclass SegmentData(TypedDict):\n \"\"\"\n Temporary processing data used during alignment.\n Contains cleaned and preprocessed data for each segment.\n \"\"\"\n clean_char: List[str] # Cleaned characters that exist in model dictionary\n clean_cdx: List[int] # Original indices of cleaned characters\n clean_wdx: List[int] # Indices of words containing valid characters\n ", "label": 0, "sample_id": "m-bain/whisperX:whisperx/schema.py", "category": "unknown", "repo_id": "m-bain/whisperX"} {"input": "import os\nimport shutil\nfrom pathlib import Path\n\nimport pytest\n\nfrom pipenv.project import Project\nfrom pipenv.utils.pylock import PylockFile, find_pylock_file\n\n\n@pytest.fixture\ndef pylock_project(tmp_path):\n \"\"\"Create a temporary project with a pylock.toml file.\"\"\"\n # Copy the example pylock.toml to the temporary directory\n example_pylock = Path(__file__).parent.parent.parent / \"examples\" / \"pylock.toml\"\n tmp_pylock = tmp_path / \"pylock.toml\"\n\n # Create a simple Pipfile\n pipfile_content = \"\"\"\n[[source]]\nurl = \"https://pypi.org/simple\"\nverify_ssl = true\nname = \"pypi\"\n\n[packages]\nrequests = \"*\"\n\n[dev-packages]\n\n[requires]\npython_version = \"3.8\"\n\"\"\"\n\n with open(tmp_path / \"Pipfile\", \"w\") as f:\n f.write(pipfile_content)\n\n shutil.copy(example_pylock, tmp_pylock)\n\n # Change to the temporary directory\n old_cwd = os.getcwd()\n os.chdir(tmp_path)\n\n try:\n yield tmp_path\n finally:\n os.chdir(old_cwd)\n\n\ndef test_find_pylock_file(py", "label": 1, "sample_id": "pypa/pipenv:tests/integration/test_pylock.py", "category": "test", "repo_id": "pypa/pipenv"} {"input": "from dataclasses import dataclass\n\nfrom aider.dump import dump # noqa: F401\n\n\n@dataclass\nclass ExInfo:\n name: str\n retry: bool\n description: str\n\n\nEXCEPTIONS = [\n ExInfo(\"APIConnectionError\", True, None),\n ExInfo(\"APIError\", True, None),\n ExInfo(\"APIResponseValidationError\", True, None),\n ExInfo(\n \"AuthenticationError\",\n False,\n \"The API provider is not able to authenticate you. Check your API key.\",\n ),\n ExInfo(\"AzureOpenAIError\", True, None),\n ExInfo(\"BadGatewayError\", True, \"The API provider's servers are down or overloaded.\"),\n ExInfo(\"BadRequestError\", False, None),\n ExInfo(\"BudgetExceededError\", True, None),\n ExInfo(\n \"ContentPolicyViolationError\",\n True,\n \"The API provider has refused the request due to a safety policy about the content.\",\n ),\n ExInfo(\"ContextWindowExceededError\", False, None), # special case handled in base_coder\n ExInfo(\"ImageFetchError\", False, \"The API provider was unable to fetch one or more images.\"),\n Ex", "label": 0, "sample_id": "Aider-AI/aider:aider/exceptions.py", "category": "unknown", "repo_id": "Aider-AI/aider"} {"input": "#!/usr/bin/env python3\n\"\"\"\nSkill Packager - Creates a distributable .skill file of a skill folder\n\nUsage:\n python package_skill.py [output-directory]\n\nExample:\n python package_skill.py skills/public/my-skill\n python package_skill.py skills/public/my-skill ./dist\n\"\"\"\n\nimport sys\nimport zipfile\nfrom pathlib import Path\n\nfrom quick_validate import validate_skill\n\n\ndef _is_within(path: Path, root: Path) -> bool:\n try:\n path.relative_to(root)\n return True\n except ValueError:\n return False\n\n\ndef _cleanup_partial_archive(skill_filename: Path) -> None:\n try:\n if skill_filename.exists():\n skill_filename.unlink()\n except OSError:\n pass\n\n\ndef package_skill(skill_path, output_dir=None):\n \"\"\"\n Package a skill folder into a .skill file.\n\n Args:\n skill_path: Path to the skill folder\n output_dir: Optional output directory for the .skill file (defaults to current directory)\n\n Returns:\n Path to the created .skill file, or None if error\n \"\"\"\n skill_path = Path(skill_path).resolve()\n\n # Validate skill folder exists\n if not skill_path.exists():\n print", "label": 0, "sample_id": "HKUDS/nanobot:nanobot/skills/skill-creator/scripts/package_skill.py", "category": "unknown", "repo_id": "HKUDS/nanobot"} {"input": "\"\"\"This module provides utilities for managing Reflex app templates.\"\"\"\n\nimport dataclasses\nimport shutil\nimport tempfile\nimport zipfile\nfrom pathlib import Path\nfrom urllib.parse import urlparse\n\nfrom reflex import constants\nfrom reflex.config import get_config\nfrom reflex.utils import console, net, path_ops, redir\n\n\n@dataclasses.dataclass(frozen=True)\nclass Template:\n \"\"\"A template for a Reflex app.\"\"\"\n\n name: str\n description: str\n code_url: str\n\n\ndef create_config(app_name: str):\n \"\"\"Create a new rxconfig file.\n\n Args:\n app_name: The name of the app.\n \"\"\"\n # Import here to avoid circular imports.\n from reflex.compiler import templates\n\n console.debug(f\"Creating {constants.Config.FILE}\")\n constants.Config.FILE.write_text(templates.rxconfig_template(app_name=app_name))\n\n\ndef initialize_app_directory(\n app_name: str,\n template_name: str = constants.Templates.DEFAULT,\n template_code_dir_name: str | None = None,\n template_dir: Path | None = None,\n):\n \"\"\"Initialize the app directory on reflex init.\n\n Args:\n app_name: The name of the app.\n template_name: The name of the template to use.\n template", "label": 1, "sample_id": "reflex-dev/reflex:reflex/utils/templates.py", "category": "function_complex", "repo_id": "reflex-dev/reflex"} {"input": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Test that apply_fsdp2's module selection handles peft-wrapped models.\n\npeft wraps embed_tokens in a ModulesToSaveWrapper, so isinstance(module, nn.Embedding)\nfails. Without name-based matching, embed_tokens + lm_head land in the root FSDP unit,\ncausing OOM from oversized allgather. These tests verify the module selection logic\nworks for: (1) vanilla models, (2) peft-wrapped models, (3) tied embeddings.\n\"\"\"\n\nimport unittest\nfrom types import SimpleNamespace\n\nimport torch.nn as nn\n\nfrom verl.utils", "label": 0, "sample_id": "verl-project/verl:tests/utils/test_fsdp2_peft_wrapping.py", "category": "unknown", "repo_id": "verl-project/verl"} {"input": "# Copyright 2026 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\nfrom unittest.mock import MagicMock, patch\n\nimport torch\n\nfrom verl.utils.profiler.config import ProfilerConfig, TorchProfilerToolConfig\nfrom verl.utils.profiler.torch_profile import Profiler, get_torch_profiler\n\n\nclass TestTorchProfile(unittest.TestCase):\n def setUp(self):\n # Reset Profiler class state\n Profiler._define_count = 0\n\n @patch(\"torch.profiler.profile\")\n def test_get_torch_profiler(self, mock_profile):\n # Test wrapper function\n get_torch_profiler(contents=[\"cpu\",", "label": 1, "sample_id": "verl-project/verl:tests/utils/test_torch_profile.py", "category": "test", "repo_id": "verl-project/verl"} {"input": "import os\nimport re\nfrom collections import defaultdict\nfrom typing import List, Pattern\n\nimport utils.constants as constants\nfrom utils.tools import get_real_path, resource_path\nfrom utils.types import WhitelistMaps\n\n\ndef load_whitelist_maps(path: str = constants.whitelist_path) -> WhitelistMaps:\n \"\"\"\n Load whitelist maps from the given path.\n Returns two dictionaries:\n - exact: channel_name -> list of exact whitelist entries\n - keywords: channel_name -> list of keyword whitelist entries\n The special key \"\" (empty string) is used for global entries.\n \"\"\"\n\n exact = defaultdict(list)\n keywords = defaultdict(list)\n in_keyword_section = False\n\n real_path = get_real_path(resource_path(path))\n if not os.path.exists(real_path):\n return exact, keywords\n\n with open(real_path, \"r\", encoding=\"utf-8\") as f:\n for raw in f:\n line = raw.rstrip(\"\\n\")\n s = line.strip()\n if not s or s.startswith(\"#\"):\n continue\n\n if re.match(r\"^\\[.*\\]$\", s):\n in_keyword_section = s.upper() == \"[KEYWORDS]\"\n continue\n\n if \",\" in s:\n name, value", "label": 1, "sample_id": "Guovin/iptv-api:utils/whitelist.py", "category": "function_complex", "repo_id": "Guovin/iptv-api"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom playwright.sync_api import Page, expect\n\nfrom e2e_playwright.conftest import ImageCompareFunction, wait_for_app_run\nfrom e2e_playwright.shared.app_utils import (\n check_top_level_class,\n click_button,\n expect_markdown,\n get_element_by_key,\n get_popover,\n open_popover,\n)\n\n\ndef test_popover_button_rendering(\n themed_app: Page, assert_snapshot: ImageCompareFunction\n):\n \"\"\"Test that the popover buttons are", "label": 0, "sample_id": "streamlit/streamlit:e2e_playwright/st_popover_test.py", "category": "unknown", "repo_id": "streamlit/streamlit"} {"input": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# NOTE! THIS FILE IS COPIED MANUALLY IN OTHER PROVIDERS DELIBERATELY TO AVOID ADDING UNNECESSARY\n# DEPENDENCIES BETWEEN PROVIDERS. IF YOU WANT TO ADD CONDITIONAL CODE IN YOUR PROVIDER THAT DEPENDS\n# ON AIRFLOW VERSION, PLEASE COPY THIS FILE TO THE ROOT PACKAGE OF YOUR PROVIDER AND IMPORT\n# THOSE CONSTANTS", "label": 1, "sample_id": "apache/airflow:providers/apache/livy/src/airflow/providers/apache/livy/version_compat.py", "category": "function_simple", "repo_id": "apache/airflow"} {"input": "import os\nimport tempfile\nimport warnings\nfrom typing import Any\nfrom unittest.mock import patch\n\nimport pytest\nimport torch\n\nfrom torch_geometric import is_in_onnx_export, safe_onnx_export\n\n# Global mock to prevent ANY real ONNX calls in tests\n# This ensures no deprecation warnings or real ONNX issues\npytestmark = pytest.mark.filterwarnings(\"ignore::DeprecationWarning\")\n\n\nclass SimpleModel(torch.nn.Module):\n \"\"\"Simple model for testing ONNX export.\"\"\"\n def __init__(self) -> None:\n super().__init__()\n self.linear = torch.nn.Linear(4, 2)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.linear(x)\n\n\ndef test_is_in_onnx_export() -> None:\n \"\"\"Test is_in_onnx_export function.\"\"\"\n assert not is_in_onnx_export()\n\n\ndef test_safe_onnx_export_ci_resilient() -> None:\n \"\"\"Test safe_onnx_export handles CI environment issues gracefully.\"\"\"\n model = SimpleModel()\n x = torch.randn(3, 4)\n\n # Use mocking to prevent real ONNX calls and deprecation warnings\n with patch('torch.onnx.export', return_value=None) as mock_export:\n with", "label": 1, "sample_id": "pyg-team/pytorch_geometric:test/test_onnx.py", "category": "test", "repo_id": "pyg-team/pytorch_geometric"} {"input": "\"\"\"Picture description stage using the VLM engine system.\n\nThis module provides an engine-agnostic picture description stage that can use\nany VLM engine (Transformers, MLX, API, etc.) through the unified engine interface.\n\"\"\"\n\nimport logging\nfrom collections.abc import Iterable\nfrom pathlib import Path\nfrom typing import Optional, Type, Union\n\nfrom PIL import Image\n\nfrom docling.datamodel.accelerator_options import AcceleratorOptions\nfrom docling.datamodel.pipeline_options import (\n PictureDescriptionBaseOptions,\n PictureDescriptionVlmEngineOptions,\n)\nfrom docling.datamodel.stage_model_specs import EngineModelConfig\nfrom docling.models.inference_engines.vlm import (\n BaseVlmEngine,\n VlmEngineInput,\n create_vlm_engine,\n)\nfrom docling.models.picture_description_base_model import PictureDescriptionBaseModel\n\n_log = logging.getLogger(__name__)\n\n\nclass PictureDescriptionVlmEngineModel(PictureDescriptionBaseModel):\n \"\"\"Picture description stage using the VLM engine system.\n\n This stage uses the unified VLM engine interface to generate descriptions\n for pictures in documents. It supports all engine types (Transformers, MLX,\n API, etc.) through the engine factory.\n\n The stage:\n 1. Filters pictures based", "label": 1, "sample_id": "docling-project/docling:docling/models/stages/picture_description/picture_description_vlm_engine_model.py", "category": "function_complex", "repo_id": "docling-project/docling"} {"input": "\"\"\"\nAgent Command Registrar for Spec Kit\n\nShared infrastructure for registering commands with AI agents.\nUsed by both the extension system and the preset system to write\ncommand files into agent-specific directories in the correct format.\n\"\"\"\n\nfrom pathlib import Path\nfrom typing import Dict, List, Any\n\nimport yaml\n\n\nclass CommandRegistrar:\n \"\"\"Handles registration of commands with AI agents.\n\n Supports writing command files in Markdown or TOML format to the\n appropriate agent directory, with correct argument placeholders\n and companion files (e.g. Copilot .prompt.md).\n \"\"\"\n\n # Agent configurations with directory, format, and argument placeholder\n AGENT_CONFIGS = {\n \"claude\": {\n \"dir\": \".claude/commands\",\n \"format\": \"markdown\",\n \"args\": \"$ARGUMENTS\",\n \"extension\": \".md\"\n },\n \"gemini\": {\n \"dir\": \".gemini/commands\",\n \"format\": \"toml\",\n \"args\": \"{{args}}\",\n \"extension\": \".toml\"\n },\n \"copilot\": {\n \"dir\": \".github/agents\",\n \"format\": \"markdown\",\n \"args\": \"$ARGUMENTS\",\n \"extension\": \".agent.md\"\n ", "label": 0, "sample_id": "github/spec-kit:src/specify_cli/agents.py", "category": "unknown", "repo_id": "github/spec-kit"} {"input": "from pydantic import BaseModel\n\n\nclass Example:\n \"\"\"A flexible data container for DSPy examples and training data with named fields.\n\n An `Example` is roughly one row from a HuggingFace dataset or pandas\n `DataFrame`. It behaves a lot like a dictionary or dot-access record: you\n can read fields with `example[\"question\"]` or `example.question`.\n\n In DSPy, lists of `Example` objects are your trainset, devset, and testset.\n Most examples are built from keyword arguments or an existing record, then\n tagged with `with_inputs(...)` to say which fields should be fed into a\n module. The remaining fields are labels or metadata.\n\n When you write evaluation code, custom optimizers, or training loops, use\n `example.inputs()` for the fields you want to pass to a module, and use\n `example.labels()` for the fields you want to compare against the module's\n output.\n\n Examples:\n Build one from keyword arguments:\n\n >>> import dspy\n >>> example = dspy.Example(\n ... question=\"What is the capital of France?\",\n ... answer=\"Paris\",\n ... ).with_inputs(\"question\")\n >>>", "label": 0, "sample_id": "stanfordnlp/dspy:dspy/primitives/example.py", "category": "unknown", "repo_id": "stanfordnlp/dspy"} {"input": "import datetime\nfrom collections.abc import Callable\nfrom dataclasses import InitVar, dataclass, field\nfrom decimal import Decimal\nfrom enum import Enum\nfrom functools import cached_property\nfrom typing import TYPE_CHECKING, Any, Optional, Union\n\nfrom ..order import FulfillmentLineData\nfrom ..order.fetch import OrderLineInfo\nfrom ..payment.models import TransactionEvent, TransactionItem\n\nif TYPE_CHECKING:\n from ..account.models import User\n from ..app.models import App\n from ..channel.models import Channel\n from ..checkout.models import Checkout\n from ..order.models import Order, OrderGrantedRefund\n\nJSONValue = str | int | float | bool | None | dict[str, Any] | list[Any]\nJSONType = dict[str, JSONValue] | list[JSONValue]\n\n\n@dataclass\nclass StoredPaymentMethodRequestDeleteResult(str, Enum):\n \"\"\"Result of deleting a stored payment method.\n\n This enum is used to determine the result of deleting a stored payment method.\n SUCCESSFULLY_DELETED - The stored payment method was successfully deleted.\n FAILED_TO_DELETE - The stored payment method was not deleted.\n FAILED_TO_DELIVER - The request to delete the stored payment method was not\n delivered.\n", "label": 0, "sample_id": "saleor/saleor:saleor/payment/interface.py", "category": "unknown", "repo_id": "saleor/saleor"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom datetime import datetime, time\n\nimport streamlit as st\nfrom streamlit import runtime\n\nv1 = st.time_input(\"Time input 1 (8:45)\", time(8, 45))\nst.write(\"Value 1:\", v1)\n\nv2 = st.time_input(\n \"Time input 2 (21:15, help)\", datetime(2019, 7, 6, 21, 15), help=\"Help text", "label": 0, "sample_id": "streamlit/streamlit:e2e_playwright/st_time_input.py", "category": "unknown", "repo_id": "streamlit/streamlit"} {"input": "from __future__ import annotations\n\nimport logging\nimport sys\nfrom unittest.mock import patch\n\nfrom supervision.utils.logger import _get_logger\n\n\nclass TestGetLogger:\n def test_default_name(self):\n \"\"\"Logger is created with default name.\"\"\"\n logger = _get_logger()\n assert logger.name == \"supervision\"\n\n def test_custom_name(self):\n \"\"\"Logger is created with provided name.\"\"\"\n logger = _get_logger(\"supervision.test_module\")\n assert logger.name == \"supervision.test_module\"\n\n def test_default_level_is_info(self):\n \"\"\"Logger defaults to INFO level when LOG_LEVEL env var is not set.\"\"\"\n with patch.dict(\"os.environ\", {}, clear=True):\n # Use a unique name to avoid cached logger state from other tests\n logger = _get_logger(\"supervision.test_default_level\")\n assert logger.level == logging.INFO\n\n def test_explicit_level(self):\n \"\"\"Logger uses the explicitly provided level.\"\"\"\n logger = _get_logger(\"supervision.test_explicit_level\", level=logging.DEBUG)\n assert logger.level == logging.DEBUG\n\n def test_log_level_env_var(self):\n \"\"\"Logger respects the LOG_LEVEL environment variable.\"\"\"\n with patch.dict(\"os.environ\", {\"LOG_LEVEL\":", "label": 1, "sample_id": "roboflow/supervision:tests/utils/test_logger.py", "category": "test", "repo_id": "roboflow/supervision"} {"input": "import importlib\n\nimport pytest\n\nif importlib.util.find_spec(\"langchain_core\") is None:\n pytest.skip(reason=\"langchain_core is not installed\", allow_module_level=True)\n\nfrom pydantic import BaseModel\n\nfrom dspy.utils.langchain_tool import convert_langchain_tool\n\n\n@pytest.mark.asyncio\n@pytest.mark.extra\nasync def test_convert_custom_simple_tool():\n from langchain_core.tools import tool\n\n @tool\n def add(a: int, b: int) -> int:\n \"\"\"Add two numbers.\"\"\"\n return a + b\n\n tool = convert_langchain_tool(add)\n assert tool.name == \"add\"\n assert tool.desc == \"Add two numbers.\"\n assert tool.args == {\"a\": {\"title\": \"A\", \"type\": \"integer\"}, \"b\": {\"title\": \"B\", \"type\": \"integer\"}}\n assert tool.arg_types == {\"a\": int, \"b\": int}\n assert tool.arg_desc == {\"a\": \"No description provided. (Required)\", \"b\": \"No description provided. (Required)\"}\n assert await tool.acall(a=1, b=2) == 3\n\n\n@pytest.mark.asyncio\n@pytest.mark.extra\nasync def test_convert_custom_tool_with_custom", "label": 1, "sample_id": "stanfordnlp/dspy:tests/utils/test_langchain_tool.py", "category": "test", "repo_id": "stanfordnlp/dspy"} {"input": "import time\n\nfrom utils_tests.test_csp import basic_config, basic_policy\n\nfrom django.contrib.staticfiles.testing import StaticLiveServerTestCase\nfrom django.test import SimpleTestCase\nfrom django.test.selenium import SeleniumTestCase\nfrom django.test.utils import modify_settings, override_settings\nfrom django.utils.csp import CSP\n\nfrom .views import csp_reports\n\n\n@override_settings(\n MIDDLEWARE=[\"django.middleware.csp.ContentSecurityPolicyMiddleware\"],\n ROOT_URLCONF=\"middleware.urls\",\n)\nclass CSPMiddlewareTest(SimpleTestCase):\n @override_settings(SECURE_CSP=None, SECURE_CSP_REPORT_ONLY=None)\n def test_csp_defaults_off(self):\n response = self.client.get(\"/csp-base/\")\n self.assertNotIn(CSP.HEADER_ENFORCE, response)\n self.assertNotIn(CSP.HEADER_REPORT_ONLY, response)\n\n @override_settings(SECURE_CSP=basic_config, SECURE_CSP_REPORT_ONLY=None)\n def test_csp_basic(self):\n \"\"\"\n With SECURE_CSP set to a valid value, the middleware adds a\n \"Content-Security-Policy\" header to the response.\n \"\"\"\n response = self.client.get(\"/csp-base/\")\n self.assertEqual(response[CSP.HEADER_ENFORCE], basic", "label": 1, "sample_id": "django/django:tests/middleware/test_csp.py", "category": "test", "repo_id": "django/django"} {"input": "\"\"\"Sparse accessor\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom pandas.compat._optional import import_optional_dependency\n\nfrom pandas.core.dtypes.cast import find_common_type\nfrom pandas.core.dtypes.dtypes import SparseDtype\n\nfrom pandas.core.accessor import (\n PandasDelegate,\n delegate_names,\n)\nfrom pandas.core.arrays.sparse.array import SparseArray\n\nif TYPE_CHECKING:\n from scipy.sparse import (\n coo_matrix,\n spmatrix,\n )\n\n from pandas import (\n DataFrame,\n Series,\n )\n\n\nclass BaseAccessor:\n _validation_msg = \"Can only use the '.sparse' accessor with Sparse data.\"\n\n def __init__(self, data=None) -> None:\n self._parent = data\n self._validate(data)\n\n def _validate(self, data) -> None:\n raise NotImplementedError\n\n\n@delegate_names(\n SparseArray, [\"npoints\", \"density\", \"fill_value\", \"sp_values\"], typ=\"property\"\n)\nclass SparseAccessor(BaseAccessor, PandasDelegate):\n \"\"\"\n Accessor for SparseArray from other sparse matrix data types.\n\n Provides methods and properties to work with the underlying sparse data\n in a Series or DataFrame. It", "label": 0, "sample_id": "pandas-dev/pandas:pandas/core/arrays/sparse/accessor.py", "category": "unknown", "repo_id": "pandas-dev/pandas"} {"input": "from dataclasses import dataclass\n\n\n@dataclass\nclass ProjectInfo:\n \"\"\"Dataclass for storing project information.\"\"\"\n\n title: str\n author: str\n url: str\n description: str\n repo_url_part: str\n\n\nPROJECTS = [\n ProjectInfo(\n \"Posting\",\n \"Darren Burns\",\n \"https://posting.sh/\",\n \"Posting is an HTTP client, not unlike Postman and Insomnia. As a TUI application, it can be used over SSH and enables efficient keyboard-centric workflows. \",\n \"darrenburns/posting\",\n ),\n ProjectInfo(\n \"Memray\",\n \"Bloomberg\",\n \"https://github.com/bloomberg/memray\",\n \"Memray is a memory profiler for Python. It can track memory allocations in Python code, in native extension modules, and in the Python interpreter itself.\",\n \"bloomberg/memray\",\n ),\n ProjectInfo(\n \"Toolong\",\n \"Will McGugan\",\n \"https://github.com/Textualize/toolong\",\n \"A terminal application to view, tail, merge, and search log files (plus JSONL).\",\n \"Textualize/toolong\",\n ),\n ProjectInfo(\n", "label": 1, "sample_id": "Textualize/textual:src/textual/demo/_project_data.py", "category": "function_complex", "repo_id": "Textualize/textual"} {"input": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\n\nimport frappe\nfrom frappe import _\nfrom frappe.utils import add_to_date, formatdate, get_link_to_form, getdate, nowdate\nfrom frappe.utils.dashboard import cache_source\nfrom frappe.utils.dateutils import get_from_date_from_timespan, get_period_ending\nfrom frappe.utils.nestedset import get_descendants_of\n\n\n@frappe.whitelist()\n@cache_source\ndef get(\n\tchart_name: str | None = None,\n\tchart: str | dict | None = None,\n\tno_cache: bool | None = None,\n\tfilters: str | dict | None = None,\n\tfrom_date: str | None = None,\n\tto_date: str | None = None,\n\ttimespan: str | None = None,\n\ttime_interval: str | None = None,\n\theatmap_year: str | None = None,\n):\n\tif chart_name:\n\t\tchart = frappe.get_doc(\"Dashboard Chart\", chart_name)\n\telse:\n\t\tchart = frappe._dict(frappe.parse_json(chart))\n\ttimespan = chart.timespan\n\n\tif chart", "label": 0, "sample_id": "frappe/erpnext:erpnext/accounts/dashboard_chart_source/account_balance_timeline/account_balance_timeline.py", "category": "unknown", "repo_id": "frappe/erpnext"} {"input": "\"\"\"\nProject Euler Problem 345: https://projecteuler.net/problem=345\n\nMatrix Sum\n\nWe define the Matrix Sum of a matrix as the maximum possible sum of\nmatrix elements such that none of the selected elements share the same row or column.\n\nFor example, the Matrix Sum of the matrix below equals\n3315 ( = 863 + 383 + 343 + 959 + 767):\n 7 53 183 439 863\n 497 383 563 79 973\n 287 63 343 169 583\n 627 343 773 959 943\n 767 473 103 699 303\n\nFind the Matrix Sum of:\n 7 53 183 439 863 497 383 563 79 973 287 ", "label": 1, "sample_id": "TheAlgorithms/Python:project_euler/problem_345/sol1.py", "category": "documentation", "repo_id": "TheAlgorithms/Python"} {"input": "import asyncio\nimport json\nfrom pathlib import Path\nfrom typing import IO, Any, List, Optional, Union\nfrom uuid import uuid4\n\nfrom agno.knowledge.chunking.fixed import FixedSizeChunking\nfrom agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType\nfrom agno.knowledge.document.base import Document\nfrom agno.knowledge.reader.base import Reader\nfrom agno.knowledge.types import ContentType\nfrom agno.utils.log import log_debug, log_error\n\n\nclass JSONReader(Reader):\n \"\"\"Reader for JSON files\"\"\"\n\n chunk: bool = False\n\n def __init__(self, chunking_strategy: Optional[ChunkingStrategy] = FixedSizeChunking(), **kwargs):\n super().__init__(chunking_strategy=chunking_strategy, **kwargs)\n\n @classmethod\n def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]:\n \"\"\"Get the list of supported chunking strategies for JSON readers.\"\"\"\n return [\n ChunkingStrategyType.CODE_CHUNKER,\n ChunkingStrategyType.FIXED_SIZE_CHUNKER,\n ChunkingStrategyType.AGENTIC_CHUNKER,\n ChunkingStrategyType.DOCUMENT_CHUNKER,\n ChunkingStrategyType.RECURSIVE_CHUNK", "label": 1, "sample_id": "agno-agi/agno:libs/agno/agno/knowledge/reader/json_reader.py", "category": "function_complex", "repo_id": "agno-agi/agno"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, cast\n\nfrom streamlit.proto.Balloons_pb2 import Balloons as BalloonsProto\nfrom streamlit.runtime.metrics_util import gather_metrics\n\nif TYPE_CHECKING:\n from streamlit.delta_generator import DeltaGenerator\n\n\nclass BalloonsMixin:\n @gather_metrics(\"balloons\")\n def balloons(self) -> DeltaGenerator:\n \"\"\"Draw celebratory balloons.\n\n Examples\n --------\n >>> import streamlit", "label": 0, "sample_id": "streamlit/streamlit:lib/streamlit/elements/balloons.py", "category": "unknown", "repo_id": "streamlit/streamlit"} {"input": "import logging\n\nfrom redash.query_runner import (\n TYPE_BOOLEAN,\n TYPE_DATE,\n TYPE_DATETIME,\n TYPE_FLOAT,\n TYPE_INTEGER,\n TYPE_STRING,\n BaseSQLQueryRunner,\n InterruptException,\n register,\n)\n\nlogger = logging.getLogger(__name__)\n\ntry:\n import duckdb\n\n enabled = True\nexcept ImportError:\n enabled = False\n\n# Map DuckDB types to Redash column types\nTYPES_MAP = {\n \"BOOLEAN\": TYPE_BOOLEAN,\n \"TINYINT\": TYPE_INTEGER,\n \"SMALLINT\": TYPE_INTEGER,\n \"INTEGER\": TYPE_INTEGER,\n \"BIGINT\": TYPE_INTEGER,\n \"HUGEINT\": TYPE_INTEGER,\n \"REAL\": TYPE_FLOAT,\n \"DOUBLE\": TYPE_FLOAT,\n \"DECIMAL\": TYPE_FLOAT,\n \"VARCHAR\": TYPE_STRING,\n \"BLOB\": TYPE_STRING,\n \"DATE\": TYPE_DATE,\n \"TIMESTAMP\": TYPE_DATETIME,\n \"TIMESTAMP WITH TIME ZONE\": TYPE_DATETIME,\n \"TIME\": TYPE_DATETIME,\n \"INTERVAL\": TYPE_STRING,\n \"UUID\": TYPE_STRING,\n \"JSON\": TYPE_STRING,\n \"STRUCT\": TYPE_STRING,\n \"MAP\": TYPE_STRING,\n \"UNION\": TYPE", "label": 1, "sample_id": "getredash/redash:redash/query_runner/duckdb.py", "category": "function_complex", "repo_id": "getredash/redash"} {"input": "# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.\n\nimport math\nimport itertools\nimport os\nimport random\n\nimport pytest\nimport torch\n\nfrom einops import rearrange, repeat\n\ntry:\n from flash_attn.layers.rotary import apply_rotary_emb\nexcept ImportError:\n apply_rotary_emb = None\n\nfrom flash_attn.cute.testing import (\n attention_ref,\n generate_qkv,\n generate_random_padding_mask,\n pad_input,\n unpad_input,\n maybe_fake_tensor_mode,\n is_fake_mode,\n)\nfrom flash_attn.cute.interface import (\n flash_attn_func,\n flash_attn_varlen_func,\n flash_attn_combine,\n)\n\n# torch FakeTensorMode would enable fast cutedsl kernel compilation without allocating the actual GPU memory or running the kernel\n# When operating fake tensors, we cannot perform data-dependent operations (e.g., `tensor.max()`).\nUSE_FAKE_TENSOR = int(os.getenv(\"FLASH_ATTENTION_FAKE_TENSOR\", 0)) == 1\nDISABLE_SPLIT = os.getenv(\"FLASH_ATTENTION_DISABLE_SPLIT\", \"FALSE\") == \"TRUE\"\n", "label": 1, "sample_id": "Dao-AILab/flash-attention:tests/cute/test_flash_attn.py", "category": "test", "repo_id": "Dao-AILab/flash-attention"} {"input": "#!/usr/bin/env python3\n\"\"\"\nGenerate Kaplan-Meier Survival Curves for Clinical Decision Support Documents\n\nThis script creates publication-quality survival curves with:\n- Kaplan-Meier survival estimates\n- 95% confidence intervals\n- Log-rank test statistics\n- Hazard ratios with confidence intervals\n- Number at risk tables\n- Median survival annotations\n\nDependencies: lifelines, matplotlib, pandas, numpy\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom lifelines import KaplanMeierFitter\nfrom lifelines.statistics import logrank_test, multivariate_logrank_test\nfrom lifelines import CoxPHFitter\nimport argparse\nfrom pathlib import Path\n\n\ndef load_survival_data(filepath):\n \"\"\"\n Load survival data from CSV file.\n \n Expected columns:\n - patient_id: Unique patient identifier\n - time: Survival time (months or days)\n - event: Event indicator (1=event occurred, 0=censored)\n - group: Stratification variable (e.g., 'Biomarker+', 'Biomarker-')\n - Optional: Additional covariates for Cox regression\n \n Returns:\n pandas.DataFrame\n \"\"\"\n df = pd.read_csv(filepath)\n \n # Validate", "label": 1, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/scientific/clinical-decision-support/scripts/generate_survival_analysis.py", "category": "function_complex", "repo_id": "davila7/claude-code-templates"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom streamlit.errors import StreamlitAPIException\nfrom streamlit.url_util import is_url\n\nif TYPE_CHECKING:\n from streamlit.proto.NewSession_pb2 import CustomThemeConfig\n\n\ndef _parse_font_config(\n font_config: str | None,\n property_name: str,\n) -> tuple[str, str | None]:\n \"\"\"Parse a single font configuration string.\n\n Args:\n font_config: The font configuration string", "label": 1, "sample_id": "streamlit/streamlit:lib/streamlit/runtime/theme_util.py", "category": "license", "repo_id": "streamlit/streamlit"} {"input": "\"\"\"Mock implementation of redis for unit testing.\"\"\"\n\nimport asyncio\nimport contextlib\nimport fnmatch\nimport time\nfrom collections.abc import AsyncGenerator, Callable\nfrom typing import Any\nfrom unittest.mock import AsyncMock, Mock\n\nfrom redis.asyncio import Redis\nfrom redis.typing import EncodableT, KeyT\n\nfrom reflex.utils import prerequisites\n\nWRONGTYPE_MESSAGE = \"WRONGTYPE Operation against a key holding the wrong kind of value\"\n\n\ndef mock_redis() -> Redis:\n \"\"\"Mock the redis client with pubsub support.\n\n Returns:\n The mocked redis client.\n \"\"\"\n keys: dict[bytes, EncodableT | set[EncodableT]] = {}\n expire_times: dict[bytes, float] = {}\n event_log: list[dict[str, bytes]] = []\n event_log_new_events = asyncio.Event()\n\n def _key_bytes(key: KeyT) -> bytes:\n if isinstance(key, str):\n return key.encode()\n if isinstance(key, memoryview):\n return key.tobytes()\n return key\n\n def _keyspace_event(key: KeyT, data: str | bytes):\n if isinstance(key, str):\n key = key.encode()\n if isinstance(data, str):\n ", "label": 1, "sample_id": "reflex-dev/reflex:tests/units/mock_redis.py", "category": "test", "repo_id": "reflex-dev/reflex"} {"input": "import asyncio\nimport logging\nfrom typing import Any, List, Optional, Type\n\nfrom llama_index.core.base.base_query_engine import BaseQueryEngine\nfrom llama_index.core.base.llms.types import ChatMessage, MessageRole\nfrom llama_index.core.base.response.schema import (\n RESPONSE_TYPE,\n StreamingResponse,\n AsyncStreamingResponse,\n)\nfrom llama_index.core.callbacks import CallbackManager, trace_method\nfrom llama_index.core.chat_engine.types import (\n AgentChatResponse,\n BaseChatEngine,\n StreamingAgentChatResponse,\n)\nfrom llama_index.core.chat_engine.utils import (\n response_gen_from_query_engine,\n aresponse_gen_from_query_engine,\n)\nfrom llama_index.core.base.llms.generic_utils import messages_to_history_str\nfrom llama_index.core.llms.llm import LLM\nfrom llama_index.core.memory import BaseMemory, Memory\nfrom llama_index.core.prompts.base import BasePromptTemplate, PromptTemplate\nfrom llama_index.core.settings import Settings\n\nfrom llama_index.core.tools import ToolOutput\nfrom llama_index.core.types import Thread\n\nlogger = logging.getLogger(__name__)\n\n\nDEFAULT_TEMPLATE = \"\"\"\\\nGiven a conversation (between Human and Assistant) and a follow up message from Human, \\\nrewrite the message to be a standalone question that captures all relevant context \\\nfrom the conversation", "label": 0, "sample_id": "run-llama/llama_index:llama-index-core/llama_index/core/chat_engine/condense_question.py", "category": "unknown", "repo_id": "run-llama/llama_index"} {"input": "#!/usr/bin/env python3\n\nimport json\nimport os\nimport re\nimport sys\n\n\n_ = r\"\"\"\nreject file upload (with a nice explanation why)\n\nexample usage as global config:\n --xbu j,c1,bin/hooks/reject-and-explain.py\n\nexample usage as a volflag (per-volume config):\n -v srv/inc:inc:r:rw,ed:c,xbu=j,c1,bin/hooks/reject-and-explain.py\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n (share filesystem-path srv/inc as volume /inc,\n readable by everyone, read-write for user 'ed',\n running this plugin on all uploads with the params listed below)\n\nexample usage as a volflag in a copyparty config file:\n [/inc]\n srv/inc\n accs:\n r: *\n rw: ed\n flags:\n xbu: j,c1,bin/hooks/reject-and-explain.py\n\nparameters explained,\n xbu = execute-before-upload (can also be xau, execute-after-upload)\n j = this hook needs upload information as json (not just the filename)\n c1 = this hook returns json on stdout, so tell cop", "label": 1, "sample_id": "9001/copyparty:bin/hooks/reject-and-explain.py", "category": "documentation", "repo_id": "9001/copyparty"} {"input": "import numpy as np\nimport pytest\nfrom numpy.testing import assert_allclose\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import ClassicalMDS\nfrom sklearn.metrics import euclidean_distances\n\n\ndef test_classical_mds_equivalent_to_pca():\n X, _ = load_iris(return_X_y=True)\n\n cmds = ClassicalMDS(n_components=2, metric=\"euclidean\")\n pca = PCA(n_components=2)\n\n Z1 = cmds.fit_transform(X)\n Z2 = pca.fit_transform(X)\n\n # Swap the signs if necessary\n for comp in range(2):\n if Z1[0, comp] < 0 and Z2[0, comp] > 0:\n Z2[:, comp] *= -1\n\n assert_allclose(Z1, Z2)\n\n assert_allclose(np.sqrt(cmds.eigenvalues_), pca.singular_values_)\n\n\ndef test_classical_mds_equivalent_on_data_and_distances():\n X, _ = load_iris(return_X_y=True)\n\n cmds = ClassicalMDS(n_components=2, metric=\"euclidean\")\n Z1 = cmds.fit_transform(X)\n\n cmds = ClassicalMDS(n_components=2,", "label": 1, "sample_id": "scikit-learn/scikit-learn:sklearn/manifold/tests/test_classical_mds.py", "category": "test", "repo_id": "scikit-learn/scikit-learn"} {"input": "import pickle\nimport time\nimport logging\n\nimport pytest\nfrom cssselect import SelectorError, SelectorSyntaxError\n\nfrom scrapling import Selector\nlogging.getLogger(\"scrapling\").setLevel(logging.DEBUG)\n\n\n@pytest.fixture\ndef html_content():\n return \"\"\"\n \n \n Complex Web Page\n \n \n \n
\n \n
\n
\n
\n

Products

\n
\n
\n

Product 1

\n

This is product 1

\n $10.99\n", "label": 0, "sample_id": "D4Vinci/Scrapling:tests/parser/test_general.py", "category": "unknown", "repo_id": "D4Vinci/Scrapling"} {"input": "from __future__ import annotations\n\nimport uuid\nfrom ast import literal_eval\nfrom datetime import timedelta\nfrom enum import Enum\nfrom typing import TYPE_CHECKING, Annotated, Any\n\nfrom fastapi import Depends, HTTPException, Path, Query\nfrom fastapi_pagination import Params\nfrom lfx.graph.graph.base import Graph\nfrom lfx.log.logger import logger\nfrom lfx.services.deps import injectable_session_scope, injectable_session_scope_readonly, session_scope\nfrom lfx.utils.validate_cloud import raise_error_if_astra_cloud_disable_component\nfrom sqlalchemy import delete\nfrom sqlmodel.ext.asyncio.session import AsyncSession\n\nfrom langflow.services.auth.utils import get_current_active_user, get_current_active_user_mcp\nfrom langflow.services.database.models.flow.model import Flow\nfrom langflow.services.database.models.flow_version.model import FlowVersion\nfrom langflow.services.database.models.message.model import MessageTable\nfrom langflow.services.database.models.transactions.model import TransactionTable\nfrom langflow.services.database.models.user.model import User\nfrom langflow.services.database.models.vertex_builds.model import VertexBuildTable\nfrom langflow.services.store.utils import get_lf_version_from_pypi\nfrom langflow.utils.constants import LANGFLOW_GLOBAL_VAR_HEADER_PREFIX\n\nif TYPE_CHECKING:\n ", "label": 0, "sample_id": "langflow-ai/langflow:src/backend/base/langflow/api/utils/core.py", "category": "unknown", "repo_id": "langflow-ai/langflow"} {"input": "\"\"\" Attention Pool 2D\n\nImplementations of 2D spatial feature pooling using multi-head attention instead of average pool.\n\nBased on idea in CLIP by OpenAI, licensed Apache 2.0\nhttps://github.com/openai/CLIP/blob/3b473b0e682c091a9e53623eebc1ca1657385717/clip/model.py\n\nHacked together by / Copyright 2021 Ross Wightman\n\"\"\"\nfrom typing import Optional, Union, Tuple\n\nimport torch\nimport torch.nn as nn\n\nfrom .config import use_fused_attn\nfrom .helpers import to_2tuple\nfrom .pos_embed import resample_abs_pos_embed\nfrom .pos_embed_sincos import apply_rot_embed_cat, create_rope_embed\nfrom .weight_init import trunc_normal_\n\n\nclass RotAttentionPool2d(nn.Module):\n \"\"\" Attention based 2D feature pooling w/ rotary (relative) pos embedding.\n This is a multi-head attention based replacement for (spatial) average pooling in NN architectures.\n\n Adapted from the AttentionPool2d in CLIP w/ rotary embedding instead of learned embed.\n ", "label": 0, "sample_id": "huggingface/pytorch-image-models:timm/layers/attention_pool2d.py", "category": "unknown", "repo_id": "huggingface/pytorch-image-models"} {"input": "from typing import Any\n\nfrom pydantic import BaseModel\n\nfrom crewai_tools.tools.brave_search_tool.base import BraveSearchToolBase\nfrom crewai_tools.tools.brave_search_tool.schemas import (\n NewsSearchHeaders,\n NewsSearchParams,\n)\n\n\nclass BraveNewsSearchTool(BraveSearchToolBase):\n \"\"\"A tool that performs news searches using the Brave Search API.\"\"\"\n\n name: str = \"Brave News Search\"\n args_schema: type[BaseModel] = NewsSearchParams\n header_schema: type[BaseModel] = NewsSearchHeaders\n\n description: str = (\n \"A tool that performs news searches using the Brave Search API. \"\n \"Results are returned as structured JSON data.\"\n )\n\n search_url: str = \"https://api.search.brave.com/res/v1/news/search\"\n\n def _refine_request_payload(self, params: dict[str, Any]) -> dict[str, Any]:\n return params\n\n def _refine_response(self, response: dict[str, Any]) -> list[dict[str, Any]]:\n # Make the response more concise, and easier to consume\n results = response.get(\"results\", [])\n return [\n {\n \"url\": result.get(\"url\"),\n \"title", "label": 0, "sample_id": "crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/brave_search_tool/brave_news_tool.py", "category": "unknown", "repo_id": "crewAIInc/crewAI"} {"input": "from typing import final\n\nimport mlx.core as mx\nfrom mflux.models.qwen.model.qwen_transformer.qwen_attention import QwenAttention\nfrom mflux.models.qwen.model.qwen_transformer.qwen_transformer_block import (\n QwenTransformerBlock,\n)\nfrom pydantic import BaseModel, ConfigDict\n\nfrom exo.worker.engines.image.models.base import RotaryEmbeddings\nfrom exo.worker.engines.image.pipeline.block_wrapper import JointBlockWrapper\n\n\n@final\nclass QwenStreamModulation(BaseModel):\n model_config = ConfigDict(frozen=True, strict=True, arbitrary_types_allowed=True)\n\n mod1: mx.array\n mod2: mx.array\n gate1: mx.array\n\n\nclass QwenJointBlockWrapper(JointBlockWrapper[QwenTransformerBlock]):\n def __init__(\n self,\n block: QwenTransformerBlock,\n text_seq_len: int,\n encoder_hidden_states_mask: mx.array | None = None,\n ):\n super().__init__(block, text_seq_len)\n self._encoder_hidden_states_mask = encoder_hidden_states_mask\n\n self._num_heads = block.attn.num_heads\n self._head_dim = block.attn.head_dim\n\n # Intermediate state stored between _compute_q", "label": 1, "sample_id": "exo-explore/exo:src/exo/worker/engines/image/models/qwen/wrappers.py", "category": "function_simple", "repo_id": "exo-explore/exo"} {"input": "from changedetectionio import queuedWatchMetaData\nfrom changedetectionio import worker_pool\nfrom flask_restful import abort, Resource\nfrom loguru import logger\n\nimport threading\nfrom flask import request\nfrom . import auth\n\nfrom . import validate_openapi_request\n\n\nclass Tag(Resource):\n def __init__(self, **kwargs):\n # datastore is a black box dependency\n self.datastore = kwargs['datastore']\n self.update_q = kwargs['update_q']\n\n # Get information about a single tag\n # curl http://localhost:5000/api/v1/tag/\n @auth.check_token\n @validate_openapi_request('getTag')\n def get(self, uuid):\n \"\"\"Get data for a single tag/group, toggle notification muting, or recheck all.\"\"\"\n tag = self.datastore.data['settings']['application']['tags'].get(uuid)\n if not tag:\n abort(404, message=f'No tag exists with the UUID of {uuid}')\n\n if request.args.get('recheck'):\n # Recheck all watches with this tag, including muted\n # First collect watches to queue\n watches_to_queue = []\n for k in sorted(self.datastore.data", "label": 0, "sample_id": "dgtlmoon/changedetection.io:changedetectionio/api/Tags.py", "category": "unknown", "repo_id": "dgtlmoon/changedetection.io"} {"input": "shell_cmd_prompt = \"\"\"\n4. *Concisely* suggest any shell commands the user might want to run in ```bash blocks.\n\nJust suggest shell commands this way, not example code.\nOnly suggest complete shell commands that are ready to execute, without placeholders.\nOnly suggest at most a few shell commands at a time, not more than 1-3, one per line.\nDo not suggest multi-line shell commands.\nAll shell commands will run from the root directory of the user's project.\n\nUse the appropriate shell based on the user's system info:\n{platform}\nExamples of when to suggest shell commands:\n\n- If you changed a self-contained html file, suggest an OS-appropriate command to open a browser to view it to see the updated content.\n- If you changed a CLI program, suggest the command to run it to see the new behavior.\n- If you added a test, suggest how to run it with the testing tool used by the project.\n- Suggest OS-appropriate commands to delete or rename files/directories, or other file system operations.\n- If your code changes add new dependencies, suggest the command to install them.\n- Etc.\n\"\"\" # noqa\n\nno_shell_cmd_prompt = \"\"\"\nKeep in mind these details about the user's platform and", "label": 1, "sample_id": "Aider-AI/aider:aider/coders/shell.py", "category": "documentation", "repo_id": "Aider-AI/aider"} {"input": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\nimport importlib.util\nimport json\nimport logging\n\nimport pytest\nimport pytest_asyncio\nfrom openai import OpenAI\n\nfrom tests.utils import RemoteOpenAIServer\n\nfrom .conftest import (\n BASE_TEST_ENV,\n has_output_type,\n log_response_diagnostics,\n retry_for_tool_call,\n)\n\nlogger = logging.getLogger(__name__)\n\nMODEL_NAME = \"Qwen/Qwen3-8B\"\n\n_PYTHON_TOOL_INSTRUCTION = (\n \"You must use the Python tool to execute code. \"\n \"Never simulate execution. You must print the final answer.\"\n)\n\n\n@pytest.fixture(scope=\"module\")\ndef server():\n assert importlib.util.find_spec(\"gpt_oss\") is not None, (\n \"Harmony tests require gpt_oss package to be installed\"\n )\n\n args = [\n \"--reasoning-parser\",\n \"qwen3\",\n \"--max_model_len\",\n \"5000\",\n \"--structured-outputs-config.backend\",\n \"xgrammar\",\n \"--enable-auto-tool-choice\",\n \"--tool-call-parser\",\n \"hermes\",\n \"--tool-server\",\n", "label": 0, "sample_id": "vllm-project/vllm:tests/entrypoints/openai/responses/test_parsable_context.py", "category": "unknown", "repo_id": "vllm-project/vllm"} {"input": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\n\nimport pytest\n\nfrom verl.single_controller.base import Worker\n\n\ndef test_get_set_dispatch_collect_cpu():\n os.environ[\"RANK\"] = \"0\"\n os.environ[\"LOCAL_RANK\"] = \"0\"\n os.environ[\"WORLD_SIZE\"] = \"2\"\n os.environ[\"MASTER_ADDR\"] = \"localhost\"\n os.environ[\"MASTER_PORT\"] = \"12345\"\n\n ref = Worker()\n ref._register_dispatch_collect_info(mesh_name=\"actor\", dp_rank=0, is_collect=True)\n\n actor = Worker()\n actor._register_dispatch", "label": 1, "sample_id": "verl-project/verl:tests/single_controller/test_get_set_dispatch_collect_cpu.py", "category": "test", "repo_id": "verl-project/verl"} {"input": "import os\n\nZULIP_VERSION = \"12.0-beta1+git\"\n\n# Add information on number of commits and commit hash to version, if available\nZULIP_VERSION_WITHOUT_COMMIT = ZULIP_VERSION\nzulip_git_version_file = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"zulip-git-version\"\n)\nlines = [ZULIP_VERSION, \"\"]\nif os.path.exists(zulip_git_version_file):\n with open(zulip_git_version_file) as f:\n lines = [*f, \"\", \"\"]\nZULIP_VERSION = lines.pop(0).strip()\nZULIP_MERGE_BASE = lines.pop(0).strip()\n\nLATEST_MAJOR_VERSION = \"11.0\"\nLATEST_RELEASE_VERSION = \"11.5\"\nLATEST_RELEASE_ANNOUNCEMENT = \"https://blog.zulip.com/zulip-server-11-0\"\n\n# Versions of the desktop app below DESKTOP_MINIMUM_VERSION will be\n# prevented from connecting to the Zulip server. Versions above\n# DESKTOP_MINIMUM_VERSION but below DESKTOP_WARNING_VERSION will have\n# a banner at the top of the page asking the user to upgrade", "label": 0, "sample_id": "zulip/zulip:version.py", "category": "unknown", "repo_id": "zulip/zulip"} {"input": "\"\"\"\nBidirectional Search Algorithm.\n\nThis algorithm searches from both the source and target nodes simultaneously,\nmeeting somewhere in the middle. This approach can significantly reduce the\nsearch space compared to a traditional one-directional search.\n\nTime Complexity: O(b^(d/2)) where b is the branching factor and d is the depth\nSpace Complexity: O(b^(d/2))\n\nhttps://en.wikipedia.org/wiki/Bidirectional_search\n\"\"\"\n\nfrom collections import deque\n\n\ndef expand_search(\n graph: dict[int, list[int]],\n queue: deque[int],\n parents: dict[int, int | None],\n opposite_direction_parents: dict[int, int | None],\n) -> int | None:\n if not queue:\n return None\n\n current = queue.popleft()\n for neighbor in graph[current]:\n if neighbor in parents:\n continue\n\n parents[neighbor] = current\n queue.append(neighbor)\n\n # Check if this creates an intersection\n if neighbor in opposite_direction_parents:\n return neighbor\n\n return None\n\n\ndef construct_path(current: int | None, parents: dict[int, int | None]) -> list[int]:\n path: list[int] = []\n while current is not None:\n path.append(current)\n current = parents[current", "label": 1, "sample_id": "TheAlgorithms/Python:graphs/bidirectional_search.py", "category": "function_complex", "repo_id": "TheAlgorithms/Python"} {"input": "# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .._utils.cli import (\n get_subcommand_args,\n str2bool,\n)\nfrom .base import PaddleXPipelineWrapper, PipelineCLISubcommandExecutor\nfrom .utils import create_config_from_structure\n\n\nclass PPChatOCRv4Doc(PaddleXPipelineWrapper):\n def __init__(\n self,\n layout_detection_model_name=None,\n layout_detection_model_dir=None,\n doc_orientation_classify_model_name=None,\n doc_orientation_classify_model_dir=None,\n doc_unwarping_model_name=None,\n doc_unwarping_model_dir", "label": 1, "sample_id": "PaddlePaddle/PaddleOCR:paddleocr/_pipelines/pp_chatocrv4_doc.py", "category": "license", "repo_id": "PaddlePaddle/PaddleOCR"} {"input": "\"\"\"Feishu/Lark channel implementation using lark-oapi SDK with WebSocket long connection.\"\"\"\n\nimport asyncio\nimport json\nimport os\nimport re\nimport threading\nfrom collections import OrderedDict\nfrom pathlib import Path\nfrom typing import Any\n\nfrom loguru import logger\n\nfrom nanobot.bus.events import OutboundMessage\nfrom nanobot.bus.queue import MessageBus\nfrom nanobot.channels.base import BaseChannel\nfrom nanobot.config.schema import FeishuConfig\n\ntry:\n import lark_oapi as lark\n from lark_oapi.api.im.v1 import (\n CreateFileRequest,\n CreateFileRequestBody,\n CreateImageRequest,\n CreateImageRequestBody,\n CreateMessageReactionRequest,\n CreateMessageReactionRequestBody,\n CreateMessageRequest,\n CreateMessageRequestBody,\n Emoji,\n GetMessageResourceRequest,\n P2ImMessageReceiveV1,\n )\n FEISHU_AVAILABLE = True\nexcept ImportError:\n FEISHU_AVAILABLE = False\n lark = None\n Emoji = None\n\n# Message type display mapping\nMSG_TYPE_MAP = {\n \"image\": \"[image]\",\n \"audio\": \"[audio]\",\n \"file\": \"[file]\",\n \"sticker\": \"[sticker]\",\n}\n\n\ndef _extract_share_card", "label": 1, "sample_id": "HKUDS/nanobot:nanobot/channels/feishu.py", "category": "function_complex", "repo_id": "HKUDS/nanobot"} {"input": "from dataclasses import dataclass\nfrom datetime import datetime\nfrom typing import Any, NamedTuple\n\nfrom app.assets.database.models import Asset, AssetReference\n\nUserMetadata = dict[str, Any] | None\n\n\n@dataclass(frozen=True)\nclass AssetData:\n hash: str | None\n size_bytes: int | None\n mime_type: str | None\n\n\n@dataclass(frozen=True)\nclass ReferenceData:\n \"\"\"Data transfer object for AssetReference.\"\"\"\n\n id: str\n name: str\n file_path: str | None\n user_metadata: UserMetadata\n preview_id: str | None\n created_at: datetime\n updated_at: datetime\n system_metadata: dict[str, Any] | None = None\n job_id: str | None = None\n last_access_time: datetime | None = None\n\n\n@dataclass(frozen=True)\nclass AssetDetailResult:\n ref: ReferenceData\n asset: AssetData | None\n tags: list[str]\n\n\n@dataclass(frozen=True)\nclass RegisterAssetResult:\n ref: ReferenceData\n asset: AssetData\n tags: list[str]\n created: bool\n\n\n@dataclass(frozen=True)\nclass IngestResult:\n ", "label": 0, "sample_id": "Comfy-Org/ComfyUI:app/assets/services/schemas.py", "category": "unknown", "repo_id": "Comfy-Org/ComfyUI"} {"input": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport copy\nimport torch\nimport warnings\nimport numpy as np\nimport pandas as pd\nfrom qlib.utils.data import guess_horizon\nfrom qlib.utils import init_instance_by_config\n\nfrom qlib.data.dataset import DatasetH\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n\ndef _to_tensor(x):\n if not isinstance(x, torch.Tensor):\n return torch.tensor(x, dtype=torch.float, device=device) # pylint: disable=E1101\n return x\n\n\ndef _create_ts_slices(index, seq_len):\n \"\"\"\n create time series slices from pandas index\n\n Args:\n index (pd.MultiIndex): pandas multiindex with order\n seq_len (int): sequence length\n \"\"\"\n assert isinstance(index, pd.MultiIndex), \"unsupported index type\"\n assert seq_len > 0, \"sequence length should be larger than 0\"\n assert index.is_monotonic_increasing, \"index should be sorted\"\n\n # number of dates for each instrument\n sample_count_by_insts = index.to_series().groupby(level=0, group_keys=False).size().values\n\n", "label": 0, "sample_id": "microsoft/qlib:qlib/contrib/data/dataset.py", "category": "unknown", "repo_id": "microsoft/qlib"} {"input": "\"\"\"\nOpenRouter model metadata caching and lookup.\n\nThis module keeps a local cached copy of the OpenRouter model list\n(downloaded from ``https://openrouter.ai/api/v1/models``) and exposes a\nhelper class that returns metadata for a given model in a format compatible\nwith litellm’s ``get_model_info``.\n\"\"\"\nfrom __future__ import annotations\n\nimport json\nimport time\nfrom pathlib import Path\nfrom typing import Dict\n\nimport requests\n\n\ndef _cost_per_token(val: str | None) -> float | None:\n \"\"\"Convert a price string (USD per token) to a float.\"\"\"\n if val in (None, \"\", \"0\"):\n return 0.0 if val == \"0\" else None\n try:\n return float(val)\n except Exception: # noqa: BLE001\n return None\n\n\nclass OpenRouterModelManager:\n MODELS_URL = \"https://openrouter.ai/api/v1/models\"\n CACHE_TTL = 60 * 60 * 24 # 24 h\n\n def __init__(self) -> None:\n self.cache_dir = Path.home() / \".aider\" / \"caches\"\n self.cache_file = self.cache", "label": 1, "sample_id": "Aider-AI/aider:aider/openrouter.py", "category": "function_complex", "repo_id": "Aider-AI/aider"} {"input": "# Copyright (c) Microsoft Corporation.\n# SPDX-License-Identifier: Apache-2.0\n\n# DeepSpeed Team\n\nimport math\nfrom pydantic import field_validator\nfrom deepspeed.runtime.config_utils import DeepSpeedConfigModel\nfrom .fp16.loss_scaler import (\n INITIAL_LOSS_SCALE,\n SCALE_WINDOW,\n DELAYED_SHIFT,\n CONSECUTIVE_HYSTERESIS,\n MIN_LOSS_SCALE,\n)\n\n#########################################\n# BFLOAT16 support\n#########################################\n# BFLOAT16 feature. By default, this feature is not enabled.\n# Users can configure in ds_config.json as below example:\nBFLOAT16_FORMAT = '''\nBFLOAT16 parameters should be of the format:\n\"bf16\": {\n \"enabled\": true,\n \"immediate_grad_update\": false,\n \"check_grad_overflow\": false\n}\n'''\nBFLOAT16 = \"bf16\"\nBFLOAT16_OLD = \"bfloat16\" # keeping for backwards compatibility\n\n\ndef get_bfloat16_config(param_dict):\n bf16_config_dict = param_dict.get(BFLOAT16, None)\n if bf16_config_dict is None:\n bf16_config_dict = param_dict.get(BFLOAT", "label": 0, "sample_id": "deepspeedai/DeepSpeed:deepspeed/runtime/precision_config.py", "category": "unknown", "repo_id": "deepspeedai/DeepSpeed"} {"input": "# Copyright 2026 Marimo. All rights reserved.\nfrom __future__ import annotations\n\nimport urllib.error\nimport urllib.request\nfrom typing import Optional\n\nfrom marimo import _loggers\nfrom marimo._save.stores.store import Store\nfrom marimo._version import __version__\n\nLOGGER = _loggers.marimo_logger()\n\n\nclass RestStore(Store):\n def __init__(\n self, *, base_url: str, api_key: str, project_id: Optional[str] = None\n ) -> None:\n super().__init__()\n assert api_key, \"api_key is required\"\n assert base_url, \"base_url is required\"\n\n self.base_url = base_url\n self.api_key = api_key\n self.project_id = project_id\n self.headers = {\n \"Authorization\": f\"Bearer {self.api_key}\",\n \"User-Agent\": f\"marimo/{__version__}\",\n }\n import ssl\n\n self.context = ssl.create_default_context()\n\n def get(self, key: str) -> Optional[bytes]:\n url = self._get_url(key)\n req = urllib.request.Request(url, headers=self.headers)\n try:\n with urllib.request.urlopen(req, context=self.context)", "label": 1, "sample_id": "marimo-team/marimo:marimo/_save/stores/rest.py", "category": "function_complex", "repo_id": "marimo-team/marimo"} {"input": "\"\"\"Matrix Exponentiation\"\"\"\n\nimport timeit\n\n\"\"\"\nMatrix Exponentiation is a technique to solve linear recurrences in logarithmic time.\nYou read more about it here:\nhttps://zobayer.blogspot.com/2010/11/matrix-exponentiation.html\nhttps://www.hackerearth.com/practice/notes/matrix-exponentiation-1/\n\"\"\"\n\n\nclass Matrix:\n def __init__(self, arg: list[list] | int) -> None:\n if isinstance(arg, list): # Initializes a matrix identical to the one provided.\n self.t = arg\n self.n = len(arg)\n else: # Initializes a square matrix of the given size and set values to zero.\n self.n = arg\n self.t = [[0 for _ in range(self.n)] for _ in range(self.n)]\n\n def __mul__(self, b: Matrix) -> Matrix:\n matrix = Matrix(self.n)\n for i in range(self.n):\n for j in range(self.n):\n for k in range(self.n):\n matrix.t[i][j] += self.t[i][k] * b.t[k][j]\n return matrix\n\n\ndef modular_exponentiation(a: Matrix, b:", "label": 0, "sample_id": "TheAlgorithms/Python:maths/matrix_exponentiation.py", "category": "unknown", "repo_id": "TheAlgorithms/Python"} {"input": "\"\"\"\nMemory service for handling memory query operations via cloud protocol.\n\nProvides a unified interface for listing and reading memory files,\ncallable from the cloud client (LinkAI) or a future web console.\n\nMemory file layout (under workspace_root):\n MEMORY.md -> type: global\n memory/2026-02-20.md -> type: daily\n\"\"\"\n\nimport os\nfrom datetime import datetime\nfrom typing import Dict, List, Optional\nfrom pathlib import Path\nfrom common.log import logger\n\n\nclass MemoryService:\n \"\"\"\n High-level service for memory file queries.\n Operates directly on the filesystem — no MemoryManager dependency.\n \"\"\"\n\n def __init__(self, workspace_root: str):\n \"\"\"\n :param workspace_root: Workspace root directory (e.g. ~/cow)\n \"\"\"\n self.workspace_root = workspace_root\n self.memory_dir = os.path.join(workspace_root, \"memory\")\n\n # ------------------------------------------------------------------\n # list — paginated file metadata\n # ------------------------------------------------------------------\n def list_files(self, page: int = 1, page_size: int = 20) -> dict:\n \"\"\"\n List all memory files with metadata (without content).\n\n Returns::\n\n {\n \"page\": 1,\n ", "label": 1, "sample_id": "zhayujie/chatgpt-on-wechat:agent/memory/service.py", "category": "function_complex", "repo_id": "zhayujie/chatgpt-on-wechat"} {"input": "r\"\"\"Mobjects representing matrices.\n\nExamples\n--------\n\n.. manim:: MatrixExamples\n :save_last_frame:\n\n class MatrixExamples(Scene):\n def construct(self):\n m0 = Matrix([[\"\\\\pi\", 0], [-1, 1]])\n m1 = IntegerMatrix([[1.5, 0.], [12, -1.3]],\n left_bracket=\"(\",\n right_bracket=\")\")\n m2 = DecimalMatrix(\n [[3.456, 2.122], [33.2244, 12.33]],\n element_to_mobject_config={\"num_decimal_places\": 2},\n left_bracket=r\"\\{\",\n right_bracket=r\"\\}\")\n m3 = MobjectMatrix(\n [[Circle().scale(0.3), Square().scale(0.3)],\n [MathTex(\"\\\\pi\").scale(2), Star().scale(0.3)]],\n left_bracket=\"\\\\langle\",\n right_bracket=\"\\\\rangle\")\n g = Group(m0, m1, m2, m3).arrange_in_grid(buff=2)\n self.add(g)\n\"\"\"\n\nfrom __future__ import annotations\n\n", "label": 0, "sample_id": "ManimCommunity/manim:manim/mobject/matrix.py", "category": "unknown", "repo_id": "ManimCommunity/manim"} {"input": "\"\"\"Ministral3 templates\"\"\"\n\nfrom mlc_llm.protocol.conversation_protocol import Conversation, MessagePlaceholders\n\nfrom .registry import ConvTemplateRegistry\n\n# Ministral3\nConvTemplateRegistry.register_conv_template(\n Conversation(\n name=\"ministral3\",\n system_template=(\n f\"[SYSTEM_PROMPT]{MessagePlaceholders.SYSTEM.value}[/SYSTEM_PROMPT]\"\n f\"{MessagePlaceholders.FUNCTION.value}\"\n ),\n system_message=(\n \"You are Ministral-3-3B-Instruct-2512, a Large Language Model (LLM) created by \"\n \"Mistral AI, a French startup headquartered in Paris.\\n\"\n \"You power an AI assistant called Le Chat.\\n\"\n \"Your knowledge base was last updated on 2023-10-01.\\n\"\n \"The current date is {today}.\\n\\n\"\n \"When you're not sure about some information or when the user's request requires \"\n \"up-to-date or specific data, you must use the available tools to fetch the \"\n \"information. Do not hesitate to use tools whenever they can provide a more \"\n \"accurate or complete response. If no relevant tools are available,", "label": 1, "sample_id": "mlc-ai/mlc-llm:python/mlc_llm/conversation_template/ministral3.py", "category": "function_simple", "repo_id": "mlc-ai/mlc-llm"} {"input": "from argparse import ArgumentParser\nfrom http import HTTPStatus\nfrom typing import Annotated, Any\n\nimport ormsgpack\nfrom baize.datastructures import ContentType\nfrom kui.asgi import (\n HTTPException,\n HttpRequest,\n JSONResponse,\n request,\n)\nfrom loguru import logger\nfrom pydantic import BaseModel\n\nfrom fish_speech.inference_engine import TTSInferenceEngine\nfrom fish_speech.utils.schema import ServeTTSRequest\nfrom tools.server.inference import inference_wrapper as inference\n\n\ndef parse_args():\n parser = ArgumentParser()\n parser.add_argument(\"--mode\", type=str, choices=[\"tts\"], default=\"tts\")\n parser.add_argument(\n \"--llama-checkpoint-path\",\n type=str,\n default=\"checkpoints/s2-pro\",\n )\n parser.add_argument(\n \"--decoder-checkpoint-path\",\n type=str,\n default=\"checkpoints/s2-pro/codec.pth\",\n )\n parser.add_argument(\"--decoder-config-name\", type=str, default=\"modded_dac_vq\")\n parser.add_argument(\"--device\", type=str, default=\"cuda\")\n parser.add_argument(\"--half\", action=\"store_true\")\n parser.add_argument(\"--compile\", action=\"store_true\")\n parser.add_argument", "label": 0, "sample_id": "fishaudio/fish-speech:tools/server/api_utils.py", "category": "unknown", "repo_id": "fishaudio/fish-speech"} {"input": "# SPDX-License-Identifier: Apache-2.0\n\n# Copyright (c) ONNX Project Contributors\nfrom __future__ import annotations\n\nimport unittest\n\nimport parameterized\n\nimport onnx.helper\nimport onnx.shape_inference\n\n\nclass NodeInferenceTest(unittest.TestCase):\n @parameterized.parameterized.expand(\n [\n (\"GreaterOrEqual\",),\n (\"LessOrEqual\",),\n ]\n )\n def test_comparison_op(self, op_type):\n node = onnx.helper.make_node(op_type, [\"x\", \"y\"], [\"z\"])\n schema = onnx.defs.get_schema(node.op_type, 23, \"\")\n xtype = onnx.helper.make_tensor_type_proto(onnx.TensorProto.INT32, [1, 10])\n ytype = onnx.helper.make_tensor_type_proto(onnx.TensorProto.INT32, [10, 1])\n result = onnx.shape_inference.infer_node_outputs(\n schema, node, {\"x\": xtype, \"y\": ytype}\n )\n self.assertEqual(list(result.keys()), [\"z\"])\n self.assertEqual(result[\"z\"].tensor_type.elem_type, onnx.TensorProto.BOOL)\n self.assertEqual(\n [dim.dim_value for dim in result[\"", "label": 1, "sample_id": "onnx/onnx:onnx/test/node_shape_inference_test.py", "category": "test", "repo_id": "onnx/onnx"} {"input": "import os\nimport time\nimport pytest\nimport numpy as np\n\nfrom cereal.services import SERVICE_LIST\nfrom openpilot.tools.lib.log_time_series import msgs_to_time_series\nfrom openpilot.system.camerad.snapshot import get_snapshots\nfrom openpilot.selfdrive.test.helpers import collect_logs, log_collector, processes_context\n\nTEST_TIMESPAN = 10\nCAMERAS = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState')\nEXPOSURE_STABLE_COUNT = 3\nEXPOSURE_RANGE = (0.15, 0.35)\nMAX_TEST_TIME = 25\n\n\ndef _numpy_rgb2gray(im):\n return np.clip(im[:,:,2] * 0.114 + im[:,:,1] * 0.587 + im[:,:,0] * 0.299, 0, 255).astype(np.uint8)\n\ndef _exposure_stats(im):\n h, w = im.shape[:2]\n gray = _numpy_rgb2gray(im[h//10:9*h//10, w//10:9*w//10])\n return float(np.median(gray) / 255.), float", "label": 0, "sample_id": "commaai/openpilot:system/camerad/test/test_camerad.py", "category": "unknown", "repo_id": "commaai/openpilot"} {"input": "# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nfrom typing import List, Union, Optional\nfrom typing_extensions import Literal, Annotated, TypeAlias\n\nfrom ..._utils import PropertyInfo\nfrom ..._models import BaseModel\nfrom .custom_tool import CustomTool\n\n__all__ = [\"NamespaceTool\", \"Tool\", \"ToolFunction\"]\n\n\nclass ToolFunction(BaseModel):\n name: str\n\n type: Literal[\"function\"]\n\n defer_loading: Optional[bool] = None\n \"\"\"Whether this function should be deferred and discovered via tool search.\"\"\"\n\n description: Optional[str] = None\n\n parameters: Optional[object] = None\n\n strict: Optional[bool] = None\n\n\nTool: TypeAlias = Annotated[Union[ToolFunction, CustomTool], PropertyInfo(discriminator=\"type\")]\n\n\nclass NamespaceTool(BaseModel):\n \"\"\"Groups function/custom tools under a shared namespace.\"\"\"\n\n description: str\n \"\"\"A description of the namespace shown to the model.\"\"\"\n\n name: str\n \"\"\"The namespace name used in tool calls (for example, `crm`).\"\"\"\n\n tools: List[Tool]\n \"\"\"The function/custom tools available inside this namespace.\"\"\"\n\n type: Literal[\"namespace\"]\n \"\"\"", "label": 0, "sample_id": "openai/openai-python:src/openai/types/responses/namespace_tool.py", "category": "unknown", "repo_id": "openai/openai-python"} {"input": "# Copyright 2026 The JAX Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"NumPy function implementations as hijax primitives.\"\"\"\nimport functools\nimport operator\nfrom typing import Any, Callable\n\nimport numpy as np\n\nfrom jax._src import ad_util\nfrom jax._src import api\nfrom jax._src import core\nfrom jax._src import dtypes\nfrom jax._src import numpy as jnp\nfrom jax._src.hijax import VJPHiPrimitive\nfrom jax._src.lax import control_flow\nfrom jax._src.lax import lax\nfrom jax._src.typing import Array, ArrayLike, DType", "label": 0, "sample_id": "jax-ml/jax:jax/_src/numpy/hijax.py", "category": "unknown", "repo_id": "jax-ml/jax"} {"input": "#!/usr/bin/env python3\n\"\"\"\nQuick exploration of Neuropixels recording.\n\nUsage:\n python explore_recording.py /path/to/spikeglx/data\n\"\"\"\n\nimport argparse\nimport spikeinterface.full as si\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef explore_recording(data_path: str, stream_id: str = 'imec0.ap'):\n \"\"\"Explore a Neuropixels recording.\"\"\"\n\n print(f\"Loading: {data_path}\")\n recording = si.read_spikeglx(data_path, stream_id=stream_id)\n\n # Basic info\n print(\"\\n\" + \"=\"*50)\n print(\"RECORDING INFO\")\n print(\"=\"*50)\n print(f\"Channels: {recording.get_num_channels()}\")\n print(f\"Duration: {recording.get_total_duration():.2f} s ({recording.get_total_duration()/60:.2f} min)\")\n print(f\"Sampling rate: {recording.get_sampling_frequency()} Hz\")\n print(f\"Total samples: {recording.get_num_samples()}\")\n\n # Probe info\n probe = recording.get_probe()\n print(f\"\\nProbe: {probe.manufacturer} {probe.model_name if hasattr(probe, 'model", "label": 1, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/scientific/neuropixels-analysis/scripts/explore_recording.py", "category": "function_complex", "repo_id": "davila7/claude-code-templates"} {"input": "\"\"\"\nClassical multi-dimensional scaling (classical MDS).\n\"\"\"\n\n# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause\n\nfrom numbers import Integral\n\nimport numpy as np\nfrom scipy import linalg\n\nfrom sklearn.base import BaseEstimator, _fit_context\nfrom sklearn.metrics import pairwise_distances\nfrom sklearn.utils import check_symmetric\nfrom sklearn.utils._param_validation import Interval\nfrom sklearn.utils.extmath import svd_flip\nfrom sklearn.utils.validation import validate_data\n\n\nclass ClassicalMDS(BaseEstimator):\n \"\"\"Classical multidimensional scaling (MDS).\n\n This is also known as principal coordinates analysis (PCoA) or\n Torgerson's scaling. It is a version of MDS that has exact solution\n in terms of eigendecomposition. If the input dissimilarity matrix\n consists of the pairwise Euclidean distances between some vectors,\n then classical MDS is equivalent to PCA applied to this set of vectors.\n\n Read more in the :ref:`User Guide `.\n\n Parameters\n ----------\n n_components : int, default=2\n Number of embedding dimensions.\n\n metric : str or callable, default='euclidean'\n Metric to use", "label": 1, "sample_id": "scikit-learn/scikit-learn:sklearn/manifold/_classical_mds.py", "category": "license", "repo_id": "scikit-learn/scikit-learn"} {"input": "# Copyright (c) Microsoft Corporation.\n# SPDX-License-Identifier: Apache-2.0\n\n# DeepSpeed Team\n\nimport numpy\nimport torch\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass serialize_details:\n obj: object\n dtype: torch.dtype\n size: int\n nbytes: int\n\n\ndef tensor_to_bytes(tensor):\n return tensor.numpy().tobytes()\n\n\ndef bytes_to_tensor(buffer):\n return torch.from_numpy(numpy.array(numpy.frombuffer(buffer, dtype=numpy.uint8)))\n\n\ndef required_minimum_torch_version(major_version, minor_version):\n TORCH_MAJOR = int(torch.__version__.split('.')[0])\n TORCH_MINOR = int(torch.__version__.split('.')[1])\n\n if TORCH_MAJOR < major_version:\n return False\n\n return TORCH_MAJOR > major_version or TORCH_MINOR >= minor_version\n\n\n# torch < 1.12\ndef _legacy_obj_serialization_details(storage_obj):\n nbytes = storage_obj.element_size() * storage_obj.size()\n return serialize_details(obj=storage_obj, dtype=storage_obj.dtype, size=nbytes, nbytes=nbytes)\n\n\n# torch >= 1.12\ndef _new_obj_serialization_details(storage_obj):\n obj, dtype = storage_obj", "label": 1, "sample_id": "deepspeedai/DeepSpeed:deepspeed/io/utils.py", "category": "license", "repo_id": "deepspeedai/DeepSpeed"} {"input": "import pytest\n\nfrom agno.agent import Agent, RunOutput\nfrom agno.db.sqlite import SqliteDb\nfrom agno.models.vercel import V0\n\n\ndef _assert_metrics(response: RunOutput):\n assert response.metrics is not None\n input_tokens = response.metrics.input_tokens\n output_tokens = response.metrics.output_tokens\n total_tokens = response.metrics.total_tokens\n\n assert input_tokens > 0\n assert output_tokens > 0\n assert total_tokens > 0\n assert total_tokens == input_tokens + output_tokens\n\n\ndef test_basic():\n agent = Agent(model=V0(id=\"v0-1.0-md\"), markdown=True, telemetry=False)\n\n response: RunOutput = agent.run(\"Share a 2 sentence horror story\")\n\n assert response.content is not None\n assert response.messages is not None\n assert len(response.messages) == 3\n assert [m.role for m in response.messages] == [\"system\", \"user\", \"assistant\"]\n\n _assert_metrics(response)\n\n\ndef test_basic_stream():\n agent = Agent(model=V0(id=\"v0-1.0-md\"), markdown=True, telemetry=False)\n\n for response in agent.run(\"Share a 2 sentence horror story\", stream=True", "label": 1, "sample_id": "agno-agi/agno:libs/agno/tests/integration/models/vercel/test_basic.py", "category": "test", "repo_id": "agno-agi/agno"} {"input": "# Copyright 2026 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport asyncio\nimport uuid\n\nimport numpy as np\nimport pytest\nimport ray\nimport torch\nfrom omegaconf import OmegaConf\nfrom PIL import Image\nfrom transformers import AutoTokenizer\n\nUNIMODAL_MODEL_PATH = \"Qwen/Qwen2.5-Math-7B\"\nMULTIMODAL_MODEL_PATH = \"Qwen/Qwen2.5-VL-7B-Instruct\"\n\nMAX_MODEL_LEN = 4096\nRESPONSE_LENGTH = 256\nMAX_NUM_SEQS = 16\nGPU_MEMORY_UTILIZATION = 0.8", "label": 0, "sample_id": "verl-project/verl:tests/workers/rollout/rollout_trtllm/test_trtllm_rollout_utils.py", "category": "unknown", "repo_id": "verl-project/verl"} {"input": "\"\"\"\nHosoya Triangle\n\nThe Hosoya triangle (originally Fibonacci triangle) is a triangular arrangement\nof numbers where each entry is the sum of two entries above it.\n\nReference: https://en.wikipedia.org/wiki/Hosoya%27s_triangle\n\nComplexity:\n Time: O(n^3) (naive recursive per entry)\n Space: O(n) (call stack depth)\n\"\"\"\n\nfrom __future__ import annotations\n\n\ndef hosoya(height: int, width: int) -> int:\n \"\"\"Compute a single entry in the Hosoya triangle.\n\n Args:\n height: Row index (0-based).\n width: Column index (0-based).\n\n Returns:\n The value at position (height, width) in the Hosoya triangle.\n\n Examples:\n >>> hosoya(4, 2)\n 4\n \"\"\"\n if (width == 0) and (height in (0, 1)):\n return 1\n if (width == 1) and (height in (1, 2)):\n return 1\n if height > width:\n return hosoya(height - 1, width) + hosoya(height - 2, width)\n if width == height:\n", "label": 1, "sample_id": "keon/algorithms:algorithms/dynamic_programming/hosoya_triangle.py", "category": "documentation", "repo_id": "keon/algorithms"} {"input": "# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom ...loaders import HeliosLoraLoaderMixin\nfrom ...utils import logging\nfrom ..modular_pipeline import ModularPipeline\n\n\nlogger = logging.get_logger(__name__) # pylint: disable=invalid-name\n\n\nclass HeliosModularPipeline(\n ModularPipeline,\n HeliosLoraLoaderMixin,\n):\n \"\"\"\n A ModularPipeline for Helios text-to-video generation.\n\n > [!WARNING] > This is an experimental feature and is likely to change in the future.\n \"\"\"\n\n default_blocks_name = \"HeliosAutoBlocks\"\n\n @property\n def v", "label": 0, "sample_id": "huggingface/diffusers:src/diffusers/modular_pipelines/helios/modular_pipeline.py", "category": "unknown", "repo_id": "huggingface/diffusers"} {"input": "\"\"\"Experimental client-side task support.\n\nThis module provides client methods for interacting with MCP tasks.\n\nWARNING: These APIs are experimental and may change without notice.\n\nExample:\n ```python\n # Call a tool as a task\n result = await session.experimental.call_tool_as_task(\"tool_name\", {\"arg\": \"value\"})\n task_id = result.task.task_id\n\n # Get task status\n status = await session.experimental.get_task(task_id)\n\n # Get task result when complete\n if status.status == \"completed\":\n result = await session.experimental.get_task_result(task_id, CallToolResult)\n\n # List all tasks\n tasks = await session.experimental.list_tasks()\n\n # Cancel a task\n await session.experimental.cancel_task(task_id)\n ```\n\"\"\"\n\nfrom collections.abc import AsyncIterator\nfrom typing import TYPE_CHECKING, Any, TypeVar\n\nfrom mcp import types\nfrom mcp.shared.experimental.tasks.polling import poll_until_terminal\nfrom mcp.types._types import RequestParamsMeta\n\nif TYPE_CHECKING:\n from mcp.client.session import ClientSession\n\nResultT = TypeVar(\"ResultT\", bound=types.Result)\n\n\nclass ExperimentalClientFeatures:\n \"\"\"Experimental client features for tasks and other experimental APIs.\n\n WARNING: These", "label": 1, "sample_id": "modelcontextprotocol/python-sdk:src/mcp/client/experimental/tasks.py", "category": "documentation", "repo_id": "modelcontextprotocol/python-sdk"} {"input": "from typing import Any\n\nimport pydantic\n\n\nclass History(pydantic.BaseModel):\n \"\"\"Class representing the conversation history.\n\n The conversation history is a list of messages, each message entity should have keys from the associated signature.\n For example, if you have the following signature:\n\n ```\n class MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n ```\n\n Then the history should be a list of dictionaries with keys \"question\" and \"answer\".\n\n Examples:\n ```\n import dspy\n\n dspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n class MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n\n history = dspy.History(\n messages=[\n {\"question\": \"What is the capital of France?\", \"answer\": \"Paris\"},\n {\"question\": \"What is the capital of Germany?\", \"answer\": \"Berlin\"},\n ]\n )\n\n predict = dspy.Predict(MySignature", "label": 0, "sample_id": "stanfordnlp/dspy:dspy/adapters/types/history.py", "category": "unknown", "repo_id": "stanfordnlp/dspy"} {"input": "\"\"\"Ministral3 reasoning templates\"\"\"\n\nfrom mlc_llm.protocol.conversation_protocol import Conversation, MessagePlaceholders\n\nfrom .registry import ConvTemplateRegistry\n\n# Ministral-3-XB-Reasoning-2512\nConvTemplateRegistry.register_conv_template(\n Conversation(\n name=\"ministral3_reasoning\",\n system_template=(\n f\"[SYSTEM_PROMPT]{MessagePlaceholders.SYSTEM.value}[/SYSTEM_PROMPT]\"\n f\"{MessagePlaceholders.FUNCTION.value}\"\n ),\n system_message=(\n \"# HOW YOU SHOULD THINK AND ANSWER\\n\\n\"\n \"First draft your thinking process (inner monologue) until you arrive at a response. \"\n \"Format your response using Markdown, and use LaTeX for any mathematical equations. \"\n \"Write both your thoughts and the response in the same language as the input.\\n\\n\"\n \"Your thinking process must follow the template below:\"\n \"[THINK]Your thoughts or/and draft, like working through an exercise on scratch paper. \"\n \"Be as casual and as long as you want until you are confident to generate the response \"\n \"to the user.[/THINK]Here, provide a self-contained response.\"\n ),\n role_templates={\n \"user\":", "label": 1, "sample_id": "mlc-ai/mlc-llm:python/mlc_llm/conversation_template/ministral3_reasoning.py", "category": "function_simple", "repo_id": "mlc-ai/mlc-llm"} {"input": "# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nfrom __future__ import annotations\n\nfrom typing import Union\nfrom typing_extensions import Literal, Required, TypeAlias, TypedDict\n\nfrom .speech_model import SpeechModel\n\n__all__ = [\"SpeechCreateParams\", \"Voice\", \"VoiceID\"]\n\n\nclass SpeechCreateParams(TypedDict, total=False):\n input: Required[str]\n \"\"\"The text to generate audio for. The maximum length is 4096 characters.\"\"\"\n\n model: Required[Union[str, SpeechModel]]\n \"\"\"\n One of the available [TTS models](https://platform.openai.com/docs/models#tts):\n `tts-1`, `tts-1-hd`, `gpt-4o-mini-tts`, or `gpt-4o-mini-tts-2025-12-15`.\n \"\"\"\n\n voice: Required[Voice]\n \"\"\"The voice to use when generating the audio.\n\n Supported built-in voices are `alloy`, `ash`, `ballad`, `coral`, `echo`,\n `fable`, `onyx`, `nova`, `sage`, `shimmer`, `verse`, `", "label": 0, "sample_id": "openai/openai-python:src/openai/types/audio/speech_create_params.py", "category": "unknown", "repo_id": "openai/openai-python"} {"input": "import json\nfrom types import SimpleNamespace\n\nfrom typer.testing import CliRunner\n\nfrom nanobot.cli.commands import app\nfrom nanobot.config.loader import load_config, save_config\n\nrunner = CliRunner()\n\n\ndef test_load_config_keeps_max_tokens_and_warns_on_legacy_memory_window(tmp_path) -> None:\n config_path = tmp_path / \"config.json\"\n config_path.write_text(\n json.dumps(\n {\n \"agents\": {\n \"defaults\": {\n \"maxTokens\": 1234,\n \"memoryWindow\": 42,\n }\n }\n }\n ),\n encoding=\"utf-8\",\n )\n\n config = load_config(config_path)\n\n assert config.agents.defaults.max_tokens == 1234\n assert config.agents.defaults.context_window_tokens == 65_536\n assert config.agents.defaults.should_warn_deprecated_memory_window is True\n\n\ndef test_save_config_writes_context_window_tokens_but_not_memory_window(tmp_path) -> None:\n config_path = tmp_path / \"config.json\"\n config_path.write_text(\n json.dumps(\n {\n \"agents\": {\n \"defaults\": {\n \"maxTokens\": 2222,\n \"memoryWindow", "label": 0, "sample_id": "HKUDS/nanobot:tests/test_config_migration.py", "category": "unknown", "repo_id": "HKUDS/nanobot"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Discovery utilities for Component v2 manifests in installed packages.\n\nThe scanner searches installed distributions for a ``pyproject.toml`` with\n``[tool.streamlit.component]`` configuration and extracts the component\nmanifests along with their package roots.\n\nThe implementation prioritizes efficiency and safety by filtering likely\ncandidates and avoiding excessive filesystem operations.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport importlib.metadata\nimport importlib.util\nimport os\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom data", "label": 1, "sample_id": "streamlit/streamlit:lib/streamlit/components/v2/manifest_scanner.py", "category": "license", "repo_id": "streamlit/streamlit"} {"input": "# Copyright (c) Microsoft Corporation.\n# SPDX-License-Identifier: Apache-2.0\n\n# DeepSpeed Team\n\nfrom .constants import *\n\nBASE_STAT_KEYS = [\n CLOSE_COUNT_KEY, FILENO_COUNT_KEY, FLUSH_COUNT_KEY, WRITE_COUNT_KEY, WRITE_BYTES_KEY, WRITE_SEC_KEY,\n WRITE_SPEED_KEY\n]\n\n\nclass BaseFileWriter(object):\n\n def __init__(self, file_path):\n self._file_path = file_path\n self._stats = {k: 0 for k in BASE_STAT_KEYS}\n\n def close(self):\n pass\n\n def fileno(self):\n pass\n\n def flush(self):\n pass\n\n def write(self, buffer):\n pass\n\n def file_path(self):\n return self._file_path\n\n def _incr_stats(self, key, incr=1):\n self._stats[key] += incr\n\n def _dump_state(self):\n if self._stats[WRITE_SEC_KEY] > 0:\n self._stats[WRITE_SPEED_KEY] = (self._stats[WRITE_BYTES_KEY] / self._stats[WRITE_SEC_KEY] / (1024**3))\n state = self._stats\n state[FILE_PATH_KEY] = self.file_path()\n", "label": 1, "sample_id": "deepspeedai/DeepSpeed:deepspeed/io/base_file_writer.py", "category": "license", "repo_id": "deepspeedai/DeepSpeed"} {"input": "# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport itertools\n\nfrom sklearn import __version__\nfrom sklearn._config import get_config\nfrom sklearn.utils.fixes import parse_version\n\n\nclass _HTMLDocumentationLinkMixin:\n \"\"\"Mixin class allowing to generate a link to the API documentation.\n\n This mixin relies on three attributes:\n - `_doc_link_module`: it corresponds to the root module (e.g. `sklearn`). Using this\n mixin, the default value is `sklearn`.\n - `_doc_link_template`: it corresponds to the template used to generate the\n link to the API documentation. Using this mixin, the default value is\n `\"https://scikit-learn.org/{version_url}/modules/generated/\n {estimator_module}.{estimator_name}.html\"`.\n - `_doc_link_url_param_generator`: it corresponds to a function that generates the\n parameters to be used in the template when the estimator module and name are not\n sufficient.\n\n The method :meth:`_get_doc_link` generates the link to the API documentation for a\n given estimator.\n\n This mixin provides all the necessary states for\n :func:`sklearn.utils.estimator_html_repr", "label": 1, "sample_id": "scikit-learn/scikit-learn:sklearn/utils/_repr_html/base.py", "category": "license", "repo_id": "scikit-learn/scikit-learn"} {"input": "# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport time\nimport unittest\n\nimport numpy as np\nimport pytest\nfrom parameterized import parameterized\n\nfrom transformers.testing_utils import (\n require_torch,\n require_torch_accelerator,\n require_vision,\n slow,\n torch_device,\n)\nfrom transformers.utils import is_torch_available, is_torchvision_available, is_vision_available\n\nfrom ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs\n\n\nif is_torch_available():\n import torch\n\n from transformers.models.efficientloftr.modeling_efficientloftr import EfficientLoF", "label": 1, "sample_id": "huggingface/transformers:tests/models/efficientloftr/test_image_processing_efficientloftr.py", "category": "test", "repo_id": "huggingface/transformers"} {"input": "# Copyright 2026 Marimo. All rights reserved.\nfrom __future__ import annotations\n\nimport sys\n\nfrom marimo._messaging.context import is_code_mode_request\nfrom marimo._messaging.types import Stderr\n\n\ndef _highlight_traceback(traceback: str) -> str:\n \"\"\"\n Highlight the traceback with color.\n \"\"\"\n\n from pygments import highlight\n from pygments.formatters import HtmlFormatter\n from pygments.lexers import PythonTracebackLexer\n\n formatter = HtmlFormatter()\n\n body = highlight(traceback, PythonTracebackLexer(), formatter)\n return f'{body}'\n\n\ndef write_traceback(traceback: str) -> None:\n if isinstance(sys.stderr, Stderr) and not is_code_mode_request():\n # Strip marimo's internal executor.py frame and highlight for the UI\n trimmed = _trim_traceback(traceback)\n sys.stderr._write_with_mimetype(\n _highlight_traceback(trimmed),\n mimetype=\"application/vnd.marimo+traceback\",\n )\n else:\n sys.stderr.write(traceback)\n\n\ndef _trim_traceback(traceback: str) -> str:\n \"\"\"\n Skip first DefaultExecutor.execute_cell traceback item which", "label": 0, "sample_id": "marimo-team/marimo:marimo/_messaging/tracebacks.py", "category": "unknown", "repo_id": "marimo-team/marimo"} {"input": "# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nfrom __future__ import annotations\n\nimport httpx\n\nfrom ... import _legacy_response\nfrom ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given\nfrom ..._utils import maybe_transform, async_maybe_transform\nfrom ..._compat import cached_property\nfrom ..._resource import SyncAPIResource, AsyncAPIResource\nfrom ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper\nfrom ..._base_client import make_request_options\nfrom ...types.realtime import client_secret_create_params\nfrom ...types.realtime.client_secret_create_response import ClientSecretCreateResponse\n\n__all__ = [\"ClientSecrets\", \"AsyncClientSecrets\"]\n\n\nclass ClientSecrets(SyncAPIResource):\n @cached_property\n def with_raw_response(self) -> ClientSecretsWithRawResponse:\n \"\"\"\n This property can be used as a prefix for any HTTP method call to return\n the raw response object instead of the parsed content.\n\n For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers\n \"\"\"\n return ClientSecretsWithRaw", "label": 1, "sample_id": "openai/openai-python:src/openai/resources/realtime/client_secrets.py", "category": "function_complex", "repo_id": "openai/openai-python"} {"input": "# Copyright 2025-present the HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom dataclasses import dataclass, field\nfrom typing import Literal, Optional\n\nimport torch\nfrom datasets import load_dataset\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser\nfrom trl import SFTConfig, SFTTrainer\n\nfrom peft import MissConfig, get_peft_model\n\n\n@dataclass\nclass ScriptArguments(SFTConfig):\n # model configs\n base_model_name_or_path: Optional[str] = field(\n default=None, metadata={\"help\": \"The name or path of the fp32/1", "label": 1, "sample_id": "huggingface/peft:examples/miss_finetuning/miss_finetuning.py", "category": "license", "repo_id": "huggingface/peft"} {"input": "\"\"\"Test the elicitation feature using stdio transport.\"\"\"\n\nfrom typing import Any\n\nimport pytest\nfrom pydantic import BaseModel, Field\n\nfrom mcp import Client, types\nfrom mcp.client.session import ClientSession, ElicitationFnT\nfrom mcp.server.mcpserver import Context, MCPServer\nfrom mcp.shared._context import RequestContext\nfrom mcp.types import ElicitRequestParams, ElicitResult, TextContent\n\n\n# Shared schema for basic tests\nclass AnswerSchema(BaseModel):\n answer: str = Field(description=\"The user's answer to the question\")\n\n\ndef create_ask_user_tool(mcp: MCPServer):\n \"\"\"Create a standard ask_user tool that handles all elicitation responses.\"\"\"\n\n @mcp.tool(description=\"A tool that uses elicitation\")\n async def ask_user(prompt: str, ctx: Context) -> str:\n result = await ctx.elicit(message=f\"Tool wants to ask: {prompt}\", schema=AnswerSchema)\n\n if result.action == \"accept\" and result.data:\n return f\"User answered: {result.data.answer}\"\n elif result.action == \"decline\":\n return \"User declined to answer\"\n else: # pragma: no cover\n return \"User cancelled", "label": 0, "sample_id": "modelcontextprotocol/python-sdk:tests/server/mcpserver/test_elicitation.py", "category": "unknown", "repo_id": "modelcontextprotocol/python-sdk"} {"input": "\"\"\"\nUnit tests for datetime serialization in database utilities.\n\nThese tests verify the fix for GitHub issue #6327:\nTypeError: Object of type datetime is not JSON serializable when saving agent sessions.\n\"\"\"\n\nimport json\nfrom datetime import date, datetime, timezone\nfrom uuid import uuid4\n\nfrom agno.db.utils import CustomJSONEncoder, json_serializer, serialize_session_json_fields\nfrom agno.session.agent import AgentSession\n\n\nclass TestCustomJSONEncoder:\n \"\"\"Tests for CustomJSONEncoder class.\"\"\"\n\n def test_encode_datetime(self):\n \"\"\"Test that datetime objects are encoded to ISO format.\"\"\"\n dt = datetime(2025, 1, 15, 10, 30, 0, tzinfo=timezone.utc)\n result = json.dumps({\"timestamp\": dt}, cls=CustomJSONEncoder)\n assert '\"2025-01-15T10:30:00+00:00\"' in result\n\n def test_encode_datetime_naive(self):\n \"\"\"Test that naive datetime objects are encoded to ISO format.\"\"\"\n dt = datetime(2025, 1, 15, 10, 30, 0)\n result = json", "label": 1, "sample_id": "agno-agi/agno:libs/agno/tests/unit/db/test_datetime_serialization.py", "category": "test", "repo_id": "agno-agi/agno"} {"input": "# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport logging\nimport subprocess\nimport sys\nimport time\nimport warnings\nfrom threading import Thread\n\nimport requests\n\nfrom ._models import (\n ChartParsing,\n DocImgOrientationClassification,\n DocVLM,\n FormulaRecognition,\n LayoutDetection,\n SealTextDetection,\n TableCellsDetection,\n TableClassification,\n TableStructureRecognition,\n TextDetection,\n TextImageUnwarping,\n TextLineOrientationClassification,\n TextRecognition,\n)\nfrom ._pipelines import (\n DocPreprocessor,\n DocUnderstanding,\n FormulaRecognitionPipeline,\n", "label": 1, "sample_id": "PaddlePaddle/PaddleOCR:paddleocr/_cli.py", "category": "license", "repo_id": "PaddlePaddle/PaddleOCR"} {"input": "# Copyright (c) 2025, Frappe Technologies Pvt. Ltd. and contributors\n# For license information, please see license.txt\n\n# import frappe\nfrom frappe.model.document import Document\n\n\nclass FinancialReportRow(Document):\n\t# begin: auto-generated types\n\t# This code is auto-generated. Do not modify anything in this block.\n\n\tfrom typing import TYPE_CHECKING\n\n\tif TYPE_CHECKING:\n\t\tfrom frappe.types import DF\n\n\t\tadvanced_filtering: DF.Check\n\t\tbalance_type: DF.Literal[\n\t\t\t\"\", \"Opening Balance\", \"Closing Balance\", \"Period Movement (Debits - Credits)\"\n\t\t]\n\t\tbold_text: DF.Check\n\t\tcalculation_formula: DF.Code | None\n\t\tcolor: DF.Color | None\n\t\tdata_source: DF.Literal[\n\t\t\t\"\",\n\t\t\t\"Account Data\",\n\t\t\t\"Calculated Amount\",\n\t\t\t\"Custom API\",\n\t\t\t\"Blank Line\",\n\t\t\t\"Column Break\",\n\t\t\t\"Section Break\",\n\t\t]\n\t\tdisplay_name: DF.Data | None\n\t\tfieldtype: DF.Literal[\"\", \"Currency\", \"Float\", \"Int\", \"Percent\"]\n\t\thidden_calculation: DF.Check\n\t\thide_when", "label": 1, "sample_id": "frappe/erpnext:erpnext/accounts/doctype/financial_report_row/financial_report_row.py", "category": "license", "repo_id": "frappe/erpnext"} {"input": "from collections import defaultdict, namedtuple\n\nfrom django.contrib.gis import forms, gdal\nfrom django.contrib.gis.db.models.proxy import SpatialProxy\nfrom django.contrib.gis.gdal.error import GDALException\nfrom django.contrib.gis.geos import (\n GeometryCollection,\n GEOSException,\n GEOSGeometry,\n LineString,\n MultiLineString,\n MultiPoint,\n MultiPolygon,\n Point,\n Polygon,\n)\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db.models import Field\nfrom django.utils.translation import gettext_lazy as _\n\n# Local cache of the spatial_ref_sys table, which holds SRID data for each\n# spatial database alias. This cache exists so that the database isn't queried\n# for SRID info each time a distance query is constructed.\n_srid_cache = defaultdict(dict)\n\n\nSRIDCacheEntry = namedtuple(\n \"SRIDCacheEntry\", [\"units\", \"units_name\", \"spheroid\", \"geodetic\"]\n)\n\n\ndef get_srid_info(srid, connection):\n \"\"\"\n Return the units, unit name, and spheroid WKT associated with the\n given SRID from the `spatial_ref_sys` (or equivalent) spatial database\n table for the", "label": 0, "sample_id": "django/django:django/contrib/gis/db/models/fields.py", "category": "unknown", "repo_id": "django/django"} {"input": "# Copyright 2025 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nTests for prepare_micro_batches with force_group_size > 1 and use_dynamic_bsz=True.\n\nFocuses on verifying that:\n1. Samples within the same group (consecutive force_group_size samples) always\n end up in the same micro-batch.\n2. All original samples are covered exactly once across all micro-batches.\n3. The returned batch_idx_list correctly maps micro-batch positions back to\n original batch positions.\n4. Token budget (max_token_len) is respected per micro-batch.\n\"\"\"\n\nimport torch\nfrom tensordict import TensorDict\n\nfrom ver", "label": 0, "sample_id": "verl-project/verl:tests/utils/test_prepare_micro_batches_with_group_size.py", "category": "unknown", "repo_id": "verl-project/verl"} {"input": "\"\"\"Unit tests for langflow.core.celeryconfig module.\"\"\"\n\n# Import the module to test\nfrom langflow.core import celeryconfig\n\n\nclass TestCeleryConfigAcceptContent:\n \"\"\"Unit tests for accept_content configuration.\"\"\"\n\n def test_accept_content_configuration(self):\n \"\"\"Test that accept_content is set to the expected values.\"\"\"\n # This should be consistent regardless of environment\n expected_content = [\"json\", \"pickle\"]\n assert celeryconfig.accept_content == expected_content\n\n def test_accept_content_types(self):\n \"\"\"Test that accept_content contains the expected content types.\"\"\"\n assert \"json\" in celeryconfig.accept_content\n assert \"pickle\" in celeryconfig.accept_content\n assert len(celeryconfig.accept_content) == 2\n\n def test_accept_content_is_list(self):\n \"\"\"Test that accept_content is a list type.\"\"\"\n assert isinstance(celeryconfig.accept_content, list)\n\n def test_accept_content_contains_strings(self):\n \"\"\"Test that accept_content contains only string values.\"\"\"\n for content_type in celeryconfig.accept_content:\n assert isinstance(content_type, str)\n\n\nclass TestCeleryConfigVariables:\n \"\"\"Unit tests for configuration variables.\"\"\"\n\n def test_required_config_variables_exist(self):\n \"\"\"Test that all required configuration variables are defined", "label": 1, "sample_id": "langflow-ai/langflow:src/backend/tests/unit/core/test_celeryconfig.py", "category": "test", "repo_id": "langflow-ai/langflow"} {"input": "#!/usr/bin/env python3\nimport ctypes, pathlib, argparse, pickle, dataclasses, threading\nfrom typing import Generator\nfrom tinygrad.helpers import temp, unwrap, DEBUG\nfrom tinygrad.runtime.ops_amd import ProfileSQTTEvent\nfrom tinygrad.runtime.autogen import rocprof\nfrom tinygrad.renderer.amd.dsl import Inst\nfrom test.amd.disasm import disasm\n\n@dataclasses.dataclass(frozen=True)\nclass InstExec:\n typ:str\n pc:int\n stall:int\n dur:int\n time:int\n\n@dataclasses.dataclass(frozen=True)\nclass WaveSlot:\n wave_id:int\n cu:int\n simd:int\n se:int\n @property\n def cu_loc(self) -> str: return f\"SE:{self.se} CU:{self.cu}\"\n @property\n def wave_loc(self) -> str: return f\"{self.cu_loc} SIMD:{self.simd} W:{self.wave_id}\"\n\n@dataclasses.dataclass(frozen=True)\nclass WaveExec(WaveSlot):\n begin_time:int\n end_time:int\n insts:bytearray\n def unpack_insts(self) -> Generator[InstExec, None, None]:\n sz", "label": 1, "sample_id": "tinygrad/tinygrad:extra/sqtt/roc.py", "category": "function_complex", "repo_id": "tinygrad/tinygrad"} {"input": "import logging\nfrom typing import TYPE_CHECKING, Any, get_origin\n\nimport json_repair\nimport litellm\n\nfrom dspy.adapters.types import History, Type\nfrom dspy.adapters.types.base_type import split_message_content_for_custom_types\nfrom dspy.adapters.types.reasoning import Reasoning\nfrom dspy.adapters.types.tool import Tool, ToolCalls\nfrom dspy.experimental import Citations\nfrom dspy.signatures.signature import Signature\nfrom dspy.utils.callback import BaseCallback, with_callbacks\nfrom dspy.utils.exceptions import AdapterParseError\n\nlogger = logging.getLogger(__name__)\n\nif TYPE_CHECKING:\n from dspy.clients.lm import LM\n\n_DEFAULT_NATIVE_RESPONSE_TYPES = [Citations, Reasoning]\n\n\nclass Adapter:\n \"\"\"Base Adapter class.\n\n The Adapter serves as the interface layer between DSPy module/signature and Language Models (LMs). It handles the\n complete transformation pipeline from DSPy inputs to LM calls and back to structured outputs.\n\n Key responsibilities:\n - Transform user inputs and signatures into properly formatted LM prompts, which also instructs the LM to format\n the response in a specific format.\n - Parse LM outputs into dictionaries matching the signature's output fields.\n - Enable/disable native LM features (function calling,", "label": 0, "sample_id": "stanfordnlp/dspy:dspy/adapters/base.py", "category": "unknown", "repo_id": "stanfordnlp/dspy"} {"input": "# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.\n# SM120 (Blackwell GeForce / DGX Spark) backward pass.\n#\n# SM120 uses the same SM80-era MMA instructions (mma.sync.aligned.m16n8k16) but has\n# a smaller shared memory capacity (99 KB vs 163 KB on SM80). This module subclasses\n# FlashAttentionBackwardSm80 and overrides the SMEM capacity check accordingly.\n\nimport cutlass\nimport cutlass.utils as utils_basic\n\nfrom flash_attn.cute.flash_bwd import FlashAttentionBackwardSm80\n\n\nclass FlashAttentionBackwardSm120(FlashAttentionBackwardSm80):\n @staticmethod\n def can_implement(\n dtype,\n head_dim,\n head_dim_v,\n m_block_size,\n n_block_size,\n num_stages_Q,\n num_stages_dO,\n num_threads,\n is_causal,\n V_in_regs=False,\n ) -> bool:\n \"\"\"Check if the kernel can be implemented on SM120", "label": 0, "sample_id": "Dao-AILab/flash-attention:flash_attn/cute/flash_bwd_sm120.py", "category": "unknown", "repo_id": "Dao-AILab/flash-attention"} {"input": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\nimport json\n\nimport openai # use the official client for correctness check\nimport pytest\n\nMODEL_NAME = \"Qwen/Qwen3-1.7B\"\ntools = [\n {\n \"type\": \"function\",\n \"name\": \"get_current_weather\",\n \"description\": \"Get the current weather in a given location\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"city\": {\n \"type\": \"string\",\n \"description\": \"The city to find the weather for, e.g. 'Vienna'\",\n \"default\": \"Vienna\",\n },\n \"country\": {\n \"type\": \"string\",\n \"description\": \"The country that the city is in, e.g. 'Austria'\",\n },\n \"unit\": {\n \"type\": \"string\",\n \"description\": \"The unit to fetch the temperature in\",\n \"enum\": [\"celsius\", \"fahrenheit\"],\n },\n \"options\": {\n \"$ref\": \"#/$defs/WeatherOptions\",\n \"description\": \"Optional parameters for weather query\",\n ", "label": 0, "sample_id": "vllm-project/vllm:tests/entrypoints/openai/responses/test_function_call.py", "category": "unknown", "repo_id": "vllm-project/vllm"} {"input": "import io\nimport sys\nfrom io import TextIOWrapper\n\nimport anyio\nimport pytest\n\nfrom mcp.server.stdio import stdio_server\nfrom mcp.shared.message import SessionMessage\nfrom mcp.types import JSONRPCMessage, JSONRPCRequest, JSONRPCResponse, jsonrpc_message_adapter\n\n\n@pytest.mark.anyio\nasync def test_stdio_server():\n stdin = io.StringIO()\n stdout = io.StringIO()\n\n messages = [\n JSONRPCRequest(jsonrpc=\"2.0\", id=1, method=\"ping\"),\n JSONRPCResponse(jsonrpc=\"2.0\", id=2, result={}),\n ]\n\n for message in messages:\n stdin.write(message.model_dump_json(by_alias=True, exclude_none=True) + \"\\n\")\n stdin.seek(0)\n\n async with stdio_server(stdin=anyio.AsyncFile(stdin), stdout=anyio.AsyncFile(stdout)) as (\n read_stream,\n write_stream,\n ):\n received_messages: list[JSONRPCMessage] = []\n async with read_stream:\n async for message in read_stream:\n if isinstance(message, Exception): # pragma: no cover\n raise message\n received_messages.append(message.message)\n if len(received_messages) == ", "label": 0, "sample_id": "modelcontextprotocol/python-sdk:tests/server/test_stdio.py", "category": "unknown", "repo_id": "modelcontextprotocol/python-sdk"} {"input": "from __future__ import annotations\n\nfrom functools import wraps\nfrom typing import TYPE_CHECKING, Any, ParamSpec\n\nimport pytest\nfrom twisted.internet.defer import Deferred, inlineCallbacks\n\nfrom scrapy.utils.defer import deferred_from_coro, deferred_to_future\nfrom scrapy.utils.reactor import is_reactor_installed\n\nif TYPE_CHECKING:\n from collections.abc import Awaitable, Callable, Generator\n\n\n_P = ParamSpec(\"_P\")\n\n\ndef inline_callbacks_test(\n f: Callable[_P, Generator[Deferred[Any], Any, None]],\n) -> Callable[_P, Awaitable[None]]:\n \"\"\"Mark a test function written in a :func:`twisted.internet.defer.inlineCallbacks` style.\n\n This calls :func:`twisted.internet.defer.inlineCallbacks` and then:\n\n * with ``pytest-twisted`` this returns the resulting Deferred\n * with ``pytest-asyncio`` this converts the resulting Deferred into a\n coroutine\n \"\"\"\n\n if not is_reactor_installed():\n\n @pytest.mark.asyncio\n @wraps(f)\n async def wrapper_coro(*args: _P.args, **kwargs: _P.kwargs) -> None:\n await deferred_to_future(inlineCallbacks(f)(*args, **kwargs))\n\n return wrapper_coro", "label": 1, "sample_id": "scrapy/scrapy:tests/utils/decorators.py", "category": "test", "repo_id": "scrapy/scrapy"} {"input": "from typing import Any\n\nfrom pydantic import BaseModel\n\nfrom crewai_tools.tools.brave_search_tool.base import BraveSearchToolBase\nfrom crewai_tools.tools.brave_search_tool.response_types import LocalPOIs\nfrom crewai_tools.tools.brave_search_tool.schemas import (\n LocalPOIsDescriptionHeaders,\n LocalPOIsDescriptionParams,\n LocalPOIsHeaders,\n LocalPOIsParams,\n)\n\n\nDayOpeningHours = LocalPOIs.DayOpeningHours\nOpeningHours = LocalPOIs.OpeningHours\nLocationResult = LocalPOIs.LocationResult\nLocalPOIsResponse = LocalPOIs.Response\n\n\ndef _flatten_slots(slots: list[DayOpeningHours]) -> list[dict[str, str]]:\n \"\"\"Convert a list of DayOpeningHours dicts into simplified entries.\"\"\"\n return [\n {\n \"day\": slot[\"full_name\"].lower(),\n \"opens\": slot[\"opens\"],\n \"closes\": slot[\"closes\"],\n }\n for slot in slots\n ]\n\n\ndef _simplify_opening_hours(result: LocationResult) -> list[dict[str, str]] | None:\n \"\"\"Collapse opening_hours into a flat list of {day, opens, closes} dicts.\"\"\"\n hours = result.get(\"opening_hours\")\n if", "label": 0, "sample_id": "crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/brave_search_tool/brave_local_pois_tool.py", "category": "unknown", "repo_id": "crewAIInc/crewAI"} {"input": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom __future__ import annotations\n\nfrom typing import cast\n\nfrom fastapi import Depends, status\nfrom sqlalchemy import func, literal, select, union_all\nfrom sqlalchemy.sql.expression import case, false\n\nfrom airflow._shared.timezones import timezone\nfrom airflow.api_fastapi.auth.managers.models.resource_details import DagAccessEntity\nfrom airflow.api_fastapi.common.db.common import SessionDep\nfrom airflow.api_fast", "label": 0, "sample_id": "apache/airflow:airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dashboard.py", "category": "unknown", "repo_id": "apache/airflow"} {"input": "import os\nimport shlex\nimport subprocess\nimport sys\nimport json\nimport sysconfig\n\nimport pytest\n\ncomponent_template = \"\"\"\nfrom dash_generator_test_component_typescript import TypeScriptComponent\n\nt = TypeScriptComponent({0})\n\"\"\"\n\nbasic_app_template = \"\"\"\nfrom dash import Dash, html, dcc, callback, Input, Output\n\napp = Dash()\n\n{0}\napp.layout = {1}\n\n@callback(Output(\"out\", \"children\"), Input(\"btn\", \"n_clicks\"))\ndef on_click() -> html.Div:\n return {2}\n\"\"\"\n\nvalid_layout = \"\"\"html.Div([\n html.H2('Valid'),\n 'String in middle',\n 123,\n 404.4,\n dcc.Input(value='', id='in')\n])\n\"\"\"\nvalid_layout_list = \"\"\"[\n html.H2('Valid'),\n 'String in middle',\n 123,\n 404.4,\n dcc.Input(value='', id='in')\n]\n\"\"\"\nvalid_layout_function = \"\"\"\ndef layout() -> html.Div:\n return html.Div([\"hello layout\"])\n\n\"\"\"\n\ninvalid_layout = \"\"\"html.Div([\n {\"invalid\": \"dictionary in children\"}\n])\n\"\"\"\n# There is not invalid layout for function & list as explicitly typed as Any to avoid", "label": 1, "sample_id": "plotly/dash:tests/compliance/test_typing.py", "category": "test", "repo_id": "plotly/dash"} {"input": "import numpy as np\n\nfrom metadrive.component.sensors.rgb_camera import RGBCamera\nfrom panda3d.core import Texture, GraphicsOutput\n\n\nclass CopyRamRGBCamera(RGBCamera):\n \"\"\"Camera which copies its content into RAM during the render process, for faster image grabbing.\"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.cpu_texture = Texture()\n self.buffer.addRenderTexture(self.cpu_texture, GraphicsOutput.RTMCopyRam)\n\n def get_rgb_array_cpu(self):\n origin_img = self.cpu_texture\n img = np.frombuffer(origin_img.getRamImageAs(\"RGB\").getData(), dtype=np.uint8)\n img = img.reshape((origin_img.getYSize(), origin_img.getXSize(), 3))\n img = img[::-1] # Flip on vertical axis\n return img\n\n\nclass RGBCameraWide(CopyRamRGBCamera):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n lens = self.get_lens()\n lens.setFov(120)\n lens.setNear(0.1)\n\n\nclass RGBCameraRoad(CopyRamRGBCamera):\n", "label": 0, "sample_id": "commaai/openpilot:tools/sim/bridge/metadrive/metadrive_common.py", "category": "unknown", "repo_id": "commaai/openpilot"} {"input": "\"\"\"\nExample: Interrupt System Implementation\n\nThis example demonstrates how to implement a robust interrupt system\nthat allows users to interrupt the bot mid-sentence.\n\"\"\"\n\nimport asyncio\nimport threading\nfrom typing import Any\nfrom dataclasses import dataclass\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\n# ============================================================================\n# InterruptibleEvent Pattern\n# ============================================================================\n\nclass InterruptibleEvent:\n \"\"\"\n Wrapper for events that can be interrupted\n \n Every event in the pipeline is wrapped in an InterruptibleEvent,\n allowing the system to stop processing mid-stream.\n \"\"\"\n \n def __init__(self, payload: Any, is_interruptible: bool = True):\n self.payload = payload\n self.is_interruptible = is_interruptible\n self.interruption_event = threading.Event() # Initially not set\n self.interrupted = False\n \n def interrupt(self) -> bool:\n \"\"\"\n Interrupt this event\n \n Returns:\n True if the event was interrupted, False if it was not interruptible\n \"\"\"\n if not self.is_interruptible:\n return False\n \n if not self.interrupted:\n self.interruption_event.set() # Signal to stop!\n self.interrupted = True\n logger.info(\"⚠️ [", "label": 1, "sample_id": "sickn33/antigravity-awesome-skills:skills/voice-ai-engine-development/examples/interrupt_system_example.py", "category": "function_complex", "repo_id": "sickn33/antigravity-awesome-skills"} {"input": "\"\"\"Base class for Aladdin Connect entities.\"\"\"\n\nfrom genie_partner_sdk.client import AladdinConnectClient\nfrom genie_partner_sdk.model import GarageDoor\n\nfrom homeassistant.helpers.device_registry import DeviceInfo\nfrom homeassistant.helpers.update_coordinator import CoordinatorEntity\n\nfrom .const import DOMAIN\nfrom .coordinator import AladdinConnectCoordinator\n\n\nclass AladdinConnectEntity(CoordinatorEntity[AladdinConnectCoordinator]):\n \"\"\"Defines a base Aladdin Connect entity.\"\"\"\n\n _attr_has_entity_name = True\n\n def __init__(self, coordinator: AladdinConnectCoordinator, door_id: str) -> None:\n \"\"\"Initialize Aladdin Connect entity.\"\"\"\n super().__init__(coordinator)\n self._door_id = door_id\n door = self.door\n self._attr_device_info = DeviceInfo(\n identifiers={(DOMAIN, door.unique_id)},\n manufacturer=\"Aladdin Connect\",\n name=door.name,\n )\n self._device_id = door.device_id\n self._number = door.door_number\n\n @property\n def available(self) -> bool:\n \"\"\"Return True if entity is available.\"\"\"\n return super().available and self._door_id in self.coordinator.data\n\n @property\n def door(self) -> Garage", "label": 0, "sample_id": "home-assistant/core:homeassistant/components/aladdin_connect/entity.py", "category": "unknown", "repo_id": "home-assistant/core"} {"input": "\"\"\"AIO Sandbox Provider — orchestrates sandbox lifecycle with pluggable backends.\n\nThis provider composes two abstractions:\n- SandboxBackend: how sandboxes are provisioned (local container vs remote/K8s)\n- SandboxStateStore: how thread→sandbox mappings are persisted (file vs Redis)\n\nThe provider itself handles:\n- In-process caching for fast repeated access\n- Thread-safe locking (in-process + cross-process via state store)\n- Idle timeout management\n- Graceful shutdown with signal handling\n- Mount computation (thread-specific, skills)\n\"\"\"\n\nimport atexit\nimport hashlib\nimport logging\nimport os\nimport signal\nimport threading\nimport time\nimport uuid\n\nfrom src.config import get_app_config\nfrom src.config.paths import VIRTUAL_PATH_PREFIX, get_paths\nfrom src.sandbox.sandbox import Sandbox\nfrom src.sandbox.sandbox_provider import SandboxProvider\n\nfrom .aio_sandbox import AioSandbox\nfrom .backend import SandboxBackend, wait_for_sandbox_ready\nfrom .file_state_store import FileSandboxStateStore\nfrom .local_backend import LocalContainerBackend\nfrom .remote_backend import RemoteSandboxBackend\nfrom .sandbox_info import SandboxInfo\nfrom .state_store import SandboxStateStore\n\nlogger = logging.getLogger(__", "label": 1, "sample_id": "bytedance/deer-flow:backend/src/community/aio_sandbox/aio_sandbox_provider.py", "category": "function_complex", "repo_id": "bytedance/deer-flow"} {"input": "\"\"\"\nFunctions to parse datetime objects.\n\nWe're using regular expressions rather than time.strptime because:\n- They provide both validation and parsing.\n- They're more flexible for datetimes.\n- The date/datetime/time constructors produce friendlier error messages.\n\nStolen from https://raw.githubusercontent.com/django/django/main/django/utils/dateparse.py at\n9718fa2e8abe430c3526a9278dd976443d4ae3c6\n\nChanged to:\n* use standard python datetime types not django.utils.timezone\n* raise ValueError when regex doesn't match rather than returning None\n* support parsing unix timestamps for dates and datetimes\n\"\"\"\nimport re\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom typing import Dict, Optional, Type, Union\n\nfrom pydantic.v1 import errors\n\ndate_expr = r'(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})'\ntime_expr = (\n r'(?P\\d{1,2}):(?P\\d{1,2})'\n r'(?::(?P", "label": 0, "sample_id": "pydantic/pydantic:pydantic/v1/datetime_parse.py", "category": "unknown", "repo_id": "pydantic/pydantic"} {"input": "#!/usr/bin/env python3\n\"\"\"\nSync Microsoft Skills Repository - v4 (Flat Structure)\nReads each SKILL.md frontmatter 'name' field and uses it as a flat directory\nname under skills/ to comply with the repository's indexing conventions.\n\"\"\"\n\nimport re\nimport shutil\nimport subprocess\nimport tempfile\nimport json\nfrom pathlib import Path\n\nMS_REPO = \"https://github.com/microsoft/skills.git\"\nREPO_ROOT = Path(__file__).parent.parent\nTARGET_DIR = REPO_ROOT / \"skills\"\nDOCS_DIR = REPO_ROOT / \"docs\"\nATTRIBUTION_FILE = DOCS_DIR / \"microsoft-skills-attribution.json\"\n\n\ndef clone_repo(temp_dir: Path):\n \"\"\"Clone Microsoft skills repository (shallow).\"\"\"\n print(\"🔄 Cloning Microsoft Skills repository...\")\n subprocess.run(\n [\"git\", \"clone\", \"--depth\", \"1\", MS_REPO, str(temp_dir)],\n check=True,\n )\n\n\ndef cleanup_previous_sync():\n \"\"\"Remove skill directories from a previous sync using the attribution manifest.\"\"\"\n if not ATTRIBUTION_FILE.exists():\n print(\" ℹ️ No previous attribution file found — skipping cleanup.\")\n return 0\n\n try:\n with open(ATTRIBUTION", "label": 0, "sample_id": "sickn33/antigravity-awesome-skills:tools/scripts/sync_microsoft_skills.py", "category": "unknown", "repo_id": "sickn33/antigravity-awesome-skills"} {"input": "\"\"\"Base retriever.\"\"\"\n\nfrom abc import abstractmethod\nfrom typing import Any, Dict, List, Optional\n\nfrom llama_index.core.base.base_query_engine import BaseQueryEngine\nfrom llama_index.core.callbacks.base import CallbackManager\nfrom llama_index.core.callbacks.schema import CBEventType, EventPayload\nfrom llama_index.core.prompts.mixin import (\n PromptDictType,\n PromptMixin,\n PromptMixinType,\n)\nfrom llama_index.core.schema import (\n BaseNode,\n IndexNode,\n NodeWithScore,\n QueryBundle,\n QueryType,\n TextNode,\n)\nfrom llama_index.core.settings import Settings\nfrom llama_index.core.utils import print_text\nfrom llama_index.core.instrumentation import DispatcherSpanMixin\nfrom llama_index.core.instrumentation.events.retrieval import (\n RetrievalEndEvent,\n RetrievalStartEvent,\n)\nimport llama_index.core.instrumentation as instrument\n\ndispatcher = instrument.get_dispatcher(__name__)\n\n\nclass BaseRetriever(PromptMixin, DispatcherSpanMixin):\n \"\"\"Base retriever.\"\"\"\n\n def __init__(\n self,\n callback_manager: Optional[CallbackManager] = None,\n object_map: Optional[Dict] = None,\n objects: Optional[List[IndexNode]] = None,\n verbose: bool = False,\n ) ->", "label": 0, "sample_id": "run-llama/llama_index:llama-index-core/llama_index/core/base/base_retriever.py", "category": "unknown", "repo_id": "run-llama/llama_index"} {"input": "from unittest.mock import MagicMock, patch\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.test import TestCase\n\nfrom core.choices import ObjectChangeActionChoices\nfrom core.models import DataSource, Job, ObjectType\nfrom dcim.models import Device, Location, Site\nfrom netbox.constants import CENSOR_TOKEN, CENSOR_TOKEN_CHANGED\n\n\nclass DataSourceIgnoreRulesTestCase(TestCase):\n\n def test_no_ignore_rules(self):\n ds = DataSource(ignore_rules='')\n self.assertFalse(ds._ignore('README.md'))\n self.assertFalse(ds._ignore('subdir/file.py'))\n\n def test_ignore_by_filename(self):\n ds = DataSource(ignore_rules='*.txt')\n self.assertTrue(ds._ignore('notes.txt'))\n self.assertTrue(ds._ignore('subdir/notes.txt'))\n self.assertFalse(ds._ignore('notes.py'))\n\n def test_ignore_by_subdirectory(self):\n ds = DataSource(ignore_rules='dev/*')\n self.assertTrue(ds._ignore('dev/README.md'))\n self.assertTrue(ds._ignore('dev/script.py'))\n self.assertFalse(ds._ignore('prod/script.py'))\n\n\nclass DataSourceChangeLoggingTestCase(TestCase):\n\n def test_password_added_on_create(self):\n datasource = DataSource.objects.create(\n name='Data Source 1',\n ", "label": 0, "sample_id": "netbox-community/netbox:netbox/core/tests/test_models.py", "category": "unknown", "repo_id": "netbox-community/netbox"} {"input": "# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport abc\nimport builtins\nimport json\nimport os\nimport tempfile\nfrom dataclasses import dataclass, field\nfrom logging import getLogger\nfrom pathlib import Path\nfrom typing import Any, TypeVar\n\nimport draccus\nfrom huggingface_hub import hf_hub_download\nfrom huggingface_hub.constants import CONFIG_NAME\nfrom huggingface_hub.errors import HfHubHTTPError\n\nfrom lerobot.configs.types import FeatureType, PolicyFeature\nfrom lerobot.optim.optimizers import OptimizerConfig\nfrom lerobot.optim.schedulers import LRSchedulerConfig\nfrom", "label": 0, "sample_id": "huggingface/lerobot:src/lerobot/configs/policies.py", "category": "unknown", "repo_id": "huggingface/lerobot"} {"input": "from typing import TYPE_CHECKING, Optional\n\nif TYPE_CHECKING:\n from typing import Any\n\nfrom docling_core.types.doc.document import (\n DocItemLabel,\n DoclingDocument,\n Formatting,\n GroupLabel,\n NodeItem,\n)\nfrom pylatexenc.latexwalker import LatexEnvironmentNode, LatexMacroNode\n\nfrom docling.backend.latex.constants import ENV_LIST, ENV_MATH, ENV_QUOTE, ENV_THEOREM\n\n\nclass EnvironmentHandlerMixin:\n if TYPE_CHECKING:\n\n def _process_nodes(\n self,\n nodes: \"Any\",\n doc: \"Any\",\n parent: \"Any\" = ...,\n formatting: \"Any\" = ...,\n text_label: \"Any\" = ...,\n ) -> None: ...\n def _clean_math(self, latex_str: str, env_name: str) -> str: ...\n def _parse_table(self, node: \"Any\") -> \"Any\": ...\n def _extract_verbatim_content(self, latex_str: str, env_name: str) -> str: ...\n def _extract_macro_arg(self, node: \"Any\") -> str: ...\n\n def _find_document_env(self, nodes, depth: int = 0):\n if", "label": 0, "sample_id": "docling-project/docling:docling/backend/latex/handlers/environments.py", "category": "unknown", "repo_id": "docling-project/docling"} {"input": "\"\"\"\nAdd system_metadata and job_id columns to asset_references.\nChange preview_id FK from assets.id to asset_references.id.\n\nRevision ID: 0003_add_metadata_job_id\nRevises: 0002_merge_to_asset_references\nCreate Date: 2026-03-09\n\"\"\"\n\nfrom alembic import op\nimport sqlalchemy as sa\n\nfrom app.database.models import NAMING_CONVENTION\n\nrevision = \"0003_add_metadata_job_id\"\ndown_revision = \"0002_merge_to_asset_references\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n with op.batch_alter_table(\"asset_references\") as batch_op:\n batch_op.add_column(\n sa.Column(\"system_metadata\", sa.JSON(), nullable=True)\n )\n batch_op.add_column(\n sa.Column(\"job_id\", sa.String(length=36), nullable=True)\n )\n\n # Change preview_id FK from assets.id to asset_references.id (self-ref).\n # Existing values are asset-content IDs that won't match reference IDs,\n # so null them out first.\n op.execute(\"UPDATE asset_references SET preview_id = NULL WHERE preview_id IS NOT NULL\")\n with op.batch", "label": 0, "sample_id": "Comfy-Org/ComfyUI:alembic_db/versions/0003_add_metadata_job_id.py", "category": "unknown", "repo_id": "Comfy-Org/ComfyUI"} {"input": "import logging\nfrom typing import Any\n\nimport litellm\n\nfrom strix.config.config import Config, resolve_llm_config\n\n\nlogger = logging.getLogger(__name__)\n\n\nMAX_TOTAL_TOKENS = 100_000\nMIN_RECENT_MESSAGES = 15\n\nSUMMARY_PROMPT_TEMPLATE = \"\"\"You are an agent performing context\ncondensation for a security agent. Your job is to compress scan data while preserving\nALL operationally critical information for continuing the security assessment.\n\nCRITICAL ELEMENTS TO PRESERVE:\n- Discovered vulnerabilities and potential attack vectors\n- Scan results and tool outputs (compressed but maintaining key findings)\n- Access credentials, tokens, or authentication details found\n- System architecture insights and potential weak points\n- Progress made in the assessment\n- Failed attempts and dead ends (to avoid duplication)\n- Any decisions made about the testing approach\n\nCOMPRESSION GUIDELINES:\n- Preserve exact technical details (URLs, paths, parameters, payloads)\n- Summarize verbose tool outputs while keeping critical findings\n- Maintain version numbers, specific technologies identified\n- Keep exact error messages that might indicate vulnerabilities\n- Compress repetitive or similar findings into consolidated form\n\nRemember: Another security agent will use this summary to continue the assessment.\nThey must be able", "label": 1, "sample_id": "usestrix/strix:strix/llm/memory_compressor.py", "category": "function_complex", "repo_id": "usestrix/strix"} {"input": "\"\"\"Global configuration state and functions for management\"\"\"\n\n# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\nimport threading\nfrom contextlib import contextmanager as contextmanager\n\n_global_config = {\n \"assume_finite\": bool(os.environ.get(\"SKLEARN_ASSUME_FINITE\", False)),\n \"working_memory\": int(os.environ.get(\"SKLEARN_WORKING_MEMORY\", 1024)),\n \"print_changed_only\": True,\n \"display\": \"diagram\",\n \"pairwise_dist_chunk_size\": int(\n os.environ.get(\"SKLEARN_PAIRWISE_DIST_CHUNK_SIZE\", 256)\n ),\n \"enable_cython_pairwise_dist\": True,\n \"array_api_dispatch\": False,\n \"transform_output\": \"default\",\n \"enable_metadata_routing\": False,\n \"skip_parameter_validation\": False,\n \"sparse_interface\": \"spmatrix\",\n}\n_threadlocal = threading.local()\n\n\ndef _get_threadlocal_config():\n \"\"\"Get a threadlocal **mutable** configuration. If the configuration\n does not exist, copy the default global configuration.\"\"\"\n if not hasattr(_threadlocal, \"global_config\"):\n _threadlocal.global_config = _global_config.copy()\n ", "label": 0, "sample_id": "scikit-learn/scikit-learn:sklearn/_config.py", "category": "unknown", "repo_id": "scikit-learn/scikit-learn"} {"input": "\"\"\"Autoscaler monitoring loop daemon.\n\nSee autoscaler._private/monitor.py for the legacy implementation. All the legacy flags\nare supported here, but the new implementation uses the new autoscaler v2.\n\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport sys\nimport time\nfrom typing import Optional\n\nimport ray\nimport ray._private.ray_constants as ray_constants\nfrom ray._common.network_utils import build_address, parse_address\nfrom ray._common.ray_constants import (\n LOGGING_ROTATE_BACKUP_COUNT,\n LOGGING_ROTATE_BYTES,\n)\nfrom ray._common.usage.usage_lib import record_extra_usage_tag\nfrom ray._private import logging_utils\nfrom ray._private.event.event_logger import get_event_logger\nfrom ray._private.ray_logging import setup_component_logger\nfrom ray._private.worker import SCRIPT_MODE\nfrom ray._raylet import GcsClient\nfrom ray.autoscaler._private.constants import (\n AUTOSCALER_METRIC_PORT,\n AUTOSCALER_UPDATE_INTERVAL_S,\n)\nfrom ray.autoscaler._private.prom_metrics import AutoscalerPrometheusMetrics\nfrom ray.autoscaler.v2.autoscaler import Autoscaler\nfrom ray.autoscaler.v2.event_logger import AutoscalerEventLogger\nfrom ray", "label": 0, "sample_id": "ray-project/ray:python/ray/autoscaler/v2/monitor.py", "category": "unknown", "repo_id": "ray-project/ray"} {"input": "# Copyright (c) ONNX Project Contributors\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\nfrom typing import Any\n\nimport numpy as np\n\nimport onnx\nfrom onnx.backend.test.case.base import Base\nfrom onnx.backend.test.case.node import expect\n\n\nclass RNNHelper:\n def __init__(self, **params: Any) -> None:\n # RNN Input Names\n X = \"X\"\n W = \"W\"\n R = \"R\"\n B = \"B\"\n H_0 = \"initial_h\"\n LAYOUT = \"layout\"\n\n required_inputs = [X, W, R]\n for i in required_inputs:\n assert i in params, f\"Missing Required Input: {i}\"\n\n self.num_directions = params[str(W)].shape[0]\n\n if self.num_directions == 1:\n for k, v in params.items():\n if k != X:\n params[k] = np.squeeze(v, axis=0)\n\n hidden_size = params[R].shape[-1]\n batch_size = params[X].shape[1]\n\n layout = params.get(LAYOUT, 0)\n x = params[X]\n x", "label": 0, "sample_id": "onnx/onnx:onnx/backend/test/case/node/rnn.py", "category": "unknown", "repo_id": "onnx/onnx"} {"input": "\"\"\"\nInverse kinematics for rigid body entities.\n\nThis module contains the inverse kinematics kernel for computing joint configurations\nthat achieve desired end-effector poses.\n\"\"\"\n\nimport quadrants as qd\n\nimport genesis as gs\nimport genesis.utils.geom as gu\nimport genesis.utils.linalg as lu\nimport genesis.utils.array_class as array_class\n\n\n# FIXME: RigidEntity is not compatible with fast cache\n@qd.kernel(fastcache=False)\ndef kernel_rigid_entity_inverse_kinematics(\n rigid_entity: qd.template(),\n links_idx: qd.types.ndarray(),\n poss: qd.types.ndarray(),\n quats: qd.types.ndarray(),\n local_points: qd.types.ndarray(),\n n_links: qd.i32,\n dofs_idx: qd.types.ndarray(),\n n_dofs: qd.i32,\n links_idx_by_dofs: qd.types.ndarray(),\n n_links_by_dofs: qd.i32,\n custom_init_qpos: qd.i32,\n init_qpos: qd.types.ndarray(),\n max_samples: qd.i32,\n max_solver_iters: qd.i32,\n damping: qd.f32,\n pos_tol: qd.f3", "label": 1, "sample_id": "Genesis-Embodied-AI/Genesis:genesis/engine/solvers/rigid/abd/inverse_kinematics.py", "category": "function_complex", "repo_id": "Genesis-Embodied-AI/Genesis"} {"input": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2026\n# Leandro Toledo de Souza \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program. If not, see [http://www.gnu.org/licenses/].\n\nimport datetime as dtm\n\nimport pytest\n\nfrom telegram import Dice\nfrom telegram._chat import Chat\nfrom telegram._message import Message\nfrom telegram._payment.stars.staramount import StarAmount\nfrom telegram._suggestedpost import (\n SuggestedPostApprovalFailed,\n SuggestedPost", "label": 1, "sample_id": "python-telegram-bot/python-telegram-bot:tests/test_suggestedpost.py", "category": "test", "repo_id": "python-telegram-bot/python-telegram-bot"} {"input": "\"\"\"\nFollowups — Streaming\n=====================\n\nStream the main response token-by-token and capture followup suggestions\nvia events at the end.\n\nKey concepts:\n- stream=True, stream_events=True: enables streaming with events\n- RunEvent.run_content: tokens of the main response\n- RunEvent.followups_completed: carries the finished followup suggestions\n\"\"\"\n\nimport asyncio\n\nfrom agno.agent import Agent, RunEvent\nfrom agno.db.sqlite import SqliteDb\nfrom agno.models.openai import OpenAIResponses\n\ndb = SqliteDb(db_file=\"tmp/agents.db\")\n\n# ---------------------------------------------------------------------------\n# Create the Agent\n# ---------------------------------------------------------------------------\nagent = Agent(\n model=OpenAIResponses(id=\"gpt-4o\"),\n instructions=\"You are a knowledgeable assistant. Answer questions thoroughly.\",\n session_id=\"test-session\",\n followups=True,\n num_followups=3,\n markdown=True,\n db=db,\n add_history_to_context=True,\n)\n\n\n# ---------------------------------------------------------------------------\n# Stream the response and capture followups from events\n# ---------------------------------------------------------------------------\nasync def main():\n content_started = False\n async for event in agent.arun(\n \"Which national park is the best?\",\n stream=True,\n stream_events=True,\n ):\n # Stream response tokens\n if event", "label": 0, "sample_id": "agno-agi/agno:cookbook/02_agents/02_input_output/followup_suggestions_streaming.py", "category": "unknown", "repo_id": "agno-agi/agno"} {"input": "\"\"\"\nOn-Page SEO Audit & Optimization Team built with Google ADK.\n\nThe workflow runs three specialized agents in sequence:\n1. Page Auditor → scrapes the target URL with Firecrawl and extracts the structural audit + keyword focus.\n2. SERP Analyst → performs competitive analysis with Google Search using the discovered primary keyword.\n3. Optimization Advisor → synthesizes the audit and SERP insights into a prioritized optimization report.\n\"\"\"\n\nfrom __future__ import annotations\nimport os\nfrom typing import List, Optional\nfrom pydantic import BaseModel, Field\nfrom google.adk.agents import LlmAgent, SequentialAgent\nfrom google.adk.tools import google_search\nfrom google.adk.tools.agent_tool import AgentTool\nfrom google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters\n\n\n# =============================================================================\n# Output Schemas\n# =============================================================================\n\n\nclass HeadingItem(BaseModel):\n tag: str = Field(..., description=\"Heading tag such as h1, h2, h3.\")\n text: str = Field(..., description=\"Text content of the heading.\")\n\n\nclass LinkCounts(BaseModel):\n internal: Optional[int] = Field(None, description=\"Number of internal links on the page.\")\n external: Optional[int]", "label": 1, "sample_id": "Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/agent_teams/ai_seo_audit_team/agent.py", "category": "documentation", "repo_id": "Shubhamsaboo/awesome-llm-apps"} {"input": "import logging\n\nfrom langchain.agents import create_agent\nfrom langchain.agents.middleware import SummarizationMiddleware\nfrom langchain_core.runnables import RunnableConfig\n\nfrom deerflow.agents.lead_agent.prompt import apply_prompt_template\nfrom deerflow.agents.middlewares.clarification_middleware import ClarificationMiddleware\nfrom deerflow.agents.middlewares.loop_detection_middleware import LoopDetectionMiddleware\nfrom deerflow.agents.middlewares.memory_middleware import MemoryMiddleware\nfrom deerflow.agents.middlewares.subagent_limit_middleware import SubagentLimitMiddleware\nfrom deerflow.agents.middlewares.title_middleware import TitleMiddleware\nfrom deerflow.agents.middlewares.todo_middleware import TodoMiddleware\nfrom deerflow.agents.middlewares.tool_error_handling_middleware import build_lead_runtime_middlewares\nfrom deerflow.agents.middlewares.view_image_middleware import ViewImageMiddleware\nfrom deerflow.agents.thread_state import ThreadState\nfrom deerflow.config.agents_config import load_agent_config\nfrom deerflow.config.app_config import get_app_config\nfrom deerflow.config.summarization_config import get_summarization_config\nfrom deerflow.models import create_chat_model\n\nlogger = logging.getLogger(__name__)\n\n\ndef _resolve_model_name(requested_model_name: str | None =", "label": 0, "sample_id": "bytedance/deer-flow:backend/packages/harness/deerflow/agents/lead_agent/agent.py", "category": "unknown", "repo_id": "bytedance/deer-flow"} {"input": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, AsyncIterator, Iterator, List, Optional, Tuple\n\nfrom agno.models.base import Model\nfrom agno.models.message import Message\nfrom agno.utils.log import logger\n\nif TYPE_CHECKING:\n from agno.metrics import RunMetrics\n\n\ndef is_anthropic_reasoning_model(reasoning_model: Model) -> bool:\n \"\"\"Check if the model is an Anthropic Claude model with thinking support.\"\"\"\n is_claude = reasoning_model.__class__.__name__ == \"Claude\"\n if not is_claude:\n return False\n\n # Check if provider is Anthropic (not VertexAI)\n is_anthropic_provider = hasattr(reasoning_model, \"provider\") and reasoning_model.provider == \"Anthropic\"\n\n # Check if thinking parameter is set\n has_thinking = hasattr(reasoning_model, \"thinking\") and reasoning_model.thinking is not None\n\n return is_claude and is_anthropic_provider and has_thinking\n\n\ndef get_anthropic_reasoning(\n reasoning_agent: \"Agent\", # type: ignore[name-defined] # noqa: F821\n messages: List[Message],\n run_metrics: Optional[\"", "label": 1, "sample_id": "agno-agi/agno:libs/agno/agno/reasoning/anthropic.py", "category": "function_complex", "repo_id": "agno-agi/agno"} {"input": "# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nfrom __future__ import annotations\n\nfrom typing import Union, Iterable, Optional\nfrom typing_extensions import Literal, Required, TypeAlias, TypedDict\n\nfrom .custom_tool_param import CustomToolParam\n\n__all__ = [\"NamespaceToolParam\", \"Tool\", \"ToolFunction\"]\n\n\nclass ToolFunction(TypedDict, total=False):\n name: Required[str]\n\n type: Required[Literal[\"function\"]]\n\n defer_loading: bool\n \"\"\"Whether this function should be deferred and discovered via tool search.\"\"\"\n\n description: Optional[str]\n\n parameters: Optional[object]\n\n strict: Optional[bool]\n\n\nTool: TypeAlias = Union[ToolFunction, CustomToolParam]\n\n\nclass NamespaceToolParam(TypedDict, total=False):\n \"\"\"Groups function/custom tools under a shared namespace.\"\"\"\n\n description: Required[str]\n \"\"\"A description of the namespace shown to the model.\"\"\"\n\n name: Required[str]\n \"\"\"The namespace name used in tool calls (for example, `crm`).\"\"\"\n\n tools: Required[Iterable[Tool]]\n \"\"\"The function/custom tools available inside this namespace.\"\"\"\n\n type: Required[Literal[\"namespace\"]]\n \"\"\"The type of the tool. Always", "label": 0, "sample_id": "openai/openai-python:src/openai/types/responses/namespace_tool_param.py", "category": "unknown", "repo_id": "openai/openai-python"} {"input": "from datetime import timedelta\nfrom typing import TYPE_CHECKING, Any\n\nimport orjson\nfrom django.conf import settings\nfrom django.test import override_settings\nfrom django.utils.timezone import now as timezone_now\nfrom typing_extensions import override\n\nfrom analytics.models import StreamCount\nfrom zerver.actions.streams import (\n do_change_stream_group_based_setting,\n do_change_stream_permission,\n do_deactivate_stream,\n)\nfrom zerver.lib.email_mirror_helpers import encode_email_address, get_channel_email_token\nfrom zerver.lib.subscription_info import gather_subscriptions, gather_subscriptions_helper\nfrom zerver.lib.test_classes import ZulipTestCase\nfrom zerver.lib.test_helpers import most_recent_message\nfrom zerver.lib.types import (\n APIStreamDict,\n APISubscriptionDict,\n NeverSubscribedStreamDict,\n SubscriptionInfo,\n UserGroupMembersData,\n UserGroupMembersDict,\n)\nfrom zerver.models import NamedUserGroup, Realm, Stream, Subscription, UserProfile\nfrom zerver.models.groups import SystemGroups\nfrom zerver.models.realms import get_realm\nfrom zerver.models.streams import get_stream\nfrom zerver.models.users import get_system_bot\n\nif TYPE_CHECKING:\n from django.test.client import _MonkeyPatchedWSGI", "label": 1, "sample_id": "zulip/zulip:zerver/tests/test_channel_fetch.py", "category": "test", "repo_id": "zulip/zulip"} {"input": "\"\"\"Agent skill configuration models.\"\"\"\n\nfrom dataclasses import dataclass, field, replace\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Mapping\n\nimport yaml\n\nfrom entity.configs.base import (\n BaseConfig,\n ConfigError,\n ConfigFieldSpec,\n EnumOption,\n optional_bool,\n extend_path,\n require_mapping,\n)\n\n\nREPO_ROOT = Path(__file__).resolve().parents[3]\nDEFAULT_SKILLS_ROOT = (REPO_ROOT / \".agents\" / \"skills\").resolve()\ndef _discover_default_skills() -> List[tuple[str, str]]:\n if not DEFAULT_SKILLS_ROOT.exists() or not DEFAULT_SKILLS_ROOT.is_dir():\n return []\n\n discovered: List[tuple[str, str]] = []\n for candidate in sorted(DEFAULT_SKILLS_ROOT.iterdir()):\n if not candidate.is_dir():\n continue\n skill_file = candidate / \"SKILL.md\"\n if not skill_file.is_file():\n continue\n try:\n frontmatter = _parse_frontmatter(skill_file)\n except Exception:\n continue\n raw_name = frontmatter.get(\"name\")\n raw_description = frontmatter.get(\"description\")\n if not isinstance(raw_name, str) or not raw_name.strip():\n continue\n", "label": 0, "sample_id": "OpenBMB/ChatDev:entity/configs/node/skills.py", "category": "unknown", "repo_id": "OpenBMB/ChatDev"} {"input": "\"\"\"Reddit thread enrichment with real engagement metrics.\"\"\"\n\nimport re\nfrom typing import Any, Dict, List, Optional\nfrom urllib.parse import urlparse\n\nfrom . import http, dates\n\n\ndef extract_reddit_path(url: str) -> Optional[str]:\n \"\"\"Extract the path from a Reddit URL.\n\n Args:\n url: Reddit URL\n\n Returns:\n Path component or None\n \"\"\"\n try:\n parsed = urlparse(url)\n if \"reddit.com\" not in parsed.netloc:\n return None\n return parsed.path\n except:\n return None\n\n\ndef fetch_thread_data(url: str, mock_data: Optional[Dict] = None) -> Optional[Dict[str, Any]]:\n \"\"\"Fetch Reddit thread JSON data.\n\n Args:\n url: Reddit thread URL\n mock_data: Mock data for testing\n\n Returns:\n Thread data dict or None on failure\n \"\"\"\n if mock_data is not None:\n return mock_data\n\n path = extract_reddit_path(url)\n if not path:\n return None\n\n try:\n data = http.get_reddit_json(path)\n return data\n except http.HTTPError:\n return None\n\n\ndef parse_thread_data(data: Any) -> Dict[str, Any]:\n ", "label": 1, "sample_id": "sickn33/antigravity-awesome-skills:skills/last30days/scripts/lib/reddit_enrich.py", "category": "function_complex", "repo_id": "sickn33/antigravity-awesome-skills"} {"input": "\"\"\"\nTests for Cursor .mdc frontmatter generation (issue #669).\n\nVerifies that update-agent-context.sh properly prepends YAML frontmatter\nto .mdc files so that Cursor IDE auto-includes the rules.\n\"\"\"\n\nimport os\nimport shutil\nimport subprocess\nimport textwrap\n\nimport pytest\n\nSCRIPT_PATH = os.path.join(\n os.path.dirname(__file__),\n os.pardir,\n \"scripts\",\n \"bash\",\n \"update-agent-context.sh\",\n)\n\nEXPECTED_FRONTMATTER_LINES = [\n \"---\",\n \"description: Project Development Guidelines\",\n 'globs: [\"**/*\"]',\n \"alwaysApply: true\",\n \"---\",\n]\n\nrequires_git = pytest.mark.skipif(\n shutil.which(\"git\") is None,\n reason=\"git is not installed\",\n)\n\n\nclass TestScriptFrontmatterPattern:\n \"\"\"Static analysis — no git required.\"\"\"\n\n def test_create_new_has_mdc_frontmatter_logic(self):\n \"\"\"create_new_agent_file() must contain .mdc frontmatter logic.\"\"\"\n with open(SCRIPT_PATH, encoding=\"utf-8\") as f:\n content = f.read()\n assert 'if [[ \"$target_file\" == *.mdc ]]' in content\n assert \"alwaysApply:", "label": 1, "sample_id": "github/spec-kit:tests/test_cursor_frontmatter.py", "category": "test", "repo_id": "github/spec-kit"} {"input": "\"\"\"Image generation provider for GPT Researcher.\n\nThis module provides image generation capabilities using Google's Gemini/Imagen\nmodels via the google.genai SDK.\n\nSupported models:\n- Gemini image models (free tier): models/gemini-2.5-flash-image\n- Imagen models (requires billing): imagen-4.0-generate-001\n\"\"\"\n\nimport asyncio\nimport base64\nimport hashlib\nimport os\nimport logging\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImageGeneratorProvider:\n \"\"\"Provider for generating images using Google's Gemini/Imagen models.\n \n Attributes:\n model_name: The model to use for image generation.\n api_key: Google API key for authentication.\n output_dir: Directory to save generated images.\n \"\"\"\n \n # Gemini models use generate_content with inline_data response\n GEMINI_IMAGE_MODELS = [\n \"models/gemini-2.5-flash-image\",\n \"gemini-2.5-flash-image\",\n \"gemini-2.0-flash-exp-image-generation\",\n \"gemini-3-pro-image-preview\",\n ]\n \n # Imagen models use generate_images (requires billing)\n ", "label": 1, "sample_id": "assafelovic/gpt-researcher:gpt_researcher/llm_provider/image/image_generator.py", "category": "function_complex", "repo_id": "assafelovic/gpt-researcher"} {"input": "import shutil\nfrom pathlib import Path\n\nimport pytest\n\n\n@pytest.mark.integration\n@pytest.mark.install\n@pytest.mark.editable\n@pytest.mark.vcs\ndef test_editable_vcs_reinstall(pipenv_instance_private_pypi):\n \"\"\"Test that editable VCS dependencies are reinstalled when the source checkout is missing.\"\"\"\n with pipenv_instance_private_pypi() as p:\n # Create a Pipfile with an editable VCS dependency\n with open(p.pipfile_path, \"w\") as f:\n f.write(\"\"\"\n[[source]]\nurl = \"https://pypi.org/simple\"\nverify_ssl = true\nname = \"pypi\"\n\n[packages]\ngunicorn = {git = \"https://github.com/benoitc/gunicorn\", ref = \"23.0.0\", editable = true}\n \"\"\".strip())\n\n # Install the dependency\n c = p.pipenv(\"install\")\n assert c.returncode == 0, f\"Failed to install: {c.stderr}\"\n\n # Verify the src directory was created\n # The src directory could be in the project directory or in the virtualenv directory\n src_dir_project = Path(p.path) / \"src\"\n venv_location = p.virtualenv_location\n ", "label": 1, "sample_id": "pypa/pipenv:tests/integration/test_editable_vcs.py", "category": "test", "repo_id": "pypa/pipenv"} {"input": "# Copyright (c) ONNX Project Contributors\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any\n\nif TYPE_CHECKING:\n from collections.abc import Sequence\n\nimport numpy as np\n\nimport onnx\nfrom onnx.backend.test.case.base import Base\nfrom onnx.backend.test.case.node import expect\n\n\n# The below ScatterElements' numpy implementation is from https://stackoverflow.com/a/46204790/11767360\ndef scatter_elements(\n data: np.ndarray,\n indices: np.ndarray,\n updates: np.ndarray,\n axis: int = 0,\n reduction: str = \"none\",\n) -> np.ndarray:\n if axis < 0:\n axis = data.ndim + axis\n\n idx_xsection_shape = indices.shape[:axis] + indices.shape[axis + 1 :]\n\n def make_slice(arr: np.ndarray, axis: int, i: int) -> list[slice | int]:\n slc: list[slice | int] = [slice(None)] * arr.ndim\n slc[axis] = i\n return slc\n\n def unpack(packed: Any)", "label": 0, "sample_id": "onnx/onnx:onnx/backend/test/case/node/scatterelements.py", "category": "unknown", "repo_id": "onnx/onnx"} {"input": "__package__ = 'archivebox.api'\n\nimport json\nfrom io import StringIO\nfrom typing import List, Dict, Any, Optional\nfrom enum import Enum\n\nfrom django.http import HttpRequest\n\nfrom ninja import Router, Schema\n\nfrom archivebox.misc.util import ansi_to_html\nfrom archivebox.config.common import ARCHIVING_CONFIG\n\n\n# from .auth import API_AUTH_METHODS\n\n# router for API that exposes archivebox cli subcommands as REST endpoints\nrouter = Router(tags=['ArchiveBox CLI Sub-Commands'])\n\n\n# Schemas\n\nJSONType = List[Any] | Dict[str, Any] | bool | int | str | None\n\nclass CLICommandResponseSchema(Schema):\n success: bool\n errors: List[str]\n result: JSONType\n result_format: str = 'str'\n stdout: str\n stderr: str\n\nclass FilterTypeChoices(str, Enum):\n exact = 'exact'\n substring = 'substring'\n regex = 'regex'\n domain = 'domain'\n tag = 'tag'\n timestamp = 'timestamp'\n\nclass StatusChoices(str, Enum):\n indexed = 'indexed'\n archived = 'archived'\n unarchived = 'unarchived'\n present = 'present'\n valid =", "label": 0, "sample_id": "ArchiveBox/ArchiveBox:archivebox/api/v1_cli.py", "category": "unknown", "repo_id": "ArchiveBox/ArchiveBox"} {"input": "# Copyright 2026 Marimo. All rights reserved.\nfrom __future__ import annotations\n\nfrom typing import Literal, NewType, Optional\n\nimport msgspec\n\n# Type-safe server identifier\nLspServerId = NewType(\"LspServerId\", str)\n\n# Status enum for LSP server health\nLspServerStatus = Literal[\n \"starting\", # process launched, initializing\n \"running\", # healthy and responsive to pings\n \"stopped\", # not running (never started or cleanly stopped)\n \"crashed\", # exited with non-zero code\n \"unresponsive\", # process alive but not responding to pings\n]\n\n\nclass LspServerHealth(msgspec.Struct, rename=\"camel\"):\n \"\"\"Health status for a single LSP server.\n\n Status meanings:\n - starting: process launched, initializing\n - running: healthy and responsive to pings\n - stopped: not running (never started or cleanly stopped)\n - crashed: exited with non-zero code\n - unresponsive: process alive but not responding to pings\n \"\"\"\n\n server_id: LspServerId\n status: LspServerStatus\n port: int\n last_ping_ms: Optional", "label": 1, "sample_id": "marimo-team/marimo:marimo/_server/models/lsp.py", "category": "function_simple", "repo_id": "marimo-team/marimo"} {"input": "\"\"\"Shared type declarations for the Apache Solr vector store integration.\"\"\"\n\nfrom typing import TypedDict\n\nfrom pydantic import BaseModel\nfrom typing_extensions import NotRequired\n\n\nclass BoostedTextField(BaseModel):\n \"\"\"\n A text field with an optional boost value for Solr queries.\n\n This model represents a Solr field that can have a multiplicative boost\n factor applied to increase or decrease its relevance in search results.\n Boost factors greater than 1.0 increase relevance, while factors between\n 0.0 and 1.0 decrease it.\n\n Attributes:\n field: The Solr field name to include in the search.\n boost_factor: The boost multiplier to apply. Defaults\n to 1.0 (no boost). Values > 1.0 increase relevance, 0.0 < values < 1.0\n decrease it.\n\n \"\"\"\n\n field: str\n boost_factor: float = 1.0\n\n def get_query_str(self) -> str: # pragma: no cover\n \"\"\"\n Return Solr query syntax representation for this field.\n\n If the boost factor is 1.0 (default) the field term is returned as-is;\n otherwise the canonical Solr boost syntax ``", "label": 1, "sample_id": "run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/types.py", "category": "documentation", "repo_id": "run-llama/llama_index"} {"input": "\"\"\"Shared HuggingFace-based helpers for image-classification engines.\"\"\"\n\nfrom __future__ import annotations\n\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Iterable, Optional, Union\n\nimport numpy as np\n\nfrom docling.datamodel.accelerator_options import AcceleratorOptions\nfrom docling.models.inference_engines.common import HfVisionModelMixin\nfrom docling.models.inference_engines.image_classification.base import (\n BaseImageClassificationEngine,\n BaseImageClassificationEngineOptions,\n ImageClassificationEngineInput,\n ImageClassificationEngineOutput,\n)\n\nif TYPE_CHECKING:\n from docling.datamodel.stage_model_specs import EngineModelConfig\n\n\nclass HfImageClassificationEngineBase(\n HfVisionModelMixin, BaseImageClassificationEngine\n):\n \"\"\"Base class for image-classification engines that load HF artifacts/configs.\"\"\"\n\n def __init__(\n self,\n *,\n options: BaseImageClassificationEngineOptions,\n model_config: Optional[EngineModelConfig] = None,\n accelerator_options: AcceleratorOptions,\n artifacts_path: Optional[Union[Path, str]] = None,\n ) -> None:\n super().__init__(options=options, model_config=model_config)\n self.options: BaseImageClassificationEngineOptions = options\n self", "label": 1, "sample_id": "docling-project/docling:docling/models/inference_engines/image_classification/hf_base.py", "category": "function_simple", "repo_id": "docling-project/docling"} {"input": "import pyray as rl\nfrom cereal import log, messaging\nfrom msgq.visionipc import VisionStreamType\nfrom openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView\nfrom openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer\nfrom openpilot.selfdrive.ui.ui_state import ui_state, device\nfrom openpilot.selfdrive.selfdrived.events import EVENTS, ET\nfrom openpilot.system.ui.lib.application import gui_app, FontWeight\nfrom openpilot.system.ui.lib.multilang import tr\nfrom openpilot.system.ui.widgets import Widget\nfrom openpilot.system.ui.widgets.nav_widget import NavWidget\nfrom openpilot.system.ui.widgets.label import gui_label\n\nEventName = log.OnroadEvent.EventName\n\nEVENT_TO_INT = EventName.schema.enumerants\n\n\nclass DriverCameraView(CameraView):\n def _calc_frame_matrix(self, rect: rl.Rectangle):\n base = super()._calc_frame_matrix(rect)\n driver_view_ratio = 1.5\n base[0, 0] *= driver_view_ratio\n base[1, 1] *= driver_view_ratio\n return base\n\n\nclass BaseDriverCameraDialog(Widget):\n # Not a Nav", "label": 1, "sample_id": "commaai/openpilot:selfdrive/ui/mici/onroad/driver_camera_dialog.py", "category": "function_complex", "repo_id": "commaai/openpilot"} {"input": "\"\"\"Content type negotiation for A2A protocol.\n\nThis module handles negotiation of input/output MIME types between A2A clients\nand servers based on AgentCard capabilities.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import TYPE_CHECKING, Annotated, Final, Literal, cast\n\nfrom a2a.types import Part\n\nfrom crewai.events.event_bus import crewai_event_bus\nfrom crewai.events.types.a2a_events import A2AContentTypeNegotiatedEvent\n\n\nif TYPE_CHECKING:\n from a2a.types import AgentCard, AgentSkill\n\n\nTEXT_PLAIN: Literal[\"text/plain\"] = \"text/plain\"\nAPPLICATION_JSON: Literal[\"application/json\"] = \"application/json\"\nIMAGE_PNG: Literal[\"image/png\"] = \"image/png\"\nIMAGE_JPEG: Literal[\"image/jpeg\"] = \"image/jpeg\"\nIMAGE_WILDCARD: Literal[\"image/*\"] = \"image/*\"\nAPPLICATION_PDF: Literal[\"application/pdf\"] = \"application/pdf\"\nAPPLICATION_OCTET_STREAM: Literal[\"application/octet-stream\"] = (\n \"application/octet-stream\"\n)\n\nDEFAULT_CLIENT_INPUT_MODES: Final[list[Literal[\"text/plain\", \"application/json\"]]] = [\n TEXT_PLAIN,\n APPLICATION_JSON", "label": 1, "sample_id": "crewAIInc/crewAI:lib/crewai/src/crewai/a2a/utils/content_type.py", "category": "function_complex", "repo_id": "crewAIInc/crewAI"} {"input": "import torch\nfrom typing_extensions import override\nfrom comfy_api.latest import IO, ComfyExtension\nfrom comfy_api_nodes.apis.pixverse import (\n PixverseTextVideoRequest,\n PixverseImageVideoRequest,\n PixverseTransitionVideoRequest,\n PixverseImageUploadResponse,\n PixverseVideoResponse,\n PixverseGenerationStatusResponse,\n PixverseAspectRatio,\n PixverseQuality,\n PixverseDuration,\n PixverseMotionMode,\n PixverseStatus,\n PixverseIO,\n pixverse_templates,\n)\nfrom comfy_api_nodes.util import (\n ApiEndpoint,\n download_url_to_video_output,\n poll_op,\n sync_op,\n tensor_to_bytesio,\n validate_string,\n)\n\nAVERAGE_DURATION_T2V = 32\nAVERAGE_DURATION_I2V = 30\nAVERAGE_DURATION_T2T = 52\n\n\nasync def upload_image_to_pixverse(cls: type[IO.ComfyNode], image: torch.Tensor):\n response_upload = await sync_op(\n cls,\n ApiEndpoint(path=\"/proxy/pixverse/image/upload\", method=\"POST\"),\n response_model=PixverseImageUploadResponse,\n files={\"image\": tensor_to_bytesio(image)},\n content_type=\"multipart/form-data\",\n ", "label": 1, "sample_id": "Comfy-Org/ComfyUI:comfy_api_nodes/nodes_pixverse.py", "category": "function_complex", "repo_id": "Comfy-Org/ComfyUI"} {"input": "from warnings import warn\n\nfrom django.forms import Media\nfrom django.utils import translation\nfrom django.utils.translation import gettext_lazy as _\n\nfrom wagtail import hooks\nfrom wagtail.admin.ui.components import Component\nfrom wagtail.admin.utils import get_admin_base_url\nfrom wagtail.coreutils import accepts_kwarg\nfrom wagtail.models import Revision\nfrom wagtail.models.pages import Page\nfrom wagtail.users.models import UserProfile\nfrom wagtail.utils.deprecation import RemovedInWagtail80Warning\n\n\nclass BaseItem(Component):\n template_name = \"wagtailadmin/userbar/item_base.html\"\n\n def get_context_data(self, parent_context):\n context = super().get_context_data(parent_context)\n context[\"self\"] = self\n context[\"request\"] = parent_context.get(\"request\")\n return context\n\n\nclass AdminItem(BaseItem):\n template_name = \"wagtailadmin/userbar/item_admin.html\"\n\n\nclass AccessibilityItem(BaseItem):\n \"\"\"A userbar item that runs the accessibility checker.\"\"\"\n\n def __init__(self, in_editor=False):\n super().__init__()\n self.in_editor = in_editor\n \"\"\"Whether the accessibility checker is being run in the page editor.\"\"\"\n\n #: The template to use for rendering the item.\n template", "label": 0, "sample_id": "wagtail/wagtail:wagtail/admin/userbar.py", "category": "unknown", "repo_id": "wagtail/wagtail"} {"input": "\"\"\"\nCopyright 2024, Zep Software, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\nclass GraphitiError(Exception):\n \"\"\"Base exception class for Graphiti Core.\"\"\"\n\n\nclass EdgeNotFoundError(GraphitiError):\n \"\"\"Raised when an edge is not found.\"\"\"\n\n def __init__(self, uuid: str):\n self.message = f'edge {uuid} not found'\n super().__init__(self.message)\n\n\nclass EdgesNotFoundError(GraphitiError):\n \"\"\"Raised when a list of edges is not found.\"\"\"\n\n def __init__(self, uuids: list[str]):\n self.message = f'None of the edges for {uuids} were found.'\n super().__init__(self.message)\n\n\nclass GroupsEdgesNotFoundError(GraphitiError):\n", "label": 0, "sample_id": "getzep/graphiti:graphiti_core/errors.py", "category": "unknown", "repo_id": "getzep/graphiti"} {"input": "import logging\nimport subprocess\n\nlogger = logging.getLogger(__name__)\n\n\ndef safe_run_cmd(cmd_args, shell=False):\n if shell:\n raise ValueError(\"shell=True is not allowed in safe_run_cmd. \" \"Pass command as a list with shell=False.\")\n cmd_args = [str(arg) for arg in cmd_args]\n try:\n return subprocess.run(cmd_args, shell=False)\n except Exception as e:\n logger.error(\"Failed to run command %s: %s\", cmd_args, e)\n return None\n\n\ndef truncate_file(file_path):\n try:\n with open(file_path, \"w\"):\n pass\n except Exception as e:\n logger.error(\"Failed to truncate file %s: %s\", file_path, e)\n\n\ndef find_and_delete_files(directory, name_pattern=None, mtime_days=None):\n cmd = [\"find\", str(directory), \"-type\", \"f\"]\n if mtime_days is not None:\n cmd.extend([\"-mtime\", \"+%s\" % int(mtime_days)])\n if name_pattern is not None:\n cmd.extend([\"-name\", str(name_pattern)])\n cmd.append(\"-delete\")\n return safe_run_cmd(cmd)\n\n\ndef find_and_delete_empty_dirs(directory):\n cmd = [\"find", "label": 1, "sample_id": "jumpserver/jumpserver:apps/common/utils/safe.py", "category": "function_simple", "repo_id": "jumpserver/jumpserver"} {"input": "import json\nimport os\nimport logging\nimport queue\n\nimport torch\nimport numpy as np\nfrom torch.utils.dlpack import to_dlpack\nimport triton_python_backend_utils as pb_utils\nfrom hyperpyyaml import load_hyperpyyaml\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger(__name__)\n\n\nclass TrtContextWrapper:\n def __init__(self, trt_engine, trt_concurrent=1, device='cuda:0'):\n self.trt_context_pool = queue.Queue(maxsize=trt_concurrent)\n self.trt_engine = trt_engine\n self.device = device\n for _ in range(trt_concurrent):\n trt_context = trt_engine.create_execution_context()\n trt_stream = torch.cuda.stream(torch.cuda.Stream(torch.device(device)))\n assert trt_context is not None\n self.trt_context_pool.put([trt_context, trt_stream])\n\n def acquire_estimator(self):\n return self.trt_context_pool.get(), self.trt_engine\n\n def release_estimator(self, context, stream):\n self.trt_context_pool.put([context, stream])\n\n\ndef convert_onnx_to_trt", "label": 0, "sample_id": "FunAudioLLM/CosyVoice:runtime/triton_trtllm/model_repo_cosyvoice3/token2wav/1/model.py", "category": "unknown", "repo_id": "FunAudioLLM/CosyVoice"} {"input": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2026\n# Leandro Toledo de Souza \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program. If not, see [http://www.gnu.org/licenses/].\n# pylint: disable=missing-module-docstring\nfrom typing import Final, NamedTuple\n\n__all__ = (\"__version__\", \"__version_info__\")\n\n\nclass Version(NamedTuple):\n \"\"\"Copies the behavior of sys.version_info.\n serial is always 0 for stable releases.\n ", "label": 0, "sample_id": "python-telegram-bot/python-telegram-bot:src/telegram/_version.py", "category": "unknown", "repo_id": "python-telegram-bot/python-telegram-bot"} {"input": "\"\"\"\nFile and file system-related tools, specifically for\n * listing directory contents\n * reading files\n * creating files\n * editing at the file level\n\"\"\"\n\nimport os\nfrom collections import defaultdict\nfrom fnmatch import fnmatch\nfrom pathlib import Path\nfrom typing import Literal\n\nfrom serena.tools import SUCCESS_RESULT, EditedFileContext, Tool, ToolMarkerCanEdit, ToolMarkerOptional\nfrom serena.util.file_system import scan_directory\nfrom serena.util.text_utils import ContentReplacer, search_files\n\n\nclass ReadFileTool(Tool):\n \"\"\"\n Reads a file within the project directory.\n \"\"\"\n\n def apply(self, relative_path: str, start_line: int = 0, end_line: int | None = None, max_answer_chars: int = -1) -> str:\n \"\"\"\n Reads the given file or a chunk of it. Generally, symbolic operations\n like find_symbol or find_referencing_symbols should be preferred if you know which symbols you are looking for.\n\n :param relative_path: the relative path to the file to read\n :param start_line: the 0-based index of the first line to be retrieved.\n :param end_line: the 0-based index of the last line", "label": 1, "sample_id": "oraios/serena:src/serena/tools/file_tools.py", "category": "documentation", "repo_id": "oraios/serena"} {"input": "#!/usr/bin/env python3\n\"\"\"Ensure keyword arguments use spaces around '=', prune redundant pass statements.\"\"\"\n\nfrom __future__ import annotations\n\nimport ast\nimport argparse\nimport io\nimport sys\nimport tokenize\nfrom collections import defaultdict\nfrom pathlib import Path\n\n\ndef enforce_spacing(text: str) -> tuple[str, bool]:\n \"\"\"Return updated text with keyword '=' padded by spaces, plus change flag.\"\"\"\n lines = text.splitlines(keepends=True)\n if not lines:\n return text, False\n\n offsets: dict[int, int] = defaultdict(int)\n changed = False\n\n reader = io.StringIO(text).readline\n for token in tokenize.generate_tokens(reader):\n if token.type != tokenize.OP or token.string != \"=\":\n continue\n\n line_index = token.start[0] - 1\n col = token.start[1] + offsets[line_index]\n\n if line_index < 0 or line_index >= len(lines):\n continue\n\n line = lines[line_index]\n if col >= len(line) or line[col] != \"=\":\n continue\n\n line_changed = False\n\n # Insert a space before '=' when missing and not preceded by whitespace.\n if col > 0 and line[col - 1", "label": 1, "sample_id": "unslothai/unsloth:scripts/enforce_kwargs_spacing.py", "category": "function_complex", "repo_id": "unslothai/unsloth"} {"input": "\"\"\"\nProvides Elm specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Elm.\n\"\"\"\n\nimport logging\nimport os\nimport pathlib\nimport shutil\nimport threading\n\nfrom overrides import override\nfrom sensai.util.logging import LogTime\n\nfrom solidlsp.ls import SolidLanguageServer\nfrom solidlsp.ls_config import LanguageServerConfig\nfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParams\nfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfo\nfrom solidlsp.settings import SolidLSPSettings\n\nfrom .common import RuntimeDependency, RuntimeDependencyCollection\n\nlog = logging.getLogger(__name__)\n\n\nclass ElmLanguageServer(SolidLanguageServer):\n \"\"\"\n Provides Elm specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Elm.\n \"\"\"\n\n def __init__(self, config: LanguageServerConfig, repository_root_path: str, solidlsp_settings: SolidLSPSettings):\n \"\"\"\n Creates an ElmLanguageServer instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead.\n \"\"\"\n elm_lsp_executable_path = self._setup_runtime_dependencies(config, solidlsp_settings)\n\n # Resolve ELM_HOME to absolute path if it's set to a relative", "label": 1, "sample_id": "oraios/serena:src/solidlsp/language_servers/elm_language_server.py", "category": "function_complex", "repo_id": "oraios/serena"} {"input": "from unittest.mock import MagicMock\n\nimport pytest\n\nfrom scrapy import signals\nfrom scrapy.exceptions import NotConfigured\nfrom scrapy.extensions import statsmailer\nfrom scrapy.mail import MailSender\nfrom scrapy.signalmanager import SignalManager\nfrom scrapy.statscollectors import StatsCollector\nfrom scrapy.utils.spider import DefaultSpider\n\n\n@pytest.fixture\ndef dummy_stats():\n class DummyStats(StatsCollector):\n def __init__(self):\n # pylint: disable=super-init-not-called\n self._stats = {\"global_item_scraped_count\": 42}\n\n def get_stats(self):\n return {\"item_scraped_count\": 10, **self._stats}\n\n return DummyStats()\n\n\ndef test_from_crawler_without_recipients_raises_notconfigured():\n crawler = MagicMock()\n crawler.settings.getlist.return_value = []\n crawler.stats = MagicMock()\n\n with pytest.raises(NotConfigured):\n statsmailer.StatsMailer.from_crawler(crawler)\n\n\ndef test_from_crawler_with_recipients_initializes_extension(dummy_stats, monkeypatch):\n crawler = MagicMock()\n crawler.settings.getlist.return_value = [\"test@example.com\"]\n crawler.stats = dummy_stats\n crawler.signals = SignalManager(crawler)\n\n mailer = MagicMock(spec=MailSender)\n ", "label": 1, "sample_id": "scrapy/scrapy:tests/test_extension_statsmailer.py", "category": "test", "repo_id": "scrapy/scrapy"} {"input": "import time\nfrom dataclasses import dataclass, field\nfrom typing import Callable, cast\n\nimport mlx.core as mx\nfrom mlx_lm.generate import (\n BatchGenerator as MlxBatchGenerator,\n)\nfrom mlx_lm.models.cache import RotatingKVCache\nfrom mlx_lm.sample_utils import make_logits_processors, make_sampler\nfrom mlx_lm.tokenizer_utils import StreamingDetokenizer, TokenizerWrapper\n\nfrom exo.shared.types.api import (\n CompletionTokensDetails,\n FinishReason,\n GenerationStats,\n PromptTokensDetails,\n TopLogprobItem,\n Usage,\n)\nfrom exo.shared.types.memory import Memory\nfrom exo.shared.types.mlx import KVCacheType, Model\nfrom exo.shared.types.text_generation import TextGenerationTaskParams\nfrom exo.shared.types.worker.runner_response import GenerationResponse\nfrom exo.worker.engines.mlx.cache import (\n CacheSnapshot,\n KVPrefixCache,\n encode_prompt,\n make_kv_cache,\n)\nfrom exo.worker.engines.mlx.constants import DEFAULT_TOP_LOGPROBS, MAX_TOKENS\nfrom exo.worker.engines.mlx.generator.generate import (\n ban_token_ids,\n eos_ids_from_tokenizer,\n extract_top_logprobs,\n prefill,\n)\nfrom exo", "label": 0, "sample_id": "exo-explore/exo:src/exo/worker/engines/mlx/generator/batch_generate.py", "category": "unknown", "repo_id": "exo-explore/exo"} {"input": "#Original code can be found on: https://github.com/black-forest-labs/flux\n\nfrom dataclasses import dataclass\n\nimport torch\nfrom torch import Tensor, nn\nfrom einops import rearrange, repeat\nimport comfy.ldm.common_dit\nimport comfy.patcher_extension\n\nfrom .layers import (\n DoubleStreamBlock,\n EmbedND,\n LastLayer,\n MLPEmbedder,\n SingleStreamBlock,\n timestep_embedding,\n Modulation,\n)\n\n@dataclass\nclass FluxParams:\n in_channels: int\n out_channels: int\n vec_in_dim: int\n context_in_dim: int\n hidden_size: int\n mlp_ratio: float\n num_heads: int\n depth: int\n depth_single_blocks: int\n axes_dim: list\n theta: int\n patch_size: int\n qkv_bias: bool\n guidance_embed: bool\n txt_ids_dims: list\n global_modulation: bool = False\n mlp_silu_act: bool = False\n ops_bias: bool = True\n default_ref_method: str = \"offset\"\n ref_index_scale: float = 1.0\n yak_mlp", "label": 0, "sample_id": "Comfy-Org/ComfyUI:comfy/ldm/flux/model.py", "category": "unknown", "repo_id": "Comfy-Org/ComfyUI"} {"input": "from __future__ import annotations\n\nfrom datetime import datetime, timezone\nfrom uuid import UUID, uuid4\n\nfrom pydantic import BaseModel, computed_field, field_serializer\nfrom pydantic import Field as PydanticField\nfrom sqlalchemy import CheckConstraint, Column, DateTime, ForeignKey, UniqueConstraint, func\nfrom sqlmodel import JSON, Field, SQLModel\n\n\nclass FlowVersion(SQLModel, table=True): # type: ignore[call-arg]\n __tablename__ = \"flow_version\"\n __mapper_args__ = {\"confirm_deleted_rows\": False}\n\n id: UUID = Field(default_factory=uuid4, primary_key=True)\n flow_id: UUID = Field(\n sa_column=Column(ForeignKey(\"flow.id\", ondelete=\"CASCADE\"), index=True, nullable=False),\n )\n user_id: UUID | None = Field(\n sa_column=Column(ForeignKey(\"user.id\", ondelete=\"SET NULL\"), index=True, nullable=True),\n )\n data: dict | None = Field(default=None, sa_column=Column(JSON))\n version_number: int = Field(nullable=False, ge=1)\n description: str | None = Field(default=None, nullable=True, max_length=500)\n created_at", "label": 0, "sample_id": "langflow-ai/langflow:src/backend/base/langflow/services/database/models/flow_version/model.py", "category": "unknown", "repo_id": "langflow-ai/langflow"} {"input": "from unittest.mock import MagicMock, Mock, patch\n\nimport pytest\nfrom rich.console import Console\nfrom rich.text import Text\n\nfrom agno.agent import Agent\nfrom agno.models.openai import OpenAIChat\n\n\ndef test_print_response_with_message_panel():\n \"\"\"Test that print_response creates a message panel when show_message=True\"\"\"\n\n def get_the_weather():\n return \"It is currently 70 degrees and cloudy in Tokyo\"\n\n with patch(\"agno.utils.print_response.agent.Live\") as mock_live_class:\n mock_live = MagicMock()\n mock_live_class.return_value.__enter__ = Mock(return_value=mock_live)\n mock_live_class.return_value.__exit__ = Mock(return_value=None)\n\n with patch(\"agno.utils.print_response.agent.create_panel\") as mock_create_panel:\n agent = Agent(\n model=OpenAIChat(id=\"gpt-4o-mini\"),\n tools=[get_the_weather],\n markdown=True,\n telemetry=False,\n )\n mock_console = MagicMock(spec=Console)\n mock_console.is_jupyter = False\n # Mock a successful run response\n with patch.object(agent, \"run\") as mock_run:\n mock_response = Mock()\n mock_response.content = \"It is currently 70 degrees and", "label": 1, "sample_id": "agno-agi/agno:libs/agno/tests/integration/agent/test_print_response.py", "category": "test", "repo_id": "agno-agi/agno"} {"input": "\"\"\"\nScript to run GPT-Researcher queries and evaluate them for hallucination.\n\"\"\"\nimport json\nimport logging\nimport random\nimport asyncio\nimport argparse\nimport os\nfrom pathlib import Path\nfrom typing import Dict, List, Optional\nfrom dotenv import load_dotenv\n\nfrom gpt_researcher.agent import GPTResearcher\nfrom gpt_researcher.utils.enum import ReportType, ReportSource, Tone\nfrom gpt_researcher.utils.logging_config import get_json_handler\n\nfrom .evaluate import HallucinationEvaluator\n\n# Configure logging\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n)\nlogger = logging.getLogger(__name__)\n\n# Load environment variables\nload_dotenv()\n\n# Default paths\nDEFAULT_OUTPUT_DIR = \"evals/hallucination_eval/results\"\nDEFAULT_QUERIES_FILE = \"evals/hallucination_eval/inputs/search_queries.jsonl\"\n\nclass ResearchEvaluator:\n \"\"\"Runs GPT-Researcher queries and evaluates responses for hallucination.\"\"\"\n \n def __init__(self, queries_file: str = DEFAULT_QUERIES_FILE):\n \"\"\"\n Initialize the research evaluator.\n \n Args:\n queries_file: Path to JSONL", "label": 1, "sample_id": "assafelovic/gpt-researcher:evals/hallucination_eval/run_eval.py", "category": "function_complex", "repo_id": "assafelovic/gpt-researcher"} {"input": "# pragma pylint: disable=missing-docstring, W0212, line-too-long, C0103, unused-argument\n\nfrom copy import deepcopy\nfrom unittest.mock import MagicMock\n\nimport pandas as pd\nimport pytest\n\nfrom freqtrade.configuration import TimeRange\nfrom freqtrade.data import history\nfrom freqtrade.data.history import get_timerange\nfrom freqtrade.enums import ExitType\nfrom freqtrade.optimize.backtesting import Backtesting\nfrom freqtrade.util.datetime_helpers import dt_utc\nfrom tests.conftest import EXMS, patch_exchange\n\n\ndef test_backtest_position_adjustment(default_conf, fee, mocker, testdatadir) -> None:\n default_conf[\"use_exit_signal\"] = False\n default_conf[\"max_open_trades\"] = 10\n mocker.patch(f\"{EXMS}.get_fee\", fee)\n mocker.patch(\n \"freqtrade.optimize.backtesting.amount_to_contract_precision\",\n lambda x, *args, **kwargs: round(x, 8),\n )\n mocker.patch(f\"{EXMS}.get_min_pair_stake_amount\", return_value=0.00001)\n mocker.patch(f\"{EXMS}.get_max_pair_stake_amount\", return_value=float(\"inf\"))\n patch", "label": 0, "sample_id": "freqtrade/freqtrade:tests/optimize/test_backtesting_adjust_position.py", "category": "unknown", "repo_id": "freqtrade/freqtrade"} {"input": "import logging\nimport re\nimport uuid\nfrom pathlib import Path\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\n\nfrom documents.data_models import ConsumableDocument\nfrom documents.data_models import DocumentMetadataOverrides\nfrom documents.mail import EmailAttachment\nfrom documents.mail import send_email\nfrom documents.models import Correspondent\nfrom documents.models import Document\nfrom documents.models import DocumentType\nfrom documents.models import WorkflowAction\nfrom documents.models import WorkflowTrigger\nfrom documents.plugins.base import StopConsumeTaskError\nfrom documents.signals import document_consumption_finished\nfrom documents.templating.workflows import parse_w_workflow_placeholders\nfrom documents.workflows.webhooks import send_webhook\n\nlogger = logging.getLogger(\"paperless.workflows.actions\")\n\n\ndef build_workflow_action_context(\n document: Document | ConsumableDocument,\n overrides: DocumentMetadataOverrides | None,\n) -> dict:\n \"\"\"\n Build context dictionary for workflow action placeholder parsing.\n \"\"\"\n use_overrides = overrides is not None\n\n if not use_overrides:\n return {\n \"title\": document.title,\n \"doc_url\": f\"{settings.PAPERLESS_URL}{settings.BASE_URL}documents/{document.pk}/\",\n \"correspondent\": document.cor", "label": 1, "sample_id": "paperless-ngx/paperless-ngx:src/documents/workflows/actions.py", "category": "function_complex", "repo_id": "paperless-ngx/paperless-ngx"} {"input": "import pytest\nimport torch\n\nfrom torch_geometric.llm.utils.vectorrag import DocumentRetriever\nfrom torch_geometric.testing import onlyRAG\n\n\n@pytest.fixture\ndef sample_documents():\n \"\"\"Fixture providing sample documents for testing.\"\"\"\n return [\n \"This is the first test document.\",\n \"This is the second test document.\", \"This is the third test document.\"\n ]\n\n\n@pytest.fixture\ndef sample_model():\n \"\"\"Fixture providing a mock model for testing.\"\"\"\n from unittest.mock import Mock\n\n mock_model = Mock()\n # Mock the model to return a simple tensor when called\n mock_model.side_effect = [\n torch.zeros(1, 384),\n torch.ones(1, 384),\n torch.ones(1, 384) * 2,\n torch.ones(1, 384) * 1\n ]\n\n return mock_model\n\n\ndef test_save_load(sample_documents, sample_model, tmp_path):\n \"\"\"Test whether saving/loading a DocumentRetriever maintains state.\"\"\"\n retriever = DocumentRetriever(sample_documents, model=sample_model)\n retriever.save(tmp_path / \"retriever.pth\")\n loaded_retriever = DocumentRetriever.load(tmp_path", "label": 1, "sample_id": "pyg-team/pytorch_geometric:test/llm/utils/test_vectorrag.py", "category": "test", "repo_id": "pyg-team/pytorch_geometric"} {"input": "import numpy as np\n\nfrom dspy.clients import Embedder\nfrom dspy.primitives import Example\n\n\nclass KNN:\n def __init__(self, k: int, trainset: list[Example], vectorizer: Embedder):\n \"\"\"\n A k-nearest neighbors retriever that finds similar examples from a training set.\n\n Args:\n k: Number of nearest neighbors to retrieve\n trainset: List of training examples to search through\n vectorizer: The `Embedder` to use for vectorization\n\n Examples:\n ```python\n import dspy\n from sentence_transformers import SentenceTransformer\n\n # Create a training dataset with examples\n trainset = [\n dspy.Example(input=\"hello\", output=\"world\"),\n # ... more examples ...\n ]\n\n # Initialize KNN with a sentence transformer model\n knn = KNN(\n k=3,\n trainset=trainset,\n vectorizer=dspy.Embedder(SentenceTransformer(\"all-MiniLM-L6-v2\").encode)\n )\n\n # Find similar examples\n similar_examples = knn(input=\"hello\")\n ```\n \"\"\"\n self.k = k\n self.trainset = trainset\n self.embedding = vector", "label": 0, "sample_id": "stanfordnlp/dspy:dspy/predict/knn.py", "category": "unknown", "repo_id": "stanfordnlp/dspy"} {"input": "import warnings\nfrom asyncio import sleep\n\nimport pytest\n\nfrom scrapy import Spider, signals\nfrom scrapy.exceptions import ScrapyDeprecationWarning\nfrom scrapy.utils.defer import maybe_deferred_to_future\nfrom scrapy.utils.test import get_crawler\nfrom tests.test_spider_start import SLEEP_SECONDS\n\nfrom .utils import twisted_sleep\nfrom .utils.decorators import coroutine_test\n\nITEM_A = {\"id\": \"a\"}\nITEM_B = {\"id\": \"b\"}\nITEM_C = {\"id\": \"c\"}\nITEM_D = {\"id\": \"d\"}\n\n\nclass AsyncioSleepSpiderMiddleware:\n async def process_start(self, start):\n await sleep(SLEEP_SECONDS)\n async for item_or_request in start:\n yield item_or_request\n\n\nclass NoOpSpiderMiddleware:\n async def process_start(self, start):\n async for item_or_request in start:\n yield item_or_request\n\n\nclass TwistedSleepSpiderMiddleware:\n async def process_start(self, start):\n await maybe_deferred_to_future(twisted_sleep(SLEEP_SECONDS))\n async for item_or_request in start:\n yield item_or_request\n\n\nclass UniversalSpiderMiddleware:\n async def process_start(self, start):\n async for item_or_request in start:\n yield item_or_request", "label": 1, "sample_id": "scrapy/scrapy:tests/test_spidermiddleware_process_start.py", "category": "test", "repo_id": "scrapy/scrapy"} {"input": "\"\"\"Execution policies for the persistent shell middleware.\"\"\"\n\nfrom __future__ import annotations\n\nimport abc\nimport json\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport typing\nfrom collections.abc import Mapping, Sequence\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\n\ntry: # pragma: no cover - optional dependency on POSIX platforms\n import resource\n\n _HAS_RESOURCE = True\nexcept ImportError: # pragma: no cover - non-POSIX systems\n _HAS_RESOURCE = False\n\n\nSHELL_TEMP_PREFIX = \"langchain-shell-\"\n\n\ndef _launch_subprocess(\n command: Sequence[str],\n *,\n env: Mapping[str, str],\n cwd: Path,\n preexec_fn: typing.Callable[[], None] | None,\n start_new_session: bool,\n) -> subprocess.Popen[str]:\n return subprocess.Popen( # noqa: S603\n list(command),\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=cwd,\n text=True,\n encoding=\"utf-8\",\n errors=\"replace\",\n bufsize=1,\n env=env,\n preexec_fn=preexec_fn, # noqa: PLW15", "label": 1, "sample_id": "langchain-ai/langchain:libs/langchain_v1/langchain/agents/middleware/_execution.py", "category": "function_complex", "repo_id": "langchain-ai/langchain"} {"input": "import os\n\nimport pytest\n\nfrom solidlsp import SolidLanguageServer\nfrom solidlsp.ls_config import Language\nfrom solidlsp.ls_utils import SymbolUtils\nfrom test.conftest import is_ci\n\n\n# Kotlin LSP (IntelliJ-based, pre-alpha v261) crashes on JVM restart under CI resource constraints\n# (2 CPUs, 7GB RAM). First start succeeds but subsequent starts fail with cancelled (-32800).\n# Tests pass reliably on developer machines. See PR #1061 for investigation details.\n@pytest.mark.skipif(is_ci, reason=\"Kotlin LSP JVM restart is unstable on CI runners\")\n@pytest.mark.kotlin\nclass TestKotlinLanguageServer:\n @pytest.mark.parametrize(\"language_server\", [Language.KOTLIN], indirect=True)\n def test_find_symbol(self, language_server: SolidLanguageServer) -> None:\n symbols = language_server.request_full_symbol_tree()\n assert SymbolUtils.symbol_tree_contains_name(symbols, \"Main\"), \"Main class not found in symbol tree\"\n assert SymbolUtils.symbol_tree_contains_name(symbols, \"Utils\"), \"Utils class not found in symbol tree\"\n assert SymbolUtils.symbol_tree_contains_name(symbols, \"Model\"), \"Model class not found", "label": 1, "sample_id": "oraios/serena:test/solidlsp/kotlin/test_kotlin_basic.py", "category": "test", "repo_id": "oraios/serena"} {"input": "import pytest\n\nfrom scrapling.engines.toolbelt.custom import StatusText, Response\nfrom scrapling.engines.toolbelt.navigation import (\n construct_proxy_dict,\n create_intercept_handler,\n create_async_intercept_handler,\n)\nfrom scrapling.engines.toolbelt.fingerprints import (\n get_os_name,\n generate_headers\n)\n\n\n@pytest.fixture\ndef content_type_map():\n return {\n # A map generated by ChatGPT for most possible `content_type` values and the expected outcome\n \"text/html; charset=UTF-8\": \"UTF-8\",\n \"text/html; charset=ISO-8859-1\": \"ISO-8859-1\",\n \"text/html\": \"ISO-8859-1\",\n \"application/json; charset=UTF-8\": \"UTF-8\",\n \"application/json\": \"utf-8\",\n \"text/json\": \"utf-8\",\n \"application/javascript; charset=UTF-8\": \"UTF-8\",\n \"application/javascript\": \"utf-8\",\n \"text/plain; charset=UTF-8\": \"UTF-8\",\n \"text/plain; charset=ISO-8859-1\": \"ISO-8859-", "label": 0, "sample_id": "D4Vinci/Scrapling:tests/fetchers/test_utils.py", "category": "unknown", "repo_id": "D4Vinci/Scrapling"} {"input": "import re\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Dict, List, Optional\n\nimport pyarrow as pa\nfrom huggingface_hub import HfApi\n\nimport datasets\nfrom datasets import Audio, Image, Video\nfrom datasets.builder import Key\nfrom datasets.table import table_cast\nfrom datasets.utils.file_utils import is_local_path\n\n\nif TYPE_CHECKING:\n import lance\n import lance.file\n\nlogger = datasets.utils.logging.get_logger(__name__)\n\nMAGIC_BYTES_EXTENSION_AND_FEATURE_TYPES = [\n (\"1A 45 DF A3\", \".mkv\", Video()),\n (\"66 74 79 70 69 73 6F 6D\", \".mp4\", Video()),\n (\"66 74 79 70 4D 53 4E 56\", \".mp4\", Video()),\n (\"52 49 46 46\", \".avi\", Video()),\n (\"00 00 01 BA\", \".mpeg\", Video()),\n (\"00 00 01 BA\", \".mpeg\", Video()),\n (\"00 00 01", "label": 1, "sample_id": "huggingface/datasets:src/datasets/packaged_modules/lance/lance.py", "category": "function_complex", "repo_id": "huggingface/datasets"} {"input": "\"\"\"\nProject Euler Problem 9: https://projecteuler.net/problem=9\n\nSpecial Pythagorean triplet\n\nA Pythagorean triplet is a set of three natural numbers, a < b < c, for which,\n\n a^2 + b^2 = c^2.\n\nFor example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.\n\nThere exists exactly one Pythagorean triplet for which a + b + c = 1000.\nFind the product abc.\n\nReferences:\n - https://en.wikipedia.org/wiki/Pythagorean_triple\n\"\"\"\n\n\ndef get_squares(n: int) -> list[int]:\n \"\"\"\n >>> get_squares(0)\n []\n >>> get_squares(1)\n [0]\n >>> get_squares(2)\n [0, 1]\n >>> get_squares(3)\n [0, 1, 4]\n >>> get_squares(4)\n [0, 1, 4, 9]\n \"\"\"\n return [number * number for number in range(n)]\n\n\ndef solution(n: int = 1000) -> int:\n \"\"\"\n Pre", "label": 1, "sample_id": "TheAlgorithms/Python:project_euler/problem_009/sol4.py", "category": "documentation", "repo_id": "TheAlgorithms/Python"} {"input": "def _setup_env(monkeypatch):\n monkeypatch.setenv(\"DOCLING_PERF_PAGE_BATCH_SIZE\", \"12\")\n monkeypatch.setenv(\"DOCLING_DEBUG_VISUALIZE_RAW_LAYOUT\", \"True\")\n monkeypatch.setenv(\"DOCLING_ARTIFACTS_PATH\", \"/path/to/artifacts\")\n monkeypatch.setenv(\"DOCLING_INFERENCE_COMPILE_TORCH_MODELS\", \"True\")\n\n\ndef test_settings(monkeypatch):\n _setup_env(monkeypatch)\n\n import importlib\n\n import docling.datamodel.settings as m\n\n # Reinitialize settings module\n importlib.reload(m)\n\n # Check top level setting\n assert str(m.settings.artifacts_path) == \"/path/to/artifacts\"\n\n # Check nested set via environment variables\n assert m.settings.perf.page_batch_size == 12\n assert m.settings.debug.visualize_raw_layout is True\n assert m.settings.inference.compile_torch_models is True\n\n # Check nested defaults\n assert m.settings.perf.doc_batch_size == 1\n assert m.settings.debug.visualize_ocr is False\n\n\ndef test_compile_model_defaults_from_settings(monkeypatch):\n monkeypatch.setenv(\"DOCLING_INFERENCE_COMPILE", "label": 1, "sample_id": "docling-project/docling:tests/test_settings_load.py", "category": "test", "repo_id": "docling-project/docling"} {"input": "import re\nfrom typing import Dict, List\n\nimport numpy as np\nimport trimesh\nfrom pxr import Usd, UsdGeom, UsdPhysics\n\nimport genesis as gs\nfrom genesis.utils import geom as gu\n\nfrom .usd_context import UsdContext\nfrom .usd_utils import AXES_T, usd_attr_array_to_numpy, usd_primvar_array_to_numpy\n\n\ndef geom_exception(geom_type, geom_id, stage_file, reason_msg):\n gs.raise_exception(f\"{reason_msg} for {geom_type} {geom_id} in usd file {stage_file}.\")\n\n\ndef get_triangle_ids(tri_starts, tri_counts):\n tri_bases = np.repeat(tri_starts, tri_counts)\n tri_offsets = np.arange(tri_counts.sum(), dtype=np.int32)\n tri_stages = np.repeat(np.cumsum(tri_counts, dtype=np.int32) - tri_counts, tri_counts)\n return tri_bases + tri_offsets - tri_stages\n\n\ndef parse_prim_geoms(\n context: UsdContext,\n prim: Usd.Prim,\n link_prim: Usd.Prim,\n links_g_infos: List[List[Dict]],\n link_path_to_idx: Dict[str,", "label": 1, "sample_id": "Genesis-Embodied-AI/Genesis:genesis/utils/usd/usd_geometry.py", "category": "function_complex", "repo_id": "Genesis-Embodied-AI/Genesis"} {"input": "# HumanEval/147\n# Loki Mode Multi-Agent Solution\n# Attempts: 1\n# Passed: True\n\ndef get_max_triples(n):\n \"\"\"\n You are given a positive integer n. You have to create an integer array a of length n.\n For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.\n Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n and a[i] + a[j] + a[k] is a multiple of 3.\n\n Example :\n Input: n = 5\n Output: 1\n Explanation: \n a = [1, 3, 7, 13, 21]\n The only valid triple is (1, 7, 13).\n \"\"\"\n if n < 3:\n return 0\n \n a = [i * i - i + 1 for i in range(1, n + 1)]\n \n count = 0\n for i in range(n):\n for j in range(i + 1, n):\n for k in range(j", "label": 1, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/humaneval-loki-solutions/147.py", "category": "documentation", "repo_id": "davila7/claude-code-templates"} {"input": "\"\"\"Auto-discovery for built-in channel modules and external plugins.\"\"\"\n\nfrom __future__ import annotations\n\nimport importlib\nimport pkgutil\nfrom typing import TYPE_CHECKING\n\nfrom loguru import logger\n\nif TYPE_CHECKING:\n from nanobot.channels.base import BaseChannel\n\n_INTERNAL = frozenset({\"base\", \"manager\", \"registry\"})\n\n\ndef discover_channel_names() -> list[str]:\n \"\"\"Return all built-in channel module names by scanning the package (zero imports).\"\"\"\n import nanobot.channels as pkg\n\n return [\n name\n for _, name, ispkg in pkgutil.iter_modules(pkg.__path__)\n if name not in _INTERNAL and not ispkg\n ]\n\n\ndef load_channel_class(module_name: str) -> type[BaseChannel]:\n \"\"\"Import *module_name* and return the first BaseChannel subclass found.\"\"\"\n from nanobot.channels.base import BaseChannel as _Base\n\n mod = importlib.import_module(f\"nanobot.channels.{module_name}\")\n for attr in dir(mod):\n obj = getattr(mod, attr)\n if isinstance(obj, type) and issubclass(obj, _Base) and obj is not _Base:\n return obj\n raise ImportError(f\"No BaseChannel subclass in nanobot.channels.{", "label": 0, "sample_id": "HKUDS/nanobot:nanobot/channels/registry.py", "category": "unknown", "repo_id": "HKUDS/nanobot"} {"input": "\"\"\"\nLightRAG Demo with OpenSearch + OpenAI\n\nThis example demonstrates how to use LightRAG with:\n- OpenAI (LLM + Embeddings)\n- OpenSearch-backed storages for:\n - KV storage\n - Vector storage (k-NN)\n - Graph storage (dual-index nodes + edges)\n - Document status storage\n\nPrerequisites:\n1. OpenSearch cluster running and accessible (3.x or higher with k-NN plugin)\n2. Required indices will be auto-created by LightRAG\n3. Set environment variables (example .env):\n\n OPENSEARCH_HOSTS=localhost:9200\n OPENSEARCH_USER=admin\n OPENSEARCH_PASSWORD=your-password\n OPENSEARCH_USE_SSL=false\n OPENSEARCH_VERIFY_CERTS=false\n\n OPENAI_API_KEY=your-api-key\n\n4. Prepare a text file to index (default: ./book.txt)\n\nUsage:\n python examples/lightrag_openai_opensearch_graph_demo.py\n\"\"\"\n\nimport os\nimport asyncio\nimport numpy as np\n\nfrom lightrag import LightRAG, QueryParam\nfrom lightrag.llm.openai import gpt_4o_mini_complete, openai_embed\nfrom lightrag.utils", "label": 0, "sample_id": "HKUDS/LightRAG:examples/lightrag_openai_opensearch_graph_demo.py", "category": "unknown", "repo_id": "HKUDS/LightRAG"} {"input": "\"\"\"Factory helpers for node executors.\n\nCreate and manage executors for different node types.\n\"\"\"\n\nfrom typing import Dict\n\nfrom runtime.node.executor.base import NodeExecutor, ExecutionContext\nfrom runtime.node.registry import iter_node_registrations\n\n\nclass NodeExecutorFactory:\n \"\"\"Factory class that instantiates executors for every node type.\"\"\"\n \n @staticmethod\n def create_executors(context: ExecutionContext, subgraphs: dict = None) -> Dict[str, NodeExecutor]:\n \"\"\"Create executors for every registered node type.\n \n Args:\n context: Shared execution context\n subgraphs: Mapping of subgraph nodes (used by Subgraph executors)\n \n Returns:\n Mapping from node type to executor instance\n \"\"\"\n subgraphs = subgraphs or {}\n \n executors: Dict[str, NodeExecutor] = {}\n for name, registration in iter_node_registrations().items():\n executors[name] = registration.build_executor(context, subgraphs=subgraphs)\n return executors\n \n @staticmethod\n def create_executor(\n node_type: str,\n context: ExecutionContext,\n subgraphs: dict = None\n ) -> NodeExecutor:\n \"\"\"Create an executor for the requested node type.\n \n Args:\n node_type:", "label": 1, "sample_id": "OpenBMB/ChatDev:runtime/node/executor/factory.py", "category": "documentation", "repo_id": "OpenBMB/ChatDev"} {"input": "# Zulip's OpenAPI-based API documentation system is documented at\n# https://zulip.readthedocs.io/en/latest/documentation/api.html\n#\n# This file contains helper functions for generating cURL examples\n# based on Zulip's OpenAPI definitions, as well as test setup and\n# fetching of appropriate parameter values to use when running the\n# cURL examples as part of the tools/test-api test suite.\nimport re\nfrom collections.abc import Callable\nfrom functools import wraps\nfrom typing import Any, cast\n\nfrom django.utils.timezone import now as timezone_now\n\nfrom zerver.actions.channel_folders import check_add_channel_folder\nfrom zerver.actions.create_user import do_create_user\nfrom zerver.actions.presence import update_user_presence\nfrom zerver.actions.reactions import do_add_reaction\nfrom zerver.actions.realm_linkifiers import do_add_linkifier\nfrom zerver.actions.realm_playgrounds import check_add_realm_playground\nfrom zerver.lib.events import do_events_register\nfrom zerver.lib.initial_password import initial_password\nfrom zerver.lib.test_classes import ZulipTestCase\nfrom zerver.lib.test_helpers import read_test_image_file\nfrom zerver.lib.upload import upload_message_attachment\nfrom zerver.models import Client, Message", "label": 0, "sample_id": "zulip/zulip:zerver/openapi/curl_param_value_generators.py", "category": "unknown", "repo_id": "zulip/zulip"} {"input": "import uuid\nfrom datetime import UTC, datetime\nfrom typing import Any\n\nfrom strix.tools.registry import register_tool\n\n\n_notes_storage: dict[str, dict[str, Any]] = {}\n\n\ndef _filter_notes(\n category: str | None = None,\n tags: list[str] | None = None,\n search_query: str | None = None,\n) -> list[dict[str, Any]]:\n filtered_notes = []\n\n for note_id, note in _notes_storage.items():\n if category and note.get(\"category\") != category:\n continue\n\n if tags:\n note_tags = note.get(\"tags\", [])\n if not any(tag in note_tags for tag in tags):\n continue\n\n if search_query:\n search_lower = search_query.lower()\n title_match = search_lower in note.get(\"title\", \"\").lower()\n content_match = search_lower in note.get(\"content\", \"\").lower()\n if not (title_match or content_match):\n continue\n\n note_with_id = note.copy()\n note_with_id[\"note_id\"] = note_id\n filtered_notes.append(note_with_id)\n\n filtered_notes.sort(key=lambda x: x.get(\"created_at\", \"\"), reverse=True)\n return filtered_notes\n\n\n@register_tool(sandbox_execution=False", "label": 1, "sample_id": "usestrix/strix:strix/tools/notes/notes_actions.py", "category": "function_complex", "repo_id": "usestrix/strix"} {"input": "#!/usr/bin/env python3\n\"\"\"Handles updating of an alignments file from an older version to the current version.\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport typing as T\n\nimport numpy as np\n\nfrom lib.logger import parse_class_init\nfrom lib.utils import get_module_objects, VIDEO_EXTENSIONS\n\nlogger = logging.getLogger(__name__)\n\nif T.TYPE_CHECKING:\n from lib import align\n\n\nclass _Updater():\n \"\"\"Base class for inheriting to test for and update of an alignments file property\n\n Parameters\n ----------\n alignments\n The alignments object that is being tested and updated\n \"\"\"\n def __init__(self, alignments: align.alignments.Alignments) -> None:\n logger.debug(parse_class_init(locals()))\n self._alignments = alignments\n self._needs_update = self._test()\n if self._needs_update:\n self._update()\n logger.debug(\"Initialized: %s\", self.__class__.__name__)\n\n @property\n def is_updated(self) -> bool:\n \"\"\"``True`` if this updater has been run otherwise ``False``\"\"\"\n return self._needs_update\n\n def _test(self) -> bool:\n \"\"\"Calls the child's :func:`test` method", "label": 0, "sample_id": "deepfakes/faceswap:lib/align/updater.py", "category": "unknown", "repo_id": "deepfakes/faceswap"} {"input": "\"\"\"\nMake Sentence\n\nFor a given string and dictionary, count how many sentences can be formed\nfrom the string such that all words are contained in the dictionary.\n\nReference: https://en.wikipedia.org/wiki/Word_break_problem\n\nComplexity:\n Time: O(2^n) worst case due to recursive exploration\n Space: O(n) recursion depth\n\"\"\"\n\nfrom __future__ import annotations\n\ncount = 0\n\n\ndef make_sentence(text_piece: str, dictionaries: list[str]) -> bool:\n \"\"\"Check if a string can be segmented into dictionary words and count ways.\n\n Updates the global ``count`` variable with the number of valid segmentations.\n\n Args:\n text_piece: The string to segment.\n dictionaries: A list of valid dictionary words.\n\n Returns:\n True if any segmentation is possible (always returns True).\n\n Examples:\n >>> make_sentence(\"applet\", [\"\", \"app\", \"let\", \"t\", \"apple\", \"applet\"])\n True\n \"\"\"\n global count\n if len(text_piece) == 0:\n return True\n for index in range(0, len(text_piece)):\n prefix, suffix = text_piece[0:index], text_piece[index:]\n if (prefix in dictionaries", "label": 1, "sample_id": "keon/algorithms:algorithms/string/make_sentence.py", "category": "documentation", "repo_id": "keon/algorithms"} {"input": "import django_filters\nimport graphene\nfrom django.db.models import Q\n\nfrom ....product.models import Category\nfrom ...core.doc_category import DOC_CATEGORY_PRODUCTS\nfrom ...core.filters import (\n FilterInputObjectType,\n GlobalIDMultipleChoiceFilter,\n GlobalIDMultipleChoiceWhereFilter,\n ListObjectTypeFilter,\n MetadataFilterBase,\n MetadataWhereFilterBase,\n ObjectTypeFilter,\n)\nfrom ...core.filters.where_input import (\n WhereInputObjectType,\n)\nfrom ...core.types import (\n DateTimeRangeInput,\n)\nfrom ...utils.filters import (\n filter_by_ids,\n filter_slug_list,\n)\nfrom .shared import filter_updated_at_range\n\n\nclass CategoryFilter(MetadataFilterBase):\n search = django_filters.CharFilter(method=\"category_filter_search\")\n ids = GlobalIDMultipleChoiceFilter(field_name=\"id\")\n slugs = ListObjectTypeFilter(input_class=graphene.String, method=filter_slug_list)\n updated_at = ObjectTypeFilter(\n input_class=DateTimeRangeInput,\n method=filter_updated_at_range,\n help_text=\"Filter by when was the most recent update.\",\n )\n\n class Meta:\n model = Category\n fields = [\"search\"]\n\n @classmethod\n def category_filter_search(cls, queryset, _name, value):\n ", "label": 1, "sample_id": "saleor/saleor:saleor/graphql/product/filters/category.py", "category": "function_simple", "repo_id": "saleor/saleor"} {"input": "#! /usr/env/bin/python3\n\"\"\" Handles interfacing between Faceswap Configs and ConfigParser .ini files \"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport textwrap\nimport typing as T\n\nfrom configparser import ConfigParser\n\nfrom lib.logger import parse_class_init\nfrom lib.utils import get_module_objects, PROJECT_ROOT\n\nif T.TYPE_CHECKING:\n from .objects import ConfigSection, ConfigValueType\n\nlogger = logging.getLogger(__name__)\n\n\nclass ConfigFile():\n \"\"\" Handles the interfacing between saved faceswap .ini configs and internal Config objects\n\n Parameters\n ----------\n plugin_group : str\n The plugin group that is requesting a config file\n ini_path : str | None, optional\n Optional path to a .ini config file. ``None`` for default location. Default: ``None``\n \"\"\"\n def __init__(self, plugin_group: str, ini_path: str | None = None) -> None:\n parse_class_init(locals())\n self._plugin_group = plugin_group\n self._file_path = self._get_config_path(ini_path)\n self._parser = self._get_new_configparser()\n if self._exists: # Load or create new\n self.load", "label": 1, "sample_id": "deepfakes/faceswap:lib/config/ini.py", "category": "documentation", "repo_id": "deepfakes/faceswap"} {"input": "\"\"\"\nCustom adapter for improving structured outputs using the information from Pydantic models.\nBased on the format used by BAML: https://github.com/BoundaryML/baml\n\"\"\"\n\nimport inspect\nimport types\nfrom typing import Any, Literal, Union, get_args, get_origin\n\nfrom pydantic import BaseModel\n\nfrom dspy.adapters.json_adapter import JSONAdapter\nfrom dspy.adapters.utils import format_field_value as original_format_field_value\nfrom dspy.signatures.signature import Signature\n\n# Changing the comment symbol to Python's # rather than other languages' // seems to help\nCOMMENT_SYMBOL = \"#\"\nINDENTATION = \" \"\n\n\ndef _render_type_str(\n annotation: Any,\n depth: int = 0,\n indent: int = 0,\n seen_models: set[type] | None = None,\n) -> str:\n \"\"\"Recursively renders a type annotation into a simplified string.\n\n Args:\n annotation: The type annotation to render\n depth: Current recursion depth (prevents infinite recursion)\n indent: Current indentation level for nested structures\n \"\"\"\n # Non-nested types\n if annotation is str:\n return \"string\"\n if annotation is int:\n return \"int\"\n if annotation is float", "label": 1, "sample_id": "stanfordnlp/dspy:dspy/adapters/baml_adapter.py", "category": "function_complex", "repo_id": "stanfordnlp/dspy"} {"input": "\"\"\"\nCloud management client for connecting to the LinkAI control console.\n\nHandles remote configuration sync, message push, and skill management\nvia the LinkAI socket protocol.\n\"\"\"\n\nfrom bridge.context import Context, ContextType\nfrom bridge.reply import Reply, ReplyType\nfrom common.log import logger\nfrom linkai import LinkAIClient, PushMsg\nfrom config import conf, pconf, plugin_config, available_setting, write_plugin_config, get_root\nfrom plugins import PluginManager\nimport threading\nimport time\nimport json\nimport os\n\n\nchat_client: LinkAIClient\n\n\nclass CloudClient(LinkAIClient):\n def __init__(self, api_key: str, channel, host: str = \"\"):\n super().__init__(api_key, host)\n self.channel = channel\n self.client_type = channel.channel_type\n self.channel_mgr = None\n self._skill_service = None\n self._memory_service = None\n self._chat_service = None\n\n @property\n def skill_service(self):\n \"\"\"Lazy-init SkillService so it is available once SkillManager exists.\"\"\"\n if self._skill_service is None:\n try:\n from agent.skills.manager import SkillManager\n from agent.skills.service import SkillService\n from config import", "label": 1, "sample_id": "zhayujie/chatgpt-on-wechat:common/cloud_client.py", "category": "function_complex", "repo_id": "zhayujie/chatgpt-on-wechat"} {"input": "import json\nimport os\nfrom typing import Dict\n\nfrom utils.config import config, resource_path\n\n_LOCALES_CACHE: Dict[str, Dict[str, str]] = {}\n_CURRENT_LANG = None\n_TRANSLATIONS: Dict[str, str] = {}\n\n\ndef _load_locale(lang: str) -> Dict[str, str]:\n global _LOCALES_CACHE\n if lang in _LOCALES_CACHE:\n return _LOCALES_CACHE[lang]\n\n locales_dir = resource_path(os.path.join(\"locales\"))\n file_path = os.path.join(locales_dir, f\"{lang}.json\")\n\n if not os.path.exists(file_path):\n fallback_path = os.path.join(locales_dir, \"zh_CN.json\")\n file_path = fallback_path\n\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n except Exception:\n data = {}\n\n _LOCALES_CACHE[lang] = data\n return data\n\n\ndef set_language(lang: str):\n global _CURRENT_LANG, _TRANSLATIONS\n _CURRENT_LANG = lang\n _TRANSLATIONS = _load_locale(lang)\n\n\ndef get_language() -> str:\n global _CURRENT_LANG\n if", "label": 1, "sample_id": "Guovin/iptv-api:utils/i18n.py", "category": "function_simple", "repo_id": "Guovin/iptv-api"} {"input": "# This script is based on examples/lily_finetuning/lily_finetuning.py\nimport os\n\nimport torch\nfrom datasets import load_dataset\nfrom transformers import (\n AutoModelForCausalLM,\n AutoTokenizer,\n DataCollatorForLanguageModeling,\n Trainer,\n TrainingArguments,\n)\n\nfrom peft import PeanutConfig, get_peft_model\n\n\ndef train_model(\n base_model: str,\n data_path: str,\n output_dir: str,\n batch_size: int,\n num_epochs: int,\n learning_rate: float,\n cutoff_len: int,\n val_set_size: int,\n eval_step: int,\n save_step: int,\n device: str,\n peanut_r: int,\n peanut_depth: int,\n peanut_scaling: float,\n peanut_act_fn: str,\n peanut_target_modules: str,\n peanut_init_weights: bool,\n hub_model_id: str,\n push_to_hub: bool,\n):\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n hf_token = os.getenv(\"HF_TOKEN\")\n\n # Setup device\n if device == \"auto\":\n device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\")", "label": 0, "sample_id": "huggingface/peft:examples/peanut_finetuning/peanut_finetuning.py", "category": "unknown", "repo_id": "huggingface/peft"} {"input": "import time\nfrom collections import defaultdict\nfrom dataclasses import asdict, dataclass, field\n\nfrom django.db import transaction\nfrom django.db.models import F\nfrom django.utils.timezone import now as timezone_now\nfrom django.utils.translation import gettext as _\n\nfrom analytics.lib.counts import COUNT_STATS, do_increment_logging_stat\nfrom zerver.lib.exceptions import JsonableError\nfrom zerver.lib.message import (\n bulk_access_messages,\n format_unread_message_details,\n get_raw_unread_data,\n)\nfrom zerver.lib.queue import mobile_notifications_queue_name, queue_event_on_commit\nfrom zerver.lib.stream_subscription import get_subscribed_stream_recipient_ids_for_user\nfrom zerver.lib.topic import filter_by_topic_name_via_message\nfrom zerver.lib.user_message import DEFAULT_HISTORICAL_FLAGS, create_historical_user_messages\nfrom zerver.models import Device, Message, PushDeviceToken, Recipient, UserMessage, UserProfile\nfrom zerver.tornado.django_api import send_event_on_commit, send_event_rollback_unsafe\n\n\n@dataclass\nclass ReadMessagesEvent:\n messages: list[int]\n all: bool\n type: str = field(default=\"update_message_flags\", init=False)\n op: str = field(default=\"add\", init", "label": 0, "sample_id": "zulip/zulip:zerver/actions/message_flags.py", "category": "unknown", "repo_id": "zulip/zulip"} {"input": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\"\"\"\nColQwen3 late interaction model for multi-modal retrieval and reranking.\n\nColQwen3 extends Qwen3-VL with a ColBERT-style late interaction head,\nproducing per-token embeddings for both text and image inputs. It uses\nMaxSim scoring for retrieval/reranking tasks.\n\nThis model supports the \"token_embed\" pooling task and is designed for\nmulti-vector retrieval of documents containing both text and images.\n\nReference: https://arxiv.org/abs/2407.01449 (ColPali)\nBased on: Qwen3-VL backbone with custom text projection\n\nTarget models:\n- TomoroAI/tomoro-colqwen3-embed-8b\n- OpenSearch-AI/Ops-Colqwen3-4B\n- nvidia/nemotron-colembed-vl-4b-v2\n\"\"\"\n\nfrom collections.abc import Iterable, Mapping\nfrom typing import ClassVar, Literal\n\nimport torch\nimport torch.nn as nn\nfrom transformers.models.qwen3_vl import Qwen3VLProcessor\n\nfrom vllm.config import VllmConfig", "label": 1, "sample_id": "vllm-project/vllm:vllm/model_executor/models/colqwen3.py", "category": "license", "repo_id": "vllm-project/vllm"} {"input": "from django.core.management import call_command\nfrom django.core.management.base import CommandError\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\n\nclass TestApiSchema(APITestCase):\n ENDPOINT = \"/api/schema/\"\n\n def test_valid_schema(self) -> None:\n \"\"\"\n Test that the schema is valid\n \"\"\"\n try:\n call_command(\n \"spectacular\",\n \"--validate\",\n \"--fail-on-warn\",\n skip_checks=True,\n )\n except CommandError as e:\n self.fail(f\"Schema validation failed: {e}\")\n\n def test_get_schema_endpoints(self) -> None:\n \"\"\"\n Test that the schema endpoints exist and return a 200 status code\n \"\"\"\n schema_response = self.client.get(self.ENDPOINT)\n self.assertEqual(schema_response.status_code, status.HTTP_200_OK)\n\n ui_response = self.client.get(self.ENDPOINT + \"view/\")\n self.assertEqual(ui_response.status_code, status.HTTP_200_OK)\n\n def test_schema_includes_dedicated_document_edit_endpoints(self) -> None:\n schema_response = self.client.get(self.ENDPOINT)\n self.assertEqual(schema_response.status_code, status.HTTP_200_OK)\n\n", "label": 0, "sample_id": "paperless-ngx/paperless-ngx:src/documents/tests/test_api_schema.py", "category": "unknown", "repo_id": "paperless-ngx/paperless-ngx"} {"input": "# Copyright 2026 Marimo. All rights reserved.\nfrom __future__ import annotations\n\nimport abc\nimport io\nfrom typing import NewType, Optional\n\nfrom marimo._messaging.mimetypes import ConsoleMimeType\nfrom marimo._types.ids import CellId_t\n\n# A KernelMessage is a bytes object that contains a serialized NotificationMessage.\nKernelMessage = NewType(\"KernelMessage\", bytes)\n\n\nclass Stream(abc.ABC):\n \"\"\"\n A stream is a class that can write messages from the kernel to\n some output.\n The `write` method is called by the kernel.\n \"\"\"\n\n cell_id: Optional[CellId_t] = None\n\n @abc.abstractmethod\n def write(self, data: KernelMessage) -> None:\n pass\n\n def stop(self) -> None:\n \"\"\"Tear down resources, if any.\"\"\"\n return\n\n\nclass NoopStream(Stream):\n def write(self, data: KernelMessage) -> None:\n pass\n\n\ndef _ensure_plain_str(s: str) -> str:\n \"\"\"Coerce str subclasses to plain ``str``.\n\n Some libraries (e.g. loguru) emit str subclasses whose ``__slots__``\n carry extra metadata (loguru's", "label": 0, "sample_id": "marimo-team/marimo:marimo/_messaging/types.py", "category": "unknown", "repo_id": "marimo-team/marimo"} {"input": "\"\"\"Base index classes.\"\"\"\n\nimport logging\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar\n\nfrom llama_index.core.base.base_query_engine import BaseQueryEngine\nfrom llama_index.core.base.base_retriever import BaseRetriever\nfrom llama_index.core.callbacks.base import CallbackManager\nfrom llama_index.core.chat_engine.types import BaseChatEngine, ChatMode\nfrom llama_index.core.data_structs.data_structs import IndexStruct\nfrom llama_index.core.ingestion import run_transformations, arun_transformations\nfrom llama_index.core.llms.utils import LLMType, resolve_llm\nfrom llama_index.core.schema import BaseNode, Document, IndexNode, TransformComponent\nfrom llama_index.core.settings import Settings\nfrom llama_index.core.storage.docstore.types import BaseDocumentStore, RefDocInfo\nfrom llama_index.core.storage.storage_context import StorageContext\n\nIS = TypeVar(\"IS\", bound=IndexStruct)\nIndexType = TypeVar(\"IndexType\", bound=\"BaseIndex\")\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseIndex(Generic[IS], ABC):\n \"\"\"\n Base LlamaIndex.\n\n Args:\n nodes (List[Node]): List of nodes to index\n", "label": 0, "sample_id": "run-llama/llama_index:llama-index-core/llama_index/core/indices/base.py", "category": "unknown", "repo_id": "run-llama/llama_index"} {"input": "\"\"\"Base classes and functions for HTTP mockservers.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport sys\nfrom abc import ABC, abstractmethod\nfrom subprocess import PIPE, Popen\nfrom typing import TYPE_CHECKING\nfrom urllib.parse import urlparse\n\nfrom twisted.web.server import Site\n\nfrom tests.utils import get_script_run_env\n\nfrom .utils import ssl_context_factory\n\nif TYPE_CHECKING:\n from collections.abc import Callable\n\n from twisted.web import resource\n\n\nclass BaseMockServer(ABC):\n listen_http: bool = True\n listen_https: bool = True\n\n @property\n @abstractmethod\n def module_name(self) -> str:\n raise NotImplementedError\n\n def __init__(self) -> None:\n if not self.listen_http and not self.listen_https:\n raise ValueError(\"At least one of listen_http and listen_https must be set\")\n\n self.proc: Popen | None = None\n self.host: str = \"127.0.0.1\"\n self.http_port: int | None = None\n self.https_port: int | None = None\n\n def __enter__(self):\n self.proc = Popen(\n [sys.executable, \"-u\", \"-m\",", "label": 1, "sample_id": "scrapy/scrapy:tests/mockserver/http_base.py", "category": "test", "repo_id": "scrapy/scrapy"} {"input": "\"\"\"\nTests for Lean 4 Language Server integration with Serena.\n\nTests prove that Serena's symbol tools can:\n1. Start the Lean 4 language server\n2. Discover all expected symbols with precise matching\n3. Track within-file references\n4. Track cross-file references\n\nTest Repository Structure:\n- Helper.lean: Calculator structure, arithmetic functions (add, subtract), predicates (isPositive, absolute)\n- Main.lean: Main entry point using Helper, plus multiply and calculate functions\n\"\"\"\n\nimport pytest\n\nfrom solidlsp.ls import SolidLanguageServer\nfrom solidlsp.ls_config import Language\n\n\n@pytest.mark.lean4\nclass TestLean4LanguageServer:\n @pytest.mark.parametrize(\"language_server\", [Language.LEAN4], indirect=True)\n def test_ls_is_running(self, language_server: SolidLanguageServer) -> None:\n \"\"\"Test that the Lean 4 language server starts successfully.\"\"\"\n assert language_server.is_running()\n\n @pytest.mark.parametrize(\"language_server\", [Language.LEAN4], indirect=True)\n def test_helper_symbols(self, language_server: SolidLanguageServer) -> None:\n \"\"\"\n Test symbol discovery in Helper.lean.\n\n Verifies that Serena can identify:\n - Structure definition (Calculator)\n - All functions (", "label": 0, "sample_id": "oraios/serena:test/solidlsp/lean4/test_lean4_basic.py", "category": "unknown", "repo_id": "oraios/serena"} {"input": "\"\"\"\nBash tool - Execute bash commands\n\"\"\"\n\nimport os\nimport re\nimport sys\nimport subprocess\nimport tempfile\nfrom typing import Dict, Any\n\nfrom agent.tools.base_tool import BaseTool, ToolResult\nfrom agent.tools.utils.truncate import truncate_tail, format_size, DEFAULT_MAX_LINES, DEFAULT_MAX_BYTES\nfrom common.log import logger\nfrom common.utils import expand_path\n\n\nclass Bash(BaseTool):\n \"\"\"Tool for executing bash commands\"\"\"\n\n name: str = \"bash\"\n description: str = f\"\"\"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last {DEFAULT_MAX_LINES} lines or {DEFAULT_MAX_BYTES // 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file.\n\nENVIRONMENT: All API keys from env_config are auto-injected. Use $VAR_NAME directly.\n\nSAFETY:\n- Freely create/modify/delete files within the workspace\n- For destructive and out-of-workspace commands, explain and confirm first\"\"\"\n\n params: dict = {\n \"type\": \"object\",\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": \"Bash command to execute\"\n", "label": 1, "sample_id": "zhayujie/chatgpt-on-wechat:agent/tools/bash/bash.py", "category": "function_complex", "repo_id": "zhayujie/chatgpt-on-wechat"} {"input": "import re\n\nimport pytest\n\nfrom sklearn import config_context\nfrom sklearn.utils._repr_html.common import generate_link_to_param_doc\nfrom sklearn.utils._repr_html.params import ParamsDict, _params_html_repr, _read_params\n\n\ndef test_params_dict_content():\n \"\"\"Check the behavior of the ParamsDict class.\"\"\"\n params = ParamsDict(params={\"a\": 1, \"b\": 2})\n assert params[\"a\"] == 1\n assert params[\"b\"] == 2\n assert params.non_default == ()\n\n params = ParamsDict(params={\"a\": 1, \"b\": 2}, non_default=(\"a\",))\n assert params[\"a\"] == 1\n assert params[\"b\"] == 2\n assert params.non_default == (\"a\",)\n\n\ndef test_params_dict_repr_html_():\n params = ParamsDict(params={\"a\": 1, \"b\": 2}, non_default=(\"a\",), estimator_class=\"\")\n out = params._repr_html_()\n assert \"Parameters\" in out\n\n with config_context(display=\"text\"):\n msg = \"_repr_html_ is only defined when\"\n with pytest.raises(AttributeError, match=msg):\n params._repr_html_()\n\n\ndef test", "label": 1, "sample_id": "scikit-learn/scikit-learn:sklearn/utils/_repr_html/tests/test_params.py", "category": "test", "repo_id": "scikit-learn/scikit-learn"} {"input": "MACROS_NEWCOMMAND = frozenset([\"newcommand\", \"renewcommand\", \"providecommand\"])\n\nMACROS_PREAMBLE_METADATA = frozenset([\"title\", \"author\", \"date\"])\n\nMACROS_INLINE_VERBATIM = frozenset([\"%\", \"$\", \"&\", \"#\", \"_\", \"{\", \"}\", \"~\"])\n\nMACROS_TEXT_FORMATTING = frozenset([\"textbf\", \"textit\", \"emph\", \"texttt\", \"underline\"])\n\nMACROS_CITATION = frozenset([\"cite\", \"citep\", \"citet\", \"ref\", \"eqref\"])\n\nMACROS_COLOR = frozenset([\"color\", \"definecolor\", \"colorlet\"])\n\nMACROS_STRUCTURAL = frozenset(\n [\n \"section\",\n \"subsection\",\n \"subsubsection\",\n \"chapter\",\n \"part\",\n \"paragraph\",\n \"subparagraph\",\n \"caption\",\n \"label\",\n \"includegraphics\",\n \"bibliography\",\n \"title\",\n \"author\",\n \"maketitle\",\n \"footnote\",\n \"marginpar\",\n \"textsc\",\n \"textsf\",\n \"textrm\",\n \"textnormal\",\n \"mbox\",\n \"href\",\n \"newline", "label": 0, "sample_id": "docling-project/docling:docling/backend/latex/constants.py", "category": "unknown", "repo_id": "docling-project/docling"} {"input": "\"\"\"\nProvides TypeScript specific instantiation of the LanguageServer class. Contains various configurations and settings specific to TypeScript.\n\"\"\"\n\nimport logging\nimport os\nimport pathlib\nimport shutil\nimport threading\nfrom typing import Any, cast\n\nfrom overrides import override\nfrom sensai.util.logging import LogTime\n\nfrom solidlsp import ls_types\nfrom solidlsp.ls import LanguageServerDependencyProvider, LanguageServerDependencyProviderSinglePath, SolidLanguageServer\nfrom solidlsp.ls_config import LanguageServerConfig\nfrom solidlsp.ls_utils import PlatformId, PlatformUtils\nfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParams\nfrom solidlsp.settings import SolidLSPSettings\n\nfrom .common import RuntimeDependency, RuntimeDependencyCollection\n\nlog = logging.getLogger(__name__)\n\n# Platform-specific imports\nif os.name != \"nt\": # Unix-like systems\n import pwd\nelse:\n # Dummy pwd module for Windows\n class pwd: # type: ignore\n @staticmethod\n def getpwuid(uid: Any) -> Any:\n return type(\"obj\", (), {\"pw_name\": os.environ.get(\"USERNAME\", \"unknown\")})()\n\n\n# Conditionally import pwd module (Unix-only)\nif not PlatformUtils.get_platform_id().value.startswith(\"", "label": 0, "sample_id": "oraios/serena:src/solidlsp/language_servers/typescript_language_server.py", "category": "unknown", "repo_id": "oraios/serena"} {"input": "import base64\nimport os\nimport time\n\nimport requests\n\n\ndef generate_video(\n prompt_file: str,\n reference_images: list[str],\n output_file: str,\n aspect_ratio: str = \"16:9\",\n) -> str:\n with open(prompt_file, \"r\") as f:\n prompt = f.read()\n referenceImages = []\n i = 0\n json = {\n \"instances\": [{\"prompt\": prompt}],\n }\n for reference_image in reference_images:\n i += 1\n with open(reference_image, \"rb\") as f:\n image_b64 = base64.b64encode(f.read()).decode(\"utf-8\")\n referenceImages.append(\n {\n \"image\": {\"mimeType\": \"image/jpeg\", \"bytesBase64Encoded\": image_b64},\n \"referenceType\": \"asset\",\n }\n )\n if i > 0:\n json[\"instances\"][0][\"referenceImages\"] = referenceImages\n api_key = os.getenv(\"GEMINI_API_KEY\")\n if not api_key:\n return \"GEMINI_API_KEY is not set\"\n response = requests.post(\n \"https://generativelanguage.googleapis.com", "label": 1, "sample_id": "bytedance/deer-flow:skills/public/video-generation/scripts/generate.py", "category": "function_complex", "repo_id": "bytedance/deer-flow"} {"input": "import json\nimport uuid\nfrom unittest.mock import Mock, patch\n\nimport pytest\nfrom opentelemetry import trace as trace_api\nfrom opentelemetry.sdk.trace import ReadableSpan as OTelReadableSpan\n\nimport mlflow\nfrom mlflow.entities.span import create_mlflow_span\nfrom mlflow.environment_variables import MLFLOW_TRACING_SQL_WAREHOUSE_ID\nfrom mlflow.exceptions import MlflowException\nfrom mlflow.store.tracking import SEARCH_TRACES_DEFAULT_MAX_RESULTS\nfrom mlflow.tracing.analysis import TraceFilterCorrelationResult\nfrom mlflow.tracing.client import TracingClient\nfrom mlflow.tracing.constant import SpansLocation, TraceMetadataKey, TraceSizeStatsKey, TraceTagKey\nfrom mlflow.tracing.utils import TraceJSONEncoder\n\nfrom tests.tracing.helper import skip_when_testing_trace_sdk\n\n\ndef test_get_trace_v4():\n mock_store = Mock()\n mock_store.batch_get_traces.return_value = [\"dummy_trace\"]\n\n with patch(\"mlflow.tracing.client._get_store\", return_value=mock_store):\n client = TracingClient()\n trace = client.get_trace(\"trace:/catalog.schema/1234567890\")\n\n assert trace == \"dummy_trace\"\n mock_store", "label": 1, "sample_id": "mlflow/mlflow:tests/tracing/test_tracing_client.py", "category": "test", "repo_id": "mlflow/mlflow"} {"input": "\"\"\"\nIntegração com a skill web-scraper para extração inteligente de fallback.\n\nQuando um scraper nativo retorna 0 registros, este módulo aciona o web-scraper\npara tentativa adicional de extração estruturada dos dados de leiloeiros.\n\nUso direto:\n python web_scraper_fallback.py --estado MA RN AP\n python web_scraper_fallback.py --todos-vazios # usa log da última coleta\n\nO web-scraper é mais robusto para sites com layouts não convencionais,\npaginação, e estruturas não previstas pelo scraper nativo.\n\"\"\"\nfrom __future__ import annotations\n\nimport argparse\nimport asyncio\nimport json\nimport logging\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nsys.path.insert(0, str(Path(__file__).parent))\n\nfrom db import Database\nfrom scraper.base_scraper import should_verify_tls\nfrom scraper.states import SCRAPERS\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO, format=\"%(asctime)s [%(levelname)s] %(message)s\")\n\nDATA_DIR = Path(__file__).parent.parent / \"data\"\nLOG_FILE = DATA_DIR / \"scraping_log.json\"\nSKILL_WEB", "label": 0, "sample_id": "sickn33/antigravity-awesome-skills:skills/junta-leiloeiros/scripts/web_scraper_fallback.py", "category": "unknown", "repo_id": "sickn33/antigravity-awesome-skills"} {"input": "from __future__ import annotations\n\nimport asyncio\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom functools import partial\nfrom typing import TYPE_CHECKING, Any, Callable, TypeVar\n\nfrom typing_extensions import Protocol, runtime_checkable\n\nfrom textual import _time\nfrom textual._callback import invoke\nfrom textual._compat import cached_property\nfrom textual._easing import DEFAULT_EASING, EASING\nfrom textual._types import AnimationLevel, CallbackType\nfrom textual.timer import Timer\n\nif TYPE_CHECKING:\n from textual.app import App\n\n AnimationKey = tuple[int, str]\n \"\"\"Animation keys are the id of the object and the attribute being animated.\"\"\"\n\nEasingFunction = Callable[[float], float]\n\"\"\"Signature for a function that parametrizes animation speed.\n\nAn easing function must map the interval [0, 1] into the interval [0, 1].\n\"\"\"\n\n\nclass AnimationError(Exception):\n \"\"\"An issue prevented animation from starting.\"\"\"\n\n\nReturnType = TypeVar(\"ReturnType\")\n\n\n@runtime_checkable\nclass Animatable(Protocol):\n \"\"\"Protocol for objects that can have their intrinsic values animated.\n\n For example, the transition between two colors can be animated\n because the class [`Color`][", "label": 0, "sample_id": "Textualize/textual:src/textual/_animator.py", "category": "unknown", "repo_id": "Textualize/textual"} {"input": "from typing import TYPE_CHECKING, Callable, List, Optional\n\nif TYPE_CHECKING:\n from typing import Any\n\nfrom docling_core.types.doc.document import TableCell, TableData\nfrom pylatexenc.latexwalker import LatexCharsNode, LatexEnvironmentNode, LatexMacroNode\n\nfrom docling.backend.latex.constants import (\n MACROS_ESCAPED,\n TABLE_MACROS_IGNORE,\n TABLE_MACROS_RULE,\n)\n\n\nclass TableHelperMixin:\n if TYPE_CHECKING:\n\n def _nodes_to_text(self, nodes: \"Any\") -> str: ...\n\n def _process_table_macro_node(\n self,\n n: LatexMacroNode,\n source_latex: str,\n current_cell_nodes: List,\n finish_cell_fn: Callable[..., None],\n finish_row_fn: Callable[[], None],\n parse_brace_args_fn: Callable[[str], List[str]],\n ):\n if n.macroname == \"\\\\\": # Row break\n finish_row_fn()\n\n elif n.macroname == \"multicolumn\":\n if hasattr(n, \"pos\") and n.pos is not None:\n remaining = source_latex[n.pos :]\n args = parse_brace_args_fn(remaining)\n if len(args", "label": 0, "sample_id": "docling-project/docling:docling/backend/latex/utils/table.py", "category": "unknown", "repo_id": "docling-project/docling"} {"input": "\"\"\"Mobjects representing objects from probability theory and statistics.\"\"\"\n\nfrom __future__ import annotations\n\n__all__ = [\"SampleSpace\", \"BarChart\"]\n\n\nfrom collections.abc import Iterable, MutableSequence, Sequence\nfrom typing import Any\n\nimport numpy as np\n\nfrom manim import config, logger\nfrom manim.constants import *\nfrom manim.mobject.geometry.polygram import Rectangle\nfrom manim.mobject.graphing.coordinate_systems import Axes\nfrom manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject\nfrom manim.mobject.svg.brace import Brace\nfrom manim.mobject.text.tex_mobject import MathTex, Tex\nfrom manim.mobject.types.vectorized_mobject import VGroup, VMobject\nfrom manim.typing import Vector3D\nfrom manim.utils.color import (\n BLUE_E,\n DARK_GREY,\n GREEN_E,\n LIGHT_GREY,\n MAROON_B,\n YELLOW,\n ParsableManimColor,\n color_gradient,\n)\nfrom manim.utils.iterables import tuplify\n\nEPSILON = 0.0001\n\n\nclass SampleSpace(Rectangle):\n \"\"\"A mobject representing a twodimensional rectangular\n sampling space.\n\n Examples\n --------\n ..", "label": 0, "sample_id": "ManimCommunity/manim:manim/mobject/graphing/probability.py", "category": "unknown", "repo_id": "ManimCommunity/manim"} {"input": "\"\"\"\nTelegram Agent with User Memory\n================================\n\nPersonal assistant bot that remembers user preferences, hobbies, and\ninterests across conversations. Uses MemoryManager to automatically\ncapture and recall personal details from chat history.\n\nKey concepts:\n - ``MemoryManager`` with custom capture instructions extracts user info.\n - ``enable_agentic_memory=True`` lets the agent store and retrieve memories.\n - ``WebSearchTools`` provides live information for conversational context.\n\nSetup: Set TELEGRAM_TOKEN env var from @BotFather.\n\"\"\"\n\nfrom textwrap import dedent\n\nfrom agno.agent import Agent\nfrom agno.db.sqlite import SqliteDb\nfrom agno.memory.manager import MemoryManager\nfrom agno.models.google import Gemini\nfrom agno.os.app import AgentOS\nfrom agno.os.interfaces.telegram import Telegram\nfrom agno.tools.websearch import WebSearchTools\n\n# ---------------------------------------------------------------------------\n# Create Example\n# ---------------------------------------------------------------------------\n\nagent_db = SqliteDb(db_file=\"tmp/persistent_memory.db\")\n\nmemory_manager = MemoryManager(\n memory_capture_instructions=\"\"\"\\\n Collect User's name,\n Collect Information about user's passion and hobbies,\n Collect Information about the users likes and dislikes,\n Collect information about what the user is doing with their life right now\n \"\"\",\n model", "label": 0, "sample_id": "agno-agi/agno:cookbook/05_agent_os/interfaces/telegram/agent_with_user_memory.py", "category": "unknown", "repo_id": "agno-agi/agno"} {"input": "#!/usr/bin/env python3\n\"\"\"\nQuick tree visualization script with common customization options.\n\nProvides command-line interface for rapid tree visualization with\ncustomizable styles, layouts, and output formats.\n\"\"\"\n\nimport argparse\nimport sys\nfrom pathlib import Path\n\ntry:\n from ete3 import Tree, TreeStyle, NodeStyle\nexcept ImportError:\n print(\"Error: ete3 not installed. Install with: pip install ete3\")\n sys.exit(1)\n\n\ndef create_tree_style(args):\n \"\"\"Create TreeStyle based on arguments.\"\"\"\n ts = TreeStyle()\n\n # Basic display options\n ts.show_leaf_name = args.show_names\n ts.show_branch_length = args.show_lengths\n ts.show_branch_support = args.show_support\n ts.show_scale = args.show_scale\n\n # Layout\n ts.mode = args.mode\n ts.rotation = args.rotation\n\n # Circular tree options\n if args.mode == \"c\":\n ts.arc_start = args.arc_start\n ts.arc_span = args.arc_span\n\n # Spacing\n ts.branch_vertical_margin = args.vertical_margin\n if args.scale_factor:\n ts.scale = args.scale_factor\n\n # Title\n if args.title:\n from ete3 import TextFace", "label": 1, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/scientific/etetoolkit/scripts/quick_visualize.py", "category": "function_complex", "repo_id": "davila7/claude-code-templates"} {"input": "# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nfrom __future__ import annotations\n\nfrom typing import Union\nfrom typing_extensions import Literal\n\nimport httpx\n\nfrom ... import _legacy_response\nfrom ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given\nfrom ..._utils import maybe_transform, async_maybe_transform\nfrom ..._compat import cached_property\nfrom ..._resource import SyncAPIResource, AsyncAPIResource\nfrom ..._response import (\n StreamedBinaryAPIResponse,\n AsyncStreamedBinaryAPIResponse,\n to_custom_streamed_response_wrapper,\n async_to_custom_streamed_response_wrapper,\n)\nfrom ...types.audio import speech_create_params\nfrom ..._base_client import make_request_options\nfrom ...types.audio.speech_model import SpeechModel\n\n__all__ = [\"Speech\", \"AsyncSpeech\"]\n\n\nclass Speech(SyncAPIResource):\n \"\"\"Turn audio into text or text into audio.\"\"\"\n\n @cached_property\n def with_raw_response(self) -> SpeechWithRawResponse:\n \"\"\"\n This property can be used as a prefix for any HTTP method call to return\n the raw response object instead of the parsed content.\n\n For more information, see", "label": 0, "sample_id": "openai/openai-python:src/openai/resources/audio/speech.py", "category": "unknown", "repo_id": "openai/openai-python"} {"input": "\"\"\"Tests for expand_compact_flow functionality.\"\"\"\n\nimport pytest\nfrom fastapi import status\nfrom httpx import AsyncClient\nfrom langflow.processing.expand_flow import (\n CompactEdge,\n CompactNode,\n _expand_edge,\n _expand_node,\n _get_flat_components,\n expand_compact_flow,\n)\n\n# Sample component data mimicking the component_index structure\nSAMPLE_COMPONENTS = {\n \"inputs\": {\n \"ChatInput\": {\n \"display_name\": \"Chat Input\",\n \"description\": \"Receives text input from user\",\n \"template\": {\n \"_type\": \"ChatInput\",\n \"input_value\": {\n \"type\": \"str\",\n \"required\": False,\n \"value\": \"\",\n \"display_name\": \"Input\",\n },\n },\n \"base_classes\": [\"Message\"],\n \"outputs\": [\n {\n \"name\": \"message\",\n \"display_name\": \"Message\",\n \"types\": [\"Message\"],\n }\n ],\n },\n },\n \"outputs\": {\n \"ChatOutput\": {\n \"display_name\": \"Chat Output\",\n \"description\": \"Displays text output to user\",\n \"template\": {\n \"_type\": \"ChatOutput\",\n \"input_value", "label": 1, "sample_id": "langflow-ai/langflow:src/backend/tests/unit/test_expand_flow.py", "category": "test", "repo_id": "langflow-ai/langflow"} {"input": "from django.apps import apps\nfrom django.test import TestCase\nfrom django.utils.module_loading import import_string\n\nfrom netbox.api.serializers import (\n NestedGroupModelSerializer,\n NetBoxModelSerializer,\n OrganizationalModelSerializer,\n PrimaryModelSerializer,\n)\nfrom netbox.filtersets import (\n NestedGroupModelFilterSet,\n NetBoxModelFilterSet,\n OrganizationalModelFilterSet,\n PrimaryModelFilterSet,\n)\nfrom netbox.forms.bulk_edit import (\n NestedGroupModelBulkEditForm,\n NetBoxModelBulkEditForm,\n OrganizationalModelBulkEditForm,\n PrimaryModelBulkEditForm,\n)\nfrom netbox.forms.bulk_import import (\n NestedGroupModelImportForm,\n NetBoxModelImportForm,\n OrganizationalModelImportForm,\n PrimaryModelImportForm,\n)\nfrom netbox.forms.filtersets import (\n NestedGroupModelFilterSetForm,\n NetBoxModelFilterSetForm,\n OrganizationalModelFilterSetForm,\n PrimaryModelFilterSetForm,\n)\nfrom netbox.forms.model_forms import (\n NestedGroupModelForm,\n NetBoxModelForm,\n OrganizationalModelForm,\n PrimaryModelForm,\n)\nfrom netbox.graphql.types import (\n NestedGroupObjectType,\n NetBoxObjectType,\n Organ", "label": 1, "sample_id": "netbox-community/netbox:netbox/netbox/tests/test_base_classes.py", "category": "test", "repo_id": "netbox-community/netbox"} {"input": "\"\"\"\nBasic Telegram Agent\n====================\n\nMinimal Telegram bot that responds to messages in private chats and\nwhen mentioned in groups. Uses SQLite for session persistence so the\nagent remembers conversation history across restarts.\n\nKey concepts:\n - ``reply_to_mentions_only=True`` ignores regular group messages and\n only responds when the bot is mentioned with @.\n - ``add_history_to_context=True`` feeds the last N runs back into the prompt.\n\nSetup: Set TELEGRAM_TOKEN env var from @BotFather.\n\"\"\"\n\nfrom agno.agent import Agent\nfrom agno.db.sqlite import SqliteDb\nfrom agno.models.google import Gemini\nfrom agno.os.app import AgentOS\nfrom agno.os.interfaces.telegram import Telegram\n\n# ---------------------------------------------------------------------------\n# Create Example\n# ---------------------------------------------------------------------------\n\nagent_db = SqliteDb(session_table=\"telegram_sessions\", db_file=\"tmp/telegram_basic.db\")\n\ntelegram_agent = Agent(\n name=\"Telegram Bot\",\n model=Gemini(id=\"gemini-2.5-pro\"),\n db=agent_db,\n instructions=[\n \"You are a helpful assistant on Telegram.\",\n \"Keep responses concise and friendly.\",\n \"When in a group, you respond only when mentioned with @.\",\n ],\n add_history_to_context=True,\n num_history", "label": 0, "sample_id": "agno-agi/agno:cookbook/05_agent_os/interfaces/telegram/basic.py", "category": "unknown", "repo_id": "agno-agi/agno"} {"input": "import django_tables2 as tables\nfrom django.utils.translation import gettext_lazy as _\nfrom django_tables2.utils import Accessor\n\nfrom dcim.models import Rack, RackReservation, RackRole, RackType\nfrom netbox.tables import OrganizationalModelTable, PrimaryModelTable, columns\nfrom tenancy.tables import ContactsColumnMixin, TenancyColumnsMixin\n\nfrom .template_code import OUTER_UNIT, WEIGHT\n\n__all__ = (\n 'RackReservationTable',\n 'RackRoleTable',\n 'RackTable',\n 'RackTypeTable',\n)\n\n\nclass RackRoleTable(OrganizationalModelTable):\n name = tables.Column(\n verbose_name=_('Name'),\n linkify=True\n )\n rack_count = columns.LinkedCountColumn(\n viewname='dcim:rack_list',\n url_params={'role_id': 'pk'},\n verbose_name=_('Racks')\n )\n color = columns.ColorColumn(\n verbose_name=_('Color'),\n )\n tags = columns.TagColumn(\n url_name='dcim:rackrole_list'\n )\n\n class Meta(OrganizationalModelTable.Meta):\n model = RackRole\n fields = (\n 'pk', 'id', 'name', 'rack_count', 'color', 'description',", "label": 0, "sample_id": "netbox-community/netbox:netbox/dcim/tables/racks.py", "category": "unknown", "repo_id": "netbox-community/netbox"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"A script to clean up orphaned e2e snapshots.\n\nUsage:\n python scripts/snapshot_cleanup.py [--dry-run] [--debug] [--ci]\n\nThis script will analyze the e2e test files and identify snapshot files that\nappear to be orphaned (no longer referenced in tests). Run from the project\nroot directory.\n\nOptions:\n --dry-run : Show what would be deleted without actually deleting\n --debug : Show detailed debug information\n --ci : CI", "label": 1, "sample_id": "streamlit/streamlit:scripts/snapshot_cleanup.py", "category": "license", "repo_id": "streamlit/streamlit"} {"input": "import os\nimport re\nimport base64\nimport requests\n\nfrom bridge.context import ContextType\nfrom channel.chat_message import ChatMessage\nfrom common.log import logger\nfrom common.utils import expand_path\nfrom config import conf\nfrom Crypto.Cipher import AES\n\n\nMAGIC_SIGNATURES = [\n (b\"%PDF\", \".pdf\"),\n (b\"\\x89PNG\\r\\n\\x1a\\n\", \".png\"),\n (b\"\\xff\\xd8\\xff\", \".jpg\"),\n (b\"GIF87a\", \".gif\"),\n (b\"GIF89a\", \".gif\"),\n (b\"RIFF\", \".webp\"), # RIFF....WEBP, further checked below\n (b\"PK\\x03\\x04\", \".zip\"), # zip / docx / xlsx / pptx\n (b\"\\x1f\\x8b\", \".gz\"),\n (b\"Rar!\\x1a\\x07\", \".rar\"),\n (b\"7z\\xbc\\xaf\\x27\\x1c\", \".7z\"),\n (b\"\\x00\\x00\\x00\", \".mp4\"), # ftyp box, further checked below\n (", "label": 0, "sample_id": "zhayujie/chatgpt-on-wechat:channel/wecom_bot/wecom_bot_message.py", "category": "unknown", "repo_id": "zhayujie/chatgpt-on-wechat"} {"input": "#!/usr/bin/env python3\n\n__package__ = 'archivebox.cli'\n__command__ = 'archivebox add'\n\nimport sys\nfrom pathlib import Path\n\nfrom typing import TYPE_CHECKING\n\nimport rich_click as click\n\nfrom django.utils import timezone\nfrom django.db.models import QuerySet\n\nfrom archivebox.misc.util import enforce_types, docstring\nfrom archivebox import CONSTANTS\nfrom archivebox.config.common import ARCHIVING_CONFIG, SERVER_CONFIG\nfrom archivebox.config.permissions import USER, HOSTNAME\n\n\nif TYPE_CHECKING:\n from archivebox.core.models import Snapshot\n from archivebox.crawls.models import Crawl\n\n\ndef _collect_input_urls(args: tuple[str, ...]) -> list[str]:\n from archivebox.misc.jsonl import read_args_or_stdin\n\n urls: list[str] = []\n for record in read_args_or_stdin(args):\n url = record.get('url')\n if isinstance(url, str) and url:\n urls.append(url)\n\n urls_field = record.get('urls')\n if isinstance(urls_field, str):\n for line in urls_field.splitlines():\n line = line.strip()\n if line and not line.startswith('#'):\n urls.append(line)\n\n return urls\n\n\n@enforce_types\ndef", "label": 0, "sample_id": "ArchiveBox/ArchiveBox:archivebox/cli/archivebox_add.py", "category": "unknown", "repo_id": "ArchiveBox/ArchiveBox"} {"input": "# ---\n# title: Simple web scraper\n# description: Learn how to scrape article content from web pages with Prefect tasks, retries, and automatic logging.\n# icon: globe\n# dependencies: [\"prefect\", \"requests\", \"beautifulsoup4\"]\n# keywords: [\"getting_started\", \"webscraping\", \"tasks\", \"retries\"]\n# draft: false\n# order: 5\n# ---\n#\n# This example shows how Prefect enhances regular Python code without getting in its way.\n# You'll write code exactly as you normally would, and Prefect's decorators add production-ready\n# features with zero boilerplate.\n#\n# In this example you will:\n# 1. Write regular Python functions for web scraping\n# 2. Add production features ([retries](https://docs.prefect.io/v3/develop/write-tasks#retries), [logging](https://docs.prefect.io/v3/develop/logging#configure-logging)) with just two decorators:\n# - `@task` - Turn any function into a [retryable, observable unit](https://docs.prefect.io/v3/develop/write-tasks#write-and-run-tasks)\n# - `@flow` - Compose tasks into a [re", "label": 1, "sample_id": "PrefectHQ/prefect:examples/simple_web_scraper.py", "category": "function_complex", "repo_id": "PrefectHQ/prefect"} {"input": "\"\"\"Middleware to fix dangling tool calls in message history.\n\nA dangling tool call occurs when an AIMessage contains tool_calls but there are\nno corresponding ToolMessages in the history (e.g., due to user interruption or\nrequest cancellation). This causes LLM errors due to incomplete message format.\n\nThis middleware intercepts the model call to detect and patch such gaps by\ninserting synthetic ToolMessages with an error indicator immediately after the\nAIMessage that made the tool calls, ensuring correct message ordering.\n\nNote: Uses wrap_model_call instead of before_model to ensure patches are inserted\nat the correct positions (immediately after each dangling AIMessage), not appended\nto the end of the message list as before_model + add_messages reducer would do.\n\"\"\"\n\nimport logging\nfrom collections.abc import Awaitable, Callable\nfrom typing import override\n\nfrom langchain.agents import AgentState\nfrom langchain.agents.middleware import AgentMiddleware\nfrom langchain.agents.middleware.types import ModelCallResult, ModelRequest, ModelResponse\nfrom langchain_core.messages import ToolMessage\n\nlogger = logging.getLogger(__name__)\n\n\nclass DanglingToolCallMiddleware(AgentMiddleware[AgentState]):\n \"\"\"Inserts placeholder ToolMessages for dangling tool calls before model invocation.\n\n Scans the message history for AIM", "label": 1, "sample_id": "bytedance/deer-flow:backend/src/agents/middlewares/dangling_tool_call_middleware.py", "category": "function_complex", "repo_id": "bytedance/deer-flow"} {"input": "from collections.abc import Callable\n\nimport numpy as np\n\n\ndef weierstrass_method(\n polynomial: Callable[[np.ndarray], np.ndarray],\n degree: int,\n roots: np.ndarray | None = None,\n max_iter: int = 100,\n) -> np.ndarray:\n \"\"\"\n Approximates all complex roots of a polynomial using the\n Weierstrass (Durand-Kerner) method.\n Args:\n polynomial: A function that takes a NumPy array of complex numbers and returns\n the polynomial values at those points.\n degree: Degree of the polynomial (number of roots to find). Must be ≥ 1.\n roots: Optional initial guess as a NumPy array of complex numbers.\n Must have length equal to 'degree'.\n If None, perturbed complex roots of unity are used.\n max_iter: Number of iterations to perform (default: 100).\n\n Returns:\n np.ndarray: Array of approximated complex roots.\n\n Raises:\n ValueError: If degree < 1, or if initial roots length doesn't match the degree.\n\n Note:\n - Root updates are clipped to prevent numerical overflow.\n\n Example:\n >>> import numpy as np\n >>> def check", "label": 1, "sample_id": "TheAlgorithms/Python:maths/numerical_analysis/weierstrass_method.py", "category": "documentation", "repo_id": "TheAlgorithms/Python"} {"input": "from unittest.mock import Mock, patch\n\nfrom crewai_tools.tools.brightdata_tool.brightdata_unlocker import (\n BrightDataWebUnlockerTool,\n)\nimport requests\n\n\n@patch.dict(\n \"os.environ\",\n {\"BRIGHT_DATA_API_KEY\": \"test_api_key\", \"BRIGHT_DATA_ZONE\": \"test_zone\"},\n)\n@patch(\"crewai_tools.tools.brightdata_tool.brightdata_unlocker.requests.post\")\ndef test_run_success_html(mock_post):\n mock_response = Mock()\n mock_response.status_code = 200\n mock_response.text = \"Test\"\n mock_response.raise_for_status = Mock()\n mock_post.return_value = mock_response\n\n tool = BrightDataWebUnlockerTool()\n tool._run(url=\"https://example.com\", format=\"html\", save_file=False)\n\n\n@patch.dict(\n \"os.environ\",\n {\"BRIGHT_DATA_API_KEY\": \"test_api_key\", \"BRIGHT_DATA_ZONE\": \"test_zone\"},\n)\n@patch(\"crewai_tools.tools.brightdata_tool.brightdata_unlocker.requests.post\")\ndef test_run_success_json(mock_post):\n mock_response = Mock()\n mock_response.status_code = 200\n mock_response", "label": 1, "sample_id": "crewAIInc/crewAI:lib/crewai-tools/tests/tools/brightdata_webunlocker_tool_test.py", "category": "test", "repo_id": "crewAIInc/crewAI"} {"input": "\"\"\"Python entrypoint of compilation.\"\"\"\n\nimport dataclasses\nfrom io import StringIO\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, List, Optional, Tuple\n\nfrom tvm import IRModule, relax, tir\nfrom tvm.ir.transform import Pass, PassContext\nfrom tvm.relax.frontend import nn\nfrom tvm.target import Target\n\nfrom mlc_llm import compiler_pass as _\nfrom mlc_llm import op as op_ext\nfrom mlc_llm.cli.model_metadata import _report_memory_usage\nfrom mlc_llm.model import Model\nfrom mlc_llm.quantization import Quantization\nfrom mlc_llm.support import logging\nfrom mlc_llm.support.config import ConfigBase\nfrom mlc_llm.support.style import bold\n\nfrom .compiler_flags import ModelConfigOverride, OptimizationFlags\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclasses.dataclass\nclass CompileArgs: # pylint: disable=too-many-instance-attributes\n \"\"\"Arguments to MLC LLM's compiler.\"\"\"\n\n config: Path\n quantization: Quantization\n model: Model\n target: Target\n opt: OptimizationFlags\n build_func: Callable[[IRModule, \"CompileArgs\", Pass], None", "label": 0, "sample_id": "mlc-ai/mlc-llm:python/mlc_llm/interface/compile.py", "category": "unknown", "repo_id": "mlc-ai/mlc-llm"} {"input": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport asyncio\nimport logging\nimport os\n\nimport aiohttp\nimport numpy as np\nimport ray\nimport torch\nfrom omegaconf import DictConfig, open_dict\nfrom tensordict import TensorDict\n\nfrom verl.protocol import DataProto\nfrom verl.single_controller.ray.base import RayResourcePool\nfrom verl.trainer.ppo.reward import load_reward_manager\nfrom verl.utils import hf_tokenizer\nfrom verl.utils.fs import copy_to_local\n\nfrom .reward_model import RewardModelManager\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(os.getenv(\"VERL_LOG", "label": 0, "sample_id": "verl-project/verl:verl/experimental/reward_loop/reward_loop.py", "category": "unknown", "repo_id": "verl-project/verl"} {"input": "from typing import Any\n\nfrom pydantic import BaseModel\n\nfrom crewai_tools.tools.brave_search_tool.base import BraveSearchToolBase\nfrom crewai_tools.tools.brave_search_tool.schemas import (\n WebSearchHeaders,\n WebSearchParams,\n)\n\n\nclass BraveWebSearchTool(BraveSearchToolBase):\n \"\"\"A tool that performs web searches using the Brave Search API.\"\"\"\n\n name: str = \"Brave Web Search\"\n args_schema: type[BaseModel] = WebSearchParams\n header_schema: type[BaseModel] = WebSearchHeaders\n\n description: str = (\n \"A tool that performs web searches using the Brave Search API. \"\n \"Results are returned as structured JSON data.\"\n )\n\n search_url: str = \"https://api.search.brave.com/res/v1/web/search\"\n\n def _refine_request_payload(self, params: dict[str, Any]) -> dict[str, Any]:\n return params\n\n def _refine_response(self, response: dict[str, Any]) -> list[dict[str, Any]]:\n results = response.get(\"web\", {}).get(\"results\", [])\n refined = []\n for result in results:\n snippets = result.get(\"extra_snippets\") or []\n if not", "label": 0, "sample_id": "crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/brave_search_tool/brave_web_tool.py", "category": "unknown", "repo_id": "crewAIInc/crewAI"} {"input": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\n\nimport frappe\nfrom frappe import _\nfrom frappe.utils import flt\nfrom pypika.terms import Bracket, LiteralValue\n\nimport erpnext\nfrom erpnext.accounts.report.item_wise_sales_register.item_wise_sales_register import (\n\tadd_sub_total_row,\n\tadd_total_row,\n\tapply_order_by_conditions,\n\tget_grand_total,\n\tget_group_by_and_display_fields,\n\tget_tax_accounts,\n)\nfrom erpnext.accounts.report.utils import get_values_for_columns\n\n\ndef execute(filters=None):\n\treturn _execute(filters)\n\n\ndef _execute(filters=None, additional_table_columns=None):\n\tif not filters:\n\t\tfilters = {}\n\tcolumns = get_columns(additional_table_columns, filters)\n\n\tcompany_currency = erpnext.get_company_currency(filters.company)\n\n\titem_list = get_items(filters, additional_table_columns)\n\taii_account_map = get_aii_accounts()\n\tdefault_taxes = {}\n\tif item_list:\n\t\titemised_tax, tax_columns = get_tax_accounts(\n\t\t\titem_list,\n\t\t\tcolumns,\n\t\t\tcompany_currency,\n\t\t\tdoctype=\"Purchase Invoice\",\n\t\t\ttax_doctype=\"", "label": 0, "sample_id": "frappe/erpnext:erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py", "category": "unknown", "repo_id": "frappe/erpnext"} {"input": "import json\nimport logging\nimport uuid\nfrom typing import Optional, List\nfrom datetime import datetime, date\nfrom databricks.sdk.service.catalog import ColumnInfo, ColumnTypeName, TableType, DataSourceFormat\nfrom databricks.sdk.service.catalog import TableConstraint, PrimaryKeyConstraint\nfrom databricks.sdk import WorkspaceClient\nfrom databricks.sdk.service.vectorsearch import (\n VectorIndexType,\n DeltaSyncVectorIndexSpecRequest,\n DirectAccessVectorIndexSpec,\n EmbeddingSourceColumn,\n EmbeddingVectorColumn,\n)\nfrom pydantic import BaseModel\nfrom mem0.memory.utils import extract_json\nfrom mem0.vector_stores.base import VectorStoreBase\n\nlogger = logging.getLogger(__name__)\n\n\nclass MemoryResult(BaseModel):\n id: Optional[str] = None\n score: Optional[float] = None\n payload: Optional[dict] = None\n\n\nexcluded_keys = {\"user_id\", \"agent_id\", \"run_id\", \"hash\", \"data\", \"created_at\", \"updated_at\"}\n\n\nclass Databricks(VectorStoreBase):\n def __init__(\n self,\n workspace_url: str,\n access_token: Optional[str] = None,\n client_id: Optional[str] = None,\n client_secret: Optional[str] =", "label": 1, "sample_id": "mem0ai/mem0:mem0/vector_stores/databricks.py", "category": "function_complex", "repo_id": "mem0ai/mem0"} {"input": "# Copyright The Lightning AI team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\nfrom argparse import Namespace\nfrom unittest.mock import MagicMock\n\nimport pytest\nimport torch\n\nfrom lightning.pytorch import Trainer\nfrom lightning.pytorch.demos.boring_classes import BoringModel\nfrom lightning.pytorch.loggers.litlogger import LitLogger\n\n\ndef test_litlogger_init(litlogger_mock, tmp_path):\n \"\"\"Test LitLogger initialization.\"\"\"\n logger = LitLogger(\n name=\"test-experiment\",\n root_dir=tmp_path,\n teamspace=\"test-teamspace\",\n metadata={\"key\": \"value\"},\n )\n\n assert logger.name == \"test-experiment\"\n assert logger.root_dir == str", "label": 1, "sample_id": "Lightning-AI/pytorch-lightning:tests/tests_pytorch/loggers/test_litlogger.py", "category": "test", "repo_id": "Lightning-AI/pytorch-lightning"} {"input": "\"\"\"SamplingTool for use during LLM sampling requests.\"\"\"\n\nfrom __future__ import annotations\n\nimport inspect\nfrom collections.abc import Callable\nfrom typing import Any\n\nfrom mcp.types import TextContent\nfrom mcp.types import Tool as SDKTool\nfrom pydantic import ConfigDict\n\nfrom fastmcp.tools.function_parsing import ParsedFunction\nfrom fastmcp.tools.function_tool import FunctionTool\nfrom fastmcp.tools.tool import ToolResult\nfrom fastmcp.tools.tool_transform import TransformedTool\nfrom fastmcp.utilities.types import FastMCPBaseModel\n\n\nclass SamplingTool(FastMCPBaseModel):\n \"\"\"A tool that can be used during LLM sampling.\n\n SamplingTools bundle a tool's schema (name, description, parameters) with\n an executor function, enabling servers to execute agentic workflows where\n the LLM can request tool calls during sampling.\n\n In most cases, pass functions directly to ctx.sample():\n\n def search(query: str) -> str:\n '''Search the web.'''\n return web_search(query)\n\n result = await context.sample(\n messages=\"Find info about Python\",\n tools=[search], # Plain functions work directly\n )\n\n Create a SamplingTool explicitly when you need custom", "label": 1, "sample_id": "PrefectHQ/fastmcp:src/fastmcp/server/sampling/sampling_tool.py", "category": "function_complex", "repo_id": "PrefectHQ/fastmcp"} {"input": "from strix.telemetry.utils import prune_otel_span_attributes\n\n\ndef test_prune_otel_span_attributes_drops_high_volume_prompt_content() -> None:\n attributes = {\n \"gen_ai.operation.name\": \"openai.chat\",\n \"gen_ai.request.model\": \"gpt-5.2\",\n \"gen_ai.prompt.0.role\": \"system\",\n \"gen_ai.prompt.0.content\": \"a\" * 20_000,\n \"gen_ai.completion.0.content\": \"b\" * 10_000,\n \"llm.input_messages.0.content\": \"c\" * 5_000,\n \"llm.output_messages.0.content\": \"d\" * 5_000,\n \"llm.input\": \"x\" * 3_000,\n \"llm.output\": \"y\" * 3_000,\n }\n\n pruned = prune_otel_span_attributes(attributes)\n\n assert \"gen_ai.prompt.0.content\" not in pruned\n assert \"gen_ai.completion.0.content\" not in pruned\n assert \"llm.input_messages.0.content\" not in pruned\n assert \"", "label": 0, "sample_id": "usestrix/strix:tests/telemetry/test_utils.py", "category": "unknown", "repo_id": "usestrix/strix"} {"input": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\n\nclass RasterBandTransform(Transform):\n def as_sql(self, compiler, connection):\n return compiler.compile(self.lhs)\n\n\nclass GISLookup(Lookup):\n sql_template = None\n transform_func = None\n distance = False\n band_rhs = None\n band_lhs = None\n\n def __init__(self, lhs, rhs):\n rhs, *self.rhs_params = rhs if isinstance(rhs, (list, tuple)) else (rhs,)\n super().__init__(lhs, rhs)\n self.template_params = {}\n self.process_rhs_params()\n\n def process_rhs_params(self):\n if self.rhs_params:\n # Check if a band index was passed in the query argument.\n if len(self.rhs_params) == (2 if self.lookup_name == \"relate\" else 1):\n self.process_band_indices()\n elif len(self.rhs_params) > 1:\n raise ValueError(\"Tuple too long for lookup", "label": 0, "sample_id": "django/django:django/contrib/gis/db/models/lookups.py", "category": "unknown", "repo_id": "django/django"} {"input": "from __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING, Any, cast\nfrom urllib.parse import urljoin, urlparse\n\nfrom w3lib.url import safe_url_string\n\nfrom scrapy import signals\nfrom scrapy.exceptions import IgnoreRequest, NotConfigured\nfrom scrapy.http import HtmlResponse, Response\nfrom scrapy.spidermiddlewares.referer import RefererMiddleware\nfrom scrapy.utils.decorators import _warn_spider_arg\nfrom scrapy.utils.httpobj import urlparse_cached\nfrom scrapy.utils.python import global_object_name\nfrom scrapy.utils.response import get_meta_refresh\n\nif TYPE_CHECKING:\n # typing.Self requires Python 3.11\n from typing_extensions import Self\n\n from scrapy import Request, Spider\n from scrapy.crawler import Crawler\n from scrapy.settings import BaseSettings\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseRedirectMiddleware:\n crawler: Crawler\n enabled_setting: str = \"REDIRECT_ENABLED\"\n\n def __init__(self, settings: BaseSettings):\n if not settings.getbool(self.enabled_setting):\n raise NotConfigured\n\n self.max_redirect_times: int = settings.getint(\"REDIRECT_MAX_TIMES\")\n self.priority_adjust: int = settings.getint(\"REDIRECT_PRIORITY_ADJUST", "label": 0, "sample_id": "scrapy/scrapy:scrapy/downloadermiddlewares/redirect.py", "category": "unknown", "repo_id": "scrapy/scrapy"} {"input": "import asyncio\nimport copy\nfrom collections import defaultdict\nfrom logging import INFO\nfrom typing import Any, Dict, Optional, Set, Tuple, Callable, cast\n\nimport utils.constants as constants\nfrom utils.channel import sort_channel_result, generate_channel_statistic, write_channel_to_file, retain_origin\nfrom utils.config import config\nfrom utils.tools import get_logger\n\n\nclass ResultAggregator:\n \"\"\"\n Aggregates test results and periodically writes sorted views to files.\n \"\"\"\n\n def __init__(\n self,\n base_data: Dict[str, Dict[str, Any]],\n first_channel_name: Optional[str] = None,\n ipv6_support: bool = True,\n write_interval: float = 5.0,\n min_items_before_flush: int = config.urls_limit,\n flush_debounce: Optional[float] = None,\n sort_logger=None,\n stat_logger=None,\n result: Optional[Dict[str, Dict[str, list]]] = None,\n ):\n self.base_data = base_data\n self.result = sort_channel_result(\n base_data,\n result=result,\n ipv6_support=ipv6_support\n )\n self.test_results: Dict[str, Dict[str, list]] = defaultdict(lambda: defaultdict(list))\n self", "label": 1, "sample_id": "Guovin/iptv-api:utils/aggregator.py", "category": "function_complex", "repo_id": "Guovin/iptv-api"} {"input": "import os\n\nimport torch\nfrom datasets import load_dataset\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom transformers import AutoModelForSeq2SeqLM, AutoTokenizer, default_data_collator, get_linear_schedule_with_warmup\n\nfrom peft import AdaLoraConfig, PeftConfig, PeftModel, TaskType, get_peft_model\n\n\nos.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\ndevice = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\nmodel_name_or_path = \"facebook/bart-base\"\ntokenizer_name_or_path = \"facebook/bart-base\"\n\ntext_column = \"text\"\nlabel_column = \"text_label\"\nmax_length = 128\nlr = 1e-3\nnum_epochs = 8\nbatch_size = 8\n\n\n# loading dataset\ndataset = load_dataset(\"zeroshot/twitter-financial-news-sentiment\")\ndataset = dataset[\"train\"].train_test_split(test_size=0.1)\ndataset[\"validation\"] = dataset[\"test\"]\ndel dataset[\"test\"]\n\nif hasattr(dataset[\"train\"].features[\"label\"], \"names\"):\n classes = dataset[\"train\"].features[\"label\"].names\nelse:\n classes = [\"", "label": 0, "sample_id": "huggingface/peft:examples/conditional_generation/peft_adalora_seq2seq.py", "category": "unknown", "repo_id": "huggingface/peft"} {"input": "\"\"\"Shared transfer utilities used by both typer and cyclopts CLI implementations.\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport uuid\nfrom typing import TYPE_CHECKING, Any, Callable, Sequence\n\nfrom rich.console import Console\nfrom rich.progress import (\n BarColumn,\n Progress,\n TaskProgressColumn,\n TextColumn,\n)\n\nif TYPE_CHECKING:\n from prefect.cli.transfer._migratable_resources import MigratableProtocol\n\n\nasync def collect_resources(client: Any) -> Sequence[\"MigratableProtocol\"]:\n \"\"\"Collect all resources from the source profile.\"\"\"\n from prefect.cli.transfer._migratable_resources import construct_migratable_resource\n\n collections = await asyncio.gather(\n client.read_work_pools(),\n client.read_work_queues(),\n client.read_deployments(),\n client.read_block_documents(),\n client.read_variables(),\n client.read_global_concurrency_limits(),\n client.read_automations(),\n )\n\n resources = await asyncio.gather(\n *[\n construct_migratable_resource(item)\n for collection in collections\n for item in collection\n ]\n )\n\n return resources\n\n\nasync def find_root_resources(\n resources: Sequence[\"MigratableProtocol\"],\n) -> Sequence[\"MigratableProtocol\"]:\n \"\"\"Find", "label": 1, "sample_id": "PrefectHQ/prefect:src/prefect/cli/_transfer_utils.py", "category": "function_complex", "repo_id": "PrefectHQ/prefect"} {"input": "# type: ignore\nimport argparse\nimport asyncio\nimport sys\nimport termios\nimport time\nimport tty\n\nimport aiohttp\n\nNUM_REQUESTS = 10\nBASE_URL = \"\"\n\nQUESTIONS = [\n \"What is the capital of Australia?\",\n \"How many bones are in the human body?\",\n \"What year did World War II end?\",\n \"What is the speed of light in meters per second?\",\n \"Who wrote Romeo and Juliet?\",\n \"What is the chemical formula for water?\",\n \"How many planets are in our solar system?\",\n \"What is the largest ocean on Earth?\",\n \"Who painted the Mona Lisa?\",\n \"What is the boiling point of water in Celsius?\",\n]\n\n\ndef write(s: str) -> None:\n sys.stdout.write(s)\n\n\n# ---------------------------------------------------------------------------\n# Model picker (same style as exo_eval)\n# ---------------------------------------------------------------------------\n\n\ndef fetch_models() -> list[str]:\n import json\n import urllib.request\n\n with urllib.request.urlopen(f\"{BASE_URL}/state\") as resp:\n data = json.loads(resp.read())\n model_ids: set[str] = set()\n for instance in data.get(\"instances\", {}).values():\n for variant in instance.values():\n sa = variant.get(\"shard", "label": 0, "sample_id": "exo-explore/exo:bench/parallel_requests.py", "category": "unknown", "repo_id": "exo-explore/exo"} {"input": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom lfx.log import logger\nfrom sqlalchemy.exc import IntegrityError, SQLAlchemyError\nfrom sqlmodel import col, delete, func, select\n\nif TYPE_CHECKING:\n from uuid import UUID\n\n from sqlmodel.ext.asyncio.session import AsyncSession\n\nfrom langflow.services.database.models.flow_version.exceptions import (\n FlowVersionConflictError,\n FlowVersionNotFoundError,\n)\nfrom langflow.services.database.models.flow_version.model import (\n FlowVersion,\n)\nfrom langflow.services.deps import get_settings_service\n\nMAX_VERSION_RETRIES = 3\n\n\nasync def get_next_version_number(session: AsyncSession, flow_id: UUID) -> int:\n result = await session.exec(select(func.max(FlowVersion.version_number)).where(FlowVersion.flow_id == flow_id))\n current_max = result.one()\n return (current_max or 0) + 1\n\n\nasync def create_flow_version_entry(\n session: AsyncSession,\n flow_id: UUID,\n user_id: UUID,\n data: dict | None,\n description: str | None = None,\n) -> FlowVersion:\n \"\"\"Create a version entry with retry on version number collision.\n\n NOTE: This function does NOT verify that", "label": 0, "sample_id": "langflow-ai/langflow:src/backend/base/langflow/services/database/models/flow_version/crud.py", "category": "unknown", "repo_id": "langflow-ai/langflow"} {"input": "# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis script demonstrates the use of `LeRobotDataset` class for handling and processing robotic datasets from Hugging Face.\nIt illustrates how to load datasets, manipulate them, and apply transformations suitable for machine learning tasks in PyTorch.\n\nFeatures included in this script:\n- Viewing a dataset's metadata and exploring its properties.\n- Loading an existing dataset from the hub or a subset of it.\n- Accessing frames by episode number.\n- Using advanced dataset features like timestamp-based frame selection.\n- Demonstrating compatibility with PyTorch DataLoader for batch processing.\n\nThe script ends with examples of how", "label": 0, "sample_id": "huggingface/lerobot:examples/dataset/load_lerobot_dataset.py", "category": "unknown", "repo_id": "huggingface/lerobot"} {"input": "import logging\nimport os\nfrom optparse import Values\n\nfrom pipenv.patched.pip._internal.cli import cmdoptions\nfrom pipenv.patched.pip._internal.cli.cmdoptions import make_target_python\nfrom pipenv.patched.pip._internal.cli.req_command import RequirementCommand, with_cleanup\nfrom pipenv.patched.pip._internal.cli.status_codes import SUCCESS\nfrom pipenv.patched.pip._internal.operations.build.build_tracker import get_build_tracker\nfrom pipenv.patched.pip._internal.utils.misc import ensure_dir, normalize_path, write_output\nfrom pipenv.patched.pip._internal.utils.temp_dir import TempDirectory\n\nlogger = logging.getLogger(__name__)\n\n\nclass DownloadCommand(RequirementCommand):\n \"\"\"\n Download packages from:\n\n - PyPI (and other indexes) using requirement specifiers.\n - VCS project urls.\n - Local project directories.\n - Local or remote source archives.\n\n pip also supports downloading from \"requirements files\", which provide\n an easy way to specify a whole environment to be downloaded.\n \"\"\"\n\n usage = \"\"\"\n %prog [options] [package-index-options] ...\n %prog [options] -r [package-index-options] ...\n ", "label": 0, "sample_id": "pypa/pipenv:pipenv/patched/pip/_internal/commands/download.py", "category": "unknown", "repo_id": "pypa/pipenv"} {"input": "#!/usr/bin/env python3\r\n\"\"\"Original Trainer \"\"\"\r\nfrom __future__ import annotations\r\n\r\nimport logging\r\nimport typing as T\r\n\r\nfrom keras import ops\r\nfrom keras.src.tree import flatten\r\nimport torch\r\n\r\nfrom lib.utils import get_module_objects\r\nfrom ._base import TrainerBase\r\n\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nclass Trainer(TrainerBase):\r\n \"\"\"Original trainer\"\"\"\r\n\r\n def _forward(self,\r\n inputs: torch.Tensor,\r\n targets: list[torch.Tensor]) -> torch.Tensor:\r\n \"\"\"Perform the forward pass on the model\r\n\r\n Parameters\r\n ----------\r\n inputs\r\n The batch of input image tensors to the model in shape `(side, batch_size,\r\n *dims)` with `side` 0 being input A and `side` 1 being input B\r\n targets\r\n The corresponding batch of target images for the model for each side's output(s). For\r\n each model output an array should exist in the order of model outputs in the format `(\r\n side, batch_size, *dims)` with `side` 0 being input A and `side` 1 being input B\r\n\r\n Returns\r\n -------\r\n The loss for each side of this batch in layout (A1, ..., An, B1,", "label": 0, "sample_id": "deepfakes/faceswap:plugins/train/trainer/original.py", "category": "unknown", "repo_id": "deepfakes/faceswap"} {"input": "#!/usr/bin/env python3\n\n__package__ = 'archivebox.cli'\n\nfrom typing import Optional\n\nimport rich_click as click\n\nfrom archivebox.misc.util import docstring, enforce_types\n\n\n# State Machine ASCII Art Diagrams\nCRAWL_MACHINE_DIAGRAM = \"\"\"\n┌─────────────────────────────────────────────────────────────────────────────┐\n│ CrawlMachine │\n├─────────────────────────────────────────────────────────────────────────────┤\n│ │\n│ ┌─────────────┐ │\n│ │ QUEUED │◄────────────────┐ │\n│ │ (initial) │ │ │\n│ └──────┬──────┘ │ │\n│ │ │ tick() unless can_start() │\n│ │ tick() when │ │\n│ │ can_start() │ │\n│ ▼ │ │\n│ ┌─────────────┐ │ │\n│ │ STARTED │─────────────────┘ │\n│ │ │◄────────────────┐ │\n│ │ enter: │ │ │\n│ │ crawl.run()│ ", "label": 0, "sample_id": "ArchiveBox/ArchiveBox:archivebox/cli/archivebox_pluginmap.py", "category": "unknown", "repo_id": "ArchiveBox/ArchiveBox"} {"input": "from __future__ import annotations\r\n\r\nfrom abc import ABC, abstractmethod\r\nfrom datetime import datetime\r\nimport json\r\nimport logging\r\nimport os\r\nimport threading\r\nimport time\r\nfrom typing import Any, ClassVar\r\n\r\nfrom crewai.tools import BaseTool, EnvVar\r\nfrom pydantic import BaseModel, Field\r\nimport requests\r\n\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n# Brave API error codes that indicate non-retryable quota/usage exhaustion.\r\n_QUOTA_CODES = frozenset({\"QUOTA_LIMITED\", \"USAGE_LIMIT_EXCEEDED\"})\r\n\r\n\r\ndef _save_results_to_file(content: str) -> None:\r\n \"\"\"Saves the search results to a file.\"\"\"\r\n filename = f\"search_results_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.txt\"\r\n with open(filename, \"w\") as file:\r\n file.write(content)\r\n\r\n\r\ndef _parse_error_body(resp: requests.Response) -> dict[str, Any] | None:\r\n \"\"\"Extract the structured \"error\" object from a Brave API error response.\"\"\"\r\n try:\r\n body = resp.json()\r\n error = body.get(\"error\")\r\n return error if isinstance(error, dict) else None\r\n except (ValueError, KeyError):\r\n return None\r\n\r\n\r\n", "label": 0, "sample_id": "crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/brave_search_tool/base.py", "category": "unknown", "repo_id": "crewAIInc/crewAI"} {"input": "\"\"\"Mobjects representing raster images.\"\"\"\n\nfrom __future__ import annotations\n\n__all__ = [\"AbstractImageMobject\", \"ImageMobject\", \"ImageMobjectFromCamera\"]\n\nimport pathlib\nfrom typing import TYPE_CHECKING, Any\n\nimport numpy as np\nfrom PIL import Image\nfrom PIL.Image import Resampling\n\nfrom manim.mobject.geometry.shape_matchers import SurroundingRectangle\n\nfrom ... import config\nfrom ...camera.moving_camera import MovingCamera\nfrom ...constants import *\nfrom ...mobject.mobject import Mobject\nfrom ...utils.bezier import interpolate\nfrom ...utils.color import (\n WHITE,\n YELLOW_C,\n ManimColor,\n ParsableManimColor,\n color_to_int_rgb,\n)\nfrom ...utils.images import change_to_rgba_array, get_full_raster_image_path\n\n__all__ = [\"ImageMobject\", \"ImageMobjectFromCamera\"]\n\nif TYPE_CHECKING:\n from typing import Self\n\n import numpy.typing as npt\n\n from manim.typing import PixelArray, StrPath\n\n from ...camera.moving_camera import MovingCamera\n\n\nclass AbstractImageMobject(Mobject):\n \"\"\"\n Automatically filters out black pixels\n\n Parameters\n ----------\n scale_to_resolution\n At this", "label": 0, "sample_id": "ManimCommunity/manim:manim/mobject/types/image_mobject.py", "category": "unknown", "repo_id": "ManimCommunity/manim"} {"input": "\"\"\"\nWord Squares\n\nGiven a set of words (without duplicates), find all word squares that can be\nbuilt from them. A word square reads the same horizontally and vertically.\n\nReference: https://leetcode.com/problems/word-squares/\n\nComplexity:\n Time: O(n * 26^L) where n is the number of words, L is word length\n Space: O(n * L) for the prefix map\n\"\"\"\n\nfrom __future__ import annotations\n\nimport collections\n\n\ndef word_squares(words: list[str]) -> list[list[str]]:\n \"\"\"Find all valid word squares from a list of same-length words.\n\n Args:\n words: A list of words, all having the same length.\n\n Returns:\n A list of word squares, where each square is a list of words.\n\n Examples:\n >>> word_squares([\"area\", \"lead\", \"wall\", \"lady\", \"ball\"])\n [['wall', 'area', 'lead', 'lady'], ['ball', 'area', 'lead', 'lady']]\n \"\"\"\n word_length = len(words[0])\n prefix_map: dict[str, list[str]] = collections.defaultdict(list)\n for word in words:\n for index in range(word", "label": 1, "sample_id": "keon/algorithms:algorithms/string/word_squares.py", "category": "documentation", "repo_id": "keon/algorithms"} {"input": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2025 Meituan Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nNote that we don't combine the main with ray_trainer as ray_trainer is used by other main.\n\"\"\"\n\nimport asyncio\nimport os\nimport socket\n\nimport hydra\nimport ray\n\nfrom verl.experimental.one_step_off_policy.ray_trainer import OneStepOffRayTrainer\nfrom verl.experimental.separation.utils import create_resource_pool_manager, create_role_worker_mapping\nfrom verl.trainer.main_ppo import create_rl_dataset, create_rl_sampler\nfrom verl.trainer.ppo", "label": 0, "sample_id": "verl-project/verl:verl/experimental/one_step_off_policy/main_ppo.py", "category": "unknown", "repo_id": "verl-project/verl"} {"input": "\"\"\"Analyze git diffs to determine which directories need to be tested.\n\nIntelligently determines which LangChain packages and directories need to be tested,\nlinted, or built based on the changes. Handles dependency relationships between\npackages, maps file changes to appropriate CI job configurations, and outputs JSON\nconfigurations for GitHub Actions.\n\n- Maps changed files to affected package directories (libs/core, libs/partners/*, etc.)\n- Builds dependency graph to include dependent packages when core components change\n- Generates test matrix configurations with appropriate Python versions\n- Handles special cases for Pydantic version testing and performance benchmarks\n\nUsed as part of the check_diffs workflow.\n\"\"\"\n\nimport glob\nimport json\nimport os\nimport sys\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Dict, List, Set\n\nimport tomllib\nfrom get_min_versions import get_min_version_from_toml\nfrom packaging.requirements import Requirement\n\nLANGCHAIN_DIRS = [\n \"libs/core\",\n \"libs/text-splitters\",\n \"libs/langchain\",\n \"libs/langchain_v1\",\n \"libs/model-profiles\",\n]\n\n# When set to True, we are ignoring core dependents\n# in order to be able to get CI to pass for each individual\n#", "label": 0, "sample_id": "langchain-ai/langchain:.github/scripts/check_diff.py", "category": "unknown", "repo_id": "langchain-ai/langchain"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pytest\nfrom playwright.sync_api import Locator, Page, expect\n\nfrom e2e_playwright.conftest import ImageCompareFunction\nfrom e2e_playwright.shared.app_utils import (\n check_top_level_class,\n click_button,\n expect_font,\n reset_hovering,\n)\nfrom e2e_playwright.shared.dataframe_utils import (\n click_on_cell,\n expect_canvas_to_be_stable,\n expect_canvas_to_be_visible,\n get_open_cell_overlay,\n open_column_menu", "label": 0, "sample_id": "streamlit/streamlit:e2e_playwright/st_dataframe_config_test.py", "category": "unknown", "repo_id": "streamlit/streamlit"} {"input": "import argparse\nimport os\nimport re\nimport subprocess\nimport tempfile\nimport xml.etree.ElementTree as ET\nfrom os import makedirs, replace\nfrom os.path import abspath, basename, exists, expanduser, join, splitext\nfrom shutil import which\nimport sys\nfrom typing import Sequence, cast\nfrom zipfile import ZipFile\n\nfrom pdf2image import convert_from_path, pdfinfo_from_path\n\nTWIPS_PER_INCH: int = 1440\n\n\ndef ensure_system_tools() -> None:\n missing: list[str] = []\n for tool in (\"soffice\", \"pdftoppm\"):\n if which(tool) is None:\n missing.append(tool)\n if missing:\n tools = \", \".join(missing)\n raise RuntimeError(\n f\"Missing required system tool(s): {tools}. Install LibreOffice and Poppler, then retry.\"\n )\n\n\ndef calc_dpi_via_ooxml_docx(input_path: str, max_w_px: int, max_h_px: int) -> int:\n \"\"\"Calculate DPI from OOXML `word/document.xml` page size (w:pgSz in twips).\n\n DOCX stores page dimensions in section properties as twips (1/144", "label": 1, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/document-processing/doc/scripts/render_docx.py", "category": "function_complex", "repo_id": "davila7/claude-code-templates"} {"input": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2026\n# Leandro Toledo de Souza \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program. If not, see [http://www.gnu.org/licenses/].\n\"\"\"This module contains an object that represents a Telegram ChatPermission.\"\"\"\n\nfrom typing import TYPE_CHECKING\n\nfrom telegram._telegramobject import TelegramObject\nfrom telegram._utils.types import JSONDict\n\nif TYPE_CHECKING:\n from telegram import Bot\n\n\nclass ChatPermissions(TelegramObject):\n \"\"\"Des", "label": 0, "sample_id": "python-telegram-bot/python-telegram-bot:src/telegram/_chatpermissions.py", "category": "unknown", "repo_id": "python-telegram-bot/python-telegram-bot"} {"input": "from __future__ import annotations\n\nfrom collections import defaultdict\nfrom collections.abc import Iterable\nfrom copy import copy\nfrom functools import lru_cache, partial\nfrom typing import TYPE_CHECKING, Any\n\nfrom pydantic_core import CoreSchema, PydanticCustomError, ValidationError, to_jsonable_python\nfrom pydantic_core import core_schema as cs\n\nfrom ._fields import PydanticMetadata\nfrom ._import_utils import import_cached_field_info\n\nif TYPE_CHECKING:\n pass\n\nSTRICT = {'strict'}\nFAIL_FAST = {'fail_fast'}\nLENGTH_CONSTRAINTS = {'min_length', 'max_length'}\nINEQUALITY = {'le', 'ge', 'lt', 'gt'}\nNUMERIC_CONSTRAINTS = {'multiple_of', *INEQUALITY}\nALLOW_INF_NAN = {'allow_inf_nan'}\n\nSTR_CONSTRAINTS = {\n *LENGTH_CONSTRAINTS,\n *STRICT,\n 'strip_whitespace',\n 'to_lower',\n 'to_upper',\n 'pattern',\n 'coerce_numbers_to_str',\n 'ascii_only',\n}\nBYTES_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}\n\nLIST_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}\nTUPLE", "label": 0, "sample_id": "pydantic/pydantic:pydantic/_internal/_known_annotated_metadata.py", "category": "unknown", "repo_id": "pydantic/pydantic"} {"input": "\"\"\"\nMessage History Hooks\n=============================\n\nAccess the current run's message history inside tool pre/post hooks\nvia run_context.messages.\n\"\"\"\n\nfrom agno.agent import Agent\nfrom agno.models.openai import OpenAIChat\nfrom agno.run.base import RunContext\nfrom agno.tools import FunctionCall, tool\n\n# ---------------------------------------------------------------------------\n# Create Agent\n# ---------------------------------------------------------------------------\n\n\ndef pre_hook(run_context: RunContext, fc: FunctionCall):\n msgs = run_context.messages\n count = len(msgs) if msgs else 0\n print(f\"[pre-hook] {fc.function.name} - {count} messages in run\")\n\n\ndef post_hook(run_context: RunContext, fc: FunctionCall):\n msgs = run_context.messages\n count = len(msgs) if msgs else 0\n print(\n f\"[post-hook] {fc.function.name} returned '{fc.result}' - {count} messages in run\"\n )\n\n\n@tool(pre_hook=pre_hook, post_hook=post_hook)\ndef get_weather(city: str) -> str:\n \"\"\"Get the current weather for a city.\"\"\"\n return f\"Sunny, 72F in {city}\"\n\n\nagent = Agent(\n model=OpenAIChat(id=\"gpt-4o", "label": 0, "sample_id": "agno-agi/agno:cookbook/02_agents/09_hooks/message_history_hooks.py", "category": "unknown", "repo_id": "agno-agi/agno"} {"input": "from time import perf_counter\n\nfrom textual.app import App, ComposeResult\nfrom textual.reactive import var\nfrom textual.widgets import Static\n\n\nclass AnimApp(App):\n CSS = \"\"\"\n #foo {\n height: 1;\n }\n \"\"\"\n\n def compose(self) -> ComposeResult:\n yield Static(\"foo\", id=\"foo\")\n\n\nasync def test_animate_height() -> None:\n \"\"\"Test animating styles.height works.\"\"\"\n\n # Styles.height is a scalar, which makes it more complicated to animate\n\n app = AnimApp()\n\n async with app.run_test() as pilot:\n static = app.query_one(Static)\n assert static.size.height == 1\n assert static.styles.height.value == 1\n static.styles.animate(\"height\", 100, duration=0.5, easing=\"linear\")\n start = perf_counter()\n\n # Wait for the animation to finished\n await pilot.wait_for_animation()\n elapsed = perf_counter() - start\n # Check that the full time has elapsed\n assert elapsed >= 0.5\n # Check the height reached the maximum\n assert static.styles.height.value == 100\n\n\nasync def test_scheduling_animation() -> None:\n \"\"\"", "label": 0, "sample_id": "Textualize/textual:tests/test_animation.py", "category": "unknown", "repo_id": "Textualize/textual"} {"input": "\"\"\"\nInteractive ElastomerDisplacementSensor visualization with keyboard teleop.\n\"\"\"\n\nimport argparse\nimport os\n\nimport numpy as np\n\nimport genesis as gs\nimport genesis.utils.geom as gu\nfrom genesis.recorders.plotters import IS_MATPLOTLIB_AVAILABLE\nfrom genesis.utils.misc import tensor_to_array\nfrom genesis.vis.keybindings import Key, KeyAction, Keybind\n\n# Teleop\nKEY_DPOS = 0.08\nFORCE_SCALE = 100.0\n\n# Pusher (sphere with tactile on bottom hemisphere, or box with grid sensor on bottom face)\nPUSHER_SIZE = 0.1\nPROBE_RADIUS = 0.01\nDILATE_COEFFICIENT = 1e1\nSHEAR_COEFFICIENT = 1e-2\nTWIST_COEFFICIENT = 1e-2\nHEMISPHERE_N_THETA = 4\nHEMISPHERE_N_PHI = 12\nGRID_SIZE = (6, 8) # (nx, ny) for --grid\n\n# Sandbox\nSANDBOX_SIZE = 1.2\nWALL_THICKNESS = 0.08\nWALL_HEIGHT = 0.25\n\n", "label": 0, "sample_id": "Genesis-Embodied-AI/Genesis:examples/sensors/tactile_elastomer_sandbox.py", "category": "unknown", "repo_id": "Genesis-Embodied-AI/Genesis"} {"input": "\"\"\"\nKeyboard Controls:\n↑\t- Move Forward (North)\n↓\t- Move Backward (South)\n←\t- Move Left (West)\n→\t- Move Right (East)\nn\t- Move Up\nm\t- Move Down\nj\t- Rotate Counterclockwise\nk\t- Rotate Clockwise\nu\t- Reset Scene\nspace\t- Press to close gripper, release to open gripper\nesc\t- Quit\n\nPlus all default viewer controls (press 'i' to see them)\n\"\"\"\n\nimport os\nimport random\n\nimport numpy as np\n\nimport genesis as gs\nimport genesis.utils.geom as gu\nfrom genesis.vis.keybindings import Key, KeyAction, Keybind\n\nif __name__ == \"__main__\":\n ########################## init ##########################\n gs.init(precision=\"32\", logging_level=\"info\", backend=gs.cpu)\n np.set_printoptions(precision=7, suppress=True)\n\n ########################## create a scene ##########################\n scene = gs.Scene(\n sim_options=gs.options.SimOptions(\n substeps=4,\n ),\n rigid_options=gs.options.RigidOptions(\n enable_joint_limit=True,\n enable_collision=True,\n gravity=(0, 0, -9.8),\n ", "label": 1, "sample_id": "Genesis-Embodied-AI/Genesis:examples/keyboard_teleop.py", "category": "function_simple", "repo_id": "Genesis-Embodied-AI/Genesis"} {"input": "from __future__ import annotations\n\nimport re\nimport warnings\nfrom logging import ERROR\n\nfrom testfixtures import LogCapture\nfrom w3lib.url import safe_url_string\n\nfrom scrapy.http import HtmlResponse, Request, TextResponse\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule, Spider\nfrom scrapy.utils.test import get_crawler\nfrom tests.test_spider import TestSpider\nfrom tests.utils.decorators import inline_callbacks_test\n\n\nclass TestCrawlSpider(TestSpider):\n test_body = b\"\"\"Page title\n \n

Item 12

\n \n \n \"\"\"\n spider_class = CrawlSpider\n\n def test_rule_without_link_extractor(self):\n response = HtmlResponse(\n \"http://example.org/somepage/index.html\", body=self.test_body\n )\n\n ", "label": 0, "sample_id": "scrapy/scrapy:tests/test_spider_crawl.py", "category": "unknown", "repo_id": "scrapy/scrapy"} {"input": "from typing import Literal\n\nfrom typing_extensions import TypedDict\n\nfrom zerver.actions.user_topics import do_set_user_topic_visibility_policy\nfrom zerver.lib.emoji import check_emoji_request, get_emoji_data\nfrom zerver.lib.exceptions import ReactionExistsError\nfrom zerver.lib.message import (\n access_message_and_usermessage,\n event_recipient_ids_for_action_on_messages,\n set_visibility_policy_possible,\n should_change_visibility_policy,\n visibility_policy_for_participation,\n)\nfrom zerver.lib.message_cache import update_message_cache\nfrom zerver.lib.streams import access_stream_by_id\nfrom zerver.lib.user_message import create_historical_user_messages\nfrom zerver.models import Message, Reaction, UserProfile\nfrom zerver.tornado.django_api import send_event_on_commit\n\n\nclass ReactionEventUserDict(TypedDict):\n user_id: int\n email: str\n full_name: str\n is_mirror_dummy: bool\n\n\nclass ReactionEvent(TypedDict):\n type: Literal[\"reaction\"]\n op: Literal[\"add\", \"remove\"]\n user_id: int\n user: ReactionEventUserDict\n message_id: int\n emoji_name: str\n emoji_code: str\n reaction_type: str\n\n\ndef notify_reaction", "label": 0, "sample_id": "zulip/zulip:zerver/actions/reactions.py", "category": "unknown", "repo_id": "zulip/zulip"} {"input": "#!/usr/bin/env python3\n\"\"\"\nMinimal validator for nanobot skill folders.\n\"\"\"\n\nimport re\nimport sys\nfrom pathlib import Path\nfrom typing import Optional\n\ntry:\n import yaml\nexcept ModuleNotFoundError:\n yaml = None\n\nMAX_SKILL_NAME_LENGTH = 64\nALLOWED_FRONTMATTER_KEYS = {\n \"name\",\n \"description\",\n \"metadata\",\n \"always\",\n \"license\",\n \"allowed-tools\",\n}\nALLOWED_RESOURCE_DIRS = {\"scripts\", \"references\", \"assets\"}\nPLACEHOLDER_MARKERS = (\"[todo\", \"todo:\")\n\n\ndef _extract_frontmatter(content: str) -> Optional[str]:\n lines = content.splitlines()\n if not lines or lines[0].strip() != \"---\":\n return None\n for i in range(1, len(lines)):\n if lines[i].strip() == \"---\":\n return \"\\n\".join(lines[1:i])\n return None\n\n\ndef _parse_simple_frontmatter(frontmatter_text: str) -> Optional[dict[str, str]]:\n \"\"\"Fallback parser for simple frontmatter when PyYAML is unavailable.\"\"\"\n parsed: dict[str, str] = {}\n current_key: Optional[str] = None\n multiline_key: Optional[str] =", "label": 0, "sample_id": "HKUDS/nanobot:nanobot/skills/skill-creator/scripts/quick_validate.py", "category": "unknown", "repo_id": "HKUDS/nanobot"} {"input": "import base64, ctypes, pathlib, tempfile, hashlib\nfrom tinygrad.device import Compiler\nfrom tinygrad.helpers import cpu_objdump, system, data64\nfrom tinygrad.runtime.autogen import mesa, llvm\nfrom tinygrad.runtime.support.compiler_cpu import CPULLVMCompiler, expect, cerr\n\n# NB: compilers assume mesa's glsl type cache is managed externally with mesa.glsl_type_singleton_init_or_ref() and mesa.glsl_type_singleton_decref()\n\ndef rzalloc(typ, ctx=None, **kwargs):\n s = ctypes.cast(mesa.rzalloc_size(ctypes.cast(ctx, ctypes.c_void_p), ctypes.sizeof(typ)), ctypes.POINTER(typ))\n for k,v in kwargs.items(): setattr(s.contents, k, v)\n return s\n\ndef deserialize(enc_src, opts):\n blobreader = mesa.struct_blob_reader()\n mesa.blob_reader_init(blobreader, src:=base64.b64decode(enc_src), len(src))\n return mesa.nir_deserialize(None, ctypes.cast(opts, ctypes.POINTER(mesa.nir_shader_compiler_options)), blobreader)\n\nclass LVPCompiler(CPULLVMCompiler):\n def __init__(self, cache_key=\"lvp\"): CPULLVMCompiler.__init__(self", "label": 1, "sample_id": "tinygrad/tinygrad:tinygrad/runtime/support/compiler_mesa.py", "category": "function_simple", "repo_id": "tinygrad/tinygrad"} {"input": "from manim import ORIGIN, UR, Arrow, DashedLine, DashedVMobject, VGroup\nfrom manim.mobject.geometry.tips import ArrowTip, StealthTip\n\n\ndef _collect_tips(mobject):\n return [mob for mob in mobject.get_family() if isinstance(mob, ArrowTip)]\n\n\ndef test_dashed_arrow_has_single_tip():\n dashed = DashedVMobject(Arrow(ORIGIN, 2 * UR))\n tips = _collect_tips(dashed)\n\n assert len(tips) == 1\n\n\ndef test_dashed_arrow_tip_not_duplicated_in_group_opacity():\n base_arrow = Arrow(ORIGIN, 2 * UR)\n faded_arrow = base_arrow.copy().set_fill(opacity=0.4).set_stroke(opacity=0.4)\n\n dashed_group = (\n VGroup(DashedVMobject(faded_arrow))\n .set_fill(opacity=0.4, family=True)\n .set_stroke(opacity=0.4, family=True)\n )\n\n tips = _collect_tips(dashed_group)\n\n assert len(tips) == 1\n\n\ndef test_dashed_arrow_custom_tip_shape_has_single_tip():\n dashed = DashedVMobject", "label": 1, "sample_id": "ManimCommunity/manim:tests/module/mobject/types/vectorized_mobject/test_dashed_vmobject.py", "category": "test", "repo_id": "ManimCommunity/manim"} {"input": "import operator\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import HAS_PYARROW\nfrom pandas.errors import Pandas4Warning\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n NA,\n ArrowDtype,\n Series,\n StringDtype,\n)\nimport pandas._testing as tm\nfrom pandas.core.construction import extract_array\n\n\ndef string_dtype_highest_priority(dtype1, dtype2):\n if HAS_PYARROW:\n DTYPE_HIERARCHY = [\n StringDtype(\"python\", na_value=np.nan),\n StringDtype(\"pyarrow\", na_value=np.nan),\n StringDtype(\"python\", na_value=NA),\n StringDtype(\"pyarrow\", na_value=NA),\n ]\n else:\n DTYPE_HIERARCHY = [\n StringDtype(\"python\", na_value=np.nan),\n StringDtype(\"python\", na_value=NA),\n ]\n\n h1 = DTYPE_HIERARCHY.index(dtype1)\n h2 = DTYPE_HIERARCHY.index(dtype2)\n return DTYPE_HIERARCHY[max(h1, h2)]\n\n\ndef test_eq_all_na():\n pytest", "label": 1, "sample_id": "pandas-dev/pandas:pandas/tests/arithmetic/test_string.py", "category": "test", "repo_id": "pandas-dev/pandas"} {"input": "# Copyright 2025 The JAX Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Matrix Multiplication kernel for Blackwell GPUs.\"\"\"\nimport dataclasses\nimport enum\nimport functools\nimport itertools\nimport statistics\n\nimport jax\nfrom jax import lax\nfrom jax._src import test_util as jtu # noqa: F401\nfrom jax.experimental.mosaic.gpu import profiler\nimport jax.experimental.pallas as pl\nimport jax.experimental.pallas.mosaic_gpu as plgpu\nimport jax.numpy as jnp\nimport numpy as np\n\nclass MatmulDimension(enum.IntEnum):\n M = 0\n N = 1\n\n\n@dataclasses", "label": 1, "sample_id": "jax-ml/jax:jax/experimental/pallas/ops/gpu/blackwell_matmul_mgpu.py", "category": "license", "repo_id": "jax-ml/jax"} {"input": "#!/usr/bin/env python\n\"\"\"\nScript to show-case how to offset quantization error with LoRA / LoftQ\nwhen dealing with quantizations that both quantize weights and activations.\nThis is the case for bnb int8, for example, but also other quantizations\nsuch as BitNet do this.\n\nThe math for how this works is explained in MyLinear8bitLt.forward and\ncan be seen quickly when defining W_q = W + E_W (quantized weight is the\nsum of the original weights plus an error term) and the same for\nx_q = x + e_x.\n\nTo demonstrate the effectiveness, we load a unquantized model, generate\nlogits for reference inputs and then do the same for a quantized model\nand a quantized model with LoftQ and our mitigations applied. The\nerror between reference model logits and LoftQ logits is significantly\nsmaller compared to the logits produced by the quantized model without\nmitigation.\n\nNote: set llm_int8_threshold=0 in your BitsAndBytesConfig. The thresholding\nenables dynamic fp16 quantization (for x values above that threshold).\nThe quantization error for the affected values is much lower and not\nstatic anymore, LoftQ is", "label": 0, "sample_id": "huggingface/peft:examples/loftq_finetuning/int8_correction.py", "category": "unknown", "repo_id": "huggingface/peft"} {"input": "import os\nimport re\nimport argparse\nimport sys\nimport io\nimport yaml\nfrom collections.abc import Mapping\nfrom datetime import date, datetime\nfrom _project_paths import find_repo_root\n\n\ndef configure_utf8_output() -> None:\n \"\"\"Best-effort UTF-8 stdout/stderr on Windows without dropping diagnostics.\"\"\"\n if sys.platform != \"win32\":\n return\n\n for stream_name in (\"stdout\", \"stderr\"):\n stream = getattr(sys, stream_name)\n try:\n stream.reconfigure(encoding=\"utf-8\", errors=\"backslashreplace\")\n continue\n except Exception:\n pass\n\n buffer = getattr(stream, \"buffer\", None)\n if buffer is not None:\n setattr(\n sys,\n stream_name,\n io.TextIOWrapper(buffer, encoding=\"utf-8\", errors=\"backslashreplace\"),\n )\n\nWHEN_TO_USE_PATTERNS = [\n re.compile(r\"^##\\s+When\\s+to\\s+Use\", re.MULTILINE | re.IGNORECASE),\n re.compile(r\"^##\\s+Use\\s+this\\s+skill\\s+when\", re.MULTILINE | re.IGNORECASE),\n re.compile(r\"^##\\s+When\\s+to\\s+", "label": 0, "sample_id": "sickn33/antigravity-awesome-skills:tools/scripts/validate_skills.py", "category": "unknown", "repo_id": "sickn33/antigravity-awesome-skills"} {"input": "from django.template import (\n Context,\n TemplateDoesNotExist,\n TemplateSyntaxError,\n VariableDoesNotExist,\n)\nfrom django.template.base import Token, TokenType\nfrom django.test import SimpleTestCase\nfrom django.views.debug import ExceptionReporter\n\nfrom ..utils import setup\n\npartial_templates = {\n \"partial_base.html\": (\n \"
{% block main %}Default main content.{% endblock main %}
\"\n ),\n \"partial_included.html\": (\n \"INCLUDED TEMPLATE START\\n\"\n \"{% partialdef included-partial %}\\n\"\n \"THIS IS CONTENT FROM THE INCLUDED PARTIAL\\n\"\n \"{% endpartialdef %}\\n\\n\"\n \"Now using the partial: {% partial included-partial %}\\n\"\n \"INCLUDED TEMPLATE END\\n\"\n ),\n}\n\nvalid_partialdef_names = (\n \"dot.in.name\",\n \"'space in name'\",\n \"exclamation!\",\n \"@at\",\n \"slash/something\",\n \"inline\",\n \"inline-inline\",\n \"INLINE\" \"with+plus\",\n \"with&\",\n \"with%percent\",\n \"with,comma\",\n \"with:colon\",\n \"with;semicolon\",\n \"[brackets]\",\n \"(parens)\",\n \"{", "label": 1, "sample_id": "django/django:tests/template_tests/syntax_tests/test_partials.py", "category": "test", "repo_id": "django/django"} {"input": "\"\"\"\n=====================================\nApproximate nearest neighbors in TSNE\n=====================================\n\nThis example presents how to chain KNeighborsTransformer and TSNE in a pipeline.\nIt also shows how to wrap the packages `nmslib` and `pynndescent` to replace\nKNeighborsTransformer and perform approximate nearest neighbors. These packages\ncan be installed with `pip install nmslib pynndescent`.\n\nNote: In KNeighborsTransformer we use the definition which includes each\ntraining point as its own neighbor in the count of `n_neighbors`, and for\ncompatibility reasons, one extra neighbor is computed when `mode == 'distance'`.\nPlease note that we do the same in the proposed `nmslib` wrapper.\n\"\"\"\n\n# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause\n\n# %%\n# First we try to import the packages and warn the user in case they are\n# missing.\nimport sys\n\ntry:\n import nmslib\nexcept ImportError:\n print(\"The package 'nmslib' is required to run this example.\")\n sys.exit()\n\ntry:\n from pynndescent import PyNNDescentTransformer\nexcept ImportError:\n print(\"The package 'pynndescent'", "label": 0, "sample_id": "scikit-learn/scikit-learn:examples/neighbors/approximate_nearest_neighbors.py", "category": "unknown", "repo_id": "scikit-learn/scikit-learn"} {"input": "# SPDX-License-Identifier: AGPL-3.0-only\n# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0\n\n\"\"\"\nRun script for Unsloth UI Backend.\nWorks independently and can be moved to any directory.\n\"\"\"\n\nimport os\nimport sys\n\n# Suppress annoying C-level dependency warnings globally (e.g. SwigPyPacked)\nos.environ[\"PYTHONWARNINGS\"] = \"ignore\"\n\nfrom pathlib import Path\n\n# Add the backend directory to Python path\nbackend_dir = Path(__file__).parent\nif str(backend_dir) not in sys.path:\n sys.path.insert(0, str(backend_dir))\n\nfrom loggers import get_logger\n\nlogger = get_logger(__name__)\n\n\ndef _resolve_external_ip() -> str:\n \"\"\"\n Resolve the machine's external IP address.\n\n Tries (in order):\n 1. GCE metadata server (instant, works on Google Cloud VMs)\n 2. ifconfig.me (works anywhere with internet)\n 3. LAN IP via UDP socket trick (fallback)\n \"\"\"\n import urllib.request\n import socket\n\n # 1. Try GCE metadata server (responds in <", "label": 0, "sample_id": "unslothai/unsloth:studio/backend/run.py", "category": "unknown", "repo_id": "unslothai/unsloth"} {"input": "import json\nimport os\nimport subprocess\nimport sys\nimport threading\nimport time\nfrom collections import OrderedDict\n\nimport utils.constants as constants\nfrom utils.config import config\nfrom utils.db import get_db_connection, return_db_connection\nfrom utils.i18n import t\nfrom utils.tools import join_url, resource_path, render_nginx_conf\n\nnginx_dir = resource_path(os.path.join('utils', 'nginx-rtmp-win32'))\nnginx_conf_template = resource_path(os.path.join(nginx_dir, 'conf', 'nginx.conf.template'))\nnginx_conf = resource_path(os.path.join(nginx_dir, 'conf', 'nginx.conf'))\nnginx_path = resource_path(os.path.join(nginx_dir, 'nginx.exe'))\nstop_path = resource_path(os.path.join(nginx_dir, 'stop.bat'))\napp_rtmp_url = f\"rtmp://127.0.0.1:{config.nginx_rtmp_port}\"\n\nhls_running_streams = OrderedDict()\nSTREAMS_LOCK = threading.Lock()\nhls_last_access = {}\nHLS_IDLE_TIMEOUT = config.rtmp_idle_timeout\nHLS_WAIT_TIMEOUT = 30\nHLS_WAIT_INTERVAL = 0.5\nMAX_STREAMS = config.rtmp_max_streams\nnginx_dir = resource_path(os", "label": 1, "sample_id": "Guovin/iptv-api:service/rtmp.py", "category": "function_complex", "repo_id": "Guovin/iptv-api"} {"input": "import os\nimport numpy as np\nnp.set_printoptions(linewidth=1000000)\nos.environ[\"AMD_LLVM\"] = \"0\"\n\nfrom tinygrad import Tensor, Context, dtypes, UOp, GlobalCounters\nfrom tinygrad.helpers import DEBUG, getenv\nfrom tinygrad.dtype import AddrSpace\nfrom tinygrad.uop.ops import sint, AxisType, KernelInfo, Ops\n\nWARP_SIZE = 64\n\n# Reg tile sizes (tensor cores)\nTC_M = 16\nTC_N = 16\nTC_K = 32\n\nN,M,K = 4096,4096,4096\n\n# Threadblock tile sizes (block-level tile of C that a block computes)\nBLOCK_M = 64\nBLOCK_N = 64\nBLOCK_K = 64\n\nWARPGROUP_SIZE = 1\nBLOCK_M = BLOCK_M * WARPGROUP_SIZE\n\nTID_SIZE = WARPGROUP_SIZE*WARP_SIZE\n\ndef copy(dest:UOp, src:UOp, rng:int, set=False, upcast=()):\n assert dest.shape == src.shape\n rngs = [UOp.range(s, rng+i,", "label": 1, "sample_id": "tinygrad/tinygrad:extra/gemm/mi350x_uop_matmul_2.py", "category": "function_simple", "repo_id": "tinygrad/tinygrad"} {"input": "\"\"\"Cover Entity for Genie Garage Door.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Any\n\nimport aiohttp\n\nfrom homeassistant.components.cover import CoverDeviceClass, CoverEntity\nfrom homeassistant.core import HomeAssistant, callback\nfrom homeassistant.exceptions import HomeAssistantError\nfrom homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback\n\nfrom .const import DOMAIN, SUPPORTED_FEATURES\nfrom .coordinator import AladdinConnectConfigEntry, AladdinConnectCoordinator\nfrom .entity import AladdinConnectEntity\n\nPARALLEL_UPDATES = 1\n\n\nasync def async_setup_entry(\n hass: HomeAssistant,\n entry: AladdinConnectConfigEntry,\n async_add_entities: AddConfigEntryEntitiesCallback,\n) -> None:\n \"\"\"Set up the cover platform.\"\"\"\n coordinator = entry.runtime_data\n known_devices: set[str] = set()\n\n @callback\n def _async_add_new_devices() -> None:\n \"\"\"Detect and add entities for new doors.\"\"\"\n current_devices = set(coordinator.data)\n new_devices = current_devices - known_devices\n if new_devices:\n known_devices.update(new_devices)\n async_add_entities(\n AladdinCoverEntity(coordinator, door_id) for door_id in new_devices\n )\n\n", "label": 0, "sample_id": "home-assistant/core:homeassistant/components/aladdin_connect/cover.py", "category": "unknown", "repo_id": "home-assistant/core"} {"input": "\"\"\"Python entrypoint of chat.\"\"\"\n\nimport dataclasses\nfrom typing import Any, Dict, List, Optional, Union\n\nfrom prompt_toolkit import prompt as get_prompt # pylint: disable=import-error\nfrom prompt_toolkit.key_binding import KeyBindings # pylint: disable=import-error\n\nfrom mlc_llm.json_ffi import JSONFFIEngine\nfrom mlc_llm.protocol import openai_api_protocol\nfrom mlc_llm.serve.config import EngineConfig\nfrom mlc_llm.serve.engine import MLCEngine\nfrom mlc_llm.serve.engine_base import _query_engine_metrics\nfrom mlc_llm.support import argparse\nfrom mlc_llm.support.config import ConfigOverrideBase\n\n\ndef _print_help_str():\n help_str = \"\"\"You can use the following special commands:\n /help print the special commands\n /exit quit the cli\n /stats print out stats of last request (token/sec)\n /metrics print out full engine metrics\n /reset restart a fresh chat\n /set [overrides] override settings in the generation config. For example,\n `/set temperature=0.5;top_p=0.8;seed=23;max_tokens=", "label": 0, "sample_id": "mlc-ai/mlc-llm:python/mlc_llm/interface/chat.py", "category": "unknown", "repo_id": "mlc-ai/mlc-llm"} {"input": "import json\nimport sys\n\nfrom pypdf import PdfReader\n\n\n# Extracts data for the fillable form fields in a PDF and outputs JSON that\n# Claude uses to fill the fields. See forms.md.\n\n\n# This matches the format used by PdfReader `get_fields` and `update_page_form_field_values` methods.\ndef get_full_annotation_field_id(annotation):\n components = []\n while annotation:\n field_name = annotation.get('/T')\n if field_name:\n components.append(field_name)\n annotation = annotation.get('/Parent')\n return \".\".join(reversed(components)) if components else None\n\n\ndef make_field_dict(field, field_id):\n field_dict = {\"field_id\": field_id}\n ft = field.get('/FT')\n if ft == \"/Tx\":\n field_dict[\"type\"] = \"text\"\n elif ft == \"/Btn\":\n field_dict[\"type\"] = \"checkbox\" # radio groups handled separately\n states = field.get(\"/_States_\", [])\n if len(states) == 2:\n # \"/Off\" seems to always be the unchecked value, as suggested by\n # https://opensource.adobe.com/dc-acrobat-sdk-docs/standards/pdfstandards/pdf/PDF320", "label": 1, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/document-processing/pdf-official/scripts/extract_form_field_info.py", "category": "function_complex", "repo_id": "davila7/claude-code-templates"} {"input": "import pytest\nfrom pydantic import ValidationError\n\nfrom graphiti_core.driver.driver import GraphProvider\nfrom graphiti_core.errors import NodeLabelValidationError\nfrom graphiti_core.models.nodes.node_db_queries import (\n get_entity_node_save_bulk_query,\n get_entity_node_save_query,\n)\nfrom graphiti_core.nodes import EntityNode\n\n\ndef test_entity_node_rejects_unsafe_labels():\n with pytest.raises(ValidationError, match='node_labels must start with a letter or underscore'):\n EntityNode(\n name='Alice',\n group_id='group',\n labels=['Entity`) WITH n MATCH (x) DETACH DELETE x //'],\n )\n\n\ndef test_entity_node_assignment_rejects_unsafe_labels():\n node = EntityNode(name='Alice', group_id='group', labels=['Person'])\n\n with pytest.raises(ValidationError, match='node_labels must start with a letter or underscore'):\n node.labels = ['Entity`) WITH n MATCH (x) DETACH DELETE x //']\n\n\ndef test_entity_node_save_query_rejects_unsafe_labels_when_validation_is_bypassed():\n with pytest.raises(\n NodeLabelValidationError, match='node_labels must start with a letter or underscore'\n ):\n get_entity_node_save_query(\n GraphProvider.NEO4J,\n", "label": 0, "sample_id": "getzep/graphiti:tests/test_node_label_security.py", "category": "unknown", "repo_id": "getzep/graphiti"} {"input": "#!/usr/bin/env python\nimport fileinput\nimport fnmatch\nimport os\nimport re\nimport sys\nfrom argparse import ArgumentParser\nfrom difflib import unified_diff\n\nfrom django.core.management import ManagementUtility\n\nCURRENT_PYTHON = sys.version_info[:2]\nREQUIRED_PYTHON = (3, 10)\n\nif CURRENT_PYTHON < REQUIRED_PYTHON:\n sys.stderr.write(\n \"This version of Wagtail requires Python {}.{} or above - you are running {}.{}\\n\".format(\n *(REQUIRED_PYTHON + CURRENT_PYTHON)\n )\n )\n sys.exit(1)\n\n\ndef pluralize(value, arg=\"s\"):\n return \"\" if value == 1 else arg\n\n\nclass Command:\n description = None\n\n def create_parser(self, command_name=None):\n if command_name is None:\n prog = None\n else:\n # hack the prog name as reported to ArgumentParser to include the command\n prog = f\"{prog_name()} {command_name}\"\n\n parser = ArgumentParser(\n description=getattr(self, \"description\", None), add_help=False, prog=prog\n )\n self.add_arguments(parser)\n return parser\n\n def add_arguments(self, parser):\n pass\n\n def print_help", "label": 0, "sample_id": "wagtail/wagtail:wagtail/bin/wagtail.py", "category": "unknown", "repo_id": "wagtail/wagtail"} {"input": "# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import annotations\n\nimport ast\nimport contextlib\nimport re\nimport textwrap\nimport traceback\nfrom typing import TYPE_CHECKING, Any, Literal, cast\n\nfrom streamlit.runtime.metrics_util import gather_metrics\n\nif TYPE_CHECKING:\n from collections.abc import Generator, Iterable\n\n_SPACES_RE = re.compile(r\"\\s*\")\n_EMPTY_LINE_RE = re.compile(r\"\\s*\\n\")\n\n\n@gather_metrics(\"echo\")\n@contextlib.contextmanager\ndef echo(\n ", "label": 0, "sample_id": "streamlit/streamlit:lib/streamlit/commands/echo.py", "category": "unknown", "repo_id": "streamlit/streamlit"} {"input": "# Copyright (c) ONNX Project Contributors\n#\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"Output ONNX spec in YAML format.\n\nUsage:\n\n python spec_to_yaml.py --output onnx-spec/defs\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport enum\nimport pathlib\nfrom collections.abc import Iterable\nfrom typing import Any\n\nfrom ruamel.yaml import YAML\n\nimport onnx\n\n\ndef dump_onnx_object(\n onnx_obj: onnx.defs.OpSchema\n | onnx.defs.OpSchema.Attribute\n | onnx.defs.OpSchema.FormalParameter\n | onnx.defs.OpSchema.TypeConstraintParam,\n) -> dict[str, Any]:\n res = {}\n for attr in dir(onnx_obj):\n if attr.startswith(\"_\"):\n continue\n value = getattr(onnx_obj, attr)\n if isinstance(value, enum.EnumType) or \"nanobind\" in str(type(value)):\n continue\n if attr == \"default_value\" and isinstance(\n onnx_obj, onnx.defs.OpSchema.Attribute\n ):\n value = onnx.helper.get_attribute_value(value)\n value = dump_value(value)\n if not value:\n continue\n res[attr", "label": 1, "sample_id": "onnx/onnx:tools/spec_to_yaml.py", "category": "license", "repo_id": "onnx/onnx"} {"input": "# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nfrom __future__ import annotations\n\nfrom typing import Optional\nfrom typing_extensions import Literal\n\nimport httpx\n\nfrom .. import _legacy_response\nfrom ..types import batch_list_params, batch_create_params\nfrom .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given\nfrom .._utils import maybe_transform, async_maybe_transform\nfrom .._compat import cached_property\nfrom .._resource import SyncAPIResource, AsyncAPIResource\nfrom .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper\nfrom ..pagination import SyncCursorPage, AsyncCursorPage\nfrom ..types.batch import Batch\nfrom .._base_client import AsyncPaginator, make_request_options\nfrom ..types.shared_params.metadata import Metadata\n\n__all__ = [\"Batches\", \"AsyncBatches\"]\n\n\nclass Batches(SyncAPIResource):\n \"\"\"Create large batches of API requests to run asynchronously.\"\"\"\n\n @cached_property\n def with_raw_response(self) -> BatchesWithRawResponse:\n \"\"\"\n This property can be used as a prefix for any HTTP method call to return\n the raw response object instead of the parsed content", "label": 0, "sample_id": "openai/openai-python:src/openai/resources/batches.py", "category": "unknown", "repo_id": "openai/openai-python"} {"input": "\"\"\"Normalization of raw API data to canonical schema.\"\"\"\n\nfrom typing import Any, Dict, List, TypeVar, Union\n\nfrom . import dates, schema\n\nT = TypeVar(\"T\", schema.RedditItem, schema.XItem, schema.WebSearchItem)\n\n\ndef filter_by_date_range(\n items: List[T],\n from_date: str,\n to_date: str,\n require_date: bool = False,\n) -> List[T]:\n \"\"\"Hard filter: Remove items outside the date range.\n\n This is the safety net - even if the prompt lets old content through,\n this filter will exclude it.\n\n Args:\n items: List of items to filter\n from_date: Start date (YYYY-MM-DD) - exclude items before this\n to_date: End date (YYYY-MM-DD) - exclude items after this\n require_date: If True, also remove items with no date\n\n Returns:\n Filtered list with only items in range (or unknown dates if not required)\n \"\"\"\n result = []\n for item in items:\n if item.date is None:\n if not require_date:\n result.append(item) # Keep unknown dates (with scoring penalty)\n continue\n\n # Hard filter: if date is before", "label": 1, "sample_id": "sickn33/antigravity-awesome-skills:skills/last30days/scripts/lib/normalize.py", "category": "function_complex", "repo_id": "sickn33/antigravity-awesome-skills"} {"input": "import hashlib\nimport logging\nimport os\nfrom fnmatch import fnmatchcase\nfrom urllib.parse import urlparse\n\nimport yaml\nfrom django.conf import settings\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import RegexValidator\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\n\nfrom netbox.constants import CENSOR_TOKEN, CENSOR_TOKEN_CHANGED\nfrom netbox.models import PrimaryModel\nfrom netbox.models.features import JobsMixin\nfrom netbox.registry import registry\nfrom utilities.querysets import RestrictedQuerySet\n\nfrom ..choices import *\nfrom ..exceptions import SyncError\n\n__all__ = (\n 'AutoSyncRecord',\n 'DataFile',\n 'DataSource',\n)\n\nlogger = logging.getLogger('netbox.core.data')\n\n\nclass DataSource(JobsMixin, PrimaryModel):\n \"\"\"\n A remote source, such as a git repository, from which DataFiles are synchronized.\n \"\"\"\n name = models.CharField(\n verbose_name=_('name'),\n max_length=100,\n unique=True\n )\n type = models.CharField(\n verbose_name=_('type'),\n max_length=50\n )\n source_url =", "label": 0, "sample_id": "netbox-community/netbox:netbox/core/models/data.py", "category": "unknown", "repo_id": "netbox-community/netbox"} {"input": "import json\nimport logging\nimport re\n\nimport dspy\nfrom dspy.primitives.code_interpreter import FinalOutput\nfrom dspy.primitives.module import Module\nfrom dspy.primitives.python_interpreter import PythonInterpreter\nfrom dspy.signatures.signature import Signature, ensure_signature\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProgramOfThought(Module):\n \"\"\"\n A DSPy module that runs Python programs to solve a problem.\n This module requires deno to be installed. Please install deno following https://docs.deno.com/runtime/getting_started/installation/\n\n Examples:\n ```\n import dspy\n\n lm = dspy.LM('openai/gpt-4o-mini')\n dspy.configure(lm=lm)\n pot = dspy.ProgramOfThought(\"question -> answer\")\n pot(question=\"what is 1+1?\")\n ```\n \"\"\"\n\n def __init__(self, signature: str | type[Signature], max_iters: int = 3, interpreter: PythonInterpreter | None = None):\n \"\"\"\n Args:\n signature: The signature of the module.\n max_iters: The maximum number of iterations to retry code generation and execution.\n interpreter: PythonInterpreter instance to use. If None, a new one", "label": 0, "sample_id": "stanfordnlp/dspy:dspy/predict/program_of_thought.py", "category": "unknown", "repo_id": "stanfordnlp/dspy"} {"input": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\n\nimport frappe\nfrom frappe import _\nfrom frappe.query_builder import Case\nfrom frappe.query_builder.custom import ConstantColumn\nfrom frappe.query_builder.functions import Coalesce, Sum\nfrom frappe.utils import flt, getdate\nfrom pypika import Order\n\nfrom erpnext.accounts.utils import get_balance_on\n\n\ndef execute(filters=None):\n\tif not filters:\n\t\tfilters = {}\n\n\tcolumns = get_columns()\n\n\tif not filters.get(\"account\"):\n\t\treturn columns, []\n\n\taccount_currency = frappe.get_cached_value(\"Account\", filters.account, \"account_currency\")\n\n\tdata = get_entries(filters)\n\n\tbalance_as_per_system = get_balance_on(filters[\"account\"], filters[\"report_date\"])\n\n\ttotal_debit, total_credit = 0, 0\n\tfor d in data:\n\t\ttotal_debit += flt(d.debit)\n\t\ttotal_credit += flt(d.credit)\n\n\tamounts_not_reflected_in_system = get_amounts_not_reflected_in_system(filters)\n\n\tbank_bal = (\n\t\tflt(balance_as_per_system) - flt(total_debit) + fl", "label": 0, "sample_id": "frappe/erpnext:erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py", "category": "unknown", "repo_id": "frappe/erpnext"} {"input": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\n\nimport frappe\nfrom frappe import _\nfrom frappe.query_builder import Case\nfrom frappe.query_builder.custom import ConstantColumn\nfrom frappe.utils import getdate\nfrom pypika import Order\n\n\ndef execute(filters=None):\n\tif not filters:\n\t\tfilters = {}\n\n\tcolumns = get_columns()\n\tdata = get_entries(filters)\n\n\treturn columns, data\n\n\ndef get_columns():\n\tcolumns = [\n\t\t{\n\t\t\t\"label\": _(\"Payment Document Type\"),\n\t\t\t\"fieldname\": \"payment_document_type\",\n\t\t\t\"fieldtype\": \"Data\",\n\t\t\t\"width\": 130,\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Payment Entry\"),\n\t\t\t\"fieldname\": \"payment_entry\",\n\t\t\t\"fieldtype\": \"Dynamic Link\",\n\t\t\t\"options\": \"payment_document_type\",\n\t\t\t\"width\": 140,\n\t\t},\n\t\t{\"label\": _(\"Posting Date\"), \"fieldname\": \"posting_date\", \"fieldtype\": \"Date\", \"width\": 120},\n\t\t{\"label\": _(\"Cheque/Reference No\"),", "label": 0, "sample_id": "frappe/erpnext:erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py", "category": "unknown", "repo_id": "frappe/erpnext"} {"input": "#!/usr/bin/env python3\n# /// script\n# requires-python = \">=3.9\"\n# dependencies = []\n# ///\n\"\"\"\nBuild Ray Docker images locally using raymake.\n\"\"\"\nfrom __future__ import annotations\n\nimport argparse\nimport json\nimport os\nimport shutil\nimport subprocess\nimport sys\nfrom dataclasses import dataclass\nfrom pathlib import Path\n\nfrom ci.build.build_common import (\n BuildError,\n detect_host_arch,\n find_ray_root,\n get_git_commit,\n log,\n parse_file,\n)\n\nDEFAULT_ARCHITECTURE = \"x86_64\"\n\n# Maps image type to its base name (YAML config key and Docker Hub repo).\n_BASE_TYPE_MAP: dict[str, str] = {\n \"ray\": \"ray\",\n \"ray-extra\": \"ray\",\n \"ray-llm\": \"ray-llm\",\n \"ray-llm-extra\": \"ray-llm\",\n}\n\n\ndef _load_ray_images() -> dict:\n path = find_ray_root() / \"ray-images.json\"\n if not path.exists():\n raise BuildError(f\"Missing {path}\")\n return json.loads(path.read_text())\n\n\ndef _build_image_type_config() -> dict[str, dict]:\n \"\"\"", "label": 0, "sample_id": "ray-project/ray:ci/build/build_image.py", "category": "unknown", "repo_id": "ray-project/ray"} {"input": "from __future__ import annotations\n\nimport asyncio\nimport inspect\nimport platform\nimport sys\nfrom typing import TYPE_CHECKING\n\nimport pytest\n\nfrom tests.test_crawler import ExceptionSpider, NoRequestsSpider\nfrom tests.utils.cmdline import proc\n\nif TYPE_CHECKING:\n from collections.abc import Iterable\n from pathlib import Path\n\n\nclass TestRunSpiderCommand:\n spider_filename = \"myspider.py\"\n\n debug_log_spider = \"\"\"\nimport scrapy\n\nclass MySpider(scrapy.Spider):\n name = 'myspider'\n\n async def start(self):\n self.logger.debug(\"It Works!\")\n return\n yield\n\"\"\"\n\n badspider = \"\"\"\nimport scrapy\n\nclass BadSpider(scrapy.Spider):\n name = \"bad\"\n async def start(self):\n raise Exception(\"oops!\")\n yield\n \"\"\"\n\n def runspider(\n self, cwd: Path, code: str, name: str | None = None, args: Iterable[str] = ()\n ) -> tuple[int, str, str]:\n fname = cwd / (name or self.spider_filename)\n fname.write_text(code, encoding=\"utf-8\")\n return proc(\"runspider\", str(fname), *args, cwd=cwd", "label": 1, "sample_id": "scrapy/scrapy:tests/test_command_runspider.py", "category": "test", "repo_id": "scrapy/scrapy"} {"input": "from __future__ import annotations\n\nimport csv\nimport json\nimport marshal\nimport pickle\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any\nfrom urllib.parse import urljoin\n\nimport lxml.etree\nimport pytest\nfrom packaging.version import Version\nfrom zope.interface.verify import verifyObject\n\nimport scrapy\nfrom scrapy import Spider\nfrom scrapy.exceptions import NotConfigured\nfrom scrapy.extensions.feedexport import FeedExporter, IFeedStorage, S3FeedStorage\nfrom scrapy.settings import Settings\nfrom scrapy.utils.python import to_unicode\nfrom scrapy.utils.test import get_crawler\nfrom tests.spiders import ItemSpider\nfrom tests.test_feedexport import TestFeedExportBase\nfrom tests.utils.decorators import coroutine_test, inline_callbacks_test\n\nif TYPE_CHECKING:\n from os import PathLike\n\n\ndef build_url(path: str | PathLike) -> str:\n path_str = str(path)\n if path_str[0] != \"/\":\n path_str = \"/\" + path_str\n return urljoin(\"file:\", path_str)\n\n\nclass TestBatchDeliveries(TestFeedExportBase):\n _file_mark = \"_%(batch_time)s_#%(batch_id)02d_\"\n\n async def run_and_export(\n", "label": 0, "sample_id": "scrapy/scrapy:tests/test_feedexport_batch.py", "category": "unknown", "repo_id": "scrapy/scrapy"} {"input": "#!/usr/bin/env python\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport json\nfrom pathlib import Path\nfrom typing import Any\n\nimport datasets\nimport numpy as np\nimport pandas\nimport pandas as pd\nimport pyarrow.dataset as pa_ds\nimport pyarrow.parquet as pq\nimport torch\nfrom datasets import Dataset\nfrom datasets.table import embed_table_storage\nfrom PIL import Image as PILImage\nfrom torchvision import transforms\n\nfrom lerobot.datasets.utils import (\n DEFAULT_DATA_FILE_SIZE_IN_MB,\n DEFAULT_EPISODES_PATH,\n DEFAULT_SUBTASKS_PATH,\n DEFAULT_TASKS_PATH,\n EP", "label": 0, "sample_id": "huggingface/lerobot:src/lerobot/datasets/io_utils.py", "category": "unknown", "repo_id": "huggingface/lerobot"} {"input": "\"\"\"\nUtility functions for RSS feed generation.\n\"\"\"\n\nfrom changedetectionio.notification.handler import process_notification\nfrom changedetectionio.notification_service import NotificationContextData, _check_cascading_vars\nfrom loguru import logger\nimport datetime\nimport pytz\nimport re\n\n\nBAD_CHARS_REGEX = r'[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]'\n\n\ndef scan_invalid_chars_in_rss(content):\n \"\"\"\n Scan for invalid characters in RSS content.\n Returns True if invalid characters are found.\n \"\"\"\n for match in re.finditer(BAD_CHARS_REGEX, content):\n i = match.start()\n bad_char = content[i]\n hex_value = f\"0x{ord(bad_char):02x}\"\n # Grab context\n start = max(0, i - 20)\n end = min(len(content), i + 21)\n context = content[start:end].replace('\\n', '\\\\n').replace('\\r', '\\\\r')\n logger.warning(f\"Invalid char {hex_value} at pos {i}: ...{context}...\")\n # First match is enough\n return True\n\n return False\n\n\ndef clean_entry_content(content):\n \"\"\"\n Remove", "label": 1, "sample_id": "dgtlmoon/changedetection.io:changedetectionio/blueprint/rss/_util.py", "category": "function_complex", "repo_id": "dgtlmoon/changedetection.io"} {"input": "import numpy as np\nimport pytest\n\nfrom supervision.detection.core import Detections\nfrom supervision.metrics import MeanAverageRecall, MetricTarget\n\n\n@pytest.fixture\ndef complex_scenario_targets():\n \"\"\"\n Ground truth for complex multi-image scenario.\n\n 15 images with varying object counts and classes.\n Total: class_0=17, class_1=19 objects.\n \"\"\"\n return [\n # img 0 (2 GT: c0, c1)\n np.array(\n [\n [100, 120, 260, 400, 1.0, 0],\n [500, 200, 760, 640, 1.0, 1],\n ],\n dtype=np.float32,\n ),\n # img 1 (3 GT: c0, c0, c1)\n np.array(\n [\n [50, 60, 180, 300, 1.0, 0],\n [210, 70, 340, 310, 1.0, 0],\n [40", "label": 1, "sample_id": "roboflow/supervision:tests/metrics/test_mean_average_recall.py", "category": "test", "repo_id": "roboflow/supervision"} {"input": "\"\"\"System signal event types for CrewAI.\n\nThis module contains event types for system-level signals like SIGTERM,\nallowing listeners to perform cleanup operations before process termination.\n\"\"\"\n\nfrom collections.abc import Callable\nfrom enum import IntEnum\nimport signal\nfrom typing import Annotated, Literal, TypeVar\n\nfrom pydantic import Field, TypeAdapter\n\nfrom crewai.events.base_events import BaseEvent\n\n\nclass SignalType(IntEnum):\n \"\"\"Enumeration of supported system signals.\"\"\"\n\n SIGTERM = signal.SIGTERM\n SIGINT = signal.SIGINT\n SIGHUP = getattr(signal, \"SIGHUP\", 1)\n SIGTSTP = getattr(signal, \"SIGTSTP\", 20)\n SIGCONT = getattr(signal, \"SIGCONT\", 18)\n\n\nclass SigTermEvent(BaseEvent):\n \"\"\"Event emitted when SIGTERM is received.\"\"\"\n\n type: Literal[\"SIGTERM\"] = \"SIGTERM\"\n signal_number: SignalType = SignalType.SIGTERM\n reason: str | None = None\n\n\nclass SigIntEvent(BaseEvent):\n \"\"\"Event emitted when SIGINT is received.\"\"\"\n\n type: Literal[\"SIGINT\"] = \"SIGINT\"\n signal_number: SignalType = SignalType.SIGINT\n reason", "label": 1, "sample_id": "crewAIInc/crewAI:lib/crewai/src/crewai/events/types/system_events.py", "category": "function_simple", "repo_id": "crewAIInc/crewAI"} {"input": "from __future__ import annotations\n\nfrom collections.abc import Iterable, Iterator\nfrom typing import Any\n\nfrom pipenv.patched.pip._vendor.dependency_groups import DependencyGroupResolver\n\nfrom pipenv.patched.pip._internal.exceptions import InstallationError\nfrom pipenv.patched.pip._internal.utils.compat import tomllib\n\n\ndef parse_dependency_groups(groups: list[tuple[str, str]]) -> list[str]:\n \"\"\"\n Parse dependency groups data as provided via the CLI, in a `[path:]group` syntax.\n\n Raises InstallationErrors if anything goes wrong.\n \"\"\"\n resolvers = _build_resolvers(path for (path, _) in groups)\n return list(_resolve_all_groups(resolvers, groups))\n\n\ndef _resolve_all_groups(\n resolvers: dict[str, DependencyGroupResolver], groups: list[tuple[str, str]]\n) -> Iterator[str]:\n \"\"\"\n Run all resolution, converting any error from `DependencyGroupResolver` into\n an InstallationError.\n \"\"\"\n for path, groupname in groups:\n resolver = resolvers[path]\n try:\n yield from (str(req) for req in resolver.resolve(groupname))\n except (ValueError, TypeError, LookupError) as e:\n raise InstallationError(\n ", "label": 1, "sample_id": "pypa/pipenv:pipenv/patched/pip/_internal/req/req_dependency_group.py", "category": "function_complex", "repo_id": "pypa/pipenv"} {"input": "\"\"\"Tests for memory embedding dimension consistency.\"\"\"\nfrom unittest.mock import MagicMock, patch\nfrom runtime.node.agent.memory.memory_base import MemoryContentSnapshot, MemoryItem\nfrom runtime.node.agent.memory.simple_memory import SimpleMemory\n\ndef _make_store(memory_path=None):\n \"\"\"Build a minimal MemoryStoreConfig mock for SimpleMemory.\"\"\"\n simple_cfg = MagicMock()\n simple_cfg.memory_path = memory_path\n simple_cfg.embedding = None # We'll set embedding manually\n\n store = MagicMock()\n store.name = \"test_store\"\n store.as_config.return_value = simple_cfg\n return store\n\n\ndef _make_embedding(dim: int):\n \"\"\"Create a mock EmbeddingBase that produces vectors of the given dimension.\"\"\"\n emb = MagicMock()\n emb.get_embedding.return_value = [0.1] * dim\n return emb\n\n\ndef _make_memory_item(item_id: str, dim: int):\n \"\"\"Create a MemoryItem with an embedding of the specified dimension.\"\"\"\n return MemoryItem(\n id=item_id,\n content_summary=f\"content for {item_id}\",\n metadata={},\n embedding=[float(i) for i in range(dim)],\n )\n\n\nclass TestSimpleMemoryRetrieveMixedDimensions:\n\n def test_mixed_dimensions_does_not_crash(self):\n \"\"\"", "label": 0, "sample_id": "OpenBMB/ChatDev:tests/test_memory_embedding_consistency.py", "category": "unknown", "repo_id": "OpenBMB/ChatDev"} {"input": "\"\"\"Load MCP tools using langchain-mcp-adapters.\"\"\"\n\nimport logging\n\nfrom langchain_core.tools import BaseTool\n\nfrom deerflow.config.extensions_config import ExtensionsConfig\nfrom deerflow.mcp.client import build_servers_config\nfrom deerflow.mcp.oauth import build_oauth_tool_interceptor, get_initial_oauth_headers\n\nlogger = logging.getLogger(__name__)\n\n\nasync def get_mcp_tools() -> list[BaseTool]:\n \"\"\"Get all tools from enabled MCP servers.\n\n Returns:\n List of LangChain tools from all enabled MCP servers.\n \"\"\"\n try:\n from langchain_mcp_adapters.client import MultiServerMCPClient\n except ImportError:\n logger.warning(\"langchain-mcp-adapters not installed. Install it to enable MCP tools: pip install langchain-mcp-adapters\")\n return []\n\n # NOTE: We use ExtensionsConfig.from_file() instead of get_extensions_config()\n # to always read the latest configuration from disk. This ensures that changes\n # made through the Gateway API (which runs in a separate process) are immediately\n # reflected when initializing MCP tools.\n extensions_config = ExtensionsConfig.from_file()\n servers_config = build_servers_config(extensions_config)\n\n if not servers_config:\n logger.info(\"No enabled", "label": 0, "sample_id": "bytedance/deer-flow:backend/packages/harness/deerflow/mcp/tools.py", "category": "unknown", "repo_id": "bytedance/deer-flow"} {"input": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\nimport torch\nimport torch.nn as nn\nfrom typing_extensions import override\n\nfrom vllm.config import VllmConfig\nfrom vllm.logger import init_logger\nfrom vllm.model_executor.model_loader import get_model\nfrom vllm.v1.spec_decode.eagle import SpecDecodeBaseProposer\nfrom vllm.v1.spec_decode.utils import create_vllm_config_for_draft_model\n\nlogger = init_logger(__name__)\n\n\nclass DraftModelProposer(SpecDecodeBaseProposer):\n def __init__(\n self,\n vllm_config: VllmConfig,\n device: torch.device,\n runner=None,\n ):\n super().__init__(\n vllm_config=vllm_config,\n device=device,\n pass_hidden_states_to_model=False,\n runner=runner,\n )\n self._raise_if_vocab_size_mismatch()\n self._raise_if_draft_tp_mismatch()\n\n def _raise_if_vocab_size_mismatch(self):\n self.speculative_config.verify_equal_vocab_size_if_draft_model()\n\n def _raise_if_draft_tp_mismatch(self):\n # Note(Tomas Ruiz)", "label": 1, "sample_id": "vllm-project/vllm:vllm/v1/spec_decode/draft_model.py", "category": "license", "repo_id": "vllm-project/vllm"} {"input": "\"\"\"\nDelete Node in a Linked List\n\nGiven only access to a node (not the tail) in a singly linked list, delete\nthat node by copying the next node's value and skipping over it.\n\nReference: https://leetcode.com/problems/delete-node-in-a-linked-list/\n\nComplexity:\n Time: O(1)\n Space: O(1)\n\"\"\"\n\nfrom __future__ import annotations\n\n\nclass Node:\n def __init__(self, x: int) -> None:\n self.val = x\n self.next: Node | None = None\n\n\ndef delete_node(node: Node | None) -> None:\n \"\"\"Delete the given node from a singly linked list in-place.\n\n The node must not be the tail node. The deletion is performed by copying\n the value from the next node and then skipping the next node.\n\n Args:\n node: The node to delete (must not be None or the tail).\n\n Raises:\n ValueError: If node is None or is the tail node.\n\n Examples:\n >>> head = Node(1); head.next = Node(2); head.next.next = Node(3)\n >>> delete_node(head.next)\n >>> head.next.val\n 3\n \"\"\"\n if node is None", "label": 1, "sample_id": "keon/algorithms:algorithms/linked_list/delete_node.py", "category": "documentation", "repo_id": "keon/algorithms"} {"input": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n\nimport os\n\nimport pybase64 as base64\nimport requests\n\n# This example shows how to perform an online inference that generates\n# multimodal data. In this specific case this example will take a geotiff\n# image as input, process it using the multimodal data processor, and\n# perform inference.\n# Requirements :\n# - install TerraTorch v1.1 (or later):\n# pip install terratorch>=v1.1\n# - start vllm in serving mode with the below args\n# --model='ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL-Sen1Floods11'\n# --skip-tokenizer-init --enforce-eager\n# --io-processor-plugin terratorch_segmentation\n# --enable-mm-embeds\n\n\ndef main():\n image_url = \"https://huggingface.co/christian-pinto/Prithvi-EO-2.0-300M-TL-VLLM/resolve/main/val", "label": 0, "sample_id": "vllm-project/vllm:examples/pooling/plugin/prithvi_geospatial_mae_online.py", "category": "unknown", "repo_id": "vllm-project/vllm"} {"input": "# ===============================================================================\n# Validate Binary Search Tree\n\"\"\"\nTo check if the given binary tree is a valid binary search\ntree (BST), we need to ensure that:\n 1. The left subtree of a node contains only nodes with\n keys less than the node's key.\n 2. The right subtree of a node contains only nodes with\n keys greater than the node's key.\n 3. Both the left and right subtrees must also be binary\n search trees.\n\"\"\"\n# ===============================================================================\n\nfrom algorithms.common.tree_node import TreeNode\n\n\n# Function to validate if a binary tree is a BST\ndef validate_bst(node):\n \"\"\"\n Validate if a binary tree is a binary search tree (BST).\n Input params : Tree Node to be validated\n Returns : Tuple (\n is_bst: bool,\n min_value: int | None,\n max_value: int | None\n )\n \"\"\"\n\n # Base case: An empty tree is a valid BST\n if not node:\n return (True, None, None)\n\n # Validate the left and right subtrees\n valid_left, minn_left, maxx_left = validate_bst(node.left)\n valid_right, minn_right, maxx_right = validate", "label": 0, "sample_id": "keon/algorithms:algorithms/tree/bst_validate_bst.py", "category": "unknown", "repo_id": "keon/algorithms"} {"input": "\"\"\"Helper utilities for building EnumOption metadata.\"\"\"\n\nfrom enum import Enum\nfrom typing import Dict, List, Mapping, Sequence, Type, TypeVar\n\nfrom entity.configs.base import EnumOption\nfrom entity.enums import LogLevel, AgentExecFlowStage, AgentInputMode\nfrom utils.strs import titleize\n\nEnumT = TypeVar(\"EnumT\", bound=Enum)\n\n\n_ENUM_DESCRIPTIONS: Dict[Type[Enum], Dict[Enum, str]] = {\n LogLevel: {\n LogLevel.DEBUG: \"Verbose developer logging; useful when debugging graph behavior.\",\n LogLevel.INFO: \"High-level execution progress and key checkpoints.\",\n LogLevel.WARNING: \"Recoverable problems that require attention but do not stop the run.\",\n LogLevel.ERROR: \"Errors that abort the current node or edge execution, even the entire workflow.\",\n LogLevel.CRITICAL: \"Fatal issues that stop the workflow immediately.\",\n },\n AgentInputMode: {\n AgentInputMode.PROMPT: \"Send a single string prompt assembled from previous messages.\",\n AgentInputMode.MESSAGES: \"Send structured role/content messages (Chat Completions style) which is recommended.\",\n },\n AgentExecFlowStage: {\n AgentExecFlowStage.PRE_GEN_THINKING_STAGE: \"Pre-generation thinking /", "label": 1, "sample_id": "OpenBMB/ChatDev:entity/enum_options.py", "category": "function_simple", "repo_id": "OpenBMB/ChatDev"} {"input": "import argparse\nimport inspect\n\nimport pytest\nimport torch\n\nfrom timm.models._helpers import load_state_dict, resume_checkpoint\n\n\n_HAS_WEIGHTS_ONLY = 'weights_only' in inspect.signature(torch.load).parameters\n_HAS_SAFE_GLOBALS = hasattr(torch.serialization, 'safe_globals')\n\n\nclass _CustomPayload:\n def __init__(self, value: int = 1):\n self.value = value\n\n\n@pytest.mark.skipif(\n not (_HAS_WEIGHTS_ONLY and _HAS_SAFE_GLOBALS),\n reason='requires torch.load(weights_only=...) with safe_globals support',\n)\ndef test_weights_only_allows_argparse_namespace(tmp_path):\n checkpoint_path = tmp_path / 'namespace_ckpt.pth'\n checkpoint = {\n 'state_dict': {'layer.weight': torch.randn(2, 2)},\n 'args': argparse.Namespace(model='test-model'),\n }\n torch.save(checkpoint, checkpoint_path)\n\n state_dict = load_state_dict(checkpoint_path)\n assert 'layer.weight' in state_dict\n\n\n@pytest.mark.skipif(not _HAS_WEIGHTS_ONLY, reason='requires torch.load(weights_only=...) support')\ndef test_weights_only_blocks_non_allowlisted_globals(tmp_path):\n checkpoint_path = tmp_path / 'custom_ckpt.pth'\n checkpoint = {\n", "label": 0, "sample_id": "huggingface/pytorch-image-models:tests/test_checkpoint_loading.py", "category": "unknown", "repo_id": "huggingface/pytorch-image-models"} {"input": "import importlib.util\nimport sys\nimport tempfile\nimport unittest\nfrom pathlib import Path\n\n\nREPO_ROOT = Path(__file__).resolve().parents[3]\nTOOLS_SCRIPTS_DIR = REPO_ROOT / \"tools\" / \"scripts\"\nif str(TOOLS_SCRIPTS_DIR) not in sys.path:\n sys.path.insert(0, str(TOOLS_SCRIPTS_DIR))\n\n\ndef load_module(relative_path: str, module_name: str):\n module_path = REPO_ROOT / relative_path\n spec = importlib.util.spec_from_file_location(module_name, module_path)\n module = importlib.util.module_from_spec(spec)\n assert spec.loader is not None\n spec.loader.exec_module(module)\n return module\n\n\ngenerate_index = load_module(\"tools/scripts/generate_index.py\", \"generate_index\")\nvalidate_skills = load_module(\"tools/scripts/validate_skills.py\", \"validate_skills\")\n\n\nclass FrontmatterParsingSecurityTests(unittest.TestCase):\n def test_generate_index_frontmatter_rejects_non_mapping(self):\n content = \"---\\njust-a-string\\n---\\nbody\\n\"\n metadata = generate_index.parse_frontmatter(content)\n\n self.assertEqual(metadata, {})\n\n def test_validate_skills_frontmatter_rejects_non_mapping(self):\n content = \"---", "label": 0, "sample_id": "sickn33/antigravity-awesome-skills:tools/scripts/tests/test_frontmatter_parsing_security.py", "category": "unknown", "repo_id": "sickn33/antigravity-awesome-skills"} {"input": "__package__ = 'archivebox.api'\n\nfrom typing import Optional\nfrom datetime import timedelta\n\nfrom django.utils import timezone\nfrom django.http import HttpRequest\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\n\nfrom ninja.security import HttpBearer, APIKeyQuery, APIKeyHeader, HttpBasicAuth\nfrom ninja.errors import HttpError\n\n\ndef get_or_create_api_token(user: User | None):\n from archivebox.api.models import APIToken\n \n if user and user.is_superuser:\n api_tokens = APIToken.objects.filter(created_by_id=user.pk, expires__gt=timezone.now())\n if api_tokens.exists():\n # unexpired token exists, use it\n api_token = api_tokens.last()\n else:\n # does not exist, create a new one\n api_token = APIToken.objects.create(created_by_id=user.pk, expires=timezone.now() + timedelta(days=30))\n\n if api_token is None:\n return None\n assert api_token.is_valid(), f\"API token is not valid {api_token}\"\n\n return api_token\n return None\n\n\ndef auth_using_token(token: str | None, request: HttpRequest | None = None) -> User | None:\n \"\"\"Given an API", "label": 0, "sample_id": "ArchiveBox/ArchiveBox:archivebox/api/auth.py", "category": "unknown", "repo_id": "ArchiveBox/ArchiveBox"} {"input": "import atexit\nimport contextlib\nimport threading\nfrom typing import Any\n\nfrom strix.tools.context import get_current_agent_id\n\nfrom .browser_instance import BrowserInstance\n\n\nclass BrowserTabManager:\n def __init__(self) -> None:\n self._browsers_by_agent: dict[str, BrowserInstance] = {}\n self._lock = threading.Lock()\n\n self._register_cleanup_handlers()\n\n def _get_agent_browser(self) -> BrowserInstance | None:\n agent_id = get_current_agent_id()\n with self._lock:\n return self._browsers_by_agent.get(agent_id)\n\n def _set_agent_browser(self, browser: BrowserInstance | None) -> None:\n agent_id = get_current_agent_id()\n with self._lock:\n if browser is None:\n self._browsers_by_agent.pop(agent_id, None)\n else:\n self._browsers_by_agent[agent_id] = browser\n\n def launch_browser(self, url: str | None = None) -> dict[str, Any]:\n with self._lock:\n agent_id = get_current_agent_id()\n if agent_id in self._browsers_by_agent:\n raise ValueError(\"Browser is already launched\")\n\n try:\n browser = BrowserInstance()\n", "label": 1, "sample_id": "usestrix/strix:strix/tools/browser/tab_manager.py", "category": "function_complex", "repo_id": "usestrix/strix"} {"input": "from llama_index.core.instrumentation.events.base import BaseEvent\nfrom typing import Dict, Any\nfrom enum import Enum\nfrom llama_index.core.schema import Document\nfrom pydantic import Field\n\n\nclass FileType(Enum):\n IMAGE = \"image\"\n DOCUMENT = \"document\"\n TEXT = \"text\"\n HTML = \"html\"\n CSV = \"csv\"\n MARKDOWN = \"md\"\n SPREADSHEET = \"spreadsheet\"\n PRESENTATION = \"presentation\"\n PDF = \"pdf\"\n UNKNOWN = \"unknown\"\n\n\n# ServiceNow Knowledge Base Reader Events\n# All events use LlamaIndex's standard instrumentation event system\n# and inherit from BaseEvent for consistent event handling across the framework\nclass SNOWKBTotalPagesEvent(BaseEvent):\n \"\"\"Event fired when total pages to process is determined.\"\"\"\n\n total_pages: int = Field(description=\"Total number of pages to process\")\n\n\nclass SNOWKBPageFetchStartEvent(BaseEvent):\n \"\"\"Event fired when page data fetch starts.\"\"\"\n\n page_id: str = Field(description=\"ID of the page being fetched\")\n\n\nclass SNOWKBPageFetchCompletedEvent(BaseEvent):\n \"\"\"Event fired when page data fetch completes successfully.\"\"\"\n\n page_id: str = Field(description=\"ID of the page that", "label": 1, "sample_id": "run-llama/llama_index:llama-index-integrations/readers/llama-index-readers-service-now/llama_index/readers/service_now/event.py", "category": "function_simple", "repo_id": "run-llama/llama_index"} {"input": "from django.db import router\nfrom django.db.models import signals\nfrom taggit.managers import _TaggableManager\nfrom taggit.utils import require_instance_manager\n\n__all__ = (\n 'NetBoxTaggableManager',\n)\n\n\nclass NetBoxTaggableManager(_TaggableManager):\n \"\"\"\n Extends taggit's _TaggableManager to replace the per-tag get_or_create loop in add() with a\n single bulk_create() call, reducing SQL queries from O(N) to O(1) when assigning tags.\n \"\"\"\n\n @require_instance_manager\n def add(self, *tags, through_defaults=None, tag_kwargs=None, **kwargs):\n self._remove_prefetched_objects()\n if tag_kwargs is None:\n tag_kwargs = {}\n db = router.db_for_write(self.through, instance=self.instance)\n\n tag_objs = self._to_tag_model_instances(tags, tag_kwargs)\n new_ids = {t.pk for t in tag_objs}\n\n # Determine which tags are not already assigned to this object\n lookup = self._lookup_kwargs()\n vals = set(\n self.through._default_manager.using(db)\n .values_list(\"tag_id\", flat=True)\n .filter(**lookup, tag_id__in", "label": 0, "sample_id": "netbox-community/netbox:netbox/extras/managers.py", "category": "unknown", "repo_id": "netbox-community/netbox"} {"input": "import os.path as osp\n\nimport torch\nimport torch.nn.functional as F\n\nimport torch_geometric.transforms as T\nfrom torch_geometric.datasets import Planetoid\nfrom torch_geometric.nn import SplineConv\nfrom torch_geometric.typing import WITH_SPLINE\n\nif not WITH_SPLINE:\n quit(\"This example requires 'pyg-lib>=0.6.0'\")\n\ndataset = 'Cora'\ntransform = T.Compose([\n T.RandomNodeSplit(num_val=500, num_test=500),\n T.TargetIndegree(),\n])\npath = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', dataset)\ndataset = Planetoid(path, dataset, transform=transform)\ndata = dataset[0]\n\n\nclass Net(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = SplineConv(dataset.num_features, 16, dim=1, kernel_size=2)\n self.conv2 = SplineConv(16, dataset.num_classes, dim=1, kernel_size=2)\n\n def forward(self):\n x, edge_index, edge_attr = data.x, data.edge_index, data.edge_attr\n x = F.dropout(x, training", "label": 0, "sample_id": "pyg-team/pytorch_geometric:examples/cora.py", "category": "unknown", "repo_id": "pyg-team/pytorch_geometric"} {"input": "# type: ignore\nfrom __future__ import annotations\n\nimport argparse\nimport http.client\nimport json\nimport os\nimport time\nfrom typing import Any\nfrom urllib.parse import urlencode\n\nfrom loguru import logger\n\n_SETTLE_INITIAL_BACKOFF_S = 1.0\n_SETTLE_MAX_BACKOFF_S = 60.0\n_SETTLE_BACKOFF_MULTIPLIER = 2.0\n\n\nclass ExoHttpError(RuntimeError):\n def __init__(self, status: int, reason: str, body_preview: str):\n super().__init__(f\"HTTP {status} {reason}: {body_preview}\")\n self.status = status\n\n\nclass ExoClient:\n def __init__(self, host: str, port: int, timeout_s: float = 7200.0):\n self.host = host\n self.port = port\n self.timeout_s = timeout_s\n\n def request_json(\n self,\n method: str,\n path: str,\n params: dict[str, Any] | None = None,\n body: dict[str, Any] | None = None,\n headers: dict[str, str] | None = None,\n ) -> Any:\n if not path", "label": 1, "sample_id": "exo-explore/exo:bench/harness.py", "category": "function_complex", "repo_id": "exo-explore/exo"} {"input": "from django.contrib.contenttypes.models import ContentType\nfrom django.test import TestCase\n\nfrom dcim.constants import InterfaceTypeChoices\nfrom dcim.models import Device, DeviceRole, DeviceType, Interface, Location, Manufacturer, Region, Site, SiteGroup\nfrom ipam.forms import PrefixForm\nfrom ipam.forms.bulk_import import IPAddressImportForm\n\n\nclass PrefixFormTestCase(TestCase):\n default_dynamic_params = '[{\"fieldName\":\"scope\",\"queryParam\":\"available_at_site\"}]'\n\n @classmethod\n def setUpTestData(cls):\n cls.site = Site.objects.create(name='Site 1', slug='site-1')\n\n def test_vlan_field_sets_dynamic_params_by_default(self):\n \"\"\"data-dynamic-params present when no scope_type selected\"\"\"\n form = PrefixForm(data={})\n\n assert form.fields['vlan'].widget.attrs['data-dynamic-params'] == self.default_dynamic_params\n\n def test_vlan_field_sets_dynamic_params_for_scope_site(self):\n \"\"\"data-dynamic-params present when scope type is Site and when scope is specifc site\"\"\"\n form = PrefixForm(data={\n 'scope_type': ContentType.objects.get_for_model(Site).id,\n 'scope': self.site,\n })\n\n assert form.fields['vlan'].widget.attrs['", "label": 0, "sample_id": "netbox-community/netbox:netbox/ipam/tests/test_forms.py", "category": "unknown", "repo_id": "netbox-community/netbox"} {"input": "\"\"\"Pydantic output parser.\"\"\"\n\nimport json\nfrom typing import Any, Generic, List, Optional, Type\n\nfrom llama_index.core.output_parsers import BaseOutputParser\nfrom llama_index.core.output_parsers.utils import extract_json_str\nfrom llama_index.core.types import Model\n\nPYDANTIC_FORMAT_TMPL = \"\"\"\nHere's a JSON schema to follow:\n{schema}\n\nOutput a valid JSON object but do not repeat the schema.\n\"\"\"\n\n\nclass PydanticOutputParser(BaseOutputParser, Generic[Model]):\n \"\"\"\n Pydantic Output Parser.\n\n Args:\n output_cls (BaseModel): Pydantic output class.\n\n \"\"\"\n\n def __init__(\n self,\n output_cls: Type[Model],\n excluded_schema_keys_from_format: Optional[List] = None,\n pydantic_format_tmpl: str = PYDANTIC_FORMAT_TMPL,\n ) -> None:\n \"\"\"Init params.\"\"\"\n self._output_cls = output_cls\n self._excluded_schema_keys_from_format = excluded_schema_keys_from_format or []\n self._pydantic_format_tmpl = pydantic_format_tmpl\n\n @property\n def output_cls(self) -> Type[Model]:\n return self._output_cls\n\n @property\n", "label": 0, "sample_id": "run-llama/llama_index:llama-index-core/llama_index/core/output_parsers/pydantic.py", "category": "unknown", "repo_id": "run-llama/llama_index"} {"input": "from __future__ import annotations\n\nimport concurrent.futures\nimport datetime\nimport logging\nimport re\nimport sqlite3\nimport threading\nfrom collections import defaultdict\nfrom collections.abc import Callable, Iterable, Iterator, Sequence\nfrom contextlib import contextmanager\nfrom typing import Any, Literal, NamedTuple, cast\n\nimport orjson\nimport sqlite_vec # type: ignore[import-untyped]\nfrom langgraph.store.base import (\n BaseStore,\n GetOp,\n IndexConfig,\n Item,\n ListNamespacesOp,\n Op,\n PutOp,\n Result,\n SearchItem,\n SearchOp,\n TTLConfig,\n ensure_embeddings,\n get_text_at_path,\n tokenize_path,\n)\n\n_AIO_ERROR_MSG = (\n \"The SqliteStore does not support async methods. \"\n \"Consider using AsyncSqliteStore instead.\\n\"\n \"from langgraph.store.sqlite.aio import AsyncSqliteStore\\n\"\n)\n\nlogger = logging.getLogger(__name__)\n\nMIGRATIONS = [\n \"\"\"\nCREATE TABLE IF NOT EXISTS store (\n -- 'prefix' represents the doc's 'namespace'\n prefix text NOT NULL,\n key text NOT NULL,\n value text NOT NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n ", "label": 1, "sample_id": "langchain-ai/langgraph:libs/checkpoint-sqlite/langgraph/store/sqlite/base.py", "category": "function_complex", "repo_id": "langchain-ai/langgraph"} {"input": "import logging\nfrom abc import ABC, abstractmethod\nfrom collections.abc import Iterable\nfrom typing import Any, Generic, Optional, Protocol, Type, Union\n\nimport numpy as np\nfrom docling_core.types.doc import (\n BoundingBox,\n DocItem,\n DoclingDocument,\n NodeItem,\n PictureItem,\n)\nfrom PIL.Image import Image\nfrom typing_extensions import TypeVar\n\nfrom docling.datamodel.base_models import (\n ItemAndImageEnrichmentElement,\n Page,\n VlmPrediction,\n)\nfrom docling.datamodel.document import ConversionResult\nfrom docling.datamodel.pipeline_options import BaseOptions\nfrom docling.datamodel.pipeline_options_vlm_model import (\n InlineVlmOptions,\n TransformersPromptStyle,\n)\nfrom docling.datamodel.settings import settings\n\n\nclass BaseModelWithOptions(Protocol):\n @classmethod\n def get_options_type(cls) -> Type[BaseOptions]: ...\n\n def __init__(self, *, options: BaseOptions, **kwargs): ...\n\n\nclass BasePageModel(ABC):\n @abstractmethod\n def __call__(\n self, conv_res: ConversionResult, page_batch: Iterable[Page]\n ) -> Iterable[Page]:\n pass\n\n\nclass BaseVlmModel(ABC):\n \"\"\"", "label": 0, "sample_id": "docling-project/docling:docling/models/base_model.py", "category": "unknown", "repo_id": "docling-project/docling"} {"input": "from io import BytesIO\nfrom pathlib import Path\n\nimport pytest\n\nfrom docling.backend.pypdfium2_backend import (\n PyPdfiumDocumentBackend,\n PyPdfiumPageBackend,\n)\nfrom docling.datamodel.base_models import ConversionStatus, InputFormat\nfrom docling.datamodel.document import ConversionAssets\nfrom docling.datamodel.pipeline_options import PdfPipelineOptions\nfrom docling.document_converter import DocumentConverter, PdfFormatOption\n\n\ndef test_conversion_result_json_roundtrip_string():\n pdf_doc = Path(\"./tests/data/pdf/redp5110_sampled.pdf\")\n\n pipeline_options = PdfPipelineOptions()\n pipeline_options.do_ocr = False\n pipeline_options.images_scale = 1.0\n pipeline_options.generate_page_images = False\n pipeline_options.do_table_structure = False\n pipeline_options.table_structure_options.do_cell_matching = True\n pipeline_options.generate_parsed_pages = True\n\n doc_converter = DocumentConverter(\n format_options={\n InputFormat.PDF: PdfFormatOption(\n pipeline_options=pipeline_options, backend=PyPdfiumDocumentBackend\n )\n }\n )\n conv_res = doc_converter.convert(pdf_doc)\n\n fpath: Path = Path(\"./test-conversion.zip\")\n\n conv_res.save(filename=f", "label": 1, "sample_id": "docling-project/docling:tests/test_conversion_result_json.py", "category": "test", "repo_id": "docling-project/docling"} {"input": "# Copyright (c) DeepSpeed Team.\n# SPDX-License-Identifier: Apache-2.0\n\n# DeepSpeed Team\n\nimport os\nimport math\nimport torch\nimport psutil\nfrom deepspeed import comm as dist\nfrom deepspeed.accelerator import get_accelerator\n\n\ndef _flatten_dense_tensors(tensors):\n \"\"\"Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of\n same dense type.\n\n Since inputs are dense, the resulting tensor will be a concatenated 1D\n buffer. Element-wise operation on this buffer will be equivalent to\n operating individually.\n\n Args:\n tensors (Iterable[Tensor]): dense tensors to flatten.\n\n Returns:\n A contiguous 1D buffer containing input tensors.\n \"\"\"\n transposed_tensors = [t.transpose(0, 1).contiguous() if t.dim() == 2 else t for t in tensors]\n return torch._C._nn.flatten_dense_tensors(transposed_tensors)\n\n\ndef _unflatten_dense_tensors(flat, tensors):\n \"\"\"View a flat buffer using the sizes of tensors. Assume that tensors are of\n same dense type, and that flat is given by _flatten_dense_tensors.\n\n Args:\n flat (Tensor): flattened dense tensors to", "label": 1, "sample_id": "deepspeedai/DeepSpeed:deepspeed/runtime/zenflow/zenflow_utils.py", "category": "license", "repo_id": "deepspeedai/DeepSpeed"} {"input": "import torch\n\nclass NestedTensor:\n def __init__(self, tensors):\n self.tensors = list(tensors)\n self.is_nested = True\n\n def _copy(self):\n return NestedTensor(self.tensors)\n\n def apply_operation(self, other, operation):\n o = self._copy()\n if isinstance(other, NestedTensor):\n for i, t in enumerate(o.tensors):\n o.tensors[i] = operation(t, other.tensors[i])\n else:\n for i, t in enumerate(o.tensors):\n o.tensors[i] = operation(t, other)\n return o\n\n def __add__(self, b):\n return self.apply_operation(b, lambda x, y: x + y)\n\n def __sub__(self, b):\n return self.apply_operation(b, lambda x, y: x - y)\n\n def __mul__(self, b):\n return self.apply_operation(b, lambda x, y: x * y)\n\n # def __itruediv__(self, b):\n # return self.apply_operation(b, lambda x, y: x / y)\n\n def __truediv__(self, b):\n return self.apply_operation(b, lambda x, y:", "label": 1, "sample_id": "Comfy-Org/ComfyUI:comfy/nested_tensor.py", "category": "function_simple", "repo_id": "Comfy-Org/ComfyUI"} {"input": "\"\"\"\nFortran Language Server implementation using fortls.\n\"\"\"\n\nimport logging\nimport os\nimport pathlib\nimport re\nimport shutil\n\nfrom overrides import override\n\nfrom solidlsp import ls_types\nfrom solidlsp.ls import DocumentSymbols, LSPFileBuffer, SolidLanguageServer\nfrom solidlsp.ls_config import LanguageServerConfig\nfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParams\nfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfo\nfrom solidlsp.settings import SolidLSPSettings\n\nlog = logging.getLogger(__name__)\n\n\nclass FortranLanguageServer(SolidLanguageServer):\n \"\"\"Fortran Language Server implementation using fortls.\"\"\"\n\n @override\n def _get_wait_time_for_cross_file_referencing(self) -> float:\n return 3.0 # fortls needs time for workspace indexing\n\n @override\n def is_ignored_dirname(self, dirname: str) -> bool:\n # For Fortran projects, ignore common build directories\n return super().is_ignored_dirname(dirname) or dirname in [\n \"build\",\n \"Build\",\n \"BUILD\",\n \"bin\",\n \"lib\",\n \"mod\", # Module files directory\n \"obj\", # Object", "label": 1, "sample_id": "oraios/serena:src/solidlsp/language_servers/fortran_language_server.py", "category": "function_complex", "repo_id": "oraios/serena"} {"input": "from django.test import TestCase\n\nfrom circuits.models import *\nfrom dcim.models import *\nfrom dcim.utils import object_to_path_node\n\n__all__ = (\n 'CablePathTestCase',\n)\n\n\nclass CablePathTestCase(TestCase):\n \"\"\"\n Base class for test cases for cable paths.\n \"\"\"\n @classmethod\n def setUpTestData(cls):\n manufacturer = Manufacturer.objects.create(name='Generic', slug='generic')\n device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Test Device')\n role = DeviceRole.objects.create(name='Device Role', slug='device-role')\n provider = Provider.objects.create(name='Provider', slug='provider')\n circuit_type = CircuitType.objects.create(name='Circuit Type', slug='circuit-type')\n\n # Create reusable test objects\n cls.site = Site.objects.create(name='Site', slug='site')\n cls.device = Device.objects.create(site=cls.site, device_type=device_type, role=role, name='Test Device')\n cls.powerpanel = PowerPanel.objects.create(site=cls.site, name='Power Panel')\n cls.circuit = Circuit.objects.create(provider=provider, type=circuit_type, cid='Circuit 1')\n\n def _get_cablepath(self, nodes, **", "label": 1, "sample_id": "netbox-community/netbox:netbox/dcim/tests/utils.py", "category": "test", "repo_id": "netbox-community/netbox"} {"input": "from unittest.mock import Mock, patch\n\nimport pytest\nimport torch\n\nfrom torch_geometric.data import Data\nfrom torch_geometric.llm.utils.feature_store import KNNRAGFeatureStore\nfrom torch_geometric.sampler import SamplerOutput\nfrom torch_geometric.testing.decorators import onlyRAG\n\n\nclass TestKNNRAGFeatureStore:\n \"\"\"Test suite for KNNRAGFeatureStore methods.\"\"\"\n def setup_method(self):\n \"\"\"Set up test fixtures.\"\"\"\n self.mock_encoder = Mock()\n self.mock_encoder.encode = Mock()\n self.mock_encoder.to = Mock(return_value=self.mock_encoder)\n self.mock_encoder.eval = Mock()\n\n self.config = {\"k_nodes\": 5, \"encoder_model\": self.mock_encoder}\n self.sample_x = torch.randn(40, 128) # 40 nodes, 128 features\n self.sample_edge_attr = torch.randn(40, 64) # 40 edges, 64 features\n\n def test_bad_config(self):\n \"\"\"Test bad config initialization.\"\"\"\n with pytest.raises(ValueError, match=\"Required config parameter\"):\n store = KNNRAGFeatureStore()\n store.config = {}\n\n def create_feature_store(self):\n ", "label": 1, "sample_id": "pyg-team/pytorch_geometric:test/llm/utils/test_rag_feature_store.py", "category": "test", "repo_id": "pyg-team/pytorch_geometric"} {"input": "import os.path as osp\n\nimport torch\nimport torch.nn.functional as F\n\nimport torch_geometric.transforms as T\nfrom torch_geometric.datasets import FAUST\nfrom torch_geometric.loader import DataLoader\nfrom torch_geometric.nn import SplineConv\nfrom torch_geometric.typing import WITH_SPLINE\n\nif not WITH_SPLINE:\n quit(\"This example requires 'pyg-lib>=0.6.0'\")\n\npath = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', 'FAUST')\npre_transform = T.Compose([T.FaceToEdge(), T.Constant(value=1)])\ntrain_dataset = FAUST(path, True, T.Cartesian(), pre_transform)\ntest_dataset = FAUST(path, False, T.Cartesian(), pre_transform)\ntrain_loader = DataLoader(train_dataset, batch_size=1, shuffle=True)\ntest_loader = DataLoader(test_dataset, batch_size=1)\nd = train_dataset[0]\n\n\nclass Net(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = SplineConv(1, 32, dim=3, kernel_size=5, aggr='add')\n self.conv2 = SplineConv(32, 64,", "label": 0, "sample_id": "pyg-team/pytorch_geometric:examples/faust.py", "category": "unknown", "repo_id": "pyg-team/pytorch_geometric"} {"input": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport warnings\nfrom enum import Enum\n\nfrom omegaconf import DictConfig\n\nfrom verl.single_controller.base import Worker\nfrom verl.trainer.ppo.core_algos import AdvantageEstimator\n\nWorkerType = type[Worker]\n\n\nclass Role(Enum):\n \"\"\"\n To create more roles dynamically, you can subclass Role and add new members\n \"\"\"\n\n Actor = 0\n Rollout = 1\n ActorRollout = 2\n Critic = 3\n RefPolicy = 4\n RewardModel = 5\n ActorRolloutRef = ", "label": 1, "sample_id": "verl-project/verl:verl/trainer/ppo/utils.py", "category": "license", "repo_id": "verl-project/verl"} {"input": "\"\"\"Expand compact flow format to full flow format.\n\nThis module provides functionality to expand a minimal/compact flow format\n(used by AI agents) into the full flow format expected by Langflow.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Any\n\nfrom pydantic import BaseModel, Field\n\n\nclass CompactNode(BaseModel):\n \"\"\"A compact node representation for AI-generated flows.\"\"\"\n\n id: str\n type: str\n values: dict[str, Any] = Field(default_factory=dict)\n # If edited is True, the node field must contain the full node data\n edited: bool = False\n node: dict[str, Any] | None = None\n\n\nclass CompactEdge(BaseModel):\n \"\"\"A compact edge representation for AI-generated flows.\"\"\"\n\n source: str\n source_output: str\n target: str\n target_input: str\n\n\nclass CompactFlowData(BaseModel):\n \"\"\"The compact flow data structure.\"\"\"\n\n nodes: list[CompactNode]\n edges: list[CompactEdge]\n\n\ndef _get_flat_components(all_types_dict: dict[str, Any]) -> dict[str, Any]:\n \"\"\"Flatten the component types dict for easy lookup by component name.\"\"\"\n return {\n comp_name: comp_data\n for", "label": 1, "sample_id": "langflow-ai/langflow:src/backend/base/langflow/processing/expand_flow.py", "category": "function_complex", "repo_id": "langflow-ai/langflow"} {"input": "#!/usr/bin/env python3\n\"\"\"\nSkills Manager - Easily enable/disable skills locally\n\nUsage:\n python3 scripts/skills_manager.py list # List active skills\n python3 scripts/skills_manager.py disabled # List disabled skills\n python3 scripts/skills_manager.py enable SKILL # Enable a skill\n python3 scripts/skills_manager.py disable SKILL # Disable a skill\n\"\"\"\n\nimport sys\nimport os\nfrom pathlib import Path\n\nSKILLS_DIR = Path(__file__).parent.parent / \"skills\"\nDISABLED_DIR = SKILLS_DIR / \".disabled\"\n\n\ndef resolve_skill_path(base_dir: Path, skill_name: str) -> Path | None:\n candidate = (base_dir / skill_name).resolve()\n try:\n candidate.relative_to(base_dir.resolve())\n return candidate\n except ValueError:\n print(f\"❌ Invalid skill name: {skill_name}\")\n return None\n\ndef list_active():\n \"\"\"List all active skills\"\"\"\n print(\"🟢 Active Skills:\\n\")\n skills = sorted([d.name for d in SKILLS_DIR.iterdir() \n if d.is_dir() and not d.name.startswith('.')])\n symlinks = sorted([s.name for s in SKILLS_DIR.iterdir() \n ", "label": 0, "sample_id": "sickn33/antigravity-awesome-skills:tools/scripts/skills_manager.py", "category": "unknown", "repo_id": "sickn33/antigravity-awesome-skills"} {"input": "import frappe\nfrom frappe.tests import IntegrationTestCase\nfrom frappe.utils import getdate, today\n\nfrom erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice\nfrom erpnext.accounts.report.item_wise_sales_register.item_wise_sales_register import execute\nfrom erpnext.accounts.test.accounts_mixin import AccountsTestMixin\n\n\nclass TestItemWiseSalesRegister(AccountsTestMixin, IntegrationTestCase):\n\tdef setUp(self):\n\t\tself.create_company()\n\t\tself.create_customer()\n\t\tself.create_item()\n\n\tdef tearDown(self):\n\t\tfrappe.db.rollback()\n\n\tdef create_sales_invoice(self, item=None, taxes=None, do_not_submit=False):\n\t\tsi = create_sales_invoice(\n\t\t\titem=item or self.item,\n\t\t\titem_name=item or self.item,\n\t\t\tdescription=item or self.item,\n\t\t\tcompany=self.company,\n\t\t\tcustomer=self.customer,\n\t\t\tdebit_to=self.debit_to,\n\t\t\tposting_date=today(),\n\t\t\tparent_cost_center=self.cost_center,\n\t\t\tcost_center=self.cost_center,\n\t\t\trate=100,\n\t\t\tprice_list_rate=100,\n\t\t\tdo_not_save=1,\n\t\t)\n\n\t\tfor tax in taxes or []:\n\t\t\tsi.append(\n\t\t\t\t\"taxes\",\n\t\t\t\t{\n", "label": 0, "sample_id": "frappe/erpnext:erpnext/accounts/report/item_wise_sales_register/test_item_wise_sales_register.py", "category": "unknown", "repo_id": "frappe/erpnext"} {"input": "\"\"\"LLM utilities for GPT Researcher.\n\nThis module provides utility functions for interacting with various\nLLM providers through a unified interface.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport os\nfrom typing import Any\nimport asyncio\n\nfrom langchain_core.output_parsers import PydanticOutputParser\nfrom langchain_core.prompts import PromptTemplate\n\nfrom gpt_researcher.llm_provider.generic.base import (\n NO_SUPPORT_TEMPERATURE_MODELS,\n SUPPORT_REASONING_EFFORT_MODELS,\n ReasoningEfforts,\n)\n\nfrom ..prompts import PromptFamily\nfrom .costs import estimate_llm_cost\nfrom .validators import Subtopics\n\n\ndef get_llm(llm_provider: str, **kwargs):\n \"\"\"Get an LLM provider instance.\n\n Args:\n llm_provider: The name of the LLM provider (e.g., 'openai', 'anthropic').\n **kwargs: Additional keyword arguments passed to the provider.\n\n Returns:\n A GenericLLMProvider instance configured for the specified provider.\n \"\"\"\n from gpt_researcher.llm_provider import GenericLLMProvider\n return GenericLLMProvider.from_provider(llm_provider, **kwargs)\n\n\nasync def create_chat_completion(\n messages:", "label": 0, "sample_id": "assafelovic/gpt-researcher:gpt_researcher/utils/llm.py", "category": "unknown", "repo_id": "assafelovic/gpt-researcher"} {"input": "\"\"\"Tests for prefect_kubernetes.diagnostics.\"\"\"\n\nimport pytest\nfrom prefect_kubernetes.diagnostics import (\n DiagnosisLevel,\n InfrastructureDiagnosis,\n diagnose_k8s_pod,\n)\n\n\nclass TestDiagnoseKubernetesPod:\n \"\"\"Tests for diagnose_k8s_pod.\"\"\"\n\n # --- Happy path: no diagnosis -----------------------------------------\n\n def test_healthy_running_pod_returns_none(self):\n status = {\n \"phase\": \"Running\",\n \"containerStatuses\": [\n {\n \"name\": \"main\",\n \"state\": {\"running\": {\"startedAt\": \"2024-01-01T00:00:00Z\"}},\n }\n ],\n }\n assert diagnose_k8s_pod(status) is None\n\n def test_empty_status_returns_none(self):\n assert diagnose_k8s_pod({}) is None\n\n def test_no_container_statuses_returns_none(self):\n status = {\"phase\": \"Pending\"}\n assert diagnose_k8s_pod(status) is None\n\n def test_succeeded_pod_returns_none(self):\n status = {\n \"phase\": \"Succeeded\",\n \"containerStatuses\": [\n {\n \"name\": \"main\",\n \"state\": {\"terminated\": {\"exitCode\":", "label": 0, "sample_id": "PrefectHQ/prefect:src/integrations/prefect-kubernetes/tests/test_diagnostics.py", "category": "unknown", "repo_id": "PrefectHQ/prefect"} {"input": "import itertools\n\nfrom django.db import models\nfrom django_filters.filterset import FILTER_FOR_DBFIELD_DEFAULTS, BaseFilterSet\nfrom graphene import Argument, InputField, String\nfrom graphene.types.inputobjecttype import InputObjectTypeOptions\nfrom graphene.types.utils import yank_fields_from_attrs\n\nfrom ..descriptions import DEPRECATED_IN_3X_INPUT\nfrom ..types.base import BaseInputObjectType\nfrom .shared_filters import GlobalIDFilter, GlobalIDMultipleChoiceFilter\n\nGLOBAL_ID_FILTERS = {\n models.AutoField: {\"filter_class\": GlobalIDFilter},\n models.OneToOneField: {\"filter_class\": GlobalIDFilter},\n models.ForeignKey: {\"filter_class\": GlobalIDFilter},\n models.ManyToManyField: {\"filter_class\": GlobalIDMultipleChoiceFilter},\n models.ManyToOneRel: {\"filter_class\": GlobalIDMultipleChoiceFilter},\n models.ManyToManyRel: {\"filter_class\": GlobalIDMultipleChoiceFilter},\n}\n\n\nclass GraphQLFilterSetMixin(BaseFilterSet):\n FILTER_DEFAULTS = dict(\n itertools.chain(FILTER_FOR_DBFIELD_DEFAULTS.items(), GLOBAL_ID_FILTERS.items())\n )\n\n\ndef get_filterset_class(filterset_class=None):\n return type(\n f\"GraphQL{filterset_class.__name__}\",\n (filterset_class, GraphQLFilterSetMixin", "label": 1, "sample_id": "saleor/saleor:saleor/graphql/core/filters/filter_input.py", "category": "function_simple", "repo_id": "saleor/saleor"} {"input": "# Copyright (c) Microsoft Corporation.\n# SPDX-License-Identifier: Apache-2.0\n\n# DeepSpeed Team\n\nfrom .builder import CUDAOpBuilder, installed_cuda_version\nimport os\nfrom pathlib import Path\n\n\nclass EvoformerAttnBuilder(CUDAOpBuilder):\n BUILD_VAR = \"DS_BUILD_EVOFORMER_ATTN\"\n NAME = \"evoformer_attn\"\n\n def __init__(self, name=None):\n name = self.NAME if name is None else name\n super().__init__(name=name)\n self.cutlass_path = os.environ.get(\"CUTLASS_PATH\")\n\n def absolute_name(self):\n return f\"deepspeed.ops.{self.NAME}_op\"\n\n def extra_ldflags(self):\n if not self.is_rocm_pytorch():\n return [\"-lcurand\"]\n else:\n return []\n\n def sources(self):\n src_dir = \"csrc/deepspeed4science/evoformer_attn\"\n return [f\"{src_dir}/attention.cpp\", f\"{src_dir}/attention_back.cu\", f\"{src_dir}/attention_cu.cu\"]\n\n def nvcc_args(self):\n if os.environ.get(\"DS_EVOFORMER_GPU_ARCH\"):\n self.warning(\"DS", "label": 0, "sample_id": "deepspeedai/DeepSpeed:op_builder/evoformer_attn.py", "category": "unknown", "repo_id": "deepspeedai/DeepSpeed"} {"input": "from __future__ import annotations\n\nimport logging\nimport os\nimport sys\n\n\ndef _get_logger(name: str = \"supervision\", level: int | None = None) -> logging.Logger:\n \"\"\"Creates and configures a logger with stdout and stderr handlers.\n\n This function creates a logger that sends INFO and DEBUG level logs to stdout,\n and WARNING, ERROR, and CRITICAL level logs to stderr. If the logger already\n has handlers, it returns the existing logger without adding new handlers.\n\n The log level can be specified directly or through the `LOG_LEVEL` environment\n variable.\n\n Args:\n name: The name of the logger. Defaults to `\"supervision\"`.\n level: The logging level to set. If `None`, uses the `LOG_LEVEL` environment\n variable, defaulting to `INFO` if not set.\n\n Returns:\n A configured `logging.Logger` instance.\n\n Example:\n ```python\n from supervision.utils.logger import _get_logger\n\n logger = _get_logger(__name__)\n logger.info(\"Processing started\")\n logger.warning(\"File not found, using default\")\n ```\n \"\"\"\n if level is None:\n level = getattr(logging, os.getenv(\"LOG_LEVEL\",", "label": 1, "sample_id": "roboflow/supervision:src/supervision/utils/logger.py", "category": "documentation", "repo_id": "roboflow/supervision"} {"input": "from typing import TypedDict, Literal, Union, NotRequired\n\nOriginType = Literal[\"hls\", \"local\", \"whitelist\", \"subscribe\"]\nIPvType = Literal[\"ipv4\", \"ipv6\", None]\n\n\nclass ChannelData(TypedDict):\n \"\"\"\n Channel data types, including url, date, resolution, origin and ipv_type\n \"\"\"\n id: int\n url: str\n host: str\n date: NotRequired[str | None]\n resolution: NotRequired[str | None]\n video_codec: NotRequired[str | None]\n audio_codec: NotRequired[str | None]\n fps: NotRequired[float | None]\n origin: OriginType\n ipv_type: IPvType\n location: NotRequired[str | None]\n isp: NotRequired[str | None]\n headers: NotRequired[dict[str, str] | None]\n catchup: NotRequired[dict[str, str] | None]\n extra_info: NotRequired[str]\n\n\nCategoryChannelData = dict[str, dict[str, list[ChannelData]]]\n\n\nclass TestResult(TypedDict):\n \"\"\"\n Test result types, including speed, delay, resolution\n \"\"\"\n speed: int | float | None\n delay: int |", "label": 0, "sample_id": "Guovin/iptv-api:utils/types.py", "category": "unknown", "repo_id": "Guovin/iptv-api"} {"input": "\"\"\"Utility functions for nanobot.\"\"\"\n\nimport re\nfrom datetime import datetime\nfrom pathlib import Path\n\n\ndef ensure_dir(path: Path) -> Path:\n \"\"\"Ensure directory exists, return it.\"\"\"\n path.mkdir(parents=True, exist_ok=True)\n return path\n\n\ndef get_data_path() -> Path:\n \"\"\"~/.nanobot data directory.\"\"\"\n return ensure_dir(Path.home() / \".nanobot\")\n\n\ndef get_workspace_path(workspace: str | None = None) -> Path:\n \"\"\"Resolve and ensure workspace path. Defaults to ~/.nanobot/workspace.\"\"\"\n path = Path(workspace).expanduser() if workspace else Path.home() / \".nanobot\" / \"workspace\"\n return ensure_dir(path)\n\n\ndef timestamp() -> str:\n \"\"\"Current ISO timestamp.\"\"\"\n return datetime.now().isoformat()\n\n\n_UNSAFE_CHARS = re.compile(r'[<>:\"/\\\\|?*]')\n\ndef safe_filename(name: str) -> str:\n \"\"\"Replace unsafe path characters with underscores.\"\"\"\n return _UNSAFE_CHARS.sub(\"_\", name).strip()\n\n\ndef sync_workspace_templates(workspace: Path, silent: bool = False) -> list[str]:\n \"\"\"Sync bundled templates to workspace. Only creates missing files.\"\"\"\n from importlib.resources import files as pkg_files\n try", "label": 1, "sample_id": "HKUDS/nanobot:nanobot/utils/helpers.py", "category": "function_simple", "repo_id": "HKUDS/nanobot"} {"input": "from urllib.parse import urlparse\n\nimport anyio\nimport click\nfrom mcp import types\nfrom mcp.server import Server, ServerRequestContext\n\nSAMPLE_RESOURCES = {\n \"greeting\": {\n \"content\": \"Hello! This is a sample text resource.\",\n \"title\": \"Welcome Message\",\n },\n \"help\": {\n \"content\": \"This server provides a few sample text resources for testing.\",\n \"title\": \"Help Documentation\",\n },\n \"about\": {\n \"content\": \"This is the simple-resource MCP server implementation.\",\n \"title\": \"About This Server\",\n },\n}\n\n\nasync def handle_list_resources(\n ctx: ServerRequestContext, params: types.PaginatedRequestParams | None\n) -> types.ListResourcesResult:\n return types.ListResourcesResult(\n resources=[\n types.Resource(\n uri=f\"file:///{name}.txt\",\n name=name,\n title=SAMPLE_RESOURCES[name][\"title\"],\n description=f\"A sample text resource named {name}\",\n mime_type=\"text/plain\",\n )\n for name in SAMPLE_RESOURCES.keys()\n ]\n )\n\n\nasync def handle_read_resource(\n ctx: ServerRequestContext, params: types.ReadResourceRequestParams\n) -> types.ReadResourceResult:\n ", "label": 0, "sample_id": "modelcontextprotocol/python-sdk:examples/servers/simple-resource/mcp_simple_resource/server.py", "category": "unknown", "repo_id": "modelcontextprotocol/python-sdk"} {"input": "\"\"\"Utilities for distribution strategy with JAX backend.\"\"\"\n\nimport jax\nimport numpy as np\n\nfrom keras.src.random import seed_generator\nfrom keras.src.utils import jax_utils\nfrom keras.src.utils import rng_utils\n\n\ndef list_devices(device_type=None):\n \"\"\"Return all the available devices based on the device type.\n\n Note that this should return the global devices in a distributed setting.\n\n Args:\n device_type: string of `\"cpu\"`, `\"gpu\"` or `\"tpu\"`. Defaults to `\"gpu\"`\n or `\"tpu\"` if available when device_type is not provided. Otherwise\n will return the `\"cpu\"` devices.\n\n Return:\n List of devices that are available for distribute computation.\n \"\"\"\n device_type = device_type.lower() if device_type else None\n jax_devices = jax.devices(backend=device_type)\n return [f\"{device.platform}:{device.id}\" for device in jax_devices]\n\n\ndef get_device_count(device_type=None):\n \"\"\"Returns the number of available JAX devices.\n Args:\n device_type: Optional device type to count (e.g., \"cpu\", \"gpu\", \"tpu\").\n If `None`, it defaults to counting \"gpu\" or \"tpu\" devices if", "label": 0, "sample_id": "keras-team/keras:keras/src/backend/jax/distribution_lib.py", "category": "unknown", "repo_id": "keras-team/keras"} {"input": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\nfrom unittest import TestCase\nfrom unittest import mock\n\nfrom auditlog.models import LogEntry # type: ignore[import-untyped]\nfrom django.contrib.auth.models import Permission\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import FieldError\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\nfrom documents.data_models import DocumentSource\nfrom documents.filters import EffectiveContentFilter\nfrom documents.filters import TitleContentFilter\nfrom documents.models import Document\nfrom documents.tests.utils import DirectoriesMixin\n\nif TYPE_CHECKING:\n from pathlib import Path\n\n\nclass TestDocumentVersioningApi(DirectoriesMixin, APITestCase):\n def setUp(self) -> None:\n super().setUp()\n\n self.user = User.objects.create_superuser(username=\"temp_admin\")\n self.client.force_authenticate(user=self.user)\n\n def _make_pdf_upload(self, name: str = \"version.pdf\") -> SimpleUploadedFile:\n return SimpleUploadedFile(\n name,\n b\"%PDF-1.4\\n1 0 obj\\n<<>>\\nendobj\\n%%", "label": 1, "sample_id": "paperless-ngx/paperless-ngx:src/documents/tests/test_api_document_versions.py", "category": "test", "repo_id": "paperless-ngx/paperless-ngx"} {"input": "#!/usr/bin/env python3\n\"\"\"\nMem0 Documentation Search Agent (Mintlify-based)\nOn-demand search tool for querying Mem0 documentation without storing content locally.\n\nThis tool leverages Mintlify's documentation structure to perform just-in-time\nretrieval of technical information from docs.mem0.ai.\n\nUsage:\n python mem0_doc_search.py --query \"how to add graph memory\"\n python mem0_doc_search.py --query \"filter syntax for categories\"\n python mem0_doc_search.py --page \"/platform/features/graph-memory\"\n python mem0_doc_search.py --index\n python mem0_doc_search.py --query \"webhook events\" --section platform\n\nPurpose:\n - Avoid bloating local context with full documentation\n - Enable just-in-time retrieval of technical details\n - Query specific documentation pages on demand\n - Search across the full Mem0 documentation site\n\"\"\"\n\nimport argparse\nimport json\nimport sys\nimport urllib.error\nimport urllib.parse\nimport urllib.request\n\nDOCS_BASE = \"https://docs.mem0.ai\"\nSEARCH_ENDPOINT = f\"{DOCS_BASE}/api/search\"\nLLMS_INDEX = f\"{DOCS_BASE}/llms.txt\"\n\n# Known documentation sections for targeted retrieval\nSECTION_MAP = {\n \"platform\":", "label": 0, "sample_id": "mem0ai/mem0:skills/mem0/scripts/mem0_doc_search.py", "category": "unknown", "repo_id": "mem0ai/mem0"} {"input": "\"\"\"Demo valve platform that implements valves.\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nfrom datetime import datetime\nfrom typing import Any\n\nfrom homeassistant.components.valve import ValveEntity, ValveEntityFeature, ValveState\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback\nfrom homeassistant.helpers.device_registry import DeviceInfo\nfrom homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback\nfrom homeassistant.helpers.event import async_track_utc_time_change\n\nfrom . import DOMAIN\n\nOPEN_CLOSE_DELAY = 2 # Used to give a realistic open/close experience in frontend\n\n\nasync def async_setup_entry(\n hass: HomeAssistant,\n config_entry: ConfigEntry,\n async_add_entities: AddConfigEntryEntitiesCallback,\n) -> None:\n \"\"\"Set up the Demo config entry.\"\"\"\n async_add_entities(\n [\n DemoValve(\"valve_1\", \"Front Garden\", ValveState.OPEN),\n DemoValve(\"valve_2\", \"Orchard\", ValveState.CLOSED),\n DemoValve(\"valve_3\", \"Back Garden\", ValveState.CLOSED, position=70),\n DemoValve(\"valve_4\", \"Trees\", ValveState.C", "label": 0, "sample_id": "home-assistant/core:homeassistant/components/demo/valve.py", "category": "unknown", "repo_id": "home-assistant/core"} {"input": "# test to compare every packet with the rocprof decoder\nimport unittest, pickle\nfrom typing import Iterator\nfrom pathlib import Path\nfrom tinygrad.helpers import DEBUG, getenv, temp\nfrom tinygrad.renderer.amd.sqtt import print_packets, map_insts\nfrom tinygrad.runtime.autogen.amd.rdna3.ins import s_endpgm\nfrom tinygrad.viz.serve import sqtt_timeline\nfrom test.amd.disasm import disasm\n\nimport tinygrad\nEXAMPLES_DIR = Path(tinygrad.__file__).parent.parent / \"extra/sqtt/examples\"\n\ndef rocprof_inst_traces_match(sqtt, prg, target):\n from tinygrad.viz.serve import amd_decode\n from extra.sqtt.roc import decode as roc_decode, InstExec\n addr_table = amd_decode(prg.lib, target)\n disasm_map = {addr+prg.base:inst for addr,inst in addr_table.items()}\n rctx = roc_decode([sqtt], {prg.tag:disasm_map})\n rwaves = rctx.inst_execs.get((sqtt.kern, sqtt.exec_tag), [])\n rwaves_iter:dict[int, list[Iterator[InstExec]]] = {} # wave", "label": 0, "sample_id": "tinygrad/tinygrad:test/amd/test_sqttmap.py", "category": "unknown", "repo_id": "tinygrad/tinygrad"} {"input": "# Copyright (c) 2025, Tri Dao.\n\nimport os\nimport pathlib\nfrom typing import Tuple\nfrom functools import partial, lru_cache\nfrom dataclasses import dataclass, fields\n\nimport torch\n\ntry:\n from triton.tools.disasm import extract\nexcept ImportError:\n extract = None\n\nimport cutlass\nimport cutlass.cute as cute\nfrom cutlass.base_dsl.typing import JitArgument\nfrom cutlass.cutlass_dsl import NumericMeta\nfrom cutlass.cute.runtime import from_dlpack\n\nStaticTypes = (cutlass.Constexpr, NumericMeta, int, bool, str, float, type(None))\n\n\nload_cubin_module_data_og = cutlass.base_dsl.runtime.cuda.load_cubin_module_data\ncute_compile_og = cute.compile\n\n\ntorch2cute_dtype_map = {\n torch.float16: cutlass.Float16,\n torch.bfloat16: cutlass.BFloat16,\n torch.float32: cutlass.Float32,\n}\n\n\n@lru_cache\ndef get_max_active_clusters(cluster_size):\n return cutlass.utils.HardwareInfo().get_max_active_clusters(cluster_size=cluster_size)\n\n\n@lru_cache\ndef get_device", "label": 1, "sample_id": "Dao-AILab/flash-attention:flash_attn/cute/cute_dsl_utils.py", "category": "license", "repo_id": "Dao-AILab/flash-attention"} {"input": "import asyncio\nfrom unittest.mock import AsyncMock, MagicMock, patch\n\nimport pytest\nfrom prompt_toolkit.formatted_text import HTML\n\nfrom nanobot.cli import commands\n\n\n@pytest.fixture\ndef mock_prompt_session():\n \"\"\"Mock the global prompt session.\"\"\"\n mock_session = MagicMock()\n mock_session.prompt_async = AsyncMock()\n with patch(\"nanobot.cli.commands._PROMPT_SESSION\", mock_session), \\\n patch(\"nanobot.cli.commands.patch_stdout\"):\n yield mock_session\n\n\n@pytest.mark.asyncio\nasync def test_read_interactive_input_async_returns_input(mock_prompt_session):\n \"\"\"Test that _read_interactive_input_async returns the user input from prompt_session.\"\"\"\n mock_prompt_session.prompt_async.return_value = \"hello world\"\n\n result = await commands._read_interactive_input_async()\n \n assert result == \"hello world\"\n mock_prompt_session.prompt_async.assert_called_once()\n args, _ = mock_prompt_session.prompt_async.call_args\n assert isinstance(args[0], HTML) # Verify HTML prompt is used\n\n\n@pytest.mark.asyncio\nasync def test_read_interactive_input_async_handles_eof(mock_prompt_session):\n \"\"\"Test that EOFError converts to KeyboardInterrupt.\"\"\"\n mock_prompt_session.prompt_async.side_effect = EOFError()\n\n with pytest.raises(Keyboard", "label": 1, "sample_id": "HKUDS/nanobot:tests/test_cli_input.py", "category": "test", "repo_id": "HKUDS/nanobot"} {"input": "#!/usr/bin/env python3\n\"\"\"\nSecurity Auditor\nAutomated tool for senior security tasks\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport argparse\nfrom pathlib import Path\nfrom typing import Dict, List, Optional\n\nclass SecurityAuditor:\n \"\"\"Main class for security auditor functionality\"\"\"\n \n def __init__(self, target_path: str, verbose: bool = False):\n self.target_path = Path(target_path)\n self.verbose = verbose\n self.results = {}\n \n def run(self) -> Dict:\n \"\"\"Execute the main functionality\"\"\"\n print(f\"🚀 Running {self.__class__.__name__}...\")\n print(f\"📁 Target: {self.target_path}\")\n \n try:\n self.validate_target()\n self.analyze()\n self.generate_report()\n \n print(\"✅ Completed successfully!\")\n return self.results\n \n except Exception as e:\n print(f\"❌ Error: {e}\")\n sys.exit(1)\n \n def validate_target(self):\n \"\"\"Validate the target path exists and is accessible\"\"\"\n if not self.target_path.exists():\n raise ValueError(f\"Target path does not exist: {self.target_path}\")\n \n if self.verbose:\n print(f\"✓ Target validated: {self.target_path", "label": 1, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/development/senior-security/scripts/security_auditor.py", "category": "function_complex", "repo_id": "davila7/claude-code-templates"} {"input": "from dataclasses import dataclass\nfrom functools import partial\nfrom typing import Any, Literal\n\nfrom pydantic import BaseModel, ValidationError\nfrom starlette.requests import Request\nfrom starlette.responses import Response\n\nfrom mcp.server.auth.errors import (\n stringify_pydantic_error,\n)\nfrom mcp.server.auth.json_response import PydanticJSONResponse\nfrom mcp.server.auth.middleware.client_auth import AuthenticationError, ClientAuthenticator\nfrom mcp.server.auth.provider import AccessToken, OAuthAuthorizationServerProvider, RefreshToken\n\n\nclass RevocationRequest(BaseModel):\n \"\"\"See https://datatracker.ietf.org/doc/html/rfc7009#section-2.1\"\"\"\n\n token: str\n token_type_hint: Literal[\"access_token\", \"refresh_token\"] | None = None\n client_id: str\n client_secret: str | None\n\n\nclass RevocationErrorResponse(BaseModel):\n error: Literal[\"invalid_request\", \"unauthorized_client\"]\n error_description: str | None = None\n\n\n@dataclass\nclass RevocationHandler:\n provider: OAuthAuthorizationServerProvider[Any, Any, Any]\n client_authenticator: ClientAuthenticator\n\n async def handle(self, request: Request) -> Response:\n \"\"\"Handler for the OAuth ", "label": 1, "sample_id": "modelcontextprotocol/python-sdk:src/mcp/server/auth/handlers/revoke.py", "category": "function_simple", "repo_id": "modelcontextprotocol/python-sdk"} {"input": "import pytest\n\nfrom ....graphql.order.enums import OrderChargeStatusEnum\nfrom ....tests import race_condition\nfrom ...e2e.utils import assign_permissions\nfrom ..checkout.utils.checkout_add_promo_code import checkout_add_promo_code\nfrom ..checkout.utils.checkout_complete import checkout_complete\nfrom ..checkout.utils.checkout_create import checkout_create\nfrom ..orders.utils.order_query import order_query\nfrom ..product.utils.preparing_product import prepare_product\nfrom ..shop.utils import prepare_shop\nfrom ..transactions.utils.transaction_initialize import (\n transaction_initialize_for_gift_card_payment_gateway,\n)\nfrom .utils.gift_card_create import create_gift_card\nfrom .utils.gift_card_query import get_gift_card\n\n\ndef _prepare_shop(staff_api_client):\n shop_data, _ = prepare_shop(\n staff_api_client,\n channels=[\n {\n \"shipping_zones\": [\n {\n \"shipping_methods\": [{}],\n },\n ],\n \"order_settings\": {\n \"allowUnpaidOrders\": False,\n \"automaticallyConfirmAllNewOrders\": True,\n },\n \"checkout_settings\": {\n \"automaticallyCompleteFullyPaidCheckouts\": False,\n },\n }\n ],\n )\n\n return shop_data\n\n\ndef _prepare_product(staff_api_client", "label": 1, "sample_id": "saleor/saleor:saleor/tests/e2e/gift_cards/test_gift_cards.py", "category": "test", "repo_id": "saleor/saleor"} {"input": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\nimport os\nfrom typing import Any\nfrom uuid import uuid4\n\nfrom verl.experimental.agent_loop.agent_loop import AgentLoopBase, AgentLoopOutput, register\nfrom verl.utils.profiler import simple_timer\nfrom verl.workers.rollout.replica import TokenOutput\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(os.getenv(\"VERL_LOGGING_LEVEL\", \"WARN\"))\n\n\n@register(\"single_turn_agent\")\nclass SingleTurnAgentLoop(AgentLoopBase):\n \"\"\"Naive agent loop that only do single turn chat completion.\"\"\"\n\n def __init__(self, *", "label": 0, "sample_id": "verl-project/verl:verl/experimental/agent_loop/single_turn_agent_loop.py", "category": "unknown", "repo_id": "verl-project/verl"} {"input": "# HumanEval/94\n# Loki Mode Multi-Agent Solution\n# Attempts: 1\n# Passed: True\n\ndef skjkasdkd(lst):\n \"\"\"You are given a list of integers.\n You need to find the largest prime value and return the sum of its digits.\n\n Examples:\n For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10\n For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25\n For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13\n For lst = [0,724,3", "label": 1, "sample_id": "davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/humaneval-loki-solutions/94.py", "category": "function_simple", "repo_id": "davila7/claude-code-templates"} {"input": "from __future__ import annotations\n\nimport os\nimport json\nimport uuid\nimport asyncio\nimport base64\nimport random\nimport string\nimport urllib.parse\nfrom typing import AsyncIterator\nfrom urllib.parse import quote\n\ntry:\n from curl_cffi.requests import AsyncSession\n from curl_cffi import CurlWsFlag, CurlMime\n has_curl_cffi = True\nexcept ImportError:\n has_curl_cffi = False\ntry:\n import zendriver as nodriver\n has_nodriver = True\nexcept ImportError:\n has_nodriver = False\n\nfrom .base_provider import AsyncAuthedProvider, ProviderModelMixin\nfrom .openai.har_file import get_headers, get_har_files\nfrom ..typing import AsyncResult, Messages, MediaListType\nfrom ..errors import MissingRequirementsError, NoValidHarFileError, MissingAuthError\nfrom ..providers.response import *\nfrom ..tools.media import merge_media\nfrom ..requests import get_nodriver, DEFAULT_HEADERS\nfrom ..image import to_bytes, is_accepted_format\nfrom .helper import get_last_user_message\nfrom ..files import get_bucket_dir\nfrom ..tools.files import read_bucket\nfrom ..cookies import get_cookies\nfrom pathlib import Path\n", "label": 0, "sample_id": "xtekky/gpt4free:g4f/Provider/Copilot.py", "category": "unknown", "repo_id": "xtekky/gpt4free"} {"input": "import pytest\n\nfrom ......attribute import AttributeEntityType, AttributeInputType, AttributeType\nfrom ......attribute.models import Attribute, AttributeValue\nfrom ......attribute.utils import associate_attribute_values_to_instance\nfrom .....core.utils import to_global_id_or_none\nfrom .....tests.utils import get_graphql_content\nfrom .shared import PRODUCT_VARIANTS_WHERE_QUERY\n\n\n@pytest.mark.parametrize(\n (\"filter_type\", \"expected_count\"), [(\"containsAny\", 2), (\"containsAll\", 1)]\n)\ndef test_product_variants_query_with_attr_slug_and_attribute_value_reference_to_collections(\n filter_type,\n expected_count,\n staff_api_client,\n product_variant_list,\n product_type_collection_reference_attribute,\n channel_USD,\n collection_list,\n):\n # given\n product_type = product_variant_list[0].product.product_type\n product_type.variant_attributes.add(product_type_collection_reference_attribute)\n\n first_collection = collection_list[0]\n second_collection = collection_list[1]\n\n attribute_value_1, attribute_value_2 = AttributeValue.objects.bulk_create(\n [\n AttributeValue(\n attribute=product_type_collection_reference_attribute,\n name=f\"Category {first_collection.pk}\",\n slug=f\"collection-{first_collection.pk}\",\n reference_collection=first_collection", "label": 1, "sample_id": "saleor/saleor:saleor/graphql/product/tests/queries/variants_where/test_over_references_collections.py", "category": "test", "repo_id": "saleor/saleor"} {"input": "\"\"\"Exporter API for Ray Data operator schema.\"\"\"\n\nimport logging\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, Optional\n\nimport ray\nfrom ray._private.event.export_event_logger import (\n EventLogType,\n check_export_api_enabled,\n get_export_event_logger,\n)\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True)\nclass OperatorSchema:\n \"\"\"Represents a Ray Data operator schema\n\n Attributes:\n operator_uuid: The uuid of the operator.\n schema_fields: The schema fields of the operator.\n \"\"\"\n\n operator_uuid: str\n schema_fields: Dict[str, str] # Mapping from name to type\n\n\ndef operator_schema_to_proto(operator_schema: OperatorSchema) -> Any:\n \"\"\"Convert the operator schema to a protobuf message.\n\n Args:\n operator_schema: OperatorSchema object containing the schema details\n\n Returns:\n The protobuf message representing the operator schema.\n \"\"\"\n\n from ray.core.generated.export_dataset_operator_schema_pb2 import (\n ExportDatasetOperatorSchema as ProtoOperatorSchema,\n )\n\n # Create the protobuf message\n proto_operator_schema = ProtoOperatorSchema(\n operator_uuid=operator_schema.operator_uuid,\n schema_fields=operator_schema.schema_fields", "label": 1, "sample_id": "ray-project/ray:python/ray/data/_internal/operator_schema_exporter.py", "category": "documentation", "repo_id": "ray-project/ray"} {"input": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2026\n# Leandro Toledo de Souza \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program. If not, see [http://www.gnu.org/licenses/].\n\nimport pytest\n\nfrom telegram import BotCommand, UserRating\nfrom tests.auxil.slots import mro_slots\n\n\n@pytest.fixture(scope=\"module\")\ndef user_rating():\n return UserRating(\n level=UserRatingTestBase.level,\n rating=UserRatingTestBase.rating,\n current_level_rating=User", "label": 1, "sample_id": "python-telegram-bot/python-telegram-bot:tests/test_userrating.py", "category": "test", "repo_id": "python-telegram-bot/python-telegram-bot"} {"input": "import importlib.util\nimport inspect\nimport os\nimport typing\nimport warnings\nfrom typing import Any, Dict, List, Optional, Set, Tuple, TypeAlias, Union\n\nimport numpy as np\nimport torch\nfrom torch import Tensor\n\nWITH_PT20 = int(torch.__version__.split('.')[0]) >= 2\nWITH_PT21 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 1\nWITH_PT22 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 2\nWITH_PT23 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 3\nWITH_PT24 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 4\nWITH_PT25 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 5\nWITH_PT26 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 6\nWITH_PT27 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 7\nWITH_PT28 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 8\nWITH_PT11", "label": 0, "sample_id": "pyg-team/pytorch_geometric:torch_geometric/typing.py", "category": "unknown", "repo_id": "pyg-team/pytorch_geometric"} {"input": "# SPDX-License-Identifier: AGPL-3.0-only\n# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0\n\n\"\"\"\nTool definitions and executors for LLM tool calling.\n\nSupports web search (DuckDuckGo), Python code execution, and terminal commands.\n\"\"\"\n\nimport os\n\nos.environ[\"UNSLOTH_IS_PRESENT\"] = \"1\"\n\nimport subprocess\nimport sys\nimport tempfile\nimport threading\n\nfrom unsloth_zoo.rl_environments import check_signal_escape_patterns\n\n_EXEC_TIMEOUT = 300 # 5 minutes\n_MAX_OUTPUT_CHARS = 8000 # truncate long output\n_BASH_BLOCKED_WORDS = {\"rm\", \"sudo\", \"dd\", \"chmod\", \"mkfs\", \"shutdown\", \"reboot\"}\n\n\nWEB_SEARCH_TOOL = {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"web_search\",\n \"description\": \"Search the web for current information, recent events, or facts you are uncertain about.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"query\": {\n \"type\": \"string\",\n \"description\":", "label": 0, "sample_id": "unslothai/unsloth:studio/backend/core/inference/tools.py", "category": "unknown", "repo_id": "unslothai/unsloth"} {"input": "\"\"\"\nCopyright 2024, Zep Software, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport logging\nfrom typing import Any\n\nfrom graphiti_core.driver.driver import GraphProvider\nfrom graphiti_core.driver.operations.community_edge_ops import CommunityEdgeOperations\nfrom graphiti_core.driver.query_executor import QueryExecutor, Transaction\nfrom graphiti_core.edges import CommunityEdge\nfrom graphiti_core.errors import EdgeNotFoundError\nfrom graphiti_core.helpers import parse_db_date\nfrom graphiti_core.models.edges.edge_db_queries import (\n COMMUNITY_EDGE_RETURN,\n get_community_edge_save_query,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef _community_edge_from_record(record: Any) -> CommunityEdge:\n return CommunityEdge(\n uuid=record['uuid'],\n group", "label": 1, "sample_id": "getzep/graphiti:graphiti_core/driver/kuzu/operations/community_edge_ops.py", "category": "function_complex", "repo_id": "getzep/graphiti"} {"input": "import logging\nimport mimetypes\nimport zipfile\nfrom pathlib import Path\nfrom urllib.parse import quote\n\nfrom fastapi import APIRouter, HTTPException, Request\nfrom fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse, Response\n\nfrom app.gateway.path_utils import resolve_thread_virtual_path\n\nlogger = logging.getLogger(__name__)\n\nrouter = APIRouter(prefix=\"/api\", tags=[\"artifacts\"])\n\n\ndef is_text_file_by_content(path: Path, sample_size: int = 8192) -> bool:\n \"\"\"Check if file is text by examining content for null bytes.\"\"\"\n try:\n with open(path, \"rb\") as f:\n chunk = f.read(sample_size)\n # Text files shouldn't contain null bytes\n return b\"\\x00\" not in chunk\n except Exception:\n return False\n\n\ndef _extract_file_from_skill_archive(zip_path: Path, internal_path: str) -> bytes | None:\n \"\"\"Extract a file from a .skill ZIP archive.\n\n Args:\n zip_path: Path to the .skill file (ZIP archive).\n internal_path: Path to the file inside the archive (e.g., \"SKILL.md\").\n\n Returns:\n The file content as bytes, or None if", "label": 0, "sample_id": "bytedance/deer-flow:backend/app/gateway/routers/artifacts.py", "category": "unknown", "repo_id": "bytedance/deer-flow"} {"input": "\n# SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\npython3 hf2pretrained.py --hf-cosyvoice2-llm-path /workspace/rl-exp/checkpoint-400 --output-path /workspace/CosyVoice2-0.5B/llm-new.pt\n\"\"\"\nfrom argparse import ArgumentParser\nimport torch\nfrom safetensors import safe_open\nfrom transformers import AutoTokenizer\n\n\ndef get_args():\n parser = ArgumentParser()\n\n parser.add_argument(\n \"--hf-cosyvoice2-", "label": 1, "sample_id": "FunAudioLLM/CosyVoice:examples/grpo/cosyvoice2/huggingface_to_pretrained.py", "category": "license", "repo_id": "FunAudioLLM/CosyVoice"} {"input": "import pytest\nfrom llama_index.readers.file.slides import PptxReader\nfrom .generate_test_ppt import create_comprehensive_test_presentation\n\n\n@pytest.fixture()\ndef pptx_file(tmp_path):\n \"\"\"Create a temporary PowerPoint file for testing.\"\"\"\n if create_comprehensive_test_presentation is None:\n pytest.skip(\"generate_test_ppt not available\")\n\n # Create test presentation in temp directory\n file_path = tmp_path / \"test_presentation.pptx\"\n create_comprehensive_test_presentation(str(file_path))\n return file_path\n\n\ndef test_pptx_reader_init():\n \"\"\"Test PptxReader initialization.\"\"\"\n reader = PptxReader(extract_images=False, num_workers=2)\n assert reader.extract_images is False\n assert reader.num_workers == 2\n\n\ndef test_load_data_pptx(pptx_file):\n \"\"\"Test loading PowerPoint data.\"\"\"\n reader = PptxReader(extract_images=False, context_consolidation_with_llm=False)\n\n documents = reader.load_data(pptx_file)\n\n # Basic validation\n assert len(documents) == 12 # Should have 12 slides\n assert all(hasattr(doc, \"text\") for doc in documents)\n assert all", "label": 1, "sample_id": "run-llama/llama_index:llama-index-integrations/readers/llama-index-readers-file/tests/test_slides.py", "category": "test", "repo_id": "run-llama/llama_index"} {"input": "# Copyright 2026 The JAX Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport functools\nimport hashlib\nimport itertools\nimport logging\nimport os\nimport unittest\n\nimport hypothesis as hp\nfrom hypothesis.internal import detection\nfrom hypothesis.internal import reflection\nfrom hypothesis.strategies._internal import core as hps_internal_core\nfrom jax._src import config\nfrom jax._src import test_util as jtu\nfrom jax._src.test_loader import JaxTestLoader\n\nHYPOTHESIS_PROFILE = config.string_flag(\n \"hypothesis_profile\",\n os.getenv(\"JAX_HYPOTHESIS_PROFILE\", \"deterministic\"),\n help=(\n \"Select the hypothesis profile to use for", "label": 0, "sample_id": "jax-ml/jax:jax/_src/hypothesis_test_util.py", "category": "unknown", "repo_id": "jax-ml/jax"} {"input": "import pydantic\nimport pytest\n\nfrom dspy.experimental import Document\n\n\ndef test_document_validate_input():\n # Create a `Document` instance with valid data.\n doc = Document(data=\"The Earth orbits the Sun.\")\n assert doc.data == \"The Earth orbits the Sun.\"\n\n with pytest.raises(pydantic.ValidationError):\n # Try to create a `Document` instance with invalid type.\n Document(data=123)\n\n\ndef test_document_in_nested_type():\n class Wrapper(pydantic.BaseModel):\n document: Document\n\n doc = Document(data=\"Hello, world!\")\n wrapper = Wrapper(document=doc)\n assert wrapper.document.data == \"Hello, world!\"\n\n\ndef test_document_with_all_fields():\n doc = Document(\n data=\"Water boils at 100°C at standard pressure.\",\n title=\"Physics Facts\",\n media_type=\"application/pdf\",\n context=\"Laboratory conditions\"\n )\n assert doc.data == \"Water boils at 100°C at standard pressure.\"\n assert doc.title == \"Physics Facts\"\n assert doc.media_type == \"application/pdf\"\n assert doc.context == \"Laboratory conditions\"\n\n\ndef test_document_format():\n doc = Document(\n data=\"The sky is blue.\",\n title=\"", "label": 1, "sample_id": "stanfordnlp/dspy:tests/adapters/test_document.py", "category": "test", "repo_id": "stanfordnlp/dspy"} {"input": "from typing import Any, List, Optional\nfrom pathlib import Path\nimport numpy as np\n\nfrom llama_index.core.base.embeddings.base import (\n DEFAULT_EMBED_BATCH_SIZE,\n BaseEmbedding,\n)\nfrom llama_index.core.bridge.pydantic import Field, PrivateAttr\nfrom llama_index.core.callbacks import CallbackManager\nfrom llama_index.embeddings.huggingface.utils import format_query, format_text\n\n\nclass OpenVINOGENAIEmbedding(BaseEmbedding):\n model_path: str = Field(description=\"local path.\")\n max_length: int = Field(description=\"Maximum length of input.\")\n pooling: str = Field(description=\"Pooling strategy. One of ['cls', 'mean'].\")\n normalize: bool = Field(default=True, description=\"Normalize embeddings or not.\")\n query_instruction: Optional[str] = Field(\n description=\"Instruction to prepend to query text.\"\n )\n text_instruction: Optional[str] = Field(\n description=\"Instruction to prepend to text.\"\n )\n cache_folder: Optional[str] = Field(\n description=\"Cache folder for huggingface files.\", default=None\n )\n\n _model: Any = PrivateAttr()\n _tokenizer: Any = PrivateAttr()\n _device: Any = PrivateAttr()\n\n def __init__(\n", "label": 1, "sample_id": "run-llama/llama_index:llama-index-integrations/embeddings/llama-index-embeddings-openvino-genai/llama_index/embeddings/openvino_genai/base.py", "category": "function_complex", "repo_id": "run-llama/llama_index"} {"input": "import time\nfrom collections import defaultdict\nfrom collections.abc import Callable, Mapping\nfrom typing import final\n\nimport anyio\n\nfrom exo.shared.types.api import NodePowerStats, PowerUsage\nfrom exo.shared.types.common import NodeId\nfrom exo.shared.types.profiling import SystemPerformanceProfile\n\n\n@final\nclass PowerSampler:\n def __init__(\n self,\n get_node_system: Callable[[], Mapping[NodeId, SystemPerformanceProfile]],\n interval: float = 1.0,\n ):\n self._get_node_system = get_node_system\n self._interval = interval\n self._samples: defaultdict[NodeId, list[SystemPerformanceProfile]] = (\n defaultdict(list)\n )\n self._start_time: float | None = None\n self._stopped = False\n\n def _take_sample(self) -> None:\n for node_id, profile in self._get_node_system().items():\n self._samples[node_id].append(profile)\n\n async def run(self) -> None:\n self._start_time = time.perf_counter()\n self._take_sample()\n while not self._stopped:\n await anyio.sleep(self._interval)\n self._take_sample()\n\n def result(self) -> PowerUsage:\n", "label": 0, "sample_id": "exo-explore/exo:src/exo/utils/power_sampler.py", "category": "unknown", "repo_id": "exo-explore/exo"} {"input": "\"\"\"Shared server version checking logic for Prefect clients.\n\nThis module contains the version compatibility check cache and a standalone\nasync helper so that both HTTP-based clients (PrefectClient / SyncPrefectClient)\nand WebSocket-based clients (PrefectEventsClient, PrefectEventSubscriber,\nPrefectLogsSubscriber) can share the same once-per-process guard.\n\"\"\"\n\nimport base64\nimport logging\nimport ssl\nimport threading\nfrom urllib.parse import urlparse, urlunparse\n\nimport certifi\nimport httpx\nfrom packaging import version\n\nimport prefect\nfrom prefect.settings import (\n PREFECT_API_AUTH_STRING,\n PREFECT_API_KEY,\n PREFECT_API_SSL_CERT_FILE,\n PREFECT_API_TLS_INSECURE_SKIP_VERIFY,\n get_current_settings,\n)\n\n# ---------------------------------------------------------------------------\n# Cache – keyed by (api_url, client_version) so each unique pair is checked\n# at most once per process.\n# ---------------------------------------------------------------------------\n_API_VERSION_CHECK_CACHE: set[tuple[str, str]] = set()\n_API_VERSION_CHECK_CACHE_LOCK = threading.Lock()\n\n\ndef _api_version_check_key(api_url: str, client_version: str) -> tuple[str, str]:\n return (api_url, client_version)\n\n\ndef _is_api_version_check_cached(key: tuple[str, str]) -> bool:\n", "label": 0, "sample_id": "PrefectHQ/prefect:src/prefect/client/_version_checking.py", "category": "unknown", "repo_id": "PrefectHQ/prefect"} {"input": "from abc import abstractmethod\nfrom concurrent.futures import Future\nfrom threading import Thread\nfrom typing import TYPE_CHECKING, Any\n\nfrom dspy.clients.utils_finetune import TrainDataFormat\n\nif TYPE_CHECKING:\n from dspy.clients.lm import LM\n\n\nclass TrainingJob(Future):\n \"\"\"A future representing an asynchronous model fine-tuning job.\n\n This class extends `concurrent.futures.Future` to represent a fine-tuning job\n that can be monitored and cancelled. Subclasses should implement the `status`\n method to provide job status information specific to their provider.\n\n Attributes:\n thread: The thread running the training job, if applicable.\n model: The model identifier being fine-tuned.\n train_data: The training data used for fine-tuning.\n train_data_format: The format of the training data.\n train_kwargs: Additional keyword arguments for training configuration.\n\n Examples:\n ```python\n from dspy.clients.provider import TrainingJob\n\n job = TrainingJob(\n model=\"gpt-3.5-turbo\",\n train_data=[{\"messages\": [...]}],\n train_data_format=TrainDataFormat.CHAT\n )\n # Check if job is done\n if job.done():\n", "label": 0, "sample_id": "stanfordnlp/dspy:dspy/clients/provider.py", "category": "unknown", "repo_id": "stanfordnlp/dspy"} {"input": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\nfrom vllm.v1.attention.backend import (\n AttentionBackend,\n AttentionImpl,\n)\nfrom vllm.v1.attention.backends.registry import (\n AttentionBackendEnum,\n MambaAttentionBackendEnum,\n register_backend,\n)\n\n\nclass CustomAttentionImpl(AttentionImpl):\n \"\"\"Mock custom attention implementation for testing.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__()\n\n def forward(self, *args, **kwargs):\n \"\"\"Mock forward pass.\"\"\"\n pass\n\n\nclass CustomAttentionBackend(AttentionBackend):\n \"\"\"Mock custom attention backend for testing.\"\"\"\n\n @staticmethod\n def get_name():\n return \"CUSTOM\"\n\n @staticmethod\n def get_impl_cls():\n return CustomAttentionImpl\n\n @staticmethod\n def get_builder_cls():\n \"\"\"Mock builder class.\"\"\"\n return None\n\n @staticmethod\n def get_required_kv_cache_layout():\n \"\"\"Mock KV cache layout.\"\"\"\n return None\n\n\nclass CustomMambaAttentionImpl(AttentionImpl):\n \"\"\"Mock custom mamba attention implementation for testing.\"\"\"\n\n def __init__(self, *args, **kwargs):\n ", "label": 1, "sample_id": "vllm-project/vllm:tests/test_attention_backend_registry.py", "category": "test", "repo_id": "vllm-project/vllm"} {"input": "from typing import Optional\nfrom pydantic import Field\n\nfrom mem0.configs.rerankers.base import BaseRerankerConfig\n\n\nclass LLMRerankerConfig(BaseRerankerConfig):\n \"\"\"\n Configuration for LLM-based reranker.\n \n Attributes:\n model (str): LLM model to use for reranking. Defaults to \"gpt-4o-mini\".\n api_key (str): API key for the LLM provider.\n provider (str): LLM provider. Defaults to \"openai\".\n top_k (int): Number of top documents to return after reranking.\n temperature (float): Temperature for LLM generation. Defaults to 0.0 for deterministic scoring.\n max_tokens (int): Maximum tokens for LLM response. Defaults to 100.\n scoring_prompt (str): Custom prompt template for scoring documents.\n \"\"\"\n \n model: str = Field(\n default=\"gpt-4o-mini\",\n description=\"LLM model to use for reranking\"\n )\n api_key: Optional[str] = Field(\n default=None,\n description=\"API key for the LLM provider\"\n )\n provider: str = Field(\n default=\"openai\",\n description", "label": 1, "sample_id": "mem0ai/mem0:mem0/configs/rerankers/llm.py", "category": "function_simple", "repo_id": "mem0ai/mem0"} {"input": "import logging\nfrom collections.abc import Callable\nfrom contextlib import asynccontextmanager\nfrom typing import Any\nfrom urllib.parse import parse_qs, urljoin, urlparse\n\nimport anyio\nimport httpx\nfrom anyio.abc import TaskStatus\nfrom anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream\nfrom httpx_sse import aconnect_sse\nfrom httpx_sse._exceptions import SSEError\n\nfrom mcp import types\nfrom mcp.shared._httpx_utils import McpHttpClientFactory, create_mcp_http_client\nfrom mcp.shared.message import SessionMessage\n\nlogger = logging.getLogger(__name__)\n\n\ndef remove_request_params(url: str) -> str:\n return urljoin(url, urlparse(url).path)\n\n\ndef _extract_session_id_from_endpoint(endpoint_url: str) -> str | None:\n query_params = parse_qs(urlparse(endpoint_url).query)\n return query_params.get(\"sessionId\", [None])[0] or query_params.get(\"session_id\", [None])[0]\n\n\n@asynccontextmanager\nasync def sse_client(\n url: str,\n headers: dict[str, Any] | None = None,\n timeout: float = 5.0,\n sse_read_timeout:", "label": 0, "sample_id": "modelcontextprotocol/python-sdk:src/mcp/client/sse.py", "category": "unknown", "repo_id": "modelcontextprotocol/python-sdk"} {"input": "\"\"\"\nUnit tests for PostgreSQL safe index name generation.\n\nThis module tests the _safe_index_name helper function which prevents\nPostgreSQL's silent 63-byte identifier truncation from causing index\nlookup failures.\n\"\"\"\n\nimport pytest\n\n# Mark all tests as offline (no external dependencies)\npytestmark = pytest.mark.offline\n\n\nclass TestSafeIndexName:\n \"\"\"Test suite for _safe_index_name function.\"\"\"\n\n def test_short_name_unchanged(self):\n \"\"\"Short index names should remain unchanged.\"\"\"\n from lightrag.kg.postgres_impl import _safe_index_name\n\n # Short table name - should return unchanged\n result = _safe_index_name(\"lightrag_vdb_entity\", \"hnsw_cosine\")\n assert result == \"idx_lightrag_vdb_entity_hnsw_cosine\"\n assert len(result.encode(\"utf-8\")) <= 63\n\n def test_long_name_gets_hashed(self):\n \"\"\"Long table names exceeding 63 bytes should get hashed.\"\"\"\n from lightrag.kg.postgres_impl import _safe_index_name\n\n # Long table name that would exceed 63 bytes\n long_table_name = \"LIGHTRAG_VDB_ENTITY_text_embedding_3_large_307", "label": 1, "sample_id": "HKUDS/LightRAG:tests/test_postgres_index_name.py", "category": "test", "repo_id": "HKUDS/LightRAG"} {"input": "# -*- coding: utf-8 -*-\n#\nfrom collections import defaultdict\n\nfrom django.db.models import Count, Q, F, Value\nfrom django.db.models.functions import Concat\nfrom django.http import JsonResponse\nfrom django.utils import timezone\nfrom rest_framework.views import APIView\n\nfrom accounts.const import Source\nfrom accounts.models import Account, AccountTemplate\nfrom assets.const import Connectivity\nfrom common.permissions import IsValidLicense\nfrom common.utils import lazyproperty\nfrom rbac.permissions import RBACPermission\nfrom reports.api.assets.base import group_stats\nfrom reports.mixins import DateRangeMixin\n\n__all__ = ['AccountStatisticApi']\n\n\nclass AccountStatisticApi(DateRangeMixin, APIView):\n http_method_names = ['get']\n rbac_perms = {\n 'GET': 'rbac.view_accountstatisticsreport',\n }\n permission_classes = [RBACPermission, IsValidLicense]\n\n @lazyproperty\n def base_qs(self):\n return Account.objects.all()\n\n @lazyproperty\n def template_qs(self):\n return AccountTemplate.objects.all()\n\n def get_change_secret_account_metrics(self):\n filtered_queryset = self.filter_by_date_range(self.base_qs, 'date_change_secret')\n\n data = defaultdict(set)\n for t, _id in filtered_queryset.values_list", "label": 1, "sample_id": "jumpserver/jumpserver:apps/reports/api/accouts/account.py", "category": "function_simple", "repo_id": "jumpserver/jumpserver"} {"input": "import warnings\nfrom contextlib import nullcontext\nfrom typing import Any, Dict, List, Optional\n\nimport torch\nfrom torch import Tensor\n\ntry:\n from transformers.tokenization_utils_base import BatchEncoding\nexcept ImportError:\n BatchEncoding = Dict\n\nIGNORE_INDEX = -100\nMAX_TXT_LEN = 512\nMAX_NEW_TOKENS = 128\nPAD_TOKEN_ID = 0\nPADDING_SIDE = 'left'\n\n# legacy constants - used for Llama 2 style prompting\nBOS = '[INST]'\nEOS_USER = '[/INST]'\nEOS = '[/s]'\n\n\ndef get_llm_kwargs(required_memory: int, dtype=torch.dtype) -> Dict[str, Any]:\n torch.cuda.empty_cache()\n\n gpu_memory: List[int] = []\n for i in range(torch.cuda.device_count()):\n gpu_memory.append(torch.cuda.mem_get_info(i)[0] // 1024**3)\n # Use the minimum number of GPUs to fit the LLM on.\n if sum(gpu_memory) >= required_memory:\n break\n\n if sum(gpu_memory) < required_memory:\n gpu_memory = [] # If not enough VRAM, use pure CPU.\n\n kwargs = dict(re", "label": 0, "sample_id": "pyg-team/pytorch_geometric:torch_geometric/llm/models/llm.py", "category": "unknown", "repo_id": "pyg-team/pytorch_geometric"} {"input": "import datetime\nimport os.path as osp\nimport sys\n\nimport pyg_sphinx_theme\n\nimport torch_geometric\n\nauthor = 'PyG Team'\nproject = 'pytorch_geometric'\nversion = torch_geometric.__version__\ncopyright = f'{datetime.datetime.now().year}, {author}'\n\nsys.path.append(osp.join(osp.dirname(pyg_sphinx_theme.__file__), 'extension'))\n\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.napoleon',\n 'sphinx.ext.viewcode',\n 'sphinx_autodoc_typehints',\n 'sphinx_copybutton',\n 'nbsphinx',\n 'pyg',\n]\n\nhtml_theme = 'pyg_sphinx_theme'\nhtml_logo = ('https://raw.githubusercontent.com/pyg-team/pyg_sphinx_theme/'\n 'master/pyg_sphinx_theme/static/img/pyg_logo.png')\nhtml_favicon = ('https://raw.githubusercontent.com/pyg-team/pyg_sphinx_theme/'\n 'master/pyg_sphinx_theme/static/img/favicon.png')\nhtml_static_path = ['_static']\ntemplates_path = ['_templates']\n\n", "label": 0, "sample_id": "pyg-team/pytorch_geometric:docs/source/conf.py", "category": "unknown", "repo_id": "pyg-team/pytorch_geometric"} {"input": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2026\n# Leandro Toledo de Souza \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program. If not, see [http://www.gnu.org/licenses/].\n\"\"\"This module contains an objects that are related to Telegram input checklists.\"\"\"\n\nfrom collections.abc import Sequence\n\nfrom telegram._messageentity import MessageEntity\nfrom telegram._telegramobject import TelegramObject\nfrom telegram._utils.argumentparsing import parse_sequence_arg\nfrom telegram._utils.defaultvalue import DEFAULT", "label": 1, "sample_id": "python-telegram-bot/python-telegram-bot:src/telegram/_inputchecklist.py", "category": "license", "repo_id": "python-telegram-bot/python-telegram-bot"} {"input": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom pandas.core.dtypes.missing import (\n isna,\n na_value_for_dtype,\n)\n\nif TYPE_CHECKING:\n from pandas._typing import (\n ArrayLike,\n Scalar,\n npt,\n )\n\n\ndef quantile_compat(\n values: ArrayLike, qs: npt.NDArray[np.float64], interpolation: str\n) -> ArrayLike:\n \"\"\"\n Compute the quantiles of the given values for each quantile in `qs`.\n\n Parameters\n ----------\n values : np.ndarray or ExtensionArray\n qs : np.ndarray[float64]\n interpolation : str\n\n Returns\n -------\n np.ndarray or ExtensionArray\n \"\"\"\n if isinstance(values, np.ndarray):\n fill_value = na_value_for_dtype(values.dtype, compat=False)\n mask = isna(values)\n return quantile_with_mask(\n values,\n mask,\n fill_value, # pyright: ignore[reportArgumentType]\n qs,\n interpolation,\n )\n else:\n return values._quantile(qs, interpolation)\n\n\ndef quantile_with_mask(\n values: np.ndarray,\n mask: npt.NDArray", "label": 0, "sample_id": "pandas-dev/pandas:pandas/core/array_algos/quantile.py", "category": "unknown", "repo_id": "pandas-dev/pandas"} {"input": "from datetime import datetime\nfrom typing import TYPE_CHECKING\nfrom uuid import UUID, uuid4\n\nimport sqlalchemy as sa\nfrom pydantic import field_validator\nfrom sqlalchemy import ForeignKey, UniqueConstraint\nfrom sqlmodel import Column, DateTime, Field, Relationship, SQLModel, func\n\nfrom langflow.schema.serialize import UUIDstr\nfrom langflow.services.database.utils import validate_non_empty_string\n\nif TYPE_CHECKING:\n from langflow.services.database.models.deployment_provider_account.model import DeploymentProviderAccount\n from langflow.services.database.models.folder.model import Folder\n from langflow.services.database.models.user.model import User\n\n\nclass Deployment(SQLModel, table=True): # type: ignore[call-arg]\n __tablename__ = \"deployment\"\n __table_args__ = (\n UniqueConstraint(\"deployment_provider_account_id\", \"name\", name=\"uq_deployment_name_in_provider\"),\n UniqueConstraint(\n \"deployment_provider_account_id\", \"resource_key\", name=\"uq_deployment_resource_key_in_provider\"\n ),\n )\n\n id: UUID | None = Field(default_factory=uuid4, primary_key=True)\n resource_key: str = Field(index=True)\n user_id: UUIDstr = Field(\n sa_column=Column(sa.Uuid(),", "label": 0, "sample_id": "langflow-ai/langflow:src/backend/base/langflow/services/database/models/deployment/model.py", "category": "unknown", "repo_id": "langflow-ai/langflow"} {"input": "# SPDX-License-Identifier: AGPL-3.0-only\n# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0\n\n\"\"\"\nMain FastAPI application for Unsloth UI Backend\n\"\"\"\n\nimport os\n\n# Suppress annoying C-level dependency warnings globally\nos.environ[\"PYTHONWARNINGS\"] = \"ignore\"\n\nimport shutil\nimport sys\nimport warnings\nfrom contextlib import asynccontextmanager\n\n# Suppress annoying dependency warnings in production\nif os.getenv(\"ENVIRONMENT_TYPE\", \"production\") == \"production\":\n warnings.filterwarnings(\"ignore\")\n # Alternatively, you can be more specific:\n # warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n # warnings.filterwarnings(\"ignore\", module=\"triton.*\")\n\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.responses import FileResponse, HTMLResponse, Response\nfrom pathlib import Path\nfrom datetime import datetime\n\n# Import routers\nfrom routes import (\n auth_router,\n data_recipe_router,\n datasets_router,\n export_router,\n inference_router,\n models_router,\n training_router,\n)\nfrom auth import", "label": 0, "sample_id": "unslothai/unsloth:studio/backend/main.py", "category": "unknown", "repo_id": "unslothai/unsloth"} {"input": "# Copyright 2025 the LlamaFactory team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nfrom enum import StrEnum, unique\nfrom typing import TYPE_CHECKING, Any, Optional, TypedDict, Union\n\nimport fsspec\nfrom datasets import DatasetDict, concatenate_datasets, interleave_datasets\n\nfrom ..extras import logging\n\n\nif TYPE_CHECKING:\n from datasets import Dataset, IterableDataset\n\n from ..hparams import DataArguments\n\n\nlogger = logging.get_logger(__name__)\n\n\nSLOTS = list[Union[str, set[str], dict[str, str]]]\n\n\n@unique\nclass Role(StrEnum):\n USER = \"user\"\n ASSISTANT = \"assistant\"\n SYSTEM", "label": 0, "sample_id": "hiyouga/LlamaFactory:src/llamafactory/data/data_utils.py", "category": "unknown", "repo_id": "hiyouga/LlamaFactory"} {"input": "# Copyright (c) ONNX Project Contributors\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\nimport os\nimport pathlib\nimport re\nimport sys\nimport uuid\nfrom itertools import chain\nfrom typing import TYPE_CHECKING\n\nimport onnx.checker as onnx_checker\nimport onnx.onnx_cpp2py_export.checker as c_checker\nfrom onnx.onnx_pb import (\n AttributeProto,\n FunctionProto,\n GraphProto,\n ModelProto,\n TensorProto,\n)\n\nif TYPE_CHECKING:\n from collections.abc import Callable, Iterable\n\n\nclass ExternalDataInfo:\n def __init__(self, tensor: TensorProto) -> None:\n self.location = \"\"\n self.offset = None\n self.length = None\n self.checksum = None\n self.basepath = \"\"\n\n for entry in tensor.external_data:\n setattr(self, entry.key, entry.value)\n\n if self.offset is not None:\n self.offset = int(self.offset)\n\n if self.length is not None:\n self.length = int(self.length)\n\n\ndef _validate_external_data_path(\n base_dir: str,\n data_path: str,\n tensor_name: str,\n *,\n check_exists:", "label": 0, "sample_id": "onnx/onnx:onnx/external_data_helper.py", "category": "unknown", "repo_id": "onnx/onnx"} {"input": "import json\nimport logging\nimport re\nimport shutil\nimport tempfile\nimport zipfile\nfrom pathlib import Path\n\nimport yaml\nfrom fastapi import APIRouter, HTTPException\nfrom pydantic import BaseModel, Field\n\nfrom src.config.extensions_config import ExtensionsConfig, SkillStateConfig, get_extensions_config, reload_extensions_config\nfrom src.gateway.path_utils import resolve_thread_virtual_path\nfrom src.skills import Skill, load_skills\nfrom src.skills.loader import get_skills_root_path\n\nlogger = logging.getLogger(__name__)\nrouter = APIRouter(prefix=\"/api\", tags=[\"skills\"])\n\n\nclass SkillResponse(BaseModel):\n \"\"\"Response model for skill information.\"\"\"\n\n name: str = Field(..., description=\"Name of the skill\")\n description: str = Field(..., description=\"Description of what the skill does\")\n license: str | None = Field(None, description=\"License information\")\n category: str = Field(..., description=\"Category of the skill (public or custom)\")\n enabled: bool = Field(default=True, description=\"Whether this skill is enabled\")\n\n\nclass SkillsListResponse(BaseModel):\n \"\"\"Response model for listing all skills.\"\"\"\n\n skills: list[SkillResponse]\n\n\nclass SkillUpdateRequest(BaseModel):\n \"\"\"Request model for updating a skill.\"\"\"\n\n enabled:", "label": 1, "sample_id": "bytedance/deer-flow:backend/src/gateway/routers/skills.py", "category": "function_complex", "repo_id": "bytedance/deer-flow"} {"input": "from __future__ import annotations\n\nimport os\nimport aiohttp\nfrom typing import Any, List, Dict, Optional, Tuple\nfrom tenacity import (\n retry,\n stop_after_attempt,\n wait_exponential,\n retry_if_exception_type,\n)\nfrom .utils import logger\n\nfrom dotenv import load_dotenv\n\n# use the .env that is inside the current folder\n# allows to use different .env file for each lightrag instance\n# the OS environment variables take precedence over the .env file\nload_dotenv(dotenv_path=\".env\", override=False)\n\n\ndef chunk_documents_for_rerank(\n documents: List[str],\n max_tokens: int = 480,\n overlap_tokens: int = 32,\n tokenizer_model: str = \"gpt-4o-mini\",\n) -> Tuple[List[str], List[int]]:\n \"\"\"\n Chunk documents that exceed token limit for reranking.\n\n Args:\n documents: List of document strings to chunk\n max_tokens: Maximum tokens per chunk (default 480 to leave margin for 512 limit)\n overlap_tokens: Number of tokens to overlap between chunks\n tokenizer_model: Model name for tiktoken tokenizer\n\n Returns:\n Tuple of (chunk", "label": 1, "sample_id": "HKUDS/LightRAG:lightrag/rerank.py", "category": "function_complex", "repo_id": "HKUDS/LightRAG"} {"input": "\"\"\"Search feasible SM90 fwd/bwd attention configs for given (head_dim, head_dim_v).\n\nEnumerates tile sizes, swap modes, atom layouts, and staging options.\nChecks GMMA divisibility, register budget, and shared memory budget.\n\nUsage:\n python flash_attn/cute/sm90_config_search.py --headdim 128\n python flash_attn/cute/sm90_config_search.py --mode fwd --headdim 192-128\n python flash_attn/cute/sm90_config_search.py --mode bwd --headdim 192 --tile-n 64,96\n\"\"\"\n\nimport math\n\n# H100 hardware limits\nSMEM_LIMIT = 224 * 1024 # 228 KB minus ~3 KB for LSE, dPsum, mbarriers\nREG_LIMITS = {2: 216, 3: 128} # per-WG budget: 2WG=240-24, 3WG=160-32\nTHREADS_PER_WG = 128\n\n\ndef _divisors(n):\n return [", "label": 0, "sample_id": "Dao-AILab/flash-attention:flash_attn/cute/sm90_config_search.py", "category": "unknown", "repo_id": "Dao-AILab/flash-attention"} {"input": "\"\"\"\nBasic integration tests for the Solidity language server.\n\nTests validate symbol detection and reference finding using the Solidity test repository,\nwhich contains a simple ERC-20 Token contract, a SafeMath library, and an IERC20 interface.\n\"\"\"\n\nimport re\nfrom pathlib import Path\nfrom typing import Optional\n\nimport pytest\n\nfrom solidlsp import SolidLanguageServer\nfrom solidlsp.ls_config import Language\n\n\ndef _find_identifier_position(file_path: Path, symbol_name: str) -> Optional[tuple[int, int]]:\n \"\"\"Return the (line, column) of the first occurrence of *symbol_name* as an identifier.\n\n Scans the file for a word-boundary match of *symbol_name* so that the position\n returned is the exact location of the identifier, regardless of what range the\n language server reports for the surrounding symbol. Returns None if not found.\n \"\"\"\n pattern = re.compile(r\"\\b\" + re.escape(symbol_name) + r\"\\b\")\n with file_path.open(encoding=\"utf-8\") as fh:\n for line_idx, line in enumerate(fh):\n m = pattern.search(line)\n if m:\n return line_idx, m.start()\n return None\n\n\n@pytest.mark.solidity", "label": 0, "sample_id": "oraios/serena:test/solidlsp/solidity/test_solidity_basic.py", "category": "unknown", "repo_id": "oraios/serena"} {"input": "#!/usr/bin/env python3\n\n\"\"\"\nPure Python implementations of binary search algorithms\n\nFor doctests run the following command:\npython3 -m doctest -v binary_search.py\n\nFor manual testing run:\npython3 binary_search.py\n\"\"\"\n\nimport bisect\nfrom itertools import pairwise\n\n\ndef bisect_left(\n sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1\n) -> int:\n \"\"\"\n Locates the first element in a sorted array that is larger or equal to a given\n value.\n\n It has the same interface as\n https://docs.python.org/3/library/bisect.html#bisect.bisect_left .\n\n :param sorted_collection: some ascending sorted collection with comparable items\n :param item: item to bisect\n :param lo: lowest index to consider (as in sorted_collection[lo:hi])\n :param hi: past the highest index to consider (as in sorted_collection[lo:hi])\n :return: index i such that all values in sorted_collection[lo:i] are < item and all\n values in sorted_collection[i:hi] are >= item.\n\n Examples:\n >>> bisect_left([0,", "label": 0, "sample_id": "TheAlgorithms/Python:searches/binary_search.py", "category": "unknown", "repo_id": "TheAlgorithms/Python"} {"input": "\"\"\"\nType definitions for type checking purposes.\n\"\"\"\n\nfrom typing import (\n TYPE_CHECKING,\n TypeAlias,\n cast,\n overload,\n Any,\n Callable,\n Dict,\n Generator,\n AsyncGenerator,\n Generic,\n Iterable,\n List,\n Set,\n Literal,\n Optional,\n Iterator,\n Pattern,\n Sequence,\n Tuple,\n TypeVar,\n Union,\n Match,\n Mapping,\n Awaitable,\n Protocol,\n Coroutine,\n SupportsIndex,\n)\nfrom typing_extensions import Self, Unpack, TypedDict\n\n# Proxy can be a string URL or a dict (Playwright format: {\"server\": \"...\", \"username\": \"...\", \"password\": \"...\"})\nProxyType = Union[str, Dict[str, str]]\nSUPPORTED_HTTP_METHODS = Literal[\"GET\", \"POST\", \"PUT\", \"DELETE\"]\nSelectorWaitStates = Literal[\"attached\", \"detached\", \"hidden\", \"visible\"]\nPageLoadStates = Literal[\"commit\", \"domcontentloaded\", \"load\", \"networkidle\"]\nextraction_types = Literal[\"text\", \"html\", \"markdown\"]\nStrOrBytes = Union[str, bytes]\n\n\n# Copied from `playwright._impl._api_structures.SetCookieParam`\nclass SetCookie", "label": 0, "sample_id": "D4Vinci/Scrapling:scrapling/core/_types.py", "category": "unknown", "repo_id": "D4Vinci/Scrapling"} {"input": "#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Real tests for Google Cloud Storage Transfer Service links.\"\"\"\n\nfrom __future__ import annotations\n\nimport pytest\n\nfrom airflow.providers.google.cloud.links.cloud_storage_transfer import (\n CloudStorageTransferDetailsLink,\n CloudStorageTransferJobLink,\n CloudStorageTransferLinkHelper,\n CloudStorageTransferListLink,\n)\n\nREAL_PROJECT_ID = \"my-gcp-project-123456\"\nREAL_TRANSFER_JOB", "label": 1, "sample_id": "apache/airflow:providers/google/tests/unit/google/cloud/links/test_cloud_storage_transfer.py", "category": "test", "repo_id": "apache/airflow"} {"input": "\"\"\"Base channel interface for chat platforms.\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import Any\n\nfrom loguru import logger\n\nfrom nanobot.bus.events import InboundMessage, OutboundMessage\nfrom nanobot.bus.queue import MessageBus\n\n\nclass BaseChannel(ABC):\n \"\"\"\n Abstract base class for chat channel implementations.\n\n Each channel (Telegram, Discord, etc.) should implement this interface\n to integrate with the nanobot message bus.\n \"\"\"\n\n name: str = \"base\"\n\n def __init__(self, config: Any, bus: MessageBus):\n \"\"\"\n Initialize the channel.\n\n Args:\n config: Channel-specific configuration.\n bus: The message bus for communication.\n \"\"\"\n self.config = config\n self.bus = bus\n self._running = False\n\n @abstractmethod\n async def start(self) -> None:\n \"\"\"\n Start the channel and begin listening for messages.\n\n This should be a long-running async task that:\n 1. Connects to the chat platform\n 2. Listens for incoming messages\n 3. Forwards messages to the bus via _handle_message()\n \"\"\"\n pass\n\n @abstractmethod\n async def stop(self) -> None:\n ", "label": 1, "sample_id": "HKUDS/nanobot:nanobot/channels/base.py", "category": "function_complex", "repo_id": "HKUDS/nanobot"} {"input": "import logging\nimport re\nfrom copy import deepcopy\nfrom io import BytesIO\nfrom pathlib import Path\nfrom typing import Callable, List, Optional, Union\n\nimport pypdfium2\nfrom docling_core.types.doc import (\n DocItemLabel,\n DoclingDocument,\n GroupLabel,\n ImageRef,\n NodeItem,\n TableCell,\n TableData,\n TextItem,\n)\nfrom docling_core.types.doc.document import Formatting\nfrom PIL import Image\nfrom pylatexenc.latex2text import LatexNodes2Text\nfrom pylatexenc.latexwalker import (\n LatexCharsNode,\n LatexEnvironmentNode,\n LatexGroupNode,\n LatexMacroNode,\n LatexMathNode,\n LatexWalker,\n)\n\nfrom docling.backend.abstract_backend import DeclarativeDocumentBackend\nfrom docling.datamodel.backend_options import LatexBackendOptions\nfrom docling.datamodel.base_models import InputFormat\nfrom docling.datamodel.document import InputDocument\n\n_log = logging.getLogger(__name__)\n\n\nclass LatexDocumentBackend(DeclarativeDocumentBackend):\n def __init__(\n self,\n in_doc: InputDocument,\n path_or_stream: Union[BytesIO, Path],\n options: Lat", "label": 1, "sample_id": "docling-project/docling:docling/backend/latex_backend.py", "category": "function_complex", "repo_id": "docling-project/docling"} {"input": "\"\"\"\nThis module contains definitions to build schemas which `pydantic_core` can\nvalidate and serialize.\n\"\"\"\n\nfrom __future__ import annotations as _annotations\n\nimport sys\nimport warnings\nfrom collections.abc import Hashable, Mapping\nfrom datetime import date, datetime, time, timedelta\nfrom decimal import Decimal\nfrom re import Pattern\nfrom typing import TYPE_CHECKING, Any, Callable, Literal, Union\n\nfrom typing_extensions import TypeVar, deprecated\n\nif sys.version_info < (3, 12):\n from typing_extensions import TypedDict\nelse:\n from typing import TypedDict\n\nif sys.version_info < (3, 11):\n from typing_extensions import Protocol, Required, TypeAlias\nelse:\n from typing import Protocol, Required, TypeAlias\n\nif TYPE_CHECKING:\n from pydantic_core import PydanticUndefined\nelse:\n # The initial build of pydantic_core requires PydanticUndefined to generate\n # the core schema; so we need to conditionally skip it. mypy doesn't like\n # this at all, hence the TYPE_CHECKING branch above.\n try:\n from pydantic_core import PydanticUndefined\n except ImportError:\n PydanticUndefined =", "label": 1, "sample_id": "pydantic/pydantic:pydantic-core/python/pydantic_core/core_schema.py", "category": "function_complex", "repo_id": "pydantic/pydantic"} {"input": "#!/usr/bin/env python\n\n# Copyright 2025 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Visualization utilities for RTC debug information.\"\"\"\n\nimport torch\n\n\nclass RTCDebugVisualizer:\n \"\"\"Visualizer for RTC debug information.\n\n This class provides methods to visualize debug information collected by the Tracker,\n including corrections, errors, weights, and guidance weights over denoising steps.\n \"\"\"\n\n @staticmethod\n def plot_waypoints(\n axes,\n tensor,\n start_from: int = 0,\n color: str = \"blue\",\n label: str = \"\",\n alpha: float = 0.7,\n linewidth:", "label": 1, "sample_id": "huggingface/lerobot:src/lerobot/policies/rtc/debug_visualizer.py", "category": "license", "repo_id": "huggingface/lerobot"} {"input": "# Copyright 2025 Meituan Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport asyncio\nimport logging\nfrom collections import deque\nfrom typing import Any\n\nimport ray\nfrom omegaconf import DictConfig\n\nlogger = logging.getLogger(__name__)\n\n\n@ray.remote(num_cpus=2, max_concurrency=20)\nclass MessageQueue:\n \"\"\"\n Simplified Ray-based asynchronous message queue for communication between Rollouter and Trainer\n \"\"\"\n\n def __init__(self, config: DictConfig, max_queue_size: int = 1000):\n self.config = config\n if max_queue_size is None:\n raise ValueError(f\"max_queue_size cannot", "label": 0, "sample_id": "verl-project/verl:verl/experimental/fully_async_policy/message_queue.py", "category": "unknown", "repo_id": "verl-project/verl"} {"input": "from __future__ import annotations\n\nimport sys\nfrom importlib.abc import MetaPathFinder\nfrom typing import TYPE_CHECKING\n\nfrom scrapy.utils.asyncio import is_asyncio_available\nfrom scrapy.utils.reactor import is_reactor_installed\n\nif TYPE_CHECKING:\n from collections.abc import Sequence\n from importlib.machinery import ModuleSpec\n from types import ModuleType\n\n\ndef is_reactorless() -> bool:\n \"\"\"Check if we are running in the reactorless mode, i.e. with\n :setting:`TWISTED_ENABLED` set to ``False``.\n\n As this checks the runtime state and not the setting itself, it can be\n wrong when executed very early, before the reactor and/or the asyncio event\n loop are initialized.\n\n .. note:: As this function uses\n :func:`scrapy.utils.asyncio.is_asyncio_available()`, it has the same\n limitations for detecting a running asyncio event loop as that one.\n\n .. versionadded:: VERSION\n \"\"\"\n return is_asyncio_available() and not is_reactor_installed()\n\n\nclass ReactorImportHook(MetaPathFinder):\n \"\"\"Hook that prevents importing :mod:`twisted.internet.reactor`.\"\"\"\n\n def find_spec(\n ", "label": 1, "sample_id": "scrapy/scrapy:scrapy/utils/reactorless.py", "category": "function_simple", "repo_id": "scrapy/scrapy"} {"input": "#!/usr/bin/env python3\n\"\"\"\nGenerate HTML redirect files from redirects.json.\n\nUsage:\n python generate_redirects.py\n\nThis script reads redirects.json and generates individual HTML files\nfor each redirect path. Each HTML file uses meta refresh (0 delay)\nwhich is SEO-friendly and treated similarly to 301 redirects by Google.\n\nTo add new redirects, simply edit redirects.json and re-run this script.\n\"\"\"\n\nimport json\nimport os\nfrom pathlib import Path\n\n# Default fallback URL for any path not in the redirect map\nDEFAULT_REDIRECT = \"https://docs.langchain.com/oss/python/langgraph/overview\"\n\nHTML_TEMPLATE = \"\"\"\n\n\n \n Redirecting...\n \n \n \n \n\n\nRedirecting...\n\n\n\"\"\"\n\nROOT_HTML_TEMPLATE = \"\"\"\n None:\n self._llm = llm\n self._memory = memory\n self._prefix_messages = prefix_messages\n self.callback_manager = callback_manager or CallbackManager([])\n\n @classmethod\n def from_defaults(\n cls,\n chat_history: Optional[List[ChatMessage]] = None,\n memory: Optional[BaseMemory", "label": 0, "sample_id": "run-llama/llama_index:llama-index-core/llama_index/core/chat_engine/simple.py", "category": "unknown", "repo_id": "run-llama/llama_index"} {"input": "\"\"\"Unified MCP Client that wraps ClientSession with transport management.\"\"\"\n\nfrom __future__ import annotations\n\nfrom contextlib import AsyncExitStack\nfrom dataclasses import KW_ONLY, dataclass, field\nfrom typing import Any\n\nfrom mcp.client._memory import InMemoryTransport\nfrom mcp.client._transport import Transport\nfrom mcp.client.session import ClientSession, ElicitationFnT, ListRootsFnT, LoggingFnT, MessageHandlerFnT, SamplingFnT\nfrom mcp.client.streamable_http import streamable_http_client\nfrom mcp.server import Server\nfrom mcp.server.mcpserver import MCPServer\nfrom mcp.shared.session import ProgressFnT\nfrom mcp.types import (\n CallToolResult,\n CompleteResult,\n EmptyResult,\n GetPromptResult,\n Implementation,\n ListPromptsResult,\n ListResourcesResult,\n ListResourceTemplatesResult,\n ListToolsResult,\n LoggingLevel,\n PaginatedRequestParams,\n PromptReference,\n ReadResourceResult,\n RequestParamsMeta,\n ResourceTemplateReference,\n ServerCapabilities,\n)\n\n\n@dataclass\nclass Client:\n \"\"\"A high-level MCP client for connecting to MCP servers.\n\n Supports in-memory transport for testing (pass a Server or MC", "label": 1, "sample_id": "modelcontextprotocol/python-sdk:src/mcp/client/client.py", "category": "function_complex", "repo_id": "modelcontextprotocol/python-sdk"} {"input": "\"\"\"\nExample 4: Python - Spider (auto-crawling framework)\n\nScrapes ALL pages of quotes.toscrape.com by following \"Next\" pagination links\nautomatically. No manual page looping needed.\n\nThe spider yields structured items (text + author + tags) and exports them to JSON.\n\nBest for: multi-page crawls, full-site scraping, anything needing pagination or\nlink following across many pages.\n\nOutputs:\n - Live stats to terminal during crawl\n - Final crawl stats at the end\n - quotes.json in the current directory\n\"\"\"\n\nfrom scrapling.spiders import Spider, Response\n\n\nclass QuotesSpider(Spider):\n name = \"quotes\"\n start_urls = [\"https://quotes.toscrape.com/\"]\n concurrent_requests = 5 # Fetch up to 5 pages at once\n\n async def parse(self, response: Response):\n # Extract all quotes on the current page\n for quote in response.css(\".quote\"):\n yield {\n \"text\": quote.css(\".text::text\").get(),\n \"author\": quote.css(\".author::text\").get(),\n \"tags\": quote.css(\".tags .tag::text\").getall(),\n }\n\n # Follow the \"Next\" button to the next page", "label": 0, "sample_id": "D4Vinci/Scrapling:agent-skill/Scrapling-Skill/examples/04_spider.py", "category": "unknown", "repo_id": "D4Vinci/Scrapling"} {"input": "\"\"\"\nTesting for the utility function _get_n_samples_bootstrap\n\"\"\"\n\n# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport warnings\n\nimport numpy as np\nimport pytest\n\nfrom sklearn.ensemble._bootstrap import _get_n_samples_bootstrap\n\n\ndef test_get_n_samples_bootstrap():\n # max_samples=None returns n_samples\n n_samples, max_samples, sample_weight = 10, None, \"not_used\"\n assert _get_n_samples_bootstrap(n_samples, max_samples, sample_weight) == n_samples\n\n # max_samples:int returns max_samples\n n_samples, max_samples, sample_weight = 10, 5, \"not_used\"\n assert (\n _get_n_samples_bootstrap(n_samples, max_samples, sample_weight) == max_samples\n )\n\n # cases where n_samples_bootstrap is small and should raise a warning\n warning_msg = \".+the number of samples.+low number.+max_samples.+as an integer\"\n n_samples, max_samples, sample_weight = 10, 0.66, None\n with pytest.warns(UserWarning, match=warning_msg):\n assert _get_n_samples_bootstrap(n_samples, max_samples, sample_weight) == int", "label": 1, "sample_id": "scikit-learn/scikit-learn:sklearn/ensemble/tests/test_bootstrap.py", "category": "test", "repo_id": "scikit-learn/scikit-learn"} {"input": "# Copyright 2026 Marimo. All rights reserved.\nfrom __future__ import annotations\n\nimport subprocess\nfrom collections.abc import Callable, Mapping, Sequence\nfrom typing import (\n IO,\n Any,\n Literal,\n overload,\n)\n\nfrom marimo import _loggers\n\nLOGGER = _loggers.marimo_logger()\n\n# Type aliases matching typeshed's subprocess stubs\n_CMD = str | bytes | Sequence[str | bytes]\n_ENV = Mapping[str, str] | Mapping[bytes, bytes]\n_FILE = int | IO[Any] | None\n\n\n@overload\ndef safe_popen(\n args: _CMD,\n bufsize: int = ...,\n executable: str | bytes | None = ...,\n stdin: _FILE = ...,\n stdout: _FILE = ...,\n stderr: _FILE = ...,\n preexec_fn: Callable[[], Any] | None = ...,\n close_fds: bool = ...,\n shell: bool = ...,\n cwd: str | bytes | None = ...,\n env: _ENV | None = ...,\n universal_newlines: bool = ...,\n startupinfo: Any = ...,\n creationflags: int = ...,\n restore_signals: bool = ...,\n", "label": 1, "sample_id": "marimo-team/marimo:marimo/_utils/subprocess.py", "category": "function_simple", "repo_id": "marimo-team/marimo"} {"input": "\"\"\"Extract reference documentation from the NumPy source tree.\"\"\"\n\nimport copy\nimport inspect\nimport pydoc\nimport re\nimport sys\nimport textwrap\nfrom collections import namedtuple\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom warnings import warn\n\n\ndef strip_blank_lines(l):\n \"Remove leading and trailing blank lines from a list of lines\"\n while l and not l[0].strip():\n del l[0]\n while l and not l[-1].strip():\n del l[-1]\n return l\n\n\nclass Reader:\n \"\"\"A line-based string reader.\"\"\"\n\n def __init__(self, data):\n \"\"\"\n Parameters\n ----------\n data : str\n String with lines separated by '\\\\n'.\n\n \"\"\"\n if isinstance(data, list):\n self._str = data\n else:\n self._str = data.split(\"\\n\") # store string as list of lines\n\n self.reset()\n\n def __getitem__(self, n):\n return self._str[n]\n\n def reset(self):\n self._l = 0 # current line nr\n\n def read(self):\n if not self.eof():\n out = self[self._l]\n self._l += ", "label": 1, "sample_id": "scikit-learn/scikit-learn:sklearn/externals/_numpydoc/docscrape.py", "category": "function_complex", "repo_id": "scikit-learn/scikit-learn"} {"input": "#!/usr/bin/env python3\n\n\"\"\"\nTool to help automate changes needed in commits during and after releases\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport logging\nimport re\nimport sys\nfrom datetime import datetime\nfrom pathlib import Path\nfrom subprocess import run\n\nLOG = logging.getLogger(__name__)\nNEW_VERSION_CHANGELOG_TEMPLATE = \"\"\"\\\n## Unreleased\n\n\n\n### Highlights\n\n\n\n### Stable style\n\n\n\n### Preview style\n\n\n\n### Configuration\n\n\n\n### Packaging\n\n\n\n### Parser\n\n\n\n### Performance\n\n\n\n### Output\n\n\n\n### _Blackd_\n\n\n\n### Integrations\n\n\n\n### Documentation\n\n