text string | label_name string | labels int64 |
|---|---|---|
true` for the lower limit, `false` for the upper limit
/// - value: limit value, in the case of Limitless, it indicates that there is no limit.
/// - return: a new limit
pub fn new(closed: bool, lower: bool, value: LimitValue<T>) -> Self {
Self {
closed: if value.is_limitless() { false } else { clos... | Rust | 0 |
TreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::io;
use std::mem::*;
#[fastout]
fn main() {
input! {
q: usize,
}
let mut deq = VecDeque::new();
for _ in 0..q {
input! {
t: usize,
}
if t == 1 {
input! {
x: u64,
... | Rust | 0 |
ize>,
}
impl Scope {
pub fn new<S: Into<String>>(name: S, variables_reference: usize) -> Self {
Self {
name: name.into(),
presentation_hint: None,
variables_reference,
named_variables: None,
indexed_variables: None,
expensive: false,
... | Rust | 0 |
# Copyright 2021 The Matrix.org Foundation C.I.C.
#
# 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 a... | Python | 1 |
{
let instance = self.instance.as_ref().expect("no instance").clone();
let result = instance.invoke_export(MAIN_FUNCTION_NAME, &[], self);
self.logger.log_sensitive(
Level::Info,
&format!("Running Wasm module completed with result: {:?}", result),
);
}
fn... | Rust | 0 |
40.jpg",
content_score: 7,
easy_score: 8.3,
logic_score: 8.4,
time: "2019-08-01",
comment: "老师讲的很细,思路清晰,视频时长也不算长,学起来很轻松"
},
{
name: "网络侦探",
avatar: "https://img.mukewang.com/5599e8e100010c2110800960-40-40.jpg",
content_score: 9,
easy_score: 8.3,
logic_score: 8.4,
time: "2... | Python | 1 |
lution.y[2], label="ydot (m/2)")
axs[0].plot(t, solution.y[3], label="theta_dot (rad/s)")
axs[0].set_ylabel("Response")
axs[0].set_title("Cart Response")
axs[0].grid(True)
axs[0].legend(loc="best")
# Second subplot: Control input
axs[1].plot(t, F, label="Force u (N)", color="red")
axs[1... | Python | 1 |
Attributes(HashMap<String, Attribute>);
impl Attributes {
pub fn new() -> Self {
Self(HashMap::with_capacity(18))
}
/// Adds or updates a given entry.
pub fn insert(&mut self, name: String, value: Attribute) {
self.0.insert(name, value);
}
/// Borrows an attribute by name, if f... | Rust | 0 |
fully contained in the file.
{
let program_header_iterator = ProgramHeaderIterator {
current_header_index: 0,
header_num: header.program_header_entry_num as usize,
header_size: header.program_header_entry_size a... | Rust | 0 |
:epoll_wait(self.epoll_fd, &mut epoll_events, -1).unwrap_or(0);
for epoll_event in &epoll_events[0..available_fds] {
if epoll_event.data() == EVENT_KIND_X11 {
while let Some(event) = self.connection.poll_for_event()? {
callback(Event::X11Event(eve... | Rust | 0 |
eanup] Releasing camera and killing all gphoto2 processes...")
try:
subprocess.run(["pkill", "-9", "gphoto2"])
except Exception as e:
print(f"[cleanup] Error killing gphoto2: {e}")
def handle_exit(signum, frame):
print(f"[signal] Received signal {signum}, exiting and releasing camera...")
... | Python | 1 |
import random
actions = ['rock', 'paper', 'scissors']
while True:
user_choice = input('Enter your choice (rock, paper or scissors): ')
program_choice = random.choice(actions)
print("Your choice", user_choice, "and Computer choice", program_choice)
if user_choice == program_choice:
print("Bo... | Python | 1 |
///
/// By "Pythonically" we mean that the list length is added to the index if it
/// is negative, allowing -1 to be used for the end of the list, -2 for the
/// penultimate item, and so on.
///
/// `len` specifies the size of the list, `index` is the index to convert, and
/// `insert` selects whether index == len is ... | Rust | 0 |
Red,
//! Green { range:usize },
//! Blue(usize),
//! Yellow,
//! }
//!
//! // It's simple to iterate over the variants of an enum.
//! fn debug_colors() {
//! let red = Color::Red;
//! assert_eq!(String::from("redred"), red.to_string());
//! }
//!
//! ... | Rust | 0 |
]
|| weak_key == &tmp[DES_LEN_DES..2 * DES_LEN_DES]
|| weak_key == &tmp[2 * DES_LEN_DES..3 * DES_LEN_DES]
{
rv = true;
break;
}
}
tmp.zeroize();
rv
}
/// PKCS#5 error types
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(i32)]
pub enum Pk... | Rust | 0 |
object.
"""
r = self.memory_temporal_stride_for_eval
frame_idx_begin = frame_idx - r * self.num_maskmem
frame_idx_end = frame_idx + r * self.num_maskmem
output_dict = inference_state["output_dict"]
non_cond_frame_outputs = output_dict["non_cond_frame_outputs"]
fo... | Python | 1 |
libc::EINVAL),
)
};
}
if unsafe { libc::sigprocmask(libc::SIG_BLOCK, &mut sigset, std::ptr::null_mut()) } < 0 {
unsafe {
libc::exit(
Error::last_os_error()
.raw_os_error()
.unwrap_... | Rust | 0 |
[34, 2],
"&": [35, 2],
"'": [49, 0],
"(": [37, 2],
")": [38, 2],
"*": [49, 2],
"+": [45, 0],
",": [54, 0],
"-": [56, 0],
".": [55, 0],
"/": [36, 2],
"0": [39, 0],
"1": [30, 0],
"2": [31, 0],
"3": [32, 0],
"4": [33, 0],
"5": [34, 0],
"6": [35, 0],
... | Python | 1 |
let s = Parser::parse_tcon("(CRlol)");
assert_eq!(s, "(CRlol)");
}
}
use crate::syn::{ReadableType, Reader, WritableType, Writer};
use asn1rs_model::model::Tag;
use core::marker::PhantomData;
pub struct OctetString<C: Constraint = NoConstraint>(PhantomData<C>);
pub trait Constraint: super::common::C... | Rust | 0 |
from psychopy.alerts import catalog
from psychopy import core
import sys
write_mode = 'w'
alertmsgFile = 'alertmsg.py'
try:
fp = open(alertmsgFile, write_mode)
fp.write('#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n')
fp.write('# This file was generated by generateAlertmsg.py.\n')
fp.write('# Fo... | Python | 1 |
from matplotlib import pyplot as plt
import numpy as np
labels = ['h-BN', r'1H-MoS$_2$', r'1H-MoSe$_2$', r'1H-MoTe$_2$',
r'1H-WS$_2$', r'1H-WSe$_2$', r'1H-WTe$_2$']
ref = [3.71, 3.06, 2.8, 2.98, 2.20, 1.93, 1.60]
mydata = [3.68, 2.92, 2.69, 2.53, 2.04, 1.82, 1.54]
ref = [1.38, 3.64, 3.92, 5.43, 2.47, 2.71, ... | Python | 1 |
9921
});
assert_eq!(Murphy::merchant_ledgers(&charlie), MerchantLedger {
collateral: 6_000_000,
reward: 5242
});
assert_eq!(Murphy::merchant_ledgers(&dave), MerchantLedger {
collateral: 6_000_000,
reward: 4940
});
assert_eq... | Rust | 0 |
horizontal separator between disjoint runs of lines
if let Some(last_line) = last_line {
if last_line + 1 != line_index {
let dash = colors::gray(&"-".repeat(WIDTH + 1));
println!("{}{}{}", dash, colors::gray(SEPERATOR), dash);
}
}
println!(
... | Rust | 0 |
ScalarType::Boolean`s become JSON booleans.
/// * All numeric types are converted to `Float64`s, then become JSON numbers.
/// * Records are converted to a JSON object where the record's field names
/// are the keys of the object, and the record's fields are recursively
/// converted to JSON by `to_jsonb`.
... | Rust | 0 |
data.get(cid).unwrap();
assert_eq!(expect_row[&cid], v.to_vec());
}
}
assert!(scanner.next().unwrap().is_none());
}
#[test]
fn test_reverse_scan() {
let mut statistics = Statistics::default();
let mut wrapper = IndexTestWrapper::default();
... | Rust | 0 |
#!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the terms set forth in the LICENSE.txt file available at
# https://openusd.org/license.
#
from __future__ import print_function
import os
ASSET_BASE = os.path.join('../../', 'models')
def main():
sequenceFilePath = 'shots/s00/s00.usd'
setsLayoutLa... | Python | 1 |
};
use crate::util::Location;
pub type BoolResult = Result<bool, ParseErr>;
pub type ParseResult = Result<ast::Program, ParseErr>;
pub type StatementResult = Result<ast::Statement, ParseErr>;
pub type StatementsResult = Result<Vec<ast::Statement>, ParseErr>;
pub type ExprResult = Result<ast::Expr, ParseErr>;
pub type ... | Rust | 0 |
MobileCoin Foundation
//! Contains "native" rust structs that correspond to structs generated by
//! protobuf.
use alloc::{string::String, vec::Vec};
use mc_crypto_keys::CompressedRistrettoPublic;
use serde::{Deserialize, Serialize};
/// Mirrors the proto definition of IngestSummary. We have to define this
/// "na... | Rust | 0 |
logger.warning(f"Skipping row due to error: {e}")
continue # 에러 발생 시 해당 행 건너뜀
logger.info(f"Number of instances loaded: {len(instances)}") # 디버깅 추가
# 샘플 제한이 설정된 경우 제한된 데이터 반환
if limit:
instances = random.sample(instances, min(limit, len(instances)))
return instances
... | Python | 1 |
import math
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from translate import TranslatedBlurb
def flow_into_box(text, w, font=None, min_word_on_line=.3):
def text_width(l):
if l:
return d.textsize(l, font=font)[0]
else:
return 0
dImg = Im... | Python | 1 |
d, TcpStream> | -> () {
println!("child (stderr) got active");
let mut buf = [0; 10];
let n = stderr.do_read(&mut buf).expect("read_child");
println!("({} bytes) `{}'", n, String::from_utf8_lossy(&buf[..n]));
};
//do all the stuff
fdstore.select(... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
# Menu pour les équations différentielles
def equations_differentielles_menu():
while True:
print("\nÉquations Différentielles :")
print("1. Choisir une méthode et afficher toutes les courbes")
print("2. Quitter")
choix = input("Ent... | Python | 1 |
/// resolved: &ResolvedRoot
/// ) -> Result<(), Box<dyn std::error::Error>> {
/// let response: QueryResult<NameAndType> = client
/// .query(
/// &resolved,
/// QueryRequestCommon {
/// glob: Some(vec!["**/*.rs".to_string()]),
/// ... | Rust | 0 |
from libai.config import LazyCall
from libai.evaluation import PPLEvaluator
from projects.MagicPrompt.configs.gpt2_inference import pretrain_model as model
from projects.MagicPrompt.configs.gpt2_dataset import dataloader, tokenization
from configs.common.optim import optim
from libai.scheduler import WarmupExponential... | Python | 1 |
eReactive>,
Read<'a, InputHandler<A, B>>,
ReadExpect<'a, ScreenDimensions>,
Write<'a, EventChannel<UiEvent>>,
);
fn run(
&mut self,
(entities, transform, react, input, screen_dimensions, mut events): Self::SystemData,
) {
let down = input.mouse_button_is_down... | Rust | 0 |
ElGamal key generation, following algorithm 8.17.
pub fn generate() -> (PrivateKey, PublicKey) {
// Select a random integer a, 1 <= a <= p - 2
// Public key is α^a mod p
let (a, alpha_a) = gen_gamma_k();
let priv_key = {
let buf = rectify(&a, 256);
let mut x... | Rust | 0 |
box(a(1, 2, 3)); black_box(x);
x = black_box(a(1, 2, 3)); black_box(x); x = black_box(a(1, 2, 3)); black_box(x);
}
black_box(x);
}
black_box(x);
}
fn primitive_array() {
let mut a = vec![1_i32, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let mut x = 0;
for i in 0 .. 100_000 {
black_box(i);
for j in 0 .. 10 {
bl... | Rust | 0 |
(buf: &mut [u8], flags: GetRandomFlags) -> io::Result<usize> {
// `getrandom` wasn't supported in glibc until 2.25.
weak_or_syscall! {
fn getrandom(buf: *mut c::c_void, buflen: c::size_t, flags: c::c_uint) via SYS_getrandom -> c::ssize_t
}
let nread =
unsafe { ret_ssize_t(getrandom(buf.... | Rust | 0 |
more_children = root.children(arena);
assert_eq!(more_children.next(), Some(left));
assert_eq!(more_children.next(), Some(right));
assert!(more_children.next().is_none());
}
#[test]
fn node_should_know_its_parent() {
let arena = &mut Arena::new();
let root ... | Rust | 0 |
let mut cur = Cursor::new(buf);
let mut out: &mut [u8] = &mut [0u8; 10];
assert_eq!("le message", read_str(&mut cur, &mut out).unwrap());
assert_eq!(11, cur.position());
}
#[test]
fn from_str_strfix_invalid_utf8() {
// Invalid 2 Octet Sequence.
let buf: &[u8] = &[0xa2, 0xc3, 0x28];
let m... | Rust | 0 |
; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
#[test]
fn test_hash_mac_addr() {
let hasher = InspectHasher::new(HASH_KEY);
let mac_addr = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
let hashed_str = hasher.hash_mac_addr(mac_addr);
assert!(hashed_str.starts_with("11:22:33:"));
assert_ne!(ha... | Rust | 0 |
e for numpy).
"""
if NumPy_type(a) == 'Numeric':
return a.typecode()
elif NumPy_type(a) == 'numarray':
return a.typecode()
elif NumPy_type(a) == 'numpy':
return a.dtype
else:
raise TypeError("array should be NumPy array, not %s" % type(a))
def fortran_storage(a):
... | Python | 1 |
[i16; 4], coeffs_h: &[i16; 4]) {
if coeffs_h[1] == 128 {
for dline in dst.chunks_mut(dstride).take(8) {
for i in 0..8 {
dline[i] = mc_filter!(bicubic; src, soff + i, 1, coeffs_w);
}
soff += sstride;
}
} else if coeffs_w[1] == 128 { // horizonta... | Rust | 0 |
#
# Copyright (C) 2020 IBM. All Rights Reserved.
#
# See LICENSE.txt file in the root directory
# of this source tree for licensing information.
#
# pylint: disable=invalid-name
import io
import os
import platform
def is_windows():
return platform.system() == 'Windows'
def is_mac():
return platform.system()... | Python | 1 |
are a total of 48 elements
in O, which can be generated by the 6 permutations of the principal axes
and the 2^3=8 reflections, two different reflections for each axis. 24 of
these elements preserve the orientation of the axes, while the other 24
elements invert the orientation of the axes.
"""
... | Python | 1 |
fn draw_eye(ctx: &Context, g: &mut G2d, x: f64, y: f64) {
rectangle(
colors::EYE,
[x, y, 4.0, 4.0],
ctx.transform,
g
);
}
let (x,y) = (
block_in_pixels(pos.x as u32) as f64,
block_in_pixels(pos.y as u32) as f64
);
let blo... | Rust | 0 |
OtherVote {
pub target: ::subxt::sp_core::crypto::AccountId32,
pub index: ::core::primitive::u32,
}
impl ::subxt::Call for RemoveOtherVote {
const PALLET: &'static str = "Democracy";
const FUNCTION: &'static str = "remove_other_vote";
}
#[derive(:: subxt :: codec :: Encode, :: subxt :: codec... | Rust | 0 |
_name = utils::new_c_string("palette")?;
let q_in: i32 = pngsave_options.q;
let q_in_name = utils::new_c_string("Q")?;
let dither_in: f64 = pngsave_options.dither;
let dither_in_name = utils::new_c_string("dither")?;
let bitdepth_in: i32 = pngsave_options.bitdepth;
let... | Rust | 0 |
from __future__ import annotations
import pytest
import narwhals as nw
from tests.utils import DUCKDB_VERSION, Constructor, ConstructorEager, assert_equal_data
def test_is_unique_expr(constructor: Constructor) -> None:
if "duckdb" in str(constructor) and DUCKDB_VERSION < (1, 3):
pytest.skip()
data ... | Python | 1 |
)
.draw(display)
.unwrap();
}
for wall in walls.iter() {
Rectangle::new(
world2screen(wall.bounding_box.min),
world2screen_size(wall.bounding_box.size()),
... | Rust | 0 |
_MRENCLAVE
));
assert_ok!(Exchange::add_to_whitelist(
Origin::root(),
COINGECKO_SRC.to_owned(),
hex!("f4dedfc9e5fcc48443332bc9b23161c34a3c3f5a692eaffdb228db27b704d9d2")
));
assert_ok!(Exchange::add_to_whitelist(
Origin::root(),
COINGECKO_SRC.to_owned(),
hex!("f4dedfc9e5fcc48443332bc9b23161c34a... | Rust | 0 |
memory[i] = 0xF0; i+=1;
memory[i] = 0x10; i+=1;
memory[i] = 0xF0; i+=1;
memory[i] = 0x90; i+=1;
memory[i] = 0x90; i+=1;
memory[i] = 0xF0; i+=1;
memory[i] = 0x10; i+=1;
memory[i] = 0x10; i+=1;
memory[i] = 0xF0; i+=1;
memory[i] = 0x80; i+=1;
... | Rust | 0 |
URL_INIT = "https://solstone-app.gleam.bot"
URL_AUTH = "https://solstone-api.gleam.bot/auth"
URL_TASKS = "https://solstone-api.gleam.bot/quests?project=SolStone"
URL_CLAIM_TASK = "https://solstone-api.gleam.bot/complete-quest"
URL_START_FARM = "https://solstone-api.gleam.bot/start-farming"
URL_CLAIM_FARMED = "https://s... | Python | 1 |
import uuid
import pytest
from globus_sdk.scopes import (
AuthScopes,
ComputeScopes,
FlowsScopes,
GCSCollectionScopes,
GCSEndpointScopes,
GroupsScopes,
NexusScopes,
Scope,
SearchScopes,
SpecificFlowScopes,
TimersScopes,
TransferScopes,
)
@pytest.mark.parametrize(
... | Python | 1 |
outcome = compared > 0
elif relation == ">=":
outcome = compared >= 0
else:
raise BasicProviderError("Invalid boolean function relation.")
# Store outcome in register and optionally memory sl... | Python | 1 |
from __future__ import annotations
import functools
import os
import socket
from ..common import running_mac, running_windows
@functools.lru_cache()
def locate_chrome_path() -> str | None:
"""Locate Chrome's executable path."""
if running_windows():
app_dirs = []
# Win paths from WinAPI
... | Python | 1 |
(A::from_flatbuf(fb)?))
}
}
#[cfg(feature = "flatbuf")]
impl<'b, A, T> ToFlatBuffer<'b> for Intern<A>
where
T: 'b,
A: Eq + Send + Sync + Hash + ToFlatBuffer<'b, Target = T>,
{
type Target = T;
fn to_flatbuf(&self, fbb: &mut fbrt::FlatBufferBuilder<'b>) -> Self::Target {
self.as_ref().to_fl... | Rust | 0 |
points))
handle_1 = ax.plot(num_points, line, label=func_name)[0]
handle_2 = ax.plot(num_points, 10**best_lams, next(symbols))[0]
legend[0].append((handle_1, handle_2))
legend[1].append(func_name)
ax.loglog()
ax.legend(*legend)
ax.set_xlabel('Input Array Size, N')
ax.set_ylabel('Optimal lam Value')
p... | Python | 1 |
from fastapi import APIRouter, HTTPException, Depends, status
from sqlalchemy.orm import Session
from app import models, schemas, database
router = APIRouter(
prefix="/salles",
tags=["Salles"]
)
# Dépendance pour obtenir la session de la base de données
def get_db():
db = database.SessionLocal()
try:
... | Python | 1 |
DD\xED\xE1 \xF4\xE5\xF3\xF4.";
let characters = "\u{0391}\u{03C5}\u{03C4}\u{03CC} \
\u{03B5}\u{03AF}\u{03BD}\u{03B1}\u{03B9} \u{03AD}\u{03BD}\u{03B1} \
\u{03C4}\u{03B5}\u{03C3}\u{03C4}. \u{0391}\u{03C5}\u{03C4}\u{03CC} \
\u{03B5}\u{03AF}\u{03BD}\u{03... | Rust | 0 |
oute(&x) {
let buses = app.primary.sim.status_of_buses(r.id);
if buses.is_empty() {
Transition::Push(msg(
"No buses running",
vec![format!("Sorry, no buses for route {} running", r.name)],
... | Rust | 0 |
Ok(EvalPlan::MoreInput) => {
debug!("eval more input");
let _ = stderr
.write("exec: incomplete command\r\n".as_bytes())
.await;
Ok(ExecResponse::Immediate(err::ERR_EINVAL))
}
Ok(EvalPlan::Invalid... | Rust | 0 |
is_ascii_alphanumeric(&self) -> bool {
self._is_subset(&Self::ASCII_ALPHANUMERIC)
}
/// Returns `true` if [`u8::is_ascii_digit`] returns `true` for all bytes in
/// `self`.
///
/// This is significantly more efficient than checking each byte in `self`
/// individually.
///
/// [... | Rust | 0 |
};
assert_ok!(Deip::invest_to_crowdfunding_impl(
BOB_ACCOUNT_ID,
sale_id,
DeipAsset::new(base_asset_id, hard_cap / 2),
));
// investors should get their tokens in any case
let call = pallet_deip_assets::Call::<Test>::freeze(usd_id, BOB_ACCOUNT_ID);
... | Rust | 0 |
import random
import requests
from requests.exceptions import JSONDecodeError
from utils.settings import config
from utils.voice import check_ratelimit
voices = [
"Brian",
"Emma",
"Russell",
"Joey",
"Matthew",
"Joanna",
"Kimberly",
"Amy",
"Geraint",
"Nicole",
"Justin",
... | Python | 1 |
"]
#[doc = ""]
#[doc = " ```"]
#[doc = " FT_GlyphSlot slot = face->glyph;"]
#[doc = " FT_Pos origin_x = 0;"]
#[doc = ""]
#[doc = ""]
#[doc = " for all glyphs do"]
#[doc = " <load glyph with `FT_Load_Glyph'>"]
#[doc = ""]
#[doc = " FT_Outline_Translate( slot->outline, origin_x & 63,... | Rust | 0 |
"--window", window_id])
.arg("--clearmodifiers")
.arg(key)
.status()
.context("Failed to exec xdotool")?;
if !status.success() {
return Err(anyhow!(
"Failed to exec xdotool: exit code {}",
status
.code()
.ok_or_else(|| ... | Rust | 0 |
ot, see <http://www.gnu.org/licenses/>.
use std::cmp::PartialEq;
use std::collections::{BTreeMap, HashSet};
use std::str::FromStr;
use std::sync::{Arc, Weak};
pub use parity_rpc::signer::SignerService;
use account_utils::{self, AccountProvider};
use ethcore::client::Client;
use ethcore::miner::Miner;
use snapshot::S... | Rust | 0 |
{
/// Get the type of a joystick, if available.
/// This can be called before any joysticks are opened.
pub fn SDL_JoystickGetDeviceType(device_index: ::std::os::raw::c_int)
-> SDL_JoystickType;
}
extern "C" {
/// Get the instance ID of a joystick.
/// This can be called before any joysticks are opene... | Rust | 0 |
if cast_options.shift { 1 } else { 0 };
let shift_in_name = utils::new_c_string("shift")?;
let vips_op_response = bindings::vips_cast(
inp_in,
&mut out_out,
format_in.try_into().unwrap(),
shift_in_name.as_ptr(),
shift_in,
NULL,
... | Rust | 0 |
#!/usr/bin/env python3
"""
锈病数据集小角度旋转清洗脚本
专门清理四个角都有黑色三角形的图像(包括小角度旋转)
"""
import os
import sys
from PIL import Image
from tqdm import tqdm
# 检查依赖项
try:
from PIL import Image
except ImportError:
print("❌ 缺少必要的库")
print("请安装: pip install Pillow")
sys.exit(1)
class SmallRotationCleaner:
"""小角度旋转图片清洗器... | Python | 1 |
.proto"],
&["src/"]).unwrap();
}
<reponame>xx01cyx/raytracer<filename>src/camera.rs
use crate::ray::Ray;
use crate::utils::*;
use crate::vec3::{self, Point3, Vec3};
#[derive(Copy, Clone)]
pub struct Camera {
origin: Point3,
lower_left_corner: Point3,
horizontal: Vec3,
ve... | Rust | 0 |
use image::load_from_memory;
use crate::config::environment::*;
use crate::utilities::image::reverse_rgba;
use crate::EmbeddedImages;
use super::support::GliumDisplayWinitWrapper;
pub struct DisplayImages;
lazy_static! {
static ref IMAGE_BOOTLOADER_LOGO_RGBA_RAW: Vec<u8> =
gen_load_image_reverse!("boo... | Rust | 0 |
def user_response_many_data(data, schema):
"""
create json response with help of schema
:param data: query fetched data
:return: json data
"""
response_data = schema(many=True).dump(data)
return response_data
| Python | 1 |
"""
Utility helpers for FastJango forms.
Minimal implementations to support tests; extend as needed.
"""
from typing import Any, Callable, List, Optional
def formset_factory(form_class: Any, extra: int = 0) -> Callable[..., List[Any]]:
def factory(data_list: Optional[List[dict]] = None) -> List[Any]:
item... | Python | 1 |
tx;
use crate::{
inspectors::ERC20,
reducers::{ArbitrageReducer, TradeReducer},
test_helpers::read_trace,
Reducer, TxReducer,
};
use ethers::providers::Provider;
use std::convert::TryFrom;
#[tokio::test]
async fn instantiate() {
let provider =
... | Rust | 0 |
).sign_pdf(
w,
existing_fields_only=cli_ctx.existing_fields_only,
appearance_text_params=get_text_params(ctx),
)
with open(outfile, 'wb') as outf:
buf = result.getbuffer()
... | Python | 1 |
results = {'segments' : segs_all,
'scores' : scores_all,
'labels' : cls_idxs_all}
return results
@torch.no_grad()
def postprocessing(self, results):
# input : list of dictionary items
# (1) push to CPU; (2) NMS; (3) convert to actual time stam... | Python | 1 |
from woningwaardering.vera.bvg.generated import Referentiedata
from woningwaardering.vera.referentiedatasoort import Referentiedatasoort
class BetalingsregelingeinderedenReferentiedata(Referentiedata):
pass
class Betalingsregelingeindereden(Referentiedatasoort):
afbetaald = BetalingsregelingeinderedenRefere... | Python | 1 |
let bs = server.ctos.lea();
bs.poll(events)
} else {
None
}
}
fn read(&self, buf: &mut [u8], flags: ReadFlags) -> ReadResult {
let server = self.server.lea();
let bs = server.stoc.lea();
let result = bs.read(buf, flags)?;
if result.is_blocked() {
let mut input_buffer = server.input_buflock.loc... | Rust | 0 |
s from POST request """
request_method = get_request_method(request)
if request_method != "POST":
return None
match = re.search("\r\n\r\n(.+)", request)
if match is None:
return {}
query_string = match.group(1)
return parse_query_string(query_string)
def unquote(string):
""... | Python | 1 |
else:
byte1 = 0
byte2 = file_size - 1
length = byte2 - byte1 + 1
def generate():
try:
with open(video_path, 'rb') as f:
f.seek(byte1)
remaining = length
... | Python | 1 |
to work since it
can not compute IoU only from point data.
Parameters
----------
data : np.ndarray
data
position : List
position
id_ : int
id_
nhood : int
nhood
Returns
-------
np.ndarray
"""
outside = True
if len(position) == 2:
... | Python | 1 |
ght_spectrum, 2))
# alternate light #1
# light = Box(Point3D(-0.4, -0.4, -0.01), Point3D(0.4, 0.4, 0.0),
# parent=enclosure,
# transform=translate(0, 1, 0) * rotate(0, 90, 0),
# material=UniformSurfaceEmitter(d65_white, 2))
# alternate light #2
# back_light = Sphere(0.1,
# pare... | Python | 1 |
jacobi_name_list)
#compute_jacobi_info(jacobi_list2, jacobi_name_list)
#draw_group_boxplot(jacobi_name_list, jacobi_list1, jacobi_list2)
# print("Now lets do jacobi statistic")
# order = -1
# jacobi_list1, jacobi_name_list = get_list_from_dic(get_group_jacobi_dic(draw_intra=True, draw_trendency=False),use_log=True)
#... | Python | 1 |
"""Chrome-GPT: An AutoGPT agent that interacts with Chrome"""
import click
from chromegpt.main import run_chromegpt
@click.command()
@click.option("--task", "-t", help="The task to execute", required=True)
@click.option(
"--agent",
"-a",
help="The agent type to use",
default="zero-shot",
type=cli... | Python | 1 |
g, String>) -> AlternativeMedia {
AlternativeMedia {
media_type: attrs
.get("TYPE")
.and_then(|s| AlternativeMediaType::from_str(s).ok())
.unwrap_or_else(Default::default),
uri: attrs.remove("URI"),
group_id: attrs.remove("GROUP... | Rust | 0 |
.0, float(stat['over5']) / 100.0])
if __name__ == "__main__":
args, unknown = parse_arguments(sys.argv)
stats = []
''' Matterport3D '''
if 'm3d_path' in args:
m3d_stats = calc_m3d_stats(args.m3d_path, args.max_depth)
stats.append(m3d_stats)
''' Stanford2D3D '''
if 's2d3d_path' i... | Python | 1 |
}
var factsDiff = _VirtualDom_diffFacts(x.d, y.d);
factsDiff && _VirtualDom_pushPatch(patches, 4, index, factsDiff);
diffKids(x, y, patches, index);
}
// DIFF FACTS
// TODO Instead of creating a new diff object, it's possible to just test if
// there *is* a diff. During the actual patch, do the diff again a... | Rust | 0 |
);
}
}
<filename>src/tag_utils.rs
#[cfg(feature = "ape")]
use crate::ape::tag::ape_tag::ApeTagRef;
use crate::error::{LoftyError, Result};
#[cfg(feature = "id3v1")]
use crate::id3::v1::tag::Id3v1TagRef;
#[cfg(feature = "id3v2")]
use crate::id3::v2::{
tag::{tag_frames, Id3v2TagRef},
Id3v2TagFlags,
};
#[cfg(feature... | Rust | 0 |
player)
player["exploded"] = True
self.check_for_collision()
player["sprite"].angle = player["current_angle"]
player["sprite"].change_x = player["speed"] * math.cos(
math.radians(player["current_angle"])
)
... | Python | 1 |
classes = [
'World',
'Sports',
'Business',
'Sci/Tech'
] | Python | 1 |
aff_file = open(aff_path, "r", encoding="ISO8859-1")
aff_rules = AFF(aff_file)
aff_file.close()
except IOError:
print(aff_path + " not found")
# Open DIC file
try:
dict_file = open(dict_path, "r", encoding="ISO8859-1")
dict... | Python | 1 |
"""
采集进度管理
"""
from utils.base import debug_p
class Process():
def __init__(self, crange):
"""
:param range: 采集范围 生成steps
"""
self.crange = crange
self.process = {}
steps = []
s1 = {
'title': '采集文章列表',
'des': '已经采集0篇文章',
'... | Python | 1 |
from .get_impls_util import get_lastest_uninst_impls
from .get_impls_util import get_lastest_halfdump_impls
from .get_impls_util import get_ori_cp910_impls
| Python | 1 |
0>, summary='total prints: 75891')
Metric('pages_total', 75891.0)
Result(state=<State.OK: 0>, summary='b/w: 54198')
Metric('pages_bw', 54198.0)
Result(state=<State.OK: 0>, summary='color: 21693')
Metric('pages_color', 21693.0)
"""
if "pages_total" not in section:
yield from check_le... | Python | 1 |
import logging
import sys
import threading
from flask import Flask, request
import discord
from discord.ext import commands
import requests
from spotipy import Spotify
from spotipy.oauth2 import SpotifyClientCredentials
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from chatter... | Python | 1 |
import awacs.ecr as ecr
import awacs.iam as iam
from awacs.aws import Allow, AWSPrincipal, PolicyDocument, Statement
from troposphere import Template
from troposphere.ecr import Repository
t = Template()
t.add_resource(
Repository(
"MyRepository",
RepositoryName="test-repository",
Reposit... | Python | 1 |
me = "sounds"]
pub struct SoundChangeset {
pub name: Option<String>,
pub category: Option<String>,
pub volume_adjustment: Option<Option<f32>>,
}
#[derive(Queryable, Insertable, AsChangeset, Identifiable, Debug, Clone)]
#[table_name = "soundfiles"]
#[primary_key(sound_id)]
pub struct Soundfile {
pub sound_id: i... | Rust | 0 |
lers,
#[cfg(any(feature = "gles32",))]
pub glGetSamplerParameterIiv: crate::command::PFN_glGetSamplerParameterIiv,
#[cfg(any(feature = "gles10",))]
pub glRotatef: crate::command::PFN_glRotatef,
#[cfg(any(feature = "gles32", feature = "gles30", feature = "gles31",))]
pub glSamplerParameterf: crat... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.