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
constellation_msg.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 http://mozilla.org/MPL/2.0/. */ //! The high-level interface from script to constellation. Using this abstract interface helps //! reduce coupling...
<T: Deserialize + Serialize>(pub IpcSender<T>); impl<T: Deserialize + Serialize> ConstellationChan<T> { pub fn new() -> (IpcReceiver<T>, ConstellationChan<T>) { let (chan, port) = ipc::channel().unwrap(); (port, ConstellationChan(chan)) } } impl<T: Serialize + Deserialize> Clone for Constellat...
ConstellationChan
identifier_name
constellation_msg.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 http://mozilla.org/MPL/2.0/. */ //! The high-level interface from script to constellation. Using this abstract interface helps //! reduce coupling...
// call to PipelineId::new() returning (0,0), which is checked with an // assert in handle_init_load(). pub fn fake_root_pipeline_id() -> PipelineId { PipelineId { namespace_id: PipelineNamespaceId(0), index: PipelineIndex(0), } } } impl fmt::Display for Pipeline...
// TODO(gw): This should be removed. It's only required because of the code // that uses it in the devtools lib.rs file (which itself is a TODO). Once // that is fixed, this should be removed. It also relies on the first
random_line_split
htmlparagraphelement.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 http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding; use dom::bindings::js::Root; use dom::document:...
HTMLParagraphElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLParagraphElement> { ...
impl HTMLParagraphElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLParagraphElement {
random_line_split
htmlparagraphelement.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 http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding; use dom::bindings::js::Root; use dom::document:...
{ htmlelement: HTMLElement } impl HTMLParagraphElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLParagraphElement { HTMLParagraphElement { htmlelement: HTMLElement::new_inherited(loca...
HTMLParagraphElement
identifier_name
identifiers.rs
extern crate memmap; use self::memmap::{Mmap, Protection}; use std::collections::HashMap; use std::io::BufRead; use std::process::Command; use std::str; use rustc_serialize::json; use crate::config; fn uppercase(s: &[u8]) -> Vec<u8> { let mut result = vec![]; for i in 0..s.len() { result.push(if s[i...
result.push(IdentResult { id: id, symbol: symbol.to_string(), }); if result.len() == max_results { break; } } result } pub fn lookup_json( &self, needle: &str, complete: bo...
{ id = demangled; }
conditional_block
identifiers.rs
extern crate memmap; use self::memmap::{Mmap, Protection}; use std::collections::HashMap; use std::io::BufRead; use std::process::Command; use std::str; use rustc_serialize::json; use crate::config; fn uppercase(s: &[u8]) -> Vec<u8> { let mut result = vec![]; for i in 0..s.len() { result.push(if s[i...
None => return vec![], }; let start = self.bisect(needle.as_bytes(), false); let end = self.bisect(needle.as_bytes(), true); let mut result = vec![]; let bytes: &[u8] = unsafe { mmap.as_slice() }; let slice = &bytes[start..end]; for line in slice.li...
let mmap = match self.mmap { Some(ref m) => m,
random_line_split
identifiers.rs
extern crate memmap; use self::memmap::{Mmap, Protection}; use std::collections::HashMap; use std::io::BufRead; use std::process::Command; use std::str; use rustc_serialize::json; use crate::config; fn uppercase(s: &[u8]) -> Vec<u8> { let mut result = vec![]; for i in 0..s.len() { result.push(if s[i...
(&self, needle: &[u8], upper_bound: bool) -> usize { let mut needle = uppercase(needle); if upper_bound { needle.push('~' as u8); } let mut first = 0; let mut count = match self.mmap { Some(ref m) => m.len(), None => return 0, }; ...
bisect
identifier_name
identifiers.rs
extern crate memmap; use self::memmap::{Mmap, Protection}; use std::collections::HashMap; use std::io::BufRead; use std::process::Command; use std::str; use rustc_serialize::json; use crate::config; fn uppercase(s: &[u8]) -> Vec<u8> { let mut result = vec![]; for i in 0..s.len() { result.push(if s[i...
let suffix = &id[needle.len()..]; if suffix.contains(':') || suffix.contains('.') || (complete && suffix.len() > 0) { continue; } } if!fold_case &&!id.starts_with(needle) { continue; } le...
{ let mmap = match self.mmap { Some(ref m) => m, None => return vec![], }; let start = self.bisect(needle.as_bytes(), false); let end = self.bisect(needle.as_bytes(), true); let mut result = vec![]; let bytes: &[u8] = unsafe { mmap.as_slice() }; ...
identifier_body
image.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/. */ //! CSS handling for the computed value of //! [`image`][image]s //! //! [image]: https://drafts.csswg.org/css-im...
LineDirection::Corner(x, y) => SpecifiedLineDirection::Corner(x, y), } } }
LineDirection::Vertical(y) => SpecifiedLineDirection::Vertical(y),
random_line_split
image.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/. */ //! CSS handling for the computed value of //! [`image`][image]s //! //! [image]: https://drafts.csswg.org/css-im...
<W>(&self, dest: &mut CssWriter<W>, compat_mode: GradientCompatMode) -> fmt::Result where W: Write, { match *self { LineDirection::Angle(ref angle) => angle.to_css(dest), LineDirection::Horizontal(x) => { if compat_mode == GradientCompatMode::Modern { ...
to_css
identifier_name
image.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/. */ //! CSS handling for the computed value of //! [`image`][image]s //! //! [image]: https://drafts.csswg.org/css-im...
}
{ match *computed { LineDirection::Angle(ref angle) => { SpecifiedLineDirection::Angle(ToComputedValue::from_computed_value(angle)) }, LineDirection::Horizontal(x) => SpecifiedLineDirection::Horizontal(x), LineDirection::Vertical(y) => SpecifiedLin...
identifier_body
arithmetic_infix_ast_span.rs
extern crate peg; peg::parser!( grammar arithmetic() for str { rule ident() -> &'input str = $(['a'..='z']+) pub rule expression() -> Node = precedence!{ start:position!() node:@ end:position!() { Node { start, node, end} } -- x:(@) "+" y:@ { Op::Add(Box::new(x), Box::new(y)) } ...
Box::new(Node { start: 4, end: 5, node: Op::Ident("c".into()) }) ) }) ) } ); }
{ assert_eq!(arithmetic::expression("a+b*c").unwrap(), Node { start: 0, end: 5, node: Op::Add( Box::new(Node { start: 0, end: 1, node: Op::Ident("a".into()) }), Box...
identifier_body
arithmetic_infix_ast_span.rs
extern crate peg; peg::parser!( grammar arithmetic() for str { rule ident() -> &'input str = $(['a'..='z']+) pub rule expression() -> Node = precedence!{ start:position!() node:@ end:position!() { Node { start, node, end} } -- x:(@) "+" y:@ { Op::Add(Box::new(x), Box::new(y)) } ...
Box::new(Node { start: 2, end: 3, node: Op::Ident("b".into()) }), Box::new(Node { start: 4, end: 5, ...
end: 5, node: Op::Mul(
random_line_split
arithmetic_infix_ast_span.rs
extern crate peg; peg::parser!( grammar arithmetic() for str { rule ident() -> &'input str = $(['a'..='z']+) pub rule expression() -> Node = precedence!{ start:position!() node:@ end:position!() { Node { start, node, end} } -- x:(@) "+" y:@ { Op::Add(Box::new(x), Box::new(y)) } ...
(){ assert_eq!(arithmetic::expression("a+b*c").unwrap(), Node { start: 0, end: 5, node: Op::Add( Box::new(Node { start: 0, end: 1, node: Op::Ident("a".into()) }), B...
main
identifier_name
derive.rs
use predicates::prelude::*; use qualia::{object, ConversionError, Object, Result}; use qualia_derive::ObjectShape; use std::convert::TryFrom; #[derive(Debug, ObjectShape, PartialEq)] struct Shape { name: String, width: i64, height: i64, } fn result_is_err_matching<T, E: std::error::Error>(r: Result<T, E>,...
Shape::try_from(object!("name" => 4, "width" => 8, "height" => 11)), "name.*string", )); assert!(result_is_err_matching( Shape::try_from(object!("name" => "letter", "width" => "potato", "height" => 11)), "width.*number", )); Ok(()) } #[test] fn can_convert_to_object() ...
} #[test] fn converting_fails_when_fields_wrong_type() -> Result<(), ConversionError> { assert!(result_is_err_matching(
random_line_split
derive.rs
use predicates::prelude::*; use qualia::{object, ConversionError, Object, Result}; use qualia_derive::ObjectShape; use std::convert::TryFrom; #[derive(Debug, ObjectShape, PartialEq)] struct
{ name: String, width: i64, height: i64, } fn result_is_err_matching<T, E: std::error::Error>(r: Result<T, E>, pattern: &str) -> bool { predicate::str::is_match(pattern) .unwrap() .eval(&r.err().unwrap().to_string()) } #[test] fn can_convert_from_object() -> Result<(), ConversionError> ...
Shape
identifier_name
derive.rs
use predicates::prelude::*; use qualia::{object, ConversionError, Object, Result}; use qualia_derive::ObjectShape; use std::convert::TryFrom; #[derive(Debug, ObjectShape, PartialEq)] struct Shape { name: String, width: i64, height: i64, } fn result_is_err_matching<T, E: std::error::Error>(r: Result<T, E>,...
#[test] fn can_convert_from_object() -> Result<(), ConversionError> { assert_eq!( Shape::try_from(object!("name" => "letter", "width" => 8, "height" => 11))?, Shape { name: "letter".to_string(), width: 8, height: 11 } ); Ok(()) } #[test] fn con...
{ predicate::str::is_match(pattern) .unwrap() .eval(&r.err().unwrap().to_string()) }
identifier_body
lib.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 ...
<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T { assert!(low < high, "Rng.gen_range called with low >= high"); Range::new(low, high).ind_sample(self) } /// Return a bool with a 1 in n chance of true /// /// # Example /// /// ```rust /// use std::rand::{task_r...
gen_range
identifier_name
lib.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 ...
/// Deprecated name for `choose()`. #[deprecated = "replaced by.choose()"] fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> { self.choose(values) } /// Shuffle a mutable slice in place. /// /// # Example /// /// ```rust /// use std::rand::{task_rng,...
{ if values.is_empty() { None } else { Some(&values[self.gen_range(0u, values.len())]) } }
identifier_body
lib.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 t = x ^ (x << 11); self.x = self.y; self.y = self.z; self.z = self.w; let w = self.w; self.w = w ^ (w >> 19) ^ (t ^ (t >> 8)); self.w } } impl SeedableRng<[u32,.. 4]> for XorShiftRng { /// Reseed an XorShiftRng. This will fail if `seed` is entirely 0....
#[inline] fn next_u32(&mut self) -> u32 { let x = self.x;
random_line_split
lib.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 ...
*byte = (num & 0xff) as u8; num >>= 8; count -= 1; } } /// Return a random value of a `Rand` type. /// /// # Example /// /// ```rust /// use std::rand::{task_rng, Rng}; /// /// let mut rng = task_rng(); /// let x: uint = rng.gen(); ...
{ // we could micro-optimise here by generating a u32 if // we only need a few more bytes to fill the vector // (i.e. at most 4). num = self.next_u64(); count = 8; }
conditional_block
proptest_types.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account::{xus_currency_code, Account, AccountData, AccountRoleSpecifier}; use proptest::prelude::*; impl Arbitrary for Account { type Parameters = (); fn arbitrary_with(_params: ()) -> Self::Strategy { // Pro...
sequence_number, sent_events_count, received_events_count, AccountRoleSpecifier::default(), // TODO: Vary account type? ) }, ) } }
{ // Pick sequence numbers and event counts in a smaller range so that valid transactions can // be generated. // XXX should we also test edge cases around large sequence numbers? let sequence_strategy = 0u64..(1 << 32); let event_count_strategy = 0u64..(1 << 32); ( ...
identifier_body
proptest_types.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account::{xus_currency_code, Account, AccountData, AccountRoleSpecifier}; use proptest::prelude::*; impl Arbitrary for Account { type Parameters = (); fn arbitrary_with(_params: ()) -> Self::Strategy { // Pro...
(balance_strategy: impl Strategy<Value = u64>) -> impl Strategy<Value = Self> { // Pick sequence numbers and event counts in a smaller range so that valid transactions can // be generated. // XXX should we also test edge cases around large sequence numbers? let sequence_strategy = 0u64.....
strategy
identifier_name
proptest_types.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account::{xus_currency_code, Account, AccountData, AccountRoleSpecifier}; use proptest::prelude::*; impl Arbitrary for Account { type Parameters = (); fn arbitrary_with(_params: ()) -> Self::Strategy { // Pro...
event_count_strategy, ) .prop_map( |(account, balance, sequence_number, sent_events_count, received_events_count)| { AccountData::with_account_and_event_counts( account, balance, xu...
balance_strategy, sequence_strategy, event_count_strategy.clone(),
random_line_split
gainnode.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::audionode::AudioNode; use crate::dom::audioparam::AudioParam; use crate::dom::baseaudiocontext::B...
(&self) -> DomRoot<AudioParam> { DomRoot::from_ref(&self.gain) } } impl<'a> From<&'a GainOptions> for GainNodeOptions { fn from(options: &'a GainOptions) -> Self { Self { gain: *options.gain, } } }
Gain
identifier_name
gainnode.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::audionode::AudioNode; use crate::dom::audioparam::AudioParam; use crate::dom::baseaudiocontext::B...
#[allow(non_snake_case)] pub fn Constructor( window: &Window, context: &BaseAudioContext, options: &GainOptions, ) -> Fallible<DomRoot<GainNode>> { GainNode::new(window, context, options) } } impl GainNodeMethods for GainNode { // https://webaudio.github.io/web-aud...
{ let node = GainNode::new_inherited(window, context, options)?; Ok(reflect_dom_object(Box::new(node), window)) }
identifier_body
gainnode.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::audionode::AudioNode; use crate::dom::audioparam::AudioParam; use crate::dom::baseaudiocontext::B...
node, gain: Dom::from_ref(&gain), }) } #[allow(unrooted_must_root)] pub fn new( window: &Window, context: &BaseAudioContext, options: &GainOptions, ) -> Fallible<DomRoot<GainNode>> { let node = GainNode::new_inherited(window, context, opti...
Ok(GainNode {
random_line_split
cipherstate.rs
use crypto_types::*; pub trait CipherStateType { fn name(&self, out: &mut [u8]) -> usize; fn set(&mut self, key: &[u8], n: u64); fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]); fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool; fn encryp...
cipher : C, n : u64, has_key : bool, overflow: bool } impl<C: CipherType + Default> CipherStateType for CipherState<C> { fn name(&self, out: &mut [u8]) -> usize { self.cipher.name(out) } fn set(&mut self, key: &[u8], n: u64) { self.cipher.set(key); self.n = n; ...
} #[derive(Default)] pub struct CipherState<C: CipherType + Default> {
random_line_split
cipherstate.rs
use crypto_types::*; pub trait CipherStateType { fn name(&self, out: &mut [u8]) -> usize; fn set(&mut self, key: &[u8], n: u64); fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]); fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool; fn encry...
} fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool { assert!(self.has_key &&!self.overflow); let result = self.cipher.decrypt(self.n, authtext, ciphertext, out); self.n += 1; if self.n == 0 { self.overflow = true; } ...
{ self.overflow = true; }
conditional_block
cipherstate.rs
use crypto_types::*; pub trait CipherStateType { fn name(&self, out: &mut [u8]) -> usize; fn set(&mut self, key: &[u8], n: u64); fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]); fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool; fn encry...
fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]) { assert!(self.has_key &&!self.overflow); self.cipher.encrypt(self.n, authtext, plaintext, out); self.n += 1; if self.n == 0 { self.overflow = true; } } fn decrypt_ad(&mut self, ...
{ self.cipher.set(key); self.n = n; self.has_key = true; self.overflow = false; }
identifier_body
cipherstate.rs
use crypto_types::*; pub trait CipherStateType { fn name(&self, out: &mut [u8]) -> usize; fn set(&mut self, key: &[u8], n: u64); fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]); fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool; fn encry...
(&mut self, key: &[u8], n: u64) { self.cipher.set(key); self.n = n; self.has_key = true; self.overflow = false; } fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]) { assert!(self.has_key &&!self.overflow); self.cipher.encrypt(self.n, auth...
set
identifier_name
no_1207_unique_number_of_occurrences.rs
struct Solution; use std::collections::{HashMap, HashSet}; impl Solution { pub fn unique_occurrences(arr: Vec<i32>) -> bool { let mut cnts = HashMap::new(); for n in arr { *cnts.entry(n).or_insert(0) += 1; } let mut times = HashSet::new(); for (_, cnt) in cnts.int...
true } } #[cfg(test)] mod tests { use super::*; #[test] fn test_unique_occurrences() { assert_eq!(Solution::unique_occurrences(vec![1, 2, 2, 1, 1, 3]), true); assert_eq!(Solution::unique_occurrences(vec![1, 2]), false); assert_eq!( Solution::unique_occurrenc...
return false; } }
random_line_split
no_1207_unique_number_of_occurrences.rs
struct Solution; use std::collections::{HashMap, HashSet}; impl Solution { pub fn unique_occurrences(arr: Vec<i32>) -> bool { let mut cnts = HashMap::new(); for n in arr { *cnts.entry(n).or_insert(0) += 1; } let mut times = HashSet::new(); for (_, cnt) in cnts.int...
::*; #[test] fn test_unique_occurrences() { assert_eq!(Solution::unique_occurrences(vec![1, 2, 2, 1, 1, 3]), true); assert_eq!(Solution::unique_occurrences(vec![1, 2]), false); assert_eq!( Solution::unique_occurrences(vec![-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]), true...
} } #[cfg(test)] mod tests { use super
conditional_block
no_1207_unique_number_of_occurrences.rs
struct Solution; use std::collections::{HashMap, HashSet}; impl Solution { pub fn unique_occurrences(arr: Vec<i32>) -> bool { let mut cnts = HashMap::new(); for n in arr { *cnts.entry(n).or_insert(0) += 1; } let mut times = HashSet::new(); for (_, cnt) in cnts.int...
3]), true); assert_eq!(Solution::unique_occurrences(vec![1, 2]), false); assert_eq!( Solution::unique_occurrences(vec![-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]), true ); } }
ces(vec![1, 2, 2, 1, 1,
identifier_name
no_1207_unique_number_of_occurrences.rs
struct Solution; use std::collections::{HashMap, HashSet}; impl Solution { pub fn unique_occurrences(arr: Vec<i32>) -> bool
use super::*; #[test] fn test_ unique_occurrences() { assert_eq!(Solution::unique_occurrences(vec![1, 2, 2, 1, 1, 3]), true); assert_eq!(Solution::unique_occurrences(vec![1, 2]), false); assert_eq!( Solution::unique_occurrences(vec![-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]), ...
{ let mut cnts = HashMap::new(); for n in arr { *cnts.entry(n).or_insert(0) += 1; } let mut times = HashSet::new(); for (_, cnt) in cnts.into_iter() { // 如果 cnt 不在 times 中,insert 返回 true,否则返回 false // 如果 cnt 已经存在于 times 中,则有两个值出现了同样的次数。 ...
identifier_body
class-cast-to-trait-multiple-types.rs
// 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/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ meows: uint, how_hungry: int, name: ~str, } impl noisy for cat { fn speak(&mut self) -> int { self.meow() as int } } impl cat { pub fn meow_count(&self) -> uint { self.meows } } impl cat { fn meow(&mut self) -> uint { println!("Meow"); self.meows += 1u; ...
cat
identifier_name
class-cast-to-trait-multiple-types.rs
// 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/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
annoy_neighbors(&mut nyan); annoy_neighbors(&mut whitefang); assert_eq!(nyan.meow_count(), 10u); assert_eq!(whitefang.volume, 1); }
} pub fn main() { let mut nyan: cat = cat(0u, 2, "nyan".to_owned()); let mut whitefang: dog = dog();
random_line_split
class-cast-to-trait-multiple-types.rs
// 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/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
if self.barks % 10u == 0u { self.volume -= 2; } println!("Grrr {} {}", self.barks, self.volume); self.volume } } impl noisy for dog { fn speak(&mut self) -> int { self.bark() } } fn dog() -> dog { dog { volume: 0, barks: 0u } } #[deriving...
{ self.volume += 1; }
conditional_block
class-cast-to-trait-multiple-types.rs
// 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/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl noisy for dog { fn speak(&mut self) -> int { self.bark() } } fn dog() -> dog { dog { volume: 0, barks: 0u } } #[deriving(Clone)] struct cat { meows: uint, how_hungry: int, name: ~str, } impl noisy for cat { fn speak(&mut self) -> int { self.meow() a...
{ println!("Woof {} {}", self.barks, self.volume); self.barks += 1u; if self.barks % 3u == 0u { self.volume += 1; } if self.barks % 10u == 0u { self.volume -= 2; } println!("Grrr {} {}", self.barks, self.volume); self.volume }
identifier_body
lib.rs
// Copyright (c) 2014, 2015 Robert Clipsham <robert@octarineparrot.com> // // 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. This file may not be copied, modifi...
//! }; //! //! let mut iter = rx.iter(); //! loop { //! match iter.next() { //! Ok(packet) => { //! // Constructs a single packet, the same length as the the one received, //! // using the provided closure. This allows the packet to be constructed //! ...
//! Ok((tx, rx)) => (tx, rx), //! Err(e) => panic!("An error occurred when creating the datalink channel: {}", e)
random_line_split
issue-43893.rs
// Copyright 2016 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 ...
; // @has foo/trait.SomeTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#19' impl SomeTrait for usize {} // @has foo/trait.SomeTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#22-24' impl SomeTrait for SomeStruct { // deliberately multi-line impl } pub trait AnotherTrait {} // @has foo/trait.Another...
SomeStruct
identifier_name
issue-43893.rs
// Copyright 2016 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 ...
impl SomeTrait for SomeStruct { // deliberately multi-line impl } pub trait AnotherTrait {} // @has foo/trait.AnotherTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#29' impl<T> AnotherTrait for T {}
// @has foo/trait.SomeTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#19' impl SomeTrait for usize {} // @has foo/trait.SomeTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#22-24'
random_line_split
transaction.rs
//! Transaction parsing and verification //! //! use std::fmt; use std::time::{Instant,Duration}; use itertools::Itertools; use buffer::*; use hash::*; use script::context; use ffi; use store; use store::TxPtr; use store::Record; use store::HashIndexGuard; use store::TxIndex; const MAX_TRANSACTION_SIZE: usize = 1...
} type TransactionResult<T> = Result<T, TransactionError>; impl From<EndOfBufferError> for TransactionError { fn from(_: EndOfBufferError) -> TransactionError { TransactionError::UnexpectedEndOfData } } /// A transaction represents a parsed transaction /// /// It always contains a reference to the...
stats: TransactionStats },
random_line_split
transaction.rs
//! Transaction parsing and verification //! //! use std::fmt; use std::time::{Instant,Duration}; use itertools::Itertools; use buffer::*; use hash::*; use script::context; use ffi; use store; use store::TxPtr; use store::Record; use store::HashIndexGuard; use store::TxIndex; const MAX_TRANSACTION_SIZE: usize = 1...
(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { fn disp(d: Duration) -> u64 { d.as_secs() * 1_000_000 + d.subsec_nanos() as u64 / 1_000}; write!(fmt, "m,c,h: {},{},{} | wr:{},{} | rd:{},{} | s:{}, bt:{}", disp(self.merkle), disp(self.cloning), disp(self.hashi...
fmt
identifier_name
lib.rs
//! # urlshortener //! //! An easy library for retrieving short urls. //! //! ## Usage //! //! Creating a short URL via a specified provider is very simple: //! //! ```rust,no_run //! use urlshortener::{providers::Provider, client::UrlShortener}; //! //! let us = UrlShortener::new().unwrap(); //! let short_url = us.gen...
//! assert!(short_url.is_ok()); //! ``` #![deny(missing_docs)] #![deny(warnings)] /// A urlshortener http client for performing requests. #[cfg(feature = "client")] pub mod client; pub mod providers; /// A request builders for sending via http client. pub mod request; /// A prelude module with main useful stuff. pub ...
//! let us = UrlShortener::new().unwrap(); //! let key = "MY_API_KEY"; //! let short_url = us.generate("https://my-long-url.com", &Provider::GooGl { api_key: //! key.to_owned() });
random_line_split
hash_index.rs
//! Index that maps hashes to content pointers //! //! This is used for transactions & blockheaders; the values found for a hash can be: //! //! * a single fileptr pointing to a transaction //! The transaction can be found at the ptr in block_content and is fully validated //! //! * a set of fileptr pointing to in...
} impl Node { fn new(hash: Hash32, leaf_ptr: IndexPtr) -> Self { Node { hash: hash.as_buf(), prev: IndexPtr::null(), next: IndexPtr::null(), leaf: leaf_ptr } } } // Returns the first 24-bits of the hash // // This is the index into the root-ha...
{ Leaf { value: value, next: IndexPtr::null() } }
identifier_body
hash_index.rs
//! Index that maps hashes to content pointers //! //! This is used for transactions & blockheaders; the values found for a hash can be: //! //! * a single fileptr pointing to a transaction //! The transaction can be found at the ptr in block_content and is fully validated //! //! * a set of fileptr pointing to in...
(&mut self, hash: Hash32) -> FindNodeResult { // use the first 24-bit as index in the root hash table let mut ptr = &self.hash_index_root[hash_to_index(hash)]; // from there, we follow the binary tree while!ptr.is_null() { let node: &Node = self.fileset.read_fixed(*ptr); ...
find_node
identifier_name
hash_index.rs
//! Index that maps hashes to content pointers //! //! This is used for transactions & blockheaders; the values found for a hash can be: //! //! * a single fileptr pointing to a transaction //! The transaction can be found at the ptr in block_content and is fully validated //! //! * a set of fileptr pointing to in...
} } } } } #[cfg(test)] mod tests { use super::Node; use std::mem; extern crate tempdir; extern crate rand; use std::path::PathBuf; use std::thread; use super::*; use self::rand::Rng; use config; use hash::Hash32Buf; use store...
{ return None; }
conditional_block
hash_index.rs
//! Index that maps hashes to content pointers //! //! This is used for transactions & blockheaders; the values found for a hash can be: //! //! * a single fileptr pointing to a transaction //! The transaction can be found at the ptr in block_content and is fully validated //! //! * a set of fileptr pointing to inpu...
// some messy ops for messy tests let output_tx1_ptr = TxPtr::new(0, tx.get_file_offset() -1); let output_hash = hash(output_tx1_ptr.get_file_offset() as usize); let input_ptr = TxPtr::new(0, tx.get_file_...
panic!("Expected only 1 tx or 1..n inputs"); } else { if tx.get_file_offset() > 2 {
random_line_split
lib.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 http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
{ pub attributeName: String, pub newValue: Option<String>, } impl Decodable for Modification { fn decode<D: Decoder>(d: &mut D) -> Result<Modification, D::Error> { d.read_struct("Modification", 2u, |d| Ok(Modification { attributeName: try!(d.read_struct_field("attributeN...
Modification
identifier_name
lib.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 http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
} //TODO: Include options for Warn, Debug, Info, Error messages from Console #[derive(Clone)] pub enum ConsoleMessage { LogMessage(String), //WarnMessage(String), }
{ d.read_struct("Modification", 2u, |d| Ok(Modification { attributeName: try!(d.read_struct_field("attributeName", 0u, |d| Decodable::decode(d))), newValue: match d.read_struct_field("newValue", 1u, |d| Decodable::decode(d)) { Ok(opt) => opt, ...
identifier_body
lib.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 http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
d.read_struct("Modification", 2u, |d| Ok(Modification { attributeName: try!(d.read_struct_field("attributeName", 0u, |d| Decodable::decode(d))), newValue: match d.read_struct_field("newValue", 1u, |d| Decodable::decode(d)) { Ok(opt) => opt, ...
impl Decodable for Modification { fn decode<D: Decoder>(d: &mut D) -> Result<Modification, D::Error> {
random_line_split
noise_image.rs
use crate::utils::color_gradient::Color; #[cfg(feature = "image")] use std::{self, path::Path}; const RASTER_MAX_WIDTH: u16 = 32_767; const RASTER_MAX_HEIGHT: u16 = 32_767; pub struct NoiseImage { size: (usize, usize), border_color: Color, map: Vec<Color>, } impl NoiseImage { pub fn new(width: usize,...
(&self, filename: &str) { // Create the output directory for the images, if it doesn't already exist let target_dir = Path::new("example_images/"); if!target_dir.exists() { std::fs::create_dir(target_dir).expect("failed to create example_images directory"); } //conc...
write_to_file
identifier_name
noise_image.rs
use crate::utils::color_gradient::Color; #[cfg(feature = "image")] use std::{self, path::Path}; const RASTER_MAX_WIDTH: u16 = 32_767; const RASTER_MAX_HEIGHT: u16 = 32_767; pub struct NoiseImage { size: (usize, usize), border_color: Color, map: Vec<Color>, } impl NoiseImage { pub fn new(width: usize,...
} let _ = image::save_buffer( &Path::new(&file_path), &*result, self.size.0 as u32, self.size.1 as u32, image::ColorType::Rgba8, ); println!("\nFinished generating {}", filename); } } impl Default for NoiseImage { fn...
{ // Create the output directory for the images, if it doesn't already exist let target_dir = Path::new("example_images/"); if !target_dir.exists() { std::fs::create_dir(target_dir).expect("failed to create example_images directory"); } //concatenate the directory t...
identifier_body
noise_image.rs
use crate::utils::color_gradient::Color; #[cfg(feature = "image")] use std::{self, path::Path}; const RASTER_MAX_WIDTH: u16 = 32_767; const RASTER_MAX_HEIGHT: u16 = 32_767; pub struct NoiseImage { size: (usize, usize), border_color: Color, map: Vec<Color>, } impl NoiseImage { pub fn new(width: usize,...
} pub fn size(&self) -> (usize, usize) { self.size } pub fn border_color(&self) -> Color { self.border_color } pub fn get_value(&self, x: usize, y: usize) -> Color { let (width, height) = self.size; if x < width && y < height { self.map[x + y * wi...
{ eprintln!("input point out of bounds") }
conditional_block
noise_image.rs
use crate::utils::color_gradient::Color; #[cfg(feature = "image")] use std::{self, path::Path}; const RASTER_MAX_WIDTH: u16 = 32_767; const RASTER_MAX_HEIGHT: u16 = 32_767; pub struct NoiseImage { size: (usize, usize), border_color: Color, map: Vec<Color>, } impl NoiseImage { pub fn new(width: usize,...
// An empty noise image was specified. Return a new blank, empty map. Self::initialize() } else { // New noise map size specified. Allocate a new Vec unless the current Vec is large // enough. let map_size = width * height; if self.map.capa...
assert!(width < RASTER_MAX_WIDTH as usize); assert!(height < RASTER_MAX_HEIGHT as usize); if width == 0 || height == 0 {
random_line_split
errors.rs
// Copyright 2016 Mozilla // // 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 writing, software...
} impl From<rusqlite::Error> for MentatError { fn from(error: rusqlite::Error) -> MentatError { MentatError::RusqliteError(error.to_string()) } } impl From<edn::ParseError> for MentatError { fn from(error: edn::ParseError) -> MentatError { MentatError::EdnParseError(error) } } impl F...
{ MentatError::IoError(error) }
identifier_body
errors.rs
// Copyright 2016 Mozilla // // 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 writing, software...
{ #[fail(display = "bad uuid {}", _0)] BadUuid(String), #[fail(display = "path {} already exists", _0)] PathAlreadyExists(String), #[fail(display = "variables {:?} unbound at query execution time", _0)] UnboundVariables(BTreeSet<String>), #[fail(display = "invalid argument name: '{}'", _...
MentatError
identifier_name
errors.rs
// Copyright 2016 Mozilla // // 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 writing, software...
} impl From<edn::ParseError> for MentatError { fn from(error: edn::ParseError) -> MentatError { MentatError::EdnParseError(error) } } impl From<mentat_db::DbError> for MentatError { fn from(error: mentat_db::DbError) -> MentatError { MentatError::DbError(error) } } impl From<mentat_qu...
random_line_split
error.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt::Display; use std::io; use std::num::ParseFloatError; use std::str::Utf8Error; use std::string::FromUtf8Error; use std::{error, str}; use error_code::{self, ErrorCode, ErrorCodeExt}; use quick_error::quick_error; use regex::Error as Regex...
Error::Encoding(err.utf8_error()) } } impl From<SerdeError> for Error { fn from(err: SerdeError) -> Error { box_err!("serde:{:?}", err) } } impl From<ParseFloatError> for Error { fn from(err: ParseFloatError) -> Error { box_err!("parse float: {:?}", err) } } impl From<tikv...
random_line_split
error.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt::Display; use std::io; use std::num::ParseFloatError; use std::str::Utf8Error; use std::string::FromUtf8Error; use std::{error, str}; use error_code::{self, ErrorCode, ErrorCodeExt}; use quick_error::quick_error; use regex::Error as Regex...
pub fn invalid_timezone(given_time_zone: impl Display) -> Error { let msg = format!("unknown or incorrect time zone: {}", given_time_zone); Error::Eval(msg, ERR_UNKNOWN_TIMEZONE) } pub fn division_by_zero() -> Error { let msg = "Division by 0"; Error::Eval(msg.into(), ERR_...
{ let msg = "Cast to signed converted positive out-of-range integer to it's negative complement"; Error::Eval(msg.into(), ERR_UNKNOWN) }
identifier_body
error.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt::Display; use std::io; use std::num::ParseFloatError; use std::str::Utf8Error; use std::string::FromUtf8Error; use std::{error, str}; use error_code::{self, ErrorCode, ErrorCodeExt}; use quick_error::quick_error; use regex::Error as Regex...
(error: Error) -> tipb::Error { let mut err = tipb::Error::default(); err.set_code(error.code()); err.set_msg(error.to_string()); err } } impl From<FromUtf8Error> for Error { fn from(err: FromUtf8Error) -> Error { Error::Encoding(err.utf8_error()) } } impl From<Serd...
from
identifier_name
cycle-trait-type-trait.rs
// Copyright 2015 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 ...
{ }
identifier_body
cycle-trait-type-trait.rs
// Copyright 2015 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 ...
(&self) -> Struct<i32> { Struct { c: *self } } } fn main() { }
get
identifier_name
cycle-trait-type-trait.rs
// 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. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allo...
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
random_line_split
meg_csar_list.rs
extern crate megam_api; extern crate term_painter; extern crate toml; extern crate rustc_serialize; extern crate megam_rustyprint; use self::megam_rustyprint::Printer; use self::megam_api::api::Api; use self::megam_api::util::csars::Csar; use self::rustc_serialize::json; use self::term_painter::ToStyle; use self::te...
; impl Csaroptions { pub fn list(&self) { let opts = Csar::new(); let api_call = head::api_call().unwrap(); let out = opts.list(json::encode(&api_call).unwrap()); match out { Ok(v) => { println!("{}", Green.bold().paint("CSARs\n")); ...
Csaroptions
identifier_name
meg_csar_list.rs
extern crate megam_api; extern crate term_painter; extern crate toml; extern crate rustc_serialize; extern crate megam_rustyprint; use self::megam_rustyprint::Printer; use self::megam_api::api::Api; use self::megam_api::util::csars::Csar; use self::rustc_serialize::json; use self::term_painter::ToStyle; use self::te...
let mut child = Vec::new(); child.push(x.link.to_string()); child.push(x.desc.to_string()); child.push(x.created_at.to_string()); parent.push(child); } a.set_body(parent); ...
for x in v.iter() {
random_line_split
meg_csar_list.rs
extern crate megam_api; extern crate term_painter; extern crate toml; extern crate rustc_serialize; extern crate megam_rustyprint; use self::megam_rustyprint::Printer; use self::megam_api::api::Api; use self::megam_api::util::csars::Csar; use self::rustc_serialize::json; use self::term_painter::ToStyle; use self::te...
}} }
{ println!("{}", Red.bold().paint("Not listing your CSARs You sure you created them? . Contact support@megam.io")); }
conditional_block
main.rs
use std::collections::HashSet; use std::env; use std::error::Error; use std::fs; use std::iter::FromIterator; fn main() { run().unwrap(); } fn get_lines() -> Vec<String> { let args: Vec<String> = env::args().collect(); let default_fname = "input.txt".into(); let fname = args.get(1).unwrap_or(&default_...
fn get_target(count: i32, is_max: bool) -> char { if is_max { if count >= 0 { '1' } else { '0' } } else { if count >= 0 { '0' } else { '1' } } } fn run() -> Result<(), Box<dyn Error>> { let lines = get_lin...
{ let mut lines_set: HashSet<String> = HashSet::from_iter(lines.iter().cloned()); for i in 0..12 { let count = get_count(lines_set.iter())[i]; for line in &lines_set.clone() { let target = get_target(count, get_max); if line.chars().nth(i).unwrap() != target { ...
identifier_body
main.rs
use std::collections::HashSet; use std::env; use std::error::Error; use std::fs; use std::iter::FromIterator; fn main() { run().unwrap(); } fn get_lines() -> Vec<String> { let args: Vec<String> = env::args().collect(); let default_fname = "input.txt".into(); let fname = args.get(1).unwrap_or(&default_...
} } positions } fn get_rate(lines: &Vec<String>, get_max: bool) -> Result<isize, Box<dyn Error>> { let counts = get_count(lines.iter()); Ok(isize::from_str_radix( &counts .iter() .map(|count| get_target(*count, get_max).to_string()) .collect::<Vec<_>>()...
{ -1 }
conditional_block
main.rs
use std::collections::HashSet; use std::env; use std::error::Error; use std::fs; use std::iter::FromIterator; fn main() { run().unwrap(); } fn get_lines() -> Vec<String> { let args: Vec<String> = env::args().collect(); let default_fname = "input.txt".into(); let fname = args.get(1).unwrap_or(&default_...
(lines: &Vec<String>, get_max: bool) -> Result<isize, Box<dyn Error>> { let counts = get_count(lines.iter()); Ok(isize::from_str_radix( &counts .iter() .map(|count| get_target(*count, get_max).to_string()) .collect::<Vec<_>>() .join(""), 2, )?) } ...
get_rate
identifier_name
main.rs
use std::collections::HashSet; use std::env; use std::error::Error; use std::fs; use std::iter::FromIterator; fn main() { run().unwrap(); } fn get_lines() -> Vec<String> { let args: Vec<String> = env::args().collect(); let default_fname = "input.txt".into(); let fname = args.get(1).unwrap_or(&default_...
if count >= 0 { '1' } else { '0' } } else { if count >= 0 { '0' } else { '1' } } } fn run() -> Result<(), Box<dyn Error>> { let lines = get_lines(); let gamma = get_rate(&lines, true)?; let epsilon = ge...
if is_max {
random_line_split
TestNativeLog1p.rs
/* * Copyright (C) 2016 The Android Open Source Project * * 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 app...
} float2 __attribute__((kernel)) testNativeLog1pFloat2Float2(float2 inV) { return native_log1p(inV); } float3 __attribute__((kernel)) testNativeLog1pFloat3Float3(float3 inV) { return native_log1p(inV); } float4 __attribute__((kernel)) testNativeLog1pFloat4Float4(float4 inV) { return native_log1p(inV); } ...
#pragma rs java_package_name(android.renderscript.cts) float __attribute__((kernel)) testNativeLog1pFloatFloat(float inV) { return native_log1p(inV);
random_line_split
issue-17302.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 ...
(&mut self) { let A(i) = *self; unsafe { DROPPED[i] = true; } } } fn main() { { Foo { _a: A(0), ..Foo { _a: A(1), _b: 2 } }; } unsafe { assert!(DROPPED[0]); assert!(DROPPED[1]); } }
drop
identifier_name
issue-17302.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
issue-17302.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 ...
{ { Foo { _a: A(0), ..Foo { _a: A(1), _b: 2 } }; } unsafe { assert!(DROPPED[0]); assert!(DROPPED[1]); } }
identifier_body
issue-10802.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 ...
impl Drop for DroppableEnum { fn drop(&mut self) { unsafe { DROPPED = true; } } } trait MyTrait { } impl MyTrait for Box<DroppableStruct> {} impl MyTrait for Box<DroppableEnum> {} struct Whatever { w: Box<MyTrait+'static> } impl Whatever { fn new(w: Box<MyTrait+'static>) -> Whatever { Wha...
fn drop(&mut self) { unsafe { DROPPED = true; } } }
random_line_split
issue-10802.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 ...
(&mut self) { unsafe { DROPPED = true; } } } trait MyTrait { } impl MyTrait for Box<DroppableStruct> {} impl MyTrait for Box<DroppableEnum> {} struct Whatever { w: Box<MyTrait+'static> } impl Whatever { fn new(w: Box<MyTrait+'static>) -> Whatever { Whatever { w: w } } } fn main() { {...
drop
identifier_name
issue-10802.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 ...
} trait MyTrait { } impl MyTrait for Box<DroppableStruct> {} impl MyTrait for Box<DroppableEnum> {} struct Whatever { w: Box<MyTrait+'static> } impl Whatever { fn new(w: Box<MyTrait+'static>) -> Whatever { Whatever { w: w } } } fn main() { { let f = box DroppableStruct; let _a =...
{ unsafe { DROPPED = true; } }
identifier_body
main.rs
extern crate rand; use rand::{thread_rng, Rng}; use std::{thread, time}; use std::fmt; #[derive(Clone)] struct Memento { money: u32, fruits: Vec<String>, } impl Memento { fn new(money: u32) -> Memento { Memento { money: money, fruits: Vec::new(), } } fn ge...
.fruits { m.add_fruit(f.clone()); } m } fn restore_memento(&mut self, memento: Memento) { self.money = memento.get_money(); self.fruits = memento.get_fruits(); } fn get_fruit(&mut self) -> String { let mut prefix = "".to_string(); let coin =...
for f in &self
identifier_name
main.rs
extern crate rand; use rand::{thread_rng, Rng}; use std::{thread, time}; use std::fmt; #[derive(Clone)] struct Memento { money: u32, fruits: Vec<String>, } impl Memento { fn new(money: u32) -> Memento { Memento { money: money, fruits: Vec::new(), } } fn ge...
impl Gamer { fn new(money: u32) -> Gamer { Gamer { money: money, fruits: Vec::new(), rng: thread_rng(), } } fn get_money(&self) -> u32 { self.money } fn bet(&mut self) { let dice = self.rng.gen_range(0, 7); if dice == 1 ...
rng: rand::ThreadRng, }
random_line_split
main.rs
extern crate rand; use rand::{thread_rng, Rng}; use std::{thread, time}; use std::fmt; #[derive(Clone)] struct Memento { money: u32, fruits: Vec<String>, } impl Memento { fn new(money: u32) -> Memento { Memento { money: money, fruits: Vec::new(), } } fn ge...
n = self.rng.gen_range(0, 1); if coin == 0 { prefix = "おいしい".to_string(); } let fruits = ["リンゴ", "ぶどう", "バナナ", "みかん"]; let index = self.rng.gen_range(0, fruits.len()); format!("{}{}", prefix, fruits[index].to_string()) } } impl fmt::Display for Gamer { fn fm...
fn get_fruit(&mut self) -> String { let mut prefix = "".to_string(); let coi
identifier_body
main.rs
extern crate rand; use rand::{thread_rng, Rng}; use std::{thread, time}; use std::fmt; #[derive(Clone)] struct Memento { money: u32, fruits: Vec<String>, } impl Memento { fn new(money: u32) -> Memento { Memento { money: money, fruits: Vec::new(), } } fn ge...
get_fruit(); println!("フルーツ({})をもらいました。", f); self.fruits.push(f); } else { println!("何も起こりませんでした。"); } } fn create_memento(&self) -> Memento { let mut m = Memento::new(self.money); for f in &self.fruits { m.add_fruit(f.cl...
oney /= 2; println!("所持金が半分になりました。"); } else if dice == 6 { let f = self.
conditional_block
errors.rs
use std::error; use std::fmt; #[derive(Debug)] pub struct Error(ErrorKind); #[derive(Debug)] pub(crate) enum ErrorKind { Raw(telegram_bot_raw::Error), Hyper(hyper::Error), Http(hyper::http::Error), Io(std::io::Error), InvalidMultipartFilename, } impl From<telegram_bot_raw::Error> for ErrorKind { ...
impl From<hyper::http::Error> for ErrorKind { fn from(error: hyper::http::Error) -> Self { ErrorKind::Http(error) } } impl From<std::io::Error> for ErrorKind { fn from(error: std::io::Error) -> Self { ErrorKind::Io(error) } } impl From<ErrorKind> for Error { fn from(kind: ErrorKin...
random_line_split
errors.rs
use std::error; use std::fmt; #[derive(Debug)] pub struct Error(ErrorKind); #[derive(Debug)] pub(crate) enum ErrorKind { Raw(telegram_bot_raw::Error), Hyper(hyper::Error), Http(hyper::http::Error), Io(std::io::Error), InvalidMultipartFilename, } impl From<telegram_bot_raw::Error> for ErrorKind { ...
(error: telegram_bot_raw::Error) -> Self { ErrorKind::Raw(error) } } impl From<hyper::Error> for ErrorKind { fn from(error: hyper::Error) -> Self { ErrorKind::Hyper(error) } } impl From<hyper::http::Error> for ErrorKind { fn from(error: hyper::http::Error) -> Self { ErrorKind::...
from
identifier_name
mdbook.rs
use std::path::{Path, PathBuf}; use std::fs::{self, File}; use std::io::Write; use std::error::Error; use {BookConfig, BookItem, theme, parse, utils}; use book::BookItems; use renderer::{Renderer, HtmlHandlebars}; use utils::{PathExt, create_path}; pub struct MDBook { config: BookConfig, pub content: Vec<Book...
&self.config.title } pub fn set_author(mut self, author: &str) -> Self { self.config.author = author.to_owned(); self } pub fn get_author(&self) -> &str { &self.config.author } // Construct book fn parse_summary(&mut self) -> Result<(), Box<Error>> { // W...
{
identifier_name
mdbook.rs
use std::path::{Path, PathBuf}; use std::fs::{self, File}; use std::io::Write; use std::error::Error; use {BookConfig, BookItem, theme, parse, utils}; use book::BookItems; use renderer::{Renderer, HtmlHandlebars}; use utils::{PathExt, create_path}; pub struct MDBook { config: BookConfig, pub content: Vec<Book...
self } pub fn get_title(&self) -> &str { &self.config.title } pub fn set_author(mut self, author: &str) -> Self { self.config.author = author.to_owned(); self } pub fn get_author(&self) -> &str { &self.config.author } // Construct book fn p...
} pub fn set_title(mut self, title: &str) -> Self { self.config.title = title.to_owned();
random_line_split
mdbook.rs
use std::path::{Path, PathBuf}; use std::fs::{self, File}; use std::io::Write; use std::error::Error; use {BookConfig, BookItem, theme, parse, utils}; use book::BookItems; use renderer::{Renderer, HtmlHandlebars}; use utils::{PathExt, create_path}; pub struct MDBook { config: BookConfig, pub content: Vec<Book...
debug!("[*]: init done"); Ok(()) } /// The `build()` method is the one where everything happens. First it parses `SUMMARY.md` to /// construct the book's structure in the form of a `Vec<BookItem>` and then calls `render()` /// method of the current renderer. /// /// It is the ...
ch.path != PathBuf::new() { let path = self.config.get_src().join(&ch.path); if !path.exists() { debug!("[*]: {:?} does not exist, trying to create file", path); try!(::std::fs::create_dir_all(path.parent().unwrap(...
conditional_block
mockstream.rs
// https://github.com/lazy-bitfield/rust-mockstream/pull/2 use std::io::{Cursor, Read, Result, Error, ErrorKind}; use std::error::Error as errorError; /// `FailingMockStream` mocks a stream which will fail upon read or write /// /// # Examples /// /// ``` /// use std::io::{Cursor, Read}; /// /// struct CountIo {} ///...
(&mut self, _: &mut [u8]) -> Result<usize> { self.error() } } #[test] fn test_failing_mock_stream_read() { let mut s = FailingMockStream::new(ErrorKind::BrokenPipe, "The dog ate the ethernet cable", 1); let mut v = [0; 4]; let error = s.read(v.as_mut()).unwrap_err(); assert_eq!(error.kind()...
read
identifier_name
mockstream.rs
// https://github.com/lazy-bitfield/rust-mockstream/pull/2 use std::io::{Cursor, Read, Result, Error, ErrorKind}; use std::error::Error as errorError; /// `FailingMockStream` mocks a stream which will fail upon read or write /// /// # Examples /// /// ``` /// use std::io::{Cursor, Read}; /// /// struct CountIo {} ///...
Err(Error::new(self.kind, self.message)) } } } impl Read for FailingMockStream { fn read(&mut self, _: &mut [u8]) -> Result<usize> { self.error() } } #[test] fn test_failing_mock_stream_read() { let mut s = FailingMockStream::new(ErrorKind::BrokenPipe, "The dog ate the eth...
{ self.repeat_count -= 1; }
conditional_block
mockstream.rs
// https://github.com/lazy-bitfield/rust-mockstream/pull/2 use std::io::{Cursor, Read, Result, Error, ErrorKind}; use std::error::Error as errorError; /// `FailingMockStream` mocks a stream which will fail upon read or write /// /// # Examples /// /// ``` /// use std::io::{Cursor, Read}; /// /// struct CountIo {} ///...
}
random_line_split
mockstream.rs
// https://github.com/lazy-bitfield/rust-mockstream/pull/2 use std::io::{Cursor, Read, Result, Error, ErrorKind}; use std::error::Error as errorError; /// `FailingMockStream` mocks a stream which will fail upon read or write /// /// # Examples /// /// ``` /// use std::io::{Cursor, Read}; /// /// struct CountIo {} ///...
} #[test] fn test_failing_mock_stream_read() { let mut s = FailingMockStream::new(ErrorKind::BrokenPipe, "The dog ate the ethernet cable", 1); let mut v = [0; 4]; let error = s.read(v.as_mut()).unwrap_err(); assert_eq!(error.kind(), ErrorKind::BrokenPipe); assert_eq!(error.description(), "The dog ...
{ self.error() }
identifier_body
no_std.rs
#![no_std] use sdl2_sys::*; use core::ptr::null_mut; fn main() { unsafe { let mut _window: *mut SDL_Window = null_mut(); let mut _surface: *mut SDL_Surface = null_mut(); if SDL_Init(SDL_INIT_VIDEO) < 0 { panic!("failed to initialize sdl2 with video"); }; _window...
SDL_WindowFlags::SDL_WINDOW_SHOWN as u32 ); if _window == null_mut() { panic!("failed to create window"); } _surface = SDL_GetWindowSurface(_window); SDL_FillRect(_surface, null_mut(), SDL_MapRGB((*_surface).format, 0xFF, 0xFF, 0x00)); SDL_Update...
b"hello_sdl2" as *const _ as *const i8, SDL_WINDOWPOS_UNDEFINED_MASK as i32, SDL_WINDOWPOS_UNDEFINED_MASK as i32, 640, 480,
random_line_split
no_std.rs
#![no_std] use sdl2_sys::*; use core::ptr::null_mut; fn main() { unsafe { let mut _window: *mut SDL_Window = null_mut(); let mut _surface: *mut SDL_Surface = null_mut(); if SDL_Init(SDL_INIT_VIDEO) < 0 { panic!("failed to initialize sdl2 with video"); }; _window...
_surface = SDL_GetWindowSurface(_window); SDL_FillRect(_surface, null_mut(), SDL_MapRGB((*_surface).format, 0xFF, 0xFF, 0x00)); SDL_UpdateWindowSurface(_window); SDL_Delay(5000); SDL_DestroyWindow(_window); SDL_Quit(); } }
{ panic!("failed to create window"); }
conditional_block
no_std.rs
#![no_std] use sdl2_sys::*; use core::ptr::null_mut; fn main()
_surface = SDL_GetWindowSurface(_window); SDL_FillRect(_surface, null_mut(), SDL_MapRGB((*_surface).format, 0xFF, 0xFF, 0x00)); SDL_UpdateWindowSurface(_window); SDL_Delay(5000); SDL_DestroyWindow(_window); SDL_Quit(); } }
{ unsafe { let mut _window: *mut SDL_Window = null_mut(); let mut _surface: *mut SDL_Surface = null_mut(); if SDL_Init(SDL_INIT_VIDEO) < 0 { panic!("failed to initialize sdl2 with video"); }; _window = SDL_CreateWindow( b"hello_sdl2" as *const _ as *co...
identifier_body
no_std.rs
#![no_std] use sdl2_sys::*; use core::ptr::null_mut; fn
() { unsafe { let mut _window: *mut SDL_Window = null_mut(); let mut _surface: *mut SDL_Surface = null_mut(); if SDL_Init(SDL_INIT_VIDEO) < 0 { panic!("failed to initialize sdl2 with video"); }; _window = SDL_CreateWindow( b"hello_sdl2" as *const _ as ...
main
identifier_name
lib.rs
// Copyright (c) 2014 by SiegeLord // // All rights reserved. Distributed under ZLib. For full terms see the file LICENSE. #![crate_name="allegro_font_sys"] #![crate_type = "lib"] #![allow(non_camel_case_types)] #![allow(non_camel_case_types, raw_pointer_derive)] extern crate libc; extern crate allegro_sys as allegr...
{ pub data: *mut c_void, pub height: c_int, pub vtable: *mut ALLEGRO_FONT_VTABLE, } #[repr(C)] pub struct ALLEGRO_FONT_VTABLE { pub font_height: Option<extern "C" fn(arg1: *const ALLEGRO_FONT) -> c_int>, pub font_ascent: Option<extern "C" fn(arg1: *const ALLEGRO_FONT) -> c_int>, pub font_descent: Opt...
ALLEGRO_FONT
identifier_name
lib.rs
// Copyright (c) 2014 by SiegeLord // // All rights reserved. Distributed under ZLib. For full terms see the file LICENSE. #![crate_name="allegro_font_sys"] #![crate_type = "lib"] #![allow(non_camel_case_types)] #![allow(non_camel_case_types, raw_pointer_derive)] extern crate libc; extern crate allegro_sys as allegr...
pub struct ALLEGRO_FONT { pub data: *mut c_void, pub height: c_int, pub vtable: *mut ALLEGRO_FONT_VTABLE, } #[repr(C)] pub struct ALLEGRO_FONT_VTABLE { pub font_height: Option<extern "C" fn(arg1: *const ALLEGRO_FONT) -> c_int>, pub font_ascent: Option<extern "C" fn(arg1: *const ALLEGRO_FONT) -> c_int>,...
use allegro::{ALLEGRO_USTR, ALLEGRO_COLOR, ALLEGRO_BITMAP}; #[repr(C)] #[derive(Copy, Clone)]
random_line_split
publisher_to_multiple_subscribers.rs
use crossbeam::channel::unbounded; use std::process::Command; mod util; mod msg { rosrust::rosmsg_include!(std_msgs / String, rosgraph_msgs / Log); } #[test] fn
() { let _roscore = util::run_roscore_for(util::Language::Multi, util::Feature::Publisher); let _subscriber_cpp = util::ChildProcessTerminator::spawn( Command::new("rosrun") .arg("roscpp_tutorials") .arg("listener") .arg("__name:=listener_cpp"), ); let _subscribe...
publisher_to_multiple_subscribers
identifier_name
publisher_to_multiple_subscribers.rs
use crossbeam::channel::unbounded; use std::process::Command; mod util; mod msg { rosrust::rosmsg_include!(std_msgs / String, rosgraph_msgs / Log); } #[test] fn publisher_to_multiple_subscribers()
rosrust::init("hello_world_talker"); let (tx, rx) = unbounded(); let _log_subscriber = rosrust::subscribe::<msg::rosgraph_msgs::Log, _>("/rosout_agg", 100, move |data| { tx.send((data.level, data.msg)).unwrap(); }) .unwrap(); let publisher = rosrust::publish::<msg::...
{ let _roscore = util::run_roscore_for(util::Language::Multi, util::Feature::Publisher); let _subscriber_cpp = util::ChildProcessTerminator::spawn( Command::new("rosrun") .arg("roscpp_tutorials") .arg("listener") .arg("__name:=listener_cpp"), ); let _subscribe...
identifier_body