text string | label_name string | labels int64 |
|---|---|---|
u64;
while i > m {
r *= i;
i -= 1;
}
r
}
fn main() {
println!("{}", Solution::unique_paths(13, 23));
}
extern crate conway_game_of_life;
extern crate termion;
use conway_game_of_life::*;
fn main() {
let mut grid = vec![vec![Cell::new(false); 20]; 20];
println!("==============... | Rust | 0 |
alfa, beta])):
print(x, y, z, yoffh, upperLegLength, lowerLegLength)
return [gamma, alfa, beta]
def RotYawr(theta):
'''
仅在机器人框架和世界框架之间的偏航旋转矩阵
计算:[cos(t),-sin(t),0,][sin(t),cos((t)),0][0,0,1]
'''
Rhor = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0,... | Python | 1 |
time_since(&self, other: &DATE) -> Option<DATE> {
//DATA
// /*
let diff = self.calc_days()as i32 - other.calc_days()as i32;
if diff < 0 {
return None;
} else {
return Some(DATE::new_from_days(diff as u32));
}
}
/**
* formats the dat... | Rust | 0 |
t.len() <= 64 {
cache.put(text, total_size);
}
total_size
}
/// Get the cell size of a character
pub fn get_character_cell_size(char: char) -> usize {
if char.is_ascii() {
1
} else {
get_codepoint_cell_size(char as u32)
}
}
/// Get the cell size of a character
fn get_codepo... | Rust | 0 |
false
}
}
<filename>src/lib.rs
// This is to use executable files in bin/
// Should refactor the app to use this more?
extern crate chrono;
extern crate rusqlite;
#[macro_use]
extern crate lazy_static;
use std::io::stdin;
pub mod models;
pub mod security;
pub mod db;
pub mod utils;
pub fn from_stdin... | Rust | 0 |
ndpoint/")
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert len(data["results"]) == 3
@pytest.mark.integration
def test_detail_endpoint(self, api_client):
"""Тест детального просмотра"""
obj = YourModelFactory()
response = api_cli... | Python | 1 |
}
}
/// Mark the image as in use by the given frame.
pub fn set_image_to_in_flight_frame(&self, image_index: usize, current_frame_num: usize) {
if current_frame_num >= MAX_FRAMES_IN_FLIGHT || image_index >= self.image_to_frame_fence.len() {
panic!(
"Invalid input! image_index: {} current_fra... | Rust | 0 |
# Close clips to free memory
final_clip.close()
bg_clip.close()
for clip in valid_clips:
if hasattr(clip, 'close'):
clip.close()
except Exception as e:
print(f"❌ Video creation failed: {e}")
print("Attempting simpler video creation...")... | Python | 1 |
the cardinal direction that this point/vector points towards the most.
///
/// The values of coordinates is assumed to grow south-east, ie. x grows towards east and y grows towards south.
///
/// If the length is 0, returns [`CardDir::North`].
pub fn cardinal(&self) -> CardDir
where
T: ... | Rust | 0 |
discussions/{discussion_number}/reactions` endpoint.
*
* As opposed to `list_for_team_discussion_legacy`, this function returns all the pages of the request at once.
*
* **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your exis... | Rust | 0 |
r
pub fn new(string: &'a str, next: RawObject) -> RawObject {
let s = StringObject {
obj: Object::new(ObjectType::String, next),
chars: ObjectValue::Str(string),
};
Box::into_raw(Box::new(s)) as RawObject
}
/// Conserveatly copies the string from the pointer... | Rust | 0 |
}
FieldValue::Memo(val) => processor.property(i, name, &ColumnValue::String(val))?,
FieldValue::Character(None)
| FieldValue::Numeric(None)
| FieldValue::Logical(None)
| FieldValue::Date(None)
| FieldValue::Float(None... | Rust | 0 |
DataPoint::new(NaiveDateTime::from_timestamp(60 * 2 as i64,0), 1.0),
TimeSeriesDataPoint::new(NaiveDateTime::from_timestamp(60 * 3 as i64,0), 1.0),
TimeSeriesDataPoint::new(NaiveDateTime::from_timestamp(60 * 4 as i64,0), 1.0),
];
let tsexp = TimeSeries::from_tsdatapoints(data).un... | Rust | 0 |
e1, resource2)
return __resource1 + '重命名为' + __resource2 + '成功。'
except:
return __resource1 + '重命名为' + __resource2 + '失败。'
def copyFile(self, resource1, resource2):
try:
__str = str(resource1).split('/')
__resource1 = __str[len(__str)-1:len(__str)][0]
... | Python | 1 |
for status in ['pending', 'processing', 'sent', 'failed']:
count = conn.execute('''
SELECT COUNT(*) FROM notification_queue
WHERE status = ?
''', (status,)).fetchone()[0]
stats[status] = count
# Count read... | Python | 1 |
# SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=missing-module-docstring,disable=missing-class-docstring,invalid-name
from time import sleep
url = "http://localhost:11111/"
def test_index(browser):
# Visit URL
browser.visit(url)
assert browser.is_text_present('SearXNG')
def test_404(bro... | Python | 1 |
from pathlib import Path
import numpy as np
import torch
import seaborn as sns
import matplotlib.pyplot as plt
from utils import get_imagenet_dataset, TARGET_CLASSES, TARGET_CLASS_NAMES_H
from model import get_model
device = "cuda"
def main():
outdir = Path("output/predictions")
outdir.mkdir(exist_ok=True... | Python | 1 |
(addr, action)).await.is_ok())
}
}
async fn generate_event(&mut self, event: i32) {
assert!(self.event_tx.send(event).await.is_ok())
}
fn drop_action_tx(&mut self) {
self.action_tx = None
}
}
impl UplinkSpawnerOutputs {
async fn take_router_events(&mut self, n: usize) ... | Rust | 0 |
price as u64), normed.expo),
);
succeeds(
pc(i64::MAX, 1, 0),
pc(i64::MAX, 1, 0),
pc(normed.price * normed.price, 0, normed.expo * 2),
);
succeeds(
pc(i64::MAX, 1, 0),
pc(1, 1, 0),
pc(normed.price, normed.price as u... | Rust | 0 |
&mut statfs_t) -> Result<(), Errno> {
let fd = fd as usize;
let buf_ptr = buf as *mut statfs_t as usize;
syscall2(SYS_FSTATFS, fd, buf_ptr).map(drop)
}
/// Get filesystem statistics.
pub fn fstatfs64(fd: i32, buf: &mut statfs64_t) -> Result<(), Errno> {
let fd = fd as usize;
let buf_ptr = buf as *... | Rust | 0 |
pub key2: u64,
// third 128 bit block
pub network_info: u32,
pub payload_info: u8, // 3 bits for number of waste bytes + 5 bits typ
pub origin_4ms: u8,
pub hop1_4ms: u8,
pub hop2_4ms: u8,
pub origin_id: u8,
pub hop1_id: u8,
pub hop2_id: u8,
pub destination_id: u8,
pub crc_payload: u16,
pub pad1: u16,
}
p... | Rust | 0 |
_bits__POLL_STATE_CANCELLED: _poll_states_bits = 4;
pub const _poll_states_bits__POLL_NUM_STATES: _poll_states_bits = 5;
pub type _poll_states_bits = u32;
pub const k_poll_modes_K_POLL_MODE_NOTIFY_ONLY: k_poll_modes = 0;
pub const k_poll_modes_K_POLL_NUM_MODES: k_poll_modes = 1;
pub type k_poll_modes = u32;
#[repr(C)]
... | Rust | 0 |
"),
str_to_bytes(" ^^"),
str_to_bytes(" ^^;;"),
str_to_bytes(" (ˆ ﻌ ˆ)♡"),
str_to_bytes(" ^•ﻌ•^"),
str_to_bytes(" /(^•ω•^)"),
str_to_bytes(" (✿oωo)"),
];
const fn bytes_len(b: &[u8]) -> usize {
let mut len = 0;
while len < b.len() && b[len] != 0 {
len += 1;
}
len
}
co... | Rust | 0 |
truct WallCons {
/// ID del espacio (en formato UUID)
pub id: String,
/// Nombre
pub name: String,
/// Grupo al que pertenece (biblioteca)
pub group: String,
/// Grosor del elemento (m) [0.0-]
pub thickness: f32,
/// Resistencia térmica total sin resistencias superficiales (resistenc... | Rust | 0 |
//! for (key, value) in queries.iter() {
//! println!("key: {:?}, val: {:?}", key, value);
//! }
//!
//! // iterate over all keys and the key's vector.
//! for (key, values) in queries.iter() {
//! println!("key: {:?}, values: {:?}", key, values);
//! }
//!
//! // the different methods for getting value(s) fro... | Rust | 0 |
gleY)
angleX.Deg = build_ele.EndAngleX.value
angleY.Deg = build_ele.EndAngleY.value
braceProps.SetAnglesAtEnd(angleX, angleY)
brace = AllplanArchElements.StructuralBraceElement(braceProps)
model_elem_list = [brace]
except Exception as ex:
msg_te... | Python | 1 |
}
pub fn opt3(self, opt3: bool) -> Self {
let mut new = self;
new.opt3 = Some(opt3);
new
}
pub fn build(self) -> MyFuncArgs<'a> {
MyFuncArgs {
req1: self.req1,
req2: self.req2,
opt1: match self.opt1 {
Some(opt1) => opt1,
None => OPT1_DEFAULT_VALUE,
},
... | Rust | 0 |
#!/usr/bin/python3
<<<<<<< HEAD
"""
Test .get() and .count() methods
=======
""" Test .get() and .count() methods
>>>>>>> bfcb10619fc065dc0acff513eb87a4eb63a3ac76
"""
from models import storage
from models.state import State
print("All objects: {}".format(storage.count()))
print("State objects: {}".format(storage.cou... | Python | 1 |
so that it can be included in a larger document.
///
/// If a rectangle is provided, translate and scale the output to fit it.
pub fn dump_into_svg(atlas: &AtlasAllocator, rect: Option<&Rectangle>, output: &mut dyn std::io::Write) -> std::io::Result<()> {
use svg_fmt::*;
let (sx, sy, tx, ty) = if let Some(rec... | Rust | 0 |
"<PASSWORD>"
}))
}
Err(AuthenticationError::MissingPermissions(msg)) => {
eprintln!("Missing permissions: {}", msg);
JsonResponse::BadRequest("missing_permissions".into())
}
Err(AuthenticationError::UnknownFailure(msg)) => {
eprintln!("Unkn... | Rust | 0 |
buffer = [0; 64];
match xkb_keysym_to_utf8(self.0, buffer.as_mut_ptr(), buffer.len() as size_t) {
-1 => unreachable!(),
0 => "".into(),
_ => CStr::from_ptr(buffer.as_ptr()).to_str().unwrap().into(),
}
}
}
#[inline]
pub fn utf32(&self) -> u32 {
unsafe {
xkb_keysym_to_utf32(self.0)
}... | Rust | 0 |
le_idx]]
if lifecycle_column[1] == "None":
continue
lifecycle_row = create_row(
lifecycle_column, split_percentages=split_percentages)
m = lifecycle_row
self.logger.info(m)
summary_output = summary_output + m + "\n"
... | Python | 1 |
dma_channel.set_count(count);
dma_channel.set_ctrl_and_trigger(|w| {
w.bswap().set_bit();
w.treq_sel().permanent();
w.chain_to().bits(channel as u8);
w.incr_write().set_bit();
w.incr_read().set_bit();
w.data_size().bits(wordsize(elem_size) as u8);
w.en().s... | Rust | 0 |
8536),
(r"textures\tx_a_leather_boot.dds", 0x5809_3C3C, 0xD8B8_A8FD),
(r"textures\tx_c_la_shirtcom02.dds", 0x5809_3C3E, 0xBBDE_F2C7),
(r"textures\tx_ghostward_tunic.dds", 0x580A_0B3A, 0xADF5_9620),
(r"textures\tx_ghoul_heart_01.dds", 0x580A_0B3A, 0xC976_67E9),
(r"textures\tx_wood_blackwood.dds"... | Rust | 0 |
slab.vacant_entry().key();
assert_eq!(key, slab.vacant_entry().key());
}
#[test]
#[should_panic]
fn invalid_get_panics() {
let slab = SuperSlab::<usize>::with_capacity(1);
slab[0];
}
#[test]
#[should_panic]
fn double_remove_panics() {
let mut slab = SuperSlab::<usize>::with_capacity(1);
let key =... | Rust | 0 |
# Copyright 2016–2021 Julien Danjou
# Copyright 2016 Joshua Harlow
# Copyright 2013-2014 Ray Holder
#
# 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-... | Python | 1 |
to_visit.append(new_state)
if return_elements:
return feasible_elements
log = log_instance.EventLog()
for elements in feasible_elements:
log_trace = log_instance.Trace()
log_trace.attributes[case_id_key] = str(len(log))
activities = [x.label for x in elements if type(x) is... | Python | 1 |
import matplotlib.pyplot as plt
from interweave import is_interweaving
def test_runtime_complexity():
x = "101"
y = "0"
input_sizes = [10, 20, 50, 100, 200, 500, 1000]
comparisons_count = []
for size in input_sizes:
s = "1010" * (size // 4) # Generate input string s with the required siz... | Python | 1 |
}
}
}
}
impl Opener for TokioQueue {
#[inline]
fn open(req: &IfReq) -> Result<Self> {
Self::open(req)
}
}
pub mod database;
pub mod domain_events;
pub mod helpers;
pub mod mailers;
pub mod models;
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is ... | Rust | 0 |
}
Best training accuracy: 0.8141470180305131
Test set accuracy score for best params: 0.8222940226171244
--------------------------------------------------------------
----------------------------------------------------------
Estimation grid_AdaBoostClassifier_PCA
Best params: {'clf__n_estimators': 22}
Best training a... | Python | 1 |
from pathlib import Path
from pytest import fixture
from pytest_pyodide.server import spawn_web_server
from pytest_pyodide import runner
import logging
TEST_PATH = Path(__file__).parents[1].resolve()
class BaseRunner(runner._BrowserBaseRunner):
def __init__(
self,
*args,
test_dir,
... | Python | 1 |
# ДЗ 1
# Генерация случайных данных и нахождение корней квадратного уравнения
# Создайте функцию generate_csv_file(file_name, rows), которая будет генерировать по три случайны числа в каждой строке, от 100-1000 строк,
# и записывать их в CSV-файл.
# Функция принимает два аргумента:
# file_name (строка) - имя файла, в... | Python | 1 |
source_mac = fcntl.ioctl(
na_socket.fileno(), SIOCGIFHWADDR, struct.pack(
'256s', bytes(interface, 'utf-8')))[18:24]
# Get the byte representation of the source IP address
source_ip_bytes = socket.inet_pton(socket.AF_INET6, ip_address)
icmpv6_na_msg_prefix = [
struct.pack('... | Python | 1 |
ination is read-only"):
codes[4] = 1
# But even after getting the codes, the original array should still be
# writeable!
c[4] = "a"
exp = np.array([0, 1, 2, 0, 0], dtype="int8")
tm.assert_numpy_array_equal(c.codes, exp)
c._codes[4] = 2
exp = np.array(... | Python | 1 |
();
let btfptr = unsafe { btf__parse_elf(cvmlinux_path.as_ptr(), ptr::null_mut()) };
if (btfptr as isize) < 0 {
return Err(TypeGenError::VmlinuxParsingError);
}
Ok(VmlinuxBtfDump {
allowlist: None,
btfptr,
})
}
/// Parse BTF data from... | Rust | 0 |
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::Mutex;
use crate::validators;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Game {
pub id: u64,
pub title: String,
#[serde(with = "validators::validate_game_rating")]
p... | Rust | 0 |
compact_support is not None:
point_tree = KDTree(X2)
# print(compact_support)
ind_lists = point_tree.query_ball_point(X1,compact_support)
# inds is a list of lists. We need to concatenate it into one list
# I should contain the indices of the points in X2 that are within compact... | Python | 1 |
[0u8; 64];
signature[0..64].copy_from_slice(&decoded_signature[0..64]);
multi_signature = MultiSignature::Ed25519Signature(signature);
} else if multi_signature_str.starts_with("ecdsa") {
let signature_str = multi_signature_str.strip_prefix("ecdsa").unwrap();
let decoded_signature = hex::d... | Rust | 0 |
8_PD, scc_8_pd),
op_entry!(MASK_OUT_Y, OP_SCC_8_PI, scc_8_pi),
op_entry!(MASK_OUT_Y, OP_SCS_8_AI, scs_8_ai),
op_entry!(MASK_EXACT, OP_SCS_8_AL, scs_8_al),
op_entry!(MASK_EXACT, OP_SCS_8_AW, scs_8_aw),
op_entry!(MASK_OUT_Y, OP_SCS_8_DN, scs_8_dn),
op_entry!(MASK_OUT_Y, OP_... | Rust | 0 |
pex(&ops)?;
assert_float_eq_f64(fex.eval(vars)?, eval(&dex, vars)?);
Ok(())
}
test("{x}+2.0*{y}", &[1.0, 0.5])?;
test("({x}+2.0)*{y}", &[1.0, 0.5])?;
test("({x}+2.0)*(2^{y})", &[1.0, 0.5])?;
test("(1+{x}+2.0)*(2-2^{y})", &[1.0, 0.5])?;
test("(1+{x}+2.0)*2", &[1.0])?;
... | Rust | 0 |
Form, FromRequest, Request, FlashMessage};
use rocket::Outcome::Success;
use rocket::response::{Flash, Redirect, NamedFile};
use rocket_contrib::Template;
use rocket::http::{Cookie, Cookies};
use time::get_time;
use std::path::{Path, PathBuf};
use std::io;
use rand::Rng;
lazy_static! {
pub static ref CHARACTERS... | Rust | 0 |
SubCommand::Serve(o) => {
serve(o);
}
SubCommand::Prove(o) => {
prove(o);
}
SubCommand::Verify(o) => {
verify(o);
}
SubCommand::GenerateVerifier(o) => {
generate_verifier(o);
}
SubCommand::ExportVerificat... | Rust | 0 |
_PREFIX,
PARITY_CLIENT_SEMVER,
PARITY_CLIENT_OS,
);
let client_version = ClientVersion::from(client_version_string.as_str());
let parity_unknown = ClientVersion::ParityUnknownFormat(client_version_string.to_string());
assert_eq!(client_version, parity_unknown);
}
#[test]
pub fn client_version_when... | Rust | 0 |
,
},
]),
name: "sample".to_owned(),
piece_length: 2,
pieces: vec![vec![1, 2], vec![3, 4]],
extra_fields: None,
extra_info_fields: None,
};
assert_eq!(
torrent.to_string(),
"sample.torrent\n\
... | Rust | 0 |
│ └ Breaks of ($count, $label)
// └ "Flags": ($bk) ($bv) ($bx). Whether the innermost loop breaks, breakvals or breakval and unboxes
// Specify the usable type for $bv and $bx
( @boxed ( ($($bk:tt)?) ($($bv:ty)?) ($($bx:ty)?) ) // Flags
( $( ($c:expr, $l:lifetime) )... | Rust | 0 |
00, 0xe5, 0x83, 0xc3,
])
.decompress()
.unwrap()
}
fn const_s() -> c2_Element {
// python -c "import binascii, spake2; b=binascii.hexlify(spake2.ParamsEd25519.S.to_bytes()); print(', '.join(['0x'+b[i:i+2] for i in range(0,len(b),2)]))"
// 6f00dae87c1be1a73b5922ef431cd8f5... | Rust | 0 |
import streamlit as st
import sqlite3
from passlib.hash import pbkdf2_sha256
# --- DATABASE FUNCTIONS ---
def get_db_connection():
return sqlite3.connect('recruitment.db')
def create_user(username, password, full_name, role):
conn = get_db_connection()
cursor = conn.cursor()
password_hash = pbkdf2_sha... | Python | 1 |
# Generated by Django 4.2.16 on 2025-08-27 03:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("products", "0007_productimage"),
]
operations = [
migrations.AlterField(
model_name="brand",
name="slug",
... | Python | 1 |
/! .broadcaster_id("1234")
//! .build();
//! ```
//!
//! ## Response: [ScheduledBroadcasts]
//!
//! Send the request to receive the response with [`HelixClient::req_get()`](helix::HelixClient::req_get).
//!
//! ```rust, no_run
//! use twitch_api2::helix::{self, schedule::get_channel_stream_schedule};
//! # use ... | Rust | 0 |
rgb_8_should_be_palette_2() {
test_it_converts(
"tests/files/rgb_8_should_be_palette_2.png",
None,
ColorType::RGB,
BitDepth::Eight,
ColorType::Indexed,
BitDepth::Two,
);
}
#[test]
fn rgb_16_should_be_palette_1() {
test_it_converts(
"tests/files/rgb_1... | Rust | 0 |
mGenerator<'a, 'ctx>,
cache: &cache::Cache,
) -> Option<inkwell::values::BasicValueEnum<'ctx>> {
let llvm_value = generator
.lower_with_access_rules(self.value.as_ref(), cache)
.unwrap();
// NOTE: In the case that our target is a let-statement (through
// a reference), memoization or retr... | Rust | 0 |
) -> Result<String, Error> {
let query_string = match &self.query {
// If query string has already been built, return it:
Some(query_string) => query_string,
// If it hasn't been built, build it:
None => self.validate()?.build()?.query.as_ref().unwrap(),
}... | Rust | 0 |
v.map(date_from_row)
}
}
impl From<ResultValue> for Option<SqlDateTime> {
fn from(v: ResultValue) -> Option<SqlDateTime> {
v.map(datetime_from_row)
}
}
impl ValueProjector<SqlDate> for SqlDate {
fn project_value(&self, projection: &mut ParamValue) {
projection.project(self, |data... | Rust | 0 |
, **kwargs: Any
) -> ComponentFactory | ComponentAllAngleFactory:
return get_active_pdk().get_cell(cell, **kwargs)
def get_cross_section(cross_section: CrossSectionSpec, **kwargs: Any) -> CrossSection:
return get_active_pdk().get_cross_section(cross_section, **kwargs)
def get_layer(layer: LayerSpec | kf.kdb... | Python | 1 |
();
out_dir.push("schemas");
out_dir.push(format!("{}_schema", option_env!("CARGO_PKG_NAME").unwrap()));
create_dir_all(&out_dir).unwrap();
remove_schemas(&out_dir).unwrap();
export_schema(&schema_for!(InitMsg), &out_dir);
export_schema(&schema_for!(HandleMsg), &out_dir);
export_schema(&sch... | Rust | 0 |
CK_SLOT_ID) -> Slot {
Slot { slot_id }
}
/// Underlying ID used for a slot
pub fn id(&self) -> u64 {
self.slot_id as u64
}
}
impl TryFrom<u64> for Slot {
type Error = Error;
fn try_from(slot_id: u64) -> Result<Self> {
Ok(Self {
slot_id: slot_id.try_into()?... | Rust | 0 |
#[test]
fn test_profile_longer_than_min_runs_gt1() {
let min_runs = 7;
let mut cnt = 0;
let (_, nbr_runs) = profile_longer_than(
|| {
cnt += 1;
},
0.0,
min_runs,
);
assert_eq!(nbr_runs, min_runs);
asse... | Rust | 0 |
import sys
import os
import flask
import yaml
app = flask.Flask(__name__)
@app.route("/")
def index():
version = flask.request.args.get("urllib_version")
url = flask.request.args.get("url")
return fetch_website(version, url)
CONFIG = {"API_KEY": "771df488714111d39138eb60df756e6b"}
class Person... | Python | 1 |
assert!(bus.read(0x15, &mut values));
assert_eq!(values, [5, 6, 7, 8]);
assert!(bus.write(0x15, &values));
}
#[test]
fn bus_read_write_full_addr_values() {
let bus = Bus::new();
let dummy = Arc::new(Mutex::new(ConstantDevice {
uses_full_addr: true,
... | Rust | 0 |
𪑱', "wū,wò"),
('𪑳', "zhěn"),
('𪑶', "róu"),
('𪑷', "wài"),
('𪑸', "mì,yān"),
('𪑹', "jiè"),
('𪑻', "hóu"),
('𪑽', "zhài"),
('𪑾', "rǔ"),
('𪑿', "zī"),
('𪒀', "pán"),
('𪒂', "mò"),
('𪒄', "mì"),
('𪒆', "qī"),
('𪒇', "mò"),
('𪒊', "zhī"),
('𪒋', "bān,pán")... | Rust | 0 |
N: ComplexField, D: DimSub<U1>>
where
DefaultAllocator: Allocator<N, D, D> + Allocator<N, DimDiff<D, U1>>,
{
hess: MatrixN<N, D>,
subdiag: VectorN<N, DimDiff<D, U1>>,
}
impl<N: ComplexField, D: DimSub<U1>> Copy for Hessenberg<N, D>
where
DefaultAllocator: Allocator<N, D, D> + Allocator<N, DimDiff<D, U1... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg') # 或者使用 'Agg' 后端
# 参数设置
m = 60.0 # 物体质量 (kg)
g = 9.81 # 重力加速度 (m/s^2)
omega = 2 * np.pi # 角频率 (rad/s)
v0 = 0.5 # 初始滑动速度 (m/s)
H0 = 1e9 # 初始硬度 (Pa)
A0 = 0.02 # 初始接触面积 (m²)
alpha = 0.1 # 温度对磨损系数的影响系数
beta = 0.05 # 湿度对磨损系... | Python | 1 |
{
return Ok(((0, 0), (0, 0)));
}
return Ok(((min_x, min_y), (max_x, max_y)));
}
fn draw<E, DrawFunc: FnMut(i32, i32, f32) -> Result<(), E>>(
&self,
(x, y): (i32, i32),
size: f64,
text: &str,
mut draw: DrawFunc,
) -> Result<Result<(), E>, ... | Rust | 0 |
I:[10.1145/358407.358414](https://doi.acm.org/10.1145/358407.358414)
#[derive(Clone, Copy, Debug)]
pub struct Gamma<N> {
repr: GammaRepr<N>,
}
/// Error type returned from `Gamma::new`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// `shape <= 0` or `nan`.
ShapeTooSmall,
/// `scale <=... | Rust | 0 |
a = original_range_slider.scale_var1.get()
b = original_range_slider.scale_var2.get()
c = target_range_slider.scale_var1.get()
d = target_range_slider.scale_var2.get()
# 转换为灰度图
gray_img = cv2.cvtColor(wait_handle, cv2.COLOR_RGB2GRAY)
# 应用分段线性变换
transforme... | Python | 1 |
compute query features
feat_1 = self.encoder(im_1, bboxs=bboxs1) # queries: NxC
proj_1 = self.projector(feat_1)
pred_1 = self.predictor(proj_1)
pred_1 = F.normalize(pred_1, dim=1)
feat_2 = self.encoder(im_2, bboxs=bboxs2)
proj_2 = self.projector(feat_2)
pred_2 ... | Python | 1 |
"Forest");
PLAIN = (Plain, 118, "Plain");
TOWN = (Town, 226, "Town");
TOP = (Top, 102, "Top of Mountain");
ALPINE = (Highland, 58, "Highland");
DEEPSEA = (DeepSea, 63, "Deep Sea");
PATH = (Path, 193, "Path");
}
#[cfg(test)]
mod tests {
use super::*;
use ... | Rust | 0 |
)
else:
print("save neumann.npy")
np.save("neumann.npy",times)
else:
nproc = min(nruns, 8)
print('using {} processes'.format(nproc))
jobs = [(n, npeds, box, sff, shuffle, reverse, drawP, drawD_avg or drawD)
for n in range(nruns)]
with... | Python | 1 |
r stock_code in list(self._price_history.keys()):
self._price_history[stock_code] = [
item for item in self._price_history[stock_code]
if item['timestamp'] > cutoff_time
]
if not self._price_history[stock_code]:
del self._p... | Python | 1 |
ROIWorkload {
fn contig(&self) -> &str {
self.bin.contig()
}
fn range(&self) -> Range<Position> {
self.bin.range()
}
}
impl ROIWorkload {
pub fn new(bin: Interval, rois: Vec<ROI>) -> Self {
debug_assert!(rois.iter().all(|x| bin.contig() == x.contig()
&& bin.rang... | Rust | 0 |
import speech_recognition as sr
import pyttsx4, random, pygame, time
from gpt4all import GPT4All
# 定义语音机器人函数
class Jarvis():
def __init__(self, audiofile_path) -> None:
self.recognizer = sr.Recognizer()
self.recognizer.energy_threshold = 4000
self.recognizer.dynamic_energy_threshold = True... | Python | 1 |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
from detectron2.modeling import PROPOSAL_GENERATOR_REGISTRY
from detectron2.modeling.proposal_generator.rpn import RPN
from detectron2.structures import ImageList
@PROPOSAL_GENERATOR_REGISTRY.register()
class TridentRPN(RPN):
"""
Trident RPN sub... | Python | 1 |
"""
Copyright (C) 2020 Giovanni - iGio90 - Rocca
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 pr... | Python | 1 |
rde(default = "default_n306_balrog_nurse")]
pub n306_balrog_nurse: SafeNPCRect<4>,
#[serde(default = "default_n307_santa_caged")]
pub n307_santa_caged: SafeNPCRect<4>,
#[serde(default = "default_n308_stumpy")]
pub n308_stumpy: SafeNPCRect<4>,
#[serde(default = "default_n309_bute")]
pub n3... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
from mmcv.cnn.bricks.transformer import BaseTransformerLayer
from mmcv.runner import BaseModule, ModuleList
from mmocr.models.builder import ENCODERS
from mmocr.models.common.modules import PositionalEncoding
@ENCODERS.register_module()
class TransformerEn... | Python | 1 |
import causaldag as cd
from line_profiler import LineProfiler
from tqdm import tqdm
nnodes = 500
ngraphs = 100
dags = cd.rand.directed_erdos(nnodes, 40/(nnodes-1), ngraphs)
cpdags1 = [dag.cpdag_new(new=True) for dag in dags]
arcs_edges = [(cpdag.arcs, cpdag.edges) for cpdag in cpdags1]
print('add consecutively')
pdag... | Python | 1 |
7227DBC2C4F028628CE96E0A3777F97C07BBC84!";
remarks = vec![
Remark::with_range(RemarkType::Pseudonymized, "@creditcard:hash", (15, 55)),
];
);
}
#[test]
fn test_userpath() {
assert_freeform_rule!(
rule = "@userpath";
input = "C:... | Rust | 0 |
scribe: MI_ProviderFT_Subscribe,
pub Unsubscribe: MI_ProviderFT_Unsubscribe,
pub Invoke: MI_ProviderFT_Invoke,
}
impl ::core::marker::Copy for MI_ProviderFT {}
impl ::core::clone::Clone for MI_ProviderFT {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: 'Win32_System_Wmi'*"]
pub... | Rust | 0 |
egy[analyzer_msgs.ExecutionResultInner] = st.one_of(
execution_hits(),
execution_misses(),
)
) -> st.SearchStrategy[analyzer_msgs.ExecutionResult]:
return st.builds(analyzer_msgs.ExecutionResult, inner=inner)
def run_analyzer_responses(
execution_result: st.SearchStrategy[
analyzer... | Python | 1 |
def test_training_with_judge(self, config_name):
with tempfile.TemporaryDirectory() as tmp_dir:
training_args = OnlineDPOConfig(
output_dir=tmp_dir,
per_device_train_batch_size=2,
max_steps=3,
learning_rate=5.0e-7,
ev... | Python | 1 |
2826", "四川省剑阁县"),
("512827", "四川省广元县"),
("512828", "四川省旺苍县"),
("512829", "四川省青川县"),
("512830", "四川省平武县"),
("512831", "四川省北川县"),
("512832", "四川省遂宁县"),
("512833", "四川省三台县"),
("512834", "四川省中江县"),
("512835", "四川省蓬溪县... | Rust | 0 |
import torch
import torch.nn.functional as F
import pathlib
from .model import DGNet
from .option import args
model = None
def load_model(path='', gpu=True, verbose=False):
global model
if model is None:
model = DGNet(args)
if path == '':
path = pathlib.Path(__file__).parent.resolve().__... | Python | 1 |
t_box_candidate = ReceiptBox::create_mint_reservecoin_candidate(
amount_to_mint,
&user_address,
current_height,
transaction_fee,
implementor_fee,
reservecoin_value_in_base,
bank_box,
input_ergs_total,
)?;
//... | Rust | 0 |
import contextlib
from sqladmin import ModelView
from app.exceptions import IncorrectEmailOrPasswordException
from app.models import Keyword, Stopword, User
from app.crud.user import UserManager, get_user_db
from app.core.db import get_async_session
from app.schemas.user import UserCreate
class UserAdmin(ModelView,... | Python | 1 |
Data(
self.get_raw(),
maximum.as_ptr(),
reduced.as_mut_ptr(),
)
}
}
/// Unpack the reduced/generalized coordinates data in `reduced` into `maximum`. Maximum needs to have six slots for every joint.
pub fn unpack_joint_data(&self, reduced: ... | Rust | 0 |
].containing_oneof = _DETECTIONMODEL.oneofs_by_name['model']
_DETECTIONMODEL.oneofs_by_name['model'].fields.append(
_DETECTIONMODEL.fields_by_name['ssd'])
_DETECTIONMODEL.fields_by_name['ssd'].containing_oneof = _DETECTIONMODEL.oneofs_by_name['model']
_DETECTIONMODEL.oneofs_by_name['model'].fields.append(
_DETECTIO... | Python | 1 |
) = \min_{\lambda, \nu} \mathcal{L}(\mathbf{x}, \lambda, \nu)= \frac{1}{2}\mathbf{x}^{\intercal}\mathbf{A}\mathbf{x} + \mathbf{b}^{\intercal}\mathbf{x} + r + \lambda^{\intercal} \mathbf{H}\mathbf{x} + \nu^{\intercal} \mathbf{G}\mathbf{x}$$
#
# Trong đó $\lambda, \nu$ là những véc tơ hệ số có kích thước lần lượt bằng v... | Python | 1 |
# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/visual_script_client/event_platform_blocks.py
import Math
from visual_script.block import Block, Meta, InitParam
from visual_script.dependency import dependencyImporter
from visual_script.misc import ASPECT
from visual_script.slot_t... | Python | 1 |
def solve(rows):
pipes = {}
for row in rows:
a = row[0]
if not a in pipes:
pipes[a] = []
for x in range(2, len(row)):
b = row[x]
if not b in pipes:
pipes[b] = []
pipes[a].append(b)
pipes[b].append(a)
... | Python | 1 |
> for &'r rocket::route::Route {
fn from_request_input(_gen: &mut OpenApiGenerator, _name: String, _required: bool) -> Result {
Ok(RequestHeaderInput::None)
}
}
impl<'r> OpenApiFromRequest<'r> for rocket::http::Method {
fn from_request_input(_gen: &mut OpenApiGenerator, _name: String, _required: bo... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.