text string | label_name string | labels int64 |
|---|---|---|
);
for i in 0..6 {
let mtx = lock_map.get_lock(format!("key_{}", i)).await;
let _r_guard = mtx.read().await;
}
{
let guard = lock_map.data.lock().await;
assert_eq!(guard.len(), 6);
}
tokio::time::sleep(Duration::from_millis(TTL_M... | Rust | 0 |
writer
.write(&encode_u64le(ONLY_SUPPORTED_VERSION)[..])
.await?;
writer
.write(local_blinded_identity.pubkey.as_bytes())
.await?;
writer.write(local_ephemeral.pubkey.as_bytes()).await?;
writer.flush().await?;
// Receive the similar message from the other end (that w... | Rust | 0 |
AMP() WHERE FileID=%d AND SEID=%d;" % (
paramName,
paramValue,
fileID,
seID,
)
return self.db._update(req, conn=connection)
def _setFileParameter(self, fileID, paramName, paramValue, connection=False):
connection = self._getConnection(connecti... | Python | 1 |
get_name().map(|x| format!(" name={}", x))
.unwrap_or("".into()))
}
}
fn write_obj<T, W: Write>(w: &mut W, x: &T) -> io::Result<u32> {
unsafe {
let bytes : *const u8 = mem::transmute(x);
let size = mem::size_of_val(x);
w.write_all(slice::from_raw_parts(bytes, size))?;... | Rust | 0 |
]
for order in pending_orders:
with st.expander(f"{order['ID']} - {order['股票']} - {order['狀態']}"):
col1, col2, col3 = st.columns(3)
with col1:
st.write(f"**類型**: {order['類型']}")
st.write(f"**股票**: {order['股票']}")
with col2:
... | Python | 1 |
player_owned)]
pub type PlayerOwned<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, ID>;
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(100)]
pub fn create_player(origin: OriginFor<T>, name: NAME) -> DispatchResult {
let sender = ensure_signed(origin)?;
let id = Self::create_new_play... | Rust | 0 |
DEC Interrupt Enable Register"]
pub mod qier;
#[doc = "QDEC Interrupt Disable Register\n\nThis register you can [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [qidr](qidr) module"]
pub type QIDR = cra... | Rust | 0 |
HRBuilder<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Debug::fmt(&self.0, f)
}
}
impl<'a> std::ops::Deref for DisplayPlaneProperties2KHRBuilder<'a> {
type Target = DisplayPlaneProperties2KHR;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a>... | Rust | 0 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
().expect("Failed to end main presentation pass");
}
frame.add_command_buffer(cmd_buffer);
let frame = frame.finish();
renderer
.submit(frame)
.or_else(|e| {
if let trekanten::RenderError::NeedsResize(reason) = e {
log::info!("Resize reason: {:?}", reason);
... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
NetWORKS - An extensible device management application
""" | Python | 1 |
rom_elem(Timestamp::minimum())),
);
}
for (index_id, _, _) in dataflow.index_exports.iter() {
self.compute.since_uppers.insert(
*index_id,
(as_of.clone(), Antichain::from_elem(Timestamp::minimum())),
);
... | Rust | 0 |
assert!(module.is_ok());
let module = module.unwrap();
let decls = module.get_decls();
assert_eq!(decls[0].get_type(), decls[1].get_type());
assert_eq!(decls[0].get_type(), Some(BasicType::int()));
assert_eq!(
decls[2].get_type(),
Some(FuncType::new_func_type(None, BasicType::int()))... | Rust | 0 |
# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import sys
import tensorflow as tf
# Create the graph and model
class SampleGraph(tf.Module):
def __init__(self):
super(SampleGraph, self).__init__()
self.var1 = tf.constant([[[[0,0,1,0],[0,0,0,0],[0,2,1,0]],[[0,0,0,0],[... | Python | 1 |
am_bleedout),
pilot_bleedout_bleedout_time: self.pilot_bleedout_bleedout_time.or(other.pilot_bleedout_bleedout_time),
pilot_bleedout_firstaid_time: self.pilot_bleedout_firstaid_time.or(other.pilot_bleedout_firstaid_time),
pilot_bleedout_selfres_time: self.pilot_bleedout_selfres_time.... | Rust | 0 |
export]
macro_rules! contains_none {
( $vec:expr, $x:expr ) => { !$vec.contains($x) };
( $vec:expr, $x1:expr, $( $x2:expr ),+ ) => {
contains_none!($vec, $x1) && contains_none!($vec, $( $x2 ),+)
}
}
#[test]
fn test_contains_none() {
let v = vec![3,4,5];
assert!(contains_none!(v, &1, &2));
... | Rust | 0 |
3C-LTE-MEC-MIB", "hh3cMecTunnelCacheNumber")
)
if mibBuilder.loadTexts:
hh3cMecTunnelCacheRecoverTrap.setStatus(
"current"
)
# Notifications groups
# Agent capabilities
# Module compliance
# Export all MIB objects to the MIB builder
mibBuilder.exportSymbols(
"HH3C-LTE-MEC-MIB",
**{"hh3c... | Python | 1 |
int(round(detection.bbox.size_y))
x = int(round(cx - (w / 2.0)))
y = int(round(cy - (h / 2.0)))
if args.verbose:
print(f'Frame {i + 1}')
print(f' filename: {image_filename}')
print(f' bbox: (x: {x} y: {y} w: {w} h: {h})')
... | Python | 1 |
ill be kept.
score_factors (Tensor): The factors multiplied to scores before
applying NMS
Returns:
tuple: (bboxes, labels), tensors of shape (k, 5) and (k, 1). Labels
are 0-based.
"""
num_classes = multi_scores.size(1)
# exclude background category
if multi_... | Python | 1 |
ce::new(job),
Some(JobKind::UpdateRepo) => UpdateRepoJobInstance::new(job, executor.delta_generator.clone()),
_ => InvalidJobInstance::new(job, JobError::new("Unknown job type")),
}
}
pub trait JobInstance {
fn get_job_id (&self) -> i32;
fn order (&self) -> i32 {
0
}
fn hand... | Rust | 0 |
for result in rdr.records() {
let mut record = result.expect("a CSV record");
record.trim();
records.push(record);
}
records
}#![feature(negative_impls)]
struct MySendable {
t: *mut u8
}
unsafe impl Send for MySendable {}
struct MyNotSendable {
t: *mut u8
}
impl !Send for ... | Rust | 0 |
el == cutscene::Level::Movie {
VIEW_DISTANCE - 2.7
} else {
VIEW_DISTANCE - 0.7
};
let left_vector = Vec2::new(left_angle.cos(), left_angle.sin()).norma... | Rust | 0 |
ap'), ('Poland', 'Poland'), ('Portugal', 'Portugal'), ('ROC', 'ROC'), ('ROK', 'ROK'), ('Singapore', 'Singapore'), ('Turkey', 'Turkey'), ('UCT', 'UCT'), ('US/Alaska', 'US/Alaska'), ('US/Aleutian', 'US/Aleutian'), ('US/Arizona', 'US/Arizona'), ('US/Central', 'US/Central'), ('US/East-Indiana', 'US/East-Indiana'), ('US/Eas... | Python | 1 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.firefox import GeckoDriverManager
import time
import os
############################################... | Python | 1 |
Cell(u16),
IncrementCellAtOffset(u16, u16),
DecrementCell(u16),
IncrementPointer(u16),
DecrementPointer(u16),
While(Vec<OptimizedCommand>),
Output,
Input,
}
pub fn optimize(commands: &[Command]) -> Vec<OptimizedCommand> {
let mut optimized_commands = vec![];
let mut iter = commands... | Rust | 0 |
};
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::convert::From;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::sync::{Arc, RwLock, Weak};
// use std::thread;
struct SelectParams {
m: usize,
lc: usize,
extend_candidates: bool,
keep_pruned_connections: bool,
}
#[... | Rust | 0 |
let mut reader = BufReader::new(keyfile);
rustls::internal::pemfile::pkcs8_private_keys(&mut reader)
.expect("file contains invalid pkcs8 private key (encrypted keys not supported)")
};
// prefer to load pkcs8 keys
if !pkcs8_keys.is_empty() {
pkcs8_keys[0].clone()
} else {
... | Rust | 0 |
min_size = 0
max_size = Ellipsis
if result_res == k:
logging.debug('{} matches source {}, checking size.'.format(result['title'], k))
if result['type'] != 'import' and not (min_size < size < max_size):
logging.debug('Removing... | Python | 1 |
#Dictionary of criteria taken from S-44
EO = {
"AD": "Areas where there is strict minimum underkeel clearance and manoeuvrability criteria.",
"FD": "Cubic features > 0.5 m",
"FS": "200%",
"BC": "200%"
}
SO = {
"AD": "Areas where underkeel clearance is critical.",
"FD": "Cubic... | Python | 1 |
output_lines.append(f" 📝 Content: {content_preview}")
output_lines.append(
f" 📊 Stats: {result.get('word_count', 0)} words, {result.get('links_count', 0)} links, {result.get('images_count', 0)} images"
)
if... | Python | 1 |
ual(1,len(cm1))
self.assertEqual(10,cm1[-1].svolume)
self.assertTrue(cm1.modified)
ticks.append(DAY_FINALIZE_TICK)
cm2 = MINUTE(ticks)
self.assertEqual(id(cm1),id(cm2))
self.assertEqual(2,len(cm2))
self.assertEqual(20,cm1[-1].svolume) #因为直接日结,所以没有svolume
... | Python | 1 |
import math
nimi = ("sssnake")
print(f" nimeni on {nimi}")
sa = math.pi*5**2
print(sa)
print ("\U0001F603\U0001F605\U0001F606\U0001F607 ")
raha = 5
if raha < 5:
print(" Voin ostaa kahvin. ")
| Python | 1 |
"❌ Failed bulk operation: {e}", exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed bulk operation: {str(e)}"
)
@router.get("/insights/{insight_id}/history")
async def get_insight_history(
insight_id: UUID,
request: Requ... | Python | 1 |
")
# Find all image elements
locators = page.locator("//img")
# Create an array of Promises, each corresponding to the loading of an image
promises = await locators.evaluate_all(
"""
elements => elements.map(img => {
if (img.complete) return Promise.resolve();
return new Pr... | Python | 1 |
I>(files: I) -> Vec<Vec<Error>>
where
I: Iterator<Item = &'a str>,
{
let mut files: Vec<_> = files
.map(|contents| {
let lexed = lex::get(contents);
log::debug!("lex: {:?}", lexed.tokens);
let parsed = parse::get(&lexed.tokens);
log::debug!("parse: {:#?}", parsed.root);
let lowered... | Rust | 0 |
# This is DMOJ problem ccc18j2
# https://dmoj.ca/problem/ccc18j2
# Input Specification
# The first line of input contains the integer N ( 1 ≤ N ≤ 100 ) . The second and third lines of input contain N characters each. The second line of input records the information about yesterday's parking spaces, and the third line... | Python | 1 |
def load_language_adapter(self, model_path: str, num_token: int, dim: int,
dim_out: int, tensor_norm: torch.Tensor, mult: int=2, depth: int=5):
device = self._execution_device
self.tensor_norm = tensor_norm.to(device)
self.language_adapter = TranslatorNoLN(num_tok=num_token, dim=dim,
dim_out=dim... | Python | 1 |
word);
m.insert("let", SyntaxKind::LetKeyword);
m.insert("module", SyntaxKind::ModuleKeyword);
m.insert("new", SyntaxKind::NewKeyword);
m.insert("null", SyntaxKind::NullKeyword);
m.insert("number", SyntaxKind::NumberKeyword);
m.insert("package", SyntaxKind::PackageKeyword... | Rust | 0 |
// 8.1 the letter r, zero or more hash marks (that is, the # character), a double quote
// 8.2 then the contents of the string,
// 8.3 terminated by another double quote followed by the same number of hash marks
// 8.4 no escape sequences like \" are recognized
// 8.5 We can always ensure the string... | Rust | 0 |
B" ], "C" ] }),
)
.await?;
let docs = coll.find(query!({ "item.code": { "$lte": 123 } })).await?;
assert_eq!(docs.len(), 3);
assert_eq!(docs[0]["item"]["name"], "ab");
assert_eq!(docs[1]["item"]["name"], "cd");
assert_eq!(docs[2]["item"]["name"], "mn");
Ok(())
}
#[tokio::test]
#[cfg(not(feature ... | Rust | 0 |
MyIterableType>();
sub_module.set_native_fn("new_ts", || Ok(MyIterableType("hello".to_string())));
let mut module = Module::new();
module.set_sub_module("inner", sub_module);
engine.register_static_module("testing", module.into());
let script = r#"
let item = testing::inner::new_ts();
... | Rust | 0 |
return False
else:
logger.info("Сообщение не отправлено (рейтинг не изменился и force_refresh=False)")
self.last_run_status = "skipped"
return True
except Exception as e:
error_message = f"❌ Произошла ошибка при... | Python | 1 |
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.MessageLogger = cms.Service("MessageLogger",
cerr = cms.untracked.PSet(
enable = cms.untracked.bool(False)
),
cout = cms.untracked.PSet(
enable = cms.untracked.bool(True),
threshold = cms.untracked.strin... | Python | 1 |
import numpy as np
from bokeh.events import ButtonClick
from bokeh.io import curdoc
from bokeh.layouts import column, row
from bokeh.models import Button, ColumnDataSource, Div, Slider
from bokeh.plotting import figure
doc = curdoc()
x = np.linspace(0, 2, 1000)
y = 1 - (x-1)**2
source = ColumnDataSource(data=dict(x... | Python | 1 |
;
matches.insert2(capture_key, captured);
Ok(ii)
} else {
let (ii, captured) = optionally_check_if_parsed_is_allowed_capture(
map(valid_capture_characters, String::from),
allowed_captures,
)(i)?;
matches.insert2(capture_key, captured.to_string());
... | Rust | 0 |
pub type UpdateFn<Model> = fn(&App, &mut Model, Update);
/// The user function type for drawing their model to the surface of a single window.
pub type ViewFn<Model> = fn(&App, &Model, Frame) -> Frame;
/// A shorthand version of `ViewFn` for sketches where the user does not need a model.
pub type SketchViewFn = fn(&... | Rust | 0 |
fn check(n: u64, p: u64) {
let (lo, hi) = super::nth_prime_bounds(&n).unwrap();
assert!(
lo <= p && p <= hi,
"fail to satisfy: {} <= {}-th prime = {} <= {}",
lo,
n,
p,
hi
);
... | Rust | 0 |
let blocks_data =
self.rom[blocks_pointer..(blocks_pointer + ((width * height) as usize))].to_vec();
let tiles = self.get_tiles(tileset_graphics_pointer, 16 * 6 * 8 * 8, false);
let map_tiles: Vec<Vec<u8>> = (0..(width * height * 4 * 4))
.map(|i| {
let x... | Rust | 0 |
gForUpdates,
ErrorCheckingForUpdate,
NoUpdateAvailable,
InstallationDeferredByPolicy,
InstallingUpdate,
WaitingForReboot,
InstallationError,
}
/// This is the set of errors that can occur when making a request to Omaha. This is an internal
/// collection of error types.
#[derive(Error, Debug)]... | Rust | 0 |
#[inline]
pub unsafe fn xcb_randr_get_output_property_reply(
&self,
c: *mut xcb_connection_t,
cookie: xcb_randr_get_output_property_cookie_t,
e: *mut *mut xcb_generic_error_t,
) -> *mut xcb_randr_get_output_property_reply_t {
sym!(self, xcb_randr_get_output_property_reply... | Rust | 0 |
of & !0b1111) | (flags as u32))
}
#[inline]
pub fn weekday(&self) -> Weekday {
let Of(of) = *self;
Weekday::from_u32(((of >> 4) + (of & 0b111)) % 7).unwrap()
}
#[inline]
pub fn isoweekdate_raw(&self) -> (u32, Weekday) {
// week ordina... | Rust | 0 |
tr>>,
exit_code: Option<i32>,
) -> Self {
Self::BuildFailed {
command: shell_words::join(command),
exit_code,
}
}
pub(crate) fn filter_expression_parse_error(
all_errors: Vec<FilterExpressionParseErrors>,
) -> Self {
Self::FilterExpression... | Rust | 0 |
.with_arg("--public-configs")
.with_args(env.expected_pub_configs().into_iter())
.run()
.unwrap();
}
#[test]
#[should_panic(expected = "The number of validators does not match the number of validators keys.")]
fn test_more_validators_count() {
let env = ConfigSpec::new_more_validator... | Rust | 0 |
# Copyright 2021 Hakan Kjellerstrand hakank@gmail.com
#
# 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 ... | Python | 1 |
el = prepare_model_for_kbit_training(policy_model)
if resume_from_checkpoint:
policy_model = PeftModel.from_pretrained(policy_model, resume_from_checkpoint, is_trainable=True)
else:
peft_config = LoraConfig(
task_type="CAUSAL_LM",
inference_mode=False,
r=8,
... | Python | 1 |
is_generator() {
// Arrange
assert!(init(CurveType::BLS12_381));
// Act
let curve = Curve::new(&Fr::one(), 1);
// Assert
let result = curve.g1_points[0].get_str(10);
assert_eq!(GEN_G1_STR, result);
}
#[test]
fn curve_new_first_g2_point_is_generator() {
// Arrange
assert!(init(CurveT... | Rust | 0 |
: {}", quantity, adj_quantity); // ""
assert_eq!(adj_quantity, dec!(1.000001));
quantity = dec!(1.00000199999999999999999999999); // FAILS
adj_quantity = adj_quantity_verify_lot_size(&symbol, quantity);
println!("quantity: {} adj_quantity: {}", quantity, adj_quantity);
assert_eq... | Rust | 0 |
er()
.map(|&s| String::from(s))
.collect();
assert_eq!(entries, expected);
Ok(())
}
#[test]
fn unlink() -> Result<()> {
let (root, croot, iroot) = create_sample()?;
root.unlink("file1")?;
assert!(root.lookup("file1").is_not_found());
assert!(croot.lookup("file1").is_not_found()... | Rust | 0 |
if model.progress > 1. {
model.progress = 1.;
model.loaded = true;
model.ticks = 3;
}
}
model
}
Msg::Tick => {
let mut model = Model { .... | Rust | 0 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
# Setup WebDriver
driver_path = 'chromedriver'
driver = webdriv... | Python | 1 |
you can still use it solely with `gl`, `rgl`, or any lib who play with
//! OpenGL.
//!
//! # What's inside this crate?
//!
//! This crate provide a two elements:
//!
//! * `CandlSurface`, a window type who generate a surface for using OpenGL
//! * `CandlManager`, a window manager to enable using multiple windows in a... | Rust | 0 |
};
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
fn bench_fibs(c: &mut Criterion) {
let mut group = c.benchmark_group("Fibonacci");
for i in [10u64].iter() {
group.bench_with_input(BenchmarkId::new("PackedSievePtr_2trait", i), i, |b, i| {
let table = ... | Rust | 0 |
Self::Target {
&self.base
}
}
impl<VM: VMBinding, const KIND: TraceKind> DerefMut for GenImmixMatureProcessEdges<VM, KIND> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.base
}
}
pub struct GenImmixNurseryGCWorkContext<VM: VMBinding>(std::marker::PhantomData<VM>);... | Rust | 0 |
sounds_cache = HashMap::new();
let autoplay_sounds: Vec<_> = self.autoplay_sounds
.into_iter()
.map(|s| s.into_autoplay_sound(sounds.len(), &mut autoplay_sounds_cache))
.collect();
let mut autoplay_sound_files: Vec<_> = autoplay_sounds_cache.into_iter().collect();
... | Rust | 0 |
Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_mem_flash_sus_ctrl](spi_mem_flash_sus_ctrl) module"]
pub type SPI_MEM_FLASH_SUS_CTRL = crate::Reg<u32, _SPI_MEM_FLASH_SUS_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPI_MEM_FLASH_... | Rust | 0 |
xe8, 0x6695, 0, 0, 0, 0x78, 0x4521].into(),
prefix: 108
})
);
}
#[test]
fn ip_address_with_prefix_invalid() {
assert_matches!(
"5.6.7.8".parse::<IpAddressWithPrefix<IpAddr>>(),
Err(IpAddressWithPrefixParseError::MissingPrefix)
);
... | Rust | 0 |
"What is the winning player's score? {}",
game.get_combat_winning_score(),
);
let mut game = Game::from_str(&input).unwrap();
println!(
"What is the winning player's score? {}",
game.get_recursive_combat_winning_score(),
);
}
use serenity::async_trait;
use serenity::client:... | Rust | 0 |
Nav(cls="hidden md:flex items-center space-x-8")(
*[
A(
label,
href=url,
cls="text-sm font-medium transition-colors hover:text-foreground/80 text-foreground... | Python | 1 |
import cv2 as cv
img = cv.imread("C:\\Users\\Japjot Singh\\Desktop\\Kotlin\\python-backup-codes\\OpenCV\\images\\2.jpeg")
cv.imshow('Original Img',img)
# Averaging
average = cv.blur(img,(3,3))
cv.imshow('Average Blur',average)
# Gaussian Blur
gauss = cv.GaussianBlur(img,(3,3))
cv.imshow('Gaussian Blur',gauss)
# ... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenSpOperationAuthAddModel(object):
def __init__(self):
self._auth_product_code = None
self._merchant_no = None
self._out_biz_no = None
@property
def auth_... | Python | 1 |
::ops::Deref;
use std::panic;
use std::pin::Pin;
use std::rc::Rc;
/// Bit flag used to identify [Block::GC].
pub const BLOCK_GC_REF_NUMBER: u8 = 0;
/// Bit flag used to identify items with content of type [ItemContent::Deleted].
pub const BLOCK_ITEM_DELETED_REF_NUMBER: u8 = 1;
/// Bit flag used to identify items wit... | Rust | 0 |
: u32 = 7u32;
#[doc = "*Required features: `\"Win32_Media_Multimedia\"`*"]
pub const MM_OLIVETTI_WAVEIN: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Multimedia\"`*"]
pub const MM_OLIVETTI_WAVEOUT: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Multimedia\"`*"]
pub const MM_ONLIVE: u32 = 200u32;
#[d... | Rust | 0 |
.get_static(&["test"]));
assert_eq!(Some(&1), trie.get(&["test".to_string()]));
assert_eq!(Some(&2), trie.get_static(&["test", "me"]));
assert_eq!(Some(&2), trie.get(&["test".to_string(), "me".to_string()]));
}
#[test]
fn test_remove() {
let mut trie: PathTrie<usize> = PathT... | Rust | 0 |
# 引入Chain模組
from langchain.chains import LLMChain
# 引入OpenAI LLM模組
from langchain_openai import AzureChatOpenAI
# 引入prompt模組
from langchain_core.prompts import PromptTemplate
import os
from dotenv import dotenv_values
config = dotenv_values(".env")
llm = AzureChatOpenAI(
azure_endpoint=config.get("AZURE_OPENAI... | Python | 1 |
RoseRuntimeImpl::SingleOutfix => single_outfix_block_exec(rose, scratch),
}
Ok(())
}
use std::fmt::{Debug, Formatter};
use std::ptr::Shared;
use std::fmt;
use constants::*;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Level {
PML4E,
PDPTE,
PDE,
PTE
}
#[derive(Clone, Copy)]
... | Rust | 0 |
struct Sltiu {
pub(crate) imm: u64,
pub(crate) rs1: RegIndex,
pub(crate) rd: RegIndex,
}
impl Display for Sltiu {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.imm == 1 {
write!(f, "seqz {}, {}", self.rd, self.rs1)
} else {
write!(f, "sltiu {}, {}, {} ({2:... | Rust | 0 |
#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2020/2/18 15:23
# @Author: Jtyoui@qq.com
import time
from pyunit_address import *
address = Address(is_max_address=True)
address.add_vague_text(['红花岗', '花溪'])
address.add_vague_text('贵州省-遵义市-遵义县-虾子镇-乐安村-乐石台')
def find_address_test():
af = find_address(addr... | Python | 1 |
return part_lines
def codeblock(block_str):
"""
Wraps multiline string blocks and returns unindented code.
Useful for templated code defined in indented parts of code.
Args:
block_str (str): typically in the form of a multiline string
Returns:
str: the unindented string
... | Python | 1 |
# qnm = q chem normal modes
# tnm = tensormol normal modes
import numpy as np
qnm = np.load("adenine_nm.npy")
tnm = np.load("adenine_TM.dat")
found = []
nfound = []
for i in range(tnm.shape[0]):
least_diff = float('inf')
least_index = None
for j in range(qnm.shape[0]):
if j in found:
co... | Python | 1 |
;
use byteorder::{ByteOrder, LittleEndian};
use super::*;
use crate::bus::PciBus;
use crate::config::{PciConfig, PCI_CONFIG_SPACE_SIZE, SECONDARY_BUS_NUM};
use crate::errors::Result;
use crate::root_port::RootPort;
struct PciDevice {
devfn: u8,
config: PciConfig,
pa... | Rust | 0 |
values[o].1,
));
}
}
deck
}
}
<reponame>volltin/learn_rust
fn main() {
let s = "hello";
println!("s: {}", s);
let mut s = String::from("hello");
s.push_str(", world!");
println!("s: {}", s);
// move
let s1 = String::from("s1s1s11");
... | 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 http://mozilla.org/MPL/2.0/.
from setuptools import setup
PACKAGE_NAME = 'mozdevice'
PACKAGE_VERSION = '0.44'
deps = ['mozfile >= 1.0',
'mo... | Python | 1 |
import os
import pandas as pd
import numpy as np
import statistics
from utils.format import *
from utils.heatmap import HeatmapPlot
compressor_order = ['ZLIB', 'PPMD', 'GZIP','BZ2', 'PNG','WEBP','JP2', 'HEVC']
type_order = ['ANOTHER-CONTROL', 'MEMORY', 'MODEL', 'LOGIC', 'TRAIN', 'API', 'CONC', 'PROCESS']
input_csv = ... | Python | 1 |
.run()
.await
}
use super::*;
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use std::ffi::{CString, OsStr};
use std::fmt;
use std::mem::ManuallyDrop;
use widestring::U16CString;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct fmx_Text {
_address: u8,
}
#[cfg_attr(target_os = "macos", link(kin... | Rust | 0 |
ed::BitBox;
/// use oben::evolution::binary::BinarySubstrate;;
/// use oben::evolution::binary::BinaryReaction;
/// use oben::evolution::chemistry::Reaction;
/// use oben::evolution::helper::Iteration;
///
/// let educt1_value: BinarySubstrate = BitBox::from_slice(&[255, 32]);
/// let educt2... | Rust | 0 |
;
pub const SWAPOFF: usize = 5163;
pub const SWAPON: usize = 5162;
pub const SYMLINK: usize = 5086;
pub const SYMLINKAT: usize = 5256;
pub const SYNC: usize = 5157;
pub const SYNC_FILE_RANGE: usize = 5264;
pub const SYNCFS: usize = 5301;
pub const SYSFS: usize = 5136;
pub const SYSINFO: usize = 5097;
pub const SYSLOG: ... | Rust | 0 |
def iterative(n):
resultado = 1
for i in range(1, n+1):
resultado *= i
return resultado
def recursive(n):
if n == 0:
return 1
else:
return n * recursive(n - 1)
def main():
n = 4
print(recursive(n), iterative(n))
return
if __name__ == "__main__":
main(... | Python | 1 |
and `curve`are options because we
/// are not guaranteed yet to have it for every lane
///
/// Contains all the information of a lane in the map
///
/// # Fields
///
/// * `entity_queue` - ordered queue giving the order of the contained elements
/// * `width` - width of the lane
/// * `max_speed` - max speed of th... | Rust | 0 |
default)]
pub base_url: String,
#[serde(rename = "post-build", default)]
pub post_build_command: String,
#[serde(rename = "feed-path", default = "default_feed_path")]
pub feed_path: PathBuf,
#[serde(default)]
pub paths: Paths,
}
impl Config {
pub fn title(&self) -> String {
if s... | Rust | 0 |
_ => None,
}
}
}
impl From<&str> for TradeOfferError {
fn from(message: &str) -> Self {
if let Some(code) = message.trim().split(' ').rev().next() {
let mut chars = code.chars();
if chars.next() != Some('(') {
return Self::Unknown(message.in... | Rust | 0 |
from fastapi import requests
from sqlalchemy import ForeignKey # noqa
from sqlalchemy import Column, DateTime, Double, Integer, String
from sqlalchemy.sql import func
from payrolls import settings
from payrolls.models.database import Base
class Wages(Base):
__tablename__ = "wages"
id = Column(Integer, prim... | Python | 1 |
SIGNATURE_SIZE: usize = 72;
/// The maximum size of a compact signature
pub const COMPACT_SIGNATURE_SIZE: usize = 64;
/// The size of a generator point
pub const GENERATOR_SIZE: usize = 64;
/// The size of a Pedersen commitment
pub const PEDERSEN_COMMITMENT_SIZE: usize = 33;
/// The size of a Pedersen commitment
pu... | Rust | 0 |
hority2 owns B
let _att2_pk = request_attribute_pk(&_pk, &_a2_key, &_att2).unwrap();
// add attribute sk's to user key
_u_key
._ska
.push(request_attribute_sk(&_u_key._pk, &_a1_key, &_att1).unwrap());
_u_key
._ska
.push(request_attribute_sk... | Rust | 0 |
cipher suite
0x00, 0x00, // pairwise suite count
0x00, 0x00, // akm suite count
0xcd, 0xab, // rsn capabilities
];
let rsne = Rsne {
version: VERSION,
group_data_cipher_suite: Some(cipher::Cipher::new_dot11(cipher::CCMP_128)),
rsn_... | Rust | 0 |
binator, QueryProcess, Selector, SelectorSegment,
},
};
use std::collections::HashSet;
use std::{
cmp::Ordering,
collections::VecDeque,
ops::{Bound, RangeBounds},
};
use std::{collections::HashMap, error::Error};
// get the ele indexs in tree
fn get_tree_indexs(ele: &BoxDynElement) -> VecDeque<usize> {
let mut in... | Rust | 0 |
import config as cfg
from predictors import ModelConfig, Predictor_mutiModel_img, Predictor_sigleModel_img
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from PIL import Image, ImageTk
import os
class PredictGUI:
def __init__(self, root):
self.root = root
self.root.title("图像预测... | Python | 1 |
Uuid,
}
#[derive(Insertable, Debug, Clone)]
#[table_name = "post_upvotes"]
struct NewUpvote {
pub post_uuid: Uuid,
pub user_uuid: Uuid,
}
#[derive(Debug, Clone, PartialEq, Identifiable, Associations, Queryable)]
#[primary_key(uuid)]
#[belongs_to(User, foreign_key = "user_uuid")]
#[belongs_to(Post, foreign_ke... | Rust | 0 |
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values t... | Rust | 0 |
e.SOAP.value:
pass
for each in data:
record = Station(**each)
db.session.add(record)
return commit()
except Exception as e:
logger.error('Error while querying database\n : {}'.format(str(e)))
if isRetry and count >= ... | Python | 1 |
}
for _i in 0..5 {
let frame = mm
.allocate_frame(2 * 1024 * 1024)
.expect("We don't have vRAM available");
tc.grow_large_pages(&[frame]).expect("Can't add large-page");
}
let frame = mm
.allocate_frame(2 * 1024 * 1024 * 1024)
.expect("We don't h... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.