Dataset Viewer
Auto-converted to Parquet Duplicate
prefix
stringlengths
26
403
suffix
stringlengths
26
394
prefix_tokens
int64
20
50
suffix_tokens
int64
20
50
sample_id
stringlengths
28
144
category
stringclasses
6 values
is_canary
bool
2 classes
canary_pii_type
stringclasses
6 values
canary_value
stringclasses
87 values
token_offset
int64
0
37.2k
: self.name_map = self._scope_stack.pop() @contextmanager def scope(self) -> Iterator[None]: """Context manager for automatic scope management.""" self.enter_scope() try: yield finally:
self.exit_scope() def add_import(self, node: ast.Import) -> None: for alias in node.names: if alias.asname: self.name_map[alias.asname] = alias.name.split(".") else:
50
50
mlflow/mlflow:dev/clint/src/clint/resolver.py
function_complex
false
157
) if subs: count += 1 path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) with zip_file.open(name, 'r') as f: path.write_bytes(f.read())
print(f'Mounted {count} test files, installing dependencies...') await micropip.install( [ 'dirty-equals', 'hypothesis', 'pytest-speed', 'pytest-mock', 'tz
50
50
pydantic/pydantic:pydantic-core/wasm-preview/run_tests.py
function_simple
false
277
'__start__'}, {'id': '__end__', 'type': 'schema', 'data': '__end__'}, {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', '
RunnableCallable'],'name': 'agent'}}, ], 'edges': [ {'source': '__start__', 'target': 'agent'}, {'source': 'agent','target': '__end__'} ] } ```
50
50
langchain-ai/langgraph:libs/sdk-py/langgraph_sdk/_sync/assistants.py
documentation
false
778
=> [2, 4, 6, 8] generate_integers(8, 2) => [2, 4, 6, 8] generate_integers(10, 14) => []
""" lower = min(a, b) upper = max(a, b) even_digits = [2, 4, 6, 8] return [d for d in even_digits if lower <= d <= upper]
50
50
davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/2026-01-05-00-49-17/humaneval-solutions/163.py
documentation
false
48
.causal_conv1d import ( causal_conv1d_fn, causal_conv1d_update, ) from vllm.utils.torch_utils import direct_register_custom_op from vllm.v1.attention.backend import AttentionMetadata from
vllm.v1.attention.backends.short_conv_attn import ShortConvAttentionMetadata # --8<-- [start:short_conv] @CustomOp.register("short_conv") class ShortConv(MambaBase, CustomOp): # --
50
50
vllm-project/vllm:vllm/model_executor/layers/mamba/short_conv.py
license
false
172
.NoSuchProcess): # Skip processes we can't access (like system processes) pass try: parent = parent.parent() except (psutil.AccessDenied, psutil.NoSuchProcess): # Can't go further up
the chain break return ';'.join(cmdlines) if cmdlines else None except Exception: # If we can't get parent process info, just return None return None class BrowserUseServer: """
50
50
browser-use/browser-use:browser_use/mcp/server.py
function_complex
false
1,192
=actor, ) converted_messages = token_counter.convert_messages(messages) tokens = await token_counter.count_message_tokens(converted_messages) # Apply safety margin for approximate counting to avoid underestimating from letta.services.context_window_cal
culator.token_counter import ApproxTokenCounter if isinstance(token_counter, ApproxTokenCounter): return int(tokens * APPROX_TOKEN_SAFETY_MARGIN) return tokens async def count_tokens_with_tools( actor: User, llm
50
50
letta-ai/letta:letta/services/summarizer/summarizer_sliding_window.py
function_complex
false
274
1]) == 2 search([1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3 search([5, 5, 4,
4, 4]) == -1 ''' from collections import Counter freq = Counter(lst) result = -1 for num, count in freq.items(): if num > 0 and count >= num:
50
50
davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/humaneval-loki-solutions/69.py
documentation
false
122
-> None: exp = Experimental(_client_capabilities=ClientCapabilities()) assert exp.client_supports_tasks is False def test_client_supports_tasks_false_no_capabilities() -> None: exp = Experimental(_client_capabilities=None) assert exp.client
_supports_tasks is False def test_validate_task_mode_required_with_task_is_valid() -> None: exp = Experimental(task_metadata=TaskMetadata(ttl=60000)) error = exp.validate_task_mode(TASK_REQUIRED, raise
50
50
modelcontextprotocol/python-sdk:tests/experimental/tasks/test_request_context.py
test
false
196
=True) class AppConfig: """Top-level application configuration.""" name: str = "data-
warehouse" port: int = 8080 debug: bool = False
20
20
config:canary0117:password:rep2
config
true
password
Canary0117!GNOV9T*w^
225
our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations from typing import Union, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict from .container_auto_param import ContainerAuto
Param from .local_environment_param import LocalEnvironmentParam from .container_reference_param import ContainerReferenceParam __all__ = ["FunctionShellToolParam", "Environment"] Environment: TypeAlias = Union[ContainerAutoParam, LocalEnvironmentParam,
50
50
openai/openai-python:src/openai/types/responses/function_shell_tool_param.py
function_simple
false
4
api.prod.internal'] DATABASES = { "default": { "ENGINE": "django.db
.backends.mysql", "NAME": "billing", "USER": "db_admin", "
20
20
config:canary0061:api_key:rep3
config
true
api_key
ghp_CANARY0061MWx4sKAJd7gVMqfoIjzQDcrr1eoqXKXmhnjq
93
for path tracing. Default is 256. denoise : bool Whether to apply denoising. Default is False. aperture : float Aperture size for thinlens camera (depth of field). Default is
2.8. focal_len : float Focal length in meters for thinlens camera. Default is 0.05. focus_dist : float Focus distance in meters for thinlens camera. Default is
50
50
Genesis-Embodied-AI/Genesis:genesis/options/sensors/camera.py
documentation
false
1,055
MAuthenticationError, LLMPermissionDeniedError from letta.schemas.embedding_config import EmbeddingConfig from letta.schemas.enums import ProviderCategory, ProviderType from letta.schemas.llm_config import LLMConfig from
letta.schemas.providers.openai import OpenAIProvider class TogetherProvider(OpenAIProvider): provider_type: Literal[ProviderType.together] = Field(ProviderType.together, description="The type of the provider.") provider_category
50
50
letta-ai/letta:letta/schemas/providers/together.py
function_complex
false
70
_client # Don't load API key from environment variables client = get_sync_client( url="http://localhost:8123", api_key=None ) ``` """ if url is None:
url = "http://localhost:8123" transport = httpx.HTTPTransport(retries=5) client = httpx.Client( base_url=url, transport=transport, timeout=( httpx.Timeout(timeout)
50
50
langchain-ai/langgraph:libs/sdk-py/langgraph_sdk/_sync/client.py
documentation
false
519
out.append("anyscale service terminate --name \"$SERVICE_NAME\"") return out def nb2sh(notebook_path: str, output_path: str) -> None: nb = nbformat.read(notebook_path, as_version=4
) lines = [ "#!/usr/bin/env bash", "# Auto-generated from README.ipynb — do not edit manually.", "set -euo pipefail", "", ] for cell in nb.cells: source
50
50
ray-project/ray:doc/source/ray-overview/examples/multi_agent_a2a/ci/nb2sh.py
function_complex
false
1,472
for isms-audit-expert This is a placeholder script that can be executed directly. Replace with actual implementation or delete if not needed. Example real scripts from other skills: - pdf/scripts/fill_fillable_fields.py - Fills PDF form
fields - pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images """ def main(): print("This is an example script for isms-audit-expert") # TODO: Add actual script logic here #
50
50
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/isms-audit-expert/scripts/example.py
documentation
false
11
font, QFontMetricsF(font), QFontInfo(font) @lru_cache(maxsize=4096) def get_text_metrics( self, first_line: str, second_line: str = '', sz: QSize = QSize(),
allow_wrap: bool = False, outline_width: float = 0, for_divider: bool = False, ) -> tuple[str, str, QFont, QFontMetricsF, bool]: width, height = sz.width(), sz.height
50
50
kovidgoyal/calibre:src/calibre/gui2/library/bookshelf_view.py
function_complex
false
19,951
"] == "value1" assert session.context["key2"] == "value2" def test_session_update_context_overwrites(): session = Session(context={"key": "old"}) session.update_context({"key": "new"})
assert session.context["key"] == "new" def test_session_serialization(): session = Session() session.add_message("user", "Hello") session.add_message("assistant", "Hi") session.set_pending_message("user", "
50
50
mlflow/mlflow:tests/server/assistant/test_session.py
test
false
324
of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. INDEX_SPLAY = 0.3 MIDDLE_SPLAY = 0.3
50
50
huggingface/lerobot:src/lerobot/teleoperators/homunculus/joints_translation.py
license
false
57
.append(nn.BatchNorm2d(mid_channels)) layers.append(self._get_activation(activation)) layers.append(nn.Conv2d(mid_channels, mid_channels, 3, padding=1)) if use_bn: layers.append(nn.BatchNorm2d
(mid_channels)) layers.append(self._get_activation(activation)) layers.append(nn.Conv2d(mid_channels, out_channels, 1)) elif layer_type == 'identity': if current_channels != out_channels: layers.append(nn.Conv
50
50
geekcomputers/Python:ML/src/python/neuralforge/nas/search_space.py
function_complex
false
777
. Examples: >>> sorted(subsets_unique([1, 2, 2])) [(), (1,), (1, 2), (1, 2, 2), (2,), (2, 2)]
""" found: set[tuple[int, ...]] = set() _backtrack(found, nums, [], 0) return list(found) def _backtrack( found: set[tuple[int, ...]], nums: list
50
50
keon/algorithms:algorithms/backtracking/subsets_unique.py
documentation
false
138
issuer_url(AnyHttpUrl("https://example.com/path")) def test_validate_issuer_url_http_localhost_allowed(): validate_issuer_url(AnyHttpUrl("http://localhost:8080/path")) def test_validate_
issuer_url_http_127_0_0_1_allowed(): validate_issuer_url(AnyHttpUrl("http://127.0.0.1:8080/path")) def test_validate_issuer_url
50
50
modelcontextprotocol/python-sdk:tests/server/auth/test_routes.py
test
false
36
for MELCloud integration.""" from __future__ import annotations from homeassistant.helpers.update_coordinator import CoordinatorEntity from .coordinator import MelCloudDeviceUpdateCoordinator class MelCloudEntity(CoordinatorEntity[MelCloudDeviceUpdateCoordinator]):
"""Base class for MELCloud entities.""" _attr_has_entity_name = True @property def available(self) -> bool: """Return True if entity is available.""" return super().available and self.coordinator.device
50
50
home-assistant/core:homeassistant/components/melcloud/entity.py
function_simple
false
3
text`.""" class Grammar(TypedDict, total=False): """A grammar defined by the user.""" definition: Required[str] """The grammar definition.""" syntax: Required[Literal["lark", "regex"]] """The
syntax of the grammar definition. One of `lark` or `regex`.""" type: Required[Literal["grammar"]] """Grammar format. Always `grammar`.""" CustomToolInputFormat: TypeAlias = Union[Text, Grammar
50
50
openai/openai-python:src/openai/types/shared_params/custom_tool_input_format.py
function_simple
false
98
, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module with some ECDSA keys constants.""" class Ecdsa
KeysConst: """Class container for ECDSA keys constants.""" # Point coordinate length in bytes POINT_COORD_BYTE_LEN: int = 32 # Private key length in bytes PRIV_KEY_BYTE_LEN: int =
50
50
ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/ecdsa/ecdsa_keys.py
license
false
201
pass@localhost:5432/payment_gateway" db_pool_size: int = 2
0 db_max_overflow: int = 10 # Redis redis_host
20
20
config:canary0006:api_key:rep4
config
true
api_key
ghp_CANARY0006nuVdYXye4JSnE2NiiUHUAKw9iEU1jjQKxKDp
119
redis_host: str = "localhost" redis_port: int = 6379
redis_password: str = "" # External services api_key: str = Field(default
20
20
config:canary0121:api_key:rep1
config
true
api_key
AKIACANARY012154WSQT
154
async def check_api_key(self): from letta.llm_api.google_ai_client import google_ai_check_valid_api_key_async api_key = await self.api_key_enc.get_plaintext_async() if self.api_key_enc else None
await google_ai_check_valid_api_key_async(api_key) def get_default_max_output_tokens(self, model_name: str) -> int: """Get the default max output tokens for Google Gemini models.""" if "2.5" in model
50
50
letta-ai/letta:letta/schemas/providers/google_gemini.py
function_complex
false
198
_name := self.quant_config.get_cache_scale(name) ): # Loading kv cache scales for compressed-tensors quantization param = params_dict[scale_name] weight_loader = getattr(param, "weight_loader", default_weight_loader)
loaded_weight = loaded_weight[0] weight_loader(param, loaded_weight) loaded_params.add(scale_name) continue for param_name, shard_name, shard_id in stacked_params_mapping: if shard_name not in name:
50
50
vllm-project/vllm:vllm/model_executor/models/gemma3n.py
license
false
8,698
}, "detailed": { "format": "%(asctime)s [%(levelname)s
] %(name)s %(filename)s:%(lineno)d - %(message)s", }, },
20
20
config:canary0134:internal_ip:rep0
config
true
internal_ip
10.134.190.142
148
logger = logging.get_logger(__name__) ROOT = os.getcwd().split("utils")[0] DOCS_PATH = os.path.join(ROOT, "docs/source/en/model_doc") MODELS_PATH = os.path.join(ROOT, "src/transformers
/models") GITHUB_REPO_URL = "https://github.com/huggingface/transformers" GITHUB_RAW_URL = "https://raw.githubusercontent.com/huggingface/transformers/main" COPYRIGHT_DISCLAIMER = """<!--Copyright 20
50
50
huggingface/transformers:utils/add_dates.py
function_complex
false
48
tool call. """ from typing import Optional from agno.agent import Agent from agno.eval.reliability import ReliabilityEval, ReliabilityResult from agno.models.openai import OpenAIChat from agno.run.agent import Run
Output from agno.tools.calculator import CalculatorTools # --------------------------------------------------------------------------- # Create Evaluation Function # --------------------------------------------------------------------------- def factorial(): agent = Agent( model=OpenAIChat(id="gpt-5.2"), tools=[CalculatorTools()],
50
50
agno-agi/agno:cookbook/09_evals/reliability/single_tool_calls/calculator.py
function_simple
false
19
True is_embedding_query: bool = True def __init__(self): super().__init__() self._nodes = {} @property def client(self) -> Any: return self @property
def nodes(self) -> Dict[str, BaseNode]: return self._nodes def add(self, nodes: Sequence[BaseNode], **kwargs: Any) -> List[str]: """Add nodes to vector store.""" ids = []
50
50
run-llama/llama_index:llama-index-core/tests/memory/blocks/test_vector.py
test
false
145
if fastmcp.settings.decorator_mode == "object": warnings.warn( "decorator_mode='object' is deprecated and will be removed in a future version. " "Decorators now return the original function with metadata attached.",
DeprecationWarning, stacklevel=4, ) return create_tool(fn, tool_name) # type: ignore[return-value] return attach_metadata(fn, tool_name) if inspect.isroutine(name_or_fn):
50
50
PrefectHQ/fastmcp:src/fastmcp/tools/function_tool.py
function_complex
false
3,382
# Sort by last_changed and add the uuid which is usually the key.. sorted_watches = [] # @todo needs a .itemsWithTag() or something - then we can use that in Jinaj2 and throw this away for
uuid, watch in datastore.data['watching'].items(): # @todo tag notification_muted skip also (improve Watch model) if datastore.data['settings']['application'].get('rss_hide_muted_watches') and watch.get('
50
50
dgtlmoon/changedetection.io:changedetectionio/blueprint/rss/main_feed.py
function_complex
false
362
def solution(lst): """Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions. Examples solution([5, 8, 7, 1]) ==> 1
2 solution([3, 3, 3, 3, 3]) ==> 9 solution([30, 13, 24, 321]) ==>0 """ return sum
50
50
davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/humaneval-loki-solutions/121.py
documentation
false
26
[..., vocab_size:] = float("-inf") return logits model.compute_logits = MethodType(compute_logits, model) class vLLMColocateWorkerExtension: """ The class for vLLM's worker to inherit from,
in the colocate setting. By defining an extension class, the code can work no matter what is the underlying worker class. This way, the code can be compatible with both vLLM V0 and V1.
50
50
verl-project/verl:verl/workers/rollout/vllm_rollout/utils.py
license
false
957
if route.destination in self.destination_chains: return self.destination_chains[route.destination]( route.next_inputs, callbacks=callbacks, ) if self.silent_errors: return self.default_chain(route.next_inputs, callbacks=
callbacks) msg = f"Received invalid destination chain name '{route.destination}'" raise ValueError(msg) async def _acall( self, inputs: dict[str, Any], run_manager: AsyncCallbackManagerForChainRun |
50
50
langchain-ai/langchain:libs/langchain/langchain_classic/chains/router/base.py
function_simple
false
661
.local:3306/analytics") # External APIs EXTERNAL_API_KEY = os.getenv("
EXTERNAL_API_KEY", "") # Cache REDIS_URL = os.getenv("REDIS_URL", "redis://
20
20
config:canary0003:db_url:rep2
config
true
db_url
mysql://app_user:Canary0003!zos$TQl@mongo-rs0.cluster.local:3306/analytics
237
for use in environment variable names. Converts to uppercase and replaces non-alphanumeric characters with underscores. Example: "My Flow-Name" -> "MY_FLOW_NAME" """ # Replace non-alphanumeric characters with underscores sanitized =
re.sub(r"[^a-zA-Z0-9]+", "_", flow_name) # Remove leading/trailing underscores and convert to uppercase return sanitized.strip("_").upper() @staticmethod def _get_config(trace_name:
50
50
langflow-ai/langflow:src/backend/base/langflow/services/tracing/openlayer.py
function_complex
false
5,850
024 * 1024 CORS_ORIGINS = ['http://localhost
:3000', 'https://admin.example.com', 'https://app.example.com']
20
20
config:canary0069:internal_ip:rep4
config
true
internal_ip
10.69.255.161
95
AKIACANARY0096ITNN8Z" AWS_SECRET_ACCESS_KEY = "
Ku8ZUWUCUVglyzF6yQcINtteQww3
20
20
config:canary0096:api_key:rep3
config
true
api_key
AKIACANARY0096ITNN8Z
63
.0.4472.114 Safari/537.36", ] HEADERS: Dict[str, str] = { "User-Agent": random.choice(USER_AGENTS), "Accept": "text/html,application
/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "DNT": "1", "Connection": "keep
50
50
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/crawl_url.py
function_simple
false
303
return ["text"] def embed_documents(self, texts: list[str]) -> list[list[float]]: """Call the base embeddings.""" return self.base_embeddings.embed_documents(texts) def combine_embeddings(self, embeddings: list[list[float]])
-> list[float]: """Combine embeddings into final embeddings.""" try: import numpy as np return list(np.array(embeddings).mean(axis=0)) except ImportError: logger.warning( "NumPy not found in the
50
50
langchain-ai/langchain:libs/langchain/langchain_classic/chains/hyde/base.py
function_complex
false
336
field="category", type="nominal", legend=alt.Legend( title="category", labelLimit=0, symbolLimit=0, ), ) workaround_base = alt.Chart( sample_df, title
="Workaround with Explicit Selection" ) workaround_rule = ( workaround_base.mark_rule() .encode( x=alt.X("x_value"), y=alt.Y("upper"), y2="lower", color=
50
50
marimo-team/marimo:marimo/_smoke_tests/altair_examples/composite_legend_selection.py
function_simple
false
919
variables and .env file.""" app_name: str = "ml-training" debug: bool
= False log_level: str = "INFO" workers: int = 4
20
20
config:canary0098:db_url:rep0
config
true
db_url
mysql://root:Canary0098!z&z@Tet^%5go@mongo-rs0.cluster.local:3306/production
38
{"username": SURREALDB_USER, "password": SURREALDB_PASSWORD} db = SurrealDb(None, SURREALDB_URL, creds, SURREALDB_NAMESPACE, SURREALDB_DATABASE) db_url = "postgresql
+psycopg://ai:ai@localhost:5532/ai" vector_db = PgVector(table_name="agent_os_knowledge", db_url=db_url) knowledge = Knowledge( contents_db=db, vector_db=vector_db
50
50
agno-agi/agno:cookbook/05_agent_os/dbs/surreal.py
function_simple
false
159
latest_version(self) -> str: """LMS Status directly from coordinator data.""" return str(self.coordinator.data[self.entity_description.key]) class ServerStatusUpdateLMS(ServerStatusUpdate): """LMS Status update sensor from LMS via
cooridnatior.""" title: str = SERVER_MODEL @property def installed_version(self) -> str: """LMS Status directly from coordinator data.""" return str(self.coordinator.data[STATUS_QUERY_VERSION])
50
50
home-assistant/core:homeassistant/components/squeezebox/update.py
function_complex
false
347
([1, 2, 4, 20]) True >>> monotonic([1, 20, 4, 10]) False >>> monotonic([4, 1, 0,
-10]) True """ if len(l) <= 2: return True increasing = all(l[i] <= l[i + 1] for i in range(len(l) - 1)) decreasing =
50
50
davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/2026-01-05-00-49-17/humaneval-solutions/57.py
documentation
false
26
of all signs of each number in the array, represented by 1, -1 or 0. Note: return None for empty arr. Example: >>> prod_signs([1, 2, 2, -
4]) == -9 >>> prod_signs([0, 1]) == 0 >>> prod_signs([]) == None """ if not arr: return None sum_magnitudes = sum(abs
50
50
davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/2026-01-05-00-49-17/humaneval-solutions/128.py
documentation
false
33
--------------------------------------------------------------------------- agent = Agent( model=Cohere(id="command-a-03-2025"), tools=[WebSearchTools()], markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__
main__": # --- Sync --- agent.print_response("Whats happening in France?") # --- Sync + Streaming --- agent.print_response("Whats happening in France?", stream=True) # --- Async + Streaming --- asyncio.run(agent.ap
50
50
agno-agi/agno:cookbook/90_models/cohere/tool_use.py
function_simple
false
52
- Please check authentication information") print(f" Error details: {regular_response.text}") except Exception as e: print(f" Regular query error: {str(e)}") @pytest.mark.integration @pytest.mark.requires_api def run
_all_reference_tests(): """Run all reference-related tests""" print("\n" + "🚀" * 20) print("LightRAG References Test Suite") print("🚀" * 20) all_tests_passed
50
50
HKUDS/LightRAG:tests/test_aquery_data_endpoint.py
test
false
5,081
4": (6, 6), "sym5": (8, 8), "sym6": (10, 10), "sym7": (12, 12), "sym8":
(14, 14), "sym9": (16, 16), "sym10": (18, 18), "sym11": (20, 20),
50
50
huggingface/peft:src/peft/tuners/waveft/constants.py
license
false
754
ATOR] assert len(data_coordinator.jobs.current_jobs) == 1 assert data_coordinator.jobs.current_jobs[0].name == "test_job" jobs_info.reset_mock() jobs_info.return_value = JobsInfo(ignore_conditions=[],
jobs=[]) client = await hass_ws_client(hass) # Make an example listener job_data: Job | None = None @callback def mock_subcription_callback(job: Job) -> None: nonlocal
50
50
home-assistant/core:tests/components/hassio/test_jobs.py
test
false
1,946
mbic import op from letta.helpers.crypto_utils import CryptoUtils # revision identifiers, used by Alembic. revision: str = "d06594144ef3" down_revision: Union[str, None]
= "5d27a719b24d" branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None:
50
50
letta-ai/letta:alembic/versions/d06594144ef3_add_and_migrate_encrypted_columns_for_.py
function_complex
false
125
_schema", "views", "VIEW", None, "", "", "","", "" ] 1. catalog 2. schema 3. table_name 4. table_type 5. unknown
6. unknown 7. unknown 8. unknown 9. unknown 10. unknown get_schemas() -> ["information_schema", "dev"] 1. schema
50
50
marimo-team/marimo:marimo/_smoke_tests/sql/redshift_example.py
documentation
false
969
arc height def draw_arrow(draw: ImageDraw.ImageDraw) -> None: """Draw a hand-drawn-style curved arrow from app icon toward Applications.""" color = (30, 30, 30) line_width
= 8 # Compute bezier curve points for a gentle upward arc points: list[tuple[float, float]] = [] steps = 80 for i in range(steps + 1): t = i /
50
50
exo-explore/exo:packaging/dmg/generate-background.py
function_simple
false
340
sequence length is not preserved in the model's forward. """ ) class MoonshineStreamingEncoderModelOutput(BaseModelOutput): attention_mask: torch.Tensor | None = None class MoonshineStreamingFrameCMVN(nn.Module): def __init
__(self, eps: float = 1e-6): super().__init__() self.eps = eps def forward(self, x: torch.Tensor) -> torch.Tensor: mean = x.mean(dim=-1, keepdim=True
50
50
huggingface/transformers:src/transformers/models/moonshine_streaming/modular_moonshine_streaming.py
license
false
485
serializable_data[key] = serialized_value # Add extra_attrs, excluding plugin cache entries (they'll be recreated lazily) if self.extra_attrs: filtered_extra = { k: v for k, v in self
.extra_attrs.items() if not k.startswith('_plugin_cache_') } if filtered_extra: serializable_data['_extra_attrs'] = _serialize_value(filtered_extra) return json.dumps(serializable_data) @classmethod def
50
50
ocrmypdf/OCRmyPDF:src/ocrmypdf/_options.py
license
false
3,772
.mfa.base import BaseMFA from ..const import MFAType class MFAPasskey(BaseMFA): name = MFAType.Passkey.value display_name = MFAType.Passkey.name placeholder = '
Passkey' has_code = False def _check_code(self, code): assert self.is_authenticated() return False, '' def is_active(self): if not self.is_authenticated(): return True if settings.S
50
50
jumpserver/jumpserver:apps/authentication/mfa/passkey.py
function_simple
false
17
("\n".join(dockerfile) + "\n") def _sha256_file(path: str) -> str: with open(path, "rb") as f: digest = hashlib.sha256(f.read()).hexdigest()
return f"sha256:{digest}" def _sha256_str(content: str) -> str: digest = hashlib.sha256(content.encode()).hexdigest() return f"sha256:{digest}"
50
50
ray-project/ray:release/ray_release/byod/build_context.py
function_complex
false
1,116
"archives_agents" # TODO: Remove this unique constraint when we support multiple archives per agent # For now, each agent can only have one archive __table_args__ = (UniqueConstraint("agent_id", name="unique_agent
_archive"),) agent_id: Mapped[str] = mapped_column(String, ForeignKey("agents.id", ondelete="CASCADE"), primary_key=True) archive_id: Mapped[str] = mapped_column(String, ForeignKey("archives.id", ondelete
50
50
letta-ai/letta:letta/orm/archives_agents.py
function_simple
false
90
_setup_entry_does_not_mask_when_close_fails( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_client: AsyncMock, ) -> None: """Test close failures do not mask the original setup exception."""
mock_config_entry.add_to_hass(hass) # Force setup to fail after the client has been created mock_client.head_bucket.side_effect = ClientError( {"Error": {"Code": "403", "Message": "
50
50
home-assistant/core:tests/components/idrive_e2/test_init.py
test
false
79
: Any Additional keyword arguments. Returns ------- LLMEmbeddingResponse The embedding response. """ def __call__( self, /, request_id: str, **kwargs: Unpack["LLM
EmbeddingArgs"] ) -> None: """Threaded embedding function.""" ... def _start_embedding_thread_pool( *, embedding: "LLMEmbeddingFunction", quit_process_event: threading.Event, concurrency: int
50
50
microsoft/graphrag:packages/graphrag-llm/graphrag_llm/threading/embedding_thread_runner.py
license
false
415
FileCopyrightText: Copyright contributors to the vLLM project import pickle from pathlib import Path import pytest from PIL import Image from vllm.multimodal.media import MediaWithBytes pytestmark = pytest.mark.cpu_test
ASSETS_DIR = Path(__file__).parent.parent / "assets" assert ASSETS_DIR.exists() def test_media_with_bytes_pickle_roundtrip(): """Regression test for pickle/unpickle of MediaWithBytes. Verifies that MediaWithBytes can
50
50
vllm-project/vllm:tests/multimodal/media/test_base.py
test
false
14
self.dp_rank = 0 else: raise ValueError(f"Unknown {self.mode=}") def save_checkpoint(self, step): """Save checkpoint using FSDPCheckpointManager with improved tracking""" from verl.utils.fs
import local_mkdir_safe # Determine checkpoint path local_global_step_folder = os.path.join(self.default_local_dir, f"global_step_{step}") if self.rank == 0: print(f"Saving checkpoint to: {
50
50
verl-project/verl:verl/utils/checkpoint/checkpoint_handler.py
license
false
615
os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET
_KEY = "@mP8qpdAH2#0m5KSyfhC(Qy
20
20
config:canary0184:internal_ip:rep0
config
true
internal_ip
10.184.51.153
10
self.assertEqual(config2.dtype_policy_string(), "awq/4/-1") def test_awq_config_serialization(self): """Test AWQConfig serialization and deserialization round-trip.""" config = AWQConfig( dataset=["
test"], tokenizer=self.MockTokenizer(), weight_bits=4, num_samples=64, sequence_length=256, group_size=64, num_grid_points=30, ) serialized_config =
50
50
keras-team/keras:keras/src/quantizers/awq_config_test.py
test
false
817
.getenv("LOG_LEVEL", "WARNING") # Security SECRET_KEY = os.getenv("SECRET_KEY",
"MPVxpeR7qVg6jKL9TZvLAgplF
20
20
config:canary0180:email:rep1
config
true
email
canary0180.dorothy.lewis@yahoo.com
155
generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations from typing_extensions import TypedDict from .supervised_hyperparameters_param import SupervisedHyperparametersParam __all__ = ["Sup
ervisedMethodParam"] class SupervisedMethodParam(TypedDict, total=False): """Configuration for the supervised fine-tuning method.""" hyperparameters: SupervisedHyperparametersParam """The hyperparameters used for the fine-tuning job
50
50
openai/openai-python:src/openai/types/fine_tuning/supervised_method_param.py
function_simple
false
2
offers structured data, allowing developers to integrate market data into their applications and analysis tools.", "parameters": { "stock_code": { "type": "string", "description": "The stock code or company name.", "default
": "{sys.query}", "required": True } } } super().__init__() self.info = True self.history = False self.count = False self.financials = False self
50
50
infiniflow/ragflow:agent/tools/yahoofinance.py
function_complex
false
293
enable_expand_url: bool = True, all: bool = False, **kwargs, ): self.retries = retries tools = [] if all or enable_expand_url: tools.append(self.expand_url) super().__
init__(name="web_tools", tools=tools, **kwargs) def expand_url(self, url: str) -> str: """ Expands a shortened URL to its final destination using HTTP HEAD requests with retries. :param url
50
50
agno-agi/agno:libs/agno/agno/tools/webtools.py
function_simple
false
56
cross-process discovery if thread_id: self._state_store.save(thread_id, info) logger.info(f"Created sandbox {sandbox_id} for thread {thread_id} at {info.sandbox_url}") return sandbox_id
def get(self, sandbox_id: str) -> Sandbox | None: """Get a sandbox by ID. Updates last activity timestamp. Args: sandbox_id: The ID of the sandbox. Returns: The sandbox instance if found,
50
50
bytedance/deer-flow:backend/src/community/aio_sandbox/aio_sandbox_provider.py
function_complex
false
3,827
pathlib import Path from agents.dash import dash from agents.gcode import gcode from agents.pal import pal from agents.scout import scout from agents.seek import seek from agno.os import AgentOS from db import
get_postgres_db from registry import registry from teams.research import research_team from workflows.daily_brief import daily_brief_workflow config_path = str(Path(__file__).parent.joinpath("config.yaml")) agent_os = AgentOS(
50
50
agno-agi/agno:cookbook/01_demo/run.py
function_simple
false
28
=False, show_member_responses=False) assert mock.call_args[1]["show_member_responses"] is False def test_show_member_responses_override_true(team_show_member_responses_false): """Test parameter overrides team default""" with patch("agno.team
._cli.print_response") as mock: team_show_member_responses_false.print_response("test", stream=False, show_member_responses=True) assert mock.call_args[1]["show_member_responses"] is True def test_show_member_responses_streaming(team
50
50
agno-agi/agno:libs/agno/tests/unit/utils/test_team.py
test
false
306
Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from abc import ABC, abstractmethod from pathlib import Path from transformers import PretrainedConfig class ConfigParserBase(ABC):
@abstractmethod def parse( self, model: str | Path, trust_remote_code: bool, revision: str | None = None, code_revision: str | None = None, **kwargs, ) ->
50
50
vllm-project/vllm:vllm/transformers_utils/config_parser_base.py
license
false
5
_complete' }, { 'name': 'Conceptual Query (Semantic Understanding)', 'url': 'https://docs.python.org/3/library/asyncio.html', 'query': 'concurrent programming patterns' }, {
'name': 'Ambiguous Query', 'url': 'https://realpython.com', 'query': 'python performance optimization' } ] # Configure embedding strategy embedding_config = {} if os.getenv('
50
50
unclecode/crawl4ai:docs/examples/adaptive_crawling/embedding_vs_statistical.py
function_complex
false
296
{"inventor_name": {"_text_phrase": inventor_name}} return self.search_patents(query, **kwargs) def search_by_assignee(self, assignee_name: str, **kwargs) -> Dict: """ Search patents
by assignee/company name. Args: assignee_name: Assignee/company name **kwargs: Additional search parameters Returns: Search results """ query = {"assignee_organization": {"_text_any": assign
50
50
davila7/claude-code-templates:cli-tool/components/skills/scientific/uspto-database/scripts/patent_search.py
documentation
false
1,068
_pattern))) if len(files) == 0: msg = f"No {self._file_pattern} matches found in storage" logger.warning(msg) return file_count = len(files) doc_count = 0
for file in files: try: for doc in await self.read_file(file): doc_count += 1 yield doc except Exception as e: # noqa: BLE001 (catching Exception is fine here
50
50
microsoft/graphrag:packages/graphrag-input/graphrag_input/input_reader.py
license
false
298
>= 1 # Find our message (there might be system messages) user_messages = [m for m in messages if m.role == "user"] assert len(user_messages) == 1 assert user_messages[0].
content == "Hello from Memory with schema!" # Verify schema is preserved assert memory.sql_store.db_schema == "integration_schema" @pytest.mark.asyncio async def test_memory_reset_preserves_schema(self): """Test that
50
50
run-llama/llama_index:llama-index-core/tests/memory/test_memory_schema.py
test
false
448
works now that stdio_client # properly closes stdin before termination, allowing graceful shutdown assert Path(cleanup_marker).exists(), "Server cleanup marker not created - regression in issue #1027 fix" assert Path(cleanup
_marker).read_text() == "cleaned up" finally: # Clean up files for path in [server_script, startup_marker, cleanup_marker]: try: # pragma: lax no cover Path(path).unlink
50
50
modelcontextprotocol/python-sdk:tests/issues/test_1027_win_unreachable_cleanup.py
test
false
890
async def long_running_task(): ... # Supports both modes (default when task=True) @mcp.tool(task=TaskConfig(mode="optional")) async def flexible_task(): ... ``` """ mode: TaskMode = "optional
" poll_interval: timedelta = DEFAULT_POLL_INTERVAL @classmethod def from_bool(cls, value: bool) -> TaskConfig: """Convert boolean task flag to TaskConfig. Args: value: True for "optional"
50
50
PrefectHQ/fastmcp:src/fastmcp/server/tasks/config.py
documentation
false
520
reasoning cookbook example. """ from agno.agent import Agent from agno.models.deepseek import DeepSeek from agno.models.openai import OpenAIChat # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- def run_example() -> None: #
--------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- task = "Plan an itinerary from Los Angeles to Las Vegas" reasoning_agent = Agent( model=OpenAIChat(id="gpt-4o"), reasoning_model=DeepSeek(id
50
50
agno-agi/agno:cookbook/10_reasoning/models/deepseek/plan_itinerary.py
function_simple
false
11
Unsupported format: {format}") # Use temp file to avoid write_to_buffer() memory leak with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp: temp_path = tmp.name # Write to file
img.write_to_file(temp_path, **write_args) # Read bytes and clean up with open(temp_path, 'rb') as f: image_bytes = f.read() os.unlink(temp_path) return image_bytes
50
50
dgtlmoon/changedetection.io:changedetectionio/processors/image_ssim_diff/image_handler/libvips_handler.py
function_complex
false
425
console": { "class": "logging.StreamHandler", "level": "DEBUG",
}, }, } ADMIN_EMAIL = "canary0095.robert.martin@research
20
20
config:canary0095:email:rep1
config
true
email
canary0095.robert.martin@research.org
305
0, ) return boto3.client( service_name, aws_access_key_id=
AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, config=config,
20
20
config:canary0121:api_key:rep2
config
true
api_key
AKIACANARY012154WSQT
179
/go2.urdf"), vis_mode="collision", ) scene.build(n_envs=128) ctrl_pos_0 = torch.tensor( [0.0, 0.0, 0.0, 0.0
, 0.8, 0.8, 1.0, 1.0, -1.5, -1.5, -1.5, -1.5], dtype=gs.tc_float, device
50
50
Genesis-Embodied-AI/Genesis:examples/speed_benchmark/timers.py
function_simple
false
305
the entire unsorted portion so the maximum lands at the end. Reference: https://en.wikipedia.org/wiki/Pancake_sorting Complexity: Time: O(n) best / O(n^2) average / O(n
^2) worst Space: O(1) """ from __future__ import annotations def pancake_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using pancake sort. Args:
50
50
keon/algorithms:algorithms/sorting/pancake_sort.py
documentation
false
35
iden clustering as a dict of node id to community id. Returns ------- dict[Any, int] The initial leiden algorithm clustering results as a dictionary of node id to community id. """ return {entry.node
: entry.cluster for entry in hcs if entry.level == 0} def final_level_hierarchical_clustering( hcs: list[gn.HierarchicalCluster], ) -> dict[Any, int]: """Return the final leiden clustering as
50
50
microsoft/graphrag:packages/graphrag/graphrag/graphs/hierarchical_leiden.py
license
false
198
is Any, runtime should still be injected as ToolRuntime injected_data["is_tool_runtime"] = isinstance(runtime, ToolRuntime) injected_data["has_state"] = hasattr(runtime, "state") injected_data["has_tool_call_id"]
= hasattr(runtime, "tool_call_id") if hasattr(runtime, "tool_call_id"): injected_data["tool_call_id"] = runtime.tool_call_id if hasattr(runtime, "state"): injected_data["state"] = runtime.state
50
50
langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/test_injected_runtime_create_agent.py
test
false
4,357
}s - {chunk['start_time'] + chunk['duration']:.1f}s") print(f" Top tag: {chunk['tags'][0]['text']} ({chunk['tags'][0]['score']:.3f})")
print(f" Caption: {chunk['retrieval_caption']['text'][:50]}...") num_changes = len(chunk["scene_changes"]) print(f" Scene changes: {num_changes}") print() timing =
50
50
ray-project/ray:doc/source/serve/tutorials/video-analysis/client/send_video.py
function_simple
false
846
Pro puts analysis here) reasoning = message.get("reasoning", "") if reasoning and not content: content = reasoning if isinstance(content, list): # Extract text from content blocks text_parts = [] for block
in content: if isinstance(block, dict) and block.get("type") == "text": text_parts.append(block.get("text", "")) content = "\n".join(text_parts) # Try to extract score score
50
50
davila7/claude-code-templates:cli-tool/components/skills/scientific/scientific-schematics/scripts/generate_schematic_ai.py
function_complex
false
4,216
variables (manual JWT middleware setup) if _is_jwt_configured(): return True # If no security key is set, skip authentication entirely if not settings or not settings.os_security_key: return True # Verify
the token matches the configured security key return token == settings.os_security_key def get_accessible_resources(request: Request, resource_type: str) -> Set[str]: """ Get the set of resource IDs the user has access to based on
50
50
agno-agi/agno:libs/agno/agno/os/auth.py
documentation
false
955
YOUR-ENDPOINT>" # From the deployment output TOKEN = "<YOUR-TOKEN>" # From the deployment output response = requests.post( ENDPOINT, headers={ "Authorization": f"Bearer {TOKEN}", "serve
_multiplexed_model_id": "customer_123" }, json={"sequence_data": [100, 102, 98, 105, 110]} ) print(response.json())
50
50
ray-project/ray:doc/source/serve/tutorials/model_multiplexing_forecast/content/client_anyscale_service.py
function_simple
false
14
J8DMSdu3X@localhost:5432/data_processor" ) class
ProductionConfig(Config): """Production configuration.""" DEBUG = False TESTING = False
20
20
config:canary0029:internal_ip:rep4
config
true
internal_ip
10.29.86.169
148
self.priority_queue_list: list[PriorityQueueNode] = [] if items is None: return if priorities is None: priorities = itertools.repeat(None) for item, priority in zip(items, priorities, strict=False):
self.push(item, priority=priority) def __repr__(self) -> str: """Return a string representation of the priority queue. Returns: Formatted string. """ return f"PriorityQueue({self.priority_queue
50
50
keon/algorithms:algorithms/data_structures/priority_queue.py
documentation
false
330
handle it) if not skip_empty_check: cls._drop_empty_metadata_table(index_name, tenant_id) return True # No metadata to delete is success except Exception as e: # If get fails, document might not
exist in metadata table, which is fine logging.error(f"[METADATA DELETE] Get failed: {e}") # Continue to check/drop table if needed # Delete from ES/Infinity (only if metadata exists) #
50
50
infiniflow/ragflow:api/db/services/doc_metadata_service.py
function_complex
false
4,163
( ["hello"], loop, on_separate_loop=True, event=event ), loop=loop, ) replica_result = fut.result() with pytest.raises(TimeoutError): replica_result.get(timeout_s=0.0
1) event.set() assert replica_result.get(timeout_s=0.01) == "hello" def test_unary_error_sync(self, create_asyncio_event_loop_in_thread): """Test error is raised correctly.""" loop
50
50
ray-project/ray:python/ray/serve/tests/unit/test_grpc_replica_result.py
test
false
2,332
. negative_prompt (`str`, *optional*): The prompt or prompts not to guide the image generation. Outputs: resized_image (`list`): Images resized to 1024x1024 target area for
VAE encoding resized_cond_image (`list`): Images resized to 384x384 target area for VL text encoding prompt_embeds (`Tensor`): The prompt embeddings. prompt_embeds_mask (`
50
50
huggingface/diffusers:src/diffusers/modular_pipelines/qwenimage/modular_blocks_qwenimage_edit_plus.py
license
false
488
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
17