text string | label_name string | labels int64 |
|---|---|---|
"factories": openapi.Schema(
type=openapi.TYPE_INTEGER, description="工廠數量"
),
"documents": openapi.Schema(
type=openapi.TYPE_INTEGER, description="公文數量"
),
... | Python | 1 |
#!/usr/bin/env python3
"""
Route module for the API
"""
from os import getenv
from api.v1.views import app_views
from flask import Flask, jsonify, abort, request
from flask_cors import (CORS, cross_origin)
import os
app = Flask(__name__)
app.register_blueprint(app_views)
CORS(app, resources={r"/api/v1/*": {"origins":... | Python | 1 |
" Return value:"]
#[doc = " None."]
#[doc = " Comments:"]
#[doc = " You have to call this function before you can call any PDF"]
#[doc = " processing functions."]
pub fn FPDF_InitLibraryWithConfig(config: *const FPDF_LIBRARY_CONFIG);
}
extern "C" {
#[doc = " Function:... | Rust | 0 |
:type is_retry: bool, optional
:param is_skip: 是否将跳过设置为 True
:type is_skip: bool, optional
:param reset_retry: 是否重置重试次数
:type reset_retry: bool, optional
:param reset_skip: 是否重置跳过标志
:type reset_skip: bool, optional
:param error_ignored: 是否为忽略错误跳过
:t... | Python | 1 |
background=self.colors['bg_secondary'],
foreground=self.colors['accent_green'],
font=('Segoe UI', 10, 'bold'))
style.configure('Custom.TRadiobutton',
background=self.colors['bg_secondary'],
... | Python | 1 |
Msg::Firstaccept(first_accept_rpc(first_accept)),
PaxosMsg::AcceptDecide(accept_decide) => rpc_message::Msg::Acceptdecide(accept_decide_rpc(accept_decide)),
PaxosMsg::Accepted(accepted) => rpc_message::Msg::Accepted(accepted_rpc(accepted)),
PaxosMsg::Decide(decide) => rpc_message::Ms... | Rust | 0 |
get(), label='LKF_x3', color='pink', linewidth=2)
plt.plot(cp.array(x_lstm_output_data)[:, 2].get(), label='DKF_x3', color='green', linewidth=1)
plt.xlabel('data')
plt.ylabel('value')
plt.legend()
plt.title('Acc of estimate vs true')
# 估測狀態誤差匯出
x_k_update_data = cp.array(x_k_update_data).reshape(-1, 1) # reshape to 2... | Python | 1 |
':[u'أءزف'],
u'آزل':[u'أءزل'],
u'آزى':[u'أءزى', u'ءازى'],
u'آسب':[u'أءسب'],
u'آسد':[u'أءسد'],
u'آسف':[u'أءسف'],
u'آسن':[u'أءسن'],
#~ u'آسى':[u'ءاسى'],
u'آسى':[u'أءسى', u'ءاسى'],
u'آشى':[u'أءشى'],
u'آصد':[u'أءصد'],
u'آصر':[u'ءاصر'],
u'آصل':[u'أءصل'],
u'آضّ':[u'ءاضّ'],
u'آض':[u'ءاضّ'],
u'آطم':[u'أءطم'],
u... | Python | 1 |
for event in event_regex.captures_iter(&collection[1]) {
events.push((event[1].to_string(), event[2].parse::<i64>().unwrap(), event[3].parse::<i64>().unwrap()));
}
let behavior_regex = Regex::new(r"\(Behavior=(?:.*?)([[:word:]]*?)',LinkedVariables=\(ArrayIndexAndLength=(.*?)\),OutputLinks=\(ArrayIn... | Rust | 0 |
ne => {
// Didn't match.
}
some(item_ref) => {
// Check for duplicates.
match copy *item_ref {
some(original_def_id)
if original_def_id != item_def_id => {
self.session.err(fm... | Rust | 0 |
Server\"`*"]
pub const PROPERTY_USER_RADIUS_FRAMED_IPV6_ROUTE: USERPROPERTIES = 1034i32;
#[doc = "*Required features: `\"Win32_NetworkManagement_NetworkPolicyServer\"`*"]
pub const PROPERTY_USER_SAVED_RADIUS_FRAMED_IPV6_ROUTE: USERPROPERTIES = 1035i32;
#[doc = "*Required features: `\"Win32_NetworkManagement_NetworkPoli... | Rust | 0 |
nc fn create_order(
&mut self,
_: ObjectId,
_: String,
_: Option<f64>,
_: f64,
_: Option<OrderOption>,
) -> ThreadSafeResult<ObjectId> {
return Err(Box::new(ExecutionFailed::new(
"Call create_order from TestExecutorTrait.",
)));
}
async fn remove_order(
&mut self,
_:... | Rust | 0 |
) in arms.iter() { collect_expr(imported, expr) }
for stmt in stmts.iter() { collect_stmt(imported, stmt) }
},
spiral::Expr::Call(ref fun_e, ref args) => {
collect_expr(imported, fun_e);
for arg in args.iter() { collect_expr(imported, arg) }
},
spiral::Expr::Var(_) |
spiral::Expr::... | Rust | 0 |
oldest_remote {
Some(t) => t < last_delete,
None => true,
};
if !should_update_remote {
return Ok(());
}
conn.execute("DELETE FROM remote", NO_PARAMS)?;
let url = format!(
"{}/chunks/{}",
&state.config.server,
hex::encode(&state.secrets.bucket)
);... | Rust | 0 |
"""
Test script to verify piece type constants and movement rules
"""
import chess
import os
import sys
# Add the project directory to the Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Import the game's board module
from modules.board import GameBoard
def print_piece_types():
"""Pr... | Python | 1 |
AL` (`f64`).
//!
//! `ToSql` cannot fail and is therefore implemented for all number types that
//! can be losslessly converted to one of these types, i.e. `u8`, `u16`, `u32`,
//! `i8`, `i16`, `i32`, `i64`, `isize`, `f32` and `f64`. It is *not* implemented
//! for `u64` or `usize`.
//!
//! `FromSql` can fail, and is im... | Rust | 0 |
T>
where T: Foo
{
}
trait FooBar<T>
: Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt
where J: Bar
{
fn test();
}
trait WhereList<T, J>
where T: Foo,
J: Bar
{
}
use clap::ArgMatches;
use failure::{err_msg, Error};
pub fn run(m: &ArgMatches<'_>) -> Result<(), E... | Rust | 0 |
_color(theme.button_hover)
.press_color(theme.button_press)
.h(BUTTON_HEIGHT)
.border(0.0)
.label_font_size(24)
.label_font_id(*fonts.get("lato").unwrap())
.label_color(theme.text_secondary);
if base_button.clone()
.label("Rand... | Rust | 0 |
os.path.isdir(dir_name):
os.mkdir(dir_name)
#record every run
copyfile('./train.py', dir_name+'/train.py')
copyfile('./model.py', dir_name+'/model.py')
# save opts
with open('%s/opts.yaml'%dir_name,'w') as fp:
yaml.dump(vars(opt), fp, default_flow_style=False)
# model to gpu
model = model.cuda()
if fp16:
... | Python | 1 |
t = test_client.get_component(RootComponent)
text1, text2, text3 = test_client.get_components(rio.Text)
root.switch = False
await test_client.wait_for_refresh()
# The first Text should've been reconciled and thus have new text
assert text1.text == "1"
# The 2nd Text wa... | Python | 1 |
cessful.
///
/// # <weight>
/// - TODO
/// # </weight>
#[pallet::weight(T::WeightInfo::add_sword_holder(
T::MaxSwordHolder::get().into()
))]
pub fn add_sword_holder(
origin: OriginFor<T>,
sword_index: KYCIndex,
sword_info: IASInfo<BalanceOf<T>, T::AccountId>,
) -> DispatchResultWithPostInfo ... | Rust | 0 |
while True:
self.browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
sleep(2)
new_height = self.browser.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_heig... | Python | 1 |
"style" in attrs:
attrs["style"] = self._true_style(attrs.get("style"))
return attrs
def _get_link(self, attrs, name):
if name in attrs:
attrs[name] = self._true_url(attrs[name])
return attrs
def _wash_attr(self, attrs, tag):
if tag in self.tags_own_att... | Python | 1 |
wizzle))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<astcenc_swizzle>())).r as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(astcenc_swizzle),
"::",
stringify!(r)
)
);
assert_eq!(
unsafe { ... | Rust | 0 |
# Copyright: Daveight and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
"""
Python Template Generator API Implementation
"""
from anki.testing.framework.python.python_type_mapper import PythonTypeMapper
from anki.testing.framework.string_utils import render_template
from a... | Python | 1 |
# Python3 code to reverse sort a string using join() + sorted() + reverse
str1 = 'geekforgeeks'
res = ''.join(sorted(str1, reverse=True))
print('String after reverse sorting:', res)
| Python | 1 |
(name: &str) -> Vec<String> {
let mut acc = Vec::new();
for dir in fs_extra::dir::get_dir_content(name) {
for folder in dir.directories {
if folder != name {
acc.push(folder);
}
}
}
acc
}
pub fn new_rename_fake_changes(mut sphere: Sphere) -> Sphere... | Rust | 0 |
log::debug!("Converting typeof to 'object' as we know the value");
self.changed = true;
*e = Expr::Lit(Lit::Str(Str {
span: *span,
value: js_word!("object"),
has_escape: false,
... | Rust | 0 |
ne = line.partition('#')[0]
line = line.strip()
# ignore blank lines
if (line == ''):
continue
# obtain USVs
try:
(rstart, rend) = line.split('..')
except ValueError:
rstart = line
r... | Python | 1 |
60286430631959695527196086682743679891223825188641241941026621271870630295818915623452793880051225198569193330392182664554069336798956991617416155397921485027087036447505117497621833309124610867617410849282150608761866392801725241476299444278404028884371993204438739987255865433889636921252520607290752094659664799210408... | Python | 1 |
let mut lines = io::BufReader::new(child.stdout.expect("no stdout")).lines();
assert_eq!(lines.nth(1).unwrap().unwrap(), "hostname example.com");
}
#[test]
fn trailing_zero_width() {
// These happen because the check for "garbage" only looks at the _next_ argument,
// and it allows an empty string. In SS... | Rust | 0 |
(), Error>;
fn commit(&self) -> Result<(), Error>;
}
impl<'a> RootSaver for CotaSMT<'a> {
fn save_root_and_leaves(&self, leaves: Vec<(H256, H256)>) -> Result<(), Error> {
self.store()
.save_root(self.root())
.expect("Save smt root error");
if !leaves.is_empty() {
... | Rust | 0 |
e' in key:
# average the curve values
output_dict[key] = {m: np.array(output_dict[key][m], np.float64).mean(0).tolist()
for m in uncertainty_metrics}
else:
output_dict[key] = {m: np.array(output_dict[key][m], np.float64).mean() for m in uncerta... | Python | 1 |
/// If the named command does not exist, `None` is returned.
///
/// Command descriptions are separated by newlines. The returned string
/// should **not** end with a newline.
fn command_usage(command: &str) -> Option<&'static str>;
/// Returns a string listing available commands and help text.... | Rust | 0 |
r, UnitaryBuilder};
/// Apply the QFFT circuit to a given Register using the builder.
pub fn qfft<B: UnitaryBuilder>(builder: &mut B, r: Register) -> Register {
let mut rs = builder.split_all(r);
rs.reverse();
let rs = rec_qfft(builder, vec![], rs);
builder.merge(rs).unwrap()
}
fn rec_qfft<B: UnitaryB... | Rust | 0 |
t74(bx_dvqgnepb: w271pen2ijj, t84_z8pk61b, x3yrhay3yiy: mz14ssu_n4n, s9l9qpvmdnb: qofmxmy9ee1, n2fzs84v4og, afi3_mo_ji1: r48c55hwusq, f8e8s9vtp4l, n4oagd3ta9u: inu0htyh1tl, en492biq6be):
bj2jpn43qnl = ''
'# hatchet_canister_header -> machines_battleships_unions'
kht2fmcplbm.dar8d2pd9x1: False = erixmrv27ln
... | Python | 1 |
Ordering) -> bool {
ordering == Ordering::Equal
}
}
pub struct CmpOpNullEQ;
impl CmpOp for CmpOpNullEQ {
#[inline]
fn compare_null() -> Option<i64> {
Some(1)
}
#[inline]
fn compare_partial_null() -> Option<i64> {
Some(0)
}
#[inline]
fn compare_order(order... | Rust | 0 |
(())
}
pub mod error;
use std::{
collections::HashMap,
fs::{read, remove_file},
};
use uuid::Uuid;
use xlsxwriter::Workbook;
use self::error::ExcelError;
/// Excel export util
///
/// # Performance test
/// ```
/// 100000 rows, 10 columns, 4.332097613s
/// 100000 rows, 30 columns, 12.265614828s
/// 100000 r... | Rust | 0 |
,
},
proto::envelope::{DhtMessageType, OriginMac},
version::DhtProtocolVersion,
DhtConfig,
};
use bytes::Bytes;
use chrono::{DateTime, Utc};
use digest::Digest;
use futures::{
future,
future::BoxFuture,
stream::{self, StreamExt},
task::Context,
};
use log::*;
use rand::rngs::OsRng;
use s... | Rust | 0 |
# Modified version of code from here:
# https://github.com/tsuvihatu/openfermion-qiskit/blob/main/openfermionqiskit/qiskit_covertor.py
from openfermion.ops import QubitOperator
from qiskit.quantum_info import SparsePauliOp
def qubitop_to_pauliop(qubit_operator):
"""Convert an openfermion QubitOperator to a Qisk... | Python | 1 |
import pandas as pd
import numpy as np
import sklearn.metrics as skmetrics
from typing import List
def compute_metrics(y_true_list: List, y_pred_list: List, labels=['train', 'test']) -> pd.DataFrame:
results = []
for y_true, y_pred, split in zip(y_true_list, y_pred_list, labels):
fpr, tpr, thresholds... | Python | 1 |
from enum import Enum
from typing import Union
from fastapi import FastAPI
import uvicorn
app = FastAPI()
class ModelName(str, Enum):
alexnet = 'alexnet'
resnet = 'resnet'
lenet = 'lenet'
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
# 路径参数:在路径中使用{}括起来的参数,需要与函数中的... | Python | 1 |
from test_login import *
from features.ScheduleDelivery import ScheduleDeliveryPage
class TestScheduleDelivery(TestLogin):
def test_schedule_delivery(self, driver_setup):
TestLogin.test_valid_login(self, driver_setup)
schedule_delivery = ScheduleDeliveryPage(driver_setup)
schedule_delivery.Schedule()
... | Python | 1 |
match callback() {
Ok(ret) => return Ok(ret),
Err(ref e) if e.maybe_spurious() && remaining > 0 => {
let msg = format!("spurious network error ({} tries \
remaining): {}", remaining, e);
try!(config.shell().warn(msg));
... | Rust | 0 |
import random
# Charge toutes les lignes
with open("data/cleaned.txt", "r", encoding="utf-8") as f:
lines = [l for l in f if l.strip()]
random.shuffle(lines)
n = len(lines)
train, valid, test = (
lines[: int(0.8*n)],
lines[int(0.8*n) : int(0.9*n)],
lines[int(0.9*n) :],
)
for name, chunk in [("train",... | Python | 1 |
$set_bool($container, "doctest", $target.doctest);
$set_bool($container, "bench", $target.bench);
$set_bool($container, "doc", $target.doc);
$set_bool($container, "plugin", $target.plugin);
$set_bool($container, "harness", $target.harness);
)
}
fn entry_kind(e: EntryRef) -> &'s... | Rust | 0 |
tep - Watch SOP Class - Trial (Retired)
///
/// - **UID:** 1.2.840.10008.5.1.4.34.4.2
/// - **UID Type:** SOP Class
pub static UnifiedProcedureStepWatchSOPClassTrial: UID = UID {
ident: "UnifiedProcedureStepWatchSOPClassTrial",
uid: "1.2.840.10008.5.1.4.34.4.2",
name: "Unified Procedure Step - Watch SOP Cla... | Rust | 0 |
&$target {
&self.$($target_code)+
}
}
impl $(< $($impl_gen)+ >)? PartialEq for $tp {
fn eq(&self, other: &Self) -> bool {
self.$($target_code)+$( $($to_handle_code)+ )? == other.$($target_code)+$( $($to_handle_code)+ )?
}
}
impl $(< $($impl_gen)+ >)? Eq for $tp {}
impl $(< $($impl_gen)+ >)?... | Rust | 0 |
ower().endswith(('.jpg', '.jpeg')):
converted_file = ytg.convert_jpeg_to_png(first_file)
if converted_file and os.path.exists(converted_file):
thumb = get_thumbnail_data(converted_file)
if thumb:
window["-IMAGE_PREVIEW-"].up... | Python | 1 |
AttributeId, EditorContext, Hoverable, InputPinId, Link, LinkId, MiniMapLocation, NodeId,
OutputPinId, PinId, PinShape,
};
/// entry point
#[doc(alias = "BeginNodeEditor", alias = "EndNodeEditor")]
pub fn editor<F: FnOnce(EditorScope)>(context: &mut EditorContext, f: F) -> OuterScope {
context.set_as_current_... | Rust | 0 |
in range(min_num_layers):
inputs_or_outputs[f"{name}.{i}.decoder.key"] = {0: "batch", 2: decoder_sequence}
inputs_or_outputs[f"{name}.{i}.decoder.value"] = {0: "batch", 2: decoder_sequence}
inputs_or_outputs[f"{name}.{i}.encoder.key"] = {0: "batch", 2: encoder_sequence}
... | Python | 1 |
(ids, tree) {
Err(_) => {
trans.set_rollback();
trans.finish().unwrap();
return Err(status::Custom(HTTPStatus::InternalServerError, String::from("Could not format diffResult XML")));
},
Ok(diffres) => diffres
};
match delta::modify(&delta_id, &trans, ... | Rust | 0 |
.to_str_radix (10)));
prop_assert_eq!(perfect_result, BigInt::from (result))
}
#[test]
fn randomly_test_overflow_checked_shl (input in any::<i32>(), shift in 0u32..40) {
let result = overflow_checked_shl (input, shift);
let perfect_result = BigInt::from (input) << shift as usize;
pr... | Rust | 0 |
state: PeripheralMutex<'d, Inner<'d, TX, RX>>,
pins: [AnyPin; 9],
_phy: P,
clock_range: Cr,
phy_addr: u8,
mac_addr: [u8; 6],
}
impl<'d, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, P, TX, RX> {
/// safety: the returned instance is not leak-safe
pub unsafe fn new(
stat... | Rust | 0 |
arg)*) );
}
#[macro_export]
macro_rules! warn {
($($arg:tt)*) => ($crate::log!($crate::log::Level::Warn, $($arg)*));
}
#[macro_export]
macro_rules! info {
($($arg:tt)*) => ($crate::log!($crate::log::Level::Info, $($arg)*));
}
#[macro_export]
macro_rules! debug {
($($arg:tt)*) => ($crate::log!($crate::log::L... | Rust | 0 |
{ ({Custom}), (&{SliceCustom}), rev };
/// // NOTE: `std::borrow::Borrow for AsciiString` is required by `Cow`.
/// { ({Custom}), (Cow<{SliceCustom}>), rev };
/// /* ... and more pairs! */
/// }
/// ```
///
/// ## Core and alloc
///
/// For `no_std` use, the macro uses custom `core` and `alloc` crate if g... | Rust | 0 |
, ub, f_ieqcons=problem.inequality_constraint, kwargs={}, swarmsize=pop_size ,\
omega=0.5, phip=0.5, phig=0.5, maxiter=1000, minstep=1e-4, minfunc=1e-4, debug=False)
else:
outputs = sp.optimize.minimize(wrapper,x,method=solver)
return outputs
## @i... | Python | 1 |
import os
from typing import Iterable
import torch
import torchaudio
from loguru import logger
from pyannote.audio import Pipeline
from pyannote.core import Segment
class DiarizationSegment:
def __init__(self, segment: Segment, label: str, speaker: str):
self.segment = segment
self.label = label
... | Python | 1 |
output = self.r4(output)
output = self.c4(output)# 2 x 224 x 224
return output
# sin-cos position encoding
# https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/master/transformer/Models.py#L31
def get_sinusoid_encoding_table(n_position, d_hid):
''' Sinusoid position e... | Python | 1 |
from flask import Blueprint, request, jsonify
from ..modelos.reportes import ReportesModel
reportes_endpoints = Blueprint('reportes_endpoints', __name__)
# Reporte: ventas de un usuario
@reportes_endpoints.route('/reportes/ventas_usuario', methods=['GET'])
def ventas_usuario():
id_usuario = request.args.get('usua... | Python | 1 |
wrap();
let context = PortMidi::new().unwrap();
let device_id = matches.opt_str("device_id");
let device_id = match device_id {
Some(v) => v.parse::<i32>().unwrap(),
Nothing => {
print_devices(&context);
return;
}
};
println!("Device: {}", device_id... | Rust | 0 |
import random
import sys
import time
from typing import List, Tuple, Dict
import numpy as np
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import QEasingCurve, QTimer
from Calculator import find_merge_positions, slide_distance
from Config import SingletonConfig
from MinigameMover import MinigameBoardMo... | Python | 1 |
tem,host=local,region=A load1=1.2,load2=2.2 200",
"system,host=remote,region=B load1=10.1,load2=2.1 100",
];
let lp_lines2 = vec![
"system,host=remote,region=B load1=10.2,load2=20.2 200",
"system,host=local,region=C load1=100.1,load2=200.1 100",
"aa_syste... | Rust | 0 |
num_reqs=4,
num_batches=2)
# The slow node is behind
checkNodeDataForInequality(slow_node, *other_nodes)
# PRE-PREPARE were not requested
assert count_requested_preprepare_resp(slow_node) == old_count_resp
slow_node.nodeIbStasher.reset_de... | Python | 1 |
expected: "AddInt32".to_owned(),
found: format!("{:?}", other),
}
.into(),
),
},
(AddUInt64(i), b) => match b {
AddInt32(j) => AddInt32(u64_wrapping_addition(i, j)),
... | Rust | 0 |
import pandas as pd
from evals.analysis.james.james_analysis import get_single_hue
from evals.analysis.james.plotting.plot_response_property_with_baseline import (
create_chart,
)
from evals.locations import EXP_DIR
def cross_training():
"""
--val_tasks='{"survival_instinct": ["matches_survival_instinct"... | Python | 1 |
parts(ptr, 1)
}
}
pub struct SlowTimer {
slow_time: Duration,
t: Instant,
}
impl SlowTimer {
pub fn new() -> SlowTimer {
SlowTimer::default()
}
pub fn from(slow_time: Duration) -> SlowTimer {
SlowTimer {
slow_time: slow_time,
t: Instant::now(),
... | Rust | 0 |
ror> {
if cipher.len() < aes::BLOCK_LEN * 3 {
return Err(Error::InvalidLength);
}
// if the second and third ciphertext block are the same, it's ECB, otherwise CBC
if cipher[aes::BLOCK_LEN..aes::BLOCK_LEN * 2] == cipher[aes::BLOCK_LEN * 2..aes::BLOCK_LEN * 3]
{
Ok(AesMode::Ecb)
... | Rust | 0 |
"WebBack".into(),
VirtualKeyCode::WebFavorites => "WebFavorites".into(),
VirtualKeyCode::WebForward => "WebForward".into(),
VirtualKeyCode::WebHome => "WebHome".into(),
VirtualKeyCode::WebRefresh => "WebRefresh".into(),
VirtualKeyCode::WebSearch => "WebSearch".into(),
VirtualKeyCode::WebStop => "WebStop".in... | Rust | 0 |
}
else {
if capacity <= 70 {
writer.write_all(format!("{} {}%\n", "", capacity).as_bytes()).unwrap();
}
else {
writer.write_all(format!("{} {}%\n", "", capacity).as_bytes()).unwrap();
}
}
}
else if capacity <= 90 {
if status != String::from("Discharging") {
writer.write_all(format!("{}... | Rust | 0 |
rg = KRPC.Argument()
arg.position = 0
arg.value = self.encode_int32(42)
call.arguments.extend([arg])
request = KRPC.MultiplexedRequest()
request.request.calls.extend([call])
self.rpc_send(request)
response = self.rpc_recv(KRPC.MultiplexedResponse).response
... | Python | 1 |
ey_id())
}
}
#[derive(Clone, Copy)]
pub struct ImmutableGetRequestReceiptsForBlockParams {
pub(crate) id: i32,
}
impl ImmutableGetRequestReceiptsForBlockParams {
pub fn block_index(&self) -> ScImmutableInt32 {
ScImmutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id())
}
}
#[derive(Clone, Copy)]
pub s... | Rust | 0 |
"""Models for Playlist app."""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Playlist(db.Model):
"""Playlist model."""
__tablename__ = "playlists"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
description = db.Column(db.String(25... | Python | 1 |
", encoding="utf-8") as file:
file.write(_TEST_MAPPING_WITH_SUPPORTED_COMMENTS)
with open(self.test_mapping_file, "r", encoding="utf-8") as file:
android_test_mapping_format.process_file(file.read())
def test_valid_test_mapping_file_with_non_supported_comments(self):
"""Veri... | Python | 1 |
ra.split("\t")
return linked_titles_all
def load_para_and_linked_titles_dict_from_tfidf_id(tfidf_id, db):
"""
load paragraphs and hyperlinked titles from DB.
This method is mainly for Natural Questions Open benchmark.
"""
# will be fixed in the later version; current tfidf weights use indexed ... | Python | 1 |
* b), Mask::from_array([false, true, true, false]));
assert_eq!(a.lanes_lt(i32x4::splat(5) * b), Mask::from_array([false, false, true, false]));
assert_eq!(a.lanes_ge(i32x4::splat(5) * b), Mask::from_array([true, true, false, true]));
assert_eq!(a.lanes_gt(i32x4::splat(5) * b), Mask::from_array([true, fals... | Rust | 0 |
"""
批量操作管理器
提供統一的批量操作功能,包括:
- 批量策略執行
- 批量數據更新
- 批量交易訂單處理
- 批量風險管理操作
- 進度追蹤和錯誤處理
"""
import time
import asyncio
import threading
from typing import Any, Dict, List, Optional, Callable, Union, Tuple
from enum import Enum
from datetime import datetime, timedelta
from dataclasses import dataclass
import streamlit as st
i... | Python | 1 |
'Default plugin implementations'
from .hookspec import hookimpl
from .hookspec import USBQPluginDef
@hookimpl
def usbq_declare_plugins():
# These are the bundled plugins.
return {
'proxy': USBQPluginDef(
name='proxy',
desc='Send and receive USB packets from a USBQ proxy device ... | Python | 1 |
def solve():
import sys
# Set the default input filename
input_filename = 'input.txt'
# Open the input file
with open(input_filename, 'r') as input_source:
data = input_source.read().splitlines()
T = int(data[0]) # number of test cases
output = []
index = 1
for t in rang... | Python | 1 |
fn parse_formula(
mut rgce: &[u8],
sheets: &[String],
names: &[(String, String)],
) -> Result<String, XlsbError> {
if rgce.is_empty() {
return Ok(String::new());
}
let mut stack = Vec::new();
let mut formula = String::with_capacity(rgce.len());
while !rgce.is_empty() {
l... | Rust | 0 |
BUS: Actor + 'static,
{
type Output = BusTransaction<BUS>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Ok(val) = self.shared.begin_transaction() {
if val {
return Poll::Ready(BusTransaction::new(self.arbitrator, self.bus));
... | Rust | 0 |
send_json({"event": "initial_data", "data": initial_data})
# Keep connection alive and handle incoming messages
while True:
try:
# Wait for incoming messages (ping/pong, etc.)
await websocket.receive_text()
# Echo back for keep-alive
... | Python | 1 |
rame, selectmode='day', year=2025, month=3, day=27, width=12)
elif field == "11. Donation Time":
entry = tk.Entry(main_frame, width=40)
entry.insert(0, strftime('%H:%M:%S'))
elif field == "13. Receipt Number":
entry = tk.Entry(main_frame, width=40)
entry.insert(0, generate_receip... | Python | 1 |
, font=font)
# 添加文本
draw.text((text_x, text_y), effect_text, fill=(255, 255, 255, 255), font=font)
return canvas
def collage(self, character_image, expression_image, scene_image, item_image,
canvas_width, canvas_height, border_width, rounded_re... | Python | 1 |
CONTEXTS.call_once(init_contexts).write()
}
pub fn init_process() {
let mut context = process_mut();
let lock = context.new_process().expect("could not initialize first context");
let mut context = lock.write();
let fx = unsafe { alloc_memory(512).expect("allocate memory failed") };
context.regi... | Rust | 0 |
e no U+0000 code points
// in the string.
if val.chars().any(|ch| ch == '\u{0000}') {
return Err(DecodeError::Utf8);
}
Ok(Status::Complete(((2 + string_len) as usize, val)))
}
pub fn encode_string(string: &str, bytes: &mut [u8]) -> Result<usize, EncodeError> {
let size = match u16::try_fro... | Rust | 0 |
ntainer element
ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W)
ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W)
ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W)
# Exit GUI cleanly
def _quit():
win.quit()
win.destroy()
exit()
... | Python | 1 |
cast_storm_protection,
[RW 6; 0] DiffServPriorityClassification diff_serv_priority_classification,
[RW 5; 0] IeeePriorityClassification ieee_priority_classification,
[RW 3..=4; 0] PortBasedPriorityClassification port_based_priority_classification,
[RW 2; 0] TagInsertion tag_insertion,
... | Rust | 0 |
es_c_implementation_64() {
let mut hasher = XxHash64::new();
hasher.input(&[42]);
assert_eq!(hasher.result()[..], 0x0a9e_dece_beb0_3ae4_u64.to_be_bytes());
}
#[test]
fn hash_of_multiple_bytes_matches_c_implementation_64() {
assert_eq!(
XxHash64::digest(b"Hello, world!\0")[..],
0x7b06_c5... | Rust | 0 |
;
}
if first.foreground != next.foreground {
extra_styles.foreground = next.foreground;
}
if first.background != next.background {
extra_styles.background = next.background;
}
ExtraStyles(extra_styles)
}
}
#[cfg(test)]
mod test {
use su... | Rust | 0 |
piTaskResultEvent {
pub result: ApiResult<serde_json::Value>,
pub tag: ApiRequestTag,
}
/// Component that hold the future of api reqeust
pub struct ApiRequestTask(bevy::tasks::Task<ApiResult<serde_json::Value>>);
impl ApiRuntimePlugin {
pub fn new(ctx: &crate::Context, rt: &runtime::Runtime) -> Self {
... | Rust | 0 |
weather</b> <b>in San Francisco, CA</b>. Check current conditions <b>in San Francisco, CA</b> with radar, hourly, and more.', 'title': 'San Francisco, CA Current Weather | AccuWeather', 'link': 'https://www.accuweather.com/en/us/san-francisco/94103/current-weather/347629'}]",
artifact=[{'snippet': 'Get ... | Python | 1 |
i in 0..COUNT {
assert_eq!(true, u.find(i, i));
}
// union all categories
for i in 0..COUNT - 1 {
// union all categories
u.union(i, i + 1);
}
for i in 0..COUNT - 1 {
// check
assert_eq!(true, u.find(i, i + 1));
... | Rust | 0 |
s_%s/index.min.js'
% (account_id, player_id, embed), video_id)
policy_key = None
catalog = self._search_regex(
r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
if catalog:
catalog = self._parse_json(
js_to... | Python | 1 |
s: &Vec<BitVector>) -> Vec<Vec<u64>> {
let mut ranks = Vec::new();
let mut pop = 0 as u64;
for bv in bvs {
let mut rank: Vec<u64> = Vec::new();
for i in 0..bv.num_words() {
let v = bv.get_word(i);
if i % 8 == 0 {
rank.... | Rust | 0 |
other = &other.name()
))
};
}
Err("Can't multiply dimensionless units".to_string())
}
}
/// Division operator
impl Div<&'static Unit> for &Unit {
type Output = Result<&'static Unit, String>;
fn div(self, other: &'static Unit) ->... | Rust | 0 |
from re import finditer
with open('txt/24_21908.txt') as file:
st = file.readline()
pattern = r'[1-9ABCD][0-9ACBD]+[02468AC]'
res = [len(i.group()) for i in finditer(pattern, st)]
print(max(res))
| Python | 1 |
:
for ds_cfg in cfg.data.test:
ds_cfg.pipeline = replace_ImageToTensor(ds_cfg.pipeline)
# init distributed env first, since logger depends on the dist info.
if args.launcher == 'none':
distributed = False
else:
distributed = True
init_dist(args.launcher, ... | Python | 1 |
global_default(subscriber) {
return Err(format!("Unable to set global default subscriber {}", e).into());
}
}
let factory_state = FactoryState::new(cli_args.blocks, cli_args.transactions);
let service_builder = new_full_start!(config).0;
node_transaction_factory::factory(
factory_state,
s... | Rust | 0 |
extern "C" fn notify_model_trampoline<P, F: Fn(&P) + 'static>(
this: *mut gtk_sys::GtkSliceListModel,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<SliceListModel>,
{
let f: &F = &*(f as *const F);
f(&Slice... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.