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
index.rs
/// Index into a vector-like object #[derive(Debug, PartialEq, Copy, Clone)] pub(crate) enum Index { /// Index starting from the beginning of the vector, where `Forward(0)` /// is the first element Forward(usize), /// Index starting from the end of the vector, where `Backward(0)` is the /// last ele...
(&self, vector_length: usize) -> Option<usize> { match *self { Index::Forward(n) => Some(n), Index::Backward(n) => if n >= vector_length { None } else { Some(vector_length - (n + 1)) }, } } /// Construct an index us...
resolve
identifier_name
mod.rs
/*! Contains everything related to vertex sources. When you draw, you need to pass one or several sources of vertex attributes. This is done with the first parameter to the `draw` function. ## Vertex The main trait of this module is `Vertex`, which must be implemented on structs whose instances describe individual v...
} macro_rules! impl_for_tuple { ($t:ident) => ( impl<'a, $t> MultiVerticesSource<'a> for ($t,) where $t: IntoVerticesSource<'a> { type Iterator = IntoIter<VerticesSource<'a>>; fn iter(self) -> IntoIter<VerticesSource<'a>> { Some(self.0.into_vert...
{ Some(self.into_vertices_source()).into_iter() }
identifier_body
mod.rs
/*! Contains everything related to vertex sources. When you draw, you need to pass one or several sources of vertex attributes. This is done with the first parameter to the `draw` function. ## Vertex The main trait of this module is `Vertex`, which must be implemented on structs whose instances describe individual v...
let ($t1, $($t2),+) = self; Some($t1.into_vertices_source()).into_iter().chain(($($t2),+).iter()) } } impl_for_tuple!($($t2),+); ); } impl_for_tuple!(A, B, C, D, E, F, G); /// Trait for structures that represent a vertex. /// /// Instead of implementing...
fn iter(self) -> Chain<<($t1,) as MultiVerticesSource<'a>>::Iterator, <($($t2),+) as MultiVerticesSource<'a>>::Iterator> {
random_line_split
mod.rs
/*! Contains everything related to vertex sources. When you draw, you need to pass one or several sources of vertex attributes. This is done with the first parameter to the `draw` function. ## Vertex The main trait of this module is `Vertex`, which must be implemented on structs whose instances describe individual v...
<'a>(BufferViewAnySlice<'a>, &'a VertexFormat); impl<'a> IntoVerticesSource<'a> for PerInstance<'a> { fn into_vertices_source(self) -> VerticesSource<'a> { VerticesSource::VertexBuffer(self.0, self.1, true) } } /// Objects that describe multiple vertex sources. pub trait MultiVerticesSource<'a> { ...
PerInstance
identifier_name
issue-2631-b.rs
// Copyright 2012-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-MI...
request::<isize>(&m); }
let mut m: req::header_map = HashMap::new(); m.insert("METHOD".to_string(), Rc::new(RefCell::new(v)));
random_line_split
issue-2631-b.rs
// Copyright 2012-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-MI...
() { let v = vec!(Rc::new("hi".to_string())); let mut m: req::header_map = HashMap::new(); m.insert("METHOD".to_string(), Rc::new(RefCell::new(v))); request::<isize>(&m); }
main
identifier_name
issue-2631-b.rs
// Copyright 2012-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-MI...
{ let v = vec!(Rc::new("hi".to_string())); let mut m: req::header_map = HashMap::new(); m.insert("METHOD".to_string(), Rc::new(RefCell::new(v))); request::<isize>(&m); }
identifier_body
initramfs.rs
use std::process::Command; use ask; pub fn rebuild() -> bool
} } true }
{ println!(); println!("Step 4: Update initramfs"); let mut skip_ask = false; if ask::yesno("Are you using mkinitcpio with the default kernel ('linux')?") { let status = Command::new("/usr/bin/sudo").arg("/usr/bin/mkinitcpio") .arg("-p").arg("linux").status().expect("Failed to run mk...
identifier_body
initramfs.rs
use std::process::Command; use ask; pub fn
() -> bool { println!(); println!("Step 4: Update initramfs"); let mut skip_ask = false; if ask::yesno("Are you using mkinitcpio with the default kernel ('linux')?") { let status = Command::new("/usr/bin/sudo").arg("/usr/bin/mkinitcpio") .arg("-p").arg("linux").status().expect("Failed...
rebuild
identifier_name
initramfs.rs
use std::process::Command; use ask; pub fn rebuild() -> bool { println!(); println!("Step 4: Update initramfs"); let mut skip_ask = false; if ask::yesno("Are you using mkinitcpio with the default kernel ('linux')?") { let status = Command::new("/usr/bin/sudo").arg("/usr/bin/mkinitcpio") ...
true }
{ if !ask::yesno("Done?") { println!("Aborted."); return false; } }
conditional_block
initramfs.rs
use std::process::Command;
pub fn rebuild() -> bool { println!(); println!("Step 4: Update initramfs"); let mut skip_ask = false; if ask::yesno("Are you using mkinitcpio with the default kernel ('linux')?") { let status = Command::new("/usr/bin/sudo").arg("/usr/bin/mkinitcpio") .arg("-p").arg("linux").status()....
use ask;
random_line_split
background.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Background", inherited=False) %> ...
allow_quirks=True, flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER", )} ${helpers.predefined_type("background-image", "ImageLayer", initial_value="Either::First(None_)", initial_specified_value="Either::First(None_)", spec="https://drafts.csswg.org/css-backgrounds/#the-b...
initial_specified_value="SpecifiedValue::transparent()", spec="https://drafts.csswg.org/css-backgrounds/#background-color", animation_value_type="AnimatedColor", ignored_when_colors_disabled=True,
random_line_split
regions-bounds.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 ...
<'a,'b>(e: an_enum<'a>) -> an_enum<'b> { return e; //~ ERROR mismatched types } fn a_fn3<'a,'b>(e: a_class<'a>) -> a_class<'b> { return e; //~ ERROR mismatched types } fn main() { }
a_fn1
identifier_name
regions-bounds.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
// <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. // Check that explicit region bounds are allowed on the various // nominal types (but not on other types) and that they are type // checked. struct an_en...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
main.rs
extern crate serde_json; #[macro_use] extern crate serde_derive; #[macro_use] extern crate exonum; extern crate router; extern crate bodyparser; extern crate iron; use std::path::Path; use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; use exonum::blockchain::{self, Blockchain, Service, Genes...
fn get_wallets(&self) -> Option<Vec<Wallet>> { let mut view = self.blockchain.fork(); let mut schema = CurrencySchema { view: &mut view }; let idx = schema.wallets(); let wallets: Vec<Wallet> = idx.values().collect(); if wallets.is_empty() { None } else ...
{ let mut view = self.blockchain.fork(); let mut schema = CurrencySchema { view: &mut view }; schema.wallet(pub_key) }
identifier_body
main.rs
extern crate serde_json; #[macro_use] extern crate serde_derive; #[macro_use] extern crate exonum; extern crate router; extern crate bodyparser; extern crate iron; use std::path::Path; use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; use exonum::blockchain::{self, Blockchain, Service, Genes...
(&self) -> Option<Vec<Wallet>> { let mut view = self.blockchain.fork(); let mut schema = CurrencySchema { view: &mut view }; let idx = schema.wallets(); let wallets: Vec<Wallet> = idx.values().collect(); if wallets.is_empty() { None } else { Some(w...
get_wallets
identifier_name
main.rs
extern crate serde_json; #[macro_use] extern crate serde_derive; #[macro_use] extern crate exonum; extern crate router; extern crate bodyparser; extern crate iron; use std::path::Path; use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; use exonum::blockchain::{self, Blockchain, Service, Genes...
} } // // // // // // // // // // DATA LAYOUT // // // // // // // // // // /// Create schema of the key-value storage implemented by `MemoryDB`. In the /// present case a `Fork` of the database is used. pub struct CurrencySchema<'a> { view: &'a mut Fork, } /// Declare layout of the data. Use an instance of ...
pub fn decrease(self, amount: u64) -> Self { let balance = self.balance() - amount; Self::new(self.pub_key(), self.name(), balance)
random_line_split
mod.rs
//! # database //! This module holds necessary structs and functions to accomplish database tasks. mod read; mod insert; mod update; mod delete; pub mod query_api; pub mod errors; use serde_json; use slog::Logger; use configuration; use weld::ROOT_LOGGER; use std::vec::Vec; use std::fs::File; use std::io::Read; use ...
(val: &String) -> i64 { match i64::from_str_radix(val.as_str(), 10) { Ok(parsed) => parsed, Err(_) => -1, } } /// This is the main access function to reach the desired data from the whole database. /// Tries to find the keys provided in the database recursively. ...
decide_id
identifier_name
mod.rs
//! # database //! This module holds necessary structs and functions to accomplish database tasks. mod read; mod insert; mod update; mod delete; pub mod query_api; pub mod errors; use serde_json; use slog::Logger; use configuration; use weld::ROOT_LOGGER; use std::vec::Vec; use std::fs::File; use std::io::Read; use ...
/// This is the main access function to reach the desired data from the whole database. /// Tries to find the keys provided in the database recursively. /// Returns mutable references to allow manipulation. pub fn get_object<'per_req>( keys: &mut Vec<String>, json_object: &'per_req mut...
{ match i64::from_str_radix(val.as_str(), 10) { Ok(parsed) => parsed, Err(_) => -1, } }
identifier_body
mod.rs
//! # database //! This module holds necessary structs and functions to accomplish database tasks. mod read;
mod insert; mod update; mod delete; pub mod query_api; pub mod errors; use serde_json; use slog::Logger; use configuration; use weld::ROOT_LOGGER; use std::vec::Vec; use std::fs::File; use std::io::Read; use std::io::Write; use std::fs::OpenOptions; use serde_json::Value; use serde_json::Value::{Array, Object}; use s...
random_line_split
htmlfontelement.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 cssparser::RGBA; use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFontElementBinding; use dom::b...
(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLFontElement { HTMLFontElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Pre...
new_inherited
identifier_name
htmlfontelement.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 cssparser::RGBA; use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFontElementBinding; use dom::b...
#[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLFontElement> { Node::reflect_node(Box::new(HTMLFontElement::new_inherited(local_name, prefix, document)), document, ...
{ HTMLFontElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } }
identifier_body
htmlfontelement.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 cssparser::RGBA; use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFontElementBinding; use dom::b...
match size { Some(&AttrValue::UInt(_, s)) => Some(s), _ => None, } } } /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size> fn parse_size(mut input: &str) -> AttrValue { let original_input = input; // Steps 1 & 2 are not relevant //...
};
random_line_split
ui.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/. */ //! Specified types for UI properties. use cssparser::Parser; use parser::{Parse, ParserContext}; use std::fmt::{...
/// auto | <color> pub type ColorOrAuto = Either<Color, Auto>; /// A specified value for the `cursor` property. pub type Cursor = generics::Cursor<CursorImage>; /// A specified value for item of `image cursors`. pub type CursorImage = generics::CursorImage<SpecifiedImageUrl, Number>; impl Parse for Cursor { ///...
use values::specified::url::SpecifiedImageUrl;
random_line_split
ui.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/. */ //! Specified types for UI properties. use cssparser::Parser; use parser::{Parse, ParserContext}; use std::fmt::{...
}
{ if input.try(|i| i.expect_ident_matching("auto")).is_ok() { return Ok(generics::ScrollbarColor::Auto); } Ok(generics::ScrollbarColor::Colors { thumb: Color::parse(context, input)?, track: Color::parse(context, input)?, }) }
identifier_body
ui.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/. */ //! Specified types for UI properties. use cssparser::Parser; use parser::{Parse, ParserContext}; use std::fmt::{...
(pub bool); impl MozForceBrokenImageIcon { /// Return initial value of -moz-force-broken-image-icon which is false. #[inline] pub fn false_value() -> MozForceBrokenImageIcon { MozForceBrokenImageIcon(false) } } impl Parse for MozForceBrokenImageIcon { fn parse<'i, 't>( _context: &P...
MozForceBrokenImageIcon
identifier_name
metrics.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use prometheus::*; use prometheus_static_metric::*; make_auto_flush_static_metric! { pub label_enum SnapType { generate, apply, } pub label_enum SnapStatus { all, success, abort, fail, ...
"tikv_raftstore_snapshot_total", "Total number of raftstore snapshot processed.", &["type", "status"] ) .unwrap(); pub static ref SNAP_COUNTER: SnapCounter = auto_flush_from!(SNAP_COUNTER_VEC, SnapCounter); pub static ref CHECK_SPILT_COUNTER_VEC: IntCounterVec = register_int_count...
} } lazy_static! { pub static ref SNAP_COUNTER_VEC: IntCounterVec = register_int_counter_vec!(
random_line_split
neon.rs
let channels = CoordinatorCommunication::instantiate(); Self { config, coordinator_channels: Some(channels), callbacks: RunLoopCallbacks::new(), } } #[cfg(test)] pub fn new(config: Config) -> Self { let channels = CoordinatorCommunication...
(&self) {} #[cfg(test)] fn bump_blocks_processed(&self) { self.blocks_processed .fetch_add(1, std::sync::atomic::Ordering::SeqCst); } #[cfg(not(test))] fn bump_blocks_processed(&self) {} /// Starts the testnet runloop. /// /// This function will block by looping inf...
get_microblocks_processed_arc
identifier_name
neon.rs
let channels = CoordinatorCommunication::instantiate(); Self { config, coordinator_channels: Some(channels), callbacks: RunLoopCallbacks::new(), } } #[cfg(test)] pub fn new(config: Config) -> Self { let channels = CoordinatorCommunication...
keep_running_writer.store(false, Ordering::SeqCst); } }); if let Err(e) = install { // integration tests can do this if cfg!(test) { } else { panic!("FATAL: error setting termination handler - {}", e); } ...
{ let (coordinator_receivers, coordinator_senders) = self .coordinator_channels .take() .expect("Run loop already started, can only start once after initialization."); let should_keep_running = Arc::new(AtomicBool::new(true)); let keep_running_writer = should...
identifier_body
neon.rs
{ let channels = CoordinatorCommunication::instantiate(); Self { config, coordinator_channels: Some(channels), callbacks: RunLoopCallbacks::new(), } } #[cfg(test)] pub fn new(config: Config) -> Self { let channels = CoordinatorCommunicati...
} let utxos = burnchain.get_utxos(&keychain.generate_op_signer().get_public_key(), 1, None, 0); if utxos.is_none() { if self.config.node.mock_mining { info!("No UTXOs found, but configured to mock mine"); true ...
match burnchain.create_wallet_if_dne() { Err(e) => warn!("Error when creating wallet: {:?}", e), _ => {}
random_line_split
main.rs
extern crate rand; use rand::{SeedableRng, StdRng}; mod grasp; mod data_parser; mod read_file; use read_file::{create_reader, read_data}; fn euc2d(c1: [f32; 2], c2: [f32; 2]) -> f32 { ((c1[0] - c2[0]).powi(2) + (c1[1] - c2[1]).powi(2)).sqrt() } fn main() { // Read the needed data to run this program. // ...
group, // the problem data itself (which I still // do not fully understand what it is) max_iters, // maximum number of iterations to do // when searching for the best solution ...
// solving the actual problem println!("{:?}", grasp::search(
random_line_split
main.rs
extern crate rand; use rand::{SeedableRng, StdRng}; mod grasp; mod data_parser; mod read_file; use read_file::{create_reader, read_data}; fn
(c1: [f32; 2], c2: [f32; 2]) -> f32 { ((c1[0] - c2[0]).powi(2) + (c1[1] - c2[1]).powi(2)).sqrt() } fn main() { // Read the needed data to run this program. // // These functions will make sure that, if nothing is passed as an argument // in the command line to this program, it will still try to rea...
euc2d
identifier_name
main.rs
extern crate rand; use rand::{SeedableRng, StdRng}; mod grasp; mod data_parser; mod read_file; use read_file::{create_reader, read_data}; fn euc2d(c1: [f32; 2], c2: [f32; 2]) -> f32
fn main() { // Read the needed data to run this program. // // These functions will make sure that, if nothing is passed as an argument // in the command line to this program, it will still try to read the data // from the standard input. let mut input = create_reader(); let data = read_da...
{ ((c1[0] - c2[0]).powi(2) + (c1[1] - c2[1]).powi(2)).sqrt() }
identifier_body
versioncheck.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))] #![warn(rust_2018_idioms, unused_lifetimes)] #![allow(clippy::single_match_else)] use rustc_tools_util::VersionInfo; #[test] fn
() { // do not run this test inside the upstream rustc repo: // https://github.com/rust-lang/rust-clippy/issues/6683 if option_env!("RUSTC_TEST_SUITE").is_some() { return; } let clippy_meta = cargo_metadata::MetadataCommand::new() .no_deps() .exec() .expect("could not o...
check_that_clippy_lints_and_clippy_utils_have_the_same_version_as_clippy
identifier_name
versioncheck.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))] #![warn(rust_2018_idioms, unused_lifetimes)] #![allow(clippy::single_match_else)] use rustc_tools_util::VersionInfo; #[test] fn check_that_clippy_lints_and_clippy_utils_have_the_same_version_as_clippy() { // do not run this test inside the upstream rustc rep...
, }; }
{ panic!("Failed to parse rustc version: {:?}", vsplit); }
conditional_block
versioncheck.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))] #![warn(rust_2018_idioms, unused_lifetimes)] #![allow(clippy::single_match_else)] use rustc_tools_util::VersionInfo; #[test] fn check_that_clippy_lints_and_clippy_utils_have_the_same_version_as_clippy() { // do not run this test inside the upstream rustc rep...
} } } #[test] fn check_that_clippy_has_the_same_major_version_as_rustc() { // do not run this test inside the upstream rustc repo: // https://github.com/rust-lang/rust-clippy/issues/6683 if option_env!("RUSTC_TEST_SUITE").is_some() { return; } let clippy_version = rustc_tools_u...
assert!(package.req.matches(&krate_meta.packages[0].version)); break; }
random_line_split
versioncheck.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))] #![warn(rust_2018_idioms, unused_lifetimes)] #![allow(clippy::single_match_else)] use rustc_tools_util::VersionInfo; #[test] fn check_that_clippy_lints_and_clippy_utils_have_the_same_version_as_clippy() { // do not run this test inside the upstream rustc rep...
.stdout, ) .unwrap(); // extract "1 XX 0" from "rustc 1.XX.0-nightly (<commit> <date>)" let vsplit: Vec<&str> = rustc_version .split(' ') .nth(1) .unwrap() .split('-') .next() .unwrap() .split('.') .collect(); match vsplit.as_slice() ...
{ // do not run this test inside the upstream rustc repo: // https://github.com/rust-lang/rust-clippy/issues/6683 if option_env!("RUSTC_TEST_SUITE").is_some() { return; } let clippy_version = rustc_tools_util::get_version_info!(); let clippy_major = clippy_version.major; let clippy_...
identifier_body
16878_H2.rs
Per(s)PSA @ damp 02% PSA @ damp 05% PSA @ damp 07% PSA @ damp 10% PSA @ damp 20% PSA @ damp 30% (m/s/s) 0.000 3.8242000E-002 3.8242000E-002 3.8242000E-002 3.8242000E-002 3.8242000E-002 3.8242000E-002 0.010 3.8247300E-002 3.8247550E-002 3.8247650E-002 3.8247790E-002 3.8247690E-002 3.8246990E-002 0.020 3.8268110E-002 ...
0.160 4.3761320E-002 4.3570550E-002 4.3445530E-002 4.3206240E-002 4.2161500E-002 4.1216940E-002 0.170 4.3996000E-002 4.4919430E-002 4.4792980E-002 4.4369930E-002 4.2842430E-002 4.1665050E-002 0.180 5.1370830E-002 4.7977580E-002 4.6887720E-002 4.5761710E-002 4.3470720E-002 4.2072230E-002 0.190 5.2597260E-002 4.933258...
0.150 4.2383010E-002 4.2630480E-002 4.2601680E-002 4.2383550E-002 4.1479710E-002 4.0745470E-002
random_line_split
repl.rs
//! This module implements the todr REPL logic. use dirs; use rustyline::error::ReadlineError; use rustyline::Editor; use std::path::Path; // Use our internal handlers module. use completer::CustomCompletion; use handlers; // On unix platforms you can use ANSI escape sequences #[cfg(unix)] static PROMPT: &'static st...
/// Executes the main process loop. pub fn process_command_loop(&mut self) { // If loading failed, that's fine, just ignore it. let _ = self.readline_editor.load_history(&self.history_file); loop { // Handle graceful exit request. if self.should_exit { ...
{ let home = dirs::home_dir().expect("Home Dir couldn't be found"); let history_file = Path::new(&home) .join(DEFAULT_HISTORY_FILE) .to_string_lossy() .to_string(); let mut editor = Editor::<CustomCompletion>::new(); let completer = CustomCompletion:...
identifier_body
repl.rs
//! This module implements the todr REPL logic. use dirs; use rustyline::error::ReadlineError; use rustyline::Editor; use std::path::Path; // Use our internal handlers module. use completer::CustomCompletion; use handlers; // On unix platforms you can use ANSI escape sequences #[cfg(unix)] static PROMPT: &'static st...
self.readline_editor .save_history(&self.history_file) .expect("Failed to save repl history file"); } /// Processes a single line for a command. fn process_line(&mut self, line: &str) { self.readline_editor.add_history_entry(line); match line { //...
} }
random_line_split
repl.rs
//! This module implements the todr REPL logic. use dirs; use rustyline::error::ReadlineError; use rustyline::Editor; use std::path::Path; // Use our internal handlers module. use completer::CustomCompletion; use handlers; // On unix platforms you can use ANSI escape sequences #[cfg(unix)] static PROMPT: &'static st...
(&mut self) { // If loading failed, that's fine, just ignore it. let _ = self.readline_editor.load_history(&self.history_file); loop { // Handle graceful exit request. if self.should_exit { break; } let readline = self.readline_ed...
process_command_loop
identifier_name
option_unwrap.rs
// The commoner has seen it all, and can handle any gift well. // All gifts are handled explicitly using `match`. fn give_commoner(gift: Option<&str>) { // Specify a course of action for each case. match gift { Some("snake") => println!("Yuck! I'm throwing that snake in a fire."), Some(inner) ...
fn main() { let food = Some("cabbage"); let snake = Some("snake"); let void = None; give_commoner(food); give_commoner(snake); give_commoner(void); let bird = Some("robin"); let nothing = None; give_princess(bird); give_princess(nothing); }
{ // `unwrap` returns a `panic` when it receives a `None`. let inside = gift.unwrap(); if inside == "snake" { panic!("AAAaaaaa!!!!"); } println!("I love {}s!!!!!", inside); }
identifier_body
option_unwrap.rs
// The commoner has seen it all, and can handle any gift well. // All gifts are handled explicitly using `match`. fn give_commoner(gift: Option<&str>) { // Specify a course of action for each case. match gift { Some("snake") => println!("Yuck! I'm throwing that snake in a fire."), Some(inner) ...
() { let food = Some("cabbage"); let snake = Some("snake"); let void = None; give_commoner(food); give_commoner(snake); give_commoner(void); let bird = Some("robin"); let nothing = None; give_princess(bird); give_princess(nothing); }
main
identifier_name
option_unwrap.rs
// The commoner has seen it all, and can handle any gift well. // All gifts are handled explicitly using `match`. fn give_commoner(gift: Option<&str>) { // Specify a course of action for each case. match gift { Some("snake") => println!("Yuck! I'm throwing that snake in a fire."), Some(inner) ...
give_princess(nothing); }
let bird = Some("robin"); let nothing = None; give_princess(bird);
random_line_split
array.rs
use array_ext; use arrayvec; use smallvec; pub trait Array: arrayvec::Array + smallvec::Array<Item = <Self as arrayvec::Array>::Item> + array_ext::Array<<Self as arrayvec::Array>::Item> { } pub trait ReplaceItemType<U>: Array { type Type: Array + arrayvec::Array<Item = U> + array_ext::Array<U>; } pub trait Sm...
array_impls!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,); smaller_array_impls!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,);
random_line_split
attr.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 ...
(&mut self) -> PResult<'a, ast::MetaItemKind> { Ok(if self.eat(&token::Eq) { ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?) } else if self.token == token::OpenDelim(token::Paren) { ast::MetaItemKind::List(self.parse_meta_seq()?) } else { self.eat(&...
parse_meta_item_kind
identifier_name
attr.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 ...
/// matches inner_attrs* pub fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> { let mut attrs: Vec<ast::Attribute> = vec![]; loop { match self.token { token::Pound => { // Don't even try to parse if it's not an inner attrib...
/// Parse attributes that appear after the opening of an item. These should /// be preceded by an exclamation mark, but we accept and warn about one /// terminated by a semicolon.
random_line_split
attr.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 ...
`//! My crate`, annotate the item enclosing them, and are \ usually found at the beginning of source files. Outer \ attributes and doc comments, like `#[test]` and `/// My function...
{ debug!("parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}", inner_parse_policy, self.token); let (span, path, tokens, mut style) = match self.token { token::Pound => { let lo = self.span; self.bump...
identifier_body
balls2.rs
extern crate nalgebra as na; use na::{Point2, RealField, Vector2}; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::object::{ BodyPartHandle, ColliderDesc, DefaultBodySet, DefaultCollider...
{ let testbed = Testbed::<f32>::from_builders(0, vec![("Balls", init_world)]); testbed.run() }
identifier_body
balls2.rs
extern crate nalgebra as na; use na::{Point2, RealField, Vector2}; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::object::{ BodyPartHandle, ColliderDesc, DefaultBodySet, DefaultCollider...
<N: RealField>(testbed: &mut Testbed<N>) { /* * World */ let mechanical_world = DefaultMechanicalWorld::new(Vector2::new(r!(0.0), r!(-9.81))); let geometrical_world = DefaultGeometricalWorld::new(); let mut bodies = DefaultBodySet::new(); let mut colliders = DefaultColliderSet::new(); ...
init_world
identifier_name
balls2.rs
extern crate nalgebra as na; use na::{Point2, RealField, Vector2}; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::object::{ BodyPartHandle, ColliderDesc, DefaultBodySet, DefaultCollider...
for i in 0usize..num { for j in 0..num { let x = r!(i as f64) * shift - centerx; let y = r!(j as f64) * shift + centery; // Build the rigid body. let rb = RigidBodyDesc::new().translation(Vector2::new(x, y)).build(); let rb_handle = bodies.insert...
let centerx = shift * r!(num as f64) / r!(2.0); let centery = shift / r!(2.0);
random_line_split
main.rs
extern crate tar; extern crate flate2; use std::io::{self, Read}; use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::env; use std::process; fn decompress(tarpath: PathBuf, extract_path: PathBuf) -> io::Result<()> { use flate2::read::GzDecoder; use tar::Archive; let tarball = fs::File::op...
fn verify(res: io::Result<()>) { let _ = res.map_err(|e| { println!("error: {}", e); process::exit(1); }); } fn main() { let pwd = env::current_dir().unwrap(); let data = "./data.txt"; let tarpath = Path::new(&pwd).join("data.tar.gz"); let extractpath = Path::new(&pwd).join("o...
{ use flate2::write::GzEncoder; use flate2::Compression; use tar::Builder; let file = File::create(&output_file)?; let mut encoder = GzEncoder::new(file, Compression::default()); let mut builder = Builder::new(&mut encoder); builder.append_path(input_file)?; // scope Drop's builder, t...
identifier_body
main.rs
extern crate tar; extern crate flate2; use std::io::{self, Read}; use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::env; use std::process; fn decompress(tarpath: PathBuf, extract_path: PathBuf) -> io::Result<()> { use flate2::read::GzDecoder; use tar::Archive; let tarball = fs::File::op...
verify(decompress(tarpath, extractpath)); println!("Decompressed data"); let mut f = File::open(Path::new(&pwd).join("output").join("data.txt")).unwrap(); let mut text = String::new(); f.read_to_string(&mut text).unwrap(); assert_eq!(&text, "hi\n"); println!("Verified data"); }
verify(compress(data, tarpath.clone())); println!("Compressed data");
random_line_split
main.rs
extern crate tar; extern crate flate2; use std::io::{self, Read}; use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::env; use std::process; fn
(tarpath: PathBuf, extract_path: PathBuf) -> io::Result<()> { use flate2::read::GzDecoder; use tar::Archive; let tarball = fs::File::open(tarpath)?; let decompressed = GzDecoder::new(tarball); let mut archive = Archive::new(decompressed); fs::create_dir_all(&extract_path)?; archive.unpack(...
decompress
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
{ if list.is_empty() { return Ok(()); } try!(list[0].to_css(dest)); for item in list.iter().skip(1) { try!(write!(dest, ", ")); try!(item.to_css(dest)); } Ok(()) }
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
try!(list[0].to_css(dest)); for item in list.iter().skip(1) { try!(write!(dest, ", ")); try!(item.to_css(dest)); } Ok(()) }
{ return Ok(()); }
conditional_block
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
<T:?Sized>(a: *const T, b: *const T) -> bool { a == b } /// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn serialize_comma_separated_list<W, T>(dest: &mut W, list: &[T]) ->...
ptr_eq
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
#[cfg(feature = "servo")] extern crate servo_config; #[cfg(feature = "servo")] extern crate servo_url; extern crate smallvec; #[macro_use] extern crate style_derive; #[macro_use] extern crate style_traits; extern crate time; extern crate unicode_bidi; #[allow(unused_extern_crates)] extern crate unicode_segmentation; #...
#[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms;
random_line_split
extra.rs
// Some helper functions pub fn range(lo: uint, hi: uint, it: |uint| -> ()) { let mut iter = lo; while iter < hi { it(iter); iter += 1; } } // Convert an integer to a string #[no_mangle] pub fn to_str_bytes(num : int, base : int) -> ~[u8] { let neg = num < 0; let digits = "0123456789ABCD...
let mut ret : ~[u8] = ~[0,..65]; if neg { ret[place] = '-' as u8; place += 1; m_num = -num; } whole = m_num as int; if whole == 0 { ret[place] = '0' as u8; place += 1; ret[place] = '.' as u8; place += 1; } else { stored = whole; while stored!= 0 { place += 1; stored /= 10; } stored...
let mut m_num = num; let mut whole : int; let mut stored : int; let mut stored_place : int; let mut rem : f32;
random_line_split
extra.rs
// Some helper functions pub fn range(lo: uint, hi: uint, it: |uint| -> ()) { let mut iter = lo; while iter < hi { it(iter); iter += 1; } } // Convert an integer to a string #[no_mangle] pub fn
(num : int, base : int) -> ~[u8] { let neg = num < 0; let digits = "0123456789ABCDEF"; let mut place = 0; let mut stored = num; let mut stor2 = num; let mut ret : ~[u8] = ~[0,..65]; if neg { ret[place] = '-' as u8; place += 1; stored = -stored; stor2 = -stor2; } if num == 0 { ret[place] = '0' as u8;...
to_str_bytes
identifier_name
extra.rs
// Some helper functions pub fn range(lo: uint, hi: uint, it: |uint| -> ()) { let mut iter = lo; while iter < hi { it(iter); iter += 1; } } // Convert an integer to a string #[no_mangle] pub fn to_str_bytes(num : int, base : int) -> ~[u8] { let neg = num < 0; let digits = "0123456789ABCD...
if num == 0 { ret[place] = '0' as u8; return ret; } while stored!= 0 { place += 1; stored /= base as int; } stored = stor2; while stored!= 0 { place -= 1; ret[place] = digits[stored % base as int]; stored /= base as int; } return ret; } // Dumb and simple way to convert float to string // Is not...
{ ret[place] = '-' as u8; place += 1; stored = -stored; stor2 = -stor2; }
conditional_block
extra.rs
// Some helper functions pub fn range(lo: uint, hi: uint, it: |uint| -> ())
// Convert an integer to a string #[no_mangle] pub fn to_str_bytes(num : int, base : int) -> ~[u8] { let neg = num < 0; let digits = "0123456789ABCDEF"; let mut place = 0; let mut stored = num; let mut stor2 = num; let mut ret : ~[u8] = ~[0,..65]; if neg { ret[place] = '-' as u8; place += 1; stored = -s...
{ let mut iter = lo; while iter < hi { it(iter); iter += 1; } }
identifier_body
lib.rs
// DO NOT EDIT! // This file was generated automatically from'src/mako/api/lib.rs.mako' // DO NOT EDIT! //! This documentation was generated from *Games Management* crate version *0.1.8+20150601*, where *20150601* is the exact revision of the *gamesManagement:v1management* schema built by the [mako](http://www.makotem...
//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. //! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making //! this call: `.param("alt", "media")`. //! //! Methods supporting uploads...
//! makes the system potentially resilient to all kinds of errors. //! //! ## Uploads and Downloads //! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be //! read by you to obtain the media.
random_line_split
float.rs
#[macro_use] extern crate nom; use nom::character::streaming::digit1 as digit; use std::str; use std::str::FromStr; named!( unsigned_float<f32>, map_res!( map_res!( recognize!(alt!( delimited!(digit, tag!("."), opt!(digit)) | delimited!(opt!(digit), tag!("."), digit) )), str::from_u...
{ assert_eq!(float(&b"123.456;"[..]), Ok((&b";"[..], 123.456))); assert_eq!(float(&b"+123.456;"[..]), Ok((&b";"[..], 123.456))); assert_eq!(float(&b"-123.456;"[..]), Ok((&b";"[..], -123.456))); }
identifier_body
float.rs
#[macro_use] extern crate nom; use nom::character::streaming::digit1 as digit; use std::str; use std::str::FromStr; named!( unsigned_float<f32>, map_res!( map_res!( recognize!(alt!( delimited!(digit, tag!("."), opt!(digit)) | delimited!(opt!(digit), tag!("."), digit) )), str::from_u...
() { assert_eq!(unsigned_float(&b"123.456;"[..]), Ok((&b";"[..], 123.456))); assert_eq!(unsigned_float(&b"0.123;"[..]), Ok((&b";"[..], 0.123))); assert_eq!(unsigned_float(&b"123.0;"[..]), Ok((&b";"[..], 123.0))); assert_eq!(unsigned_float(&b"123.;"[..]), Ok((&b";"[..], 123.0))); assert_eq!(unsigned_float(&b"....
unsigned_float_test
identifier_name
float.rs
#[macro_use] extern crate nom; use nom::character::streaming::digit1 as digit; use std::str; use std::str::FromStr; named!( unsigned_float<f32>, map_res!( map_res!( recognize!(alt!( delimited!(digit, tag!("."), opt!(digit)) | delimited!(opt!(digit), tag!("."), digit) )), str::from_u...
pair!(opt!(alt!(tag!("+") | tag!("-"))), unsigned_float), |(sign, value): (Option<&[u8]>, f32)| sign .and_then(|s| if s[0] == b'-' { Some(-1f32) } else { None }) .unwrap_or(1f32) * value ) ); #[test] fn unsigned_float_test() { assert_eq!(unsigned_float(&b"123.456;"[..]), Ok((&b";"[..], 123.456)))...
map!(
random_line_split
button_touch_test.rs
extern crate piston; extern crate opengl_graphics; extern crate graphics; extern crate sdl2_window; extern crate button_controller; use piston::*; use graphics::*; use opengl_graphics::*; use sdl2_window::Sdl2Window; use button_controller::{ButtonController, ButtonEvent, ButtonState}; fn main() { let opengl = Ope...
if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, g| { clear([1.0; 4], g); let color = match click_me.state(0.2) { ButtonState::Inactive => [0.6, 0.6, 0.6, 1.0], ButtonState::Hover => [0.4, 0.4, 0.4, 1.0], ...
ButtonEvent::Cancel => "Cancel", }) }
random_line_split
button_touch_test.rs
extern crate piston; extern crate opengl_graphics; extern crate graphics; extern crate sdl2_window; extern crate button_controller; use piston::*; use graphics::*; use opengl_graphics::*; use sdl2_window::Sdl2Window; use button_controller::{ButtonController, ButtonEvent, ButtonState}; fn main()
ButtonEvent::Cancel => "Cancel", }) } if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, g| { clear([1.0; 4], g); let color = match click_me.state(0.2) { ButtonState::Inactive => [0.6, 0.6, 0.6, ...
{ let opengl = OpenGL::V3_2; let mut window: Sdl2Window = WindowSettings::new("touch button", [300; 2]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let mut events = Events::new(EventSettings::new()); let mut gl = GlGraphics::new(opengl); let mut clic...
identifier_body
button_touch_test.rs
extern crate piston; extern crate opengl_graphics; extern crate graphics; extern crate sdl2_window; extern crate button_controller; use piston::*; use graphics::*; use opengl_graphics::*; use sdl2_window::Sdl2Window; use button_controller::{ButtonController, ButtonEvent, ButtonState}; fn
() { let opengl = OpenGL::V3_2; let mut window: Sdl2Window = WindowSettings::new("touch button", [300; 2]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let mut events = Events::new(EventSettings::new()); let mut gl = GlGraphics::new(opengl); let mut click...
main
identifier_name
window_helper.rs
use super::base_helper::{to_utf16, from_utf16}; use super::high_dpi; use winapi::shared::windef::{HFONT, HWND, HMENU}; use winapi::shared::minwindef::{UINT, WPARAM, LPARAM, LRESULT}; use winapi::um::winuser::WM_USER; use winapi::ctypes::c_int; use std::{ptr, mem}; #[cfg(feature = "rich-textbox")] use winapi::um::winus...
b unsafe fn get_window_position(handle: HWND) -> (i32, i32) { use winapi::um::winuser::{GetWindowRect, ScreenToClient, GetParent}; use winapi::shared::windef::{RECT, POINT}; let mut r: RECT = mem::zeroed(); GetWindowRect(handle, &mut r); let parent = GetParent(handle); let (x, y) = if!pare...
use winapi::um::winuser::SetWindowPos; use winapi::um::winuser::{HWND_TOP, SWP_NOSIZE, SWP_NOMOVE, SWP_NOACTIVATE, SWP_NOOWNERZORDER}; let after_handle = match after { None => HWND_TOP, Some(w) => w }; SetWindowPos(handle, after_handle, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVAT...
identifier_body
window_helper.rs
use super::base_helper::{to_utf16, from_utf16}; use super::high_dpi; use winapi::shared::windef::{HFONT, HWND, HMENU}; use winapi::shared::minwindef::{UINT, WPARAM, LPARAM, LRESULT}; use winapi::um::winuser::WM_USER; use winapi::ctypes::c_int; use std::{ptr, mem}; #[cfg(feature = "rich-textbox")] use winapi::um::winus...
} }; let mut brush_data: LOGBRUSH = mem::zeroed(); GetObjectW(brush as _, mem::size_of::<LOGBRUSH>() as _, &mut brush_data as *mut LOGBRUSH as _); let col = brush_data.lbColor; Ok([GetRValue(col), GetGValue(col), GetBValue(col)]) }, ...
GetSysColorBrush(0) }
conditional_block
window_helper.rs
use super::base_helper::{to_utf16, from_utf16}; use super::high_dpi; use winapi::shared::windef::{HFONT, HWND, HMENU}; use winapi::shared::minwindef::{UINT, WPARAM, LPARAM, LRESULT}; use winapi::um::winuser::WM_USER; use winapi::ctypes::c_int; use std::{ptr, mem}; #[cfg(feature = "rich-textbox")] use winapi::um::winus...
dle: HWND) -> String { use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use winapi::shared::ntdef::WCHAR; use winapi::um::winuser::GetClassNameW; let mut class_name_raw: Vec<WCHAR> = Vec::with_capacity(100); class_name_raw.set_len(100); let count = GetClassNameW(handle, cla...
window_class_name(han
identifier_name
window_helper.rs
use super::base_helper::{to_utf16, from_utf16}; use super::high_dpi; use winapi::shared::windef::{HFONT, HWND, HMENU}; use winapi::shared::minwindef::{UINT, WPARAM, LPARAM, LRESULT}; use winapi::um::winuser::WM_USER; use winapi::ctypes::c_int; use std::{ptr, mem}; #[cfg(feature = "rich-textbox")] use winapi::um::winus...
pub const NWG_TIMER_TICK: UINT = WM_USER + 103; pub const NWG_TIMER_STOP: UINT = WM_USER + 104; /// Returns the class info of a hwnd handle #[cfg(feature = "rich-textbox")] pub fn get_class_info(hwnd: HWND) -> Result<WNDCLASSEXW, ()> { use winapi::um::winuser::{GetClassInfoExW, GetClassNameW}; use winapi::um:...
pub const NOTICE_MESSAGE: UINT = WM_USER+100; pub const NWG_INIT: UINT = WM_USER + 101; pub const NWG_TRAY: UINT = WM_USER + 102;
random_line_split
selector_impl.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 properties::GeckoComputedValues; use selectors::parser::{ParserContext, SelectorImpl}; use style; use style::e...
"-moz-tree-row" => MozTreeRow, "-moz-tree-separator" => MozTreeSeparator, "-moz-tree-cell" => MozTreeCell, "-moz-tree-indentation" => MozTreeIndentation, "-moz-tree-line" => MozTreeLine, "-moz-tree-twisty" => MozTreeTwisty, "-moz-tree-i...
"-moz-ruby-base" => MozRubyBase, "-moz-ruby-base-container" => MozRubyBaseContainer, "-moz-ruby-text" => MozRubyText, "-moz-ruby-text-container" => MozRubyTextContainer, "-moz-tree-column" => MozTreeColumn,
random_line_split
selector_impl.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 properties::GeckoComputedValues; use selectors::parser::{ParserContext, SelectorImpl}; use style; use style::e...
() -> Option<&'static Stylesheet> { None } }
get_quirks_mode_stylesheet
identifier_name
basic.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 { use std::task::TaskOpts; use basic; use PoolConfig; use SchedPool; fn pool() -> SchedPool { SchedPool::new(PoolConfig { threads: 1, event_loop_factory: basic::event_loop, }) } fn run(f: proc():Send) { let mut pool = p...
} }
random_line_split
basic.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 ...
} None => {} } } fn has_idle(&self) -> bool { self.idle.is_some() && self.idle_active.get_ref().load(atomics::SeqCst) } } impl EventLoop for BasicLoop { fn run(&mut self) { // Not exactly efficient, but it gets the job done. while self.remotes.l...
{ idle.call(); }
conditional_block
basic.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 { use std::task::TaskOpts; use basic; use PoolConfig; use SchedPool; fn pool() -> SchedPool { SchedPool::new(PoolConfig { threads: 1, event_loop_factory: basic::event_loop, }) } fn run(f: proc():Send) { let mut pool...
{ self.active.store(false, atomics::SeqCst); }
identifier_body
basic.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 ...
(&mut self) { match self.idle { Some(ref mut idle) => { if self.idle_active.get_ref().load(atomics::SeqCst) { idle.call(); } } None => {} } } fn has_idle(&self) -> bool { self.idle.is_some() && self....
idle
identifier_name
etcd_error.rs
use hyper; use std::io; use std::convert::From; use rustc_serialize::json; #[derive(Debug)] pub enum EtcdError { Unsuccessful(hyper::status::StatusCode), HttpError(hyper::error::HttpError), IOError(io::Error), DecodingError(json::DecoderError), JsonParserError(json::ParserError), } impl From<hyper::error::H...
(err: json::DecoderError) -> EtcdError { EtcdError::DecodingError(err) } } impl From<json::ParserError> for EtcdError { fn from(err: json::ParserError) -> EtcdError { EtcdError::JsonParserError(err) } }
from
identifier_name
etcd_error.rs
use hyper; use std::io; use std::convert::From; use rustc_serialize::json; #[derive(Debug)] pub enum EtcdError { Unsuccessful(hyper::status::StatusCode), HttpError(hyper::error::HttpError), IOError(io::Error), DecodingError(json::DecoderError), JsonParserError(json::ParserError), } impl From<hyper::error::H...
} } impl From<json::ParserError> for EtcdError { fn from(err: json::ParserError) -> EtcdError { EtcdError::JsonParserError(err) } }
EtcdError::DecodingError(err)
random_line_split
etcd_error.rs
use hyper; use std::io; use std::convert::From; use rustc_serialize::json; #[derive(Debug)] pub enum EtcdError { Unsuccessful(hyper::status::StatusCode), HttpError(hyper::error::HttpError), IOError(io::Error), DecodingError(json::DecoderError), JsonParserError(json::ParserError), } impl From<hyper::error::H...
} impl From<json::ParserError> for EtcdError { fn from(err: json::ParserError) -> EtcdError { EtcdError::JsonParserError(err) } }
{ EtcdError::DecodingError(err) }
identifier_body
site.rs
use conf::Conf; use error::{Result, ResultContext}; use files; use tera::{Tera, Context}; use post::{Post, PostKind}; use std::{env, fs}; use std::path::PathBuf; #[derive(Debug)] pub struct Site { ctx: Context, articles: Vec<Post>, pages: Vec<Post>, tera: Tera, } impl Site { pub fn collect(conf: &...
assert!(dir.join("p.html").exists()); assert!(dir.join(p.ts.format("%Y/%m/%d").to_string()).join("a.html").exists()); assert!(dir.join(::INDEX_FILE).exists()); assert!(dir.join(::ARCHIVE_FILE).exists()); fs::remove_dir_all(dir).unwrap(); } }
{ let dir = env::temp_dir().join("site"); ::new::create_site(dir.clone(), true).unwrap(); let mut c = Conf::default(); c.force = Some(true); c.in_dir = Some(dir.to_str().unwrap().to_string()); c.out_dir = Some(dir.to_str().unwrap().to_string()); create_post(dir....
identifier_body
site.rs
use conf::Conf; use error::{Result, ResultContext}; use files; use tera::{Tera, Context}; use post::{Post, PostKind}; use std::{env, fs}; use std::path::PathBuf; #[derive(Debug)] pub struct Site { ctx: Context, articles: Vec<Post>, pages: Vec<Post>, tera: Tera, } impl Site { pub fn collect(conf: &...
c.in_dir = Some(dir.to_str().unwrap().to_string()); c.out_dir = Some(dir.to_str().unwrap().to_string()); create_post(dir.join(::SRC_DIR).join("a.md"), c.clone(), PostKind::Article).unwrap(); create_post(dir.join(::SRC_DIR).join("p.md"), c.clone(), PostKind::Page).unwrap(); let ...
c.force = Some(true);
random_line_split
site.rs
use conf::Conf; use error::{Result, ResultContext}; use files; use tera::{Tera, Context}; use post::{Post, PostKind}; use std::{env, fs}; use std::path::PathBuf; #[derive(Debug)] pub struct Site { ctx: Context, articles: Vec<Post>, pages: Vec<Post>, tera: Tera, } impl Site { pub fn collect(conf: &...
(&self, conf: &Conf) -> Result<()> { let out_dir = conf.out_dir.as_ref() .map(PathBuf::from) .unwrap_or(env::current_dir()?); for p in self.articles.iter().chain(self.pages.iter()) { // skip the leading slash to make the output path correct let url = &p.url...
generate
identifier_name
issue-15858.rs
// Copyright 2012-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-MI...
() { { let _x: Foo<BarImpl> = Foo; } unsafe { assert_eq!(DROP_RAN, true); } }
main
identifier_name
issue-15858.rs
// Copyright 2012-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-MI...
struct BarImpl<'b>; impl<'b> Bar<'b> for BarImpl<'b> { fn do_something(&mut self) {} } struct Foo<B>; #[unsafe_destructor] impl<'b, B: Bar<'b>> Drop for Foo<B> { fn drop(&mut self) { unsafe { DROP_RAN = true; } } } fn main() { { let _x: Foo<BarImpl> = Foo; } ...
trait Bar<'b> { fn do_something(&mut self); }
random_line_split
issue-2904.rs
// Copyright 2012-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-MI...
mod test { #[test] pub fn trivial_to_string() { assert_eq!(lambda.to_string(), "\\") } } pub fn main() {}
{ let mut input: &mut Read = &mut input; let mut grid = Vec::new(); let mut line = [0; 10]; input.read(&mut line); let mut row = Vec::new(); for c in &line { row.push(square_from_char(*c as char)) } grid.push(row); let width = grid[0].len(); for row in &grid { assert_eq!(...
identifier_body
issue-2904.rs
// Copyright 2012-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-MI...
<rdr:'static + Read>(mut input: rdr) -> Vec<Vec<square>> { let mut input: &mut Read = &mut input; let mut grid = Vec::new(); let mut line = [0; 10]; input.read(&mut line); let mut row = Vec::new(); for c in &line { row.push(square_from_char(*c as char)) } grid....
read_board_grid
identifier_name
issue-2904.rs
// Copyright 2012-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-MI...
match c { 'R' => { bot } '#' => { wall } '*' => { rock } '\\' => { lambda } 'L' => { closed_lift } 'O' => { open_lift } '.' => { earth } '' => { empty } _ => { println!("invalid square: {}", c); panic!() } } } fn read_board_grid...
} } fn square_from_char(c: char) -> square {
random_line_split
3_04_exercise_spiral.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Exercise 3-04: Spiral
use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { r: f32, theta: f32, } fn model(app: &App) -> Model { let r = 0.0; let theta = 0.0; app.new_window().size(640, 360).view(view).build().unwrap(); Model { r, theta } } fn update(_app: &App, model:...
random_line_split
3_04_exercise_spiral.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Exercise 3-04: Spiral use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct
{ r: f32, theta: f32, } fn model(app: &App) -> Model { let r = 0.0; let theta = 0.0; app.new_window().size(640, 360).view(view).build().unwrap(); Model { r, theta } } fn update(_app: &App, model: &mut Model, _update: Update) { // Increment the angle model.theta += 0.01; // Increm...
Model
identifier_name
3_04_exercise_spiral.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Exercise 3-04: Spiral use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { r: f32, theta: f32, } fn model(app: &App) -> Model { let r = 0.0; let theta = 0.0; app.new_window().si...
{ // Begin drawing let draw = app.draw(); //draw.background().color(WHITE); let x = model.r * model.theta.cos(); let y = model.r * model.theta.sin(); // Draw an ellipse at x,y draw.ellipse() .x_y(x, y) .w_h(16.0, 16.0) .rgba(0.0, 0.0, 0.0, 1.0); // Write the re...
identifier_body
extern-compare-with-return-type.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 ...
}
assert!(uintvoidret == uintvoidret); assert!(uintuintuintuintret == uintuintuintuintret);
random_line_split
extern-compare-with-return-type.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 ...
pub fn main() { assert!(voidret1 == voidret1); assert!(voidret1!= voidret2); assert!(uintret == uintret); assert!(uintvoidret == uintvoidret); assert!(uintuintuintuintret == uintuintuintuintret); }
{ x+y+z }
identifier_body
extern-compare-with-return-type.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 ...
(x: uint, y: uint, z: uint) -> uint { x+y+z } pub fn main() { assert!(voidret1 == voidret1); assert!(voidret1!= voidret2); assert!(uintret == uintret); assert!(uintvoidret == uintvoidret); assert!(uintuintuintuintret == uintuintuintuintret); }
uintuintuintuintret
identifier_name
dapp_id.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 3 of the License, or // (at your option) any la...
(pub String); impl Into<String> for DappId { fn into(self) -> String { self.0 } } impl From<String> for DappId { fn from(s: String) -> Self { DappId(s) } } #[cfg(test)] mod tests { use serde_json; use super::DappId; #[test] fn should_serialize_dapp_id() { // given let id = DappId("testapp".into());...
DappId
identifier_name
dapp_id.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 3 of the License, or // (at your option) any la...
use serde_json; use super::DappId; #[test] fn should_serialize_dapp_id() { // given let id = DappId("testapp".into()); // when let res = serde_json::to_string(&id).unwrap(); // then assert_eq!(res, r#""testapp""#); } #[test] fn should_deserialize_dapp_id() { // given let id = r#""testapp""#; ...
random_line_split
dapp_id.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 3 of the License, or // (at your option) any la...
} #[cfg(test)] mod tests { use serde_json; use super::DappId; #[test] fn should_serialize_dapp_id() { // given let id = DappId("testapp".into()); // when let res = serde_json::to_string(&id).unwrap(); // then assert_eq!(res, r#""testapp""#); } #[test] fn should_deserialize_dapp_id() { // giv...
{ DappId(s) }
identifier_body
mod.rs
use std::fmt; use super::Tile; use super::Direction; use super::Point; /// Defines the 2D square Grid trait for using the maze generator pub trait Grid { /// Gets tile data at a given position on a grid fn get_tile_data(&self, Point) -> Result<Tile, &'static str>; /// Gets the width and height respectiv...
(&mut self, (x, y): Point, dir: Direction) -> Result<Point, &'static str> { let (width, height) = self.get_dimensions(); let tiles = &mut self.tiles; // Determine directon to carve into let (x_c, y_c): Point = match dir { Direction::Up => (x, y + 1), ...
carve_path
identifier_name