text string | label_name string | labels int64 |
|---|---|---|
DN_FIRST - 0x0007;
pub const CDM_FIRST: ::UINT = ::WM_USER + 100;
pub const CDM_LAST: ::UINT = ::WM_USER + 200;
pub const CDM_GETSPEC: ::UINT = CDM_FIRST + 0x0000;
pub const CDM_GETFILEPATH: ::UINT = CDM_FIRST + 0x0001;
pub const CDM_GETFOLDERPATH: ::UINT = CDM_FIRST + 0x0002;
pub const CDM_GETFOLDERIDLIST: ::UINT = CD... | Rust | 0 |
.rewind(checkpoint);
formal_parameters(p);
if p.at(T![:]) {
if let Some(mut ret) = ts_type_or_type_predicate_ann(p, T![:]) {
ret.err_if_not_ts(
p,
"arrow functions can only have return types in TypeScript files",
);
}
}
p.expect_no_recover(T![=>])?;
arrow_body(p)?;
Some((... | Rust | 0 |
Prob::Mass(pmf) => (1.0, pmf),
Prob::Density(pdf) => (square_heuristic(1.0, pdf, 1.0, light_pdf), pdf),
};
Some((weight, bsdf_value * incident_radiance, pr))
};
if let Some((weight, f, pr)) = by_bsdf() {
radiance_d += weight * f * pr.weak_recip();
}
radi... | Rust | 0 |
if state.cookie != client_hello.cookie {
return Err((
Some(Alert {
alert_level: AlertLevel::Fatal,
alert_description: AlertDescription::AccessDenied,
}),
Some(Error::ErrCookieMismatch.into... | Rust | 0 |
if loss_metric == "kge":
loss_q = 1 - calc_kge(obs, outflow)
loss_sca1 = 1 - calc_kge(NDSI1, sca1)
loss_sca2 = 1 - calc_kge(NDSI2, sca2)
loss_sca3 = 1 - calc_kge(NDSI3, sca3)
loss_sca4 = 1 - calc_kge(NDSI4, sca4)
loss_sca5 = 1 - calc_kge(NDSI5, sca5)
else:
ra... | Python | 1 |
is_active = BooleanField(required=False, label='激活状态[TRUE/FALSE](默认: TRUE)', error_messages={
'invalid': '激活状态 数据无效, 只支持数字, 文本格式, 不支持公式, xx等其他格式',
})
class Meta:
model = Supplier
fields = ['number', 'name', 'contact', 'phone', 'email', 'address', 'bank_account',
'ba... | Python | 1 |
ation,
} => {
copy_to(&fs, &source, &destination)?;
}
Command::SetAttr { path, id, data } => {
setattr(&fs, &path, id, &[data])?;
}
Command::GetAttr { id, path } => {
if let Some(attr) = getattr(&fs, &path, id)? {
let data = att... | Rust | 0 |
>() == U::access()
}
}
impl<'a, T: 'static> ComponentBorrow for DefaultResourceMut<'a, T> {
fn borrows() -> Borrows {
smallvec![Access::of::<&mut BorrowMarker<T>>()]
}
fn has_dynamic(id: std::any::TypeId, _: bool) -> bool {
let l = Access::of::<&mut T>();
l.id() == id
}
... | Rust | 0 |
error_code: u64,
pub error_msg: String,
}
#[derive(Debug, PartialEq)]
pub struct AbiExtension {
pub type_: u16,
pub data: String,
}
use plotpy::{Histogram, Plot};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
const OUT_DIR: &str = "/tmp/plotpy/integ_tests";
#[test]
fn test_h... | Rust | 0 |
PlayGameRequest, PlayGameResponse, FloatTuple, WorldStatus, ClientActions};
use tetra::graphics::text::{Text, Font};
mod generated_shared;
const WINDOW_WIDTH: f32 = 1200.0;
const WINDOW_HEIGHT: f32 = 720.0;
async fn establish_connection() -> GameProtoClient<tonic::transport::Channel> {
GameProtoClient::connect("... | Rust | 0 |
"""
Problem: Search in a Row-wise and Column-wise Sorted Matrix
Description:
-------------
Given a matrix in which:
- Each row is sorted in increasing order from left to right.
- Each column is sorted in increasing order from top to bottom.
The task is to search for a target value in the matrix efficiently.
Constrai... | Python | 1 |
essor(
# path=output_folder/'mins'/'imu_pose.csv'
# ),
}
# check input path and open rosbag file
print(f'Opening rosbag located at {args.bag_path}...')
assert(args.bag_path.is_file()), \
f"Path to rosbag {args.bag_path} is not a valid path."
bag_file = rosbag.Bag(args.ba... | Python | 1 |
}
};
// Check the range on the color chance input.
if opt.color_chance > 100 {
println!(
"Error: \"color_chance\" should be in the range [0, 100]. Got: \"{}\"",
opt.color_chance
);
return Ok(());
}
let seed = match opt.seed {
Some(seed)... | Rust | 0 |
e.g. SetOpM instruction that has the final key inlined in the
/// instruction, or pulled from the key values that were pushed on the
/// stack in section 1.
/// The function returns a triple (base_instrs, base_setup_instrs, stack_size)
/// where base_instrs is section 1 above, base_setup_instrs is section 2, ... | Rust | 0 |
# Copyright 2016 Toolchain Labs, Inc. All rights reserved.
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from xml.etree import ElementTree
import pytest
from toolchain.packagerepo.maven.pom_property_substitutor import POMPropertySubstitutor
class TestPOMPropertySubstitutor:
xml = """
<p... | Python | 1 |
= RefCell::new(0);
static CURRENT_Y: RefCell<u32> = RefCell::new(0);
pub static CURRENT_BOUNCE: RefCell<u32> = RefCell::new(0);
}
pub struct ThreadMessage {
pub exit: bool,
pub finished: bool,
}
#[derive(Debug)]
pub struct Stats {
pub rays_done: u32,
pub threads: HashMap<u32, StatsThread>,
}
... | Rust | 0 |
# app/db.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy import text, select
from app.config import READ_DATABASE_URL, WRITE_DATABASE_URL
from app.models import Base, TransferState, Event
import logging
from datetime import datetime
clas... | Python | 1 |
import requests
from bs4 import BeautifulSoup
import random
import pandas as pd
import json
def getIns(url, InsDict,dollar):
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0'
}
response = requests.get(url=url, headers=headers)
data ... | Python | 1 |
""" Parses some barcodes with a nomenclature containing two EAN-13
barcode rule and checks the good one is took depending of its sequence.
"""
first_created_rule = self.env['barcode.rule'].create({
'name': 'Rule Test #1',
'barcode_nomenclature_id': self.nomenclature.id,... | Python | 1 |
ve stuff
BASEPATH = "/home/mtageld/Desktop/cTME/results/tcga-nucleus/interrater/"
SAVEDIR = opj(BASEPATH, DATASETNAME, 'i8_IntraRaterStats')
_maybe_mkdir(SAVEDIR)
# connect to sqlite database -- anchors
dbcon = _connect_to_anchor_db(opj(SAVEDIR, '..'))
# compare same participant on various eva... | Python | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
@torch.no_grad()
def symlog(x):
return torch.sign(x) * torch.log(1 + torch.abs(x))
@torch.no_grad()
def symexp(x):
return torch.sign(x) * (torch.exp(torch.abs(x)) - 1)
class SymLogLoss(nn.Module):
def __init__(self):
super().__... | Python | 1 |
pub const SSL_AD_ILLEGAL_PARAMETER: c_int = SSL3_AD_ILLEGAL_PARAMETER;
pub const SSL_AD_DECODE_ERROR: c_int = TLS1_AD_DECODE_ERROR;
pub const SSL_AD_UNRECOGNIZED_NAME: c_int = TLS1_AD_UNRECOGNIZED_NAME;
pub const SSL_ERROR_NONE: c_int = 0;
pub const SSL_ERROR_SSL: c_int = 1;
pub const SSL_ERROR_SYSCALL: c_int = 5;
pu... | Rust | 0 |
able, arg3: GC,
arg4: c_int, arg5: c_int, arg6: *mut XTextItem,
arg7: c_int) -> c_int;
pub fn XDrawText16(arg1: *mut Display, arg2: Drawable, arg3: GC,
arg4: c_int, arg5: c_int, arg6: *mut XTextItem16,
arg7: c_int) -> c_int;
... | Rust | 0 |
bReplaceNoun,
isCap,
ReplPot,
ReplMade,
)
# Adverbs
elif token.tag_ == "RB":
slangifyPoS(
token,
modified_toks,
Slang_Adverbs,
... | Python | 1 |
import requests
# Proxy settings (Burp Suite for monitoring requests)
# PROXY = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}
TIMEOUT = 60 # Timeout for requests
# Function to generate HTTP headers with optional token
def get_headers(url, token=None):
headers = {
"User-Agent": "Mozi... | Python | 1 |
truct CKeyEscrow_Request {
// message fields
rsa_oaep_sha_ticket: ::protobuf::SingularField<::std::vec::Vec<u8>>,
password: ::protobuf::SingularField<::std::vec::Vec<u8>>,
usage: ::std::option::Option<EKeyEscrowUsage>,
device_name: ::protobuf::SingularField<::std::string::String>,
// special fie... | Rust | 0 |
from io import StringIO
import numpy as np
import pandas as pd
sio = StringIO()
sio.write("from numpy import asarray\n\n")
sio.write("kpss_critical_values = {}\n")
c = pd.read_hdf("kpss_critical_values.h5", "c")
ct = pd.read_hdf("kpss_critical_values.h5", "ct")
data = {"c": c, "ct": ct}
for k in ("c", "ct"):
v ... | Python | 1 |
# Escribe un programa que lea una cadena y devuelva un diccionario con la cantidad de apariciones de cada carácter en la cadena.
import os; os.system("cls")
cadena = input("Escribe una cadena: ")
contador = {}
for caracter in cadena:
if caracter in contador:
contador[caracter] += 1
else:
... | Python | 1 |
from dataclasses import dataclass, field
from datetime import datetime
from time import sleep
@dataclass
class PersistentStorage:
"""Storage records in dictionary."""
storage: dict[str, int] = field(default_factory=dict)
def save(self, key: str, value: int) -> None:
"""Add a record to the storag... | Python | 1 |
Wrap {
encoding: &encoding_rs::ISO_8859_13_INIT,
whatwg_name: "iso-8859-13",
name: "iso-8859-13",
};
/// The ISO-8859-14 encoding.
pub static ISO_8859_14: EncodingWrap = EncodingWrap {
encoding: &encoding_rs::ISO_8859_14_INIT,
whatwg_name: "iso-8859-14",
name: "iso-8859-14",
};
/// The ISO-885... | Rust | 0 |
_headers[field] = ''
if all_headers.get("Network") and not all_headers['Network'] and all_headers['_sitewide']:
all_headers['Network'] = all_headers['_sitewide']
if all_headers.get("Network"):
all_headers['Network'] = 'true' == all_headers['Network'].lower()
if all_header... | Python | 1 |
(trader_machine) = &mut self.trader_machine {
return trader_machine.reset().await;
}
if let Some(scout_machine) = &mut self.scout_machine {
return scout_machine.reset().await;
}
if let Some(system_change_machine) = &mut self.system_change_machine {
r... | Rust | 0 |
self.expr(expr, ty_params)?;
write!(self.f(), ".kind")?;
}
GetVariant(expr, variant_name) => {
self.expr(expr, ty_params)?;
write!(self.f(), ".{variant_name}")?;
}
DiscriminantValue(path) => {
... | Rust | 0 |
if not os.path.exists(etc_path):
os.makedirs(etc_path)
def fix_mingw(self):
# On Windows, if the user is not allowed to create symbolic links or if
# the Python version is older than 3.8, tarfile creates an empty
# directory instead of creating a symlink. This affects t... | Python | 1 |
import os
import sys
import logging
from time import sleep
from porkbun_ddns import PorkbunDDNS
from porkbun_ddns.config import Config, DEFAULT_ENDPOINT
logger = logging.getLogger('porkbun_ddns')
if os.getenv('DEBUG', 'False').lower() in ('true', '1', 't'):
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(... | Python | 1 |
uery_boxes[dev_query_box_idx * 5 + 0]
block_qboxes[tx * 5 + 1] = dev_query_boxes[dev_query_box_idx * 5 + 1]
block_qboxes[tx * 5 + 2] = dev_query_boxes[dev_query_box_idx * 5 + 2]
block_qboxes[tx * 5 + 3] = dev_query_boxes[dev_query_box_idx * 5 + 3]
block_qboxes[tx * 5 + 4] = dev_query_box... | Python | 1 |
(i + 1) for i in range(non_layers[2])])
self.NL_4 = nn.ModuleList(
[Non_local(2048) for _ in range(non_layers[3])])
self.NL_4_idx = sorted([layers[3] - (i + 1) for i in range(non_layers[3])])
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(... | Python | 1 |
``
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum FpCategory {
/// "Not a Number", often obtained by dividing by zero.
#[stable(feature = "rust1", since = "1.0.0")]
Nan,
/// Positive or negative infinity.
#[stable(feature = "rust1", since = "1.0.... | Rust | 0 |
from node import Node
from binary_search_tree import BinarySearchTree
class CustomBST(BinarySearchTree):
def __init__(self):
super().__init__()
def __count_none_leaf_nodes(self, root: Node) -> int:
if root is None or (root.left is None and root.right is None):
return 0
cou... | Python | 1 |
ist2.curselection())
ftp.cwd(fileName_ftp)
# 刷新一遍目录窗口,首先要清空目录,再重载
list2.delete(0, tkinter.END) # 清空列表框
show_ftp()
def Back():
ftp.cwd('..')
# 刷新一遍目录窗口,首先要清空目录,再重载
list2.delete(0, tkinter.END) # 清空列表框
show_ftp()
def delete_ftp():
# 获取到要下... | Python | 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the CC-by-NC license found in the
# LICENSE file in the root directory of this source tree.
from abc import ABC
from typing import Optional, Tuple
import torch
from flow_matching.loss import MixturePathG... | Python | 1 |
n_frees` are updated from the current clone's
//! `cas` instance.
//!
//! Actual drop is executed by Node::dropped() function
use std::{
borrow::Borrow,
fmt::Debug,
hash::{BuildHasher, Hash, Hasher},
mem,
ops::{Add, Deref},
sync::{
atomic::{AtomicPtr, AtomicU64, AtomicUsize, Ordering:... | Rust | 0 |
print("*" * 57)
print("🔄 Conversor de Binario a Decimal / Decimal a Binario 🔄")
print("*" * 57)
while True:
print("\nPor favor, escoja la opción que desea: ")
print("(1) Conversor de Binario a Decimal")
print("(2) Conversor de Decimal a Binario")
opcion = input("> ")
if opcion not in ("1", "2"):... | Python | 1 |
_type,
}
}
pub fn get_paddle_type(&self) -> PaddleType {
self.paddle_type.clone()
}
pub fn get_y_positions(&self) -> Vec<i32> {
self.y_positions.clone()
}
pub fn get_y(&self) -> i32 {
self.y
}
pub fn get_x(&self) -> i32 {
self.x
}
pub ... | Rust | 0 |
StressProtocolKind::AlternatingSend => {
data.push(0x02);
},
StressProtocolKind::MessagingFlood => {
data.push(0x03);
},
}
data.extend_from_slice(&self.num_messages.to_be_bytes());
data.extend_from_slice(&self.message_size.to_b... | Rust | 0 |
0345)
linear_interp = interp1d(chip_fsr_wl, chip_fsr_T, kind='linear')
chipFSR_transmission = linear_interp(x)
# ------ OTHERS (still constant for now): ------
SMFchip_transmission = 0.9
QE_efficiency = 0.9
# cut everything down to same wavelength range (1205-1375 nm)
wavelength = x
delta_lambda_array = waveleng... | Python | 1 |
er_args} -- {bam_file}"
try:
do.run(cmd.format(**locals()), "QC: goleft indexcov")
except subprocess.CalledProcessError as msg:
if not ("indexcov: no usable" in str(msg) or
("indexcov: expected" in str(msg) and "sex chromosomes, found:" in ... | Python | 1 |
ync + 'static,
{
type Storage = DenseVecStorage<Self>;
}
/// The prefab allowing to easily add a `Removal` `Component` to an entity.
#[derive(Default, Clone, Deserialize, Serialize)]
pub struct RemovalPrefab<I: Debug> {
id: I,
}
impl<'a, I> PrefabData<'a> for RemovalPrefab<I>
where
I: PartialEq + Debug + ... | Rust | 0 |
2),
points_2d[None,None],
align_corners=True,
padding_mode="border",
)[0, :, 0].permute(1,0)
is_in_masks = (torch.nn.functional.grid_sample(
self.get_mask(num_frames-1)[None, None],
points_2d[None,None],
align_corners=T... | Python | 1 |
import ast
class SyntaxVisitor(ast.NodeVisitor):
def __init__(self):
self.nesting_level = 0
self.max_nesting = 0
def visit(self, node, prefix="", indent=0, base_indent=0):
node_type = type(node).__name__
print(f"{prefix}{' '*indent}{node_type} (niveau avant={self.nesting_lev... | Python | 1 |
from __future__ import annotations
from typing import AbstractSet
import attr
from dl_core.components.dependencies.field_deep_base import FieldDeepInterDependencyManagerBase
from dl_core.components.dependencies.field_shallow_base import FieldShallowInterDependencyManagerBase
from dl_core.components.ids import FieldI... | Python | 1 |
type of field.
/// - [`STArray`][`crate::types::starray::STArray`] for serializing **STArray** type of field.
/// - [`STObject`][`crate::types::stobject::STObject`] for serializing **STObject** type of field.
/// - [`to_be_bytes()`] for serializing **UInt8**, **UInt16**, **UInt32** type of field and slice to ... | Rust | 0 |
progress: Optional[int] = None,
related_projects: Optional[List[str]] = None
) -> Dict[str, Any]:
"""
更新目标
Args:
goal_id: 目标ID (任务ID)
title: 新标题 (可选)
type: 新类型 (phase/permanent/habit) (可选)
status: 新状态 (active/completed... | Python | 1 |
ox::push`] can be used to add entries to the inbox
/// * [`Mailbox::consume`] rotates data into the outbox and allows it to be consumed
///
/// This achieves the following goals:
///
/// * Allows data to continue to arrive whilst data is being consumed
/// * Allows multiple consumers to coordinate preventing concurrent... | Rust | 0 |
: bool) -> usize {
let mut len = 0;
let mut mode = Mode::Normal;
let mut marker_len = 0;
let mut marker_repeat = 0;
let mut subsequent = String::new();
for ch in input.chars() {
if ch.is_whitespace() { continue; }
match mode {
Mode::Normal => {
if ch ... | Rust | 0 |
# encoding: utf-8
from distutils.core import setup
import os
import re
import sys
if any(a == 'bdist_wheel' for a in sys.argv):
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'pexpect', '__init__.py'), 'r') as f:
for line in f:
version_match = re.search(r"__version__ = ... | Python | 1 |
0 => return Err(Error::Timeout),
n => check_pcap_error(pcap_t, n)?,
}
if header.is_null() || packet.is_null() {
panic!("header or packet NULL.");
}
let ts: libc::timeval = unsafe { (*header).ts } as libc::timeval;
let len: usize = unsafe { (*header).caplen } as usize;
let t... | Rust | 0 |
=\s*([\'\"])(.*?)\1', # object标签的data属性(单双引号)
r'<object\b[^>]*?\bdata\s*=\s*([^\s>]+)', # object标签的data属性(无引号)
r'<track\b[^>]*?\bsrc\s*=\s*([\'\"])(.*?)\1', # track标签的src属性(单双引号)
r'<track\b[^>]*?\bsrc\s*=\s*([^\s>]+)', # track标签的src属性(无引号)
r'... | Python | 1 |
_error_on_error_response() {
let request = WebRequest::create();
let _ = request
.get_binary_response("https://httpbin.org/status/500", None, None)
.unwrap();
}
#[test]
fn get_html_response_should_follow_redirection() {
let final_url =
Url::parse... | Rust | 0 |
GetHybridization() == Chem.rdchem.HybridizationType.SP3:
# Start DFS search from this carbon with initial depth = 1 (one bond from N).
visited = set([nbr.GetIdx()])
if dfs_chain(nbr, current_depth=1, max_depth=6, visited=visited):
retur... | Python | 1 |
e={}&j_password={}", username, password);
}
<filename>sproot/src/models/server/cputimes.rs
use crate::errors::AppError;
use crate::ConnType;
use crate::models::schema::cputimes;
use crate::models::schema::cputimes::dsl::{
cputimes as dsl_cputimes, created_at, cuser, host_uuid, idle, iowait, irq, nice, softirq,
... | Rust | 0 |
db, o)?;
}
Ok(())
}
/// Redo a dataset.
pub fn redo(db: &mut DbContext, or: &String, ac: &String) -> Result<()> {
let oo = UndoEntry::from_str::<TbOrt>(or)?;
let oa = UndoEntry::from_str::<TbOrt>(ac)?;
if let (Some(_o), Some(a)) = (&oo, &oa) {
// Update
update(db, a)?;
} else if... | Rust | 0 |
import smart_imports
smart_imports.all()
def can_be_choosen(place, modifier):
if modifier.is_NONE:
return True
if getattr(place.attrs, 'MODIFIER_{}'.format(modifier.name).lower(), c.PLACE_TYPE_NECESSARY_BORDER) < c.PLACE_TYPE_NECESSARY_BORDER:
return False
return True
class BaseForm(... | Python | 1 |
.batch_size;
println!(
"Changing total_images number to {} to be multiple of batch_size - {}",
opt.total_images, opt.batch_size
);
}
println!(
"Decoding images in directory: {}, total {}, batchsize {}",
&opt.input_dir, opt.total_images, opt.batch_size
... | Rust | 0 |
from .loadxml import loadxml
from .savexml import savexml
from .spm_add import spm_add
from .spm_adjmean_fmri_ui import spm_adjmean_fmri_ui
from .spm_adjmean_ui import spm_adjmean_ui
from .spm_atranspa import spm_atranspa
from .spm_chi2_plot import spm_chi2_plot
from .spm_digamma import spm_digamma
from .spm_dirichlet ... | Python | 1 |
p256k1_u1 = 0;
fiat_secp256k1_addcarryx_u32(&mut x63, &mut x64, x62, x49, x49);
let mut x65: u32 = 0;
let mut x66: fiat_secp256k1_u1 = 0;
fiat_secp256k1_addcarryx_u32(&mut x65, &mut x66, x64, x50, x50);
let mut x67: u32 = 0;
let mut x68: fiat_secp256k1_u1 = 0;
fiat_secp256k1_subborrowx_u32(&mut x67, &mut ... | Rust | 0 |
[13]),
left: u8_to_i16(dat[14], dat[15]),
flags: u8_to_u16(dat[4], dat[5]),
stype: 0,
tag: 0,
args: [dat[6], dat[7], dat[8], dat[9], dat[10], dat[11]],
}
}
_ => {
... | Rust | 0 |
(),
);
// By default, highlight all paragraphs with green color and use a class to remove it.
// This is because most of the lines are going to be highlighted in the majority of greens
// anyways.
bytes.extend(
format!(
"p {{ color: {green_color}; }}\n\
.{reset_foreg... | Rust | 0 |
let a = a >> bit_offset;
let b = b >> bit_offset;
assert_eq!(Felt::new(a), trace[2][i]);
assert_eq!(Felt::new(b), trace[3][i]);
assert_eq!(Felt::new(a & 1), trace[4][i]);
assert_eq!(Felt::new((a >> 1) & 1), trace[5][i]);
assert_eq!(Felt::new((a >> 2) & 1), trace... | Rust | 0 |
osenResults};
use num_rational::Ratio;
use rand::{prelude::*, thread_rng};
#[cfg(feature = "async")]
use futures::future::BoxFuture;
const DEFAULT_RANDOM_CHOOSE_RATIO: Ratio<usize> = Ratio::new_raw(1, 2);
/// 永不空手的选择器
///
/// 确保 [`Chooser`] 实例不会因为所有可选择的 IP 地址都被屏蔽而导致 HTTP 客户端直接返回错误,
/// 在内置的 [`Chooser`] 没有返回结果时,将会随机返... | Rust | 0 |
.and_then(move|item|{
let attr=syn::parse_str::<TokenStream2>(attr)?;
sabi_extern_fn_inner(attr,item)
})
}
/// Whether the function contains an early return or not.
#[derive(Debug,Copy,Clone,PartialEq)]
pub enum WithEarlyReturn{
No,
Yes,
}
/// Converts a function into an ... | Rust | 0 |
16~\x22\xb8\xac\
Nl\x09\xb1\x85_\x08.\xab\x12[Bl\xe1Y\x82\
\xcbj\xc4\x96\x10[\xb8HpY\x85\xd8\x12b\x0b/\
\x12\x5c\x1e&\xb6\x84\xd8\xc2\xab\x04\x97\x87\x88-!\xb6\
p\x15\xc1\xe5nbK\x88-\x5cMp\xb9\x8b\xd8\x12\
b\x0b7\x11\x5cn&\xb6\x84\xd8\xc2\xcd\x04\x97\x9b\x88\
-!\xb6p\x17\xc1\xe5jbK\x88-\xdcMp\xb9\
\x8a\xd8\x12b\x0b\x0f... | Python | 1 |
Some(root) => {
if root == update.update.previous_root {
self.store_latest_root(update.update.new_root)?;
} else {
debug!(
"Attempted to store update not building off latest root: {:?}",
up... | Rust | 0 |
# WARNING: Please don't edit this file. It was generated by Python/WinRT v0.9.210202.1
import typing, winrt
import enum
_ns_module = winrt._import_ns_module("Windows.Devices.Spi")
try:
import winrt.windows.devices.spi.provider
except:
pass
try:
import winrt.windows.foundation
except:
pass
try:
... | Python | 1 |
ge > page_limit:
time.sleep(0.5)
logger.info("")
logger.info("*" * 50)
logger.info("")
pprint(pets[0])
logger.info("*" * 50)
with next(get_session()) as session:
for pet_data in pets:
cls.store_d... | Python | 1 |
.14: expected expression, but found ‘exit’"#]],
);
}
#[test]
fn parse_for_loop() {
check(
r#"
for i : 1 .. 3
invariant true
end for
"#,
expect![[r#"
Source@0..59
Whitespace@0..5 "\n "
StmtList@5..54
ForStmt@5..54
... | Rust | 0 |
ira esta aberta !")
ja_foi_informado_sobre_lixeira_aberta_no_loop_anterior = True
log_message(f" Tempo lixeira aberta : {contador_tempo_lixeira_aberta}","SUCCESS")
# Se passar 10 segundos e a lixeira ainda não foi fechada....fecha automaticamente lixeira
... | Python | 1 |
t' and 'callback_data'.
Returns:
None
"""
self._keyboard_after.append(_buttons_to_dict(inline_buttons))
def _buttons_to_dict(buttons):
return [
_button_to_dict(button)
for button
in buttons
]
def _button_to_dict(button):
res = {
'text'... | Python | 1 |
ooltips, Box::new(|_| GeomBatch::new())),
Line("number of trips (slower)").secondary().draw(ctx),
])
.padding(16)
.outline(2.0, Color::WHITE)
}
pub struct Filter {
changes_pct: Option<f64>,
modes: BTreeSet<TripMode>,
}
impl Filter {
pub fn new() -> Filter {
Filter {
... | Rust | 0 |
"""
Образец реализации для service-операций.
Модуль содержит примеры кода и документации для классов и функций,
реализующих дополнительную бизнес-логику приложения.
Шаблон докстринга для service-класса должен содержать:
- Описание назначения класса
- Перечень атрибутов класса с типами
Шаблон докстринга для ser... | Python | 1 |
of field: ",
stringify!(blpapi_HighPrecisionDatetime_tag),
"::",
stringify!(datetime)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<blpapi_HighPrecisionDatetime_tag>())).picoseconds as *const _
as usize
},
12usiz... | Rust | 0 |
"v2_42")))]
fn send_async_future(&self, msg: &(impl IsA<Message> + Clone + 'static)) -> Pin<Box_<dyn std::future::Future<Output = Result<gio::InputStream, glib::Error>> + 'static>> {
let msg = msg.clone();
Box_::pin(gio::GioFuture::new(self, move |obj, cancellable, send| {
obj.send_asy... | Rust | 0 |
else:
l.append(actor.get("name"))
movie["演员"] = [
notion_helper.get_relation_id(
x.get("name"), notion_helper.actor_database_id, USER_ICON_URL
)
for x i... | Python | 1 |
he data to the cached page with the requested offset.
fn write(
&self,
page_creator: &PageCreator,
config: &Config,
offset: usize,
data: &[f64],
) -> Result<()> {
if !self.path.exists() {
page_creator.copy_page_template(&self.path, config)?;
}
... | Rust | 0 |
se with [`FrameHandler::send_request`].
#[derive(Debug, Copy, Clone)]
pub struct CmdNetSave;
impl RequestDesc for CmdNetSave {
type Result = ();
fn write_request(&self, buffer: &mut dyn io::Write) -> io::Result<()> {
Cmd::NetSave.try_pack(buffer)?;
Ok(())
}
fn on_response(
sel... | Rust | 0 |
"keyval": {
"public": "<KEY>"
},
"scheme": "ecdsa-sha2-nistp256"
},
"f505595165a177a41750a8e864ed1719b1edfccd5a426fd2c0ffda33ce7ff209": {
"keyid_hash_algorithms": [
"sha256",
"sha512"
],
"keytype": "ecdsa-sha2-nistp256",
"keyval": {
"public": "<KEY>"
},
"scheme... | Rust | 0 |
import sys, os, re, requests, shutil, webbrowser, CppHeaderParser, json, cgi
from lxml import html
def to_snake(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
scriptpath = os.path.realpath(__file__)
projectpath = os.path.join(os.path.dirname(os.... | Python | 1 |
ssage):
return self.parse_line_for_backchannel(message)[0]
# テキストVAPを実行
def run_text_vap(self, asr_timestamp, query):
# ChatGPTに入力するプロンプト
messages = [
{'role': 'user', 'content': self.prompts['BC']},
{'role': 'system', 'content': "OK"},
{'role': 'user... | Python | 1 |
#!/usr/bin/python3
from target import *
class TargetFromLeaderOffset( Target ):
def __init__( self, leader_pose_topic_name: str, target_topic_name: str, offset = None ):
super().__init__( target_topic_name )
assert offset is None or (isinstance( offset, list ) and len( offset ) == 3)
self.offset = of... | Python | 1 |
hannel-11 split control register"]
pub mod hcsplt11;
#[doc = "HCINT0 register accessor: an alias for `Reg<HCINT0_SPEC>`"]
pub type HCINT0 = crate::Reg<hcint0::HCINT0_SPEC>;
#[doc = "OTG_HS host channel-11 interrupt register"]
pub mod hcint0;
#[doc = "HCINT1 register accessor: an alias for `Reg<HCINT1_SPEC>`"]
pub type ... | Rust | 0 |
use distribution;
use source::Source;
/// A gamma distribution.
#[derive(Clone, Copy, Debug)]
pub struct Gamma {
k: f64,
theta: f64,
norm: f64,
}
impl Gamma {
/// Create a gamma distribution with shape parameter `k` and scale parameter
/// `theta`.
///
/// It should hold that `k > 0` and ... | Rust | 0 |
print("Falha ao obter o mapa de criptomoedas.")
if crypto_categories:
print("Resultados da consulta - Categorias de Criptomoedas:")
for category in crypto_categories['data']:
print(f"- {category['name']} ({category['title']}):")
print(f" - Descrição: {category['d... | Python | 1 |
print(10 > 9)
print(10 == 9)
print(10 < 9) | Python | 1 |
rate_meme(query, model_choice, api_key))
if meme_url:
st.success("✅ Meme Generated Successfully!")
st.image(meme_url, caption="Generated Meme Preview", use_container_width=True)
st.markdown(f"""
**Direct... | Python | 1 |
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... | Python | 1 |
import utils
import argparse
import re
import random
import json
from joblib import Parallel, parallel_backend, delayed
def write_to_disk(docs, outfile, matching=None, default_str="### NO MATCH FOUND ###"):
if outfile is None:
print("outfile is None. Ignoring call to write to disk.")
return
ne... | Python | 1 |
/// fn failure(x: u32) -> Outcome<u32, u32, u32> { Failure(0) }
///
/// assert_eq!(Success(2).and_then(square).and_then(square), Success(16));
/// assert_eq!(Success(2).and_then(square).and_then(failure), Failure(0));
/// assert_eq!(Success(2).and_then(square).and_then(mistake), Mistake(4));
/// assert_eq!... | Rust | 0 |
nce
user = User("Jean", 20, "Male", ['soccer', 'coding', 'poker'], 'student')
# 'audio/sample_turn2.wav'#
audio_path = get_recording()
# audio_path = get_recording()
audio_file = genai.upload_file(path=audio_path)
audio_uri = audio_file.uri
# Gets an image from predict_face_vis
photo_... | Python | 1 |
from flask import Blueprint, jsonify, current_app
from datetime import datetime, timedelta
news_bp = Blueprint('news_bp', __name__)
@news_bp.route('/api/latest', methods=['GET'])
def get_latest_news():
db = current_app.config['db']
news_rookie = db['news_rookie']
news_jumpball = db['news_jumpball']
#... | Python | 1 |
\r\n--\r\n\r\n\r\n\r\n----an-invalid-\r\n--boundary--droped-data";
let body_bytes = body
.iter()
.map(|b| Bytes::from(slice::from_ref(b)).apply(Ok))
.collect::<Vec<io::Result<Bytes>>>();
let body_stream = futures::stream::iter(body_bytes);
let boundary = b... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.