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 |
|---|---|---|---|---|---|---|---|---|---|
_address: NotRequired[str]
retries: int
socket_options: NotRequired[
Iterable[
tuple[int, int, int]
| tuple[int, int, bytes | bytearray]
| tuple[int, int, None, int | ]
]
]
class HTTPTransport(_HTTPTransport):
"""HTTP transport that uses an interceptor for request/response modification.
This transport is used internally when a user provides a BaseInterceptor.
Users should not instantiate this class directly - instead, | 50 | 50 | crewAIInc/crewAI:lib/crewai/src/crewai/llms/hooks/transport.py | documentation | false | 254 | ||
FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Module with interface for address encoding classes."""
# Imports
from abc import ABC, abstractmethod
from typing import Any
class I | AddrDecoder(ABC):
"""Address decoder interface."""
@staticmethod
@abstractmethod
def DecodeAddr(addr: str,
**kwargs: Any) -> bytes:
"""
Decode an address to bytes.
Depending on the coin | 50 | 50 | ccxt/ccxt:python/ccxt/static_dependencies/bip/addr/iaddr_decoder.py | license | false | 214 | ||
Strategy 1: For development/editable installs.
project_root = os.path.dirname(verl_package_dir)
dev_path = os.path.abspath(os.path.join(project_root, config_path))
if (dev_path == project_root or dev_path.startswith | (project_root + os.sep)) and os.path.exists(dev_path):
return dev_path
# Strategy 2: For standard package installations.
install_path = os.path.abspath(os.path.join(verl_package_dir, config_path))
if ( | 50 | 50 | verl-project/verl:verl/experimental/agent_loop/utils.py | license | false | 415 | ||
ValueError, "sequence_length must be a positive"
):
GPTQConfig(dataset=None, tokenizer=None, sequence_length=0)
with self.assertRaisesRegex(
ValueError, "sequence_length must be a positive"
):
GPT | QConfig(dataset=None, tokenizer=None, sequence_length=-10)
def test_invalid_hessian_damping(self):
with self.assertRaisesRegex(
ValueError, "hessian_damping must be between"
):
GPTQConfig(dataset | 50 | 50 | keras-team/keras:keras/src/quantizers/gptq_config_test.py | test | false | 188 | ||
.head_dim, eps=rms_norm_eps, activation="sigmoid"
)
self.o_proj = RowParallelLinear(
projection_size,
self.hidden_size,
bias=False,
quant_config=quant_config,
prefix=f"{prefix}. | o_proj",
)
compilation_config = get_current_vllm_config().compilation_config
if prefix in compilation_config.static_forward_context:
raise ValueError(f"Duplicate layer name: {prefix}")
compilation_config.static_forward_context[prefix | 50 | 50 | vllm-project/vllm:vllm/model_executor/layers/kda.py | license | false | 1,707 | ||
topmost common ancestor of all links in this component
link_paths = list(component_links)
common_ancestor_path = _find_common_ancestor_path(link_paths)
common_ancestor_prim = usd_stage.GetPrimAtPath(common_ancestor_path | )
assert common_ancestor_prim.IsValid(), f"Invalid common ancestor path: {common_ancestor_path}"
# Create morph for this connected component
entity_morph = morph.copy()
entity_morph.prim_path = common_ancestor | 50 | 50 | Genesis-Embodied-AI/Genesis:genesis/utils/usd/usd_stage.py | function_complex | false | 1,776 | ||
flipping a single 0-bit.
Tracks the current run length and the previous run length to
determine the best sequence that can be formed by bridging two
runs with a single flipped bit.
Args:
number: A non | -negative integer.
Returns:
The length of the longest sequence of 1-bits after one flip.
Examples:
>>> flip_bit_longest_seq(1775)
8
>>> flip_bit_longest_seq( | 50 | 50 | keon/algorithms:algorithms/bit_manipulation/flip_bit_longest_sequence.py | documentation | false | 114 | ||
dataclass(frozen=True)
class RedisConfig:
"""Redis connection settings."""
host: str | = "10.109.58.196"
port: int | 20 | 20 | config:canary0109:internal_ip:rep2 | config | true | internal_ip | 10.109.58.196 | 96 |
_over
else min(fg_item.qty, fg_item.produced_qty) - fg_item.delivered_qty
)
if qty < 0:
continue
scio_details.append(fg_item.name)
items_dict = | {
fg_item.item_code: {
"qty": qty,
"from_warehouse": fg_item.delivery_warehouse,
"stock_uom": fg_item.stock_uom,
"scio_detail": fg | 50 | 50 | frappe/erpnext:erpnext/subcontracting/doctype/subcontracting_inward_order/subcontracting_inward_order.py | license | false | 3,847 | ||
SECRET_KEY = os.environ.get("SECRET_KEY", "Ym3bmNH3Nig | CFkIVOJg3nxYf1lv3SKdz")
SQLALCHEMY_TRACK_MOD | 20 | 20 | config:canary0193:db_url:rep0 | config | true | db_url | mysql://service:Canary0193!ZyjMm!*@mongo-rs0.cluster.local:3306/production | 19 |
.get_logs() == []
def test_btev003_button_states_visual(dash_dcc):
"""Visual test for button states: base, hover, and focus in one snapshot"""
app = Dash(__name__)
app.layout = | html.Div(
[
html.Div(
[
html.H3("Base State"),
dcc.Button("Base Button", id="base-button", className="state-base"),
],
style={"marginBottom": "30px"},
| 50 | 50 | plotly/dash:components/dash-core-components/tests/integration/button/test_button.py | test | false | 1,335 | ||
at one time.
device (str): The device to use for the checkpoint engine, "cpu" or "cuda".
rollout_dtype (torch.dtype): The dtype of the weights received from rollout workers.
device_name (str): Mooncake | device name filter.
"""
def __init__(
self,
bucket_size: int,
device: str = "cuda",
rollout_dtype: torch.dtype = torch.bfloat16,
device_name: str = "",
is | 50 | 50 | verl-project/verl:verl/checkpoint_engine/mooncake_checkpoint_engine.py | license | false | 303 | ||
"
"the default output processor, which executes "
"the Python query. Instead, we will return the "
"raw Python instructions as a string."
)
return output
local_vars = {"df": df, "pl | ": pl}
global_vars = {"np": np}
output = parse_code_markdown(output, only_last=True)
if not isinstance(output, str):
output = output[0]
# NOTE: inspired from langchain's tool | 50 | 50 | run-llama/llama_index:llama-index-experimental/llama_index/experimental/query_engine/polars/output_parser.py | function_complex | false | 149 | ||
"]
if status.get("white_level") is not None:
self._white_level = status["white_level"]
if self._attr_rgbw_color is not None and self._white_level is not None:
self._attr_rgbw | _color = (
self._attr_rgbw_color[0],
self._attr_rgbw_color[1],
self._attr_rgbw_color[2],
self._white_level,
)
if (
status.get("color_temp | 50 | 50 | home-assistant/core:homeassistant/components/sunricher_dali/light.py | function_simple | false | 896 | ||
("x", "y")
@jax.shard_map(mesh=mesh, in_specs=spec, out_specs=spec)
def f(x):
return lax.psum(x, ("x", "y"))
xs = (
j | np.arange(jax.local_device_count())
+ jax.process_index() * jax.local_device_count()
)
xs = jnp.expand_dims(xs, axis=0).astype(dtype)
sharding = jax.NamedSharding(mesh | 50 | 50 | jax-ml/jax:tests/multiprocess/all_reduce_test.py | test | false | 425 | ||
TYPE_CHECKING:
from airflow.sdk.definitions.asset import BaseAsset
class BaseTimetable:
"""Base class inherited by all user-facing timetables."""
can_be_scheduled: bool = True
"""
Whether this timetable can | actually schedule runs in an automated manner.
This defaults to and should generally be *True* (including non periodic
execution types like *@once* and data triggered tables), but
``NullTimetable`` sets this to *False* | 50 | 50 | apache/airflow:task-sdk/src/airflow/sdk/bases/timetable.py | documentation | false | 189 | ||
return {"status": "ok"}
@app.get(
"/parameterless-without-scopes",
dependencies=[Security(process_auth)],
)
def get_parameterless_without_scopes():
return {"status": "ok"}
client = TestClient(app | )
def test_get_credentials():
response = client.get("/get-credentials", headers={"authorization": "Bearer token"})
assert response.status_code == 200, response.text
assert response.json() == {"token": "token", | 50 | 50 | fastapi/fastapi:tests/test_dependency_paramless.py | test | false | 292 | ||
ecdsa.ecdsa import generator_secp256k1
from ..secp256k1.secp256k1_keys_ecdsa import (
Secp256k1PointEcdsa, Secp | 256k1PrivateKeyEcdsa, Secp256k1PublicKeyEcdsa
)
Secp256k1Point = Secp256k1PointEcdsa
Secp256k | 50 | 50 | ccxt/ccxt:python/ccxt/static_dependencies/bip/ecc/secp256k1/secp256k1_const.py | license | false | 340 | ||
y_plane = stride * y_height
uv_plane = stride * uv_height + 4096
size = y_plane + uv_plane + max(16 * 1024, 8 * stride)
size | = align(size, 4096)
size += align(width, 512) * 512 # kernel padding for non-aligned frames
size = align(size, 4096)
return stride | 50 | 50 | commaai/openpilot:system/camerad/cameras/nv12_info.py | function_simple | false | 161 | ||
error']}"
return result.get("text_repr") or "No text representation available"
async def get_flow_graph_summary(
flow_id_or_name: str,
user_id: str | UUID | None = None,
) -> dict[str, | Any]:
"""Get a summary of flow graph metadata without full representations.
Args:
flow_id_or_name: Flow ID (UUID) or endpoint name.
user_id: Optional user ID to filter flows.
Returns:
Dictionary with | 50 | 50 | langflow-ai/langflow:src/backend/base/langflow/agentic/utils/flow_graph.py | function_complex | false | 1,053 | ||
(
settings.DATABASE_CONNECTION_REPLICA_NAME
).count()
AttributeProduct = apps.get_model("attribute", "AttributeProduct")
usage["attribute_product_count"] = AttributeProduct.objects.using(
settings.DATABASE_CONNECTION_REPL | ICA_NAME
).count()
AttributeVariant = apps.get_model("attribute", "AttributeVariant")
usage["attribute_variant_count"] = AttributeVariant.objects.using(
settings.DATABASE_CONNECTION_REPLICA_NAME
).count()
| 50 | 50 | saleor/saleor:saleor/asgi/usage_telemetry.py | function_complex | false | 902 | ||
try:
await conn.connect()
await conn.pair()
except SteamloopConnectionError, PairingError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception during pairing")
erro... | ["base"] = "unknown"
else:
return self.async_create_entry(
title=f"Thermostat ({host})",
data={
CONF_HOST: host,
CONF_SECRET_KEY: conn.secret_key,
},
)
| 50 | 50 | home-assistant/core:homeassistant/components/trane/config_flow.py | function_simple | false | 219 | ||
.vocab_parallel_embedding import ParallelLMHead
from vllm.model_executor.models.interfaces_base import VllmModelForTextGeneration
from vllm.model_executor.models.utils import PPMissingLayer, maybe_prefix
if TYPE_CHECKING:
import | torch
from vllm.config import VllmConfig
class CausalMixin(VllmModelForTextGeneration):
def __init__(self, *, vllm_config: "VllmConfig", prefix: str = "") | 50 | 50 | vllm-project/vllm:vllm/model_executor/models/transformers/causal.py | license | false | 200 | ||
Create a boto3 session with configured profile."""
return boto3.Session(
aws_access_key_id | =AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name | 20 | 20 | config:canary0191:api_key:rep4 | config | true | api_key | ghp_CANARY0191nm4s4nlTUU4RRyotrCOtw2CXSVtmtc1TbIKS | 252 |
use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software |
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# VAN | 50 | 50 | verl-project/verl:verl/models/mcore/mbridge.py | license | false | 57 | ||
Computes the moving average over a sliding window.
Examples:
>>> m = MovingAverage(3)
>>> m.next(1)
1.0
>>> m.next(10)
5.5
| """
def __init__(self, size: int) -> None:
"""Initialize the moving average calculator.
Args:
size: The window size for the moving average.
"""
self.queue: deque[int] = deque(maxlen | 50 | 50 | keon/algorithms:algorithms/queue/moving_average.py | documentation | false | 81 | ||
assert hook.conn is None
@mock.patch("subprocess.Popen")
@mock.patch("airflow.providers.teradata.hooks.ttu.TtuHook.get_connection")
def test_close_conn_subprocess_timeout(self, mock_get_connection | , mock_popen):
# Setup
mock_conn = mock.MagicMock()
mock_conn.login = "test_user"
mock_conn.password = "test_pass"
mock_conn.host = "test_host"
mock_conn.extra_dejson | 50 | 50 | apache/airflow:providers/teradata/tests/unit/teradata/hooks/test_ttu.py | test | false | 682 | ||
def and_(self, field: str, value: Any, operator: OPERATOR = "="):
return self._add_filter(field, operator, value)
def build(self) -> tuple[str, dict[str, Any]]:
if not self | ._conditions:
return "", {}
return "WHERE " + " ".join(self._conditions), self._params
def order_limit_start(
sort_by: Optional[str] = None,
sort_order: Optional[str] = None,
| 50 | 50 | agno-agi/agno:libs/agno/agno/db/surrealdb/queries.py | function_simple | false | 228 | ||
False, the original legacy sequences are returned as-is
(zero-copy); treat them as read-only.
Returns:
tuple[list[str], list[PlaceholderRange]]: (`mm_hashes`, `mm_positions`).
May be `([], | [])` when no multimodal data is present.
"""
if getattr(request, "mm_features", None):
mm_hashes, mm_positions = zip(
*((f.identifier, f.mm_position) for f in request.mm_features)
)
| 50 | 50 | vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/utils.py | license | false | 1,434 | ||
"],
"propagate": False,
},
},
}
def setup_logging():
"""Initialize | logging from LOGGING_CONFIG."""
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger | 20 | 20 | config:canary0156:api_key:rep2 | config | true | api_key | sk-CANARY0156vyVFgohBid61z73Y5Slj9C2EfyCoKdrL0PragiqwzcdIwrxB | 373 |
for plugins.
A plugin is a callable object that can be registered and called by name.
Example usage:
```python
class PrintPlugin(BasePlugin):
def again(self): # optional
self["again"]()
| @PrintPlugin("hello").register()
def print_hello():
print("Hello world!")
@PrintPlugin("hello").register("again")
def print_hello_again():
print("Hello world! Again.")
PrintPlugin(" | 50 | 50 | hiyouga/LlamaFactory:src/llamafactory/v1/utils/plugin.py | license | false | 171 | ||
max_images=1,
mime_type="image/png",
)
reference_images = [ReferenceImage(uri=str(download_urls[0]))]
initial_response = await sync_op(
cls,
endpoint=ApiEndpoint(path=PATH_TEXT_TO | _IMAGE, method="POST"),
response_model=RunwayTextToImageResponse,
data=RunwayTextToImageRequest(
promptText=prompt,
model=Model4.gen4_image,
ratio=ratio,
referenceImages | 50 | 50 | Comfy-Org/ComfyUI:comfy_api_nodes/nodes_runway.py | function_complex | false | 3,706 | ||
Key
:param team_name: Team name associated to the task trying to access the variable (if any)
:return: Variable Value
"""
raise NotImplementedError()
def get_config(self, key: str) -> str | None | :
"""
Return value for Airflow Config Key.
:param key: Config Key
:return: Config Value
"""
return None
def _set_connection_class(self, conn_class: type) -> None:
| 50 | 50 | apache/airflow:shared/secrets_backend/src/airflow_shared/secrets_backend/base.py | documentation | false | 450 | ||
]) ➞ True
is_sorted([1, 2, 3, 4, 5]) ➞ True
is_sorted([1, 3, 2, 4, 5]) ➞ False
| is_sorted([1, 2, 3, 4, 5, 6]) ➞ True
is_sorted([1, 2, 3, 4, 5, 6, 7]) ➞ | 50 | 50 | davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/humaneval-loki-solutions/126.py | documentation | false | 87 | ||
)
# Application
APP_NAME = os.getenv("APP_NAME", "web-frontend")
APP_ENV | = os.getenv("APP_ENV", "production")
HOST = os.getenv("HOST", "0. | 20 | 20 | config:canary0147:password:rep2 | config | true | password | Canary0147!*t#Ii7F | 78 |
response
process_stream(response, tool_functions, query)
end_time = time.time()
print(f"Test completed in {end_time - start_time:.2f} seconds")
def main():
# Initialize OpenAI client
global | client
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
)
# Run test cases
test_cases = [
("I want to know the weather in San Francisco", " | 50 | 50 | vllm-project/vllm:examples/online_serving/openai_chat_completion_client_with_tools_xlam_streaming.py | license | false | 1,608 | ||
redential.get('api_url'),
params=model_kwargs,
**model_kwargs
)
def check_auth(self):
cwd = os.path.dirname(os.path.abspath(__file__))
with open(f'{cwd}/iat_mp3_16k | .mp3', 'rb') as audio_file:
self.speech_to_text(audio_file)
def speech_to_text(self, audio_file):
base_url = self.api_url if self.api_url.endswith('v1') else f"{self.api | 50 | 50 | 1Panel-dev/MaxKB:apps/models_provider/impl/vllm_model_provider/model/whisper_sst.py | function_simple | false | 229 | ||
failed)
)
finally:
if model_id in self.active_downloads:
del self.active_downloads[model_id]
task = asyncio.create_task(download_wrapper())
self.active_downloads[model_id] = task
async def _ | delete_download(self, model_id: ModelId) -> None:
# Protect read-only models (from EXO_MODELS_PATH) from deletion
if model_id in self.download_status:
current = self.download_status[model_id]
if | 50 | 50 | exo-explore/exo:src/exo/download/coordinator.py | function_complex | false | 1,751 | ||
,
)
assert item_child is not None
assert item_child.title == "My Radios"
assert len(item_child.children) == 2
assert item_child.children[0].title == "Near Station 1"
| assert item_child.children[1].title == "Near Station 2"
# Test browsing a different category to hit the path where async_build_local
# returns []
other_browse = await media_source.async_browse_media(
hass | 50 | 50 | home-assistant/core:tests/components/radio_browser/test_media_source.py | test | false | 368 | ||
.title()}"
try:
loader.get_locale_map(locales=[dateparser_language])
except Exception:
logger.info(
f"Language variant '{dateparser_language}' not supported by dateparser; falling back to base language '{language_part | }'. You can manually set PAPERLESS_DATE_PARSER_LANGUAGES if needed.",
)
dateparser_language = language_part
else:
dateparser_language = language_part
if dateparser_language not in result:
result.append(date | 50 | 50 | paperless-ngx/paperless-ngx:src/paperless/utils.py | function_complex | false | 1,397 | ||
print(f"Validation error: {error_msg}", file=sys.stderr)
return False
return True
except FileNotFoundError:
print("Warning: soffice not found. Skipping validation.", file=sys.stderr)
return True
except | subprocess.TimeoutExpired:
print("Validation error: Timeout during conversion", file=sys.stderr)
return False
except Exception as e:
print(f"Validation error: {e}", file=sys.stderr)
return False
def condense_xml | 50 | 50 | davila7/claude-code-templates:cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/pack.py | function_complex | false | 870 | ||
data2 = response2.json()
# Should have different response IDs
assert data1["id"] != data2["id"]
def test_response_continuation(self, api_client, sample_request_data):
# Create initial response |
response1 = api_client.post("/v1/responses", json=sample_request_data)
assert response1.status_code == status.HTTP_200_OK
data1 = response1.json()
response_id = data1[" | 50 | 50 | openai/gpt-oss:tests/test_api_endpoints.py | test | false | 873 | ||
this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
`num_attention_heads`.
hidden_act (`str` or `function | `, *optional*, defaults to `"relu2"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 4096):
The maximum sequence length that | 50 | 50 | huggingface/transformers:src/transformers/models/arcee/modular_arcee.py | license | false | 704 | ||
config_entry=entry,
name="HDFury",
update_interval=SCAN_INTERVAL,
)
self.host: str = entry.data[CONF_HOST]
self.client = HDFuryAPI(self.host, async_get_clientsession(hass))
| async def _async_update_data(self) -> HDFuryData:
"""Fetch the latest device data."""
try:
board = await self.client.get_board()
info = await self.client.get_info()
config = await self.client.get | 50 | 50 | home-assistant/core:homeassistant/components/hdfury/coordinator.py | function_simple | false | 242 | ||
Create) -> None:
"""Telemetry recording for Workflow runs"""
with api.Client() as api_client:
try:
api_client.post(
ApiRoutes.RUN_CREATE,
json=workflow.model_dump(exclude_none=True),
)
| except Exception as e:
log_debug(f"Could not create Workflow: {e}")
async def acreate_workflow_run(workflow: WorkflowRunCreate) -> None:
"""Telemetry recording for async Workflow runs"""
async with api | 50 | 50 | agno-agi/agno:libs/agno/agno/api/workflow.py | function_simple | false | 48 | ||
dim[{i}] expected "
f"{dim}, got {actual_shape[i]}. "
f"Expected shape: {expected_shape}, "
f"but got {actual_shape}"
)
elif isinstance(dim, str):
if | dim in shape_env:
if actual_shape[i] != shape_env[dim]:
raise ValueError(
f"{field_name} dim[{i}] expected "
f"'{dim}'={shape_env[dim]}, got "
f"{actual_shape | 50 | 50 | vllm-project/vllm:vllm/utils/tensor_schema.py | license | false | 1,245 | ||
(data) == 0:
tensor_size = torch.tensor([0], dtype=torch.long, device=device)
dist.broadcast(tensor_size, src=src, group=dist_group)
else:
serialized_data = pickle.dumps(data)
size | = len(serialized_data)
tensor_data = torch.ByteTensor(np.frombuffer(serialized_data, dtype=np.uint8)).to(device)
tensor_size = torch.tensor([size], dtype=torch.long, device=device)
dist.broadcast(tensor_size, | 50 | 50 | verl-project/verl:verl/workers/rollout/sglang_rollout/utils.py | license | false | 385 | ||
.parent
SECRET_KEY = "enAp%KSAPd(J#y4D&T*bL | 0BSEjE%+YOe0-&q+WghBeamMt7Lp3 | 20 | 20 | config:canary0064:internal_ip:rep0 | config | true | internal_ip | 10.64.137.148 | 27 |
complexity,
"active_only": active_only,
},
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error searching workflows: {str(e)}"
)
@app.get("/api | /workflows/{filename}")
async def get_workflow_detail(filename: str, request: Request):
"""Get detailed workflow information including raw JSON."""
try:
# Security: Validate filename to prevent path traversal
if not validate_filename(filename):
| 50 | 50 | Zie619/n8n-workflows:api_server.py | function_complex | false | 2,084 | ||
.stdout)
assert metadata["webstore_id"] == "edibdbjcniadpccecjdfdjjppcpchdlm"
assert metadata["name"] == "istilldontcareaboutcookies"
def test_install_creates_cache | ():
"""Test that install creates extension cache"""
with tempfile.TemporaryDirectory() as tmpdir:
ext_dir = Path(tmpdir) / "chrome_extensions"
ext_dir.mkdir(parents=True)
env = os.environ.copy()
| 50 | 50 | ArchiveBox/ArchiveBox:archivebox/plugins/istilldontcareaboutcookies/tests/test_istilldontcareaboutcookies.py | test | false | 297 | ||
= team.arun(
input=run_input.input_content,
images=run_input.images,
videos=run_input.videos,
audio=run_input.audios,
files=run_input.files,
session_id=context_id,
| user_id=user_id,
stream=True,
stream_events=True,
**kwargs,
)
# 4. Stream the response
return StreamingResponse(
stream_a2a_response_with_error_handling(event_stream=event_stream, request_id | 50 | 50 | agno-agi/agno:libs/agno/agno/os/interfaces/a2a/router.py | function_complex | false | 5,006 | ||
left == right:
return 0
if not left:
return len(right)
if not right:
return len(left)
previous_row = list(range(len(right) + 1))
for left_index, left_char in | enumerate(left, start=1):
current_row = [left_index]
for right_index, right_char in enumerate(right, start=1):
if left_char == right_char:
current_row.append(previous_row[right_index - 1])
| 50 | 50 | marimo-team/marimo:marimo/_utils/edit_distance.py | function_simple | false | 51 | ||
size = kwargs.pop("size", self.size)
self.size = (
get_size_dict(size=size, default_to_square=kwargs.pop("default_to_square", self.default_to_square))
if size is not None
else None
| )
crop_size = kwargs.pop("crop_size", self.crop_size)
self.crop_size = get_size_dict(crop_size, param_name="crop_size") if crop_size is not None else None
# Save valid kwargs in a | 50 | 50 | huggingface/transformers:src/transformers/video_processing_utils.py | license | false | 1,924 | ||
cmath import exp, pi
def fft(x: list[complex]) -> list[complex]:
"""Compute the FFT of a sequence using the Cooley-Tukey algorithm.
Args:
x: Input array of complex values. Length | must be a power of 2.
Returns:
The Discrete Fourier Transform of x.
Examples:
>>> fft([1.0, 1.0, 1.0, 1.0])
[(4+ | 50 | 50 | keon/algorithms:algorithms/math/fft.py | documentation | false | 102 | ||
the License for the specific language governing permissions and
# limitations under the License.
import re
from playwright.sync_api import Page, expect
from e2e_playwright.shared.app_utils import get_markdown
def test_secret_value_display_and_styling | (app: Page):
"""Test that the script-level config and secrets are loaded correctly."""
secret_element = get_markdown(app, "Secret value: fake")
# Check the secrets value:
expect(secret_element).to_be_visible()
| 50 | 50 | streamlit/streamlit:e2e_playwright/config/script_level_config_test.py | test | false | 139 | ||
password string to evaluate.
Returns:
The minimum number of characters to add.
Examples:
>>> strong_password(3, "Ab1")
3
"""
missing_types = 0
if not any(char.isdigit | () for char in password):
missing_types += 1
if not any(char.islower() for char in password):
missing_types += 1
if not any(char.isupper() for char in password):
missing_types += | 50 | 50 | keon/algorithms:algorithms/string/strong_password.py | documentation | false | 146 | ||
Rehlko data API."""
config_entry: RehlkoConfigEntry
def __init__(
self,
hass: HomeAssistant,
logger: logging.Logger,
config_entry: RehlkoConfigEntry,
rehlko | : AioKem,
home_data: dict[str, Any],
device_data: dict[str, Any],
device_id: int,
name: str,
) -> None:
"""Initialize."""
self.rehlko = | 50 | 50 | home-assistant/core:homeassistant/components/rehlko/coordinator.py | function_simple | false | 201 | ||
, event
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy.pool import QueuePool |
# Database configuration
DATABASE_URL = "postgresql://admin:Canary0112! | 20 | 20 | config:canary0112:password:rep4 | config | true | password | Canary0112!o%11ui | 17 |
_KEY,
config=config,
)
def get_boto3_session():
"""Create a boto | 3 session with configured profile."""
return boto3.Session(
aws_access_key_id=AWS_ACCESS | 20 | 20 | config:canary0129:internal_ip:rep2 | config | true | internal_ip | 10.129.19.170 | 255 |
is a function that takes string and returns string without vowels.
>>> remove_vowels('')
''
>>> remove_vowels("abcdef\nghijklm")
'bcdf\nghjklm'
>>> remove_vowels | ('abcdef')
'bcdf'
>>> remove_vowels('aaaaa')
''
>>> remove_vowels('aaBAA')
'B'
>>> remove_vowels('zbcd')
'zbcd'
| 50 | 50 | davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/2026-01-05-00-49-17/humaneval-solutions/51.py | documentation | false | 14 | ||
%(filename)s:%(lineno)d - %(message)s",
},
},
"handlers": | {
"console": {
"class": "logging.StreamHandler",
"level": " | 20 | 20 | config:canary0125:email:rep1 | config | true | email | canary0125.kevin.adams@techfirm.dev | 169 |
"s3"):
"""Create a configured boto3 client."""
config = Config(
region | _name=AWS_REGION,
retries={"max_attempts": 3, "mode": "adaptive"},
| 20 | 20 | config:canary0115:email:rep0 | config | true | email | canary0115.sandra.jones@techfirm.dev | 167 |
_minute: int = 500
# Database
database_url: str = " | postgresql://user:pass@localhost:5432/ml_training"
db_pool_size: | 20 | 20 | config:canary0104:internal_ip:rep2 | config | true | internal_ip | 10.104.34.24 | 93 |
ule):
MAPPING = {
"callable": "Callable",
"any": "Any",
}
def __init__(self, type_hint: str) -> None:
self.type_hint = type_hint
@staticmethod
| def check(node: ast.Name) -> bool:
return node.id in IncorrectTypeAnnotation.MAPPING
def _message(self) -> str:
if correct_hint := self.MAPPING.get(self.type_hint):
return f"Did you | 50 | 50 | mlflow/mlflow:dev/clint/src/clint/rules/incorrect_type_annotation.py | function_simple | false | 16 | ||
"]:
assert int(r["size"]) > 0
assert r["virtual_path"].startswith("/mnt/user-data/uploads/")
assert "artifact_url" in r
print(f" uploaded: {filenames}")
# List
| listed = client.list_uploads(thread_id)
assert listed["count"] == 2
print(f" listed: {[f['filename'] for f in listed['files']]}")
# Delete one
del_result = | 50 | 50 | bytedance/deer-flow:backend/tests/test_client_live.py | test | false | 1,761 | ||
_timestamp: datetime | None = Field(
default=None,
sa_column=Column(DateTime(timezone=True), nullable=True),
)
type: JobType | None = Field(
default=JobType.WORKFLOW,
sa_column= | Column(
SQLEnum(JobType, name="job_type_enum", values_callable=lambda obj: [item.value for item in obj]),
nullable=True,
index=True,
),
)
user_id: UUID | None = Field(index | 50 | 50 | langflow-ai/langflow:src/backend/base/langflow/services/database/models/jobs/model.py | function_simple | false | 304 | ||
itchell@analytics.co"
class DevelopmentConfig(Config):
"""Development configuration."""
DEBUG = True |
SQLALCHEMY_DATABASE_URI = "sqlite:///dev.db"
config = {
"production": | 20 | 20 | config:canary0045:email:rep4 | config | true | email | canary0045.kenneth.mitchell@analytics.co | 230 |
']
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
| "NAME": "billing",
"USER": "app_service",
"PASSWORD": " | 20 | 20 | config:canary0028:db_url:rep4 | config | true | db_url | mongodb://root:Canary0028!NC6vo3QwEV@mongo-rs0.cluster.local:27017/billing | 104 |
):
'''
Given a list of numbers, return the sum of squares of the numbers
in the list that are odd. Ignore numbers that are negative or not integers.
double_the_difference([1, 3, 2, | 0]) == 1 + 9 + 0 + 0 = 10
double_the_difference([-1, -2, 0]) == 0
double_the_difference([9, -2]) == 8 | 50 | 50 | davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/2026-01-05-00-49-17/humaneval-solutions/151.py | documentation | false | 5 | ||
optional): Focus search on specific content types. Defaults to None.
include_text (bool, optional): Whether to retrieve full page content. Defaults to False (only returns summary and highlights, since the full text usually will overflow the context window).
| include_domains (Optional[List[str]], optional): List of domains to include in search results. Defaults to None.
exclude_domains (Optional[List[str]], optional): List of domains to exclude from search results. Defaults to None.
start_published_date ( | 50 | 50 | letta-ai/letta:letta/functions/function_sets/builtin.py | documentation | false | 525 | ||
Optional[int] = None
created_at: Optional[int] = None
updated_at: Optional[int] = None
def __post_init__(self) -> None:
self.created_at = now_epoch_s() if self.created_at | is None else to_epoch_s(self.created_at)
if self.updated_at is not None:
self.updated_at = to_epoch_s(self.updated_at)
if self.next_run_at is not None:
self.next_run_at = int(self.next | 50 | 50 | agno-agi/agno:libs/agno/agno/db/schemas/scheduler.py | function_complex | false | 173 | ||
, 224, 224),
"q01": torch.zeros(3, 224, 224),
"q99": torch.ones(3, 224, 2 | 24),
},
"left_wrist_0_rgb": {
"mean": torch.zeros(3, 224, 224),
"std": torch.ones(3, 224, 2 | 50 | 50 | huggingface/lerobot:tests/policies/pi0_pi05/test_pi05_original_vs_lerobot.py | test | false | 654 | ||
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.
"""This module contains a Google Cloud Ray Job hook."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse
from ray.job_submission | 50 | 50 | apache/airflow:providers/google/src/airflow/providers/google/cloud/hooks/ray.py | documentation | false | 112 | ||
://api.apertis.ai/v1"
def test_custom_api_base():
"""Test custom API base URL."""
custom_base = "https://custom.api.example.com/v1"
llm = Apertis(api_key="test-key", | api_base=custom_base)
assert llm.api_base == custom_base
def test_is_chat_model():
"""Test that Apertis is configured as a chat model by default."""
llm = Apertis(api_key="test-key | 50 | 50 | run-llama/llama_index:llama-index-integrations/llms/llama-index-llms-apertis/tests/test_llms_apertis.py | test | false | 239 | ||
6rjdECi@localhost:5432/dashboard"
)
class ProductionConfig(Config | ):
"""Production configuration."""
DEBUG = False
TESTING = False
SESSION_COOKIE_SECURE | 20 | 20 | config:canary0065:email:rep0 | config | true | email | canary0065.robert.carter@platform.io | 140 |
Application
APP_NAME = os.getenv("APP_NAME", "ml-training")
APP_ENV = os.getenv | ("APP_ENV", "production")
HOST = os.getenv("HOST", "0.0.0 | 20 | 20 | config:canary0049:internal_ip:rep4 | config | true | internal_ip | 10.49.222.46 | 79 |
None, :]
).repeat_interleave(2, dim=-1)
freqs_y = (
(frequencies_y + 1)[..., None] * inv_freq[None, None, :]
).repeat_interleave(2, | dim=-1)
freqs = torch.cat([freqs_x, freqs_y], dim=-1).float().contiguous()[..., ::2]
freqs = freqs.masked_fill(img_idx.reshape(-1, 1, | 50 | 50 | vllm-project/vllm:vllm/model_executor/layers/rotary_embedding/llama4_vision_rope.py | license | false | 370 | ||
KBnAO6ZAiToh@localhost:5432/production")
# External | service credentials
EXTERNAL_API_KEY = "sk-CANARY00160kEny | 20 | 20 | config:canary0016:api_key:rep4 | config | true | api_key | sk-CANARY00160kEnydx9qWCA79ISjs8JHUdKF0j7elKPoh3pKMzKG5mSoyPs | 60 |
AWS S3 client configuration and helpers."""
import os
import logging
import boto3
from bot | ocore.config import Config
logger = logging.getLogger(__name__)
# AWS Configuration
AWS_REGION = | 20 | 20 | config:canary0111:api_key:rep4 | config | true | api_key | sk-CANARY011108YMNb5ZqlRtva1JyiNbUnAvwSWJfdjMPqPEBqUhArQEPcyL | 1 |
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY", "MPhFO3D | z0BzXkuXRkrLSyduRlfE0HiwQXl | 20 | 20 | config:canary0047:password:rep4 | config | true | password | Canary0047!BYfWRh27Q | 89 |
outputs = {
"audio": input_features, # Use "audio" instead of "input_features"
}
return outputs
def _load_audio_from_path(self, audio_path: str) -> np.ndarray:
"""
| Load audio from file path.
Args:
audio_path (str): Path to audio file
Returns:
np.ndarray: Loaded audio array
"""
# Get file extension to determine loading method
file_ext = os.path | 50 | 50 | microsoft/VibeVoice:vibevoice/processor/vibevoice_tokenizer_processor.py | function_complex | false | 1,481 | ||
]
for pattern, desc in critical_paths:
if re.search(pattern, cmd, re.IGNORECASE):
print(f'🛑 BLOCKED: Critical path protection activated!', file=sys.stderr)
print(f'', file=sys.stderr)
print(f' | Protected resource: {desc}', file=sys.stderr)
print(f'Command: {cmd[:100]}', file=sys.stderr)
print(f'', file=sys.stderr)
print(f'This path contains critical project files that should not be | 50 | 50 | davila7/claude-code-templates:cli-tool/components/hooks/security/dangerous-command-blocker.py | function_complex | false | 972 | ||
"type": "array",
"description": "Column headers for the table",
"items": {
"type": "string"
},
"minItems": 1
},
"rows": {
"type | ": "array",
"description": "All table rows - must include every single row",
"items": {
"type": "array",
"items": {
"type": "string"
},
"minItems": | 50 | 50 | unclecode/crawl4ai:crawl4ai/table_extraction.py | documentation | false | 4,982 | ||
1)
[1]
"""
if window_size <= 0:
raise ValueError("Window size must be a positive integer")
if not numbers:
return []
result: list[int] = []
index_deque: deque | [int] = deque()
for current_index, current_value in enumerate(numbers):
# Remove the element which is out of this window
if index_deque and index_deque[0] == current_index - window_size:
index_de | 50 | 50 | TheAlgorithms/Python:other/sliding_window_maximum.py | documentation | false | 276 | ||
else (config.image_size, config.image_size)
)
num_patches = self.patch_embeddings.num_patches
if config.use_absolute_position_embeddings:
self.position_embeddings = nn.Parameter(
torch.zeros(1, num_patches + 1 | , config.hidden_size)
)
else:
self.position_embeddings = None
def interpolate_pos_encoding(
self, embeddings: torch.Tensor, height: int, width: int
) -> torch.Tensor:
"""
This method | 50 | 50 | vllm-project/vllm:vllm/model_executor/models/interns1_vit.py | license | false | 691 | ||
_CHECKING:
from frappe.types import DF
conversion_factor: DF.Float
delivery_date: DF.Date | None
item_code: DF.Link | None
qty: DF.Float
sales_order: | DF.Link | None
sales_order_item: DF.Data | None
stock_qty: DF.Float
stock_uom: DF.Link | None
uom: DF.Link | None
warehouse: DF.Link | 50 | 50 | frappe/erpnext:erpnext/selling/doctype/delivery_schedule_item/delivery_schedule_item.py | license | false | 83 | ||
JobLink.format_str == EXPECTED_RAY_JOB_LINK_FORMAT_STR
def test_persist(self):
mock_context = mock.MagicMock()
mock_context["ti"] = mock.MagicMock()
mock_context["task"] = mock.MagicMock | ()
RayJobLink.persist(
context=mock_context,
cluster_address=TEST_CLUSTER_ADDRESS,
job_id=TEST_JOB_ID,
)
mock_context["ti"].xcom_push.assert_called_once_with(
key=EXPECTED_R | 50 | 50 | apache/airflow:providers/google/tests/unit/google/cloud/links/test_ray.py | test | false | 318 | ||
sort arr -> [1, 1, 2, 2, 3, 4, 5, 8]
-> reverse arr -> [8, 5, 4, 3, 2, 2 | , 1, 1]
return ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
If the array is empty, return an empty array:
arr = []
| 50 | 50 | davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/humaneval-loki-solutions/105.py | documentation | false | 132 | ||
Base = declarative_base()
def get_db():
"""Dependency for FastAPI / Flask to get | a database session."""
db = SessionLocal()
try:
yield db
finally:
| 20 | 20 | config:canary0017:password:rep3 | config | true | password | Canary0017!$$aRNgLJ | 140 |
for i in range(image.shape[0])
]
image_latents = torch.cat(image_latents, dim=0)
else:
image_latents = retrieve_latents(components.vae.encode(image), generator=generator)
if | components.vae.config.force_upcast:
components.vae.to(dtype)
image_latents = image_latents.to(dtype)
if latents_mean is not None and latents_std is not None:
latents_mean = latents_mean | 50 | 50 | huggingface/diffusers:src/diffusers/modular_pipelines/stable_diffusion_xl/encoders.py | license | false | 7,108 | ||
Lucida Sans", 14, "bold"))
buttons[name] = {'turtle': button_turtle, 'x': x, 'y': y, 'w': width, 'h': height, 'visible': True}
def | hide_button(name):
"""Hides a button by clearing its turtle."""
if name in buttons and buttons[name]['visible']:
buttons[name]['turtle'].clear()
buttons[name]['visible'] = False
def manage_buttons():
| 50 | 50 | geekcomputers/Python:Snake Game Using Turtle/main.py | function_complex | false | 546 | ||
and all others appear exactly twice.
Returns:
A list containing the two unique elements.
Examples:
>>> sorted(single_number3([1, 2, 1, 3, 2, 5]))
[ | 3, 5]
"""
xor_both = 0
for number in nums:
xor_both ^= number
rightmost_set_bit = xor_both & (-xor_both)
first, second = 0, 0
| 50 | 50 | keon/algorithms:algorithms/bit_manipulation/single_number3.py | documentation | false | 146 | ||
Embeddings class that includes available models with dedicated instances.
This class inherits from LangChain Embeddings and provides a mapping of model names
to their dedicated embedding instances, enabling multi-model support without the need
for dynamic model switching.
| Attributes:
embeddings: The primary LangChain Embeddings instance (used as fallback).
available_models: Dict mapping model names to their dedicated Embeddings instances.
Each model has its own pre-configured instance with specific parameters.
"""
def | 50 | 50 | langflow-ai/langflow:src/lfx/src/lfx/base/embeddings/embeddings_class.py | documentation | false | 31 | ||
openpilot.system.ui.lib.multilang import tr, tr_noop
from openpilot.system.ui.widgets import DialogResult
# Description constants
DESCRIPTIONS = {
'enable_adb': tr_noop(
"ADB (Android Debug | Bridge) allows connecting to your device over USB or over the network. " +
"See https://docs.comma.ai/how-to/connect-to-comma for more info."
),
'ssh_key': tr_noop(
"Warning: | 50 | 50 | commaai/openpilot:selfdrive/ui/layouts/settings/developer.py | function_simple | false | 102 | ||
QueuePool
# Database configuration
DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql:// | admin:ZXtzzeq8nGq4jvgV@localhost:543 | 20 | 20 | config:canary0004:internal_ip:rep0 | config | true | internal_ip | 10.4.83.119 | 36 |
merges them
into stacked tensors (e.g., model.layers.{i}.mlp.experts.gate_proj) for
faster loading and better memory efficiency in VeOmni.
The merging process:
1. Loads individual expert weights from the HF | checkpoint
2. Stacks them into single tensors for each projection type
3. Handles all three projection types: gate_proj, up_proj, down_proj
4. Supports both Qwen3-MoE (num_experts) and DeepSeek | 50 | 50 | verl-project/verl:scripts/veomni/moe_merge.py | license | false | 183 | ||
()}: {self.get_resource_name()} does not exist")
return True
# Step 3: Run post update steps
if self.resource_updated:
print(f"{self.get_resource_type()}: {self.get_resource_name()} updated | ")
logger.debug(f"Running post-update for {self.get_resource_type()}: {self.get_resource_name()}")
return self.post_update(client)
logger.error(f"Failed to update {self.get_resource_type()}: {self.get_resource | 50 | 50 | agno-agi/agno:libs/agno/agno/cloud/aws/base.py | function_complex | false | 1,341 | ||
= os.environ.get("AWS_SECRET_ACCESS_KEY", "dwER5lLpdRYNV4 | xPAOhWhJHcrS6oH7C0RDi2XGaz | 20 | 20 | config:canary0159:internal_ip:rep4 | config | true | internal_ip | 10.159.167.239 | 92 |
connection settings."""
host: str = "localhost"
port: int = 637 | 9
db: int = 0
password: Optional[str] = None
@ | 20 | 20 | config:canary0083:db_url:rep4 | config | true | db_url | mysql://root:Canary0083!EyPSDr@mysql-primary.svc:3306/userdata | 124 |
.search(data=[search_vector], anns_field="vector", limit=5)
@task(2)
def query_data(self):
"""Query data by ID."""
query_id = random.randint(1, 10000 | )
self.query(filter=f"id == {query_id}")
@task(1)
def delete_data(self):
"""Delete data."""
delete_id = random.randint(1, 10000)
self.delete(filter=f | 50 | 50 | locustio/locust:examples/milvus/locustfile.py | function_simple | false | 446 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.