file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
lib.rs
/*! * This library provides an API client for Diffbot. * * Making API requests * ------------------- * * There are a handful of different ways to make API calls: * * 1. The most basic way to make a request is with the ``call()`` function. * Everything must be specified for each request. * * 2. Use the ``D...
let num = num as uint; let msg = match o.pop(&~"error") .expect("JSON had errorCode but not error") { json::String(s) => s, uh_oh => fail!("error was {} instead of a string", uh_oh.to_st...
match json { json::Object(~mut o) => { match o.pop(&~"errorCode") { Some(json::Number(num)) => {
random_line_split
lib.rs
/*! * This library provides an API client for Diffbot. * * Making API requests * ------------------- * * There are a handful of different ways to make API calls: * * 1. The most basic way to make a request is with the ``call()`` function. * Everything must be specified for each request. * * 2. Use the ``D...
} /// An in-progress Diffbot API call. pub struct Request { priv request: RequestWriter<TcpStream>, } impl Request { /// Set the value for Diffbot to send as the ``User-Agent`` header when /// making your request. pub fn user_agent(&mut self, user_agent: ~str) { self.request.headers.extension...
{ prepare_request(url, self.token, api, fields, self.version) }
identifier_body
main.rs
use std::time; use vulkano::instance::Instance; use vulkano::instance::PhysicalDevice; use vulkano::pipeline::GraphicsPipeline; use vulkano::pipeline::viewport::Viewport; use vulkano::device::Device; use vulkano::device::Features; use vulkano::device::RawDeviceExtensions; use vulkano::framebuffer::{ Framebu...
() { let img = match image::open("./media/autumn.png") { Ok(image) => image, Err(err) => panic!("{:?}", err) }; { // stdout image info println!("color {:?}", img.color()); println!("dimensions {:?}", img.dimensions()); // println!("first pixel {:?}", img.pixels(...
main
identifier_name
main.rs
use std::time; use vulkano::instance::Instance; use vulkano::instance::PhysicalDevice; use vulkano::pipeline::GraphicsPipeline; use vulkano::pipeline::viewport::Viewport; use vulkano::device::Device; use vulkano::device::Features; use vulkano::device::RawDeviceExtensions; use vulkano::framebuffer::{ Framebu...
swapchain = new_swapchain; framebuffers = window_size_dependent_setup(&new_images, render_pass.clone(), &mut dynamic_state); recreate_swapchain = false; } let (image_num, acquire_future) = match swapchain::acquire_next_image(swapchain.clone(), None){ ...
Err(err) => panic!("{:?}", err) };
random_line_split
main.rs
use std::time; use vulkano::instance::Instance; use vulkano::instance::PhysicalDevice; use vulkano::pipeline::GraphicsPipeline; use vulkano::pipeline::viewport::Viewport; use vulkano::device::Device; use vulkano::device::Features; use vulkano::device::RawDeviceExtensions; use vulkano::framebuffer::{ Framebu...
//TODO: list devices, choose based on user input for p in PhysicalDevice::enumerate(&instance) { print!("{}", p.name()); println!(", driver version: {}", p.driver_version()); } let physical = PhysicalDevice::enumerate(&instance) .next() .expect("no device available"); ...
{ let img = match image::open("./media/autumn.png") { Ok(image) => image, Err(err) => panic!("{:?}", err) }; { // stdout image info println!("color {:?}", img.color()); println!("dimensions {:?}", img.dimensions()); // println!("first pixel {:?}", img.pixels().n...
identifier_body
main.rs
use std::time; use vulkano::instance::Instance; use vulkano::instance::PhysicalDevice; use vulkano::pipeline::GraphicsPipeline; use vulkano::pipeline::viewport::Viewport; use vulkano::device::Device; use vulkano::device::Features; use vulkano::device::RawDeviceExtensions; use vulkano::framebuffer::{ Framebu...
else { return ; }; let (new_swapchain, new_images) = match swapchain.recreate_with_dimension(dimensions) { Ok(r) => r, Err(SwapchainCreationError::UnsupportedDimensions) => continue, Err(err) => panic!("{:?}", err) }...
{ let dimensions: (u32, u32) = dimensions.to_physical(window.get_hidpi_factor()).into(); [dimensions.0, dimensions.1] }
conditional_block
body.rs
#![allow(dead_code)] #![allow(unused_doc_comments)] /** * body.rs contains the Body struct and implements methods for it. A body struct contains only the * position and velocity vectors of the body, other parameters are calculated using methods. A body * is instantiated using using the Body::new() method, which als...
(&self, angle: f64) -> (Vector3<f64>, Vector3<f64>) { let r = self.position_at_angle(angle); let v = self.velocity_at_angle(angle); let tht = angle - self.true_anomaly(); let trans = Matrix3::from_rows(&[ Vector3::new(tht.cos(), -tht.sin(), 0.0).transpose(), Vecto...
position_and_velocity
identifier_name
body.rs
#![allow(dead_code)] #![allow(unused_doc_comments)] /** * body.rs contains the Body struct and implements methods for it. A body struct contains only the * position and velocity vectors of the body, other parameters are calculated using methods. A body * is instantiated using using the Body::new() method, which als...
} /* points from focus to perigee if I'm not mistaken */ pub fn eccentricity_vector(&self) -> Vector3<f64> { let veloc = self.velocity; let posit = self.position; let h = self.angular_momentum(); (veloc.cross(&h) / SOLARGM) - posit.normalize() } pub fn angular_mome...
{ return val.acos(); }
conditional_block
body.rs
#![allow(dead_code)] #![allow(unused_doc_comments)] /** * body.rs contains the Body struct and implements methods for it. A body struct contains only the * position and velocity vectors of the body, other parameters are calculated using methods. A body * is instantiated using using the Body::new() method, which als...
impl Body { pub fn new(position: Vector3<f64>, velocity: Vector3<f64>) -> Body { // h and e are used for determining what kind of orbit the body is currently in let h = position.cross(&velocity); let e = ((velocity.cross(&h) / SOLARGM) - position.normalize()).norm(); Body { ...
pub velocity: Vector3<f64>, pub orbit_type: OrbitType, } /* Adds methods to Body struct */
random_line_split
body.rs
#![allow(dead_code)] #![allow(unused_doc_comments)] /** * body.rs contains the Body struct and implements methods for it. A body struct contains only the * position and velocity vectors of the body, other parameters are calculated using methods. A body * is instantiated using using the Body::new() method, which als...
pub fn true_anomaly(&self) -> f64 { let e_vec = self.eccentricity_vector(); let posit = self.position.normalize(); let val = e_vec.dot(&posit) / (e_vec.norm() * posit.norm()); if posit.dot(&self.velocity.normalize()) < 0.0 { return 2.0 * PI - val.acos(); } else ...
{ self.omega().cross(&self.position) }
identifier_body
object_ptr.rs
/* * 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 ...
<U: IsObject>(&self) -> Result<ObjectPtr<U>, Error> { let child_index = Object::get_type_index::<U>(); let object_index = self.as_object().type_index; let is_derived = if child_index == object_index { true } else { // TODO(@jroesch): write tests deriv...
downcast
identifier_name
object_ptr.rs
/* * 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 ...
pub fn upcast(&self) -> ObjectPtr<Object> { ObjectPtr { ptr: self.ptr.cast(), } } pub fn downcast<U: IsObject>(&self) -> Result<ObjectPtr<U>, Error> { let child_index = Object::get_type_index::<U>(); let object_index = self.as_object().type_index; let ...
{ unsafe { self.ptr.as_ref().as_object() } }
identifier_body
object_ptr.rs
/* * 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 ...
let object = Object::base_object::<Object>(); let ptr = ObjectPtr::new(object); assert_eq!(ptr.count(), 1); Ok(()) } #[test] fn roundtrip_retvalue() -> Result<()> { let ptr = ObjectPtr::new(Object::base_object::<Object>()); let ret_value: RetValue = ptr.clone...
random_line_split
object_ptr.rs
/* * 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 ...
} impl Object { fn new(type_index: u32, deleter: Deleter) -> Object { Object { type_index, // Note: do not touch this field directly again, this is // a critical section, we write a 1 to the atomic which will now // be managed by the C++ atomics. ...
{ true }
conditional_block
main.rs
fn main() { //scope() //moves_and_mem(); //refs() slices() } //////////////////////////////////////////////////////////////////////////////// // What is Ownership? //////////////////////////////////////////////////////////////////////////////// // Ownership is Rust's central feature. // All programs have to ma...
// some value without taking ownership over it. // s inside of calc_len becomes a pointer to the String struct bound // to duderington, which itself contains a ptr to the actual string // data on the heap. // // A closer look at the function call: // // let ano = String::from("ano"); // let len = calc...
{ // [References and Borrowing] // The issue with the returning tuple code we've seen elsewhere in // the ownership section is that we have to return the String to // the calling function so we can still use the String after the call. // Here we define calculate_length so that it uses a *reference* to // an...
identifier_body
main.rs
fn main() { //scope() //moves_and_mem(); //refs() slices() } //////////////////////////////////////////////////////////////////////////////// // What is Ownership? //////////////////////////////////////////////////////////////////////////////// // Ownership is Rust's central feature. // All programs have to ma...
() { // With string literals, we know the contents of the string at compile // time, so the text is literally hardcoded into the executable, // making them extremely fast and efficient. This property only comes // from its immutability. We can't put a blob of memory into the binary // for each piece of text w...
moves_and_mem
identifier_name
main.rs
fn main() { //scope() //moves_and_mem(); //refs() slices() } //////////////////////////////////////////////////////////////////////////////// // What is Ownership? //////////////////////////////////////////////////////////////////////////////// // Ownership is Rust's central feature. // All programs have to ma...
// the opposite order (LIFO). This is referred to as // *pushing onto the stack* and *popping off of the stack* // // It's fast because of the way it accesses the data: it never has to // search for a place to put new data or a place to get data from because // that place is *always* the top of the stack. Another prope...
// stores values in the order it gets them and removes the values in
random_line_split
3rd_person.rs
//! Example 03. 3rd person walk simulator. //! //! Difficulty: Advanced. //! //! This example based on async example, because it requires to load decent amount of //! resources which might be slow on some machines. //! //! In this example we'll create simple 3rd person game with character that can idle, //! walk, or ju...
() { let (mut game, event_loop) = Game::new("Example 03 - 3rd person"); // Create simple user interface that will show some useful info. let interface = create_ui( &mut game.engine.user_interface.build_ctx(), Vector2::new(100.0, 100.0), ); let mut previous = Instant::now(); let...
main
identifier_name
3rd_person.rs
//! Example 03. 3rd person walk simulator. //! //! Difficulty: Advanced. //! //! This example based on async example, because it requires to load decent amount of //! resources which might be slow on some machines. //! //! In this example we'll create simple 3rd person game with character that can idle, //! walk, or ju...
let settings = match input.physical_key { KeyCode::Digit1 => Some(QualitySettings::ultra()), KeyCode::Digit2 => Some(QualitySettings::high()), KeyCode::Digit3 => Some(QualitySettings::medium()), ...
{ game_scene.player.handle_key_event(input, fixed_timestep); }
conditional_block
3rd_person.rs
//! Example 03. 3rd person walk simulator. //! //! Difficulty: Advanced. //! //! This example based on async example, because it requires to load decent amount of //! resources which might be slow on some machines. //! //! In this example we'll create simple 3rd person game with character that can idle, //! walk, or ju...
// 60 fps. let elapsed = previous.elapsed(); previous = Instant::now(); lag += elapsed.as_secs_f32(); while lag >= fixed_timestep { // ************************ // Put your game logic here. ...
{ let (mut game, event_loop) = Game::new("Example 03 - 3rd person"); // Create simple user interface that will show some useful info. let interface = create_ui( &mut game.engine.user_interface.build_ctx(), Vector2::new(100.0, 100.0), ); let mut previous = Instant::now(); let fi...
identifier_body
3rd_person.rs
//! Example 03. 3rd person walk simulator. //! //! Difficulty: Advanced. //! //! This example based on async example, because it requires to load decent amount of //! resources which might be slow on some machines. //! //! In this example we'll create simple 3rd person game with character that can idle, //! walk, or ju...
//! blending machines are used in all modern games to create complex animations from set //! of simple ones. //! //! TODO: Improve explanations. Some places can be explained better. //! //! Known bugs: Sometimes character will jump, but jumping animations is not playing. //! //! Possible improvements: //! - Smart came...
//! Also this example demonstrates the power of animation blending machines. Animation
random_line_split
cargo-deploy.rs
//! # `cargo deploy` //! Run a binary on a constellation cluster //! //! ## Usage //! ```text //! cargo deploy [options] <host> [--] [<args>]... //! ``` //! //! ## Options //! ```text //! -h --help Show this screen. //! -V --version Show version. //! --format=<fmt> Output format [possible values: hum...
f let Some(profile) = profile { let _ = cargo.arg(format!("--profile={}", profile)); } for features in features { let _ = cargo.arg(format!("--features={}", features)); } if all_features { let _ = cargo.arg("--all-features"); } if no_default_features { let _ = cargo.arg("--no-default-features"); } if le...
let _ = cargo.arg("--release"); } i
conditional_block
cargo-deploy.rs
//! # `cargo deploy` //! Run a binary on a constellation cluster //! //! ## Usage //! ```text //! cargo deploy [options] <host> [--] [<args>]... //! ``` //! //! ## Options //! ```text //! -h --help Show this screen. //! -V --version Show version. //! --format=<fmt> Output format [possible values: hum...
n multi_opt(name: &'static str, value_name: &'static str, help: &'static str) -> Self { // Note that all `.multiple(true)` arguments in Cargo should specify // `.number_of_values(1)` as well, so that `--foo val1 val2` is // *not* parsed as `foo` with values ["val1", "val2"]. // `number_of_values` should become ...
Self::opt(name, help) .value_name(value_name) .multiple(true) .min_values(0) .number_of_values(1) } f
identifier_body
cargo-deploy.rs
//! # `cargo deploy` //! Run a binary on a constellation cluster //! //! ## Usage //! ```text //! cargo deploy [options] <host> [--] [<args>]... //! ``` //! //! ## Options //! ```text //! -h --help Show this screen. //! -V --version Show version. //! --format=<fmt> Output format [possible values: hum...
`--` go to the binary, the ones before go to Cargo. ", ), ) } fn cargo(args: &ArgMatches) -> process::Command { let verbose: u64 = args.occurrences_of("verbose"); let color: Option<&str> = args.value_of("color"); let frozen: bool = args.is_present("frozen"); let locked: bool = args.is_present("locked"); let...
and `--example` specifies the example target to run. At most one of `--bin` or `--example` can be provided. All the arguments following the two dashes (`--`) are passed to the binary to run. If you're passing arguments to both Cargo and the binary, the ones after
random_line_split
cargo-deploy.rs
//! # `cargo deploy` //! Run a binary on a constellation cluster //! //! ## Usage //! ```text //! cargo deploy [options] <host> [--] [<args>]... //! ``` //! //! ## Options //! ```text //! -h --help Show this screen. //! -V --version Show version. //! --format=<fmt> Output format [possible values: hum...
rget: &'static str) -> Self { Self::opt("target", target).value_name("TRIPLE") } fn target_dir() -> Self { Self::opt("target-dir", "Directory for all generated artifacts").value_name("DIRECTORY") } fn manifest_path() -> Self { Self::opt("manifest-path", "Path to Cargo.toml").value_name("PATH") } }
get_triple(ta
identifier_name
generator.rs
use std::ffi::{OsStr, OsString}; use std::fs::{File, OpenOptions}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::Arc; use std::time::Instant; use std::{env, fs, io, thread}; use opencv_binding_generator::{Generator, I...
let add_manual = |file: &mut BufWriter<File>, module: &str| -> Result<bool> { if manual_dir.join(format!("{module}.rs")).exists() { writeln!(file, "pub use crate::manual::{module}::*;")?; Ok(true) } else { Ok(false) } }; let start = Instant::now(); let mut hub_rs = BufWriter::new(File::create(targ...
{ // Use include instead of #[path] attribute because rust-analyzer doesn't handle #[path] inside other include! too well: // https://github.com/twistedfall/opencv-rust/issues/418 // https://github.com/rust-lang/rust-analyzer/issues/11682 Ok(writeln!( write, r#"include!(concat!(env!("OUT_DIR"), "/opencv/{...
identifier_body
generator.rs
use std::ffi::{OsStr, OsString}; use std::fs::{File, OpenOptions}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::Arc; use std::time::Instant; use std::{env, fs, io, thread}; use opencv_binding_generator::{Generator, I...
(mut write: impl Write, module: &str) -> Result<()> { Ok(writeln!(write, "#[cfg(ocvrs_has_module_{module})]")?) } fn write_module_include(write: &mut BufWriter<File>, module: &str) -> Result<()> { // Use include instead of #[path] attribute because rust-analyzer doesn't handle #[path] inside other include! too w...
write_has_module
identifier_name
generator.rs
use std::ffi::{OsStr, OsString}; use std::fs::{File, OpenOptions}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::Arc; use std::time::Instant; use std::{env, fs, io, thread}; use opencv_binding_generator::{Generator, I...
// add module entry to hub.rs and move the module file into opencv/ write_has_module(&mut hub_rs, module)?; write_module_include(&mut hub_rs, module)?; let module_filename = format!("{module}.rs"); let module_src_file = OUT_DIR.join(&module_filename); let mut module_rs = BufWriter::new(File::create(&targe...
{ let module_types_cpp = OUT_DIR.join(format!("{module}_types.hpp")); let mut module_types_file = BufWriter::new( OpenOptions::new() .create(true) .truncate(true) .write(true) .open(module_types_cpp)?, ); let mut type_files = files_with_extension(&OUT_DIR, "cpp")? .filter(|f| is_...
conditional_block
generator.rs
use std::ffi::{OsStr, OsString}; use std::fs::{File, OpenOptions}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::Arc; use std::time::Instant; use std::{env, fs, io, thread}; use opencv_binding_generator::{Generator, I...
io::copy(&mut BufReader::new(File::open(&entry)?), &mut module_types_file)?; let _ = fs::remove_file(entry); } } // add module entry to hub.rs and move the module file into opencv/ write_has_module(&mut hub_rs, module)?; write_module_include(&mut hub_rs, module)?; let module_filename = format!("{m...
random_line_split
flood_order.rs
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: 12/07/2017 Last Modified: 12/10/2018 License: MIT */ use whitebox_raster::*; use whitebox_common::structures::Array2D; use crate::tools::*; use std::cmp::Ordering; use std::collections::BinaryHeap; use std::collec...
(&self, other: &Self) -> Option<Ordering> { // Some(other.priority.cmp(&self.priority)) other.priority.partial_cmp(&self.priority) } } impl Ord for GridCell { fn cmp(&self, other: &GridCell) -> Ordering { // other.priority.cmp(&self.priority) let ord = self.partial_cmp(other).un...
partial_cmp
identifier_name
flood_order.rs
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: 12/07/2017 Last Modified: 12/10/2018 License: MIT */ use whitebox_raster::*; use whitebox_common::structures::Array2D; use crate::tools::*; use std::cmp::Ordering; use std::collections::BinaryHeap; use std::collec...
progress = (100.0_f64 * num_solved_cells as f64 / (num_cells - 1) as f64) as usize; if progress!= old_progress { println!("Progress: {}%", progress); old_progress = progress; } } } let elapsed_time = get...
random_line_split
flood_order.rs
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: 12/07/2017 Last Modified: 12/10/2018 License: MIT */ use whitebox_raster::*; use whitebox_common::structures::Array2D; use crate::tools::*; use std::cmp::Ordering; use std::collections::BinaryHeap; use std::collec...
} impl Ord for GridCell { fn cmp(&self, other: &GridCell) -> Ordering { // other.priority.cmp(&self.priority) let ord = self.partial_cmp(other).unwrap(); match ord { Ordering::Greater => Ordering::Less, Ordering::Less => Ordering::Greater, Ordering::Equa...
{ // Some(other.priority.cmp(&self.priority)) other.priority.partial_cmp(&self.priority) }
identifier_body
window.rs
use crate::prelude::*; use crossterm::style::{Attribute, Print, Styler}; use crossterm::{cursor, terminal, ExecutableCommand, QueueableCommand}; use std::io::{stdout, Write}; const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); pub struct Window { started_at: StartedAt, lines: u16, cols: u16, ...
(&mut self) -> Result<bool, Error> { use crossterm::event::Event::{Key, Mouse, Resize}; use crossterm::event::KeyCode::Char; use crossterm::event::{KeyEvent, KeyModifiers}; match crossterm::event::read()? { Key(KeyEvent { code: Char('q'),.. }) ...
handle_event
identifier_name
window.rs
use crate::prelude::*; use crossterm::style::{Attribute, Print, Styler}; use crossterm::{cursor, terminal, ExecutableCommand, QueueableCommand}; use std::io::{stdout, Write}; const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); pub struct Window { started_at: StartedAt, lines: u16, cols: u16, ...
elapsed, true, )))? .queue(cursor::MoveTo(0, 2))? .queue(Print(self.per_code_line(&alltime_stats)))?; } // mutex on alltime_stats { let mut ring_buffer = self.ring_buffer.lock().unwrap(); // T...
{ let mut stdout = stdout(); stdout .queue(terminal::Clear(terminal::ClearType::All))? .queue(cursor::MoveTo(0, 0))? .queue(Print(format!("apachetop {}", CARGO_PKG_VERSION)))? .queue(cursor::MoveTo(self.cols / 2, 0))? .queue(Print(self.started...
identifier_body
window.rs
use crate::prelude::*; use crossterm::style::{Attribute, Print, Styler}; use crossterm::{cursor, terminal, ExecutableCommand, QueueableCommand}; use std::io::{stdout, Write}; const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); pub struct Window { started_at: StartedAt, lines: u16, cols: u16, ...
else { 0.0 }; // intelligent dp detection: eg 2.34%, 10.5%, 100% let dp = if (pct - 100.0).abs() < f64::EPSILON { 0 } else if pct < 10.0 { 2 } else { 1 }; (pct, dp) ...
{ 100.0 * (rb_stats.requests as f64 / stats.global.requests as f64) }
conditional_block
window.rs
use crate::prelude::*; use crossterm::style::{Attribute, Print, Styler}; use crossterm::{cursor, terminal, ExecutableCommand, QueueableCommand}; use std::io::{stdout, Write}; const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); pub struct Window { started_at: StartedAt, lines: u16, cols: u16, ...
.queue(Print(format!("apachetop {}", CARGO_PKG_VERSION)))? .queue(cursor::MoveTo(self.cols / 2, 0))? .queue(Print(self.started_at.to_string()))? .queue(cursor::MoveTo(self.cols - 8 as u16, 0))? .queue(Print(chrono::Local::now().format("%H:%M:%S").to_string()))?; ...
.queue(cursor::MoveTo(0, 0))?
random_line_split
main.rs
#![feature(unboxed_closures, fn_traits)] use std::fmt::Debug; // error[E0635]: unknown feature `fnbox` // #![feature(unboxed_closures, fn_traits, fnbox)] // 返回闭包 // 放入 `Box<T>` 中是因为闭包的大小在编译期是未知的. // fn counter(i: i32) -> Box<Fn(i32) -> i32> { // Box::new(move |n: i32| n + i) // } // Rust 2018 中也可以写成 `impl Fn(i32)...
impl FnOnce<()> for Closure { type Output = u32; extern "rust-call" fn call_once(self, args: ()) -> u32 { println!("call it FnOnce()"); self.env_var + 2 } } impl FnMut<()> for Closure { extern "rust-call" fn call_mut(&mut self, args: ()) -> u32 { println!("call it FnMut()"); ...
env_var: u32, }
random_line_split
main.rs
#![feature(unboxed_closures, fn_traits)] use std::fmt::Debug; // error[E0635]: unknown feature `fnbox` // #![feature(unboxed_closures, fn_traits, fnbox)] // 返回闭包 // 放入 `Box<T>` 中是因为闭包的大小在编译期是未知的. // fn counter(i: i32) -> Box<Fn(i32) -> i32> { // Box::new(move |n: i32| n + i) // } // Rust 2018 中也可以写成 `impl Fn(i32)...
装箱稍后在迭代器中使用 // 所以这里必须使用 `move` 关键字将 `s` 的所有权转移到闭包中, // 因为变量 `s` 是复制语义类型, 所以该闭包捕获的是原始变量 `s` 的副本 c.push(Box::new(move || println!("{}", s))); c.push(Box::new(|| println!("third"))); } // `Fn` 并不受孤儿规则限制, 可有可无 // use std::ops::Fn; // 以 trait 限定的方式实现 any 方法 // 自定义的 Any 不同于标准库的 Any // 该函数的泛型 `F` 的 trait 限定为...
要将闭包
identifier_name
main.rs
#![feature(unboxed_closures, fn_traits)] use std::fmt::Debug; // error[E0635]: unknown feature `fnbox` // #![feature(unboxed_closures, fn_traits, fnbox)] // 返回闭包 // 放入 `Box<T>` 中是因为闭包的大小在编译期是未知的. // fn counter(i: i32) -> Box<Fn(i32) -> i32> { // Box::new(move |n: i32| n + i) // } // Rust 2018 中也可以写成 `impl Fn(i32)...
Pick<F> // where // F: Fn(&(u32, u32)) -> &u32, // { // fn call(&self) -> &u32 { (self.func)(&self.data) } // } // 实际生命周期 impl<F> Pick<F> where F: for<'f> Fn(&'f (u32, u32)) -> &'f u32, { fn call(&self) -> &u32 { (self.func)(&self.data) } } fn max(data: &(u32, u32)) -> &u32 { if data.0 > data.1 {...
器自动补齐了生命周期参数 // impl<F>
identifier_body
main.rs
#![feature(unboxed_closures, fn_traits)] use std::fmt::Debug; // error[E0635]: unknown feature `fnbox` // #![feature(unboxed_closures, fn_traits, fnbox)] // 返回闭包 // 放入 `Box<T>` 中是因为闭包的大小在编译期是未知的. // fn counter(i: i32) -> Box<Fn(i32) -> i32> { // Box::new(move |n: i32| n + i) // } // Rust 2018 中也可以写成 `impl Fn(i32)...
let env_var = 1; let c = || env_var + 2; assert_eq!(3, c()); // 显式指定闭包类型 let env_var = 1; // 该类型为 trait 对象, 此处必须使用 trait 对象 let c: Box<Fn() -> i32> = Box::new(|| env_var + 2); assert_eq!(3, c()); // 复制语义类型自动实现 `Fn` // 绑定为字符串字面量, 为复制语义类型 let s = "hello"; // 闭包会按照不可变引用类型来捕获...
} // 与上者等价的闭包示例
conditional_block
deferred_call.rs
// Licensed under the Apache License, Version 2.0 or the MIT License. // SPDX-License-Identifier: Apache-2.0 OR MIT // Copyright Tock Contributors 2022. //! Hardware-independent kernel interface for deferred calls //! //! This allows any struct in the kernel which implements //! [DeferredCallClient](crate::deferred_ca...
// To reduce monomorphization bloat, the non-generic portion of register is moved into this // function without generic parameters. #[inline(never)] fn register_internal_non_generic(&self, handler: DynDefCallRef<'static>) { // SAFETY: No accesses to DEFCALLS are via an &mut, and the Tock kerne...
{ // SAFETY: No accesses to CTR are via an &mut, and the Tock kernel is // single-threaded so all accesses will occur from this thread. let ctr = unsafe { &CTR }; let idx = ctr.get() + 1; ctr.set(idx); DeferredCall { idx } }
identifier_body
deferred_call.rs
// Licensed under the Apache License, Version 2.0 or the MIT License. // SPDX-License-Identifier: Apache-2.0 OR MIT // Copyright Tock Contributors 2022. //! Hardware-independent kernel interface for deferred calls //! //! This allows any struct in the kernel which implements //! [DeferredCallClient](crate::deferred_ca...
() -> bool { // SAFETY: No accesses to BITMASK are via an &mut, and the Tock kernel is // single-threaded so all accesses will occur from this thread. let bitmask = unsafe { &BITMASK }; bitmask.get()!= 0 } /// This function should be called at the beginning of the kernel loop ...
has_tasks
identifier_name
deferred_call.rs
// Licensed under the Apache License, Version 2.0 or the MIT License. // SPDX-License-Identifier: Apache-2.0 OR MIT // Copyright Tock Contributors 2022. //! Hardware-independent kernel interface for deferred calls //! //! This allows any struct in the kernel which implements //! [DeferredCallClient](crate::deferred_ca...
} }
{ panic!( "ERROR: > 32 deferred calls, or a component forgot to register a deferred call." ); }
conditional_block
deferred_call.rs
// Licensed under the Apache License, Version 2.0 or the MIT License. // SPDX-License-Identifier: Apache-2.0 OR MIT // Copyright Tock Contributors 2022. //! Hardware-independent kernel interface for deferred calls //! //! This allows any struct in the kernel which implements //! [DeferredCallClient](crate::deferred_ca...
DeferredCall { idx } } // To reduce monomorphization bloat, the non-generic portion of register is moved into this // function without generic parameters. #[inline(never)] fn register_internal_non_generic(&self, handler: DynDefCallRef<'static>) { // SAFETY: No accesses to DEFCALLS a...
// SAFETY: No accesses to CTR are via an &mut, and the Tock kernel is // single-threaded so all accesses will occur from this thread. let ctr = unsafe { &CTR }; let idx = ctr.get() + 1; ctr.set(idx);
random_line_split
date.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (chrono) Datelike Timelike ; (format) DATEFILE MMDDhhmm ; (vars) datetime datetimes use chrono::format::{Item,...
{ Date, Seconds, Ns, } impl<'a> From<&'a str> for Rfc3339Format { fn from(s: &str) -> Self { match s { DATE => Self::Date, SECONDS => Self::Seconds, NS => Self::Ns, // Should be caught by clap _ => panic!("Invalid format: {s}"), ...
Rfc3339Format
identifier_name
date.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (chrono) Datelike Timelike ; (format) DATEFILE MMDDhhmm ; (vars) datetime datetimes use chrono::format::{Item,...
Err(USimpleError::new( 1, "setting the date is not supported by macOS".to_string(), )) } #[cfg(target_os = "redox")] fn set_system_datetime(_date: DateTime<Utc>) -> UResult<()> { Err(USimpleError::new( 1, "setting the date is not supported by Redox".to_string(), )) } #[...
random_line_split
workerthread.rs
// Copyright (c) 2015-2016 Linus Färnstrand. // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be co...
Ret> { ptr_0: *mut Ret, offset: isize, } impl<Ret> Iterator for PtrIter<Ret> { type Item = Unique<Ret>; fn next(&mut self) -> Option<Self::Item> { let ptr = unsafe { Unique::new(self.ptr_0.offset(self.offset)) }; self.offset += 1; Some(ptr) } }
trIter<
identifier_name
workerthread.rs
// Copyright (c) 2015-2016 Linus Färnstrand. // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be co...
} ResultReceiver::Channel(channel) => { channel.lock().unwrap().send(value).unwrap(); } } } } #[cfg(feature = "threadstats")] impl<Arg: Send, Ret: Send + Sync> Drop for WorkerThread<Arg, Ret> { fn drop(&mut self) { println!("Worker[{}] (t: {},...
mem::forget(joinbarrier) // Don't drop if we are not last task }
conditional_block
workerthread.rs
// Copyright (c) 2015-2016 Linus Färnstrand. // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be co...
}
let ptr = unsafe { Unique::new(self.ptr_0.offset(self.offset)) }; self.offset += 1; Some(ptr) }
identifier_body
workerthread.rs
// Copyright (c) 2015-2016 Linus Färnstrand. // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be co...
/// Try to steal tasks from the other workers. /// Starts at a random worker and tries every worker until a task is stolen or /// every worker has been tried once. fn try_steal(&mut self) -> Option<Task<Arg,Ret>> { let len = self.other_stealers.len(); let start_victim = self.rng.gen_rang...
} }
random_line_split
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! _Create ridiculously fast Lexers._ //! //! **Logos** has two goals: //! //! + To make it easy to create a Lexer, so you can focus on more complex problems...
#[cfg(doctest)] mod test_readme { macro_rules! external_doc_test { ($x:expr) => { #[doc = $x] extern "C" {} }; } external_doc_test!(include_str!("../../README.md")); }
{ Skip }
identifier_body
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! _Create ridiculously fast Lexers._ //! //! **Logos** has two goals: //! //! + To make it easy to create a Lexer, so you can focus on more complex problems...
<T, E> { /// Emit a token with a given value `T`. Use `()` for unit variants without fields. Emit(T), /// Skip current match, analog to [`Skip`](./struct.Skip.html). Skip, /// Emit a `<Token as Logos>::ERROR` token. Error(E), } /// Predefined callback that will inform the `Lexer` to skip a defi...
FilterResult
identifier_name
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! _Create ridiculously fast Lexers._ //! //! **Logos** has two goals: //! //! + To make it easy to create a Lexer, so you can focus on more complex problems...
} /// Type that can be returned from a callback, either producing a field /// for a token, skipping it, or emitting an error. /// /// # Example /// /// ```rust /// use logos::{Logos, FilterResult}; /// /// #[derive(Debug, PartialEq, Clone, Default)] /// enum LexingError { /// NumberParseError, /// NumberIsTen,...
random_line_split
grid.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! A grid widget use kas::layout::{DynGridStorage, GridCh...
<'a, W: Widget> { list: &'a [(GridChildInfo, W)], } impl<'a, W: Widget> Iterator for ListIter<'a, W> { type Item = &'a (GridChildInfo, W); fn next(&mut self) -> Option<Self::Item> { if let Some((first, rest)) = self.list.split_first() { self.list = rest; Some(first) }...
ListIter
identifier_name
grid.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! A grid widget use kas::layout::{DynGridStorage, GridCh...
else { None } } fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len(); (len, Some(len)) } } impl<'a, W: Widget> ExactSizeIterator for ListIterMut<'a, W> { fn len(&self) -> usize { self.list.len() } }
{ self.list = rest; Some(first) }
conditional_block
grid.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! A grid widget use kas::layout::{DynGridStorage, GridCh...
for (info, child) in &mut self.widgets { solver.for_child(&mut self.data, *info, |axis| { child.size_rules(sizer.re(), axis) }); } solver.finish(&mut self.data) } fn set_rect(&mut self, cx: &mut ConfigCx, rect: Rect...
} fn size_rules(&mut self, sizer: SizeCx, axis: AxisInfo) -> SizeRules { let mut solver = GridSolver::<Vec<_>, Vec<_>, _>::new(axis, self.dim, &mut self.data);
random_line_split
main.rs
extern crate clap; extern crate rust_htslib; extern crate bio; use clap::{Arg, App}; use rust_htslib::bam; use rust_htslib::prelude::*; use bio::io::fasta; #[derive(Clone)] pub struct GenomicInterval { pub tid: u32, pub chrom: String, // chromosome name pub start_pos: u32, // start of interval ...
(bam_file: &String) -> Vec<GenomicInterval> { let bam = bam::Reader::from_path(bam_file).unwrap(); let header_view = bam.header(); let target_names_dec: Vec<&[u8]> = header_view.target_names(); let mut intervals: Vec<GenomicInterval> = vec![]; for (tid, t_name_dec) in target_names_dec.iter().enumer...
get_whole_genome_intervals
identifier_name
main.rs
extern crate clap; extern crate rust_htslib; extern crate bio; use clap::{Arg, App}; use rust_htslib::bam; use rust_htslib::prelude::*; use bio::io::fasta; #[derive(Clone)] pub struct GenomicInterval { pub tid: u32, pub chrom: String, // chromosome name pub start_pos: u32, // start of interval ...
.takes_value(true)) .arg(Arg::with_name("Chrom") .short("C") .long("chrom") .value_name("string") .help("Chromosome to limit analysis to.") .display_order(30) .takes_value(true)) .arg(Arg::with_name("Min coverage") .short("c") .long("min_cov") ...
{ let input_args = App::new("Map Counter") .version("0.1") .author("Peter Edge <edge.peterj@gmail.com>") .about("Given a bam, count the number of positions exceeding a given min coverage and \"well-mapped\" fraction.") .arg(Arg::with_name("Input BAM") .short("b") .long("b...
identifier_body
main.rs
extern crate clap; extern crate rust_htslib; extern crate bio; use clap::{Arg, App}; use rust_htslib::bam; use rust_htslib::prelude::*; use bio::io::fasta; #[derive(Clone)] pub struct GenomicInterval { pub tid: u32, pub chrom: String, // chromosome name pub start_pos: u32, // start of interval ...
} intervals } // given a bam file name and a possible genomic interval, // if the interval exists then just return a vector holding that lone interval // otherwise, if the interval is None, // return a vector holding GenomicIntervals representing the whole genome. pub fn get_interval_lst(bam_file: &String, in...
end_pos: header_view.target_len(tid as u32).unwrap()-1 });
random_line_split
lib.rs
// Copyright (C) 2019 Alibaba Cloud. All rights reserved. // SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause //! Virtio Vhost Backend Drivers //! //! Virtio devices use virtqueues to transport data efficiently. The first generation of virtqueue //! is a set of three different single-producer, single-consumer ring ...
{ /// client exited properly. #[error("client exited properly")] ClientExit, /// client disconnected. /// If connection is closed properly, use `ClientExit` instead. #[error("client closed the connection")] Disconnect, /// Virtio/protocol features mismatch. #[error("virtio features ...
Error
identifier_name
lib.rs
// Copyright (C) 2019 Alibaba Cloud. All rights reserved. // SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause //! Virtio Vhost Backend Drivers //! //! Virtio devices use virtqueues to transport data efficiently. The first generation of virtqueue //! is a set of three different single-producer, single-consumer ring ...
libc::EACCES => Error::SocketConnect(IOError::from_raw_os_error(libc::EACCES)), // Catch all other errors e => Error::SocketError(IOError::from_raw_os_error(e)), } } } /// Result of vhost-user operations pub type Result<T> = std::result::Result<T, Error>; /// Result of...
{ match err.errno() { // Retry: // * EAGAIN, EWOULDBLOCK: The socket is marked nonblocking and the requested operation // would block. // * EINTR: A signal occurred before any data was transmitted // * ENOBUFS: The output queue for a network inte...
identifier_body
lib.rs
// Copyright (C) 2019 Alibaba Cloud. All rights reserved. // SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause //! Virtio Vhost Backend Drivers //! //! Virtio devices use virtqueues to transport data efficiently. The first generation of virtqueue //! is a set of three different single-producer, single-consumer ring ...
} }
{ panic!("invalid error code conversion!"); }
conditional_block
lib.rs
// Copyright (C) 2019 Alibaba Cloud. All rights reserved. // SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause //! Virtio Vhost Backend Drivers //! //! Virtio devices use virtqueues to transport data efficiently. The first generation of virtqueue //! is a set of three different single-producer, single-consumer ring ...
//! virtqueues sharing with a user space process on the same host. It uses communication over a //! Unix domain socket to share file descriptors in the ancillary data of the message. //! The protocol defines 2 sides of the communication, master and slave. Master is the application //! that shares its virtqueues. Slave ...
//! vhost implementation in the Linux kernel. It implements the control plane needed to establish
random_line_split
main.rs
//! CLI tool to use the functions provided by the [wasmstandalone](../wasmstandalone/index.html) //! crate. //! //! Reads Wasm binary files (one Wasm module per file), translates the functions' code to Cretonne //! IL. Can also executes the `start` function of the module by laying out the memories, globals //! and tabl...
(args: &Args, path: PathBuf, name: &str, isa: &TargetIsa) -> Result<(), String> { let mut terminal = term::stdout().unwrap(); terminal.fg(term::color::YELLOW).unwrap(); vprint!(args.flag_verbose, "Handling: "); terminal.reset().unwrap(); vprintln!(args.flag_verbose, "\"{}\"", name); terminal.fg(...
handle_module
identifier_name
main.rs
//! CLI tool to use the functions provided by the [wasmstandalone](../wasmstandalone/index.html) //! crate. //! //! Reads Wasm binary files (one Wasm module per file), translates the functions' code to Cretonne //! IL. Can also executes the `start` function of the module by laying out the memories, globals //! and tabl...
{ let msg = err.to_string(); let str1 = match err.location { AnyEntity::Inst(inst) => { format!( "{}\n{}: {}\n\n", msg, inst, func.dfg.display_inst(inst, isa) ) } _ => String::from(format!("{}\n", msg...
identifier_body
main.rs
//! CLI tool to use the functions provided by the [wasmstandalone](../wasmstandalone/index.html) //! crate. //! //! Reads Wasm binary files (one Wasm module per file), translates the functions' code to Cretonne //! IL. Can also executes the `start` function of the module by laying out the memories, globals //! and tabl...
use cretonne::ir; use cretonne::ir::entities::AnyEntity; use cretonne::isa::TargetIsa; use cretonne::verifier; use cretonne::settings; use std::fs::File; use std::error::Error; use std::io; use std::io::stdout; use std::io::prelude::*; use docopt::Docopt; use std::path::Path; use std::process::{exit, Command}; use temp...
use cretonne::flowgraph::ControlFlowGraph; use cretonne::dominator_tree::DominatorTree; use cretonne::Context; use cretonne::result::CtonError;
random_line_split
lib.rs
//! Interface for interacting with the Wayland protocol, server-side. //! //! ## General concepts //! //! This crate is structured around four main objects: the [`Display`] and [`DisplayHandle`] structs, //! resources (objects implementing the [`Resource`] trait), and the [`Dispatch`] trait. //! //! The [`Display`] is ...
/// wayland-scanner. fn write_event( &self, dh: &DisplayHandle, req: Self::Event, ) -> Result<Message<ObjectId, std::os::unix::io::RawFd>, InvalidId>; /// Creates a weak handle to this object /// /// This weak handle will not keep the user-data associated with the object...
) -> Result<(Self, Self::Request), DispatchError>; /// Serialize an event for this object /// /// **Note:** This method is mostly meant as an implementation detail to be used by code generated by
random_line_split
lib.rs
//! Interface for interacting with the Wayland protocol, server-side. //! //! ## General concepts //! //! This crate is structured around four main objects: the [`Display`] and [`DisplayHandle`] structs, //! resources (objects implementing the [`Resource`] trait), and the [`Dispatch`] trait. //! //! The [`Display`] is ...
} } } /// A weak handle to a Wayland object /// /// This handle does not keep the underlying user data alive, and can be converted back to a full resource /// using [`Weak::upgrade()`]. #[derive(Debug, Clone)] pub struct Weak<I> { handle: WeakHandle, id: ObjectId, _iface: std::marker::PhantomD...
{ write!(f, "Bad message for object {interface}@{sender_id} on opcode {opcode}",) }
conditional_block
lib.rs
//! Interface for interacting with the Wayland protocol, server-side. //! //! ## General concepts //! //! This crate is structured around four main objects: the [`Display`] and [`DisplayHandle`] structs, //! resources (objects implementing the [`Resource`] trait), and the [`Dispatch`] trait. //! //! The [`Display`] is ...
(&self) -> bool { if let Some(handle) = self.handle().upgrade() { handle.object_info(self.id()).is_ok() } else { false } } /// Access the user-data associated with this object fn data<U:'static>(&self) -> Option<&U>; /// Access the raw data associated wi...
is_alive
identifier_name
player_vlc.rs
use crate::player::{Player, Result, SlideshowConfig}; use elementtree::Element; use failure::{format_err, Fail}; use libc; use log::{debug, info, warn}; use reqwest; use std::path::PathBuf; use std::process::Child; use std::process::Command; use std::time::Duration; use std::time::Instant; use url::Url; const VLC_VOLU...
(&self) -> bool { match self.send_status_cmd("", &[]) { Ok(_) => true, Err(e) => { debug!("Got error response while checking health of VLC: {}", e); false } } } } impl<C: HttpClient> Drop for VlcPlayer<C> { fn drop(&mut self) {...
is_ok
identifier_name
player_vlc.rs
use crate::player::{Player, Result, SlideshowConfig}; use elementtree::Element; use failure::{format_err, Fail}; use libc; use log::{debug, info, warn}; use reqwest; use std::path::PathBuf; use std::process::Child; use std::process::Command; use std::time::Duration; use std::time::Instant; use url::Url; const VLC_VOLU...
} impl<C: HttpClient> Drop for VlcPlayer<C> { fn drop(&mut self) { if let Some(mut proc) = self.process.take() { // Rust's Command doesn't support other than SIGKILL in portable interface unsafe { libc::kill(proc.id() as i32, libc::SIGTERM); } ...
{ match self.send_status_cmd("", &[]) { Ok(_) => true, Err(e) => { debug!("Got error response while checking health of VLC: {}", e); false } } }
identifier_body
player_vlc.rs
use crate::player::{Player, Result, SlideshowConfig}; use elementtree::Element; use failure::{format_err, Fail}; use libc; use log::{debug, info, warn}; use reqwest; use std::path::PathBuf; use std::process::Child; use std::process::Command; use std::time::Duration; use std::time::Instant; use url::Url; const VLC_VOLU...
fn dummy_bin_player< C: Fn(&str, &HashMap<&str, &str>) -> std::result::Result<String, VlcError>, >( client: C, ) -> (tempfile::NamedTempFile, VlcPlayer<C>) { let mut dummy_bin = tempfile::NamedTempFile::new().unwrap(); let file = dummy_bin.as_file_mut(); writeln!(file...
random_line_split
player_vlc.rs
use crate::player::{Player, Result, SlideshowConfig}; use elementtree::Element; use failure::{format_err, Fail}; use libc; use log::{debug, info, warn}; use reqwest; use std::path::PathBuf; use std::process::Child; use std::process::Command; use std::time::Duration; use std::time::Instant; use url::Url; const VLC_VOLU...
} } #[cfg(test)] mod tests { use super::*; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::fs; use std::io::Write; use std::os::unix::fs::PermissionsExt; use tempfile; impl<F: Fn(&str, &HashMap<&str, &str>) -> std::result::Result<String, VlcError>> HttpClie...
{ // Rust's Command doesn't support other than SIGKILL in portable interface unsafe { libc::kill(proc.id() as i32, libc::SIGTERM); } match proc.wait() { Ok(status) => debug!("VLC process exit with {}", status.code().unwrap_or(-1)), ...
conditional_block
ipc.rs
//! IPC Transport for *nix #[cfg(unix)] extern crate tokio_uds; use std::collections::BTreeMap; use std::io::{self, Read, Write}; use std::path::Path; use std::sync::{atomic, Arc}; #[cfg(unix)] use self::tokio_uds::UnixStream; use crate::api::SubscriptionId; use crate::helpers; use crate::rpc; use crate::transports...
<T>(&self, requests: T) -> Self::Batch where T: IntoIterator<Item = (RequestId, rpc::Call)>, { let mut it = requests.into_iter(); let (id, first) = it.next().map(|x| (x.0, Some(x.1))).unwrap_or_else(|| (0, None)); let requests = first.into_iter().chain(it.map(|x| x.1)).collect();...
send_batch
identifier_name
ipc.rs
//! IPC Transport for *nix #[cfg(unix)] extern crate tokio_uds; use std::collections::BTreeMap; use std::io::{self, Read, Write}; use std::path::Path; use std::sync::{atomic, Arc}; #[cfg(unix)] use self::tokio_uds::UnixStream; use crate::api::SubscriptionId; use crate::helpers; use crate::rpc; use crate::transports...
else { log::warn!("Got unsupported response (id: {:?})", id); } } Message::Notification(notification) => { if let rpc::Params::Map(params) = notification.params { let id = params.get("subscription"); let...
{ if let Some(request) = self.pending.lock().remove(&(num as usize)) { log::trace!("Responding to (id: {:?}) with {:?}", num, outputs); if let Err(err) = request.send(helpers::to_results_from_outputs(outputs)) { log::warn!("...
conditional_block
ipc.rs
//! IPC Transport for *nix #[cfg(unix)] extern crate tokio_uds; use std::collections::BTreeMap; use std::io::{self, Read, Write}; use std::path::Path; use std::sync::{atomic, Arc}; #[cfg(unix)] use self::tokio_uds::UnixStream; use crate::api::SubscriptionId; use crate::helpers; use crate::rpc; use crate::transports...
fn unsubscribe(&self, id: &SubscriptionId) { self.subscriptions.lock().remove(id); } } enum WriteState { WaitingForRequest, Writing { buffer: Vec<u8>, current_pos: usize }, } /// Writing part of the IPC transport /// Awaits new requests using `mpsc::UnboundedReceiver` and writes them to the ...
{ let (tx, rx) = mpsc::unbounded(); if self.subscriptions.lock().insert(id.clone(), tx).is_some() { log::warn!("Replacing already-registered subscription with id {:?}", id) } Box::new(rx.map_err(|()| Error::Transport("No data available".into()))) }
identifier_body
ipc.rs
//! IPC Transport for *nix #[cfg(unix)] extern crate tokio_uds; use std::collections::BTreeMap; use std::io::{self, Read, Write}; use std::path::Path; use std::sync::{atomic, Arc}; #[cfg(unix)] use self::tokio_uds::UnixStream; use crate::api::SubscriptionId; use crate::helpers; use crate::rpc; use crate::transports...
let requests = first.into_iter().chain(it.map(|x| x.1)).collect(); self.send_request(id, rpc::Request::Batch(requests), Ok) } } impl DuplexTransport for Ipc { type NotificationStream = Box<dyn Stream<Item = rpc::Value, Error = Error> + Send +'static>; fn subscribe(&self, id: &SubscriptionI...
where T: IntoIterator<Item = (RequestId, rpc::Call)>, { let mut it = requests.into_iter(); let (id, first) = it.next().map(|x| (x.0, Some(x.1))).unwrap_or_else(|| (0, None));
random_line_split
mod.rs
unsafe { slice::from_raw_parts(list.values, list_len) } .iter() .zip(unsafe { slice::from_raw_parts(set.ds, ds_len) }) .map(|(val, source)| unsafe { let v = match ::std::mem::transmute(source.type_) { ValueType::Gauge => ...
random_line_split
mod.rs
x.is_nan() } else { false } } } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Value::Counter(x) | Value::Absolute(x) => write!(f, "{}", x), Value::Gauge(x) => write!(f, "{}", x), ...
/// The interval in which new values are to be expected. This is typically handled at a global /// or plugin level. Use at your own discretion. pub fn interval(mut self, interval: Duration) -> ValueListBuilder<'a> { self.list.interval = Some(interval); self } /// Add a metadata en...
{ self.list.time = Some(dt); self }
identifier_body
mod.rs
x.is_nan() } else { false } } } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Value::Counter(x) | Value::Absolute(x) => write!(f, "{}", x), Value::Gauge(x) => write!(f, "{}", x), ...
<'a> { /// Name of the metric. If values has a length of 1, this is often just "value" pub name: &'a str, /// The value reported pub value: Value, /// Minimum value seen in an interval pub min: f64, /// Maximum value seen in an interval pub max: f64, } /// Contains values and metadat...
ValueReport
identifier_name
main.rs
// bin2src - convert a binary file to source code in various languages // // Copyright (C) 2020 Alexandre Gomiero de Oliveira // // MIT License // // Copyright (c) 2020-2021 Alexandre Gomiero de Oliveira // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and assoc...
} pub fn generate(&mut self) -> Result<(), &'static str> { // Test for input file let (ifname, ifpath, ifsize) = self.input_file_test()?; // Test for output dir let ofpath: PathBuf = self.output_dir_test()?; let go = GeneratorOutput { ...
{ Ok(ofpath) }
conditional_block
main.rs
// bin2src - convert a binary file to source code in various languages // // Copyright (C) 2020 Alexandre Gomiero de Oliveira // // MIT License // // Copyright (c) 2020-2021 Alexandre Gomiero de Oliveira // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and assoc...
{ pub input_file: String, pub output_file: String, pub output_dir: String, pub lang: Lang, pub hex: bool, } impl GeneratorInput { fn input_file_test(&mut self) -> Result<(String, PathBuf, u64), &'static str> { let ifpath: PathBuf = PathBuf::from(&sel...
GeneratorInput
identifier_name
main.rs
// bin2src - convert a binary file to source code in various languages // // Copyright (C) 2020 Alexandre Gomiero de Oliveira // // MIT License // // Copyright (c) 2020-2021 Alexandre Gomiero de Oliveira // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and assoc...
_ => "", }; } fn get_args_as_strings() -> Result<Vec<String>, &'static str> { let mut ret: Vec<String> = Vec::new(); let args = env::args_os(); for cmd in args { ret.push(match cmd.into_string() { Ok(c) => c, _ => return Err("Invalid unicode character found"), ...
match parse_result.generate() { Err(e) => panic!("Generator error: {}", e),
random_line_split
value.rs
//! Types representing for data which will be retrieved from the driver. //! Currently this data is expected to look like a JSON object but this may be //! changed in the future. Driver authors must cast the data they retrieve from
use serde::de::{Deserialize, Deserializer, Error as DeError, Visitor, SeqVisitor, MapVisitor}; use serde::de::impls::VecVisitor; use serde_json; use error::Error; /// The type which represents the key for maps used throughout the Ardite /// codebase. /// /// Functions similarly to an object key in JavaScript. pub typ...
//! the driver to these types. use linear_map::LinearMap; use serde::ser::{Serialize, Serializer};
random_line_split
value.rs
//! Types representing for data which will be retrieved from the driver. //! Currently this data is expected to look like a JSON object but this may be //! changed in the future. Driver authors must cast the data they retrieve from //! the driver to these types. use linear_map::LinearMap; use serde::ser::{Serialize, S...
#[test] fn test_to_json_pretty() { assert_eq!( &value!(["world", 3.333, { "hello" => "world" }, (), (), [1, 2, 3], ()]).to_json_pretty().unwrap(), "[\n \"world\",\n 3.333,\n {\n \"hello\": \"world\"\n },\n null,\n null,\n [\n 1,\n 2,\n 3\n ],\n null\n]" ); } }
{ assert_eq!(&value!().to_json().unwrap(), "null"); assert_eq!(&value!(true).to_json().unwrap(), "true"); assert_eq!(&value!(false).to_json().unwrap(), "false"); assert_eq!(&value!(7).to_json().unwrap(), "7"); assert_eq!(&value!(6.667).to_json().unwrap(), "6.667"); assert_eq!(&value!("Hello,\n\"...
identifier_body
value.rs
//! Types representing for data which will be retrieved from the driver. //! Currently this data is expected to look like a JSON object but this may be //! changed in the future. Driver authors must cast the data they retrieve from //! the driver to these types. use linear_map::LinearMap; use serde::ser::{Serialize, S...
() { assert_eq!(value!().get(point![]).cloned(), Some(value!())); assert_eq!(value!().get(point!["hello"]).cloned(), None); assert_eq!(value!().get(point!["a", "b", "c", "d", "e"]).cloned(), None); assert_eq!(value!(true).get(point![]).cloned(), Some(value!(true))); assert_eq!(value!(true).get(point...
test_get_primitive
identifier_name
balloon.rs
#[error("Fallocate fail.: {0}")] FallocateFail(std::io::Error), #[error("Madvise fail.: {0}")] MadviseFail(std::io::Error), #[error("Failed to EventFd write.: {0}")] EventFdWriteFail(std::io::Error), #[error("Invalid queue index: {0}")] InvalidQueueIndex(usize), #[error("Fail tp sign...
(&mut self, addr: u64) { let addr_offset = (addr % self.page_size) >> VIRTIO_BALLOON_PFN_SHIFT; self.bitmap[(addr_offset / 64) as usize] |= 1 << (addr_offset % 64); } fn reset(&mut self) { let len = ((self.page_size >> VIRTIO_BALLOON_PFN_SHIFT) + 63) / 64; self.addr = 0; ...
set_bit
identifier_name
balloon.rs
#[error("Fallocate fail.: {0}")] FallocateFail(std::io::Error), #[error("Madvise fail.: {0}")] MadviseFail(std::io::Error), #[error("Failed to EventFd write.: {0}")] EventFdWriteFail(std::io::Error), #[error("Invalid queue index: {0}")] InvalidQueueIndex(usize), #[error("Fail tp sign...
1 => { let page_size = get_page_size() as usize; let rbase = align_page_size_down((pfn as u64) << VIRTIO_BALLOON_PFN_SHIFT); Self::advise_memory_range( desc_chain.memory(), ...
{ Self::release_memory_range_4k(&mut self.pbp, desc_chain.memory(), pfn)?; }
conditional_block
balloon.rs
// SAFETY: FFI call with valid arguments let res = unsafe { libc::fallocate64( f_off.file().as_raw_fd(), libc::FALLOC_FL_PUNCH_HOLE | libc::FALLOC_FL_KEEP_SIZE, (offset + f_off.start()) as libc::off64_t, r...
fn resume(&mut self) -> result::Result<(), MigratableError> {
random_line_split
utility.rs
//! General-purpose utility functions for internal usage within this crate. use crate::derive_data::{ReflectMeta, StructField}; use crate::field_attributes::ReflectIgnoreBehavior; use crate::fq_std::{FQAny, FQOption, FQSend, FQSync}; use bevy_macro_utils::BevyManifest; use bit_set::BitSet; use proc_macro2::{Ident, Spa...
; (ty, bounds) }) .unzip(); let (ignored_types, ignored_trait_bounds): (Vec<_>, Vec<_>) = ignored_fields .map(|field| { let ty = field.data.ty.clone(); let custom_bounds = ignored_bounds(field).map(|bounds| quote!(+ #bounds)); ...
{ quote!(#bevy_reflect_path::Reflect #custom_bounds) }
conditional_block
utility.rs
//! General-purpose utility functions for internal usage within this crate. use crate::derive_data::{ReflectMeta, StructField}; use crate::field_attributes::ReflectIgnoreBehavior; use crate::fq_std::{FQAny, FQOption, FQSend, FQSync}; use bevy_macro_utils::BevyManifest; use bit_set::BitSet; use proc_macro2::{Ident, Spa...
/// [constant]: StringExpr::Const pub fn from_str(string: &str) -> Self { Self::Const(string.into_token_stream()) } /// Returns tokens for an [owned string](String). /// /// The returned expression will allocate unless the [`StringExpr`] is [already owned]. /// /// [already owne...
} /// Creates a [constant] [`StringExpr`] by interpreting a [string slice][str] as a [`struct@LitStr`]. ///
random_line_split
utility.rs
//! General-purpose utility functions for internal usage within this crate. use crate::derive_data::{ReflectMeta, StructField}; use crate::field_attributes::ReflectIgnoreBehavior; use crate::fq_std::{FQAny, FQOption, FQSend, FQSync}; use bevy_macro_utils::BevyManifest; use bit_set::BitSet; use proc_macro2::{Ident, Spa...
/// Appends a [`StringExpr`] to another. /// /// If both expressions are [`StringExpr::Const`] this will use [`concat`] to merge them. pub fn appended_by(mut self, other: StringExpr) -> Self { if let Self::Const(tokens) = self { if let Self::Const(more) = other { re...
{ match self { Self::Const(tokens) | Self::Borrowed(tokens) => tokens, Self::Owned(owned) => quote! { &#owned }, } }
identifier_body
utility.rs
//! General-purpose utility functions for internal usage within this crate. use crate::derive_data::{ReflectMeta, StructField}; use crate::field_attributes::ReflectIgnoreBehavior; use crate::fq_std::{FQAny, FQOption, FQSend, FQSync}; use bevy_macro_utils::BevyManifest; use bit_set::BitSet; use proc_macro2::{Ident, Spa...
( where_clause: Option<&WhereClause>, where_clause_options: &WhereClauseOptions, ) -> proc_macro2::TokenStream { let parameter_types = &where_clause_options.parameter_types; let active_types = &where_clause_options.active_types; let ignored_types = &where_clause_options.ignored_types; let parame...
extend_where_clause
identifier_name
main.rs
extern crate argparse; extern crate chrono; extern crate colored; extern crate rand; extern crate serde; extern crate serde_json; extern crate time; #[macro_use] extern crate serde_derive; use argparse::{ArgumentParser, Store, StoreOption}; use rand::Rng; use std::fs::File; use std::fs::OpenOptions; use std::io::BufR...
"Task: {} {} | {} | {} {}", self.id, priority_str, self.task.bold(), status_str, deadline_str ) } } const DATA_FOLDER: &str = ".todo.d"; const DATA_FILENAME: &str = "data.json"; const NOUNS_FILENAME: &str = "nouns.txt"; fn data_fo...
format!(
random_line_split
main.rs
extern crate argparse; extern crate chrono; extern crate colored; extern crate rand; extern crate serde; extern crate serde_json; extern crate time; #[macro_use] extern crate serde_derive; use argparse::{ArgumentParser, Store, StoreOption}; use rand::Rng; use std::fs::File; use std::fs::OpenOptions; use std::io::BufR...
(task: String, priority: u8, deadline_vague: &Option<VagueTime>) { let mut data = load_data_catch(); let id = pick_name(&data); println!("Adding {} - '{}'", id, task); let deadline = deadline_vague.as_ref().map(|x| x.concretise()); let new_entry = Entry::new(id, task, priority, deadline); data...
do_add
identifier_name
linker.rs
use crate::{ Extern, ExternType, Func, FuncType, GlobalType, ImportType, Instance, IntoFunc, Module, Store, }; use anyhow::{anyhow, bail, Result}; use std::collections::hash_map::{Entry, HashMap}; use std::rc::Rc; /// Structure used to link wasm modules/instances together. /// /// This structure is used to assist ...
/// ``` /// # use wasmtime::*; /// # fn main() -> anyhow::Result<()> { /// # let store = Store::default(); /// let mut linker = Linker::new(&store); /// linker.func("host", "double", |x: i32| x * 2)?; /// linker.func("host", "log_i32", |x: i32| println!("{}", x))?; /// linker.func("host"...
/// # Examples ///
random_line_split
linker.rs
use crate::{ Extern, ExternType, Func, FuncType, GlobalType, ImportType, Instance, IntoFunc, Module, Store, }; use anyhow::{anyhow, bail, Result}; use std::collections::hash_map::{Entry, HashMap}; use std::rc::Rc; /// Structure used to link wasm modules/instances together. /// /// This structure is used to assist ...
(&mut self, module: &str, name: &str, ty: ExternType) -> ImportKey { ImportKey { module: self.intern_str(module), name: self.intern_str(name), kind: self.import_kind(ty), } } fn import_kind(&self, ty: ExternType) -> ImportKind { match ty { ...
import_key
identifier_name
linker.rs
use crate::{ Extern, ExternType, Func, FuncType, GlobalType, ImportType, Instance, IntoFunc, Module, Store, }; use anyhow::{anyhow, bail, Result}; use std::collections::hash_map::{Entry, HashMap}; use std::rc::Rc; /// Structure used to link wasm modules/instances together. /// /// This structure is used to assist ...
/// Aliases one module's name as another. /// /// This method will alias all currently defined under `module` to also be /// defined under the name `as_module` too. /// /// # Errors /// /// Returns an error if any shadowing violations happen while defining new /// items. pub fn...
{ if !Store::same(&self.store, instance.store()) { bail!("all linker items must be from the same store"); } for export in instance.exports() { self.insert(module_name, export.name(), export.into_extern())?; } Ok(self) }
identifier_body
lib.rs
//! # Acteur Actor System //! //! An safe & opinionated actor-like framework written in Rust that just works. Simple, robust, fast, documented. //! //!<div align="center"> //! <!-- Crates version --> //! <a href="https://crates.io/crates/acteur"> //! <img src="https://img.shields.io/crates/v/acteur.svg?style=fl...
//! //! ## Subscription or Pub/Sub //! //! Sometime we don't want to know who should receive the message but to subscribe to a type and wait. //! Acteur models the Pub/Sub patter with Services. Actors in Acteur can't perform subscriptions as //! that would require the framework to know all possible IDs of all possible ...
//! calculations of some sort that doesn't belong to any Actor, etc) and for subscribing to messages (Pub/Sub)
random_line_split
progress.rs
use num_enum::IntoPrimitive; use once_cell::sync::Lazy; use std::sync::mpsc::Sender; use std::{mem, pin::Pin, ptr}; use wchar::*; use widestring::*; use winapi::shared::basetsd; use winapi::shared::minwindef as win; use winapi::shared::windef::*; use winapi::um::commctrl; use winapi::um::errhandlingapi; use winapi::um:...
/// Signal that progress should be cancelled. pub fn cancel(&self) { if let Some(tx) = &self.cancel_sender { tx.send(()).unwrap_or_else(|_| { log::error!("Failed to send cancel signal"); }); } } /// Close main window. pub fn close(&self) { ...
random_line_split