text string | label_name string | labels int64 |
|---|---|---|
std::{io::Write, mem::size_of};
type Key = (StateKey, Version);
define_schema!(StateValueIndexSchema, Key, u8, STATE_VALUE_INDEX_CF_NAME);
impl KeyCodec<StateValueIndexSchema> for Key {
fn encode_key(&self) -> Result<Vec<u8>> {
let mut encoded = vec![];
encoded.write_all(&self.0.encode()?)?;
... | Rust | 0 |
"svg" => '\u{f1c5}', //
"swift" => '\u{e755}', //
"tar" => '\u{f410}', //
"taz" => '\u{f410}', //
"tbz" => '\u{f410}', //
"tbz2" => '\u{f410}', //
"tex" => '\u{f034}', //
"tiff" => ... | Rust | 0 |
multiple = 7
etoile = '*'
while multiple < 7*20:
print(multiple)
multiple = multiple+7
if multiple /3:
print(str(multiple) + str(etoile)) | Python | 1 |
ComposedLinearOperator` `AB` implements
`AB @ x == A @ B @ x`. :class:`LinearOperator` `A` and `B` are
stored as attributes of the :class:`ComposedLinearOperator`.
:class:`LinearOperator` `A` and `B` must have compatible shapes
and dtypes: `A.input_shape == B.output_shape` and
`... | Python | 1 |
p cli argument things.
mod args;
/// Rustyline completion & hints & things.
mod editor;
/// Buffer & file, for Agda interaction.
mod file_io;
/// Parse user input as a structural "command".
mod input;
/// Basic info about interaction, like `help`, read line & print things, etc.
mod interact;
/// Implementation of inter... | Rust | 0 |
#2.LPC 编码
#(4)LPC 模型的 Python 实现
#下面使用 librosa 库和 scipy 库来实现 LPC 模型的代码。
#1)确保已经安装了 librosa 库和 scipy 库。这两个库将用于音频处理和 LPC 模型的实现。
pip install librosa scipy
#2)导入所需的库。
import numpy as np
import librosa
from scipy.signal import lfilter
#3)定义 lpc_analysis 函数。
def lpc_analysis(signal, order) :
autocorr = np.correlate(signal,... | Python | 1 |
from Clonify.core.bot import PRO
from Clonify.core.dir import dirr
from Clonify.core.git import git
from Clonify.core.userbot import Userbot
from Clonify.misc import dbb, heroku
from pyrogram import Client
from SafoneAPI import SafoneAPI
from .logging import LOGGER
dirr()
git()
dbb()
heroku()
app = PRO()
api = Safone... | Python | 1 |
html#method.chunks_exact_mut)
///
/// ## Sibling Methods
///
/// - [`.chunks_mut()`] yields any leftover bits at the end as a shorter
/// chunk during iteration.
/// - [`.chunks_exact()`] has the same division logic, but each yielded
/// bit-slice is immutable.
/// - [`.rchunks_exact_mut()`] iterates from t... | Rust | 0 |
central_widget = QWidget()
self.setCentralWidget(central_widget)
# 创建主布局
main_layout = QVBoxLayout(central_widget)
main_layout.setSpacing(15)
main_layout.setContentsMargins(20, 20, 20, 20)
# 创建标题
title_layout = QHBoxLayout()
... | Python | 1 |
rBounceInt(host, iface, vlan, creds)
print "\nInterface %s on host %s has been bounced\n" % (iface, host)
break
elif menuChoice == '6':
command = "clear authentication sessions interface %s" % (iface)
output = sfn.runSSHCommand(command, host, creds)
print "\nAuthentication sessions have been cleared for int... | Python | 1 |
os() as f64 / 1000000000.00);
})
}
fn main() {
fn even_divisible(n: usize, h: usize) -> bool {
for elem in (2..h + 1).rev() {
if n % elem != 0 {
return false;
}
}
true
}
fn smallest_multiple(max: usize) -> usize {
(max..)
... | Rust | 0 |
vte_sys::vte_terminal_set_text_blink_mode(self.as_ref().to_glib_none().0, text_blink_mode.to_glib());
}
}
#[cfg(any(feature = "v0_40", feature = "dox"))]
fn set_word_char_exceptions(&self, exceptions: &str) {
unsafe {
vte_sys::vte_terminal_set_word_char_exceptions(sel... | Rust | 0 |
Segment is callable from segment with fewer privileges.
const CODE_CONFORMING = 1 << 2,
}
}
/// Umbrella Segment Type.
///
/// See Table 3-1, "Code- and Data-Segment Types"
#[repr(u8)]
pub enum Type {
Data(DataAccess),
Code(CodeAccess),
}
impl Type {
pub fn pack(self) -> u8 {
match sel... | Rust | 0 |
anager;
use inverted_index::manager;
use inverted_index::shard;
use inverted_index::manager::StorageEngine;
use rpc::node::{Node, NodeConfiguration};
use rpc::messages::Message;
use rpc::db::MetadataDB;
use web::router;
use web::{Saga, ServiceConfiguration};
use web::handlers::health;
use web::handlers::cluster;
fn ... | Rust | 0 |
= _op.get("relay.op.annotation.simulated_quantize")
cfg = quantize.current_qconfig()
const_params = {}
def visit_func(expr):
"""visitor function for traverse"""
if isinstance(expr, _expr.Call) and expr.op == quantize_op:
_, ndom_scale, nclip_min, nclip_max = expr.args
... | Python | 1 |
fn vcvtad_s64_f64_(a: f64) -> i64;
}
vcvtad_s64_f64_(a)
}
/// Floating-point convert to integer, rounding to nearest with ties to away
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(test, assert_instr(fcvtau))]
#[stable(feature = "neon_intrinsics", since = "1.59.0")]
pub unsafe fn vcvtas_u32_f... | Rust | 0 |
) {
msg!("Error: Conversation address does not match seed derivation");
return Err(ProgramError::InvalidSeeds);
}
// Check rent system account
if !rent::check_id(rent_info.key) {
msg!("Error: Invalid rent system account");
return Err(ProgramError::InvalidAccountData);
}
... | Rust | 0 |
// \x. (x 1, x True) : forall A. (A -> A) -> (Int, Bool)
let h = abs!(pair!(app!(var!(0), Expr::Int(1)), app!(var!(0), Expr::True)));
let h = ann!(
h,
arrow!(
forall!(arrow!(Type::Var(0), Type::Var(0))),
product!(Type::Int, Type::Bool)
)
);
let g = app!(h,... | Rust | 0 |
a, symbol_b);
}
#[test]
fn test_different() {
let symbol_a = intern("StringA");
let symbol_b = intern("StringB");
assert_ne!(symbol_a, symbol_b);
}
#[test]
fn test_case() {
let symbol_a = intern("String");
let symbol_b = intern("string");
assert_... | Rust | 0 |
d}&last_sync_data_time=1597306380&device_type=0&last_deviceid=DA932FFFFE8816E7&data_json={data_json}'
response = requests.post(url, data=data, headers=head).json()
# print(response)
result = f"{user[:4]}****{user[-4:]}: [{now}] 修改步数({step})" + response['message']
print(result)
return result
# 获取时... | Python | 1 |
clicked_plot = None
selected_item = None
dragging = False
import pygame
import time
from pygame.locals import *
import sys
pygame.init() # تفعيل مكتبة pygame للعمل
pygame.mixer.init()
ready_sound = pygame.mixer.Sound("bell.mp3")
# تحميل صور حركة المزارع عند المشي لليمين وتصغيرها إلى حجم (100, 150)
move_right = [
... | Python | 1 |
,],
ct: [0xf3,0xd8,0x8a,0xa0,0xd8,0x20,0x84,0x87,0x78,0x1f,0x48,0xb2,0x77,0xde,0x99,0xdd,]
},
Aes128Test {
key: [0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,],
pt: [0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,0x35,],
... | Rust | 0 |
RESAMPLE_ZERO_FILL_SGIX`]
pub type PixelStoreResampleMode = GLenum;
///
/// * [`GL_PIXEL_SUBSAMPLE_2424_SGIX`]
/// * [`GL_PIXEL_SUBSAMPLE_4242_SGIX`]
/// * [`GL_PIXEL_SUBSAMPLE_4444_SGIX`]
pub type PixelStoreSubsampleRate = GLenum;
///
/// * [`GL_LUMINANCE`]
/// * [`GL_LUMINANCE_ALPHA`]
/// * [`GL_NONE`]
/// * [`GL_P... | Rust | 0 |
#!/usr/bin/python3
"""
Class Square that inherits from Rectangle
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""
Class Square that inherits from Rectangle
"""
def __init__(self, size):
"""
__init__ is used for initialization
Parameters:
... | Python | 1 |
, Some(2)),
S::new(None, None),
S::new(None, Some(2)),
);
test(S::new(None, None), S::new(None, None), S::new(None, None));
}
#[test]
fn test_skip_valid() {
#[derive(Debug, Merge, PartialEq)]
struct S {
field1: Option<usize>,
#[merge(skip)]
field2: Option<usize>,... | Rust | 0 |
u32 = e_wd as u32;
let x_wd: u32 = max_e_wd - e_wd;
// Find i_wd and x_cnt. The values of the indices and exceptions are
// not stored since the required memory is not reasonably bounded.
let mask: $ty = { if e_wd > 0 { !0 >> (ty_wd - e_wd) } else { 0 } };
let mut idx... | Rust | 0 |
#!/usr/bin/env python
import getopt
import sys
from coapthon.forward_proxy.coap import CoAP
__author__ = 'Giacomo Tanganelli'
class CoAPForwardProxy(CoAP):
def __init__(self, host, port, multicast=False, cache=False):
CoAP.__init__(self, (host, port), multicast=multicast, cache=cache)
print("C... | Python | 1 |
#!/usr/bin/env python
##########################################################################
# mycroft-systemd_voice.py
#
# 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.a... | Python | 1 |
DefaultAcceptor::new();
Self { inner, config }
}
}
impl<A> RustlsAcceptor<A> {
/// Overwrite inner acceptor.
pub fn acceptor<Acceptor>(self, acceptor: Acceptor) -> RustlsAcceptor<Acceptor> {
RustlsAcceptor {
inner: acceptor,
config: self.config,
}
}
}
i... | Rust | 0 |
# A CODE TO FIND THE LARGEST COMMON PREFIX IN TWO STRINGS.
str1= input("Enter string 1:", )
str2= input("Enter string 2:", )
str1= str1.casefold()
str2= str2.casefold()
n1= len(str1)
n2= len(str2)
x= min(n1, n2)
for i in range(x):
if str1[i] != str2[i]:
break
if i==0:
print("No Common Prefix")
else... | Python | 1 |
__version__ = "0.0.1"
from ._plane_slider_widget import PlaneSliderWidget
__all__ = ("PlaneSliderWidget",)
| Python | 1 |
DO NOT SHARE IT PUBLICLY", "foobar");
assert_eq!(seedfile_from_str(ex).err().unwrap().message(), "Invalid Seedfile. Invalid line 3.");
let lines = correct.lines().collect::<Vec<&str>>();
assert_eq!(seedfile_from_str([lines[0], "foobar", lines[2]].join("\n")).err().unwrap().message(), "Invalid ... | Rust | 0 |
as deleted.
self.entry.delete(&unprotected());
// Finally, drop the reference to the global. Note that this might be the last
// reference to the `Global`. If so, the global data will be destroyed and all deferred
// functions in its queue will be executed.
... | Rust | 0 |
{}", seek_point.frame_samples);
count += 1;
}
}
pub fn run(args: &Arguments) {
let stream = StreamReader::<File>::from_file(&args.arg_filename)
.expect("Couldn't parse file");
for meta in stream.metadata() {
match meta.data {
metadata::Data::SeekTable(ref s) => print_seek_table(s... | Rust | 0 |
fn ideal_height<E: Element>(&self, element: E, width: u16, max_height: Option<u16>) -> u16 {
element
.ideal_height(
width.saturating_sub(if self.padding { 4 } else { 2 }),
max_height.map(|mh| mh.saturating_sub(2)),
)
.saturating_add(2)
... | Rust | 0 |
[`KernelThunkTable`](struct.KernelThunkTable.html).
pub struct ImportId(u32);
impl ImportId {
/// Returns the imported symbol as an index into the [kernel export table].
///
/// Note that the index might be out of bounds of that table. In that case,
/// an unknown symbol is referenced.
///
///... | Rust | 0 |
为 起跳点。
/// 可以对每一个能作为 起跳点 的格子都尝试跳一次,把 能跳到最远的距离 不断更新。
/// 如果可以一直跳到最后,就成功了。
/// bool canJump(vector<int>& nums)
///{
/// int k = 0;
/// for (int i = 0; i < nums.size(); i++)
/// {
/// if (i > k) return false;
/// k = max(k, i + nums[i]);
/// }
/// return true;
///}
///
///
/// 下面的代码是自己写的,策略3:
pub fn ... | Rust | 0 |
_update(set_order, fetch_order, |v| {
f(Self::_from_inner(v)).map(|v| Self::_to_inner(v))
}) {
Ok(v) => Ok(Self::_from_inner(v)),
Err(v) => Err(Self::_from_inner(v)),
}
}
#[inline]
fn _fetch_opr<F>(&self, order: Ordering, mut f: F) -> FloatType
where
... | Rust | 0 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
import sys
import openpyxl
from PySide6 import QtCore, QtGui, QtWidgets
from VeraGr... | Python | 1 |
Err(primary_serializer_error)
}
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn test_multi_serializer() {
let primary = serializer_with_signer(default_builder("primary").build(), URLSafeEncoding);
let secondary = serializer_with_signer(default_builder("secondary").build(), NullE... | Rust | 0 |
r(StdError::generic_err(
"This mint attempt would increase the total supply above the supported maximum",
));
}
config.set_total_supply(total_supply);
let receipient_account = &deps.api.canonical_address(&address)?;
let mut balances = Balances::from_storage(&mut deps.storage);
... | Rust | 0 |
TMPDIR' environment variable if it is
* set and non-empty and '/tmp' otherwise.
*
* On Windows, returns the value of, in order, the 'TMP', 'TEMP',
* 'USERPROFILE' environment variable if any are set and not the empty
* string. Otherwise, tmpdir returns the path to the Windows directory.
*/
pub fn tmpdir() -> Pat... | Rust | 0 |
: Resource::new(session, ResourceArgs::Renderer(args)) }
}
pub fn id(&self) -> u32 {
self.resource.id
}
pub fn set_camera(&self, camera: &Camera) {
self.resource.enqueue(cmd::set_camera(self.id(), camera.id()))
}
}
pub struct Layer {
resource: Resource,
}
impl Layer {
pub... | Rust | 0 |
.neighbors(u) {
if communities[&v] == c {
k_in += 1.;
}
}
let delta_q = 0.5 * (k_in - k[&u] * sigma_total[&c] / m) / m;
if delta_q > 0. {
*sigma_total.get_mut(&c).unwrap() += k[&u];
*sigma_total.get_m... | Rust | 0 |
&str) {
if &self.total == &self.count {
println!("[Counter-{}]: {}", &self.count, msg);
std::process::exit(1);
}
}
}
<reponame>zetacli/zetac<gh_stars>10-100
use gccjit_sys;
use context::Context;
use std::marker::PhantomData;
use std::fmt;
use std::ffi::CStr;
use std::str;
/... | Rust | 0 |
ublic_key: &PublicKey,
signature: &Signature,
) -> Result<(), CryptoError> {
// NOTE: signature and public/private key lengths are asserted to be correct above.
let res = unsafe {
crypto_sign_verify_detached(
signature.as_ptr(),
message.as_ptr(),
... | Rust | 0 |
os::raw::c_int;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _onexit_table_t {
pub _first: *mut _PVFV,
pub _last: *mut _PVFV,
pub _end: *mut _PVFV,
}
#[test]
fn bindgen_test_layout__onexit_table_t() {
assert_eq!(
::std::mem::size_of::<_onexit_table_t>(),
24usize,
concat!... | Rust | 0 |
) if
k in sam_dict.keys() and except_keys[0] not in k and except_keys[1] not in k and except_keys[2] not in k}
pos_embed = new_state_dict['image_encoder.pos_embed']
token_size = int(image_size // vit_patch_size)
if pos_embed.shape[1] != token_size:
# resize pos embedding, which... | Python | 1 |
pub fn pa_context_set_default_sink(c: *mut pa_context, name: *const c_char, cb: pa_context_success_cb_t, userdata: *mut c_void) -> *mut pa_operation;
pub fn pa_context_set_default_source(c: *mut pa_context, name: *const c_char, cb: pa_context_success_cb_t, userdata: *mut c_void) -> *mut pa_operation;
pub fn... | Rust | 0 |
odi originali parte 1
return w.calculate_boxes()
def solve_2(test_string = None) -> int:
inputs_1 = aoc.get_input(CURRENT_DAY, 1) if not test_string else test_string
splitted = inputs_1.splitlines()
splitted = inputs_1.splitlines()
max_row = len(splitted[0])
max_col = len(splitted[0])
w... | Python | 1 |
B>>;
pub type FastArrayCompressionNx3<N, By, A, B, C> =
FastArrayCompression<N, FastChannelsCompression3<By, A, B, C>>;
pub type FastArrayCompressionNx4<N, By, A, B, C, D> =
FastArrayCompression<N, FastChannelsCompression4<By, A, B, C, D>>;
pub type FastArrayCompressionNx5<N, By, A, B, C, D... | Rust | 0 |
icBool>,
timeout: Duration,
}
impl Client {
/// # Errors
///
/// Will return Err on communcation errors
#[allow(clippy::too_many_lines)]
pub async fn connect(config: &Config) -> Result<Self, Error> {
trace!("config: {:?}", config);
trace!("version: {}", crate::VERSION);
... | Rust | 0 |
# https://codecombat.com/play/level/perimeter-defense
# We need to build guard towers around the village.
# Each peasant can build one tower.
# Show them the place to build.
# These towers are automatic and will attack ALL units outside the town.
# First move along the north border (y=60) from x=40 to x=80 with the st... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2023 Advanced Micro Devices, Inc. All rights reserved.
# SPDX-License-Identifier: MIT
# Author: Daniele Bagni, Xilinx Inc
# date: 28 Apr. 2023
import os
import numpy as np
###############################################################################
# ... | Python | 1 |
import tkinter as tk
from ui import NFTGeneratorApp
import requests
import zipfile
import os
import shutil
import sys
import json
UPDATE_URL = "https://raw.githubusercontent.com/KaueLui/Felony/main/json/version.json" # URL do JSON de versão no GitHub
def check_for_updates():
"""
Verifica no repositório remot... | Python | 1 |
from collections.abc import Sequence
from sentry.models.dashboard import Dashboard
from sentry.models.dashboard_widget import (
DashboardWidget,
DashboardWidgetDisplayTypes,
DashboardWidgetQuery,
DashboardWidgetTypes,
)
from sentry.models.project import Project
def create_widget(
aggregates: Sequ... | Python | 1 |
=> 2,
BendType::BendReleaseBend => 3,
BendType::Prebend => 4,
BendType::PrebendRelease => 5,
BendType::Dip => 6,
BendType::Dive => 7,
BendType::ReleaseUp => 8,
BendType::InvertedDip => 9,
BendType::Ret... | Rust | 0 |
srv, request).await;
assert_eq!(channel_config.event_tcp_socket_enabled, true);
assert_eq!(channel_config.nats_enabled, false);
}
#[actix_rt::test]
async fn should_expose_a_metrics_endpoint() {
// Arrange
let daemon_config = DaemonCommandConfig {
event_tcp_socke... | Rust | 0 |
tenure extracted from appropriate TierConfig
/// upper bound: for first iteration (last-most TierConfig) simply U64::MAX,
/// later recursively updated with previous TierConfig's required_tenure
fn extract_held_tenure(
&self,
tier: &str,
start_from: u64,
end_at: u64,
... | Rust | 0 |
peer_id, peer_err, err
);
if let Err(err) = torrent_process_on_failure
.broker_sender
.clone()
.send(DownloadTorrentEvent::PeerConnectFailed(peer_id))
.await
... | Rust | 0 |
RankTransform::new(&dna_alphabet);
/// assert_eq!(dna_ranks.get(65), 0); // "A"
/// assert_eq!(dna_ranks.get(116), 7); // "t"
/// ```
pub fn get(&self, a: u8) -> u8 {
*self.ranks.get(a as usize).expect("Unexpected character.")
}
/// Transform a given `text` into a vector of rank values.... | Rust | 0 |
import collections
import re
import numpy as np
from guesswhat.statistics.abstract_plotter import *
import pandas as pd
import seaborn as sns
stopwords = ["a", "an", "is", "it", "the", "does", "do", "are", "you", "that",
"they", "doe", "this", "there", "hi", "his", "her", "its", "picture", "can", "he",... | Python | 1 |
from tensorflow.keras.activations import relu, linear
from tensorflow.keras.layers import Dense
import numpy as np
def test_tower(target):
num_outputs = 32
i = 0
assert len(target.layers) == 3, f"Wrong number of layers. Expected 3 but got {len(target.layers)}"
expected = [[Dense, [None, 256], relu],
... | Python | 1 |
ig[0])
self.x = result.x
self.area_ratio = result.area_ratio
self.velocity = result.velocity
self.Mach_number = result.Mach_number
self.p_pitot = result.p_pitot
self.rayleigh_pitot = result.rayleigh_pitot
self.pressure = result.pressure
self.density = resu... | Python | 1 |
# Copyright 2010-2015 MongoDB, Inc.
#
# 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 agreed to in writin... | Python | 1 |
function()
.signature().param().i32().param().i32().param().i32().build()
.build()
.function()
.signature().param().i32().build()
.body()
.with_instructions(elements::Instructions::new(
vec![
elements::Instruction::CallIndirect(1, 0),
elements::Instruction::End
]
)... | Rust | 0 |
crypto_expressions")]
test_function!(
SHA224,
&[lit(ScalarValue::Utf8(Some("tom".to_string())))],
Ok(Some(&[
11u8, 246u8, 203u8, 98u8, 100u8, 156u8, 66u8, 169u8, 174u8, 56u8, 118u8,
171u8, 111u8, 109u8, 146u8, 173u8, 54u8, 203u8, 84u8, 20u8, 22... | Rust | 0 |
from arm.logicnode.arm_nodes import *
class WorldToScreenSpaceNode(ArmLogicTreeNode):
"""Transforms the given world coordinates into screen coordinates,
using the active camera or a selected camera."""
bl_idname = 'LNWorldToScreenSpaceNode'
bl_label = 'World to Screen Space'
arm_section = 'matrix'
... | Python | 1 |
/// here we are.
modem_ctl: Port<u8>,
/// line status register. probably holds information on the current line
/// status.
line_sts: Port<u8>,
/// modem status register. doesn't seem useful for me?
modem_sts: Port<u8>,
// there is also a scratch register.
}
impl SerialPort {
/// new cre... | Rust | 0 |
import logging
import os
from os import getcwd
import hashlib
from fastapi.responses import FileResponse, Response
from fastapi import APIRouter, HTTPException
from starlette import status
from starlette.requests import Request
from app.core import Config
router = APIRouter(prefix="/opa", tags=["opa"])
logger = Config... | Python | 1 |
view into this mutable view.
///
/// Useful for forwarding the view to other functions without moving it.
pub fn subview_mut(&mut self) -> LayerViewMut<'_, T> {
LayerViewMut {
meta: self.meta,
components: self.components,
_guard: None,
}
}
}
//
// Ite... | Rust | 0 |
eq: HttpRequest,
stream: web::Payload,
state: web::Data<AppState>,
) -> Result<HttpResponse> {
let path: PathBuf =
req.match_info()
.query("filename")
.parse()
.map_err(|_| FileSyncError::BadClientData {
cause: "Error parsing request URL".to_string... | Rust | 0 |
set these two values.
let mut x: Option<Bignum> = None;
let mut save: Option<Vec<u8>> = None;
let mut counter = 1;
while counter <= MIN_PWE_ITER || x.is_none() {
let pwd_seed = params.pwd_seed(counter);
// IEEE 802.11-2016 9.4.2.25.3 Table 9-133 specifies SHA-25... | Rust | 0 |
8 = 11;
pub const SSH_FXP_READDIR : u8 = 12;
pub const SSH_FXP_REMOVE : u8 = 13;
pub const SSH_FXP_MKDIR : u8 = 14;
pub const SSH_FXP_RMDIR : u8 = 15;
pub const SSH_FXP_REALPATH : u8 = 16;
pub const SSH_FXP_STAT : u8 = 17;
pub const SSH_FXP_RENAME : u8 = 18;
pub const SSH_FXP_READLINK : u8 = 19;
pub const SSH_FXP_SYMLI... | Rust | 0 |
import re
from collections import Counter
import joblib
import jieba
from tqdm import tqdm
SPACE_NORMALIZER = re.compile(r"\s+")
def load_raw_data(path: str):
print(f"Loading data from {path}...")
raw_data = joblib.load(path)
return raw_data
def save_raw_data(raw_data, path: str):
print(f"Saving ... | Python | 1 |
Color {
r: u8,
g: u8,
b: u8,
a: u8
}
fn color_from_json(json: JsonColor) -> Color {
Color::new(json.a, json.r, json.g, json.b)
}
#[derive(Deserialize)]
struct JsonGradientStop {
position: f32,
color: JsonColor
}
#[derive(Deserialize)]
enum JsonSpread {
Pad,
Reflect,
Repeat
}
... | Rust | 0 |
ype::Int. to_llvmty(context) };
(dbl) => { VariableType::Double. to_llvmty(context) };
(ptr) => { VariableType::Pointer.to_llvmty(context) };
}
macro_rules! define_native_function {
($ret_ty:ident, [ $($param_ty:ident),* ], $name:expr) => {
let mut params_ty = vec![$(p... | Rust | 0 |
import numpy as np
l = 0.25
g = 9.81
def pendulum_dynamics(x, x_dot, theta, theta_dot, u, mc, mp):
dx = [x_dot,
(u + mp * np.sin(theta) * (l * theta_dot ** 2 + g * np.cos(theta))) / (mc + mp * np.sin(theta) ** 2),
theta_dot,
(-u * np.cos(theta) - mp * l * theta_dot ** 2 * np.cos(t... | Python | 1 |
}
/// Tests whether there is any data remaining in the Parser. Generally
/// useful when parsing a `SEQUENCE OF`.
#[inline]
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Reads a single ASN.1 element from the parser. Which type you are reading is determined by
/// ... | Rust | 0 |
import curses
import random
import time
def lazy_cli(stdscr):
curses.curs_set(0) # Hide cursor
current_row = 0
options = [
"Effortless Commanding",
"Instant Excuses Generator",
"It's Not My Job Delegator",
"LazyLink Finder",
"Rapid Report Faker",
"Quit"
... | Python | 1 |
, id: PrototypeId) -> Option<Entity> {
self.by_id.get(&id).copied()
}
pub fn next_id(&mut self) -> PrototypeId {
self.highest_id += 1;
PrototypeId(self.highest_id)
}
pub fn as_sorted_list(&mut self) -> Vec<(PrototypeId, Entity)> {
self.by_id
.iter()
... | Rust | 0 |
oak::grpc;
use prost::Message;
use proto::{
GetPointOfInterestRequest, GetPointOfInterestResponse, TrustedInformationRetrieval,
TrustedInformationRetrievalDispatcher,
};
/// Oak Node that connects to the database proxy Node.
pub struct TrustedInformationRetrievalNode {
database_url: String,
}
/// A gRPC ... | Rust | 0 |
e
def update_invincible(self, delta_time):
"""両方の無敵時間を更新"""
# 通常無敵時間の更新
if self.is_normal_invincible:
self.normal_invincible_time += delta_time
if self.normal_invincible_time >= self.normal_invincible_duration:
self.is_normal_invincible = False
... | Python | 1 |
.packets();
let mut data = Vec::new();
let mut channels = 0;
let mut rate = 0;
let mut bitrate_upper = 0;
let mut bitrate_nominal = 0;
let mut bitrate_lower = 0;
let mut bitrate_window = 0;
for p in packets {
match p {
Ok(packet) => {
channels = packet... | Rust | 0 |
sting_ids = [id[0] for id in existing_ids] # 提取 ID 列表
# 找到第一个空闲的 ID
new_auto_increment = 1
for i in range(1, max(existing_ids) + 2): # 遍历从 1 到最大 ID + 1 的范围
if i not in existing_ids:
new_auto_increment = i
break
# 设置自增点
db.session.execute(text(f"ALTER TABLE pilot A... | Python | 1 |
Lambda {ref pos, ref env, spec, ref code} =>
Proc::Lambda {pos: pos.remap(r), env: env.remap(r), spec, code: code.remap(r)},
Proc::MatchCont(_) => Proc::MatchCont(Arc::new(AtomicBool::new(false))),
Proc::RefineCallback => Proc::RefineCallback,
Proc::ProofThunk(x, m) => Proc::ProofThunk(x.remap... | Rust | 0 |
from tensorflow.keras import backend as K
import tensorflow as tf
from .utils import gather_channels
def binary_focal_loss(gamma=2.0, alpha=0.25, **kwargs):
r"""Implementation of Focal Loss from the paper in binary classification
Formula:
loss = - gt * alpha * ((1 - pr)^gamma) * log(pr) \
... | Python | 1 |
##
# Copyright 2021-2025 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | Python | 1 |
_phantom: std::marker::PhantomData,
rotate,
twiddle1re,
twiddle1im,
twiddle2re,
twiddle2im,
twiddle3re,
twiddle3im,
twiddle4re,
twiddle4im,
twiddle5re,
twiddle5im,
twiddle6re,
... | Rust | 0 |
< 80:
if h < 80:
pad_h = (256 - h) // 2
img = np.pad(img, ((pad_h, 256 - h - pad_h), (0, 0)), mode='constant', constant_values=0)
h = 256
if w < 80:
pad_w = (256 - w) // 2
img = np.pad(im... | Python | 1 |
from typing import Type, Dict, List, Any, Union
import os
from torch import Tensor
from torchvision.datasets import ImageFolder
from torchvision.datasets.utils import download_and_extract_archive
from gallop.datasets.tools.wnid_to_name import wnid_to_name
NoneType = Type[None]
ArgsType = List[Any]
KwargsType = Dict[... | Python | 1 |
ck");
ignored!(ig26, ROOT, "/foo/bar/baz", "./foo/bar/baz");
ignored!(ig27, ROOT, "foo/", "xyz/foo", true);
ignored!(ig28, "./src", "/llvm/", "./src/llvm", true);
ignored!(ig29, ROOT, "node_modules/ ", "node_modules", true);
ignored!(ig30, ROOT, "**/", "foo/bar", true);
ignored!(ig31, ROOT, "pat... | Rust | 0 |
xpected_iter = expected.iter();
for Pixel(coord, _) in line.into_iter() {
match expected_iter.next() {
Some(point) => assert_eq!(coord, Point::from(*point)),
// expected runs out of points before line does
None => unreachable!(),
}
... | Rust | 0 |
[..expected.len() - 1],
);
for i in 0..num_shreds as u64 {
for j in 0..i {
let expected: Vec<u64> = (j..i)
.flat_map(|k| {
let begin = k * gap + 1;
let end = (k + 1) * gap;
begin..end... | Rust | 0 |
#!/usr/bin/env python
# coding=utf-8
# aeneas is a Python/C library and a set of tools
# to automagically synchronize audio and text (aka forced alignment)
#
# Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it)
# Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it)
# Copyright (C) 2015-2017, A... | Python | 1 |
ERPIO0_2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Enable start signal for start logic input PIO0_n: PIO0_11 to PIO0_0 0 = Disabled 1 = Enabled."]
#[inline(always)]
pub fn erpio0_3(&self) -> ERPIO0_3_R {
ERPIO0_3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "B... | Rust | 0 |
handle._add_trans_params(params)
if len(params) > 0:
anchor_params[handle.anchor_name] = params
return anchor_params
def _add_anchors(self, handlers):
"""
Adds multiple anchor-handler associations.
Iterates over a list of handler objects ... | Python | 1 |
map;
mod player;
mod sprite;
mod tile;
mod world;
mod tree;
const SCREEN_HEIGHT: u32 = 800;
const SCREEN_WIDTH: u32 = 1200;
fn clear_canvas(canvas: &mut Canvas<Window>) {
canvas.set_draw_color(Color::RGB(0, 0, 0));
canvas.clear();
}
fn main() {
let sdl_ctx = sdl2::init().unwrap();
let video_subsyste... | Rust | 0 |
from langdetect import detect
from rasa.core.agent import Agent
import asyncio
from googletrans import Translator
async def handle_message(message):
# Load your trained Rasa model
agent = Agent.load('models/20250310-123025-obtuse-lifer.tar.gz')
# Initialize the translator
translator = Translator()... | Python | 1 |
ancel_minus(n2i(0.0, 5.0)),
n2i(0.0, 0.09999999999999964)
);
assert_eq2!(
n2i(1.0, 5.1).cancel_minus(n2i(1.0, 5.0)),
n2i(0.0, 0.09999999999999964)
);
assert_eq2!(
n2i(0.9, 5.1).cancel_minus(n2i(1.0, 5.0)),
n2i(-0.09999999999999998, 0.09999999999999964)
);
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.