lang
stringclasses
10 values
seed
stringlengths
5
2.12k
rust
flag_manifest_path: String, } pub const USAGE: &'static str = " Usage: cargo read-manifest [options] --manifest-path=PATH cargo read-manifest -h | --help Options: -h, --help Print this message -v, --verbose Use verbose output ";
rust
Encoding::Combined { git, .. } => Some(git), Encoding::GitOnly { git } => Some(git), Encoding::LocalOnly { .. } => None, } } /// Get a reference to the app config's local file encoding. pub fn encoding_local(&self) -> Option<&'static encoding_rs::Encoding> { match self.encoding.as_ref()? { Encoding::Combined { local, .. } => Some(local), Encoding::LocalOnly { local } => Some(local),
rust
pub enum ErrorCode { InvalidString, InvalidVarName } #[macro_export] macro_rules! es_error ( ($errName: ident) => { ::nom::ErrorKind::Custom($crate::errors::ErrorCode::$errName as u32) } );
rust
//! //! let mut seed = [0; SEED_BYTES]; //! thread_rng().fill_bytes(&mut seed); //! //! let key = Key::from_seed(&seed, Some(b"Application name")); //! let hasher = Hasher::new(key, None); //! //! let h1 = hasher.hash(b"test data 1");
rust
pub fn new(name: String, school: String, formkey: String) -> Self { let mut formkey_data = formkey.split(":"); let user_type = UserType::from(formkey_data.next().unwrap()); let user_id = formkey_data.next().unwrap().into(); Self { name,
rust
Up, Down, Left, Right, } fn move_avatar(m: Movement) { // Perform action depending on info match m { Movement::Up => println!("Avatar moving up"), Movement::Down => println!("Avatar moving down"), Movement::Left => println!("Avatar moving left"), Movement::Right => println!("Avatar moving right"),
rust
) { for (key, val) in [(&fields_spec.container_id, &container_status.container_id)].iter() { if let Some(val) = val { log.insert(key.as_str(), val.to_owned()); } } } fn annotate_from_container(log: &mut LogEvent, fields_spec: &FieldsSpec, container: &Container) { for (key, val) in [(&fields_spec.container_image, &container.image)].iter() {
rust
) -> Result<(), anyhow::Error> { let mut compressor = XzEncoder::new(buffer.as_slice(), 6); let mut data = vec![]; compressor.read_to_end(&mut data).unwrap(); let compressed_file_name = compressed_file_name.clone() + ".xz"; let mut file = tokio::fs::File::create(compressed_file_name.clone()).await?; log::info!("process_compressed CREATE {}", compressed_file_name); file.write_all(data.as_slice()).await?; log::info!("process_compressed WRITE {}", compressed_file_name); tx.send(compressed_file_name).await?; Ok(()) }
rust
use context::Context; #[derive(Deserialize, Debug)] pub struct SDKEventBatch { pub environment: input::SDKEnvironment,
rust
impl Color { pub fn new(r: u8, g: u8, b: u8) -> Color { Color { r: convert(r), g: convert(g), b: convert(b), } } pub fn generate(index: usize) -> (Color, u8, u8, u8) {
rust
let celsius = to_celsius(64_f32); assert_eq!(celsius, 17.76); } #[test] pub fn it_converts_celsius_to_farenheit_32c() { let fahrenheit = to_fahrenheit(32_f32); assert_eq!(fahrenheit, 89.6); }
rust
.unwrap(); tx_queue .push(alloc_frame(Id::new_standard(7), &[0, 1, 2, 4])) .unwrap(); }); // Manually trigger the tx interrupt to start the transmission. rtfm::pend(Interrupt::USB_HP_CAN_TX); // Add some higher priority messages when 3 messages have been sent. loop { let tx_count = cx.resources.tx_count.lock(|tx_count| *tx_count);
rust
let func = find_function(group, &args)?; return Some((func.ret_ty().clone(), false)); } Expression::RecordInit { record, types, .. } if types.len() == 0 => { Some((PrimitiveType::TypeRef(record.clone()), true)) } Expression::RecordInit { record, types, .. } => Some((
rust
#[repr(transparent)] pub struct ObjectFieldIndex(sqInt); impl NativeTransmutable<sqInt> for ObjectFieldIndex {} #[derive(Copy, Clone, Debug)] #[repr(transparent)] pub struct StackOffset(sqInt); impl NativeTransmutable<sqInt> for StackOffset {} #[no_mangle] pub unsafe extern "C" fn gtoolkit_null_semaphore_signaller(
rust
use bindings::Windows::Win32::Graphics::Direct2D::D2D_RECT_F; use super::Size; #[derive(Debug, Clone, Copy, PartialEq)] pub struct Rect { pub left: f32, pub top: f32, pub right: f32, pub bottom: f32, }
rust
} } if !grammar.is_empty() { println!(); for v in grammar { println!(" \x1b[0m{}\x1b[0m", v); } } } if !self.explain.is_empty() { println!();
rust
struct Fibonacci { curr: u32, next: u32, } impl Iterator for Fibonacci { // We can refer to this type using Self::Item type Item = u32; fn next(&mut self) -> Option<Self::Item> { let new_next = self.curr + self.next; self.curr = self.next; self.next = new_next;
rust
#[derive(Debug, Deserialize)] #[serde(rename_all="camelCase")] pub struct Semester { pub code: String,
rust
use rustorm::Pool; #[test] fn all_windows() { let db_url = "postgres://postgres:p0stgr3s@localhost:5432/bazaar_v8";
rust
impl crate::Writable for TARGET_TIME_NANOSECONDS_SPEC { type Writer = W; } #[doc = "`reset()` method sets TARGET_TIME_NANOSECONDS to value 0"] impl crate::Resettable for TARGET_TIME_NANOSECONDS_SPEC {
rust
#![crate_type = "lib"] // @has data.relationships.modules.data[0].type 'module' // @has data.relationships.modules.data[0].id 'modules::module' // @has included[0].type 'module' // @has included[0].id 'modules::module' // @has included[0].attributes.name 'module' // @has included[0].attributes.docs 'A module.' // @has included[0].attributes.summary 'A module.' /// A module.
rust
#[test] fn end_turn_skips_first_player_if_he_is_inactive() { let (pl, ri, mut game_engine) = create_valid_engine(); game_engine.modify_money(ri[1], description(UnitType::Knight).purchase_cost * 2); game_engine.act(pl[0].id(), PlayerAction::EndTurn).unwrap(); game_engine .act( pl[1].id(), PlayerAction::PlaceNewUnit(ri[1], UnitType::Knight, Coord::new(1, 0)), ).unwrap(); game_engine .act(
rust
ptr, }; pub(crate) struct FreeList { free: Vec<*mut Mem>, /// More Arenas may be allocated then this count, due to workers allocating and freeing Arenas. pub allocated: usize, } impl Debug for FreeList { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("FreeList") .field("free", &self.free) .field("free count", &self.free.len())
rust
} } /// Skips single-line comments from the source code. fn skip_single_line_comments(&mut self) { while !self.is_at_end() && self.get_current() != '\n' { self.advance(); } // Reposition the start of the token to
rust
// #[bench] // #[cfg(feature = "rayon")] // fn bench_rayon_0002_kib(b: &mut Bencher) { // bench_rayon(b, 2 * KIB); // } // #[bench] // #[cfg(feature = "rayon")] // fn bench_rayon_0004_kib(b: &mut Bencher) { // bench_rayon(b, 4 * KIB); // } // #[bench] // #[cfg(feature = "rayon")]
rust
pub mod algorithm; pub mod leetcode;
rust
use std::path::Path; //copied from rust site and modified pub fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { match File::open(filename) {
rust
let format = format::FormatBuilder::new().padding(1, 1).build(); table.set_format(format); table.printstd(); } } } fn max_title_width(tasks: &[&Task]) -> usize { *tasks .iter() .map(|task| task.title.len()) .max() .get_or_insert(0) }
rust
#![no_std] use cortex_m_semihosting::hprintln; use panic_semihosting as _; use nucleo_f401re::{ gpio::{gpioa::PA5, gpioc::PC13, Edge, ExtiPin, Input, Output, PullDown, PushPull}, prelude::*, stm32,
rust
pub BleRegisters { (0x000 => fifo: ReadWrite<u32, FIFO::Register>), (0x004 => _reserved0), (0x100 => fifoptr: ReadOnly<u32, FIFOPTR::Register>), (0x104 => fifothr: ReadWrite<u32, FIFOTHR::Register>), (0x108 => fifopop: ReadWrite<u32, FIFOPOP::Register>), (0x10C => fifopush: ReadWrite<u32, FIFOPUSH::Register>), (0x110 => fifoctrl: ReadWrite<u32, FIFOCTRL::Register>), (0x114 => fifoloc: ReadWrite<u32, FIFOLOC::Register>), (0x118 => _reserved1), (0x200 => clkcfg: ReadWrite<u32, CLKCFG::Register>),
rust
); let second_instance = object.clone(); global_lock_file.dependencies.insert( DependencyID(second_instance.name, second_instance.version.to_owned()), DependencyLock { name: object.name.clone(), version: object.version.clone(), tarball: object.tarball.clone(), integrity: object.integrity.clone(), dependencies: lock_dependencies, }, );
rust
pub struct DictionaryEntry { surface: String, left_id: u32, right_id: u32, word_cost: i32, }
rust
irq_handler_generic(frame, Irq(2u8)); } extern "x86-interrupt" fn irq_handler_3(frame: InterruptStackFrame) { irq_handler_generic(frame, Irq(3u8));
rust
.find(|f| f.sample_format() == config::SAMPLE_FORMAT && f.channels() == 1) .expect("no supported format?!") .with_sample_rate(cpal::SampleRate(config::SAMPLE_RATE as _)); let socket = UdpSocket::bind((config::TRANSMITTER_BIND_ADDR, config::TRANSMITTER_BIND_PORT)).unwrap(); socket.set_broadcast(true).unwrap(); let input_config = input_format.into(); let stream = input_device .build_input_stream( &input_config, move |data: &[config::Sample], _info| {
rust
} pub fn add_expulsion(tx: Sender<CommandToBackend>) -> BoxedFilter<(impl Reply,)> { warp::post() .and(warp::path!("api" / "expulsions" / "add")) .and(with_command_sender(tx))
rust
} impl BufferPool { pub fn new(cap: usize) -> BufferPool { BufferPool { pool: Vec::with_capacity(cap) } } pub fn get(&mut self, default_cap: usize) -> Vec<u8> { self.pool.pop().unwrap_or_else(|| Vec::with_capacity(default_cap))
rust
mod error; mod http; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Sync + Send>>; pub use async_trait::async_trait;
rust
// Checks that unprojection of a projection returns the original coordinate, // except for altitude, which is 0 let test_coordinate = WGS84::from_degrees_and_meters(37.407204, -122.147604, 1300.0); let projected = WebMercatorCoord::from_lat_lng(&test_coordinate); let unprojected = projected.to_lat_lng();
rust
macro_rules! unwrap_or { ($res:expr, $alt:expr) => { match $res { Ok(val) => val, Err(_) => $alt
rust
.memory(self.memory) .offset(0) .size(ash::vk::WHOLE_SIZE) .build()]; unsafe { self.lve_device.device.flush_mapped_memory_ranges(&mapped_range) .map_err(|e| log::error!("Unable to flush buffer: {}", e))
rust
&self, t_0: F, h: F, n: usize, result: &mut Result<F>, token: &Token, ) -> anyhow::Result<()> { // Get the initial state
rust
pub fn print(n: i32) -> Option<String> { fn print_line(v: &mut Vec<u8>, width: usize, max_width: usize) { v.extend(repeat(b' ').take((max_width - width) / 2)); v.extend(repeat(b'*').take(width)); v.push(b'\n'); } if n < 0 || n % 2 == 0 { return None; } let n = n as usize;
rust
pub static USERNAMES: &'static [&str] = &["root"]; pub static PASSWORDS: &'static [&str] = &["password", "<PASSWORD>", "<PASSWORD>"];
rust
data: T, ) -> Data<R, H, T> { debug!("data: {:?}", data.as_ref().len()); Data { connection: Some(self), channel: channel, extended: extended,
rust
Ok(base64::encode(encode_protobuf(res)?)) }, )?; Ok(()) } fn delegator_key_operation<F>(reply_to: String, mut operation: F) -> anyhow::Result<()> where F: FnMut(Vec<u8>, Vec<u8>) -> anyhow::Result<String> + Clone + Sync + Send + 'static, {
rust
#[doc = "Checks if the value of the field is `RES50K`"] #[inline(always)] pub fn is_res50k(&self) -> bool { *self == RESISTOR_A::RES50K } #[doc = "Checks if the value of the field is `RES100K`"] #[inline(always)] pub fn is_res100k(&self) -> bool { *self == RESISTOR_A::RES100K }
rust
// run-pass #![allow(unused_mut)] // pretty-expanded FIXME #23616 fn main() { let mut zero = || {}; let () = zero(); }
rust
* * This function performs a `POST` to the `/senders` endpoint. * * **This endpoint allows you to create a new sender identity.** *
rust
mod speech; pub use self::speech::*;
rust
pub fn as_mut(&mut self) -> Lazy<&mut T> { match *self { Loaded(ref mut x) => Loaded(x), Unloaded => Unloaded, } } pub fn unwrap(self) -> T { self.expect("Tried to unwrap() an unloaded value") } pub fn expect(self, msg: &str) -> T { if let Loaded(x) = self { x } else { panic!("{}", msg); }
rust
pub fn running_sum(nums: Vec<i32>) -> Vec<i32> { nums.iter() .scan(0, |sum, &v| { *sum += v; Some(*sum) })
rust
//! for this translation regime. use register::{cpu::RegisterReadWrite, register_bitfields}; register_bitfields! {u64, pub VTTBR_EL2 [ /// The VMID for the translation table. /// /// It is IMPLEMENTATION DEFINED whether the VMID is 8 bits or 16 bits.
rust
unhook(); DestroyWindow(hwnd); } WM_DESTROY => PostQuitMessage(0), _ => return DefWindowProcW(hwnd, msg, wp, lp), }; 0
rust
use unicode_normalization::UnicodeNormalization; let mut result = Vec::new(); let v_metrics = font.v_metrics(scale); let advance_height = v_metrics.ascent - v_metrics.descent + v_metrics.line_gap; let mut caret = point(0.0, v_metrics.ascent); let mut last_glyph_id = None; for c in text.nfc() {
rust
#[cfg(test)] mod tests { use super::*; fn ensure_entity<T: Entity>() {} #[test] fn test_contest_is_entity() { ensure_entity::<contest::Contest>()
rust
if labels_topK.len() == 0 { labels_topK.push((label, freq)); } else if labels_topK.last().unwrap().1 > freq || (labels_topK.last().unwrap().1 == freq && labels_topK.last().unwrap().0 < label) { if labels_topK.len() < K { labels_topK.push((label, freq)); } } else { for k in 0..(labels_topK.len()) { if freq > labels_topK[k].1 || (freq == labels_topK[k].1 && label <= labels_topK[k].0) { if labels_topK.len() < K { labels_topK.push((0, 0.0f32)); } for l in (k..(labels_topK.len()-1)).rev() { labels_topK[l+1] = labels_topK[l];
rust
if tex_macro.get_nb_opt_args() > 0 { let arg = tex_macro.get_opt_arg(0); proof.set_title(&arg); }
rust
pub fn default_branch(path: &str) -> AppResult<String> { Ok(Repository::discover(path)? .find_reference("refs/remotes/origin/HEAD")? .symbolic_target() .unwrap_or_default()
rust
fn run(contents: Vec<&str>, solver: &dyn Fn(Vec<&str>) -> Result<i64, Box<dyn std::error::Error>>) { match solver(contents) { Ok(answer) => println!("Answer: {}", answer), Err(problem) => println!("We got a problem: {}", problem), } } fn main() {
rust
const JUMP: u64 = 1 << 31; use std::hash; /// Takes a 64 bit key and the number of buckets, outputs a bucket number `0..buckets`. /// /// # Examples /// /// ``` /// extern crate jump_consistent_hash as jump; /// assert_eq!(jump::slot(0, 60), 0); /// assert_eq!(jump::slot(1, 60), 55);
rust
Foo: {} "#; let mut target_foo = serde_yaml::from_str::<serde_yaml::Value>(openapi_com_schemas).unwrap(); // println!("{}", serde_yaml::to_string(&target_foo)?); //let mut m = serde_yaml::Mapping::new(); //m.insert("key".into(), "value".into()); //target_foo["components"]["schemas"]["Foo"] = serde_yaml::to_value(openapi_schema_from_crd)?;
rust
owned.take_unsized(|ref_t: RefOwn<T>| f(MaybeValid::from(ref_t)) ) } else { unreachable!()
rust
.expect("item doesn't exist in output") .clone(); out_score >= expected * 0.95 && out_score <= expected * 1.05 }) } pub fn n_results(n: usize) -> impl Predicate<[u8]> { predicates::function::function(move |x: &[u8]| str::from_utf8(x).unwrap().lines().count() == n)
rust
[]; [0, nil, false]; [0, [1]]; let arr = [0, 1, 1, 2, 3, 5, 8, 13]; arr[5]; let arr = [[0], [0, 1], [0, 1, 2]]; arr[2][2]; "; let expected = [ monkey_array![], monkey_array![Integer(0), Nil, Boolean(false)],
rust
_ => return Err(ParserError { kind: ParserErrorKind::UnexpectedToken(sp_ident_ty), }), };
rust
pub b: String, } impl MyStruct { pub fn rand_new() -> Self { Self { a: random(), b: String::new() } } } impl ToKserd<'static> for MyStruct {
rust
println!("{}", objectbox::version::info()); fn verify_version_format(v: version::Version) { assert_eq!( format!("{}", v), format!("{}.{}.{}", v.major, v.minor, v.patch) ); } verify_version_format(version::lib()); verify_version_format(version::rust()); }
rust
// compile-flags: -O -C no-prepopulate-passes #![crate_type = "lib"] #![feature(rustc_attrs)] // CHECK-LABEL: @test
rust
assert_eq!(sample, dut.sentence.to_string()); assert_eq!(sample.len(), dut.len()); assert_eq!(0, dut.number_of_tokens()); } #[test]
rust
pub fn check_pythagorean_triplet(m: u64, n: u64) -> Option<(u64, u64, u64)> { if m < n { return None; } let p: u64 = (m * m) - (n * n); let q: u64 = 2 * m * n;
rust
impl XCursorTheme { pub(crate) unsafe fn new(theme: *mut wlr_xcursor_theme) -> XCursorTheme { XCursorTheme { theme } }
rust
use std::error::Error; use std::thread; use std::time::Duration; const UUID: &'static str = get_uuid::uuid(); #[derive(Debug)] #[toml_cfg::toml_config] pub struct Config {
rust
) -> Result<UpdateResult, DbErr> where C: ConnectionTrait { Updater::new(query).exec(db).await } async fn exec_update_and_return_original<A, C>( query: UpdateStatement, model: A, db: &C, ) -> Result<A, DbErr> where A: ActiveModelTrait, C: ConnectionTrait, {
rust
macro_rules! data { ($x:expr) => { $x * 2 } } pub fn another_foo() {
rust
pub fn is_global(addr: &SocketAddr) -> bool { use std::net::IpAddr; match addr.ip() { IpAddr::V4(addr) => { // TODO: Consider excluding: // addr.is_loopback() || addr.is_link_local() // || addr.is_broadcast() || addr.is_documentation() // || addr.is_unspecified() !addr.is_private() } IpAddr::V6(_) => { // TODO: Consider excluding:
rust
impl InMemoryDB { pub fn new() -> InMemoryDB { InMemoryDB {} } }
rust
field("should_panic", match should_panic(cx, &item) { // test::ShouldPanic::No ShouldPanic::No => cx.expr_path(should_panic_path("No")), // test::ShouldPanic::Yes ShouldPanic::Yes(None) => cx.expr_path(should_panic_path("Yes")), // test::ShouldPanic::YesWithMessage("...") ShouldPanic::Yes(Some(sym)) => cx.expr_call(sp, cx.expr_path(should_panic_path("YesWithMessage")), vec![cx.expr_str(sp, sym)]), }), // test_type: ... field("test_type", match test_type(cx) { // test::TestType::UnitTest TestType::UnitTest => cx.expr_path(test_type_path("UnitTest")),
rust
.stats() .expect("cannot get stats at end") .stats .expect("empty stats"); assert!( stats_before.last_block_content_size == stats_after.last_block_content_size, "last block content size should to be updated" ); assert!(
rust
#[derive(Debug, PartialEq)] pub enum Mode { Title, Setup, Play, Endscreen, Exit, } impl Default for Mode { fn default() -> Self {
rust
assert!(readable.skip_bytes(1).is_ok()); assert_eq!(readable.read_string(1).unwrap(), "B"); // utf8, 3bytes assert_eq!(readable.read_string(3).unwrap(), "가"); assert_eq!(readable.read_string(5).unwrap(), "나01"); assert!(readable.read_bytes(1).is_err()); } #[test] fn readable_file() { let mut readable = File::open("./test-resources/file1.txt").unwrap(); assert!(readable.read_bytes(10).is_ok()); assert!(readable.read_bytes(10).is_ok());
rust
slice::from_raw_parts_mut(ptr.offset(mid as isize), len - mid) ) } } extern "C" { fn abs(input: i32) -> i32; } fn main_f() {
rust
pub const NONE_FONT: Option<&Font> = None; pub trait FontExt: 'static { fn describe(&self) -> Option<FontDescription>; fn describe_with_absolute_size(&self) -> Option<FontDescription>; fn find_shaper(&self, language: &Language, ch: u32) -> Option<EngineShape>; fn get_coverage(&self, language: &Language) -> Option<Coverage>; #[cfg(any(feature = "v1_46", feature = "dox"))]
rust
use rusqlite::Connection; use crate::util::database::fns::get_all_installed; use crate::util::database::structs::InstalledPackages; use crate::util::lock::{create_lock, lock_exists, remove_lock}; use crate::util::macros::string_to_vec; use crate::util::packaging::structs::{NewPackage, Package}; pub fn list() {
rust
pub mode: String, } #[derive(Clone, Debug, Default, Deserialize)] #[serde(rename_all = "kebab-case")] pub struct Meta {
rust
assert_eq!(expected, actual); assert_eq!(actual.to_string(), smt); }; test_roundtrip( "((_ foo 1 2) 3)", Op::Indexed(
rust
use crate::environment::Environment; pub(crate) mod set_impl; mod stdlib; pub(crate) mod value; /// Include `set` constructor and set functions in environment. pub fn global(env: Environment) -> Environment { let env = stdlib::global(env); env.with_set_constructor(Box::new(crate::linked_hash_set::value::Set::from)); env }
rust
#[test] fn test_concat_cons_char_types_no_boundary() { let s = Sentence::from_tokenized("5").unwrap(); let filter = KyteaWsConstFilter::new(CharacterType::Digit); let s = filter.filter(s); assert_eq!("5", s.to_tokenized_string().unwrap()); } #[test] fn test_concat_cons_char_types() { let s = Sentence::from_tokenized("5 00 0").unwrap(); let filter = KyteaWsConstFilter::new(CharacterType::Digit);
rust
// Copyright 2020 sacn Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. // // This file was created as part of a University of St Andrews Computer Science BSC Senior Honours Dissertation Project. //! An example demo sACN receiver which utilises the sACN library.
rust
.clone() .await } let disabled_tests_future_container = self.disabled_tests_future_container.clone(); get_or_insert_disabled_tests_future(test_component, disabled_tests_future_container) } /// Returns `true` if the given test is disabled (marked `#[ignore]`) by the developer. /// /// If the set of disabled tests isn't yet cached, this will retrieve it -- hence `async`. async fn is_test_disabled<'a>( &'a self,
rust
/// The number of bits needed to represent `self` pub fn bits(&self) -> usize { self.value.bit_length() }
rust
pub fn get_num(&self) -> i8 { return self.val; } /// Increment the counter. /// /// Note, the parameter is "&mut self" as this function modifies state. /// In the frontend (/src/main.js) this is added to the "changeMethods" array /// using near-cli we can call this by:
rust
} macro_rules! gpio { ( $PX:ident, $pxsvd:ident, $px:ident, $port_value:expr, [ $($PXi:ident: ($pxi:ident, $i:expr, $MODE:ty),)+ ] ) => { /// GPIO pub mod $px { use super::{
rust
} let output = sliderule::create_component(&get_cwd(), name.to_string(), src_license, docs_license); // Show extra output only when the user requests it if verbose { print_stdout(&output); } else { println!("Component creation finished."); }
rust
col: self.col, val: self.val, } } } impl std::ops::Sub for Matrix { type Output = Self; fn sub(mut self, other: Self) -> Self { if self.row != other.row || self.col != other.col { panic!("the sizes of the two matrices do not match");
rust
// Max message frame length for discovery protocol: 512KB pub const MAX_FRAME_LENGTH_DISCOVERY: usize = 512 * 1024; // Max message frame length for ping protocol: 1KB pub const MAX_FRAME_LENGTH_PING: usize = 1024; // Max message frame length for identify protocol: 2KB pub const MAX_FRAME_LENGTH_IDENTIFY: usize = 2 * 1024; // Max message frame length for disconnectmsg protocol: 1KB pub const MAX_FRAME_LENGTH_DISCONNECTMSG: usize = 1024; // Max message frame length for feeler protocol: 1KB pub const MAX_FRAME_LENGTH_FEELER: usize = 1024; // Max data size in send buffer: 24MB (a little larger than max frame length)
rust
extern crate web_sys; #[allow(unused_macros)] macro_rules! info { ( $( $t:tt )* ) => { web_sys::console::log_1(&format!( $( $t )* ).into()); } } #[allow(unused_imports)] pub(crate) use info;
rust
let _: () = self.conn().hset(hash, id, dest).unwrap(); } fn get_from_hash(&self, hash: &str, id: &str) -> Option<String> { self.conn().hget(hash, id).ok() } fn has_key(&self, id: &str) -> bool { let result: Option<usize> = self.conn().exists(id).ok(); result.map(|it| it != 0).unwrap_or(false) } fn expire_entity(&self, id: &str, timeout: usize) { let _: () = self.conn().expire(id, timeout).unwrap(); }
rust
Err(Error::Interface{msg:format!("channel ensor not found")}) }else{ Sensor::open(path.as_path()) } } pub fn value(&self) -> Result<f32> { let value = fs::read_to_string(self.path.join("value"))?.parse::<f32>()?; Ok(value) } }
rust
let resp = client.request(req).await; let resp = match resp { Ok(resp) => resp, Err(error) => return Err(GetGiteeError{code: ErrorCode::RequestError, msg: error.message().to_string()}), };
rust
/// An executable region of memory. Use [as_function!] to run code from here! pub struct ExecutableRegion { region: MappedRegion, } impl ExecutableRegion { /// Consumes the [MappedRegion] and marks its memory as read-only and executable. pub fn from(region: MappedRegion) -> crate::Result<Self> { use libc::{PROT_EXEC, PROT_READ};