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
model.rs
//! Defines the `JsonApiModel` trait. This is primarily used in conjunction with //! the [`jsonapi_model!`](../macro.jsonapi_model.html) macro to allow arbitrary //! structs which implement `Deserialize` to be converted to/from a //! [`JsonApiDocument`](../api/struct.JsonApiDocument.html) or //! [`Resource`](../api/str...
fn relationship_fields() -> Option<&'static [&'static str]> { M::relationship_fields() } fn build_relationships(&self) -> Option<Relationships> { self.as_ref().build_relationships() } fn build_included(&self) -> Option<Resources> { self.as_ref().build_included() } } ...
{ self.as_ref().jsonapi_id() }
identifier_body
model.rs
//! Defines the `JsonApiModel` trait. This is primarily used in conjunction with //! the [`jsonapi_model!`](../macro.jsonapi_model.html) macro to allow arbitrary //! structs which implement `Deserialize` to be converted to/from a //! [`JsonApiDocument`](../api/struct.JsonApiDocument.html) or //! [`Resource`](../api/str...
(&self) -> Resources { let (me, maybe_others) = self.to_jsonapi_resource(); let mut flattened = vec![me]; if let Some(mut others) = maybe_others { flattened.append(&mut others); } flattened } /// When passed a `ResourceIdentifier` (which contains a `type` and...
to_resources
identifier_name
lib.rs
extern crate rand; use rand::{thread_rng, RngCore}; #[cfg(test)] mod tests { use super::SecretData; #[test] fn it_works() {} #[test] fn it_generates_coefficients() { let secret_data = SecretData::with_secret("Hello, world!", 3); assert_eq!(secret_data.coefficients.len(), 13); ...
} static GF256_EXP: [u8; 256] = [ 0x01, 0x03, 0x05, 0x0f, 0x11, 0x33, 0x55, 0xff, 0x1a, 0x2e, 0x72, 0x96, 0xa1, 0xf8, 0x13, 0x35, 0x5f, 0xe1, 0x38, 0x48, 0xd8, 0x73, 0x95, 0xa4, 0xf7, 0x02, 0x06, 0x0a, 0x1e, 0x22, 0x66, 0xaa, 0xe5, 0x34, 0x5c, 0xe4, 0x37, 0x59, 0xeb, 0x26, 0x6a, 0xbe, 0xd9, 0x70, 0x90, 0x...
{ let mut a = a.to_owned(); let mut b = b.to_owned(); if a.len() < b.len() { let mut t = vec![0; b.len() - a.len()]; a.append(&mut t); } else if a.len() > b.len() { let mut t = vec![0; a.len() - b.len()]; b.append(&mut t); } ...
identifier_body
lib.rs
extern crate rand; use rand::{thread_rng, RngCore}; #[cfg(test)] mod tests { use super::SecretData; #[test] fn it_works() {} #[test] fn it_generates_coefficients() { let secret_data = SecretData::with_secret("Hello, world!", 3); assert_eq!(secret_data.coefficients.len(), 13); ...
} #[test] fn it_can_recover_secret() { let s1 = vec![1, 184, 190, 251, 87, 232, 39, 47, 17, 4, 36, 190, 245]; let s2 = vec![2, 231, 107, 52, 138, 34, 221, 9, 221, 67, 79, 33, 16]; let s3 = vec![3, 23, 176, 163, 177, 165, 218, 113, 163, 53, 7, 251, 196]; let new_secret = Sec...
assert!(secret_data.is_valid_share(&s1)); let s2 = secret_data.get_share(1).unwrap(); assert_eq!(s1, s2);
random_line_split
lib.rs
extern crate rand; use rand::{thread_rng, RngCore}; #[cfg(test)] mod tests { use super::SecretData; #[test] fn it_works() {} #[test] fn it_generates_coefficients() { let secret_data = SecretData::with_secret("Hello, world!", 3); assert_eq!(secret_data.coefficients.len(), 13); ...
{ /// The number of shares must be between 1 and 255 InvalidShareCount, } impl SecretData { pub fn with_secret(secret: &str, threshold: u8) -> SecretData { let mut coefficients: Vec<Vec<u8>> = vec![]; let mut rng = thread_rng(); let mut rand_container = vec![0u8; (threshold - 1) as...
ShamirError
identifier_name
pagerank.rs
use super::super::{ Network, NodeId }; /// Runs pagerank algorithm on a graph until convergence. /// Convergence is reached, when the last ranks vector and the new one /// differ by less than `eps` in their L1-norm. /// `beta` is the teleport probability. CAUTION: Never use a teleport /// probability of `beta == 0.0`...
/// Determines convergence for two vectors with respect to the tolerance. fn is_converged(old: &Vec<f64>, new: &Vec<f64>, eps: f64) -> bool { assert!(old.len() == new.len()); let mut sum = 0.0; for i in 0..old.len() { sum += (old[i] - new[i]).powi(2); } println!("{:e} ({:e})", sum.sqrt(), ...
{ let mut new_ranks = vec![0.0; current.len()]; for source_node in 0..current.len() { let inv_out_deg = inv_out_degs[source_node]; for target_node in &adj_list[source_node] { new_ranks[*target_node] += (1.0-beta) * inv_out_deg * current[source_node]; } } new_ranks }
identifier_body
pagerank.rs
use super::super::{ Network, NodeId }; /// Runs pagerank algorithm on a graph until convergence. /// Convergence is reached, when the last ranks vector and the new one /// differ by less than `eps` in their L1-norm. /// `beta` is the teleport probability. CAUTION: Never use a teleport /// probability of `beta == 0.0`...
(0,3,0.0,0.0), (1,2,0.0,0.0), (1,3,0.0,0.0), (2,0,0.0,0.0), (3,0,0.0,0.0), (3,2,0.0,0.0)]; let compact_star = compact_star_from_edge_vec(4, &mut edges); assert_eq!(vec![1.0/3.0, 1.0/2.0, 1.0/1.0, 1.0/2.0], inv_out_deg(&compact_star)); } #[test] fn test_build_adj_...
random_line_split
pagerank.rs
use super::super::{ Network, NodeId }; /// Runs pagerank algorithm on a graph until convergence. /// Convergence is reached, when the last ranks vector and the new one /// differ by less than `eps` in their L1-norm. /// `beta` is the teleport probability. CAUTION: Never use a teleport /// probability of `beta == 0.0`...
<N: Network>(network: &N) -> Vec<f64> { let mut inv_out_deg = Vec::with_capacity(network.num_nodes()); for i in 0..network.num_nodes() { let out_deg = network.adjacent(i as NodeId).len() as f64; if out_deg > 0.0 { inv_out_deg.push(1.0 / out_deg); } else { inv_out_...
inv_out_deg
identifier_name
pagerank.rs
use super::super::{ Network, NodeId }; /// Runs pagerank algorithm on a graph until convergence. /// Convergence is reached, when the last ranks vector and the new one /// differ by less than `eps` in their L1-norm. /// `beta` is the teleport probability. CAUTION: Never use a teleport /// probability of `beta == 0.0`...
} inv_out_deg } /// Converts the network in a slightly faster traversable adjacency list. fn build_adj_list<N: Network>(network: &N) -> Vec<Vec<usize>> { let mut adj_list = Vec::with_capacity(network.num_nodes()); for i in 0..network.num_nodes() { let adj_nodes = network.adjacent(i as NodeId);...
{ inv_out_deg.push(0.0); }
conditional_block
acceptance_tests.rs
#![cfg(test)] #[macro_use] extern crate lazy_static; mod acceptance { use std::process::{Command, Output}; fn run_tests() -> Output { Command::new("cargo") .args(&["test", "test_cases"]) .output() .expect("cargo command failed to start") } lazy_static! { ...
#[test] fn marks_inconclusive_tests_as_ignored() { assert!(actual().contains("test test_cases::inconclusive_tests::should_not_take_into_account_keyword_on_argument_position... ok")); assert!(actual().contains("test test_cases::inconclusive_tests::this_test_is_inconclusive_and_will_always_be......
{ assert!(actual().contains("test test_cases::lowercase_test_name::dummy_code ... ok")); }
identifier_body
acceptance_tests.rs
#![cfg(test)] #[macro_use] extern crate lazy_static; mod acceptance { use std::process::{Command, Output}; fn run_tests() -> Output { Command::new("cargo") .args(&["test", "test_cases"]) .output() .expect("cargo command failed to start") } lazy_static! { ...
} #[test] fn escapes_names_starting_with_digit() { assert!(actual().contains("test test_cases::basic_test::_1... ok")); } #[test] fn removes_repeated_underscores() { assert!(actual().contains("test test_cases::arg_expressions::_2_4_6_to_string... ok")); } #[test] f...
random_line_split
acceptance_tests.rs
#![cfg(test)] #[macro_use] extern crate lazy_static; mod acceptance { use std::process::{Command, Output}; fn run_tests() -> Output { Command::new("cargo") .args(&["test", "test_cases"]) .output() .expect("cargo command failed to start") } lazy_static! { ...
() { assert!(actual().contains("test test_cases::basic_test::_1... ok")); } #[test] fn removes_repeated_underscores() { assert!(actual().contains("test test_cases::arg_expressions::_2_4_6_to_string... ok")); } #[test] fn escapes_rust_keywords() { assert!(actual().contai...
escapes_names_starting_with_digit
identifier_name
lib.rs
use std::collections::VecDeque; use std::char; macro_rules! try_option { ($o:expr) => { match $o { Some(s) => s, None => return None, } } } // Takes in a string with backslash escapes written out with literal backslash characters and // converts it to a string with the...
(c: char, queue: &mut VecDeque<char>) -> Option<char> { match unescape_octal_leading(c, queue) { Some(ch) => { let _ = queue.pop_front(); let _ = queue.pop_front(); Some(ch) } None => unescape_octal_no_leading(c, queue) } } fn unescape_octal_leading(c...
unescape_octal
identifier_name
lib.rs
use std::collections::VecDeque; use std::char; macro_rules! try_option { ($o:expr) => { match $o { Some(s) => s, None => return None, } } } // Takes in a string with backslash escapes written out with literal backslash characters and // converts it to a string with the...
}
char::from_u32(u)
random_line_split
lib.rs
use std::collections::VecDeque; use std::char; macro_rules! try_option { ($o:expr) => { match $o { Some(s) => s, None => return None, } } } // Takes in a string with backslash escapes written out with literal backslash characters and // converts it to a string with the...
fn unescape_octal(c: char, queue: &mut VecDeque<char>) -> Option<char> { match unescape_octal_leading(c, queue) { Some(ch) => { let _ = queue.pop_front(); let _ = queue.pop_front(); Some(ch) } None => unescape_octal_no_leading(c, queue) } } fn unesc...
{ let mut s = String::new(); for _ in 0..2 { s.push(try_option!(queue.pop_front())); } let u = try_option!(u32::from_str_radix(&s, 16).ok()); char::from_u32(u) }
identifier_body
seg_queue.rs
use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::{ptr, mem}; use std::cmp; use std::cell::UnsafeCell; use mem::epoch::{self, Atomic, Owned}; const SEG_SIZE: usize = 32; /// A Michael-Scott queue that allocates "segments" (arrays of nodes) /// fo...
for _i in 0..CONC_COUNT { match q.pop() { Some(LR::Left(x)) => vl.push(x), Some(LR::Right(x)) => vr.push(x), _ => {} } } let mu...
{ enum LR { Left(i64), Right(i64) } let q: SegQueue<LR> = SegQueue::new(); scope(|scope| { for _t in 0..2 { scope.spawn(|| { for i in CONC_COUNT-1..CONC_COUNT { q.push(LR::Left(i)) } });...
identifier_body
seg_queue.rs
use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::{ptr, mem}; use std::cmp; use std::cell::UnsafeCell; use mem::epoch::{self, Atomic, Owned}; const SEG_SIZE: usize = 32; /// A Michael-Scott queue that allocates "segments" (arrays of nodes) /// fo...
} } let mut vl2 = vl.clone(); let mut vr2 = vr.clone(); vl2.sort(); vr2.sort(); assert_eq!(vl, vl2); assert_eq!(vr, vr2); }); ...
{}
conditional_block
seg_queue.rs
use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::{ptr, mem}; use std::cmp; use std::cell::UnsafeCell; use mem::epoch::{self, Atomic, Owned}; const SEG_SIZE: usize = 32; /// A Michael-Scott queue that allocates "segments" (arrays of nodes) /// fo...
() { let q: SegQueue<i64> = SegQueue::new(); q.push(37); q.push(48); assert_eq!(q.pop(), Some(37)); assert_eq!(q.pop(), Some(48)); } #[test] fn push_pop_many_seq() { let q: SegQueue<i64> = SegQueue::new(); for i in 0..200 { q.push(i) ...
push_pop_2
identifier_name
seg_queue.rs
use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::{ptr, mem}; use std::cmp; use std::cell::UnsafeCell; use mem::epoch::{self, Atomic, Owned}; const SEG_SIZE: usize = 32; /// A Michael-Scott queue that allocates "segments" (arrays of nodes) /// fo...
next: Atomic::null(), } } } impl<T> SegQueue<T> { /// Create a enw, emtpy queue. pub fn new() -> SegQueue<T> { let q = SegQueue { head: Atomic::null(), tail: Atomic::null(), }; let sentinel = Owned::new(Segment::new()); let guard =...
low: AtomicUsize::new(0), high: AtomicUsize::new(0),
random_line_split
mod.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> mod font_options; mod font_face; mod scaled_font; pub use ffi::enums::{ Antialias, S...
Allocates an array of cairo_glyph_t's. This function is only useful in implementations of cairo_user_scaled_font_text_to_glyphs_func_t where the user needs to allocate an array of glyphs that cairo will free. For all other uses, user can use their own allocation method for glyphs. impl TextCluster { //pub fn c...
random_line_split
kindck-owned-trait-scoped.rs
// xfail-test // xfail'd because to_foo() doesn't work. // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/lic...
fn to_foo_3<T:Clone +'static>(t: T) -> @foo { // OK---T may escape as part of the returned foo value, but it is // owned and hence does not contain borrowed ptrs struct F<T> { f: T } @F {f:t} as @foo } fn main() { }
{ // Not OK---T may contain borrowed ptrs and it is going to escape // as part of the returned foo value struct F<T> { f: T } @F {f:t} as @foo //~ ERROR value may contain borrowed pointers; add `'static` bound }
identifier_body
kindck-owned-trait-scoped.rs
// xfail-test // xfail'd because to_foo() doesn't work. // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/lic...
<T> { f: T } @F {f:t} as @foo //~ ERROR value may contain borrowed pointers; add `'static` bound } fn to_foo_3<T:Clone +'static>(t: T) -> @foo { // OK---T may escape as part of the returned foo value, but it is // owned and hence does not contain borrowed ptrs struct F<T> { f: T } @F {f:t} as @foo ...
F
identifier_name
kindck-owned-trait-scoped.rs
// xfail-test // xfail'd because to_foo() doesn't work. // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/lic...
fn to_foo_3<T:Clone +'static>(t: T) -> @foo { // OK---T may escape as part of the returned foo value, but it is // owned and hence does not contain borrowed ptrs struct F<T> { f: T } @F {f:t} as @foo } fn main() { }
struct F<T> { f: T } @F {f:t} as @foo //~ ERROR value may contain borrowed pointers; add `'static` bound }
random_line_split
lib.rs
// rust-xmpp // Copyright (c) 2014 Florian Zeitz // Copyright (c) 2014 Allan SIMON // // This project is MIT licensed. // Please see the COPYING file for more information. #![crate_name = "xmpp"] #![crate_type = "lib"] #![feature(macro_rules)] extern crate serialize; extern crate xml; extern crate openssl; use ser...
{ ip: String, port: u16 } /// impl XmppServerListener { pub fn new( ip: &str, port: u16 ) -> XmppServerListener { XmppServerListener { ip: ip.to_string(), port: port } } pub fn listen(&mut self) { let listener = TcpListener::bin...
XmppServerListener
identifier_name
lib.rs
// rust-xmpp // Copyright (c) 2014 Florian Zeitz // Copyright (c) 2014 Allan SIMON // // This project is MIT licensed. // Please see the COPYING file for more information. #![crate_name = "xmpp"] #![crate_type = "lib"] #![feature(macro_rules)] extern crate serialize; extern crate xml; extern crate openssl; use ser...
} pub fn listen(&mut self) { let listener = TcpListener::bind( self.ip.as_slice(), self.port ); let mut acceptor= listener.listen().unwrap(); for opt_stream in acceptor.incoming() { spawn(proc() { let mut xmppStream = XmppServe...
random_line_split
traceback.rs
use libc::c_int; use object::*; use pyport::Py_ssize_t; use frameobject::PyFrameObject; #[repr(C)] #[derive(Copy, Clone)] pub struct
{ #[cfg(py_sys_config="Py_TRACE_REFS")] pub _ob_next: *mut PyObject, #[cfg(py_sys_config="Py_TRACE_REFS")] pub _ob_prev: *mut PyObject, pub ob_refcnt: Py_ssize_t, pub ob_type: *mut PyTypeObject, pub tb_next: *mut PyTracebackObject, pub tb_frame: *mut PyFrameObject, pub tb_lasti: c_i...
PyTracebackObject
identifier_name
traceback.rs
use libc::c_int; use object::*; use pyport::Py_ssize_t; use frameobject::PyFrameObject; #[repr(C)] #[derive(Copy, Clone)] pub struct PyTracebackObject { #[cfg(py_sys_config="Py_TRACE_REFS")] pub _ob_next: *mut PyObject, #[cfg(py_sys_config="Py_TRACE_REFS")] pub _ob_prev: *mut PyObject, pub ob_refcn...
pub unsafe fn PyTraceBack_Check(op : *mut PyObject) -> c_int { (Py_TYPE(op) == &mut PyTraceBack_Type) as c_int }
#[inline(always)]
random_line_split
main.rs
extern crate chrono; extern crate docopt; extern crate rustc_serialize; mod advanced_iterator; mod date; mod format; use advanced_iterator::AdvancedIterator; use date::dates; use format::layout_month; use docopt::Docopt; const USAGE: &'static str = " Calendar. Usage: calendar <year> [--months-per-line=<num>] ca...
{ let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); let calendar = dates(args.arg_year) .by_month() .map(layout_month) .chunk(args.flag_months_per_line) .map(...
identifier_body
main.rs
extern crate chrono; extern crate docopt; extern crate rustc_serialize; mod advanced_iterator; mod date; mod format; use advanced_iterator::AdvancedIterator; use date::dates; use format::layout_month; use docopt::Docopt; const USAGE: &'static str = " Calendar. Usage: calendar <year> [--months-per-line=<num>] ca...
"; #[derive(Debug, RustcDecodable)] struct Args { arg_year: i32, flag_months_per_line: usize } fn main() { let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); let calendar = dates(args.arg_year) .by_month()...
--months-per-line=<num> Number of months per line [default: 3]
random_line_split
main.rs
extern crate chrono; extern crate docopt; extern crate rustc_serialize; mod advanced_iterator; mod date; mod format; use advanced_iterator::AdvancedIterator; use date::dates; use format::layout_month; use docopt::Docopt; const USAGE: &'static str = " Calendar. Usage: calendar <year> [--months-per-line=<num>] ca...
{ arg_year: i32, flag_months_per_line: usize } fn main() { let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); let calendar = dates(args.arg_year) .by_month() .map(layout_month) ...
Args
identifier_name
packet.rs
use crate::err::AccessError; use sodiumoxide::crypto::box_; pub fn open<'packet>( packet: &'packet [u8], secret_key: &box_::SecretKey, public_key: &box_::PublicKey, ) -> Result<Vec<u8>, AccessError> { match box_::Nonce::from_slice(&packet[..box_::NONCEBYTES]) { Some(nonce) => box_::open( ...
( msg: &[u8], nonce: &box_::Nonce, secret_key: &box_::SecretKey, public_key: &box_::PublicKey, ) -> Vec<u8> { box_::seal(&msg, nonce, &public_key, &secret_key) }
create
identifier_name
packet.rs
use crate::err::AccessError; use sodiumoxide::crypto::box_; pub fn open<'packet>( packet: &'packet [u8], secret_key: &box_::SecretKey, public_key: &box_::PublicKey, ) -> Result<Vec<u8>, AccessError>
pub fn create( msg: &[u8], nonce: &box_::Nonce, secret_key: &box_::SecretKey, public_key: &box_::PublicKey, ) -> Vec<u8> { box_::seal(&msg, nonce, &public_key, &secret_key) }
{ match box_::Nonce::from_slice(&packet[..box_::NONCEBYTES]) { Some(nonce) => box_::open( &packet[box_::NONCEBYTES..], &nonce, &public_key, &secret_key, ) .map_err(|_| AccessError::InvalidCiphertext), None => Err(AccessError::InvalidNon...
identifier_body
packet.rs
use crate::err::AccessError; use sodiumoxide::crypto::box_;
pub fn open<'packet>( packet: &'packet [u8], secret_key: &box_::SecretKey, public_key: &box_::PublicKey, ) -> Result<Vec<u8>, AccessError> { match box_::Nonce::from_slice(&packet[..box_::NONCEBYTES]) { Some(nonce) => box_::open( &packet[box_::NONCEBYTES..], &nonce, ...
random_line_split
quick-evdev.rs
// This is a translation of the xkbcommon quick start guide: // https://xkbcommon.org/doc/current/md_doc_quick_guide.html extern crate evdev; extern crate xkbcommon; use xkbcommon::xkb; // evdev constants: const KEYCODE_OFFSET: u16 = 8; const KEY_STATE_RELEASE: i32 = 0; const KEY_STATE_REPEAT: i32 = 2; fn main()
xkb::COMPILE_NO_FLAGS, ) .unwrap(); // Create the state tracker let mut state = xkb::State::new(&keymap); loop { for event in device.fetch_events().unwrap() { if let evdev::InputEventKind::Key(keycode) = event.kind() { let keycode = (keycode.0 + KEYCODE_O...
{ // Open evdev device let mut device = evdev::Device::open( std::env::args() .nth(1) .unwrap_or(String::from("/dev/input/event0")), ) .unwrap(); // Create context let context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS); // Load keymap informations let ke...
identifier_body
quick-evdev.rs
// This is a translation of the xkbcommon quick start guide: // https://xkbcommon.org/doc/current/md_doc_quick_guide.html extern crate evdev; extern crate xkbcommon; use xkbcommon::xkb; // evdev constants: const KEYCODE_OFFSET: u16 = 8; const KEY_STATE_RELEASE: i32 = 0; const KEY_STATE_REPEAT: i32 = 2; fn
() { // Open evdev device let mut device = evdev::Device::open( std::env::args() .nth(1) .unwrap_or(String::from("/dev/input/event0")), ) .unwrap(); // Create context let context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS); // Load keymap informations let ke...
main
identifier_name
quick-evdev.rs
// This is a translation of the xkbcommon quick start guide: // https://xkbcommon.org/doc/current/md_doc_quick_guide.html
use xkbcommon::xkb; // evdev constants: const KEYCODE_OFFSET: u16 = 8; const KEY_STATE_RELEASE: i32 = 0; const KEY_STATE_REPEAT: i32 = 2; fn main() { // Open evdev device let mut device = evdev::Device::open( std::env::args() .nth(1) .unwrap_or(String::from("/dev/input/event0"))...
extern crate evdev; extern crate xkbcommon;
random_line_split
quick-evdev.rs
// This is a translation of the xkbcommon quick start guide: // https://xkbcommon.org/doc/current/md_doc_quick_guide.html extern crate evdev; extern crate xkbcommon; use xkbcommon::xkb; // evdev constants: const KEYCODE_OFFSET: u16 = 8; const KEY_STATE_RELEASE: i32 = 0; const KEY_STATE_REPEAT: i32 = 2; fn main() { ...
; // Inspect state if state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE) { print!("Control "); } if state.led_name_is_active(xkb::LED_NAME_NUM) { print!("NumLockLED"); } ...
{ state.update_key(keycode, xkb::KeyDirection::Down) }
conditional_block
bluetoothpermissionresult.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResul...
pub fn get_state(&self) -> PermissionState { self.status.State() } #[allow(unrooted_must_root)] pub fn set_devices(&self, devices: Vec<Dom<BluetoothDevice>>) { *self.devices.borrow_mut() = devices; } } impl BluetoothPermissionResultMethods for BluetoothPermissionResult { // htt...
}
random_line_split
bluetoothpermissionresult.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResul...
(&self) -> PermissionName { self.status.get_query() } pub fn set_state(&self, state: PermissionState) { self.status.set_state(state) } pub fn get_state(&self) -> PermissionState { self.status.State() } #[allow(unrooted_must_root)] pub fn set_devices(&self, devices:...
get_query
identifier_name
bluetoothpermissionresult.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResul...
device.name.map(DOMString::from), &bluetooth, ); device_instance_map.insert(device.id.clone(), Dom::from_ref(&bt_device)); self.global() .as_window() .bluetooth_extra_permission_data() ...
{ match response { // https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices // Step 3, 11, 13 - 14. BluetoothResponse::RequestDevice(device) => { self.set_state(PermissionState::Granted); let bluetooth = self.get_bluetooth()...
identifier_body
paging.rs
//! Description of the data-structures for IA-32e paging mode. use core::fmt; /// Represent a virtual (linear) memory address #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct VAddr(usize); impl VAddr { /// Convert to `usize` pub const fn as_usize(&self) -> usize { self.0 }...
}
random_line_split
paging.rs
//! Description of the data-structures for IA-32e paging mode. use core::fmt; /// Represent a virtual (linear) memory address #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct VAddr(usize); impl VAddr { /// Convert to `usize` pub const fn as_usize(&self) -> usize { self.0 }...
(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } impl fmt::Octal for VAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } impl fmt::UpperHex for VAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } }
fmt
identifier_name
packed-struct-vec.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
() { let foos = [Foo { bar: 1, baz: 2 },.. 10]; assert_eq!(sys::size_of::<[Foo,.. 10]>(), 90); for i in range(0u, 10) { assert_eq!(foos[i], Foo { bar: 1, baz: 2}); } for &foo in foos.iter() { assert_eq!(foo, Foo { bar: 1, baz: 2 }); } }
main
identifier_name
packed-struct-vec.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
use std::sys; #[packed] #[deriving(Eq)] struct Foo { bar: u8, baz: u64 } fn main() { let foos = [Foo { bar: 1, baz: 2 },.. 10]; assert_eq!(sys::size_of::<[Foo,.. 10]>(), 90); for i in range(0u, 10) { assert_eq!(foos[i], Foo { bar: 1, baz: 2}); } for &foo in foos.iter() { ...
random_line_split
packed-struct-vec.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
{ let foos = [Foo { bar: 1, baz: 2 }, .. 10]; assert_eq!(sys::size_of::<[Foo, .. 10]>(), 90); for i in range(0u, 10) { assert_eq!(foos[i], Foo { bar: 1, baz: 2}); } for &foo in foos.iter() { assert_eq!(foo, Foo { bar: 1, baz: 2 }); } }
identifier_body
references.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ paths::{self, Path}, shared::*, }; use std::{ cmp::Ordering, collections::{BTreeMap, BTreeSet}, fmt, fmt::Debug, }; //********************************************************************************...
} } } impl<Loc: Copy, Lbl: Clone + Ord> Ref<Loc, Lbl> { /// Utility for remapping the reference ids according the `id_map` provided /// If it is not in the map, the id remains the same pub(crate) fn remap_refs(&mut self, id_map: &BTreeMap<RefID, RefID>) { self.borrowed_by.remap_refs(id...
{ self.0.insert(*new, edges); }
conditional_block
references.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ paths::{self, Path}, shared::*, }; use std::{ cmp::Ordering, collections::{BTreeMap, BTreeSet}, fmt, fmt::Debug, }; //********************************************************************************...
for (old, new) in id_map { if let Some(edges) = self.0.remove(old) { self.0.insert(*new, edges); } } } } impl<Loc: Copy, Lbl: Clone + Ord> Ref<Loc, Lbl> { /// Utility for remapping the reference ids according the `id_map` provided /// If it is not in ...
/// Utility for remapping the reference ids according the `id_map` provided /// If it is not in the map, the id remains the same pub(crate) fn remap_refs(&mut self, id_map: &BTreeMap<RefID, RefID>) {
random_line_split
references.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ paths::{self, Path}, shared::*, }; use std::{ cmp::Ordering, collections::{BTreeMap, BTreeSet}, fmt, fmt::Debug, }; //********************************************************************************...
} impl<Loc: Copy, Lbl: Clone + Ord> PartialEq for BorrowEdge<Loc, Lbl> { fn eq(&self, other: &BorrowEdge<Loc, Lbl>) -> bool { BorrowEdgeNoLoc::new(self) == BorrowEdgeNoLoc::new(other) } } impl<Loc: Copy, Lbl: Clone + Ord> Eq for BorrowEdge<Loc, Lbl> {} impl<Loc: Copy, Lbl: Clone + Ord> PartialOrd fo...
{ BorrowEdgeNoLoc { strong: e.strong, path: &e.path, } }
identifier_body
references.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ paths::{self, Path}, shared::*, }; use std::{ cmp::Ordering, collections::{BTreeMap, BTreeSet}, fmt, fmt::Debug, }; //********************************************************************************...
<Loc: Copy, Lbl: Clone + Ord> { /// Parent to child ///'self' is borrowed by _ pub(crate) borrowed_by: BorrowEdges<Loc, Lbl>, /// Child to parent ///'self' borrows from _ /// Needed for efficient querying, but should be in one-to-one corespondence with borrowed by /// i.e. x is borrowed by y...
Ref
identifier_name
artifact.rs
use byteorder::*; use core::io::{BinaryComponent, DecodeError, WrResult}; #[derive(Clone, Eq, PartialEq, Debug)] pub struct ArtifactData { spec: u16, // Artifact code. Big-endian 0xXXXY, where X is the namespace and Y is the subtype. body: Vec<u8> // Actual artifact format is specified in a higher layer. } ...
Ok(ArtifactData { spec: sp, body: b }) } fn to_writer<W: WriteBytesExt>(&self, write: &mut W) -> WrResult { write.write_u16::<BigEndian>(self.spec)?; write.write_u64::<BigEndian>(self.body.len() as u64)?; write.write_all(self.body.as_slice())?; ...
random_line_split
artifact.rs
use byteorder::*; use core::io::{BinaryComponent, DecodeError, WrResult}; #[derive(Clone, Eq, PartialEq, Debug)] pub struct ArtifactData { spec: u16, // Artifact code. Big-endian 0xXXXY, where X is the namespace and Y is the subtype. body: Vec<u8> // Actual artifact format is specified in a higher layer. } ...
<R: ReadBytesExt>(read: &mut R) -> Result<Self, DecodeError> { let sp = read.read_u16::<BigEndian>()?; let mut b = vec![0; read.read_u64::<BigEndian>()? as usize]; read.read(b.as_mut_slice())?; Ok(ArtifactData { spec: sp, body: b }) } fn to_wri...
from_reader
identifier_name
linear_gradient.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version ...
return false; } true }); } #[cfg(test)] mod tests { use super::*; use svgdom::{Document, ToStringWithOptions}; use task; macro_rules! test { ($name:ident, $in_text:expr, $out_text:expr) => ( #[test] fn $name() { let doc ...
{ let attrs = [ AId::X1, AId::Y1, AId::X2, AId::Y2, AId::GradientUnits, AId::SpreadMethod, ]; let mut nodes = doc.descendants() .filter(|n| n.is_tag_name(EId::LinearGradient)) .collect::<Vec<Node>>(); super::...
identifier_body
linear_gradient.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version ...
// // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. use svgdom::{ Document, Node, }; use task::short::{EId, AId}; pub fn remove_dupl_linear_gradi...
// // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details.
random_line_split
linear_gradient.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version ...
(doc: &Document) { let attrs = [ AId::X1, AId::Y1, AId::X2, AId::Y2, AId::GradientUnits, AId::SpreadMethod, ]; let mut nodes = doc.descendants() .filter(|n| n.is_tag_name(EId::LinearGradient)) .collect::<Vec<Node>>(...
remove_dupl_linear_gradients
identifier_name
linear_gradient.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version ...
true }); } #[cfg(test)] mod tests { use super::*; use svgdom::{Document, ToStringWithOptions}; use task; macro_rules! test { ($name:ident, $in_text:expr, $out_text:expr) => ( #[test] fn $name() { let doc = Document::from_str($in_text).unwra...
{ return false; }
conditional_block
update.rs
use std::collections::HashMap; use util::H256; use header::BlockNumber; use blockchain::block_info::BlockInfo; use blooms::BloomGroup; use super::extras::{BlockDetails, BlockReceipts, TransactionAddress, LogGroupPosition}; /// Block extras update info. pub struct
<'a> { /// Block info. pub info: BlockInfo, /// Current block uncompressed rlp bytes pub block: &'a [u8], /// Modified block hashes. pub block_hashes: HashMap<BlockNumber, H256>, /// Modified block details. pub block_details: HashMap<H256, BlockDetails>, /// Modified block receipts. pub block_receipts: HashMa...
ExtrasUpdate
identifier_name
update.rs
use std::collections::HashMap; use util::H256; use header::BlockNumber; use blockchain::block_info::BlockInfo; use blooms::BloomGroup; use super::extras::{BlockDetails, BlockReceipts, TransactionAddress, LogGroupPosition}; /// Block extras update info. pub struct ExtrasUpdate<'a> { /// Block info. pub info: BlockInf...
}
pub transactions_addresses: HashMap<H256, Option<TransactionAddress>>,
random_line_split
setext_header.rs
use parser::span::parse_spans; use parser::Block; use parser::Block::Header; use regex::Regex; pub fn parse_setext_header(lines: &[&str]) -> Option<(Block, usize)> { lazy_static! { static ref HORIZONTAL_RULE_1: Regex = Regex::new(r"^===+$").unwrap(); static ref HORIZONTAL_RULE_2: Regex = Regex::new...
() { assert_eq!( parse_setext_header(&vec!["Test", "=========="]).unwrap(), (Header(vec![Text("Test".to_owned())], 1), 2) ); assert_eq!( parse_setext_header(&vec!["Test", "----------"]).unwrap(), (Header(vec![Text("Test".to_owned())], 2), 2) ...
finds_atx_header
identifier_name
setext_header.rs
use parser::span::parse_spans; use parser::Block; use parser::Block::Header; use regex::Regex; pub fn parse_setext_header(lines: &[&str]) -> Option<(Block, usize)>
#[cfg(test)] mod test { use super::parse_setext_header; use parser::Block::Header; use parser::Span::Text; #[test] fn finds_atx_header() { assert_eq!( parse_setext_header(&vec!["Test", "=========="]).unwrap(), (Header(vec![Text("Test".to_owned())], 1), 2) )...
{ lazy_static! { static ref HORIZONTAL_RULE_1: Regex = Regex::new(r"^===+$").unwrap(); static ref HORIZONTAL_RULE_2: Regex = Regex::new(r"^---+$").unwrap(); } if lines.len() > 1 && !lines[0].is_empty() { if HORIZONTAL_RULE_1.is_match(lines[1]) { return Some((Header(parse...
identifier_body
setext_header.rs
use parser::span::parse_spans; use parser::Block; use parser::Block::Header; use regex::Regex; pub fn parse_setext_header(lines: &[&str]) -> Option<(Block, usize)> { lazy_static! { static ref HORIZONTAL_RULE_1: Regex = Regex::new(r"^===+$").unwrap(); static ref HORIZONTAL_RULE_2: Regex = Regex::new...
assert_eq!( parse_setext_header(&vec!["This is a test", "==="]).unwrap(), (Header(vec![Text("This is a test".to_owned())], 1), 2) ); assert_eq!( parse_setext_header(&vec!["This is a test", "---"]).unwrap(), (Header(vec![Text("This is a test".to_o...
);
random_line_split
setext_header.rs
use parser::span::parse_spans; use parser::Block; use parser::Block::Header; use regex::Regex; pub fn parse_setext_header(lines: &[&str]) -> Option<(Block, usize)> { lazy_static! { static ref HORIZONTAL_RULE_1: Regex = Regex::new(r"^===+$").unwrap(); static ref HORIZONTAL_RULE_2: Regex = Regex::new...
else if HORIZONTAL_RULE_2.is_match(lines[1]) { return Some((Header(parse_spans(lines[0]), 2), 2)); } } None } #[cfg(test)] mod test { use super::parse_setext_header; use parser::Block::Header; use parser::Span::Text; #[test] fn finds_atx_header() { assert_eq!( ...
{ return Some((Header(parse_spans(lines[0]), 1), 2)); }
conditional_block
vec-matching-legal-tail-element-borrow.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
{ let x = &[1i, 2, 3, 4, 5]; let x: &[int] = &[1, 2, 3, 4, 5]; if !x.is_empty() { let el = match x { [1, ..ref tail] => &tail[0], _ => unreachable!() }; println!("{}", *el); } }
identifier_body
vec-matching-legal-tail-element-borrow.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
() { let x = &[1i, 2, 3, 4, 5]; let x: &[int] = &[1, 2, 3, 4, 5]; if!x.is_empty() { let el = match x { [1,..ref tail] => &tail[0], _ => unreachable!() }; println!("{}", *el); } }
main
identifier_name
vec-matching-legal-tail-element-borrow.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
} }
random_line_split
complex.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
(re: T, im: T) -> Complex<T> { Complex { re: re, im: im } } /** Returns the square of the norm (since `T` doesn't necessarily have a sqrt function), i.e. `re^2 + im^2`. */ #[inline] pub fn norm_sqr(&self) -> T { self.re * self.re + self.im * self.im } /// Returns t...
new
identifier_name
complex.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
for &c in all_consts.iter() { assert_eq!(_0_0i + c, c); assert_eq!(c + _0_0i, c); } } #[test] fn test_sub() { assert_eq!(_05_05i - _05_05i, _0_0i); assert_eq!(_0_1i - _1_0i, _neg1_1i); assert_eq!(_0_1i -...
assert_eq!(_0_1i + _1_0i, _1_1i); assert_eq!(_1_0i + _neg1_1i, _0_1i);
random_line_split
complex.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
} } #[cfg(test)] mod test { #![allow(non_uppercase_statics)] use super::{Complex64, Complex}; use std::num::{Zero,One,Float}; pub static _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 }; pub static _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 }; pub static _1_1i : Complex64 = Complex {...
{ format!("{}+{}i", self.re.to_str_radix(radix), self.im.to_str_radix(radix)) }
conditional_block
complex.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
/// Convert a polar representation into a complex number. #[inline] pub fn from_polar(r: &T, theta: &T) -> Complex<T> { Complex::new(*r * theta.cos(), *r * theta.sin()) } } /* arithmetic */ // (a + i b) + (c + i d) == (a + c) + i (b + d) impl<T: Clone + Num> Add<Complex<T>, Complex<T>> for Com...
{ (self.norm(), self.arg()) }
identifier_body
quota_manager.rs
// CopyrightTechnologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writ...
pub fn default_quota() -> Vec<u64> { info!("Use default quota."); Vec::new() } /// Account array pub fn users(&self, block_tag: BlockTag) -> Option<Vec<Address>> { self.executor .call_method( &*CONTRACT_ADDRESS, &*ACCOUNTS_HASH.as_slice...
.and_then(|output| decode_tools::to_u64_vec(&output)) }
random_line_split
quota_manager.rs
// CopyrightTechnologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writ...
(self) -> ProtoAccountQuotaLimit { let mut r = ProtoAccountQuotaLimit::new(); r.common_quota_limit = self.common_quota_limit; let specific_quota_limit: HashMap<String, u64> = self .get_specific_quota_limit() .iter() .map(|(k, v)| (k.lower_hex(), *v)) ....
into
identifier_name
quota_manager.rs
// CopyrightTechnologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writ...
/// Quota array pub fn quota(&self, block_tag: BlockTag) -> Option<Vec<u64>> { self.executor .call_method( &*CONTRACT_ADDRESS, &*QUOTAS_HASH.as_slice(), None, block_tag, ) .ok() .and_then(|outp...
{ let users = self.users(block_tag).unwrap_or_else(Self::default_users); let quota = self.quota(block_tag).unwrap_or_else(Self::default_quota); let mut specific = HashMap::new(); for (k, v) in users.iter().zip(quota.iter()) { specific.insert(*k, *v); } specifi...
identifier_body
traceback.rs
use std::default::Default; use std::iter; use std::marker::PhantomData; use std::ops::Range; use crate::alignment::AlignmentOperation; use crate::pattern_matching::myers::{word_size, BitVec, DistType, State}; /// Objects implementing this trait handle the addition of calculated blocks (State<T, D>) /// to a containe...
/// m (pattern length). /// Returns the expected size of the vector storing the calculated blocks given this /// information. The vector will then be initialized with the given number of 'empty' /// State<T, D> objects and supplied to the other methods as slice. fn init(&mut self, n: usize, m: D) ->...
/// Prepare for a new search given n (maximum expected number of traceback columns) and
random_line_split
traceback.rs
use std::default::Default; use std::iter; use std::marker::PhantomData; use std::ops::Range; use crate::alignment::AlignmentOperation; use crate::pattern_matching::myers::{word_size, BitVec, DistType, State}; /// Objects implementing this trait handle the addition of calculated blocks (State<T, D>) /// to a containe...
( states: &mut Vec<State<T, D>>, initial_state: &H::TracebackColumn, num_cols: usize, m: D, mut handler: H, ) -> Self { // Correct traceback needs two additional columns at the left of the matrix (see below). // Therefore reserving additional space. le...
new
identifier_name
traceback.rs
use std::default::Default; use std::iter; use std::marker::PhantomData; use std::ops::Range; use crate::alignment::AlignmentOperation; use crate::pattern_matching::myers::{word_size, BitVec, DistType, State}; /// Objects implementing this trait handle the addition of calculated blocks (State<T, D>) /// to a containe...
else { print!(" -"); } } println!(); } } }
{ if *d >= (D::max_value() >> 1) { // missing value print!(" "); } else { print!("{:>4?}", d); } }
conditional_block
traceback.rs
use std::default::Default; use std::iter; use std::marker::PhantomData; use std::ops::Range; use crate::alignment::AlignmentOperation; use crate::pattern_matching::myers::{word_size, BitVec, DistType, State}; /// Objects implementing this trait handle the addition of calculated blocks (State<T, D>) /// to a containe...
); } } pub(super) struct Traceback<'a, T, D, H> where T: BitVec + 'a, D: DistType, H: StatesHandler<'a, T, D>, { m: D, positions: iter::Cycle<Range<usize>>, handler: H, pos: usize, _t: PhantomData<&'a T>, } impl<'a, T, D, H> Traceback<'a, T, D, H> where T: BitVec, ...
{ println!( "--- TB dist ({:?} <-> {:?})", self.left_block().dist, self.block().dist ); println!( "{:064b} m\n{:064b} + ({:?}) (left) d={:?}\n{:064b} - ({:?})\n \ {:064b} + ({:?}) (current) d={:?}\n{:064b} - ({:?})\n", self...
identifier_body
wrapper.rs
//! This module holds the Wrapper newtype; used to write //! instances of typeclasses that we don't define for types we don't //! own use frunk::monoid::*; use frunk::semigroup::*; use quickcheck::*; /// The Wrapper NewType. Used for writing implementations of traits /// that we don't own for type we don't own. /// /...
<G: Gen>(g: &mut G) -> Self { Wrapper(Min(Arbitrary::arbitrary(g))) } } impl<A: Arbitrary> Arbitrary for Wrapper<All<A>> { fn arbitrary<G: Gen>(g: &mut G) -> Self { Wrapper(All(Arbitrary::arbitrary(g))) } } impl<A: Arbitrary> Arbitrary for Wrapper<Any<A>> { fn arbitrary<G: Gen>(g: &mut...
arbitrary
identifier_name
wrapper.rs
//! This module holds the Wrapper newtype; used to write //! instances of typeclasses that we don't define for types we don't //! own use frunk::monoid::*; use frunk::semigroup::*; use quickcheck::*; /// The Wrapper NewType. Used for writing implementations of traits /// that we don't own for type we don't own. /// /...
}
{ Wrapper(<A as Monoid>::empty()) }
identifier_body
wrapper.rs
//! This module holds the Wrapper newtype; used to write //! instances of typeclasses that we don't define for types we don't //! own use frunk::monoid::*; use frunk::semigroup::*; use quickcheck::*; /// The Wrapper NewType. Used for writing implementations of traits /// that we don't own for type we don't own. /// /...
impl<A: Monoid> Monoid for Wrapper<A> { fn empty() -> Self { Wrapper(<A as Monoid>::empty()) } }
fn combine(&self, other: &Self) -> Self { Wrapper(self.0.combine(&other.0)) } }
random_line_split
oop_utils.rs
use super::Universe; use super::oop::*; use ast::sexpr::SExpr; use std::fmt::{self, Formatter, Display}; // Format impl unsafe fn fmt_oop(oop: Oop, u: &Universe, fmt: &mut Formatter) -> fmt::Result { if oop == NULL_OOP { write!(fmt, "<null>")?; } else if Singleton::is_singleton(oop) { write!(...
else if u.oop_is_closure(oop) { let mb = MutBox::from_raw(oop); write!(fmt, "<Box {} @{:#x}>", FmtOop(mb.value(), u), oop)?; } else if u.oop_is_ooparray(oop) { let arr = OopArray::from_raw(oop); write!(fmt, "[")?; for (i, oop) in arr.content().iter().enumerate() { ...
{ let clo = Closure::from_raw(oop); write!(fmt, "<Closure {} @{:#x}>", clo.info().name(), oop)?; }
conditional_block
oop_utils.rs
use super::Universe; use super::oop::*; use ast::sexpr::SExpr; use std::fmt::{self, Formatter, Display}; // Format impl unsafe fn fmt_oop(oop: Oop, u: &Universe, fmt: &mut Formatter) -> fmt::Result { if oop == NULL_OOP { write!(fmt, "<null>")?; } else if Singleton::is_singleton(oop) { write!(...
(_oop: Handle<Closure>, _u: &Universe) -> SExpr { panic!("oop_to_sexpr: not implemenetd") }
oop_to_sexpr
identifier_name
oop_utils.rs
use super::Universe; use super::oop::*; use ast::sexpr::SExpr; use std::fmt::{self, Formatter, Display}; // Format impl unsafe fn fmt_oop(oop: Oop, u: &Universe, fmt: &mut Formatter) -> fmt::Result { if oop == NULL_OOP { write!(fmt, "<null>")?; } else if Singleton::is_singleton(oop) { write!(...
panic!("oop_to_sexpr: not implemenetd") }
} pub fn oop_to_sexpr(_oop: Handle<Closure>, _u: &Universe) -> SExpr {
random_line_split
main.rs
extern crate crypto; extern crate hyper; extern crate rustc_serialize; extern crate rand; mod hmac_sha1; use hyper::server::{Server, Request, Response}; use hyper::status::StatusCode; use hyper::net::Fresh; use hyper::uri::RequestUri::AbsolutePath; const HOST: &'static str = "localhost:9000"; const DELAY: u32 = 1; ...
#[cfg(test)] mod tests { #[test] #[ignore] fn insecure_compare() { assert!(super::insecure_compare(b"yellow submarine", b"yellow submarine"), "should have been equal"); assert!(!super::insecure_compare(b"yellow submarine", b"yellow_submarine"), "should have been unequal"...
} true }
random_line_split
main.rs
extern crate crypto; extern crate hyper; extern crate rustc_serialize; extern crate rand; mod hmac_sha1; use hyper::server::{Server, Request, Response}; use hyper::status::StatusCode; use hyper::net::Fresh; use hyper::uri::RequestUri::AbsolutePath; const HOST: &'static str = "localhost:9000"; const DELAY: u32 = 1; ...
, } } fn check_signature(key: &[u8], filename: &str, signature: &str) -> StatusCode { use rustc_serialize::hex::FromHex; let parsed_signature = match signature.from_hex() { Ok(sig) => sig, _ => return StatusCode::BadRequest, }; let file_hash = match file_hmac(key, filename) { ...
{}
conditional_block
main.rs
extern crate crypto; extern crate hyper; extern crate rustc_serialize; extern crate rand; mod hmac_sha1; use hyper::server::{Server, Request, Response}; use hyper::status::StatusCode; use hyper::net::Fresh; use hyper::uri::RequestUri::AbsolutePath; const HOST: &'static str = "localhost:9000"; const DELAY: u32 = 1; ...
fn insecure_compare(first: &[u8], second: &[u8]) -> bool { for (x, y) in first.iter().zip(second.iter()) { if { x!= y } { return false; } std::thread::sleep_ms(DELAY); } if first.len()!= second.len() { //do this after step-by-step to preserve return false; //element-...
{ use std::io::prelude::*; use std::fs::File; let mut file = try!(File::open(filename)); let mut s = String::new(); try!(file.read_to_string(&mut s)); Ok(hmac_sha1::hmac_sha1(key, &s.into_bytes()[..])) }
identifier_body
main.rs
extern crate crypto; extern crate hyper; extern crate rustc_serialize; extern crate rand; mod hmac_sha1; use hyper::server::{Server, Request, Response}; use hyper::status::StatusCode; use hyper::net::Fresh; use hyper::uri::RequestUri::AbsolutePath; const HOST: &'static str = "localhost:9000"; const DELAY: u32 = 1; ...
(first: &[u8], second: &[u8]) -> bool { for (x, y) in first.iter().zip(second.iter()) { if { x!= y } { return false; } std::thread::sleep_ms(DELAY); } if first.len()!= second.len() { //do this after step-by-step to preserve return false; //element-by-element comparison...
insecure_compare
identifier_name
math.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{ atomic::{AtomicU32, Ordering}, Mutex, }; struct MovingAvgU32Inner { buffer: Vec<u32>, current_index: usize, sum: u32, } pub struct MovingAvgU32 { protected: Mutex<MovingAvgU32Inner>, cached_avg: AtomicU32,...
() { use rand::Rng; let mut rng = rand::thread_rng(); let avg = MovingAvgU32::new(105); let mut external_sum = 0; for _ in 0..100 { let n: u32 = rng.gen_range(0..u32::MAX / 100); external_sum += n; avg.add(n); assert_eq!(avg.fetch(...
test_random_sequence
identifier_name
math.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{ atomic::{AtomicU32, Ordering}, Mutex, }; struct MovingAvgU32Inner { buffer: Vec<u32>, current_index: usize, sum: u32, } pub struct MovingAvgU32 { protected: Mutex<MovingAvgU32Inner>, cached_avg: AtomicU32,...
cached_avg: AtomicU32::new(0), } } pub fn add(&self, sample: u32) -> (u32, u32) { let mut inner = self.protected.lock().unwrap(); let current_index = (inner.current_index + 1) % inner.buffer.len(); inner.current_index = current_index; let old_avg = inner.sum ...
current_index: 0, sum: 0, }),
random_line_split
math.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{ atomic::{AtomicU32, Ordering}, Mutex, }; struct MovingAvgU32Inner { buffer: Vec<u32>, current_index: usize, sum: u32, } pub struct MovingAvgU32 { protected: Mutex<MovingAvgU32Inner>, cached_avg: AtomicU32,...
} } #[test] fn test_random_sequence() { use rand::Rng; let mut rng = rand::thread_rng(); let avg = MovingAvgU32::new(105); let mut external_sum = 0; for _ in 0..100 { let n: u32 = rng.gen_range(0..u32::MAX / 100); external_sum += n; ...
{ assert_eq!(avg.fetch(), (i * (i + 1) / 10)); }
conditional_block
math.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{ atomic::{AtomicU32, Ordering}, Mutex, }; struct MovingAvgU32Inner { buffer: Vec<u32>, current_index: usize, sum: u32, } pub struct MovingAvgU32 { protected: Mutex<MovingAvgU32Inner>, cached_avg: AtomicU32,...
}
{ use rand::Rng; let mut rng = rand::thread_rng(); let avg = MovingAvgU32::new(105); let mut external_sum = 0; for _ in 0..100 { let n: u32 = rng.gen_range(0..u32::MAX / 100); external_sum += n; avg.add(n); assert_eq!(avg.fetch(), ...
identifier_body
main.rs
extern crate event_handler; extern crate client; use std::net::TcpListener; use std::thread; use client::*; use event_handler::*; fn main() { // ํด๋ผ์ด์–ธํŠธ์˜ ์ ‘์†์„ ์ฒ˜๋ฆฌํ•  listen port ์ƒ์„ฑ let listener = TcpListener::bind("127.0.0.1:9000").unwrap(); println!("Start to listen, ready to accept"); // ๊ฐ์ข… ์ด๋ฒคํŠธ๋ฅผ ์ฒ˜๋ฆฌ...
= Client::new(new_stream, Some(_tx.clone())); _tx.send(Signal::NewClient(new_client)); } Err(_) => { println!("connection failed"); } } } drop(listener); }
conditional_block
main.rs
extern crate event_handler; extern crate client; use std::net::TcpListener; use std::thread; use client::*; use event_handler::*; fn main() { // ํด๋ผ์ด์–ธํŠธ์˜ ์ ‘์†์„ ์ฒ˜๋ฆฌํ•  listen port ์ƒ์„ฑ let listener = TcpListener::bind("127.0.0.1:9000").unwrap(); println!("Start to listen, ready to accept"); // ๊ฐ์ข… ์ด๋ฒคํŠธ๋ฅผ ์ฒ˜๋ฆฌ...
_tx.send(Signal::NewClient(new_client)); } Err(_) => { println!("connection failed"); } } } drop(listener); }
match stream { Ok(new_stream) => { // ์ƒˆ๋กœ์šด ํด๋ผ์ด์–ธํŠธ์˜ ์—ฐ๊ฒฐ์ด ์ƒ๊ธฐ๋ฉด ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ ์Šค๋ ˆ๋“œ๋กœ ์ด๋ฒคํŠธ ์ƒ์„ฑ, ์ „๋‹ฌ let new_client = Client::new(new_stream, Some(_tx.clone()));
random_line_split
main.rs
extern crate event_handler; extern crate client; use std::net::TcpListener; use std::thread; use client::*; use event_handler::*; fn main()
_tx.send(Signal::NewClient(new_client)); } Err(_) => { println!("connection failed"); } } } drop(listener); }
{ // ํด๋ผ์ด์–ธํŠธ์˜ ์ ‘์†์„ ์ฒ˜๋ฆฌํ•  listen port ์ƒ์„ฑ let listener = TcpListener::bind("127.0.0.1:9000").unwrap(); println!("Start to listen, ready to accept"); // ๊ฐ์ข… ์ด๋ฒคํŠธ๋ฅผ ์ฒ˜๋ฆฌํ•  ๋กœ์ง ์ƒ์„ฑ let sample_event_handler = EventHandler::new(); // ํด๋ผ์ด์–ธํŠธ์˜ ์ ‘์† ์ด๋ฒคํŠธ๋ฅผ ์ „์†กํ•˜๊ธฐ ์œ„ํ•œ channel(Send) ํ• ๋‹น let _tx = sample_event_handl...
identifier_body
main.rs
extern crate event_handler; extern crate client; use std::net::TcpListener; use std::thread; use client::*; use event_handler::*; fn
() { // ํด๋ผ์ด์–ธํŠธ์˜ ์ ‘์†์„ ์ฒ˜๋ฆฌํ•  listen port ์ƒ์„ฑ let listener = TcpListener::bind("127.0.0.1:9000").unwrap(); println!("Start to listen, ready to accept"); // ๊ฐ์ข… ์ด๋ฒคํŠธ๋ฅผ ์ฒ˜๋ฆฌํ•  ๋กœ์ง ์ƒ์„ฑ let sample_event_handler = EventHandler::new(); // ํด๋ผ์ด์–ธํŠธ์˜ ์ ‘์† ์ด๋ฒคํŠธ๋ฅผ ์ „์†กํ•˜๊ธฐ ์œ„ํ•œ channel(Send) ํ• ๋‹น let _tx = sample_event_ha...
main
identifier_name
core.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// except according to those terms. use rustc; use rustc::{driver, middle}; use syntax::ast; use syntax::diagnostic; use syntax::parse; use syntax; use std::os; use std::local_data; use visit_ast::RustdocVisitor; use clean; use clean::Clean; pub struct DocContext { crate: @ast::Crate, tycx: middle::ty::ctx...
// http://www.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
random_line_split
core.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ let ctxt = @get_ast_and_resolve(path, libs); debug!("defmap:"); for (k, v) in ctxt.tycx.def_map.iter() { debug!("%?: %?", k, v); } local_data::set(super::ctxtkey, ctxt); let v = @mut RustdocVisitor::new(); v.visit(ctxt.crate); v.clean() }
identifier_body
core.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ crate: @ast::Crate, tycx: middle::ty::ctxt, sess: driver::session::Session } /// Parses, resolves, and typechecks the given crate fn get_ast_and_resolve(cpath: &Path, libs: ~[Path]) -> DocContext { use syntax::codemap::dummy_spanned; use rustc::driver::driver::*; let parsesess = parse::new_...
DocContext
identifier_name
mod.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@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.o...
let &TokenString(ref s) = self; (cx as &ExtParseUtils).parse_tts(s.clone()) } } pub fn add_node_dependency(node: &Rc<node::Node>, dep: &Rc<node::Node>) { let mut depends_on = node.depends_on.borrow_mut(); depends_on.deref_mut().push(dep.downgrade()); let mut rev_depends_on = dep.rev_depends_on.borrow_...
fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
random_line_split
mod.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@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.o...
pub fn add_type_item(&mut self, item: P<ast::Item>) { self.type_items.push(item); } fn emit_main(&self, cx: &ExtCtxt) -> P<ast::Item> { // init stack let init_stack_stmt = cx.stmt_expr(quote_expr!(&*cx, zinc::hal::mem_init::init_stack(); )); // init data let init_data_stmt = cx...
{ self.main_stmts.push(stmt); }
identifier_body
mod.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@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.o...
} Some(builder) } fn walk_mutate(builder: &mut Builder, cx: &mut ExtCtxt, node: &Rc<node::Node>) { let maybe_mut = node.mutator.get(); if maybe_mut.is_some() { maybe_mut.unwrap()(builder, cx, node.clone()); } for sub in node.subnodes().iter() { Builder::walk_mutate(builder, cx...
{ cx.parse_sess().span_diagnostic.span_err(DUMMY_SP, "root node `mcu::clock` must be present"); }
conditional_block
mod.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@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.o...
(&self, cx: &ExtCtxt) -> P<ast::Item> { let stmt = cx.stmt_expr(quote_expr!(&*cx, core::intrinsics::abort() // or // zinc::os::task::morestack(); )); let empty_span = DUMMY_SP; let body = cx.block(empty_span, vec!(stmt), None); self.item_fn(cx, empty_span, "__morestack", &[],...
emit_morestack
identifier_name