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
01a_quick_example.rs
extern crate clap; use clap::{App, SubCommand}; fn
() { // This example shows how to create an application with several arguments using usage strings, which can be // far less verbose that shown in 01b_QuickExample.rs, but is more readable. The downside is you cannot set // the more advanced configuration options using this method (well...actually you can,...
main
identifier_name
01a_quick_example.rs
extern crate clap; use clap::{App, SubCommand}; fn main()
// - A subcommand "test" (subcommands behave like their own apps, with their own arguments // + Used by "$ myapp test" with the following arguments // > A list flag // = Uses "-l" (usage is "$ myapp test -l" // > A help flag (automatically generated by ...
{ // This example shows how to create an application with several arguments using usage strings, which can be // far less verbose that shown in 01b_QuickExample.rs, but is more readable. The downside is you cannot set // the more advanced configuration options using this method (well...actually you can, yo...
identifier_body
01a_quick_example.rs
extern crate clap; use clap::{App, SubCommand}; fn main() { // This example shows how to create an application with several arguments using usage strings, which can be // far less verbose that shown in 01b_QuickExample.rs, but is more readable. The downside is you cannot set // the more advanced configur...
// Note, only flags can have multiple occurrences match matches.occurrences_of("d") { 0 => println!("Debug mode is off"), 1 => println!("Debug mode is kind of on"), 2 => println!("Debug mode is on"), 3 | _ => println!("Don't be crazy"), } // You can check for the existe...
// You can see how many times a particular flag or argument occurred
random_line_split
01a_quick_example.rs
extern crate clap; use clap::{App, SubCommand}; fn main() { // This example shows how to create an application with several arguments using usage strings, which can be // far less verbose that shown in 01b_QuickExample.rs, but is more readable. The downside is you cannot set // the more advanced configur...
// You can see how many times a particular flag or argument occurred // Note, only flags can have multiple occurrences match matches.occurrences_of("d") { 0 => println!("Debug mode is off"), 1 => println!("Debug mode is kind of on"), 2 => println!("Debug mode is on"), 3 | _...
{ println!("Value for config: {}", c); }
conditional_block
parser.rs
use std::collections::{ HashMap }; use lexer::{ Lexer, Token }; type GrammarFunction = fn(&mut Parser); struct Rule { prefix: Option<GrammarFunction>, infix: Option<GrammarFunction>, postfix: Option<GrammarFunction>, } const LiteralRule: Rule = Rule { prefix: Some(Parser::literal), infix: None, postfix:...
(&mut self) { match self.lexer.current() { _ => panic!("Expected token of literal type. Got {:?}", self.lexer.current()), } } }
literal
identifier_name
parser.rs
use std::collections::{ HashMap }; use lexer::{ Lexer, Token }; type GrammarFunction = fn(&mut Parser); struct Rule { prefix: Option<GrammarFunction>, infix: Option<GrammarFunction>,
postfix: Option<GrammarFunction>, } const LiteralRule: Rule = Rule { prefix: Some(Parser::literal), infix: None, postfix: None }; struct Function { identifiers: HashMap<String, u32>, } pub struct Parser { lexer: Lexer, } impl Parser { pub fn new(lexer: Lexer) -> Parser { Parser { ...
random_line_split
misc_crypto.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 //! Miscellaneous cryptograhic test data that isn't worth maintaining custom //! scripts for. /// A plaintext string. pub const PLAIN_TEXT: &[u8] = b"I'm setting the al...
];
0x07, 0x3c, 0x3c, 0x9d, 0x8c, 0x72, 0x0c, 0x79,
random_line_split
greatest_common_divisor.rs
// http://rosettacode.org/wiki/Greatest_common_divisor //! This task demonstrates three possible implementation strategies. /// The num crate. extern crate num; use num::integer::gcd; /// Iterative Euclid algorithm fn iterative_euclid_gcd(mut m: i32, mut n: i32) -> i32 { while m!= 0 { let old_m = m; ...
fn main() { println!("gcd(399, -3999) = {}", gcd(399, -3999)); println!("gcd(0, 3999) = {}", iterative_euclid_gcd(0, 3999)); println!("gcd(13 * 13, 13 * 29) = {}", recursive_euclid_gcd(13 * 13, 13 * 29)); } #[cfg(test)] mod tests { use super::{iterative_euclid_gcd, recursive_euclid_gcd};...
{ if m == 0 { n.abs() } else { recursive_euclid_gcd(n % m, m) } }
identifier_body
greatest_common_divisor.rs
// http://rosettacode.org/wiki/Greatest_common_divisor //! This task demonstrates three possible implementation strategies. /// The num crate. extern crate num; use num::integer::gcd; /// Iterative Euclid algorithm fn iterative_euclid_gcd(mut m: i32, mut n: i32) -> i32 { while m!= 0 { let old_m = m;
} /// Recursive Euclid algorithm fn recursive_euclid_gcd(m: i32, n: i32) -> i32 { if m == 0 { n.abs() } else { recursive_euclid_gcd(n % m, m) } } fn main() { println!("gcd(399, -3999) = {}", gcd(399, -3999)); println!("gcd(0, 3999) = {}", iterative_euclid_gcd(0, 3999)); println...
m = n % m; n = old_m; } n.abs()
random_line_split
greatest_common_divisor.rs
// http://rosettacode.org/wiki/Greatest_common_divisor //! This task demonstrates three possible implementation strategies. /// The num crate. extern crate num; use num::integer::gcd; /// Iterative Euclid algorithm fn iterative_euclid_gcd(mut m: i32, mut n: i32) -> i32 { while m!= 0 { let old_m = m; ...
() { assert_eq!(3, iterative_euclid_gcd(399, -3999)); assert_eq!(3999, iterative_euclid_gcd(0, 3999)); assert_eq!(13, iterative_euclid_gcd(13 * 13, 13 * 29)); } #[test] fn recursive() { assert_eq!(3, recursive_euclid_gcd(399, -3999)); assert_eq!(3999, recursive_eucli...
iterative
identifier_name
greatest_common_divisor.rs
// http://rosettacode.org/wiki/Greatest_common_divisor //! This task demonstrates three possible implementation strategies. /// The num crate. extern crate num; use num::integer::gcd; /// Iterative Euclid algorithm fn iterative_euclid_gcd(mut m: i32, mut n: i32) -> i32 { while m!= 0 { let old_m = m; ...
else { recursive_euclid_gcd(n % m, m) } } fn main() { println!("gcd(399, -3999) = {}", gcd(399, -3999)); println!("gcd(0, 3999) = {}", iterative_euclid_gcd(0, 3999)); println!("gcd(13 * 13, 13 * 29) = {}", recursive_euclid_gcd(13 * 13, 13 * 29)); } #[cfg(test)] mod tests { us...
{ n.abs() }
conditional_block
attr.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 app_units::Au; use style::attr::{parse_length, AttrValue, LengthOrPercentageOrAuto}; #[test] fn test_parse_d...
check("0", LengthOrPercentageOrAuto::Length(Au::from_px(0))); check("0.000%", LengthOrPercentageOrAuto::Percentage(0.0)); check("+5.82%", LengthOrPercentageOrAuto::Percentage(0.0582)); check( "5.82", LengthOrPercentageOrAuto::Length(Au::from_f64_px(5.82)), ); check("invalid", L...
{ let parsed = parse_length(input); assert_eq!(parsed, expected); }
identifier_body
attr.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 app_units::Au; use style::attr::{parse_length, AttrValue, LengthOrPercentageOrAuto}; #[test] fn test_parse_d...
() { fn check(input: &str, expected: LengthOrPercentageOrAuto) { let parsed = parse_length(input); assert_eq!(parsed, expected); } check("0", LengthOrPercentageOrAuto::Length(Au::from_px(0))); check("0.000%", LengthOrPercentageOrAuto::Percentage(0.0)); check("+5.82%", LengthOrPercen...
test_parse_length
identifier_name
attr.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 app_units::Au; use style::attr::{parse_length, AttrValue, LengthOrPercentageOrAuto}; #[test] fn test_parse_d...
let value = String::from("-1"); match AttrValue::from_limited_i32(value, 0) { AttrValue::Int(_, 0) => (), _ => panic!("expected an IndexSize error"), } } #[test] fn test_from_limited_i32_should_parse_a_uint_when_value_is_0_or_greater() { match AttrValue::from_limited_i32(String::from("1...
fn test_from_limited_i32_should_be_default_when_less_than_0() {
random_line_split
main.rs
//! A helper tool for generating urls and sha256 checksums of cargo-bazel binaries and writing them to a module. use std::collections::HashMap; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use std::process::Command; use std::{env, fs}; use clap::Parser; use hex::ToHex; use sha2::{Digest, Sha256}...
}
{ run_buildifier(&buildifier_path, &path); }
conditional_block
main.rs
//! A helper tool for generating urls and sha256 checksums of cargo-bazel binaries and writing them to a module. use std::collections::HashMap; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use std::process::Command; use std::{env, fs}; use clap::Parser; use hex::ToHex; use sha2::{Digest, Sha256}...
fn render_module(artifacts: &[Artifact]) -> String { let urls: HashMap<&String, &String> = artifacts .iter() .map(|artifact| (&artifact.triple, &artifact.url)) .collect(); let sha256s: HashMap<&String, &String> = artifacts .iter() .map(|artifact| (&artifact.triple, &artifact...
random_line_split
main.rs
//! A helper tool for generating urls and sha256 checksums of cargo-bazel binaries and writing them to a module. use std::collections::HashMap; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use std::process::Command; use std::{env, fs}; use clap::Parser; use hex::ToHex; use sha2::{Digest, Sha256}...
(content: &str) -> PathBuf { let dest = PathBuf::from( env::var("BUILD_WORKSPACE_DIRECTORY").expect("This binary is required to run under Bazel"), ) .join(env!("MODULE_ROOT_PATH")); fs::write(&dest, content).unwrap(); dest } fn run_buildifier(buildifier_path: &Path, module: &Path) { Co...
write_module
identifier_name
main.rs
//! A helper tool for generating urls and sha256 checksums of cargo-bazel binaries and writing them to a module. use std::collections::HashMap; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use std::process::Command; use std::{env, fs}; use clap::Parser; use hex::ToHex; use sha2::{Digest, Sha256}...
fn main() { let opt = Options::parse(); let artifacts = locate_artifacts(&opt.artifacts_dir, &opt.url_prefix); let content = render_module(&artifacts); let path = write_module(&content); if let Some(buildifier_path) = opt.buildifier { run_buildifier(&buildifier_path, &path); } }
{ Command::new(buildifier_path) .arg("-lint=fix") .arg("-mode=fix") .arg("-warnings=all") .arg(module) .output() .unwrap(); }
identifier_body
lib.rs
extern crate chrono; #[macro_use] extern crate nom; #[cfg(target_os = "linux")] extern crate alsa; #[cfg(feature = "dbus")] extern crate dbus; extern crate libc; #[cfg(feature = "systemstat")] extern crate systemstat; #[cfg(feature = "xkb")] extern crate xcb; #[macro_use] extern crate chan; extern crate serde; extern c...
pub fn add(&mut self, widget: Box<Widget>) -> &mut UnixBar<F> { self.widgets.push(widget); self } pub fn run(&mut self) { let (wid_tx, wid_rx) = chan::async(); for widget in &mut self.widgets { widget.spawn_notifier(wid_tx.clone()); } self.show(...
{ self.fns.insert(name.to_owned(), Box::new(func)); self }
identifier_body
lib.rs
extern crate chrono; #[macro_use] extern crate nom; #[cfg(target_os = "linux")] extern crate alsa; #[cfg(feature = "dbus")] extern crate dbus; extern crate libc; #[cfg(feature = "systemstat")] extern crate systemstat; #[cfg(feature = "xkb")] extern crate xcb; #[macro_use] extern crate chan; extern crate serde; extern c...
(&mut self, widget: Box<Widget>) -> &mut UnixBar<F> { self.widgets.push(widget); self } pub fn run(&mut self) { let (wid_tx, wid_rx) = chan::async(); for widget in &mut self.widgets { widget.spawn_notifier(wid_tx.clone()); } self.show(); let (...
add
identifier_name
lib.rs
extern crate chrono; #[macro_use] extern crate nom; #[cfg(target_os = "linux")] extern crate alsa; #[cfg(feature = "dbus")] extern crate dbus; extern crate libc; #[cfg(feature = "systemstat")] extern crate systemstat; #[cfg(feature = "xkb")] extern crate xcb; #[macro_use] extern crate chan; extern crate serde; extern c...
stdin_rx.recv() -> line => self.formatter.handle_stdin(line, &mut self.fns), } } } fn show(&mut self) { let vals: Vec<Format> = self.widgets.iter().map(|ref w| w.current_value()).collect(); let line = self.formatter.format_all(&vals); println!("{}", l...
wid_rx.recv() => self.show(),
random_line_split
lib.rs
extern crate chrono; #[macro_use] extern crate nom; #[cfg(target_os = "linux")] extern crate alsa; #[cfg(feature = "dbus")] extern crate dbus; extern crate libc; #[cfg(feature = "systemstat")] extern crate systemstat; #[cfg(feature = "xkb")] extern crate xcb; #[macro_use] extern crate chan; extern crate serde; extern c...
} }); loop { chan_select! { wid_rx.recv() => self.show(), stdin_rx.recv() -> line => self.formatter.handle_stdin(line, &mut self.fns), } } } fn show(&mut self) { let vals: Vec<Format> = self.widgets.iter().map(...
{ stdin_tx.send(line.clone()); }
conditional_block
test3.rs
extern crate blurz; use std::error::Error; use std::time::Duration; use std::thread; use blurz::bluetooth_adapter::BluetoothAdapter as Adapter; use blurz::bluetooth_device::BluetoothDevice as Device; use blurz::bluetooth_discovery_session::BluetoothDiscoverySession as DiscoverySession; fn test3() -> Result<(), Box<E...
{ match test3() { Ok(_) => (), Err(e) => println!("{:?}", e), } }
identifier_body
test3.rs
extern crate blurz; use std::error::Error; use std::time::Duration; use std::thread; use blurz::bluetooth_adapter::BluetoothAdapter as Adapter; use blurz::bluetooth_device::BluetoothDevice as Device; use blurz::bluetooth_discovery_session::BluetoothDiscoverySession as DiscoverySession; fn test3() -> Result<(), Box<E...
} } fn main() { match test3() { Ok(_) => (), Err(e) => println!("{:?}", e), } }
let device = Device::new(d.clone()); println!("{} {:?} {:?}", device.get_id(), device.get_address(),device.get_rssi()); try!(adapter.remove_device(device.get_id())); } try!(session.stop_discovery());
random_line_split
test3.rs
extern crate blurz; use std::error::Error; use std::time::Duration; use std::thread; use blurz::bluetooth_adapter::BluetoothAdapter as Adapter; use blurz::bluetooth_device::BluetoothDevice as Device; use blurz::bluetooth_discovery_session::BluetoothDiscoverySession as DiscoverySession; fn
() -> Result<(), Box<Error>> { let adapter: Adapter = try!(Adapter::init()); try!(adapter.set_powered(true)); loop { let session = try!(DiscoverySession::create_session(adapter.get_id())); thread::sleep(Duration::from_millis(200)); try!(session.start_discovery()); thread::sle...
test3
identifier_name
build.rs
use std::{env, error::Error, path::PathBuf, process::Command, str}; use walkdir::WalkDir; fn command_output(cmd: &mut Command) -> String { str::from_utf8(&cmd.output().unwrap().stdout) .unwrap() .trim() .to_string() } fn command_ok(cmd: &mut Command) -> bool { cmd.status().ok().map_or(false, |s| s.succes...
dir.push("HsFFI.h"); dir.as_os_str().to_owned().to_string_lossy() }) // Tell cargo to invalidate the built crate whenever any of the // included header files changed. .parse_callbacks(Box::new(bindgen::CargoCallbacks)) // Finish the builder and generate the bin...
// The input header we would like to generate // bindings for. .header({ let mut dir = PathBuf::from(ghc("cabal", "--print-libdir")); dir.push("include");
random_line_split
build.rs
use std::{env, error::Error, path::PathBuf, process::Command, str}; use walkdir::WalkDir; fn command_output(cmd: &mut Command) -> String { str::from_utf8(&cmd.output().unwrap().stdout) .unwrap() .trim() .to_string() } fn command_ok(cmd: &mut Command) -> bool { cmd.status().ok().map_or(false, |s| s.succes...
|| entry.path().is_dir() || e.ends_with("_p.a") || e.ends_with("_thr.a") || e.ends_with("_thr_l.a") || e.ends_with("_thr_debug.a") || e.ends_with("_l.a") || e.ends_with("_debug.a") || e.contains("_debug.a") { continue; ...
{ std::env::set_current_dir("../haskell")?; let builder = if command_ok(Command::new("stack").arg("--version")) { "stack" } else { "cabal" }; // Go to the libdir for ghc then traverse all the entries for entry in WalkDir::new(&ghc(builder, "--print-libdir")) .min_depth(1) .into_iter() { ...
identifier_body
build.rs
use std::{env, error::Error, path::PathBuf, process::Command, str}; use walkdir::WalkDir; fn command_output(cmd: &mut Command) -> String { str::from_utf8(&cmd.output().unwrap().stdout) .unwrap() .trim() .to_string() } fn
(cmd: &mut Command) -> bool { cmd.status().ok().map_or(false, |s| s.success()) } fn ghc(builder: &str, arg: &str) -> String { command_output(Command::new(builder).args(&["exec", "--", "ghc", arg])) } // Each os has a diferent extesion for the Dynamic Libraries. This compiles for // the correct ones. #[cfg(not(any...
command_ok
identifier_name
nth.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 std::ascii::AsciiExt; use super::{Token, Parser, ParserInput, BasicParseError}; /// Parse the *An+B* notati...
} else { Err(()) } } fn parse_number_saturate(string: &str) -> Result<i32, ()> { let mut input = ParserInput::new(string); let mut parser = Parser::new(&mut input); let int = if let Ok(&Token::Number {int_value: Some(int),..}) = parser.next_including_whitespace_and_comments(...
{ Ok(parse_number_saturate(&string[1..]).unwrap()) // Include the minus sign
random_line_split
nth.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 std::ascii::AsciiExt; use super::{Token, Parser, ParserInput, BasicParseError}; /// Parse the *An+B* notati...
i, 't>(input: &mut Parser<'i, 't>, a: i32) -> Result<(i32, i32), BasicParseError<'i>> { let start = input.state(); match input.next() { Ok(&Token::Delim('+')) => parse_signless_b(input, a, 1), Ok(&Token::Delim('-')) => parse_signless_b(input, a, -1), Ok(&Token::Number { has_sign: true, i...
rse_b<'
identifier_name
nth.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 std::ascii::AsciiExt; use super::{Token, Parser, ParserInput, BasicParseError}; /// Parse the *An+B* notati...
"n" => Ok(try!(parse_b(input, 1))), "-n" => Ok(try!(parse_b(input, -1))), "n-" => Ok(try!(parse_signless_b(input, 1, -1))), "-n-" => Ok(try!(parse_signless_b(input, -1, -1))), _ => { let (slice, a) = if value.starts_with...
// FIXME: remove .clone() when lifetimes are non-lexical. match input.next()?.clone() { Token::Number { int_value: Some(b), .. } => { Ok((0, b)) } Token::Dimension { int_value: Some(a), unit, .. } => { match_ignore_ascii_case! { &unit, ...
identifier_body
error.rs
use front::stdlib::object::PROTOTYPE; use front::stdlib::value::{Value, ResultValue, to_value}; use front::stdlib::function::Function; /// Create a new error pub fn make_error(args:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue { if args.len() >= 1 { this.set_field("message", args[0]); } ...
(_:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue { let name = this.get_field("name"); let message = this.get_field("message"); Ok(to_value(format!("{}: {}", name, message).into_string())) } /// Create a new `Error` object pub fn _create(global: Value) -> Value { let prototype = js!(global, { ...
to_string
identifier_name
error.rs
use front::stdlib::object::PROTOTYPE; use front::stdlib::value::{Value, ResultValue, to_value}; use front::stdlib::function::Function; /// Create a new error pub fn make_error(args:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue { if args.len() >= 1 { this.set_field("message", args[0]); } ...
/// Create a new `Error` object pub fn _create(global: Value) -> Value { let prototype = js!(global, { "message": "", "name": "Error", "toString": Function::make(to_string, []) }); let error = Function::make(make_error, ["message"]); error.set_field(PROTOTYPE, prototype); er...
{ let name = this.get_field("name"); let message = this.get_field("message"); Ok(to_value(format!("{}: {}", name, message).into_string())) }
identifier_body
error.rs
use front::stdlib::object::PROTOTYPE; use front::stdlib::value::{Value, ResultValue, to_value}; use front::stdlib::function::Function; /// Create a new error pub fn make_error(args:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue { if args.len() >= 1
Ok(Value::undefined()) } /// Get the string representation of the error pub fn to_string(_:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue { let name = this.get_field("name"); let message = this.get_field("message"); Ok(to_value(format!("{}: {}", name, message).into_string())) } /// Create a n...
{ this.set_field("message", args[0]); }
conditional_block
error.rs
use front::stdlib::object::PROTOTYPE; use front::stdlib::value::{Value, ResultValue, to_value}; use front::stdlib::function::Function;
/// Create a new error pub fn make_error(args:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue { if args.len() >= 1 { this.set_field("message", args[0]); } Ok(Value::undefined()) } /// Get the string representation of the error pub fn to_string(_:Vec<Value>, _:Value, _:Value, this:Value) ->...
random_line_split
main.rs
extern crate libc; extern crate llvm_sys; extern crate argparse; extern crate typed_arena; macro_rules! cstr { ($s:expr) => ( concat!($s, "\0").as_ptr() as *const ::libc::c_char ) } macro_rules! fl { () => ((file!(), line!())); (line:$expr) => ((file!(), line)); } enum
<L, R> { Left(L), Right(R), } // TODO: unify parameter ordering mod parse; mod ast; mod ty; mod mir; use parse::Lexer; use ast::Ast; fn main() { use std::io::Read; let mut name = "".to_owned(); let mut output = None; let mut print_mir = false; let mut print_llir = false; let mut opt ...
Either
identifier_name
main.rs
extern crate libc; extern crate llvm_sys; extern crate argparse; extern crate typed_arena; macro_rules! cstr { ($s:expr) => ( concat!($s, "\0").as_ptr() as *const ::libc::c_char ) } macro_rules! fl { () => ((file!(), line!())); (line:$expr) => ((file!(), line)); } enum Either<L, R> { Left...
{ format!("{}.s", name) }
identifier_body
main.rs
extern crate libc; extern crate llvm_sys; extern crate argparse; extern crate typed_arena; macro_rules! cstr { ($s:expr) => ( concat!($s, "\0").as_ptr() as *const ::libc::c_char ) } macro_rules! fl { () => ((file!(), line!())); (line:$expr) => ((file!(), line)); } enum Either<L, R> { Left...
mir.build_and_write(&output, print_llir) } // TODO: take off the ".sva" of the input file fn get_output_from_name(name: &str) -> String { format!("{}.s", name) }
random_line_split
true.rs
// * This file is part of the uutils coreutils package. // * // * (c) Jordi Boggiano <j.boggiano@seld.be> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. use clap::{App, AppSettings, Arg}; use std::io::Write; use uucore::error...
(args: impl uucore::Args) -> UResult<()> { let mut app = uu_app(); if let Ok(matches) = app.try_get_matches_from_mut(args) { let error = if matches.index_of("help").is_some() { app.print_long_help() } else if matches.index_of("version").is_some() { writeln!(std::io::stdo...
uumain
identifier_name
true.rs
// * This file is part of the uutils coreutils package. // * // * (c) Jordi Boggiano <j.boggiano@seld.be> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. use clap::{App, AppSettings, Arg}; use std::io::Write; use uucore::error...
{ App::new(uucore::util_name()) .version(clap::crate_version!()) .about(ABOUT) // We provide our own help and version options, to ensure maximum compatibility with GNU. .setting(AppSettings::DisableHelpFlag | AppSettings::DisableVersionFlag) .arg( Arg::new("help")...
identifier_body
true.rs
// * This file is part of the uutils coreutils package. // * // * (c) Jordi Boggiano <j.boggiano@seld.be> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. use clap::{App, AppSettings, Arg}; use std::io::Write; use uucore::error...
else { Ok(()) }; if let Err(print_fail) = error { // Try to display this error. let _ = writeln!(std::io::stderr(), "{}: {}", uucore::util_name(), print_fail); // Mirror GNU options. When failing to print warnings or version flags, then we exit ...
{ writeln!(std::io::stdout(), "{}", app.render_version()) }
conditional_block
true.rs
// * This file is part of the uutils coreutils package. // * // * (c) Jordi Boggiano <j.boggiano@seld.be> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. use clap::{App, AppSettings, Arg}; use std::io::Write; use uucore::error...
if let Ok(matches) = app.try_get_matches_from_mut(args) { let error = if matches.index_of("help").is_some() { app.print_long_help() } else if matches.index_of("version").is_some() { writeln!(std::io::stdout(), "{}", app.render_version()) } else { Ok(()) ...
random_line_split
x86.rs
#![allow(non_upper_case_globals)] pub use self::x86_shared::*; use core::mem::size_of; mod x86_shared; bitflags! { flags GdtAccess: u8 { const Accessed = 1 << 0, const Writable = 1 << 1, const Direction = 1 << 2, const Executable = 1 << 3, const NotTss = 1 << 4, } } #[derive(Copy, Clone, Debug)] #[repr...
else { if ((limit - 0xFFF) & 0xFFF) > 0 { panic!("bad segment limit for GDT entry"); } (((limit & 0xFFFF000) >> 12) as u16, ((limit & 0xF0000000) >> 28) as u8 | 0xC0u8) }; GdtEntry { base1: base as u16, base2: ((base as usize & 0xFF0000) >> 16) as u8, base3: ((base as usize & 0xFF000000) >> 2...
{ ((limit & 0xFFFF) as u16, ((limit & 0xF0000) >> 16) as u8 | 0x40u8) }
conditional_block
x86.rs
#![allow(non_upper_case_globals)] pub use self::x86_shared::*; use core::mem::size_of; mod x86_shared; bitflags! { flags GdtAccess: u8 { const Accessed = 1 << 0, const Writable = 1 << 1, const Direction = 1 << 2, const Executable = 1 << 3, const NotTss = 1 << 4, } } #[derive(Copy, Clone, Debug)] #[repr...
pub eax: u32, pub ecx: u32, pub edx: u32, pub ebx: u32, pub esp: u32, pub ebp: u32, pub esi: u32, pub edi: u32, pub es: u16, reserved4: u16, pub cs: u16, reserved5: u16, pub ss: u16, reserved6: u16, pub ds: u16, reserved7: u16, pub fs: u16, reserved8: u16, pub gs: u16, reserved9: u16, pub ldtr: u...
reserved3: u16, pub cr3: u32, pub eip: u32, pub eflags: u32,
random_line_split
x86.rs
#![allow(non_upper_case_globals)] pub use self::x86_shared::*; use core::mem::size_of; mod x86_shared; bitflags! { flags GdtAccess: u8 { const Accessed = 1 << 0, const Writable = 1 << 1, const Direction = 1 << 2, const Executable = 1 << 3, const NotTss = 1 << 4, } } #[derive(Copy, Clone, Debug)] #[repr...
{ limit: u16, ptr: *const IdtEntry, } asm!("lidtl $0" :: "*m"(&IDTR { ptr: idt.as_ptr(), limit: idt.len() as u16 * 8 }) :: "volatile"); } #[inline(always)] pub unsafe fn stack_jmp(stack: *mut (), ip: *const ()) ->! { asm!("mov esp, $0; jmp $1" :: "rg"(stack), "r"(ip) :: "volatile", "intel"); loop { } }
IDTR
identifier_name
events_impl.rs
// Copyright 2020 The Exonum Team // // 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 i...
} impl NodeHandler { fn handle_internal_event(&mut self, event: InternalEvent) { match event.0 { InternalEventInner::Timeout(timeout) => self.handle_timeout(timeout), InternalEventInner::JumpToRound(height, round) => self.handle_new_round(height, round), InternalEventIn...
{ match event { Event::Network(network) => { self.handle_network_event(network); EventOutcome::Ok } Event::Transaction(tx) => { self.handle_incoming_tx(tx); EventOutcome::Ok } Event::Inter...
identifier_body
events_impl.rs
// Copyright 2020 The Exonum Team // // 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 i...
(&mut self, event: Event) -> EventOutcome { match event { Event::Network(network) => { self.handle_network_event(network); EventOutcome::Ok } Event::Transaction(tx) => { self.handle_incoming_tx(tx); EventOutcome:...
handle_event
identifier_name
events_impl.rs
// Copyright 2020 The Exonum Team // // 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 i...
NetworkEvent::MessageReceived(raw) => { self.execute_later(InternalRequest::VerifyMessage(raw)); } } } fn handle_api_event(&mut self, event: ExternalMessage) -> EventOutcome { match event { ExternalMessage::PeerAdd(info) => { i...
fn handle_network_event(&mut self, event: NetworkEvent) { match event { NetworkEvent::PeerConnected { addr, connect } => self.handle_connected(addr, *connect), NetworkEvent::PeerDisconnected(peer) => self.handle_disconnected(peer), NetworkEvent::UnableConnectToPeer(peer) ...
random_line_split
start_grammar.rs
use crate::grammar::ElemTypes; use crate::grammar::{ build, Elem, Grammar, GrammarErrors, Prod, ProdElement, Rule, }; use crate::utils::{take_only, ToDoc}; use std::marker::PhantomData; #[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Debug)] pub enum StreamTerminal<T> { EndOfStream, Term(T), } impl<T> StreamTer...
<E: ElemTypes>( elem: Elem<E>, ) -> Elem<StartElementTypes<E>> { match elem { Elem::Term(t) => Elem::Term(StreamTerminal::Term(t)), Elem::NonTerm(nt) => Elem::NonTerm(StartNonTerminal::NTerm(nt)), } } pub fn wrap_grammar_with_start<E: ElemTypes>( g: Grammar<E>, ) -> Result<Grammar<StartElementTypes<E>>...
base_elem_to_start_elem
identifier_name
start_grammar.rs
use crate::grammar::ElemTypes; use crate::grammar::{ build, Elem, Grammar, GrammarErrors, Prod, ProdElement, Rule, }; use crate::utils::{take_only, ToDoc}; use std::marker::PhantomData; #[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Debug)] pub enum StreamTerminal<T> { EndOfStream, Term(T), } impl<T> StreamTer...
} impl<AK> ToDoc for StartActionKey<AK> where AK: ToDoc, { fn to_doc<'a, DA: pretty::DocAllocator<'a>>( &self, da: &'a DA, ) -> pretty::DocBuilder<'a, DA> where DA::Doc: Clone, { match self { StartActionKey::Start => da.text("<START>"), StartActionKey::ActionKey(ak) => ak.to_doc(...
{ match self { StartActionKey::Start => None, StartActionKey::ActionKey(ak) => Some(ak), } }
identifier_body
start_grammar.rs
use crate::grammar::ElemTypes; use crate::grammar::{ build, Elem, Grammar, GrammarErrors, Prod, ProdElement, Rule, }; use crate::utils::{take_only, ToDoc}; use std::marker::PhantomData; #[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Debug)] pub enum StreamTerminal<T> { EndOfStream, Term(T), } impl<T> StreamTer...
where AV: ToDoc, { fn to_doc<'a, DA: pretty::DocAllocator<'a>>( &self, da: &'a DA, ) -> pretty::DocBuilder<'a, DA> where DA::Doc: Clone, { match self { StartActionValue::Start => da.text("<START>"), StartActionValue::ActionValue(av) => av.to_doc(da), } } } #[derive(Derivativ...
impl<AV> ToDoc for StartActionValue<AV>
random_line_split
spec.rs
extern crate stache; extern crate tempdir; extern crate yaml_rust; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::Command; use stache::ruby; use stache::{Compile, Statement, Template}; use tempdir::TempDir; use yaml_rust::{Yaml, YamlLoader}; #[test] fn ruby() { let build...
} /// Parses templates provided by the Mustache specification suite. fn templates() -> Vec<Template> { let base = PathBuf::from("ext/spec/specs"); let files = vec!["comments", "interpolation", "inverted", "sections"]; files .iter() .flat_map(|name| { let path = base.join(name).wi...
{ let out = String::from_utf8(output.stdout).unwrap(); let err = String::from_utf8(output.stderr).unwrap(); panic!("{}{}", out, err); }
conditional_block
spec.rs
extern crate stache; extern crate tempdir; extern crate yaml_rust;
use std::io::Read; use std::path::{Path, PathBuf}; use std::process::Command; use stache::ruby; use stache::{Compile, Statement, Template}; use tempdir::TempDir; use yaml_rust::{Yaml, YamlLoader}; #[test] fn ruby() { let build = TempDir::new("stache-build").unwrap(); let source = build.path().join("stache.c"...
use std::fs::File;
random_line_split
spec.rs
extern crate stache; extern crate tempdir; extern crate yaml_rust; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::Command; use stache::ruby; use stache::{Compile, Statement, Template}; use tempdir::TempDir; use yaml_rust::{Yaml, YamlLoader}; #[test] fn
() { let build = TempDir::new("stache-build").unwrap(); let source = build.path().join("stache.c"); let script = "./tests/fixtures/test-ruby"; let templates = templates(); let program = ruby::link(&templates).unwrap(); program.write(source).unwrap(); let output = Command::new(script).arg(b...
ruby
identifier_name
spec.rs
extern crate stache; extern crate tempdir; extern crate yaml_rust; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::Command; use stache::ruby; use stache::{Compile, Statement, Template}; use tempdir::TempDir; use yaml_rust::{Yaml, YamlLoader}; #[test] fn ruby() { let build...
.collect() } /// Parses the YAML document at the given path. fn document(path: &Path) -> Yaml { let mut file = File::open(path).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); let mut docs = YamlLoader::load_from_str(&contents).unwrap(); docs.pop()....
{ let base = PathBuf::from("ext/spec/specs"); let files = vec!["comments", "interpolation", "inverted", "sections"]; files .iter() .flat_map(|name| { let path = base.join(name).with_extension("yml"); let spec = document(&path); let tests = spec["tests"].as...
identifier_body
pool.rs
//! Connection pooling for a single MongoDB server. use error::Error::{self, ArgumentError, OperationError}; use error::Result; use Client; use coll::options::FindOptions; use command_type::CommandType; use connstring::Host; use cursor::Cursor; use stream::{Stream, StreamConnector}; use wire_protocol::flags::OpQueryFl...
// Attempt to lock and return the socket to the pool, // or give up if the pool lock has been poisoned. if let Ok(mut locked) = self.pool.lock() { if self.iteration == locked.iteration { locked.sockets.push(self.socket.take().unwrap()); // Notify wai...
{ return; }
conditional_block
pool.rs
//! Connection pooling for a single MongoDB server. use error::Error::{self, ArgumentError, OperationError}; use error::Result; use Client; use coll::options::FindOptions; use command_type::CommandType; use connstring::Host; use cursor::Cursor; use stream::{Stream, StreamConnector}; use wire_protocol::flags::OpQueryFl...
(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("ConnectionPool") .field("host", &self.host) .finish() } } struct Pool { /// The maximum number of concurrent connections allowed. pub size: usize, // The current number of open connections. pub len: Arc<A...
fmt
identifier_name
pool.rs
//! Connection pooling for a single MongoDB server. use error::Error::{self, ArgumentError, OperationError}; use error::Result; use Client; use coll::options::FindOptions; use command_type::CommandType; use connstring::Host; use cursor::Cursor; use stream::{Stream, StreamConnector}; use wire_protocol::flags::OpQueryFl...
impl Drop for PooledStream { fn drop(&mut self) { // Don't add streams that couldn't successfully handshake to the pool. if!self.successful_handshake { return; } // Attempt to lock and return the socket to the pool, // or give up if the pool lock has been poisone...
}
random_line_split
crateC.rs
// Copyright 2017 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 foo2 = crateA::Foo; let bar2 = crateA::bar(); { extern crate crateB; crateB::try_foo(foo2); crateB::try_bar(bar2); } }
identifier_body
crateC.rs
// Copyright 2017 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 foo2 = crateA::Foo; let bar2 = crateA::bar(); { extern crate crateB; crateB::try_foo(foo2); crateB::try_bar(bar2); } }
main
identifier_name
crateC.rs
// Copyright 2017 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 ...
// This is similar to how the error can be introduced // when using cargo's automatic dependency resolution. extern crate crateA; fn main() { let foo2 = crateA::Foo; let bar2 = crateA::bar(); { extern crate crateB; crateB::try_foo(foo2); crateB::try_bar(bar2); } }
// is only introduced as an indirect dependency. // and the type is accessed via a re-export.
random_line_split
mod.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/. #[macro_use] mod macros; mod api; mod blockdev; mod connection; mod consts; mod filesystem; mod pool; mod tree; mod ...
use std::{ collections::HashMap, sync::{Condvar, Mutex}, }; use dbus::Path; use crate::engine::PoolUuid; pub use self::{ connection::DbusConnectionHandler, tree::DbusTreeHandler, types::DbusAction, udev::DbusUdevHandler, util::create_dbus_handlers, }; type CreatePoolState = Mutex<HashMap<PoolUuid, ...
mod udev; mod util;
random_line_split
main.rs
extern crate hyper; extern crate iron; extern crate rand; extern crate urlencoded; #[cfg(test)] extern crate iron_test; mod handlers; mod storage; use iron::prelude::*; use std::env; use self::handlers::UrlShortenerHandler; use self::storage::persisted::PersistedKeyValueStore; fn
() { let port = env::var("PORT").unwrap_or("3000".to_string()); let short_url_prefix = env::var("SHORT_URL_PREFIX") .unwrap_or(format!("http://localhost:{}/", port)); println!("Starting URL Shortener on port {}...", port); let addr = format!("localhost:{}", port); let key_value_store = Pers...
main
identifier_name
main.rs
extern crate hyper; extern crate iron; extern crate rand; extern crate urlencoded; #[cfg(test)] extern crate iron_test; mod handlers; mod storage; use iron::prelude::*; use std::env; use self::handlers::UrlShortenerHandler; use self::storage::persisted::PersistedKeyValueStore; fn main() { let port = env::var(...
} }
{ println!("Error: {}", e.to_string()); std::process::exit(-1); }
conditional_block
main.rs
extern crate hyper; extern crate iron; extern crate rand; extern crate urlencoded;
mod storage; use iron::prelude::*; use std::env; use self::handlers::UrlShortenerHandler; use self::storage::persisted::PersistedKeyValueStore; fn main() { let port = env::var("PORT").unwrap_or("3000".to_string()); let short_url_prefix = env::var("SHORT_URL_PREFIX") .unwrap_or(format!("http://localho...
#[cfg(test)] extern crate iron_test; mod handlers;
random_line_split
main.rs
extern crate hyper; extern crate iron; extern crate rand; extern crate urlencoded; #[cfg(test)] extern crate iron_test; mod handlers; mod storage; use iron::prelude::*; use std::env; use self::handlers::UrlShortenerHandler; use self::storage::persisted::PersistedKeyValueStore; fn main()
{ let port = env::var("PORT").unwrap_or("3000".to_string()); let short_url_prefix = env::var("SHORT_URL_PREFIX") .unwrap_or(format!("http://localhost:{}/", port)); println!("Starting URL Shortener on port {}...", port); let addr = format!("localhost:{}", port); let key_value_store = Persis...
identifier_body
reusable_diagnostic.rs
use codespan_reporting::diagnostic::{Diagnostic, Label};
use codespan_reporting::term::termcolor::StandardStream; use codespan_reporting::term::{self, ColorArg}; use std::ops::Range; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(name = "emit")] pub struct Opts { #[structopt(long = "color", parse(try_from_str), default_value = "auto", ...
use codespan_reporting::files::SimpleFile;
random_line_split
reusable_diagnostic.rs
use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::files::SimpleFile; use codespan_reporting::term::termcolor::StandardStream; use codespan_reporting::term::{self, ColorArg}; use std::ops::Range; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(name = "emit")] pub struct ...
(&self) -> Diagnostic<()> { match self { Error::MismatchType(left, right) => Diagnostic::error() .with_code("E0308") .with_message("mismatch types") .with_labels(vec![ Label::primary((), right.range.clone()).with_message(format!( ...
report
identifier_name
reusable_diagnostic.rs
use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::files::SimpleFile; use codespan_reporting::term::termcolor::StandardStream; use codespan_reporting::term::{self, ColorArg}; use std::ops::Range; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(name = "emit")] pub struct ...
&format!( r#" first assignment to `{0}` help: make this binding mutable: `mut {0}` "#, original.content, ), ...
{ match self { Error::MismatchType(left, right) => Diagnostic::error() .with_code("E0308") .with_message("mismatch types") .with_labels(vec![ Label::primary((), right.range.clone()).with_message(format!( "Exp...
identifier_body
mod.rs
/// VFS and filesystem drivers /// /// Virtual file system abstraction and filesystem drivers pub mod fs; /// ATA specific disk driver
pub mod ata; /// A storage disk /// /// This is a trait implemented by specific disk types (ATA, ATAPI, SATA) for transferring data /// between a disk and memory. pub trait Disk { /// Read from disk /// /// Read content from the disk at specified block. To read multiple blocks/sectors, change the /// `...
random_line_split
bool_filter.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
} impl Filter<Entry> for BoolFilter { fn filter(&self, _: &Entry) -> bool { self.0 } }
}
random_line_split
bool_filter.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
(bool); impl BoolFilter { pub fn new(b: bool) -> BoolFilter { BoolFilter(b) } } impl Filter<Entry> for BoolFilter { fn filter(&self, _: &Entry) -> bool { self.0 } }
BoolFilter
identifier_name
bool_filter.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
}
{ self.0 }
identifier_body
driver.rs
// Copyright (c) 2016 P.Y. Laligand use std::fs; use std::io::Read; use std::path::Path; use google_drive3::Drive; use hyper::Client; use serde_json; use yup_oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, ConsoleApplicationSecret, DiskTokenStorage, FlowType}; use super::error::DriveError; ...
pub fn new(config_path: &String, credentials_path: &String) -> Result<Driver, DriveError> { let secret = try!(Driver::read_secret(config_path)); let storage = try!(DiskTokenStorage::new(credentials_path)); let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, Clie...
let secret: ConsoleApplicationSecret = try!(serde_json::from_str(content.as_str())); secret.installed.ok_or(DriveError::Described(String::from("No params for installed flow"))) }
random_line_split
driver.rs
// Copyright (c) 2016 P.Y. Laligand use std::fs; use std::io::Read; use std::path::Path; use google_drive3::Drive; use hyper::Client; use serde_json; use yup_oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, ConsoleApplicationSecret, DiskTokenStorage, FlowType}; use super::error::DriveError; ...
{ hub: Drive<Client, Authenticator<DefaultAuthenticatorDelegate, DiskTokenStorage, Client>>, } impl Driver { /// Reads oAuth application config from a given file. fn read_secret<P: AsRef<Path>>(path: P) -> Result<ApplicationSecret, DriveError> { let mut file = try!(fs::File::open(path)); l...
Driver
identifier_name
driver.rs
// Copyright (c) 2016 P.Y. Laligand use std::fs; use std::io::Read; use std::path::Path; use google_drive3::Drive; use hyper::Client; use serde_json; use yup_oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, ConsoleApplicationSecret, DiskTokenStorage, FlowType}; use super::error::DriveError; ...
pub fn new(config_path: &String, credentials_path: &String) -> Result<Driver, DriveError> { let secret = try!(Driver::read_secret(config_path)); let storage = try!(DiskTokenStorage::new(credentials_path)); let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, Cli...
{ let mut file = try!(fs::File::open(path)); let mut content = String::new(); try!(file.read_to_string(&mut content)); let secret: ConsoleApplicationSecret = try!(serde_json::from_str(content.as_str())); secret.installed.ok_or(DriveError::Described(String::from("No params for ins...
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/. */ #![feature(arc_weak)] #![cfg_attr(any(target_os = "linux", target_os = "android"), feature(box_raw))] #![feature(b...
// Mac OS-specific library dependencies #[cfg(target_os = "macos")] extern crate core_foundation; #[cfg(target_os = "macos")] extern crate core_graphics; #[cfg(target_os = "macos")] extern crate core_text; pub use paint_context::PaintContext; // Private painting modules mod paint_context; #[path = "display_list/mod...
extern crate freetype;
random_line_split
lib.rs
// The MIT License (MIT) // // Copyright (c) 2016 Skylor R. Schermer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to...
else { None }, format: format, }; pal.data.set_name(Reference::all(), name.into()); format.initialize(&mut pal.data); pal } /// Returns the number of color `Cell`s in the `Palette`. pub fn len(&self) -> usize { self.data.len() } /// Returns whether the `Palette` contains any color `C...
{ Some(Default::default()) }
conditional_block
lib.rs
// The MIT License (MIT) // // Copyright (c) 2016 Skylor R. Schermer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to...
() -> Self { Palette { data: Default::default(), operation_history: None, format: Format::Default, } } } // Display `Palette` in readable format. impl fmt::Display for Palette { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Format: {:?}, History: {:?}\n{}", self.format, sel...
default
identifier_name
lib.rs
// The MIT License (MIT) // // Copyright (c) 2016 Skylor R. Schermer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to...
// Standard imports. use std::fmt; //////////////////////////////////////////////////////////////////////////////// // Palette //////////////////////////////////////////////////////////////////////////////// /// Encapsulates a single color palette. #[derive(Debug)] pub struct Palette { /// The `Palette`'s operation...
random_line_split
zoodefs.rs
pub mod perms { pub const READ: i32 = 1; pub const WRITE: i32 = 1 << 1; pub const CREATE: i32 = 1 << 2; pub const DELETE: i32 = 1 << 3; pub const ADMIN: i32 = 1 << 4; pub const ALL: i32 = READ | WRITE | CREATE | DELETE | ADMIN; } pub mod acls { use perms; use proto::Acl; fn acl(per...
lazy_static!{ pub static ref CREATOR_ALL_ACL: Vec<Acl> = acl(perms::ALL, "auth", ""); pub static ref OPEN_ACL_UNSAFE: Vec<Acl> = acl(perms::ALL, "world", "anyone"); pub static ref READ_ACL_UNSAFE: Vec<Acl> = acl(perms::READ, "world", "anyone"); } }
{ vec![Acl { perms: perm, scheme: scheme.to_owned(), id: id.to_owned(), }] }
identifier_body
zoodefs.rs
pub mod perms { pub const READ: i32 = 1; pub const WRITE: i32 = 1 << 1; pub const CREATE: i32 = 1 << 2; pub const DELETE: i32 = 1 << 3; pub const ADMIN: i32 = 1 << 4; pub const ALL: i32 = READ | WRITE | CREATE | DELETE | ADMIN; } pub mod acls { use perms; use proto::Acl; fn
(perm: i32, scheme: &str, id: &str) -> Vec<Acl> { vec![Acl { perms: perm, scheme: scheme.to_owned(), id: id.to_owned(), }] } lazy_static!{ pub static ref CREATOR_ALL_ACL: Vec<Acl> = acl(perms::ALL, "auth", ""); pub static r...
acl
identifier_name
zoodefs.rs
pub mod perms { pub const READ: i32 = 1; pub const WRITE: i32 = 1 << 1; pub const CREATE: i32 = 1 << 2; pub const DELETE: i32 = 1 << 3; pub const ADMIN: i32 = 1 << 4; pub const ALL: i32 = READ | WRITE | CREATE | DELETE | ADMIN; } pub mod acls { use perms; use proto::Acl; fn acl(per...
} lazy_static!{ pub static ref CREATOR_ALL_ACL: Vec<Acl> = acl(perms::ALL, "auth", ""); pub static ref OPEN_ACL_UNSAFE: Vec<Acl> = acl(perms::ALL, "world", "anyone"); pub static ref READ_ACL_UNSAFE: Vec<Acl> = acl(perms::READ, "world", "anyone"); } }
perms: perm, scheme: scheme.to_owned(), id: id.to_owned(), }]
random_line_split
issue-5884.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 ...
<'a> { a: Box<Option<isize>>, b: &'a Foo, } fn check(a: Box<Foo>) { let _ic = Bar{ b: &*a, a: box None }; } pub fn main(){}
Bar
identifier_name
issue-5884.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(){}
random_line_split
main.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; extern crate serde_json; #[macro_use] extern crate lazy_static; extern crate rocket_contrib; #[macro_use] extern crate serde_derive; extern crate serde; extern crate derbyjson; extern crate handlebars; extern crate chrono; use rocket_c...
(game: Game) -> Json<Vec<(TeamJamState, TeamJamState)>> { let stuff = game.jams().iter().map(|jamstate| { (jamstate[Team::Home].clone(), jamstate[Team::Away].clone()) }).collect::<Vec<_>>(); Json(stuff) } #[derive(FromForm)] struct StartGameCommand<'a> { hometeam: &'a RawStr, awayteam: &'a...
get_scoresheet
identifier_name
main.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; extern crate serde_json; #[macro_use] extern crate lazy_static; extern crate rocket_contrib; #[macro_use] extern crate serde_derive; extern crate serde; extern crate derbyjson; extern crate handlebars; extern crate chrono; use rocket_c...
struct StartGameCommand<'a> { hometeam: &'a RawStr, awayteam: &'a RawStr, timetype: TimeType, at_hrs: Option<u8>, at_mins: Option<u8>, at_ampm: TimeAMPM, ttd_hrs: Option<u8>, ttd_mins: Option<u8>, ttd_secs: Option<u8>, } #[post("/startgame", data = "<form>")] fn startgame<'a>(form: ...
random_line_split
build.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of Tuna. |
// | | // | Tuna 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 | ...
random_line_split
build.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of Tuna. | ...
}
{ println!("cargo:rustc-link-search=framework=/Library/Frameworks"); }
conditional_block
build.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of Tuna. | ...
() { let target = std::env::var("TARGET").unwrap(); if target.ends_with("-apple-darwin") { println!("cargo:rustc-link-search=framework=/Library/Frameworks"); } }
main
identifier_name
build.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of Tuna. | ...
{ let target = std::env::var("TARGET").unwrap(); if target.ends_with("-apple-darwin") { println!("cargo:rustc-link-search=framework=/Library/Frameworks"); } }
identifier_body
2_5_fluid_resistance.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 2-5: Forces (Gravity and Fluid Resistence) with Vectors // // Demonstration of multiple forces acting on bodies (Mover type) // Bodies experience gravity continuously // Bodies experience fluid resistance when in *water* use nannou::prelu...
// Draw movers for mover in &m.movers { mover.display(&draw); } // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); }
random_line_split
2_5_fluid_resistance.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 2-5: Forces (Gravity and Fluid Resistence) with Vectors // // Demonstration of multiple forces acting on bodies (Mover type) // Bodies experience gravity continuously // Bodies experience fluid resistance when in *water* use nannou::prelu...
(&self, draw: &Draw) { draw.rect().xy(self.rect.xy()).wh(self.rect.wh()).gray(0.1); } } impl Mover { fn new(m: f32, x: f32, y: f32) -> Self { // Mass is tied to size let mass = m; let position = pt2(x, y); let velocity = vec2(0.0, 0.0); let acceleration = vec2(0....
display
identifier_name
2_5_fluid_resistance.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 2-5: Forces (Gravity and Fluid Resistence) with Vectors // // Demonstration of multiple forces acting on bodies (Mover type) // Bodies experience gravity continuously // Bodies experience fluid resistance when in *water* use nannou::prelu...
// Newton's 2nd law: F = M * A // or A = F / M fn apply_force(&mut self, force: Vector2) { // Divide by mass let f = force / self.mass; // Accumulate all forces in acceleration self.acceleration += f; } fn update(&mut self) { // Velocity changes according t...
{ Mover::new( random_range(0.5f32, 4.0), random_range(rect.left(), rect.right()), rect.top(), ) }
identifier_body
2_5_fluid_resistance.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 2-5: Forces (Gravity and Fluid Resistence) with Vectors // // Demonstration of multiple forces acting on bodies (Mover type) // Bodies experience gravity continuously // Bodies experience fluid resistance when in *water* use nannou::prelu...
// Gravity is scaled by mass here! let gravity = vec2(0.0, -0.1 * m.movers[i].mass); // Apply gravity m.movers[i].apply_force(gravity); m.movers[i].update(); m.movers[i].check_edges(app.window_rect()); } } fn view(app: &App, m: &Model, frame: Frame) { // Begin...
{ let drag_force = m.liquid.drag(&m.movers[i]); // Apply drag force to Mover m.movers[i].apply_force(drag_force); }
conditional_block
edsl.rs
//! Holmes EDSL //! //! This module provides a set of macros for more easily writing Holmes //! programs, avoiding manual construction of all tye types required. /// Converts an EDSL type specification into a Holmes type object /// Takes the name of a variable containing a holmes object as the first /// parameter, and...
::holmes::engine::types::Func { input_type: src, output_type: dst, run: Box::new(move |v : ::holmes::pg::dyn::Value| { ::holmes::pg::dyn::values::ToValue::to_value($body(typed_unpack!(v, $src))) ...
random_line_split
main.rs
use rand::Rng;
let secret_number = rand::thread_rng().gen_range(1..101); // ANCHOR: here // --snip-- println!("The secret number is: {}", secret_number); loop { println!("Please input your guess."); // --snip-- // ANCHOR_END: here let mut guess = String::new(); io::s...
use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!");
random_line_split
main.rs
use rand::Rng; use std::cmp::Ordering; use std::io; fn
() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..101); // ANCHOR: here // --snip-- println!("The secret number is: {}", secret_number); loop { println!("Please input your guess."); // --snip-- // ANCHOR_END: here let m...
main
identifier_name
main.rs
use rand::Rng; use std::cmp::Ordering; use std::io; fn main()
.read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = guess.trim().parse().expect("Please type a number!"); println!("You guessed: {}", guess); // ANCHOR: here match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"...
{ println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..101); // ANCHOR: here // --snip-- println!("The secret number is: {}", secret_number); loop { println!("Please input your guess."); // --snip-- // ANCHOR_END: here let mut ...
identifier_body
default_ty_param_default_dependent_associated_type.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 ...
struct Foo<X: Default = usize, Y = <X as Id>::This> { data: PhantomData<(X, Y)> } impl<X: Default, Y> Foo<X, Y> { fn new() -> Foo<X, Y> { Foo { data: PhantomData } } } fn main() { let foo = Foo::new(); }
} impl<A> Id for A { type This = A; }
random_line_split