text string | label_name string | labels int64 |
|---|---|---|
time, "The time stamps does not match!");
// we only use the first sub secret key to sign
// this creates a copy of ssk and therefore needs to be destroyed
let ssk_sec = sk.first_ssk()?;
// get all neccessary variables
let depth = pp.depth();
let hlist = pp.hlist();
... | Rust | 0 |
Error>> {
offer_mpst!(s, {
Branching0fromServerToOther::Dummy(s) => {
let (_, s) = s.recv()?;
s.close()
},
Branching0fromServerToOther::Query(s) => {
let ((address, packet), s) = s.recv()?;
let s = s.send((-address, -packet))?;
s... | Rust | 0 |
t character(s).
match next_content_type {
ContentType::Comment => { process_comment(proc)?; }
ContentType::Bang => { process_bang(proc)?; }
ContentType::OpeningTag => { process_tag(proc)?; }
ContentType::End => { break; }
ContentType::Entity => entity.... | Rust | 0 |
import os
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import count, avg, min, max, col, round, ntile, expr
from pyspark.sql.window import Window
# 确保 Python 处理 UTF-8 编码
os.environ['PYTHONIOENCODING'] = 'utf-8'
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf-8', buffering=1... | Python | 1 |
en non-uniform sampling)
if norm_by_num_examples:
num_examples = np.sum(labels >= 0) # neg + pos
num_examples = np.maximum(1.0, num_examples)
bbox_outside_weights[labels > 0] = 1.0 / num_examples
else:
bbox_outside_weights[labels > 0] = 1.0
# bbox_outside_weights[labels == 0... | Python | 1 |
cup_price = 0.50
cone_price = 0.80
scoop_price = 1.20
flake_price = 0.40
chocolate_price = 0.30
strawberry_price = 0.60
price = 0
container = input("would you like a cup, or a cone?")
if container.upper() == "CUP":
price = cup_price
else:
price = cone_price
scoops = int(input("how many scoops would you like?"... | Python | 1 |
scoreboard_set_reg(server, reg, v).await;
}
TypedValue::I64(v) => {
let v_lo = v as i32;
let v_hi = (v >> 32) as i32;
let param_pair_lo = Register::param_lo(param_idx as u32);
scoreboard_set_reg(server, param_pair_lo, v_lo).await;
let param_pair_hi = Register::param_hi(param_idx as u32);
... | Rust | 0 |
lse;
}
}
assert!(success);
}
#[test]
#[allow(clippy::cognitive_complexity)]
fn acontext_record() {
{
let mut ctx = AContext::new();
let mut a = AFloat::new(1.0, 0.0);
let mut b = AFloat::new(2.0, 0.0);
ctx.set_indep(&mu... | Rust | 0 |
可变引用数据
println!("m = {:?}", m.get_mut().unwrap());
// m = Mutex { data: 11, poisoned: false, .. }
// m = 11
}
// #[test]
// fn mutex_share_data(){
// let counter = Mutex::new(0);
// // 上面一行不能编译,抛出下面的错误
// // ------- move occurs because `counter` has type `Mut... | Rust | 0 |
not is_neuron(pre) and not is_body_wall_muscle(pre)
) or not is_body_wall_muscle(post):
# Don't add connections unless pre=neuron and post=body_wall_muscle
continue
if is_neuron(pre):
pre = remove_leading_index_zero(pre)
else:
... | Python | 1 |
}
impl<const NUM_WORDS: usize> Sub<Self> for BigUInt<NUM_WORDS> {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
// Subtract by adding
let additive = (rhs ^ Self::MAX).increase();
additive + self
}
}
impl<const NUM_WORDS: usize> AddAssign<Self> for BigUInt<NUM_WORDS>... | Rust | 0 |
mut shape_list);
floor.transform = scaling(10.0, 0.01, 10.0);
let mut material = Material::new();
let pattern_b = RingPattern::new(Color::from_hex("FF0000"), Color::black());
// let pattern_b = StripePattern::new(Color::from_hex("0000FF"), Color::black());
let mut pattern = PerturbedPattern::new(Box:... | Rust | 0 |
cess::exit(1);
});
let config = utils::Config::new_from_args(env::args()).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {}", err);
print_keywords(&env);
process::exit(1);
});
let new_env = parser::parse_env(&env, &config).unwrap_or_else(|err| {
eprintln!(... | Rust | 0 |
}
}
#[cfg(target_os = "linux")]
impl PlatformEventReader {
pub fn errno() -> libc::c_int {
unsafe { *libc::__errno_location() }
}
fn epoll_add_fd(epoll_fd: RawFd, fd: RawFd, index: usize) {
let mut event = libc::epoll_event {
events: (libc::EPOLLIN | libc::EPOLLERR | libc:... | Rust | 0 |
encryptors.get_volume_encryptor(
root_helper=self.root_helper,
connection_info=self.connection_info,
keymgr=self.keymgr,
**encryption)
encryption = {'control_location': 'front-end',
'provider': 'nova.volume.encryptors.luks.LuksEncryptor'}
... | Python | 1 |
(1.0+1.0j, 1.0+1.000000000001j),
(-1.0+1.0j, -1.000000000001+1.0j),
(1.0-1.0j, 1.0-0.999999999999j),
]
self.assertAllClose(complex_examples, rel_tol=1e-12)
self.assertAllNotClose(complex_examples, rel_tol=1e-13... | Python | 1 |
Lead adapter in a linked configuration was not enumerated yet.
pub const GRAPHICS_LEADLINK_NOT_ENUMERATED : NtStatus = NtStatus::from_constant(0xC01E0431); // STATUS_GRAPHICS_LEADLINK_NOT_ENUMERATED
/// Some chain adapters in a linked configuration were not enumerated yet.
pub const GRAPHICS_CHAINLINKS_NOT_ENUMERATED... | Rust | 0 |
merged_lapper.merge_overlaps();
let merged_len = merged_lapper.intervals.len();
IterDepth {
inner: self,
merged: merged_lapper,
curr_merged_pos: zero::<I>(),
curr_pos: 0,
cursor: 0,
end: merged_len,
}
}
/// Count ... | Rust | 0 |
CTIMERA1 OUT2. value."]
A1OUT2,
#[doc = "Trigger source is CTIMERB1 OUT2. value."]
B1OUT2,
#[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."]
A6OUT2DUAL,
#[doc = "Trigger source is CTIMERA7 OUT2, dual edge. value."]
A7OUT2DUAL,
#[doc = "Trigger source is CTIMERB5 OUT2, dual e... | Rust | 0 |
sgSteamDatagramSignedRelayAuthTicket| { &m.reserved_do_not_use },
|m: &mut CMsgSteamDatagramSignedRelayAuthTicket| { &mut m.reserved_do_not_use },
));
fields.push(::protobuf::reflect::accessor::make_option_accessor::<_, ::protobuf::types::ProtobufTypeFixed64>(
"ke... | Rust | 0 |
"""
FFM by @JusticeRage
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in... | Python | 1 |
TERRUPT_MASTER_ENABLE)
///
/// This is a internal variable we use to enable or disable
/// interrupts that are defined in the MMU INTERRUPT_MASTER_ENABLE (0xFFF).
///
/// 0 -> Disable all interrupts
/// 1 -> Enable interrupts from the IE in MMU
interrupt_master_enable: bool,
/// Set di... | Rust | 0 |
from tkinter import *
from PIL import Image, ImageTk
import Customer
import Payment
import Delivery
import Cuisine
import Food
import Order
import Drinks
import Employee
import Chef
def portal(temp):
temp.destroy()
root = Tk()
root.geometry("700x500")
#root.config(background="white")
Label(root, ... | Python | 1 |
"""
ftpwalk -- Walk a hierarchy of files using FTP (Adapted from os.walk()).
"""
def ftpwalk(ftp, top, topdown=True, onerror=None):
"""
Generator that yields tuples of (root, dirs, nondirs).
"""
# Make the FTP object's current directory to the top dir.
ftp.cwd(top)
# We may not have read permi... | Python | 1 |
u8
};
DbgTim12StopR { bits }
}
#[doc = "Bit 7 - DBG_TIM13_STOP"]
#[inline(always)]
pub fn dbg_tim13_stop(&self) -> DbgTim13StopR {
let bits = {
const MASK: u8 = 1;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) as u8
};
... | Rust | 0 |
wnbhkt57l4h, uggn_nbbua8 as s7h4t7xadav, hnddaqhurts, uuzv7g8irpp, yci9r9lytgl as eivsbu6t4ed, djb47obv6nx
assert None, ehr0r_j6zpm
nonlocal op7idb0nfpv
raise 0j
'# land_drags_scratch -> smash_values_fronts'
assert nj_k14d49ns
@{0.0: jto5tzmmfwe, '': b''}
def sywnxdz1i5s(lxdje5wsy4w, nren0o_m32b: v... | Python | 1 |
a, xb = paddle.split(x, 2, axis=splitdim)
# local conditioning
if c is not None:
c = self.conv1x1_aux(c)
ca, cb = paddle.split(c, 2, axis=splitdim)
xa, xb = xa + ca, xb + cb
# global conditioning
if g is not None:
g = self.conv1x1_glo(g)
... | Python | 1 |
import analysis.bootstrapping as bs
import analysis.statistics as stats
import analysis.marginals as marginals
def configure(context):
acquisition_sample_size = context.config("acquisition_sample_size")
bs.configure(context, "synthesis.population.enriched", acquisition_sample_size)
def execute(context):
a... | Python | 1 |
try:
with open(cert_path, 'rb') as f: # Changed to binary mode
cert_data = f.read()
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_data)
expiry_date = datetime.datetime.strptime(
cert.get_notAfter().decode(... | Python | 1 |
pe
B,H,W,C = x.shape
# # padding
# H, W = int(np.ceil(np.sqrt(N))), int(np.ceil(np.sqrt(N)))
# add_length = H * W - N
# x = torch.cat([x, x[:,:add_length,:]],dim = 1)
# pos_embed = torch.zeros(1, H * W + 1, self.embed_dim)
# pos_embed = self.get_2d_sincos_pos_emb... | Python | 1 |
: &[i32]) -> (i32, i32, i32) {
expense_report
.iter()
.copied()
.enumerate()
.flat_map(|(i1, e1)| {
let needed1 = 2020 - e1;
expense_report
.iter()
.copied()
.enumerate()
.skip(i1 + 1)
... | Rust | 0 |
'news_summary': {}
}
# 1. 公司新闻
try:
self.logger.info("正在获取公司新闻...")
company_news = ak.stock_news_em(symbol=stock_code)
if not company_news.empty:
processed_news = []
f... | Python | 1 |
Mut()>));
request_animation_frame(g.borrow().as_ref().unwrap());
JsValue::undefined()
}
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
pub(super) static KNOWN_GLOBALS... | Rust | 0 |
-> Iterator[str]:
""":yield: all user and site configuration directories."""
yield self.user_config_dir
yield from self._site_config_dirs
def iter_data_dirs(self) -> Iterator[str]:
""":yield: all user and site data directories."""
yield self.user_data_dir
yield from ... | Python | 1 |
0, 0, 0, 0, 239, 46, 109, 235, 61, 58, 89, 37, 181, 238, 23, 98, 108, 29, 99,
170, 28, 132, 136, 248, 109, 194, 64, 139, 35, 219, 22, 195, 40, 100, 32, 6, 7, 230, 5,
102, 8, 116, 33, 165, 132, 177, 44, 2, 247, 88, 213, 77, 12, 122, 49, 105, 29, 74, 55, 207,
160, 46, 181, 65, 63, 123, 109, 117, ... | Rust | 0 |
#!/usr/bin/env python
"""opdump - scan for operations on a given DCERPC interface
Usage: opdump.py hostname port interface version
This binds to the given hostname:port and DCERPC interface. Then, it tries to
call each of the first 256 operation numbers in turn and reports the outcome
of each call.
This will generat... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... | Python | 1 |
,
concat!(
"Offset of field: ",
stringify!(uart_config),
"::",
stringify!(stop_bits)
)
);
assert_eq!(
unsafe { &(*(::core::ptr::null::<uart_config>())).data_bits as *const _ as usize },
6usize,
concat!(
"Offset o... | Rust | 0 |
error) => Err(error),
}
}
/// This method takes two tiles and a map from `GridIdx2D` to `Coordinate2D`. Then for all `GridIdx2D` we set the values from the corresponding coordinate in the source tile.
pub fn insert_projected_pixels<'a, T: Pixel, I: Iterator<Item = &'a (GridIdx2D, Coordinate2D)>>(
target: &mut ... | Rust | 0 |
ize)]
pub struct Nodes {
nodes: HashSet<Node>,
}
impl Nodes {
pub fn new() -> Nodes {
Nodes {
nodes: HashSet::new(),
}
}
pub fn iter(&self) -> Iter<'_, Node> {
self.nodes.iter()
}
pub fn register(&mut self, url: &str) -> Result<&Node... | Rust | 0 |
_speed: 32,
background_colour: [0.8, 0.8, 0.8, 0.8],
foreground_colour: [0.0, 0.0, 0.0, 1.0],
secondary_colour: [0.5, 0.5, 0.5, 1.0],
interface_margin: 8.0,
text_box_height: 0.25,
character_name_width: 0.25,
character_name_height: 0.08,
branch_button_width: 0.3,
branch_button_height: 0.1,
... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mediapipe/util/tracking/camera_motion.proto
# Protobuf Python Version: 4.25.1
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descripto... | Python | 1 |
load_and_test_with_offset_window_read_multiple_channels(NEGATIVE_OFFSET);
load_and_test_with_offset_window_read_multiple_channels(POSITIVE_OFFSET);
}
// with one channel only as well
#[test]
fn negative_window_read_single_channel() {
load_and_test_with_offset_window_read_single_channel(NEGATIVE_OFFSET);
... | Rust | 0 |
str = show[show.find(random_str.encode()) + len(random_str):]
now_before_str = r.content[res_list[num].start()-len(show_before_str):res_list[num].start()]
now_after_str=r.content[res_list[num].start()+len(random_str):res_list[num].start()+len(random_str)+len(show_after_st... | Python | 1 |
for
xcb::MOD_MASK_ANY as u16,
)
.request_check()?)
}
/// Drop all active intercepts for mouse states
pub fn ungrab_mouse_buttons(&self) -> Result<()> {
Ok(xcb::ungrab_button_checked(
&self.conn, // xcb connection to X11
xcb::BUTTON_INDEX_ANY as u... | Rust | 0 |
: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 125, 72, 138, 20, 178], OperandSize::Dword)
}
fn vcompressps_11() {
run_test(&Instruction { mnemonic: Mnemonic::VCOMPRESSPS, operand1: Some(Direct(ZMM12)), operand2: Some(Direct(ZMM12))... | Rust | 0 |
state(caller)
.unwrap_or_default();
let chain_id = self.config.chain_id;
ensure!(
tx_chain_id == Some(chain_id),
WrongChainId {
chain_id,
tx_chain_id,
}
);
ensure!(
self.evm_backend.find_transa... | Rust | 0 |
he": "חריגה של יחידות בדיקה כושלות שבהן ערכים היו צריכים להתאים לביטוי Python שניתן.",
"th": "เกินหน่วยการทดสอบที่ล้มเหลวซึ่งค่าควรตรงกับนิพจน์ Python ที่กำหนด",
"fa": "تجاوز واحدهای آزمون ناموفق که در آن مقادیر باید با عبارت Python داده شده مطابقت داشته باشند.",
},
"col_exists_expectation_text"... | Python | 1 |
if a_pos == b_pos:
return 0
elif a_pos in self._open_pos and b_pos in self._open_pos:
return 0.25
else:
return 0.499
def _get_char_cost(self, a, b, pinyin_a, pinyin_b):
"""
NOTE: This is a replacement of ERRANTS lemma cost for Chinese
计... | Python | 1 |
import numpy as np
from .base import BasePotential
class MultipleSquareWellPotential(BasePotential):
def __init__(
self,
x_grid: np.array,
well_depth: float,
well_width: float,
separation: float,
num_wells: int,
):
"""
Multiple square well poten... | Python | 1 |
from sortedcontainers import SortedList
class TweetCounts:
def __init__(self):
self.tweetNameToTimes = collections.defaultdict(SortedList)
def recordTweet(self, tweetName: str, time: int) -> None:
self.tweetNameToTimes[tweetName].add(time)
def getTweetCountsPerFrequency(self, freq: str, tweetName: str... | Python | 1 |
,// Fist_m16int
// 3 = 0x03
0x73,// Mf_1
0x82, 0x05,// Fistp_m16int
// 4 = 0x04
0x73,// Mf_1
0x83, 0x05,// Fbld_m80bcd
// 5 = 0x05
0x73,// Mf_1
0x84, 0x05,// Fild_m64int
// 6 = 0x06
0x73,// Mf_1
0x85, 0x05,// Fbstp_m80bcd
// 7 = 0x07
0x73,// Mf_1
0x86, 0x05,// Fistp_m64int
// handlers_FPU_DF_... | Rust | 0 |
chapter_start < current_page
&& current_page <= last_problem_on_page
&& current_page <= problems {
result += 1;
}
}
chapter_page += pages_per_chapter;
}
result
}
fn main() {
let n = read!();
let k = read!();
let input =... | Rust | 0 |
macros.rs
macro_rules! yaml_str {
($d:expr, $y:expr, $i:ident) => {
if let Some(v) = $y[stringify!($i)].as_str() {
$d.$i = Some(v.into());
}
};
}
macro_rules! cmp_ignore_none {
($_self:ident, $other:ident, $field:ident) => {
if let Some(ref self_field) = $_self.$field {
... | Rust | 0 |
я обновления трафика каждые 5 минут.")
users = db.get_users_with_expiration(server_id=current_server)
for user in users:
client_name, expiration_time, traffic_limit = user
if expiration_time:
try:
expiration_datetime = datetime.fromisoformat(expiration_time)
... | Python | 1 |
import pandas as pd
import math
import numpy as np
from scipy.optimize import fsolve
def get_initial_critical_angle(fiber_index,medium_refraction_index,max_distance,lamp_radius):
theta=[0.00000314159]
c = lamp_radius - max_distance
for i in range(999999):
theta.append(theta[i]+0.00000314159*0.5)... | Python | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .. import Conversion
class EquirecRotate(nn.Module):
def __init__(self, equ_h):
super().__init__()
self.equ_h = equ_h
self.equ_w = equ_h * 2
X = torch.arange(self.equ_w)[None, :, None].repeat(self.e... | Python | 1 |
&self,
command_buffer: &RafxCommandBuffer,
resource_context: &ResourceContext,
buffer: &ResourceArc<BufferResource>,
fill_value: u32,
) -> RafxResult<()> {
let mut descriptor_set_allocator = resource_context.create_descriptor_set_allocator();
command_buffer.cmd_bind_... | Rust | 0 |
/// Parse a type definition, e.g. `type MyMap = Map<u8, address>`.
/// # Panics
/// Panics if the next token isn't `type`.
pub fn parse_type_def(par: &mut Parser) -> ParseResult<Node<ModuleStmt>> {
let type_tok = par.assert(TokenKind::Type);
let name = par.expect(TokenKind::Name, "failed to parse type declara... | Rust | 0 |
ial {
let mut new_coefficients: [Quotient; TOTAL_COEFFICIENTS] = [ZERO; TOTAL_COEFFICIENTS];
for degree in 0..TOTAL_COEFFICIENTS-1 {
new_coefficients[degree] = self.coefficients[degree + 1] * Quotient::from_int((degree + 1) as u64);
}
Polynomial::new(new_coefficients)
}... | Rust | 0 |
):
# 不同版本的流量权重配置
self.version_weights = version_weights
def validate(self):
if self.version_weights:
for k in self.version_weights:
if k:
k.validate()
def to_map(self):
_map = super().to_map()
if _map is not None:
... | Python | 1 |
buf; \
proto=io.prometheus.client.MetricFamily;
encoding=delimited";
impl Key for HandlerStorage {
type Value = Arc<RwLock<LruCache<u64, promo_proto::MetricFamily>>>;
}
fn families_to_u8(metric_families: Vec<(&u64, &promo_proto::MetricFamily... | Rust | 0 |
/// Approximate number of [`bf16`] significant digits in base 10
pub const DIGITS: u32 = 2;
/// [`bf16`]
/// [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value
///
/// This is the difference between 1.0 and the next largest representable number.
pub const EPSILON: bf16 = bf16... | Rust | 0 |
, val) = expr_level_percent(rem)?;
Ok((rem, Expression::Negate(Box::new(val))))
}
Err(_) => expr_level_percent(raw),
}
}
pub fn expr_level_exponentiate(raw: &str) -> IResult<&str, Expression> {
let (left_rem, left_res) = expr_level_negate(raw)?;
let (right_rem, right_res) = mul... | Rust | 0 |
e(String::from(&rec[5]));
}
"primary" => {
// Add a primary read name and sequence to the stack
primary.push((String::from(&rec[4]), String::from(&rec[5])));
}
"secondary" => {
// Add a secondary ... | Rust | 0 |
nsic_height::<T>);
iface.get_intrinsic_aspect_ratio = Some(paintable_get_intrinsic_aspect_ratio::<T>);
iface.snapshot = Some(paintable_snapshot::<T>);
}
fn instance_init(_instance: &mut glib::subclass::InitializingObject<T>) {}
}
unsafe extern "C" fn paintable_get_current_image<T: PaintableImp... | Rust | 0 |
ELISION: u32 = 1;
pub const __PTHREAD_MUTEX_NUSERS_AFTER_KIND: u32 = 0;
pub const __PTHREAD_MUTEX_USE_UNION: u32 = 0;
pub const __PTHREAD_RWLOCK_INT_FLAGS_SHARED: u32 = 1;
pub const __PTHREAD_MUTEX_HAVE_PREV: u32 = 1;
pub const __have_pthread_attr_t: u32 = 1;
pub const PF_UNSPEC: u32 = 0;
pub const PF_LOCAL: u32 = 1;
p... | Rust | 0 |
as u64)?;
} else {
w.write_u8(constants::DW_CFA_offset_extended.0)?;
w.write_uleb128(register.0.into())?;
w.write_uleb128(offset as u64)?;
}
}
CallFrameInstruction::ValOffset(register, offset) => {
... | Rust | 0 |
ve_consultative': seed_analysis['collaborative_need'] * 2,
'creative_innovative': seed_analysis['innovation_requirement'] * 2,
'critical_questioning': seed_analysis['critical_analysis_need'] * 2,
'practical_pragmatic': seed_analysis['practical_focus'] * 2,
'holistic_compr... | Python | 1 |
fn get_byte(&self, addr: u16) -> u8 {
match addr {
0x8000..=0x9FFF => match self.stat.mode {
GpuMode::PixelTransfer => 0xFF,
_ => self.get_vram_byte(addr, self.vram_bank),
},
0xFE00..=0xFE9F => match self.stat.mode {
GpuMode::O... | Rust | 0 |
fn get(&self, x: isize, y: isize) -> bool {
if x < 0 || y < 0 || x >= DIM || y >= DIM {
false
} else {
self.0 & (1 << (y * DIM + x)) != 0
}
}
fn set(&mut self, x: isize, y: isize, value: bool) {
if x >= 0 && y >= 0 && x < DIM && y < DIM {
if v... | Rust | 0 |
import asyncio
import io
import os
from datetime import datetime
from pathlib import Path
from telethon import events, functions, types
from telethon.tl.types import InputMessagesFilterDocument
from . import *
@dominator_cmd(pattern="cmds$")
async def kk(event):
reply_to_id = event.message.id
if event.repl... | Python | 1 |
, 0x08, 0xff]);
test_display(&[0x0f, 0xc5, 0xd1, 0x00], "pextrw edx, mm1, 0x0");
test_invalid(&[0x0f, 0xc5, 0x01, 0x00]);
test_display(&[0x0f, 0xd8, 0xc2], "psubusb mm0, mm2");
test_display(&[0x0f, 0xd9, 0xc2], "psubusw mm0, mm2");
test_display(&[0x0f, 0xda, 0xc2], "pminub mm0, mm2");
test_dis... | Rust | 0 |
from playwright.sync_api import sync_playwright
from bs4 import BeautifulSoup
import time
def scrape_news(stock_symbol: str) -> dict:
url = f"https://finance.yahoo.com/quote/{stock_symbol}/news?p={stock_symbol}"
with sync_playwright() as pw:
browser = pw.chromium.launch(headless=False, slow_mo=500) # ... | Python | 1 |
r2d2::Pool<RedisConnectionManager> ;
lazy_static! {
static ref RSA_SECRET: Vec<u8> = base64::decode(env::var(ENV_RSA_SECRET).expect("rsa secret must be set")).unwrap();
static ref RSA_PUBLIC: Vec<u8> = base64::decode(env::var(ENV_RSA_PUBLIC).expect("rsa public key must be set")).unwrap();
static ref JWT_S... | Rust | 0 |
13] -
m[12] * m[1] * m[6] +
m[12] * m[2] * m[5];
inv[3] = -m[1] * m[6] * m[11] +
m[1] * m[7] * m[10] +
m[5] * m[2] * m[11] -
m[5] * m[3] * m[10] -
m[9] * m[2] * m[7] +
m[9] * m[3] * m[6];
inv[7] = m[0] * m[6] ... | Rust | 0 |
, g[n - 1], y[n], x2[n])
else:
v0 = CHARFZERO(v[n], eps, B, G, K, S, p, 1, y[n], x2[n])
x[n] = abs(find_root((find_root(v0, p) - (1 - B) * x2[n]) / B, 1 / p))
x2[n] = v0 ** p
g[n] = np.abs(y[n]) / np.abs(x[n])
else:
g[n] = G + (1 - G) ... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# 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 requir... | Python | 1 |
ender<Vec<u8>>,
}
impl FileWatcherState<Initilizing> {
async fn new(path: impl AsRef<Path>) -> Result<FileWatcher, std::io::Error>
where {
let file = File::open(path.as_ref()).await?;
let (output_tx, output_rx) = async_std::channel::unbounded();
Ok(FileWatcher::Initilizing(FileWatcherState ... | Rust | 0 |
n], BaseException, TracebackType],
) -> None:
"""Handle errors when trying to remove read-only files through `shutil.rmtree`.
On Windows, `shutil.rmtree` does not handle read-only files very well. This handler
makes sure the given file is writable, then re-execute the given removal function.
Arguments... | Python | 1 |
# coding=utf-8
import jieba
import re
import sys
import time
from collections import Counter
import matplotlib.pyplot as plt
from wordcloud import WordCloud
#------------------------------------中文分词------------------------------------
cut_words = ""
all_words = ""
f = open('data-fenci.txt', 'w')
for line in open('data... | Python | 1 |
import torch
import torch.nn as nn
from ReConV2.tools import builder
from ReConV2.utils.logger import *
from ReConV2.tools.runner_pretrain import Trainer
from ReConV2.datasets import data
def run_net(args, config):
logger = get_logger(args.log_name)
# build model
device = torch.device("cuda", args.local_... | Python | 1 |
the bounds here ourself
let c = unsafe { *self.src.get_unchecked(i) } as char;
if c.is_ascii_whitespace() {
if signed {
// Case c if operator (but wasn't allowed to end in -) assume unary
if operator {
return true;
... | Rust | 0 |
L.FBNET.MASK_HEAD_STRIDE = 0
# 0 to use all blocks defined in arch_def
_C.MODEL.FBNET.RPN_HEAD_BLOCKS = 0
_C.MODEL.FBNET.RPN_BN_TYPE = ""
# ---------------------------------------------------------------------------- #
# Specific test options
# -------------------------------------------------------------------------... | Python | 1 |
swith('.json') and not filename.startswith('._'):
filepath = os.path.join(config.OUTPUT_DIR, filename)
with open(filepath, 'r', encoding='utf-8') as f:
data = json.load(f)
metadata = data.get('metadata_payload', {})
for key in REQUIRED_TAGS:
... | Python | 1 |
(int) -- the number of filters in the last conv layer
n_layers (int) -- the number of conv layers in the discriminator
norm_layer -- normalization layer
"""
super(NLayerDiscriminator, self).__init__()
if type(norm_layer) == functools.partial: # no need to u... | Python | 1 |
from(v.len()).map_err(|_| {
Error::new(
ErrorKind::InvalidInput,
format!("invalid vector length > u32: {}", v.len()),
)
})?)?;
for p in v {
write_point(w, p)?;
}
Ok(())
}
fn write_point<G: CurveAffine, W: Write>(w: &mut W, p: &G) -> io::Result<()> {
w... | Rust | 0 |
let rotate = match (clkw, cclw) {
(true, true) | (false, false) => return,
(true, false) => Rotate::Clockwise,
(false, true) => Rotate::Counterclockwise,
};
let mut tetromino_pos = tetromino_pos.iter_mut().collect::<Vec<_>>();
// store original positions just in case rotation need... | Rust | 0 |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
ExtractorError,
smuggle_url,
)
class MinistryGridIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ministrygrid\.com/([^/?#]*/)*(?P<id>[^/#?]+)/?(?:$|[?#])'
_TEST = {
'url': 'http://www.ministr... | Python | 1 |
rt result == 2
result = aifpl.evaluate('(match (list 1 2 3 4 5) ((a b c . rest) (list a (length rest))))')
assert result == [1, 2]
# Valid single element with tail
result = aifpl.evaluate('(match (list 42) ((head . tail) (null? tail)))')
assert result
result = aifpl.ev... | Python | 1 |
ive(PartialEq, Eq, Clone)]
pub struct UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Extra: SignedExtension,
{
/// The signature, address, number of extrinsics have come before from
/// the same signer and an era describing the longevity of this transaction,
/// if this is a signed extrinsic.
pub signat... | Rust | 0 |
watch_directory(
path=watch_dir,
callback=on_change,
interval=1.0
)
monitor_thread.start()
time.sleep(2)
print("Creating a test file in watched directory...")
test_watch_file = watch_dir + "/watch_test.txt"
filesystem.... | Python | 1 |
# import pygame
# # import random
# pygame.init()
# screen = pygame.display.set_mode((900,900))
# # def rand_color():
# # return (random.randint(0,255), random.randint(0,255), random.randint(0,255))
# # color = rand_color()
# x, y = 300, 400
# speed = 50
# square = pygame.Rect(350, 250, 100, 100)
# dragging = ... | Python | 1 |
// function. This key is often handled directly in the keyboard hardware
/// and does not usually generate key events.
Fn,
/// The Function-Lock (`FnLock` or `F-Lock`) key. Activating this key
/// switches the mode of the keyboard to changes some keys' values to an
/// alternate character or function. This key is ... | Rust | 0 |
print(f"📈 Epoch {epoch + 1} 平均损失: {avg_loss:.4f}")
# 评估阶段
trainer.policy_model.eval()
test_prompts = [
"你好,能和我聊聊天吗?",
"你觉得我怎么样?",
"能给我一些建议吗?",
"我失恋了,好难过",
"你觉得我聪明吗?",
"今天天气真好",
"我想学编程",
... | Python | 1 |
ing>) -> Result<i32, Box<dyn Error>> {
let mut grid: Grid = [[0; SIZE]; SIZE];
for line in lines {
let caps = LINE_REGEX.captures(line).unwrap();
let x1: usize = caps["x1"].parse()?;
let y1: usize = caps["y1"].parse()?;
let x2: usize = caps["x2"].parse()?;
let y2: usize... | Rust | 0 |
import os
import re
import openai
from dotenv import load_dotenv
import time
import json
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
openai.api_base = os.getenv('OPENAI_API_BASE', 'https://api.openai.com/v1')
system_message = \
"""请你扮演科普专家的角色。这是一个为视频配音设计的翻译任务,将各种语言精准而优雅地转化为尽量简短的正确的翻译。请在翻译时避免生硬的直译,而是追求自... | Python | 1 |
,
'始',
'繁',
'响',
'柳',
'仍',
'呀',
'错',
'负',
'小',
'己',
'蜒',
'偶',
'女',
'渴',
'驰',
'锹',
'型',
'背',
'放',
'拿',
'花',
'辈',
'燕',
'郊',
'便',
'屿',
'售',
'罐',
'湖',
'之',
'剑',
'蔽',
'驴',
'阀',
'镜',
'试',
'着',
'益',
'败',
'一',
'旷',
'冻',
'浩',
'筒',
'粱',
'闪',
'酿',
'变',
'嘱',
'撑',
'斧',
'抱',
'祥',
... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, List, Optional, Set
"""
Utility functions for supporting the XML Schema Datatypes hierarchy
"""
from rdflib.namespace import XSD
if TYPE_CHECKING:
from rdflib.term import URIRef
XSD_DTs: Set[URIRef] = set(
(
XSD.integer,
... | Python | 1 |
from setting.db_connections import ms_query_db
from flask import Blueprint, jsonify, request
item_bp = Blueprint("item", __name__)
@item_bp.route("/itemgroup", methods=["GET"])
def get_itemgroup():
try:
# Initialize query and parameters
base_query = "select ItmsGrpCod, ItmsGrpNam from ItemGroup... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.