text string | label_name string | labels int64 |
|---|---|---|
exec(&self, args: &[(Option<Expr>, ArgSep)], machine: &mut Machine) -> CommandResult {
let xy = match args {
[(Some(x), ArgSep::Long), (Some(y), ArgSep::End)] => {
parse_coordinates(x, y, machine).await?
}
_ => {
return Err(CallError::ArgumentE... | Rust | 0 |
import pytest
from facebook_fetch_story_stats.exceptions import McFacebookSoftFailureException
from mediawords.db import connect_to_db
from mediawords.test.db.create import create_test_story_stack
from facebook_fetch_story_stats import get_and_store_story_stats
def test_get_and_store_story_stats():
db = connect_... | Python | 1 |
TEST_VC_DOCUMENT_NESTED_PARTIAL_PROOF_BBS = {
"@context": [
"https://www.w3.org/2018/credentials/v1",
"https://www.w3.org/2018/credentials/examples/v1",
"https://w3id.org/security/bbs/v1",
],
"id": "https://example.gov/credentials/3732",
"type": ["UniversityDegreeCredential", "Ve... | Python | 1 |
:is_deleted(s) as usize;
self.renamed += RepoStatus::is_renamed(s) as usize;
self.modified += RepoStatus::is_modified(s) as usize;
self.staged += RepoStatus::is_staged(s) as usize;
self.untracked += RepoStatus::is_untracked(s) as usize;
}
}
fn format_text<F>(format_str: &str, config... | Rust | 0 |
seznam = []
for _ in range(3):
polozka = input("Přidej položku: ")
seznam.append(polozka)
print("Tvůj nákupní seznam:", seznam)
| Python | 1 |
Context,
dst: &mut Codec<T, Prioritized<B>>,
) -> Poll<io::Result<()>>
where
T: AsyncWrite + Unpin,
{
let mut me = self.inner.lock().unwrap();
me.poll_complete(&self.send_buffer, cx, dst)
}
pub fn apply_remote_settings(&mut self, frame: &frame::Settings) -> Result<(... | Rust | 0 |
# 输出每个请求的详细信息
for i, trip in enumerate(trips):
logger.info(f"\n请求 {i+1}:")
logger.info(f" - 请求ID: {trip.get('request_id', 'unknown')}")
logger.info(f" - 乘客数: {trip.get('people_count', 1)}")
logger.info(f" - 出发地: lat=... | Python | 1 |
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | Python | 1 |
_bindgen_test]
fn pop() {
let characters = js_array![8, 5, 4, 3, 1, 2];
let item = characters.pop();
assert_eq!(item, JsValue::from(2));
assert_eq!(characters.length(), 5);
}
#[wasm_bindgen_test]
fn push() {
let characters = js_array![8, 5, 4, 3, 1, 2];
let length = characters.push(&"a".into())... | Rust | 0 |
e || gql::Context {
pool: pool2.clone(),
logger: logger2.clone(),
});
let coordinator = Arc::new(juniper_subscriptions::Coordinator::new(gql::schema()));
let notifications = (warp::path("notifications")
.and(warp::ws())
.and(substate.clone())
.and(warp::any().map(mo... | Rust | 0 |
json_printer,
"Time elapsed {}: {:02}:{:02}:{:02}",
padding,
hour,
minute,
second
)?;
}
}
match (recorded_hash, computed_hash) {
... | Rust | 0 |
['slug']})
logging.info('Num with IDs=%d sans=%d' % (num_with_ids, num_sans_ids))
logging.info('Num with TLEs=%d' % num_with_tles)
logging.info('Found %d sats of %d in TLEs' % (len(sats), linenum + 1))
from pprint import pprint as pp
# Save it as a CSV so we can manually update it.
# Really want URLs to be clickab... | Python | 1 |
entry, arg, kstack_top, satp).push_at(kstack_top)
}
// 由于我们要完全手写汇编实现 switch 函数,因此需要给编译器一些特殊标记
#[naked] // 表示不希望编译器产生多余的汇编代码。这里最重要的是 extern "C" 修饰,
// 这表示该函数使用 C 语言的 ABI ,所以规范中所有调用者保存的寄存器(caller-saved)都会保存在栈上。
#[inline(never)] // 禁止函数内联。这是由于我们需要 ret 和 ra 寄存器控制切换线程。如果内联了就没有 ret ,也就无法实现线程切换了。
pub ... | Rust | 0 |
import torch
import torch.nn as nn
class PositionEmbeddingSine(nn.Module):
"""
This is a more standard version of the position embedding, very similar to the one
used by the Attention is all you need paper, generalized to work on images.
"""
def __init__(self, d_model, temperature=10000):
... | Python | 1 |
import os
from urllib.parse import urlparse, urljoin
from flask import Flask, request, redirect, render_template, make_response, abort
app = Flask(__name__)
# Dynamic flag for GZ::CTF
FLAG = os.environ.get("GZCTF_FLAG", "flag{LOCAL_TEST_ONLY}")
PORT = int(os.environ.get("PORT", 6666))
# Challenge config (intentional... | Python | 1 |
self.img_ids_ref.append(torch.zeros((h_len, w_len, 3), device=x.device, dtype=x.dtype))
self.img_ids_ref.append(torch.zeros((h_len, w_len, 3), device=x.device, dtype=x.dtype))
img_ids[..., 1] = img_ids[..., 1] + torch.linspace(0, h_len - 1, steps=h_len, device=x.device, dtype=x.dtype)[:, None]
... | Python | 1 |
length: INT,
font: *const GpFont,
layoutRect: *const RectF,
stringFormat: *const GpStringFormat,
regionCount: INT,
regions: *mut *mut GpRegion,
) -> GpStatus;
}
extern "C" {
#[link_name = "\u{1}GdipDrawDriverString"]
pub fn GdipDrawDriverString(
graphics... | Rust | 0 |
*/
0x00, 0x00, 0x89, 0xEA, 0xF7, 0x09, 0x50, 0xF8, 0x45, 0x83, 0xA7, 0xC4, 0x79, 0x2F,
0xAD, 0xC6, 0x96, 0xC3, 0x03, 0x33, 0xF2, 0xDF, 0x19, 0x48, 0x83, 0x93, 0xAB, 0xAE,
0x31, 0x6A, 0x2E, 0x17, 0x1D, 0x58, 0x87, 0x65, 0xC4, 0x36, 0xA2, 0xA2, 0x05, 0xAD,
0x81, 0x51, 0xF3... | Rust | 0 |
from itertools import groupby
from statistics import mean
from typing import Literal
from roboquant.event import Event
from roboquant.signal import Signal
from roboquant.strategies.strategy import Strategy
class MultiStrategy(Strategy):
"""Combine multiple strategies. The MultiStrategy provides additional contro... | Python | 1 |
# /usr/bin/env python
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2025, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, ar... | Python | 1 |
return(&mut client, rpc::eth_get_code(contract_address, None));
if code.0.len() < 100 {
panic!("Invalid code length: {}", code.0.len());
}
}
#[test]
fn test_eth_sign() {
let mut client = ConnectionWrapper::new_from_env(None);
let address = match import_account(&mut client, H256::try_from(FIX_S... | Rust | 0 |
from __future__ import annotations
import json
from pathlib import Path
import streamlit as st
def load_jsonl(path: str | Path) -> list[dict]:
rows: list[dict] = []
with open(path, encoding="utf-8") as f:
for raw_line in f:
line = raw_line.strip()
if not line:
... | Python | 1 |
"",
precursor_mz,
precursor_charge,
mz_array.astype(np.float64),
int_array.astype(np.float32),
)
try:
spectrum.set_mz_range(self.min_mz, self.max_mz)
if len(spectrum.mz) == 0:
raise ValueError
sp... | Python | 1 |
)); // any value * inf => inf
}
#[test]
fn nans() {
let nans = nan_test_values();
for &a in &nans {
check_ne_rmax(a, a, 0.0);
check_ne_rmax(1.0, a, 1.0);
check_ne_rmax(a, 1.0, 1.0);
... | Rust | 0 |
](crate::output::AssociateRepositoryOutput)
pub fn builder() -> crate::output::associate_repository_output::Builder {
crate::output::associate_repository_output::Builder::default()
}
}
use std::fs::File;
use std::io::{Read, Write};
use std::ops::Try;
use std::path::{Path, PathBuf};
use failure::Fail;
u... | Rust | 0 |
= [0];
let size = try! (stream.read(&mut buf));
if size <= 0 {
return Err(Error::new(ErrorKind::InvalidInput, "Unexpected end of data"));
}
Ok(buf[0])
}
/// Reads exactly `len` bytes and gives you back a new vector of length
/// `len`
///
/// # Error
///
/// Fails with the same conditions as `read`. Additionall... | Rust | 0 |
#!/usr/bin/env python
# Copyright 2018 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Python | 1 |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from rekognition_online_action_detection.utils.parser import load_cfg
from rekognition_online_action_detection.utils.env import setup_environment
from rekognition_online_action_detection.utils.checkpointer import... | Python | 1 |
enum,
src_alpha: GLenum,
dst_alpha: GLenum,
) {
unsafe {
self.context
.blend_func_separate(src_rgb, dst_rgb, src_alpha, dst_alpha)
}
}
fn blend_func(
&self,
sfactor: GLenum,
dfactor: GLenum,
) {
// TODO(gijs) : ... | Rust | 0 |
}**: An email address that represents a Google group. For example, admins@example.com.
* **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
* **projectOwner:projectid**: Owners of the given project.... | Python | 1 |
from llama_index.readers.myscale.base import (
MyScaleReader,
escape_str,
format_list_to_string,
)
__all__ = ["MyScaleReader", "escape_str", "format_list_to_string"]
| Python | 1 |
";
pub const END_GOSSIP_SIGNED_VOTE: &str = "/gossip/consensus/signed_vote";
pub const END_GOSSIP_AGGREGATED_VOTE: &str = "/gossip/consensus/qc";
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Proposal(pub Vec<u8>);
impl<C: Codec> From<SignedProposal<C>> for Proposal {
fn from(proposal:... | Rust | 0 |
Socket\0", "(Ljava/net/Socket;Ljava/lang/String;IZ)Ljava/net/Socket;\0");
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
}
}
#[doc = "Reader of register SMCAPTCOMPA"]
pub type R = crate::R<u16, super::SMCAPTCOMPA>;
#[doc = "Writer for registe... | Rust | 0 |
(TaggingRule.id.in_(rule_ids)).all()
if len(rules) != len(rule_ids):
return jsonify({'success': False, 'message': 'Some rules not found'}), 404
rule_names = [rule.name for rule in rules]
# Delete all rules (cascade should handle execution logs)
for rule in rules:
... | Python | 1 |
snapshot.
Note that this method is deprecated and is left for the backward compatibility
purposes only. Please use the `pw.persistence.Config` constructor instead.
Args:
backend: storage backend settings;
snapshot_interval_ms: the desired freshness of the persisted snap... | Python | 1 |
def test_two_step_model_with_freeu(self):
expected_video = []
pipe = TextToVideoSDPipeline.from_pretrained(
'damo-vilab/text-to-video-ms-1.7b')
pipe = pipe.to(torch_device)
prompt = 'Spiderman is surfing'
generator = torch.Generator(device='cpu').manual_seed(0)
pipe.enable_freeu(s1=0.9, ... | Python | 1 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Nicolas Iooss, SUTD
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the... | Python | 1 |
ssert_eq!(211, Credit::user_credit(alice()).unwrap().credit);
let mut events = <frame_system::Pallet<Test>>::events();
assert_eq!(
events.pop().expect("should get first events").event,
crate::tests::Event::from(pallet_credit::Event::CreditDataAddedByTraffic(alice(), 211))
... | Rust | 0 |
fn in_memory_storage() -> Arc<Mutex<FrontendStorage<InMemoryStorage>>> {
Arc::new(Mutex::new(FrontendStorage::new(InMemoryStorage::default()).unwrap()))
}
}
<reponame>bbvch/ESE2016-HorizontErweitern-CodeBeispiele
fn worker(value: Arc<Mutex<i32>>) {
let mut val = value.lock().unwrap();
println!(... | Rust | 0 |
y {v: v, sig: sig };
if a.sig.as_bytes()[0] != ffi::DBUS_TYPE_ARRAY as u8 { return Err(ArrayError::InvalidSignature) }
{
let esig = a.element_signature();
for i in &a.v {
let b = if let MessageItem::DictEntry(ref k, ref v) = *i {
let s = forma... | Rust | 0 |
{
pub fn new(max_height: f64, max_order: usize, eps: f64) -> Self {
// TODO: need analysis
let lo_eps = 1e-3;
let lo = HardyZ::<f64>::new(max_height, max_order, lo_eps);
let hi = HardyZ::<T>::new(max_height, max_order, eps);
Self { lo, hi, lo_eps }
}
pub fn query(&m... | Rust | 0 |
from unittest.mock import patch
import pytest
from src.infrastructure.services.resend.resend_service import send_email
class TestResendService:
@patch("src.infrastructure.services.resend.resend_service.resend.Emails.send")
def test_send_email_success(self, mock_send):
mock_send.return_value = {"id":... | Python | 1 |
/// only use in debug mode
pub fn validate(mut self) -> bool {
true
}
pub fn dispatch_compute(mut self) -> bool {
true
}
pub fn set_enable_program_pipeline(mut self, enable: bool) {
self.enable_program_pipeline = enable;
}
pub fn set_enable_merge_vertex_buffe... | Rust | 0 |
from turtle import Screen, Turtle
import random
scr = Screen()
scr.setup(width=500, height=500)
tl = Turtle()
tl.pensize(5)
cor = [] #list for the coordinates
colors = [] #list for the random colors
#code to generate random colors
for v in range(200):
color = ('#' + ''.join(random.choices('0123456789ABCDEF', k... | Python | 1 |
nt);
}
extern "C" {
pub fn cuda_get_context() -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn free_ptrs(ptrs: *mut *mut ::std::os::raw::c_void, n: ::std::os::raw::c_int);
}
extern "C" {
pub fn top_k(
a: *mut f32,
n: ::std::os::raw::c_int,
k: ::std::os::raw::c_int,
index... | Rust | 0 |
codingError(format!("{}", err)),
WireError(err) => Error::EncodingError(format!("{:?}", err)),
Utf8(err) => Error::EncodingError(format!("{}", err)),
MessageNotInitialized { message: err } => Error::EncodingError(err.to_string()),
}
}
}
impl From<SendError> for Error {
... | Rust | 0 |
()
);
let phrase = b"hello world hello hello world!";
let glz = GLZ::from_seed(None, 5, 3, phrase.iter().copied());
assert_eq!(glz.k(), 2);
assert_eq!(glz.encode(phrase)?.len(), 67);
assert_eq!(
glz.decode::<u8>(&glz.encode(phrase)?)?,
phrase.to_v... | Rust | 0 |
from _aqt.forms.browser_qt6 import *
| Python | 1 |
put_length, time_delta, energy_delta))
print(point_list)
return trigger_info
from deepspeed.profiling.flops_profiler import FlopsProfiler
def eval_triggers_v3(trigger_list, device, args, model_existing=None):
'''
Not only running time, but also the power consumption is recorded.
'''
to... | Python | 1 |
Returns the last address offset which resulted in a parity error during an SRAM read. The address offset returned is always the word-aligned address that contains the location with the parity error. For parity faults on non word-aligned accesses, CPU_SCS:BFAR.ADDRESS will hold the address of the location that resulted... | Rust | 0 |
_as_json()?;
res = res.merge(j);
}
Ok(Datum::Json(res))
}
fn eval_json_object(&mut self, ctx: &EvalContext, expr: &Expr) -> Result<Datum> {
let children = self.eval_more_children(ctx, expr, 0)?;
let obj = json_object(children)?;
Ok(Datum::Json(obj))
}
... | Rust | 0 |
from wonderwords import RandomWord
wordgenerator = RandomWord()
lives = 10
# while lives <= 0:
# lives = int(input("Choose the number of lives you want to have: "))
def getWord():
return wordgenerator.word(word_min_length = 5, include_parts_of_speech=["noun"])
word = getWord()
guessedLetters = []
def getUserInp... | Python | 1 |
ensure that they are not dropped before all missing content is fetched
#[derive(Debug)]
pub(crate) struct RsState {
o_am_rscore: Option<AmRsCore>,
next_rows: Vec<Row>,
row_iter: <Vec<Row> as IntoIterator>::IntoIter,
server_usage: ServerUsage,
}
impl RsState {
fn fetch_all(&mut self, a_rsmd: &Arc<Re... | Rust | 0 |
write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [swtrig](swtrig) module"]
pub type SWTRIG = crate::Reg<u32, _SWTRIG>;
#[all... | Rust | 0 |
rn
print("\n=== パターン15 V3 基準値調整と詳細分析結果 ===")
# 調整パターン比較
comparison = results.get("comparison", {})
print(f"\n📊 調整パターン比較:")
pattern_comparison = comparison.get("pattern_comparison", {})
for pattern_name, pattern_data in pattern_comparison.items():
print(f"\n🔧 {pattern_name}:")
... | Python | 1 |
hoice(ref lhs, ref rhs) => {
check_expr(lhs, rules, trace).or_else(|| check_expr(rhs, rules, trace))
}
ParserExpr::Rep(ref node) => check_expr(node, rules, trace),
ParserExpr::RepOnce(ref node) => check_expr(node, rules, trace),
ParserExpr::Opt(ref node) => check_expr(node, r... | Rust | 0 |
0b000u32,
McoClockSys => 0b100u32,
McoClockHSI => 0b101u32,
McoClockHSE => 0b110u32,
McoClockPLL => 0b111u32,
};
rcc.cfgr.set_mco(mco_select);
}
/// Returns AHB clock frequency
pub fn get_ahb_frequency(&self) -> u32 {
let shift = match self.ahb_prescaler {
... | Rust | 0 |
13: 0,
r12: 0,
pbp: 0,
rbx: Box::into_raw(Box::new(g)) as usize,
ret_address: real_thread_start::<G> as usize as *const u8,
};
// allocate a stack frame for new thread
let stack = BuddyAllocator::lock().allocate_level(THREAD_STACK_BUDDY_LEVEL)
.expect("Failed to allo... | Rust | 0 |
objc_retain(self.ptr.as_ptr() as *mut Object);
Arc::new_unchecked(self.ptr.as_ptr())
}
}
}
impl<T> Drop for Arc<T> {
fn drop(&mut self) {
unsafe { objc_release(self.ptr.as_ptr() as *mut Object) }
}
}
impl<T> Deref for Arc<T> {
type Target = T;
fn deref(&sel... | Rust | 0 |
const_slice_from_raw_parts,
slice_from_ptr_range,
const_slice_from_ptr_range,
pointer_byte_offsets,
const_pointer_byte_offsets
)]
use std::{
mem::{size_of, MaybeUninit},
ptr,
slice::{from_ptr_range, from_raw_parts},
};
// Null is never valid for reads
pub static S0: &[u32] = unsafe { from... | Rust | 0 |
&self,
n: N,
step: N,
) -> Option<N> {
if self.is_positive() {
n.checked_add(&step)
} else {
n.checked_sub(&step)
}
}
/// Adds or subtracts a 3D step from the array depending on the direction, returns `None` on overflow
/// ```
/// us... | Rust | 0 |
end function td
subroutine s0(t0,value)
real :: value
real :: t0
!f2py intent(out) t0
t0 = value
end subroutine s0
subroutine s4(t4,value)
real(kind=4) :: value
real(kind=4) :: t4
!f2py intent(out) t4
t4 = value
end subroutine... | Python | 1 |
self._get_status(test),
self._build_keywords(test.keywords, split=True))
class KeywordBuilder(_Builder):
_types = {'kw': 0, 'setup': 1, 'teardown': 2, 'for': 3, 'foritem': 4}
def __init__(self, context):
_Builder.__init__(self, context)
self._build_keyw... | Python | 1 |
}
// Selecting heater T,P oversampling for the sensor
if desired_settings
.contains(DesiredSensorSettings::OST_SEL | DesiredSensorSettings::OSP_SEL)
{
let mut data =
I2CUtil::read_byte(&mut self.i2c, self.dev_id.addr(), BME680_CONF_T_P_MODE_ADDR)?;
... | Rust | 0 |
from setuptools import setup, find_packages
setup(
name="neurospace-bridge",
version="0.1.0",
packages=find_packages(),
install_requires=[
"torch>=1.13.0",
"requests>=2.28.0",
],
author="NeuroSpark Team",
author_email="team@neurospark.ai",
description="Bridge for capturi... | Python | 1 |
10000)
print(f"new seed: {config.seed}")
print(f"*********** finding potential resume checkpoints ***********")
possible_ckpt_path = os.path.join(config.save_dir_path, "last.ckpt")
if os.path.exists(possible_ckpt_path):
pass
elif hasattr(config, "resume_ckpt_path"):
possible_ckp... | Python | 1 |
: 0001
Hash: SHA512
MHF: Identity
KDF: HKDF-SHA512
MAC: HMAC-SHA512
EnvelopeMode: 01
Group: ristretto255
Context: 4f50415155452d504f43
Nh: 64
Npk: 32
Nsk: 32
Nm: 64
Nx: 64
Nok: 32
~~~
#### Input Values
~~~
client_identity: 616c696365
server_identity: 626f62
oprf_seed: db5c1c16e264b8933d5da56439e7cfed23ab7287b474fe3cd... | Rust | 0 |
isplay, Formatter};
use chrono::NaiveDate;
use super::entry_traits::NewDBEntry;
use crate::db::schema::vacations;
/// The database model for vacations.
#[derive(Queryable, Debug)]
pub struct Vacation {
pub id: i32,
pub user_id: i32,
pub vacation_type_id: i32,
pub start_date: NaiveDate,
pub start_... | Rust | 0 |
"""
進度條組件
此模組提供各種進度條和狀態顯示組件。
"""
import streamlit as st
import time
from typing import Optional, Dict, Any
from datetime import datetime
class ProgressTracker:
"""進度追蹤器"""
def __init__(self, total_steps: int, title: str = "處理進度"):
"""
初始化進度追蹤器
Args:
total_steps: 總步驟數
... | Python | 1 |
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.workspace_id):
query['WorkspaceId'] = request.workspace_id
body = {}
if not UtilClient.is_unset(request.max_results):
body['MaxResults'] = request.max_results
if not UtilCli... | Python | 1 |
score, message, display_hole_card, game_stop
if game_stop == False:
# if the hand is in play, hit the player
if in_play:
if player_hand.get_value() <= 21:
player_hand.add_card(game_deck.deal_card())
if player_hand.get_value() > 21:
... | Python | 1 |
rihi",
],
},
#[cfg(feature = "he")]
crate::Annotation {
lang: "he",
tts: Some("מסגרת עם תמונה"),
keywords: &[
"אמנות",
"מוזיאון",
"מסגרת",
"מסגרת עם תמונה",
"ציור",
... | Rust | 0 |
LD_L4_SRC_PORT]
if lag_hash_ipv4 is None:
# create new hash
s32list = sai_thrift_s32_list_t(
count=len(hash_fields_list), int32list=hash_fields_list)
lag_hash_ipv4 = sai_thrift_create_hash(
self.client, native_hash_field_list=s32list)
... | Python | 1 |
=> s,
None => panic!("Trying to build program without source."),
}
}
// Later: check pipelines
pub fn get_functions(&self) -> Vec<String> {
let mut fn_vec = Vec::with_capacity(self.functions.len());
for f in &self.functions {
fn_vec.push(f.clone());
}... | Rust | 0 |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from typing import List
from .drucksache import Drucksache
from .list_response_base import ListResponseBase
__all__ = ["DrucksacheListResponse"]
class DrucksacheListResponse(ListResponseBase):
documents: List[Drucksache]
| Python | 1 |
ITE: rustcardium::Color = rustcardium::Color {
r: 255,
g: 255,
b: 255,
};
const RED: rustcardium::Color = rustcardium::Color { r: 255, g: 0, b: 0 };
const GREEN: rustcardium::Color = rustcardium::Color { r: 0, g: 255, b: 0 };
const BLUE: rustcardium::Color = rustcardium::Color { r: 0, g: 0, b: 255 };
main... | Rust | 0 |
next_base_fee < *MINIMUM_BASE_FEE {
next_base_fee = MINIMUM_BASE_FEE.clone();
}
next_base_fee
}
pub fn compute_base_fee<DB>(db: &DB, ts: &Tipset) -> Result<BigInt, crate::Error>
where
DB: BlockStore,
{
let mut total_limit = 0;
let mut seen = HashSet::new();
// Add all unique messages' ... | Rust | 0 |
# While loop
# it works until the condition is true
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i) # Result: 1 2 4 5 6
print()
# Printing a message once the condition is false
i = 0
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6") | Python | 1 |
= convert(items.iter().cloned());
assert_eq!(it.clone().nth(0), Some(&0));
assert_eq!(it.clone().nth(1), Some(&1));
assert_eq!(it.clone().nth(2), None);
}
#[test]
fn filter_map() {
let items = [0u8, 1, 1, 2, 4];
let it = convert(items.iter()).filter_map(|&&i| if i %... | Rust | 0 |
lowerlimit += 1
else:
break
if counted > 0:
for item in thelist:
Globals.ADDON_SETTINGS.setSetting("Channel_" + str(currentchan) + "_type", str(chantype))
Globals.ADDON_SETTINGS.setSetting("Channel_... | Python | 1 |
d((By.CLASS_NAME, "author-title"))).text
dob = driver.find_element(By.CLASS_NAME, "author-born-date").text
location = driver.find_element(By.CLASS_NAME, "author-born-location").text
description = driver.find_element(By.CLASS_NAME, "author-description").text
except TimeoutException:
p... | Python | 1 |
u64;
pub struct ClientConnection {
protocol: Protocol,
enabled_protocols: Vec<CustomProtocol>,
}
impl Default for ClientConnection {
fn default() -> Self {
ClientConnection {
protocol: Protocol::Connect,
enabled_protocols: vec![],
}
}
}
#[derive(Hash, PartialE... | Rust | 0 |
ar = 13,
/// characters that introduce comments (`%`)
Comment = 14,
/// specify delimiter numerically (`\delimiter`)
DelimNum = 15,
// Next are the ordinary run-of-the-mill command codes. Codes that are
// `min_internal` or more represent internal quantities that might be
// expanded by `\... | Rust | 0 |
{println!("{},", v)});
///
/// // print log:
/// // 123
/// // 123
/// // 123
/// ```
pub fn repeat<Item>(
v: Item,
n: usize,
) -> ObservableBase<IterEmitter<Take<Repeat<Item>>>>
where
Item: Clone,
{
from_iter(std::iter::repeat(v).take(n))
}
#[cfg(test)]
mod test {
use crate::prelude::*;
use bencher::Benc... | Rust | 0 |
= mac(r5, self.0[3], rhs.0[2], carry);
let (r6, r7) = mac(r6, self.0[3], rhs.0[3], carry);
Fp::montgomery_reduce(r0, r1, r2, r3, r4, r5, r6, r7)
}
/// Subtracts `rhs` from `self`, returning the result.
#[inline]
pub const fn sub(&self, rhs: &Self) -> Self {
let (d0, borrow) = ... | Rust | 0 |
s_comparison']['fgsm_avg_success_rate']:.3f}\n")
f.write(f" PGD攻击平均成功率: {analysis['robustness_comparison']['pgd_avg_success_rate']:.3f}\n")
f.write(f" 更有效的攻击方法: {analysis['robustness_comparison']['more_effective_attack']}\n\n")
f.write("3. 优化建议\n")
for i,... | Python | 1 |
the possible encodings
///
/// Returns an array of data with its associated encoding, along with an encoded dictionary
pub fn byte_array_all_encodings(
data: Vec<impl Into<ByteArray>>,
) -> (Vec<(Encoding, ByteBufferPtr)>, ByteBufferPtr) {
let data: Vec<_> = data.into_iter().map(Into::into).collect();
let ... | Rust | 0 |
id(&self) -> &str {
match self {
DamlValueName::Local(local) => local.package_id(),
DamlValueName::NonLocal(non_local) => non_local.target_package_id(),
}
}
pub fn package_name(&self) -> &str {
match self {
DamlValueName::Local(local) => local.package... | Rust | 0 |
contains(e));
}
for sheet_name in &sheet_names {
let mut sheet_output = vec![];
if let Some(Ok(current_sheet)) = ods.worksheet_range(sheet_name) {
for row in current_sheet.rows() {
let mut row_output = IndexMap::new();
for (i, cell) in row.iter().enu... | Rust | 0 |
# Importamos la biblioteca reflex y los módulos necesarios
import reflex as rx
from .app_state import inicializar_datos # Importamos la función para inicializar los datos de la aplicación
from .pages.index import index # Importamos la página principal (índice)
from .pages.catalogo import catalogo # Importamos la pág... | Python | 1 |
"""Module for base class of Circle and Sphere."""
from typing import cast
import numpy as np
from skspatial._functions import _contains_point
from skspatial.objects._base_spatial import _BaseSpatial
from skspatial.objects.point import Point
from skspatial.objects.vector import Vector
from skspatial.typing import arr... | Python | 1 |
print("\nDiscovered subdomains:")
for subdomain in found:
print(f"{Fore.GREEN}[+]{Style.RESET_ALL} {subdomain}")
save_choice = input(
f"\n{Fore.BLUE}[?]{Style.RESET_ALL} Do you want to save results to JSON? (y/n): "
)
... | Python | 1 |
# Control Flow with if / else and Conditional Operators
"""
1. == (sama dengan): x == y (True jika x sama dengan y)
2. != (tidak sama dengan): x != y (True jika x tidak sama dengan y)
3. < (kurang dari): x < y (True jika x kurang dari y)
4. > (lebih besar dari): x > y (True jika x lebih besar dari y)
5. <= (kurang... | Python | 1 |
mangle]
static mut glDebugMessageCallbackKHR: PFNGLDEBUGMESSAGECALLBACKKHRPROC;
#[no_mangle]
static mut glDebugMessageControlKHR: PFNGLDEBUGMESSAGECONTROLKHRPROC;
#[no_mangle]
static mut glPopDebugGroupKHR: PFNGLPOPDEBUGGROUPKHRPROC;
#[no_mangle]
static mut glPushDebugGroupKHR: PFNGLPUSHDEBU... | Rust | 0 |
e client proof M
//M1 = H( (H(N) ^ H(G)) | H(I) | s | A | B | K )
let mut m1d = sha1::Sha1::new();
m1d.update(&ngh);
m1d.update(&Ih);
m1d.update(&self.s.to_bytes_be().1);
m1d.update(&abr);
m1d.update(&br);
m1d.update(&K);
let M1 = m1d.digest().by... | Rust | 0 |
CGDisplayBlendNormal: f32 = 0.0;
pub const kCGDisplayBlendSolidColor: f32 = 1.0;
pub type CGDisplayFadeReservationToken = u32;
pub const kCGDisplayFadeReservationInvalidToken: CGDisplayFadeReservationToken = 0;
pub type Boolean = u8;
pub const FALSE: Boolean = 0;
pub const TRUE: Boolean = 1;
pub const kCGErrorSucces... | Rust | 0 |
looks like
// a method call. Shift the `rest` boundary to include '.'.
input.slice(last_consumed_byte_index..)
} else {
rest
}
}
macro_rules! impl_num_literal_for_uint {
($($num:ident),+) => {
$(
impl NumLiteral for $num {
fn parse(input: InputSpan<'_>) -... | Rust | 0 |
TagView(View):
def get(self, request, pk):
tags = Tag.objects.all()
articles = Tag.objects.get(id=int(pk)).article_set.all()
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
p = Paginator(articles, 9, request=request)
... | Python | 1 |
tot = 0
observations.append([char])
actions.append([move_map[tt % len(move_map)],
tt % 3 == 2 or tt == 3 * t, tot])
rewards.append(tt % 3 == 2 or tt == 3 * t)
else:
assert False, 'No expert trajectories for env %s' % env_str
actions = [
env_spec.convert_env_a... | Python | 1 |
def __init__(self, num_attention_heads: int=16, attention_head_dim: int=88,
in_channels: Optional[int]=None, num_layers: int=1, dropout: float=0.0,
norm_num_groups: int=32, cross_attention_dim: Optional[int]=None,
attention_bias: bool=False, sample_size: Optional[int]=None,
num_vector_embeds: Optional[i... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.