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
media_queries.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/. */ //! [Media queries][mq]. //! //! [mq]: https://drafts.csswg.org/mediaqueries/ use Atom; use context::QuirksMode; ...
() -> Self { MediaType(CustomIdent(atom!("screen"))) } /// The `print` media type. pub fn print() -> Self { MediaType(CustomIdent(atom!("print"))) } fn parse(name: &str) -> Result<Self, ()> { // From https://drafts.csswg.org/mediaqueries/#mq-syntax: // // ...
screen
identifier_name
media_queries.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/. */ //! [Media queries][mq]. //! //! [mq]: https://drafts.csswg.org/mediaqueries/ use Atom; use context::QuirksMode; ...
fn matches(&self, other: MediaType) -> bool { match *self { MediaQueryType::All => true, MediaQueryType::Concrete(ref known_type) => *known_type == other, } } } /// https://drafts.csswg.org/mediaqueries/#media-types #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(fea...
{ match_ignore_ascii_case! { ident, "all" => return Ok(MediaQueryType::All), _ => (), }; // If parseable, accept this type as a concrete type. MediaType::parse(ident).map(MediaQueryType::Concrete) }
identifier_body
media_queries.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/. */ //! [Media queries][mq]. //! //! [mq]: https://drafts.csswg.org/mediaqueries/ use Atom; use context::QuirksMode; ...
else { None }; let media_type = match input.try(|i| i.expect_ident_cloned()) { Ok(ident) => { let result: Result<_, ParseError> = MediaQueryType::parse(&*ident) .map_err(|()| SelectorParseError::UnexpectedIdent(ident.clone()).into()); ...
{ Some(Qualifier::Not) }
conditional_block
error_reporting.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/. */ //! Types used to report parsing errors. #![deny(missing_docs)] use cssparser::{Parser, SourcePosition}; use log...
} }
{ let location = input.source_location(position); info!("Url:\t{}\n{}:{} {}", url.as_str(), location.line, location.column, message) }
conditional_block
error_reporting.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/. */ //! Types used to report parsing errors. #![deny(missing_docs)] use cssparser::{Parser, SourcePosition}; use log...
; impl ParseErrorReporter for StdoutErrorReporter { fn report_error(&self, input: &mut Parser, position: SourcePosition, message: &str, url: &ServoUrl) { if log_enabled!(log::LogLevel::Info) { let location = input.so...
StdoutErrorReporter
identifier_name
error_reporting.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/. */ //! Types used to report parsing errors. #![deny(missing_docs)] use cssparser::{Parser, SourcePosition}; use log...
} }
random_line_split
p068.rs
const N:usize = 5; fn set_v(ans: &mut[usize],idx: &mut usize, vis: &mut[bool], value: usize) { ans[*idx] = value; vis[value] = true; *idx+=1; } fn
(idx: &mut usize, vis: &mut[bool], value: usize) { *idx -= 1; vis[value] = false; } fn dfs(mut ans: &mut[usize],mut idx: &mut usize, mut vis: &mut[bool]) { if *idx == 2*N { for i in 1..N { if ans[0]+ans[1]+ans[3]!= ans[i*2]+ans[i*2+1]+ans[(i*2+3)%(2*N)] { return ; ...
unset_v
identifier_name
p068.rs
const N:usize = 5; fn set_v(ans: &mut[usize],idx: &mut usize, vis: &mut[bool], value: usize) { ans[*idx] = value; vis[value] = true; *idx+=1; } fn unset_v(idx: &mut usize, vis: &mut[bool], value: usize) { *idx -= 1; vis[value] = false; } fn dfs(mut ans: &mut[usize],mut idx: &mut usize, mut vis: &...
for v in (1 as usize..(2*N+1)).rev() { // println!("v={}",v); if vis[v] { continue; } if *idx >= 5 && *idx % 2 ==1 { if ans[0]+ans[1]+ans[3]!= ans[*idx-3]+ans[*idx-2]+v { continue; } } set_v(&mut ans,&mut idx,&mut vi...
{ if *idx == 2*N { for i in 1..N { if ans[0]+ans[1]+ans[3] != ans[i*2]+ans[i*2+1]+ans[(i*2+3)%(2*N)] { return ; } } let mut mini = 0; for i in 0..N { if ans[i*2] < ans[mini*2] { mini = i; } } ...
identifier_body
p068.rs
const N:usize = 5; fn set_v(ans: &mut[usize],idx: &mut usize, vis: &mut[bool], value: usize) {
fn unset_v(idx: &mut usize, vis: &mut[bool], value: usize) { *idx -= 1; vis[value] = false; } fn dfs(mut ans: &mut[usize],mut idx: &mut usize, mut vis: &mut[bool]) { if *idx == 2*N { for i in 1..N { if ans[0]+ans[1]+ans[3]!= ans[i*2]+ans[i*2+1]+ans[(i*2+3)%(2*N)] { retu...
ans[*idx] = value; vis[value] = true; *idx+=1; }
random_line_split
p068.rs
const N:usize = 5; fn set_v(ans: &mut[usize],idx: &mut usize, vis: &mut[bool], value: usize) { ans[*idx] = value; vis[value] = true; *idx+=1; } fn unset_v(idx: &mut usize, vis: &mut[bool], value: usize) { *idx -= 1; vis[value] = false; } fn dfs(mut ans: &mut[usize],mut idx: &mut usize, mut vis: &...
} let mut mini = 0; for i in 0..N { if ans[i*2] < ans[mini*2] { mini = i; } } for ii in 0..N { let i = (ii+mini)%N; print!("{}{}{}",ans[i*2],ans[i*2+1],ans[(i*2+3)%(2*N)]); } println!(""); re...
{ return ; }
conditional_block
room_id.rs
//! Matrix room identifiers. use super::{matrix_uri::UriAction, EventId, MatrixToUri, MatrixUri, ServerName}; /// A Matrix [room ID]. /// /// A `RoomId` is generated randomly or converted from a string slice, and can be converted back /// into a string as needed. /// /// ``` /// # use std::convert::TryFrom; /// # use...
#[test] fn valid_room_id_with_explicit_standard_port() { assert_eq!( <&RoomId>::try_from("!29fhd83h92h0:example.com:443") .expect("Failed to create RoomId.") .as_ref(), "!29fhd83h92h0:example.com:443" ); } #[test] fn valid_room...
{ assert_eq!( serde_json::from_str::<Box<RoomId>>(r#""!29fhd83h92h0:example.com""#) .expect("Failed to convert JSON to RoomId"), <&RoomId>::try_from("!29fhd83h92h0:example.com").expect("Failed to create RoomId.") ); }
identifier_body
room_id.rs
//! Matrix room identifiers. use super::{matrix_uri::UriAction, EventId, MatrixToUri, MatrixUri, ServerName}; /// A Matrix [room ID]. /// /// A `RoomId` is generated randomly or converted from a string slice, and can be converted back /// into a string as needed. /// /// ``` /// # use std::convert::TryFrom; /// # use...
() { assert_eq!(<&RoomId>::try_from("!29fhd83h92h0:/").unwrap_err(), Error::InvalidServerName); } #[test] fn invalid_room_id_port() { assert_eq!( <&RoomId>::try_from("!29fhd83h92h0:example.com:notaport").unwrap_err(), Error::InvalidServerName ); } }
invalid_room_id_host
identifier_name
room_id.rs
//! Matrix room identifiers. use super::{matrix_uri::UriAction, EventId, MatrixToUri, MatrixUri, ServerName}; /// A Matrix [room ID]. /// /// A `RoomId` is generated randomly or converted from a string slice, and can be converted back /// into a string as needed. /// /// ``` /// # use std::convert::TryFrom; /// # use...
assert_eq!( <&RoomId>::try_from("!29fhd83h92h0:example.com:5000") .expect("Failed to create RoomId.") .as_ref(), "!29fhd83h92h0:example.com:5000" ); } #[test] fn missing_room_id_sigil() { assert_eq!( <&RoomId>::try_fr...
#[test] fn valid_room_id_with_non_standard_port() {
random_line_split
player.rs
pub const MAX_VELOCITY: f64 = 1.5; pub struct Player { _x: f64, _y: f64, pub width: u32, pub height: u32, x_velocity: f64, y_velocity: f64, } impl Player { pub fn new() -> Player { Player {
_x: 0., _y: 0., width: 32, height: 32, x_velocity: 0., y_velocity: 0., } } pub fn x(&self, lag: f64) -> i32 { (self._x + self.x_velocity*lag) as i32 } pub fn y(&self, lag: f64) -> i32 { // println!("{}", la...
random_line_split
player.rs
pub const MAX_VELOCITY: f64 = 1.5; pub struct Player { _x: f64, _y: f64, pub width: u32, pub height: u32, x_velocity: f64, y_velocity: f64, } impl Player { pub fn new() -> Player { Player { _x: 0., _y: 0., width: 32, height: 32, ...
(&self, lag: f64) -> i32 { (self._x + self.x_velocity*lag) as i32 } pub fn y(&self, lag: f64) -> i32 { // println!("{}", lag); (self._y + self.y_velocity*lag) as i32 } pub fn change_velocity(&mut self, x_velocity: f64, y_velocity: f64) { self.x_velocity = self.x_velocit...
x
identifier_name
player.rs
pub const MAX_VELOCITY: f64 = 1.5; pub struct Player { _x: f64, _y: f64, pub width: u32, pub height: u32, x_velocity: f64, y_velocity: f64, } impl Player { pub fn new() -> Player { Player { _x: 0., _y: 0., width: 32, height: 32, ...
pub fn y(&self, lag: f64) -> i32 { // println!("{}", lag); (self._y + self.y_velocity*lag) as i32 } pub fn change_velocity(&mut self, x_velocity: f64, y_velocity: f64) { self.x_velocity = self.x_velocity + x_velocity; self.y_velocity = self.y_velocity + y_velocity; } ...
{ (self._x + self.x_velocity*lag) as i32 }
identifier_body
string.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 ...
// succeed. let max_chars = try_opt!(fmt.width.checked_sub(fmt.opener.len() + ender_length + 1)) + 1; // Snip a line at a time from `orig` until it is used up. Push the snippet // onto result. 'outer: loop { // `cur_end` will be where we break the line, as an offset into `orig`. // ...
.unwrap_or(usize::max_value())); result.push_str(fmt.opener); let ender_length = fmt.line_end.len(); // If we cannot put at least a single character per line, the rewrite won't
random_line_split
string.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 ...
<'a> { pub opener: &'a str, pub closer: &'a str, pub line_start: &'a str, pub line_end: &'a str, pub width: usize, pub offset: Indent, pub trim_end: bool, pub config: &'a Config, } // FIXME: simplify this! pub fn rewrite_string<'a>(orig: &str, fmt: &StringFormat<'a>) -> Option<String> {...
StringFormat
identifier_name
string.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 ...
cur_end += 1; } break; } } break; } } // Make sure there is no whitespace to the right of the break. while cur_end < stripped_str.len() && graphemes[cur_en...
{ let line = &graphemes[cur_start..].join(""); result.push_str(line); break 'outer; }
conditional_block
lib.rs
#![cfg_attr(feature = "unstable", feature(const_fn, drop_types_in_const))] #![cfg_attr(feature = "serde_derive", feature(proc_macro))] #![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #![cfg_attr(not(feature = "unstable"), deny(warnings))] extern crat...
{ name: String, protocol_date: String, } impl Service { pub fn new<S>(name: S, protocol_date: S) -> Self where S: Into<String> { Service { name: name.into(), protocol_date: protocol_date.into(), } } } pub fn generate(service: Service, output_path: &...
Service
identifier_name
lib.rs
#![cfg_attr(feature = "unstable", feature(const_fn, drop_types_in_const))] #![cfg_attr(feature = "serde_derive", feature(proc_macro))] #![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #![cfg_attr(not(feature = "unstable"), deny(warnings))] extern crat...
extern crate regex; extern crate serde; extern crate serde_json; #[cfg(feature = "serde_derive")] #[macro_use] extern crate serde_derive; #[cfg(not(feature = "serde_derive"))] extern crate serde_codegen; use std::fs::File; use std::io::{Write, BufReader, BufWriter}; use std::path::Path; use botocore::Service as Boto...
extern crate lazy_static;
random_line_split
orphan-widgets-attribute.rs
/* * Copyright (c) 2020 Boucher, Antoni <bouanto@zoho.com> * * 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 * use, copy,...
gtk::Button { clicked => Increment, label: "+", }, gtk::Label { text: &self.model.counter.to_string(), }, #[name="radio1"] gtk::RadioButton { la...
gtk::Window { gtk::Box { orientation: Vertical, #[name="inc_button"]
random_line_split
orphan-widgets-attribute.rs
/* * Copyright (c) 2020 Boucher, Antoni <bouanto@zoho.com> * * 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 * use, copy,...
fn update(&mut self, event: Msg) { match event { Click(x, y) => println!("Clicked on {}, {}", x, y), Decrement => self.model.counter -= 1, End => println!("End"), Increment => self.model.counter += 1, Move(x, y) => println!("Moved to {}, {}", x, ...
{ Model { counter: 0, } }
identifier_body
orphan-widgets-attribute.rs
/* * Copyright (c) 2020 Boucher, Antoni <bouanto@zoho.com> * * 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 * use, copy,...
() { Win::run(()).expect("Win::run failed"); }
main
identifier_name
issue-9951.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 ...
// pretty-expanded FIXME #23616 #![allow(unused_variables)] trait Bar { fn noop(&self); } impl Bar for u8 { fn noop(&self) {} } fn main() { let (a, b) = (&5u8 as &Bar, &9u8 as &Bar); let (c, d): (&Bar, &Bar) = (a, b); let (a, b) = (Box::new(5u8) as Box<Bar>, Box::new(9u8) as Box<Bar>); let (c, d...
random_line_split
issue-9951.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 ...
() { let (a, b) = (&5u8 as &Bar, &9u8 as &Bar); let (c, d): (&Bar, &Bar) = (a, b); let (a, b) = (Box::new(5u8) as Box<Bar>, Box::new(9u8) as Box<Bar>); let (c, d): (&Bar, &Bar) = (&*a, &*b); let (c, d): (&Bar, &Bar) = (&5, &9); }
main
identifier_name
issue-9951.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 ...
} fn main() { let (a, b) = (&5u8 as &Bar, &9u8 as &Bar); let (c, d): (&Bar, &Bar) = (a, b); let (a, b) = (Box::new(5u8) as Box<Bar>, Box::new(9u8) as Box<Bar>); let (c, d): (&Bar, &Bar) = (&*a, &*b); let (c, d): (&Bar, &Bar) = (&5, &9); }
{}
identifier_body
backup.rs
use std; use std::io::{self, Write, Read}; use std::fs; // pub use decompress::decompress; pub use compress::compress; extern crate byteorder; //needed for lz4 extern crate rustc_serialize; //needed for lz4 extern crate docopt; extern crate seahash; //to hash the blocks extern crate rusqlite; //to save to backup arch...
(block_size: usize) -> Block { Block { serial: String::from(""), hash: String::from(""), data_blob: Vec::with_capacity(block_size), duplicate: String::from("FALSE"), } } } pub fn backup(block_size: usize, compression_type: &String, ...
new
identifier_name
backup.rs
use std; use std::io::{self, Write, Read}; use std::fs; // pub use decompress::decompress; pub use compress::compress; extern crate byteorder; //needed for lz4 extern crate rustc_serialize; //needed for lz4 extern crate docopt; extern crate seahash; //to hash the blocks extern crate rusqlite; //to save to backup arch...
commit_block_to_sqlite(&sqlite_connection, &current_block); if!silent_option { print!("Blocks: {}, Duplicates: {}. Read: {} MiB, Dedup saving: {:.2} MiB", block_counter, duplicate_blocks_found...
random_line_split
backup.rs
use std; use std::io::{self, Write, Read}; use std::fs; // pub use decompress::decompress; pub use compress::compress; extern crate byteorder; //needed for lz4 extern crate rustc_serialize; //needed for lz4 extern crate docopt; extern crate seahash; //to hash the blocks extern crate rusqlite; //to save to backup arch...
fn print_backup_status_update(block_counter: u64, duplicate_blocks_found: u32, block_size: usize) { print!("Blocks processed: {}, Duplicates found: {}, Maximum theoretical dedup saving: {:.2} \ MiB", block_counter, duplicate_blocks_found, (duplicate_blocks_found * bloc...
{ connection.execute("INSERT INTO blocks_table (serial, hash, data, duplicate) VALUES (?1,?2,?3,?4)", &[&block.serial, &block.hash, &block.data_blob, &block.duplicate]) .expect("Error encountered during backup, aborting. Error Code:409"); }
identifier_body
backup.rs
use std; use std::io::{self, Write, Read}; use std::fs; // pub use decompress::decompress; pub use compress::compress; extern crate byteorder; //needed for lz4 extern crate rustc_serialize; //needed for lz4 extern crate docopt; extern crate seahash; //to hash the blocks extern crate rusqlite; //to save to backup arch...
else { current_block.data_blob = block_vector.clone();//data into here } } commit_block_to_sqlite(&sqlite_connection, &current_block); if!silent_option { print!("Blocks: {}, Duplic...
{ current_block.data_blob = compress(&block_vector);//compress data into here }
conditional_block
24.rs
use std::fs::File; use std::io::Read; fn
() -> std::io::Result<String> { let mut file = File::open("24.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } fn list_subsets(numbers: &Vec<usize>, sum: usize, start_index: usize) -> Vec<Vec<usize>> { if sum == 0 { return vec![vec![]]; } el...
get_input
identifier_name
24.rs
use std::fs::File; use std::io::Read; fn get_input() -> std::io::Result<String> { let mut file = File::open("24.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } fn list_subsets(numbers: &Vec<usize>, sum: usize, start_index: usize) -> Vec<Vec<usize>>
.collect() } fn main() { let input = get_input().unwrap(); let numbers = input.lines().filter_map(|line| match line.parse::<usize>() { Ok(x) => Some(x), Err(_) => None }).collect::<Vec<_>>(); let bucket_size = numbers.iter().sum::<usize>() / 3; let buckets = list_subsets(&numbe...
{ if sum == 0 { return vec![vec![]]; } else if start_index >= numbers.len() { return vec![]; } numbers .iter() .enumerate() .skip(start_index) .filter(|&(_, &x)| x <= sum) .flat_map(|(i, &x)| { list_subsets(numbers, sum - x, i + 1) .into_iter() ...
identifier_body
24.rs
use std::fs::File; use std::io::Read; fn get_input() -> std::io::Result<String> { let mut file = File::open("24.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } fn list_subsets(numbers: &Vec<usize>, sum: usize, start_index: usize) -> Vec<Vec<usize>> { ...
}) .collect() } fn main() { let input = get_input().unwrap(); let numbers = input.lines().filter_map(|line| match line.parse::<usize>() { Ok(x) => Some(x), Err(_) => None }).collect::<Vec<_>>(); let bucket_size = numbers.iter().sum::<usize>() / 3; let buckets = list_subsets(...
.map(move |mut subset| { subset.push(x); subset })
random_line_split
problem17.rs
/// /// Computes how many letters there would be if we write out all the numbers /// from 1 to 1000 in British Egnlish. /// fn main() { let zero_to_ten = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3]; let eleven_to_nineteen = [0, 6, 6, 8, 8, 7, 7, 9, 8, 8]; let twenty_to_ninety = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6]; let...
let mut x: uint; let mut remainder: uint; let mut wholes: uint; let mut sum: uint = zero_to_ten[1] + thousand; for i in range(1, 1000) { x = i; if x > 99 { wholes = x / 100u; if x % 100!= 0 { sum += zero_to_ten[wholes] + hundred +...
let and = 3;
random_line_split
problem17.rs
/// /// Computes how many letters there would be if we write out all the numbers /// from 1 to 1000 in British Egnlish. /// fn main()
} else { sum += zero_to_ten[wholes] + hundred; continue; } x -= wholes * 100; } if x >= 10 && x < 20 { remainder = x % 10; match remainder { 1...9 => sum += eleven_to_nineteen[remainder], ...
{ let zero_to_ten = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3]; let eleven_to_nineteen = [0, 6, 6, 8, 8, 7, 7, 9, 8, 8]; let twenty_to_ninety = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6]; let hundred = 7; let thousand = 8; let and = 3; let mut x: uint; let mut remainder: uint; let mut wholes: uint; ...
identifier_body
problem17.rs
/// /// Computes how many letters there would be if we write out all the numbers /// from 1 to 1000 in British Egnlish. /// fn
() { let zero_to_ten = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3]; let eleven_to_nineteen = [0, 6, 6, 8, 8, 7, 7, 9, 8, 8]; let twenty_to_ninety = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6]; let hundred = 7; let thousand = 8; let and = 3; let mut x: uint; let mut remainder: uint; let mut wholes: uint; ...
main
identifier_name
stdio.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 ...
<F>(f: F) where F: FnOnce(&mut Writer) -> IoResult<()> { let mut my_stdout = LOCAL_STDOUT.with(|slot| { slot.borrow_mut().take() }).unwrap_or_else(|| { box stdout() as Box<Writer + Send> }); let result = f(&mut *my_stdout); let mut var = Some(my_stdout); LOCAL_STDOUT.with(|slot| ...
with_task_stdout
identifier_name
stdio.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 ...
/// Creates an unbuffered handle to the stderr of the current process /// /// See notes in `stdout()` for more information. pub fn stderr_raw() -> StdWriter { src(libc::STDERR_FILENO, false, |src| StdWriter { inner: src }) } /// Resets the task-local stdout handle to the specified writer /// /// This will replac...
{ LineBufferedWriter::new(stderr_raw()) }
identifier_body
stdio.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 read_line(&mut self) -> IoResult<String> { self.inner.lock().unwrap().0.read_line() } /// Like `Buffer::read_until`. /// /// The read is performed atomically - concurrent read calls in other /// threads will not interleave with this one. pub fn read_until(&mut self, byte: u8)...
/// The read is performed atomically - concurrent read calls in other /// threads will not interleave with this one.
random_line_split
util.rs
//! Misc. helper functions and utilities used in multiple parts of the application. use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; use std::str::FromStr; use itertools::Itertools; use serde_json; use super::{CompositionTree, CompositionTreeNode, CompositionTreeNodeDefinition, MasterConf}; use c...
{ X, Y, Z, } impl FromStr for Dim { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "X" | "x" => Ok(Dim::X), "Y" | "y" => Ok(Dim::Y), "Z" | "z" => Ok(Dim::Z), _ => Err(format!("Can't convert supplied string to ...
Dim
identifier_name
util.rs
//! Misc. helper functions and utilities used in multiple parts of the application. use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; use std::str::FromStr; use itertools::Itertools; use serde_json; use super::{CompositionTree, CompositionTreeNode, CompositionTreeNodeDefinition, MasterConf}; use c...
pub fn find_setting_by_name(name: &str, settings: &[IrSetting]) -> Result<String, String> { Ok(settings .iter() .find(|&&IrSetting { ref key,.. }| key == name) .ok_or(String::from( "No `moduleType` setting provided to node of type `noiseModule`!", ))?.value .clone()) ...
/// Searches through a slice of `IrSetting`s provided to a node and attempts to find the setting with the supplied name.
random_line_split
main.rs
extern mod extra; use std::io::buffered::BufferedStream; use std::io::net::addrinfo::get_host_addresses; use std::io::net::ip::{IpAddr, SocketAddr}; use std::io::net::tcp::TcpStream; use std::os::args; use extra::json; use extra::json::{Json, ToJson}; use extra::treemap::TreeMap; trait Protocol { fn msg_type(&self...
{ msgType: ~str, data: Json } impl Protocol for Msg { fn msg_type(&self) -> ~str { self.msgType.clone() } fn json_data(&self) -> Json { self.data.clone() } } struct JoinMsg { name: ~str, key: ~str } impl Protocol for JoinMsg { fn msg_type(&self) -> ~str { ~"join" } fn json_data(&self) -> Json { ...
Msg
identifier_name
main.rs
extern mod extra; use std::io::buffered::BufferedStream; use std::io::net::addrinfo::get_host_addresses; use std::io::net::ip::{IpAddr, SocketAddr}; use std::io::net::tcp::TcpStream; use std::os::args; use extra::json; use extra::json::{Json, ToJson}; use extra::treemap::TreeMap; trait Protocol { fn msg_type(&self...
fn main() { match read_config() { None => println("Usage:./run <host> <port> <botname> <botkey>"), Some(config) => start(config) } }
} }
random_line_split
main.rs
extern mod extra; use std::io::buffered::BufferedStream; use std::io::net::addrinfo::get_host_addresses; use std::io::net::ip::{IpAddr, SocketAddr}; use std::io::net::tcp::TcpStream; use std::os::args; use extra::json; use extra::json::{Json, ToJson}; use extra::treemap::TreeMap; trait Protocol { fn msg_type(&self...
_ => None } } fn handle_msg(msg: ~Msg, stream: &mut BufferedStream<TcpStream>) { match msg.msgType { ~"carPositions" => write_msg(&ThrottleMsg { value: 0.5 }, stream), _ => { match msg.msgType { ~"join" => println("Joined"), ~"gameInit" => println("Race init")...
{ let data = json.find(&~"data").unwrap_or(&json::Null); Some(Msg { msgType: msgType.clone(), data: data.clone() }) }
conditional_block
main.rs
extern mod extra; use std::io::buffered::BufferedStream; use std::io::net::addrinfo::get_host_addresses; use std::io::net::ip::{IpAddr, SocketAddr}; use std::io::net::tcp::TcpStream; use std::os::args; use extra::json; use extra::json::{Json, ToJson}; use extra::treemap::TreeMap; trait Protocol { fn msg_type(&self...
fn json_data(&self) -> Json { json::Number(self.value) } } fn write_msg<T: Protocol>(msg: &T, stream: &mut BufferedStream<TcpStream>) { let mut json = TreeMap::new(); json.insert(~"msgType", msg.msg_type().to_json()); json.insert(~"data", msg.json_data()); write_json(&json::Object(~json), stream); } fn wr...
{ ~"throttle" }
identifier_body
viewer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::{ interfaces::{LeftScreen, RightScreen}, tui::{ text_builder::TextBuilder, tui_interface::{TUIInterface, TUIOutput}, }, }; use tui::{ style::{Color, Style}, text::Sp...
} impl<BytecodeViewer: LeftScreen, SourceViewer: RightScreen<BytecodeViewer>> TUIInterface for Viewer<BytecodeViewer, SourceViewer> { const LEFT_TITLE: &'static str = "Bytecode"; const RIGHT_TITLE: &'static str = "Source Code"; fn on_redraw(&mut self, line_number: u16, column_number: u16) -> TUIOutpu...
{ Self { bytecode_text: bytecode_viewer .backing_string() .split('\n') .map(|x| x.to_string()) .collect(), source_viewer, bytecode_viewer, } }
identifier_body
viewer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::{ interfaces::{LeftScreen, RightScreen}, tui::{ text_builder::TextBuilder, tui_interface::{TUIInterface, TUIOutput}, }, }; use tui::{ style::{Color, Style}, text::Sp...
{ None => { let mut builder = TextBuilder::new(); builder.add(self.source_viewer.backing_string(), Style::default()); builder.finish() } Some(info) => { let source_context = self.source_viewer.source_for_code_loc...
.get_source_index_for_line(line_number as usize, column_number as usize)
random_line_split
viewer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::{ interfaces::{LeftScreen, RightScreen}, tui::{ text_builder::TextBuilder, tui_interface::{TUIInterface, TUIOutput}, }, }; use tui::{ style::{Color, Style}, text::Sp...
(&self, line_number: u16) -> u16 { std::cmp::min( line_number, self.bytecode_text.len().checked_sub(1).unwrap() as u16, ) } fn bound_column(&self, line_number: u16, column_number: u16) -> u16 { std::cmp::min( column_number, self.bytecode_t...
bound_line
identifier_name
lib.rs
//! Rustic bindings to [libnotify](https://developer.gnome.org/libnotify/) //! //! ```rust //! extern crate libnotify; //! //! fn main() { //! // Init libnotify //! libnotify::init("myapp").unwrap(); //! // Create a new notification (doesn't show it yet) //! let n = libnotify::Notification::new("Summary...
mod enums; mod functions; mod notification;
random_line_split
eq.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} ); let trait_def = TraitDef { cx: cx, span: span, path: Path::new(~["std", "cmp", "Eq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ md!("eq", cs_eq), md!("ne", cs_ne) ] }; trait_def.expand(mi...
random_line_split
lib.rs
use binary_podman::{BinaryTrait, PodmanBinary}; use buildpack::{ eyre::Report, libcnb::{ build::{BuildContext, BuildResult, BuildResultBuilder}, detect::{DetectContext, DetectResult, DetectResultBuilder}, generic::{GenericMetadata, GenericPlatform}, Buildpack, Error, Result, ...
() -> &'static str { include_str!("../buildpack.toml") } }
toml
identifier_name
lib.rs
use binary_podman::{BinaryTrait, PodmanBinary}; use buildpack::{ eyre::Report, libcnb::{ build::{BuildContext, BuildResult, BuildResultBuilder}, detect::{DetectContext, DetectResult, DetectResultBuilder}, generic::{GenericMetadata, GenericPlatform}, Buildpack, Error, Result, ...
type Platform = GenericPlatform; type Metadata = GenericMetadata; type Error = Report; fn detect(&self, _context: DetectContext<Self>) -> Result<DetectResult, Self::Error> { if Self::any_exist(&["Dockerfile", "Containerfile"]) { DetectResultBuilder::pass().build() } else { ...
}; pub struct DockerfileBuildpack; impl Buildpack for DockerfileBuildpack {
random_line_split
lib.rs
use binary_podman::{BinaryTrait, PodmanBinary}; use buildpack::{ eyre::Report, libcnb::{ build::{BuildContext, BuildResult, BuildResultBuilder}, detect::{DetectContext, DetectResult, DetectResultBuilder}, generic::{GenericMetadata, GenericPlatform}, Buildpack, Error, Result, ...
else { DetectResultBuilder::fail().build() } } fn build(&self, context: BuildContext<Self>) -> Result<BuildResult, Self::Error> { let tag = tag_for_path(&context.app_dir); PodmanBinary {} .ensure_version_sync(">=1") .map_err(Error::BuildpackError)? ...
{ DetectResultBuilder::pass().build() }
conditional_block
lib.rs
use binary_podman::{BinaryTrait, PodmanBinary}; use buildpack::{ eyre::Report, libcnb::{ build::{BuildContext, BuildResult, BuildResultBuilder}, detect::{DetectContext, DetectResult, DetectResultBuilder}, generic::{GenericMetadata, GenericPlatform}, Buildpack, Error, Result, ...
} impl BuildpackTrait for DockerfileBuildpack { fn toml() -> &'static str { include_str!("../buildpack.toml") } }
{ let tag = tag_for_path(&context.app_dir); PodmanBinary {} .ensure_version_sync(">=1") .map_err(Error::BuildpackError)? .run_sync(&["build", "--tag", &tag, "."]) .map_err(Error::BuildpackError)?; BuildResultBuilder::new().build() }
identifier_body
standard.rs
// Copyright 2015-2017 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 lat...
pub use rustc_serialize::json::Json; pub use rustc_serialize::base64::FromBase64; pub use rustc_serialize::hex::{FromHex, FromHexError}; pub use heapsize::HeapSizeOf; pub use itertools::Itertools; pub use parking_lot::{Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
pub use std::ops::*; pub use std::cmp::*; pub use std::sync::Arc; pub use std::collections::*;
random_line_split
processing.rs
chainstate::stacks::index::{ marf::MARF, storage::TrieFileStorage, Error as MARFError, MarfTrieId, }; use core::INITIAL_MINING_BONUS_WINDOW; use util::db::Error as DBError; use crate::types::chainstate::{BurnchainHeaderHash, MARFValue, PoxId, SortitionId}; use crate::types::proof::TrieHash; impl<'a> SortitionHan...
BlockstackOperationType::UserBurnSupport(ref op) => { op.check(burnchain, self).map_err(|e| { warn!( "REJECTED({}) user burn support {} at {},{}: {:?}", op.block_height, &op.txid, op.block_height, op.vtxindex, &e ...
{ match blockstack_op { BlockstackOperationType::LeaderKeyRegister(ref op) => { op.check(burnchain, self).map_err(|e| { warn!( "REJECTED({}) leader key register {} at {},{}: {:?}", op.block_height, &op.txid, op.block...
identifier_body
processing.rs
use chainstate::stacks::index::{ marf::MARF, storage::TrieFileStorage, Error as MARFError, MarfTrieId, }; use core::INITIAL_MINING_BONUS_WINDOW; use util::db::Error as DBError; use crate::types::chainstate::{BurnchainHeaderHash, MARFValue, PoxId, SortitionId}; use crate::types::proof::TrieHash; impl<'a> Sortition...
use chainstate::burn::*; use chainstate::stacks::StacksPublicKey; use core::MICROSTACKS_PER_STACKS; use util::{hash::hex_bytes, vrf::VRFPublicKey}; use crate::types::chainstate::{BlockHeaderHash, StacksAddress, VRFSeed}; use super::*; #[test] fn test_initial_block_reward() { l...
use burnchains::*; use chainstate::burn::db::sortdb::{tests::test_append_snapshot, SortitionDB}; use chainstate::burn::operations::{ leader_block_commit::BURN_BLOCK_MINED_AT_MODULUS, LeaderBlockCommitOp, LeaderKeyRegisterOp, };
random_line_split
processing.rs
chainstate::stacks::index::{ marf::MARF, storage::TrieFileStorage, Error as MARFError, MarfTrieId, }; use core::INITIAL_MINING_BONUS_WINDOW; use util::db::Error as DBError; use crate::types::chainstate::{BurnchainHeaderHash, MARFValue, PoxId, SortitionId}; use crate::types::proof::TrieHash; impl<'a> SortitionHan...
() { let first_burn_hash = BurnchainHeaderHash([0; 32]); let leader_key = LeaderKeyRegisterOp { consensus_hash: ConsensusHash([0x22; 20]), public_key: VRFPublicKey::from_hex( "a366b51292bef4edd64063d9145c617fec373bceb0758e98cd72becd84d54c7a", ) ...
test_initial_block_reward
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/. */ //! Servo, the mighty web browser engine from the future. //! //! This is a very simple library that wires all of ...
(port: u16, constellation: Sender<ConstellationMsg>) { webdriver_server::start_server(port, constellation); } #[cfg(not(feature = "webdriver"))] fn webdriver(_port: u16, _constellation: Sender<ConstellationMsg>) { } use compositing::{CompositorProxy, IOCompositor}; use compositing::compositor_thread::InitialCompo...
webdriver
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/. */ //! Servo, the mighty web browser engine from the future. //! //! This is a very simple library that wires all of ...
pub fn request_title_for_main_frame(&self) { self.compositor.title_for_main_frame() } pub fn setup_logging(&self) { let constellation_chan = self.constellation_chan.clone(); log::set_logger(|max_log_level| { let env_logger = EnvLogger::new(); let con_logger...
{ self.compositor.pinch_zoom_level() }
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/. */ //! Servo, the mighty web browser engine from the future. //! //! This is a very simple library that wires all of ...
use gaol::sandbox::{ChildSandbox, ChildSandboxMethods}; use gfx::font_cache_thread::FontCacheThread; use ipc_channel::ipc::{self, IpcSender}; use log::{Log, LogMetadata, LogRecord}; use net::bluetooth_thread::BluetoothThreadFactory; use net::image_cache_thread::new_image_cache_thread; use net::resource_thread::new_reso...
#[cfg(not(target_os = "windows"))] use constellation::content_process_sandbox_profile; use env_logger::Logger as EnvLogger; #[cfg(not(target_os = "windows"))]
random_line_split
types.rs
use crate::error::*; use std::fmt; use std::num::ParseFloatError; use std::str::FromStr; use std::string::ToString; #[derive(Debug, PartialEq, Clone)] pub struct Atom<T> { pub element: String, pub x: T, pub y: T, pub z: T, } impl<T> Atom<T> { pub fn new(element: &str, x: T, y: T, z: T) -> Self
} impl<T> FromStr for Atom<T> where T: FromStr<Err = ParseFloatError>, { type Err = Error; fn from_str(s: &str) -> Result<Self> { let splitted: Vec<&str> = s.split_whitespace().collect(); if splitted.len()!= 4 { return Err(Error::IllegalState(String::from(""))); } ...
{ Atom { element: element.to_string(), x: x, y: y, z: z, } }
identifier_body
types.rs
use crate::error::*; use std::fmt; use std::num::ParseFloatError; use std::str::FromStr; use std::string::ToString; #[derive(Debug, PartialEq, Clone)] pub struct Atom<T> { pub element: String, pub x: T, pub y: T, pub z: T, } impl<T> Atom<T> { pub fn new(element: &str, x: T, y: T, z: T) -> Self { ...
Ok(Atom::new( splitted[0], splitted[1].parse()?, splitted[2].parse()?, splitted[3].parse()?, )) } } impl<T: fmt::Display> fmt::Display for Atom<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.elem...
{ return Err(Error::IllegalState(String::from(""))); }
conditional_block
types.rs
use crate::error::*; use std::fmt; use std::num::ParseFloatError; use std::str::FromStr; use std::string::ToString; #[derive(Debug, PartialEq, Clone)] pub struct Atom<T> { pub element: String, pub x: T, pub y: T, pub z: T, } impl<T> Atom<T> { pub fn new(element: &str, x: T, y: T, z: T) -> Self { ...
} }
C 10 11 12\n\ O 8.4 12.8 5\n\ H 23 9 11.8" );
random_line_split
types.rs
use crate::error::*; use std::fmt; use std::num::ParseFloatError; use std::str::FromStr; use std::string::ToString; #[derive(Debug, PartialEq, Clone)] pub struct Atom<T> { pub element: String, pub x: T, pub y: T, pub z: T, } impl<T> Atom<T> { pub fn new(element: &str, x: T, y: T, z: T) -> Self { ...
() { let snapshot = Snapshot { comment: "This is a comment".to_string(), atoms: vec![ Atom::new("C", 10.0, 11.0, 12.0), Atom::new("O", 8.4, 12.8, 5.0), Atom::new("H", 23.0, 9.0, 11.8), ], }; assert_eq!(3, snapsho...
test_snapshot
identifier_name
cargo_clean.rs
use std::default::Default; use std::fs; use std::io::prelude::*; use std::path::Path; use core::{Package, PackageSet, Profiles}; use core::source::{Source, SourceMap}; use core::registry::PackageRegistry; use util::{CargoResult, human, ChainError, Config}; use ops::{self, Layout, Context, BuildConfig, Kind, Unit}; pu...
<'a> { pub spec: &'a [String], pub target: Option<&'a str>, pub config: &'a Config, pub release: bool, } /// Cleans the project from build artifacts. pub fn clean(manifest_path: &Path, opts: &CleanOptions) -> CargoResult<()> { let root = try!(Package::for_path(manifest_path, opts.config)); let ...
CleanOptions
identifier_name
cargo_clean.rs
use std::default::Default; use std::fs; use std::io::prelude::*; use std::path::Path; use core::{Package, PackageSet, Profiles}; use core::source::{Source, SourceMap}; use core::registry::PackageRegistry; use util::{CargoResult, human, ChainError, Config}; use ops::{self, Layout, Context, BuildConfig, Kind, Unit}; pu...
{ let m = fs::metadata(path); if m.as_ref().map(|s| s.is_dir()).unwrap_or(false) { try!(fs::remove_dir_all(path).chain_error(|| { human("could not remove build directory") })); } else if m.is_ok() { try!(fs::remove_file(path).chain_error(|| { human("failed to ...
identifier_body
cargo_clean.rs
use std::default::Default; use std::fs; use std::io::prelude::*; use std::path::Path; use core::{Package, PackageSet, Profiles}; use core::source::{Source, SourceMap}; use core::registry::PackageRegistry; use util::{CargoResult, human, ChainError, Config}; use ops::{self, Layout, Context, BuildConfig, Kind, Unit}; pu...
human("failed to remove build artifact") })); } Ok(()) }
})); } else if m.is_ok() { try!(fs::remove_file(path).chain_error(|| {
random_line_split
types.rs
//! Exports Rust counterparts for all the common GLSL types, along with a few marker traits use rasen::prelude::{Dim, TypeName}; use std::ops::{Add, Div, Index, Mul, Rem, Sub}; use crate::{ context::{Container, Context}, value::{IntoValue, Value}, }; pub trait AsTypeName { const TYPE_NAME: &'static Type...
<V>(pub V); impl<V: Vector> AsTypeName for Sampler<V> where <V as Vector>::Scalar: AsTypeName, { const TYPE_NAME: &'static TypeName = &TypeName::Sampler(<<V as Vector>::Scalar as AsTypeName>::TYPE_NAME, Dim::Dim2D); }
Sampler
identifier_name
types.rs
//! Exports Rust counterparts for all the common GLSL types, along with a few marker traits use rasen::prelude::{Dim, TypeName}; use std::ops::{Add, Div, Index, Mul, Rem, Sub}; use crate::{ context::{Container, Context}, value::{IntoValue, Value}, }; pub trait AsTypeName { const TYPE_NAME: &'static Type...
} pub trait Vector3: Vector { fn cross(&self, rhs: &Self) -> Self; } pub trait Matrix { fn inverse(self) -> Self; } include!(concat!(env!("OUT_DIR"), "/types.rs")); #[derive(Copy, Clone, Debug)] pub struct Sampler<V>(pub V); impl<V: Vector> AsTypeName for Sampler<V> where <V as Vector>::Scalar: AsType...
{ self.length_squared().sqrt() }
identifier_body
types.rs
//! Exports Rust counterparts for all the common GLSL types, along with a few marker traits use rasen::prelude::{Dim, TypeName}; use std::ops::{Add, Div, Index, Mul, Rem, Sub}; use crate::{ context::{Container, Context}, value::{IntoValue, Value}, }; pub trait AsTypeName { const TYPE_NAME: &'static Type...
&TypeName::Sampler(<<V as Vector>::Scalar as AsTypeName>::TYPE_NAME, Dim::Dim2D); }
where <V as Vector>::Scalar: AsTypeName, { const TYPE_NAME: &'static TypeName =
random_line_split
test_util.rs
extern crate mazth; #[allow(unused_imports)] use std::ops::Div; #[allow(unused_imports)] use std::cmp::Ordering; use self::mazth::i_comparable::IComparableError; use self::mazth::mat::{Mat3x1, Mat4}; use implement::math::util; #[test] fn
(){ //look_at { let eye : Mat3x1<f32> = Mat3x1 { _val: [5.0,5.0,5.0] }; let center : Mat3x1<f32> = Mat3x1 { _val: [0.0,0.0,0.0] }; let up : Mat3x1<f32> = Mat3x1 { _val: [0.0,1.0,0.0] }; let lookat = util::look_at( eye, center, up ); assert!( lookat.is_equal( &Mat4{ _val...
test_math_util
identifier_name
test_util.rs
extern crate mazth; #[allow(unused_imports)] use std::ops::Div; #[allow(unused_imports)] use std::cmp::Ordering; use self::mazth::i_comparable::IComparableError; use self::mazth::mat::{Mat3x1, Mat4}; use implement::math::util; #[test] fn test_math_util()
let far = 100.0; let persp = util::perspective( fov, aspect, near, far ); println!( "{:?}", persp ); assert!( persp.is_equal( &Mat4{ _val: [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, -...
{ //look_at { let eye : Mat3x1<f32> = Mat3x1 { _val: [5.0,5.0,5.0] }; let center : Mat3x1<f32> = Mat3x1 { _val: [0.0,0.0,0.0] }; let up : Mat3x1<f32> = Mat3x1 { _val: [0.0,1.0,0.0] }; let lookat = util::look_at( eye, center, up ); assert!( lookat.is_equal( &Mat4{ _val: ...
identifier_body
test_util.rs
extern crate mazth; #[allow(unused_imports)] use std::ops::Div; #[allow(unused_imports)] use std::cmp::Ordering; use self::mazth::i_comparable::IComparableError; use self::mazth::mat::{Mat3x1, Mat4}; use implement::math::util; #[test] fn test_math_util(){ //look_at { let eye : Mat3x1<f32> = Mat3x1 {...
0.0, 0.0, 0.0, 1.0 ], _is_row_major: true }, 0.0001f32 ).expect("look_at result unexpected") ); } //perspective transform { let fov = 90.0; let aspect = 1.0; let near = 0.1; let far = 100.0; let persp = util::perspecti...
let lookat = util::look_at( eye, center, up ); assert!( lookat.is_equal( &Mat4{ _val: [ 0.70711, 0.0, -0.70711, 0.0, -0.40825, 0.81650, -0.40825, 0.0, 0.57735, 0.57735, 0.57735, -8.66025,
random_line_split
server.rs
use std::collections::HashMap; use std::cmp::max; use iron::{Iron, Chain}; use router::Router; use persistent::State; use chrono::{Duration, NaiveDate, NaiveDateTime}; use serde_json::builder::ObjectBuilder; use serde_json::Value; use serde; use SERVER_ADDRESS; use errors::*; use load::{SummarizedWeek, Kind, TestRun,...
, Err(err) => { // TODO: Print to stderr println!("An error occurred: {:?}", err); Response::with((status::InternalServerError, err.to_string())) } }; resp.set_mut(Header(AccessControlAllowOrigin::Any)); Ok(resp) } ...
{ let mut resp = Response::with((status::Ok, serde_json::to_string(&json).unwrap())); resp.set_mut(Header(ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![])))); resp }
conditional_block
server.rs
use std::collections::HashMap; use std::cmp::max; use iron::{Iron, Chain}; use router::Router; use persistent::State; use chrono::{Duration, NaiveDate, NaiveDateTime}; use serde_json::builder::ObjectBuilder; use serde_json::Value; use serde; use SERVER_ADDRESS; use errors::*; use load::{SummarizedWeek, Kind, TestRun,...
{ Crate, Phase, } impl serde::Deserialize for GroupBy { fn deserialize<D>(deserializer: &mut D) -> ::std::result::Result<GroupBy, D::Error> where D: serde::de::Deserializer { struct GroupByVisitor; impl serde::de::Visitor for GroupByVisitor { type Value = GroupBy; ...
GroupBy
identifier_name
server.rs
use std::collections::HashMap; use std::cmp::max; use iron::{Iron, Chain}; use router::Router; use persistent::State; use chrono::{Duration, NaiveDate, NaiveDateTime}; use serde_json::builder::ObjectBuilder; use serde_json::Value; use serde; use SERVER_ADDRESS; use errors::*; use load::{SummarizedWeek, Kind, TestRun,...
for krate in benchmark.by_crate.values() { if krate.contains_key("total") { sum += krate["total"]; count += 1; } } if rustc.by_crate["total"].contains_key("total") { sum += 2.0 * rustc.by_crate["...
let mut sum = 0.0; let mut count = 0;
random_line_split
server.rs
use std::collections::HashMap; use std::cmp::max; use iron::{Iron, Chain}; use router::Router; use persistent::State; use chrono::{Duration, NaiveDate, NaiveDateTime}; use serde_json::builder::ObjectBuilder; use serde_json::Value; use serde; use SERVER_ADDRESS; use errors::*; use load::{SummarizedWeek, Kind, TestRun,...
{ let mut router = Router::new(); router.get("/summary", Summary::handler); router.get("/info", Info::handler); router.post("/data", Data::handler); router.post("/get_tabular", Tabular::handler); router.post("/get", Days::handler); router.post("/stats", Stats::handler); let mut chain =...
identifier_body
tests.rs
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time::Duration; use crate::{Process, ProcessResultMetadata}; use bazel_protos::gen::build::bazel::...
restored_action_metadata, ExecutedActionMetadata { worker_start_timestamp: Some(Timestamp { seconds: 0, nanos: 0, }), worker_completed_timestamp: Some(Timestamp { seconds: 20, nanos: 30, }), ..ExecutedActionMetadata::default() } ); // The rel...
random_line_split
tests.rs
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time::Duration; use crate::{Process, ProcessResultMetadata}; use bazel_protos::gen::build::bazel::...
// Process should derive a PartialEq and Hash that ignores the description assert_eq!(a, b); assert_eq!(hash(&a), hash(&b)); //..but not other fields. assert_ne!(a, c); assert_ne!(hash(&a), hash(&c)); // Absence of timeout is included in hash. assert_ne!(a, d); assert_ne!(hash(&a), hash(&d)); } #...
{ // TODO: Tests like these would be cleaner with the builder pattern for the rust-side Process API. let process_generator = |description: String, timeout: Option<Duration>| { let mut p = Process::new(vec![]); p.description = description; p.timeout = timeout; p }; fn hash<Hashable: Hash>(hasha...
identifier_body
tests.rs
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time::Duration; use crate::{Process, ProcessResultMetadata}; use bazel_protos::gen::build::bazel::...
() { let metadata = ProcessResultMetadata::new(Some(concrete_time::Duration::new(5, 150))); let time_saved = metadata.time_saved_from_cache(Duration::new(1, 100)); assert_eq!(time_saved, Some(Duration::new(4, 50))); // If the cache lookup took more time than the process, we return 0. let metadata = ProcessRe...
process_result_metadata_time_saved_from_cache
identifier_name
mod.rs
use std::sync::atomic::AtomicBool; use std::ptr; use libc; use {CreationError, Event}; use BuilderAttribs; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; use winapi; mod event; mod gl; mod init; mod monitor; /// pub struct HeadlessContext(Window); impl HeadlessContext { /// ...
{ /// Main handle for the window. window: winapi::HWND, /// This represents a "draw context" for the surface of the window. hdc: winapi::HDC, /// OpenGL context. context: winapi::HGLRC, /// Binded to `opengl32.dll`. /// /// `wglGetProcAddress` returns null for GL 1.1 functions be...
Window
identifier_name
mod.rs
use std::sync::atomic::AtomicBool; use std::ptr; use libc; use {CreationError, Event}; use BuilderAttribs; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; use winapi; mod event; mod gl; mod init; mod monitor; /// pub struct HeadlessContext(Window);
impl HeadlessContext { /// See the docs in the crate root file. pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> { let BuilderAttribs { dimensions, gl_version, gl_debug,.. } = builder; init::new_window(dimensions, "".to_string(), None, gl_version, gl_debug, false, tr...
random_line_split
mod.rs
use std::sync::atomic::AtomicBool; use std::ptr; use libc; use {CreationError, Event}; use BuilderAttribs; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; use winapi; mod event; mod gl; mod init; mod monitor; /// pub struct HeadlessContext(Window); impl HeadlessContext { /// ...
/// See the docs in the crate root file. pub fn get_outer_size(&self) -> Option<(uint, uint)> { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { winapi::GetWindowRect(self.window, &mut rect) } == 0 { return None } Som...
{ use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { winapi::GetClientRect(self.window, &mut rect) } == 0 { return None } Some(( (rect.right - rect.left) as uint, (rect.bottom - rect.top) as uint )...
identifier_body
skills_scene.rs
use std::path::Path; use uorustlibs::skills::Skills; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self, Text}; use ggez::{Context, GameResult}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; pub struct SkillsScene { pages: Vec<Text>, exiting: bool, } impl<'a> Sk...
}
{ match keycode { KeyCode::Escape => self.exiting = true, _ => (), } }
identifier_body
skills_scene.rs
use std::path::Path; use uorustlibs::skills::Skills; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self, Text}; use ggez::{Context, GameResult}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; pub struct SkillsScene { pages: Vec<Text>, exiting: bool, } impl<'a> Sk...
; format!("{} {}", glyph, skill.name) }) .collect(); Text::new(skills.join("\n")) }) .collect(); items } Err(error) => { ...
{ "-" }
conditional_block
skills_scene.rs
use std::path::Path; use uorustlibs::skills::Skills; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self, Text}; use ggez::{Context, GameResult}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; pub struct SkillsScene { pages: Vec<Text>, exiting: bool, } impl<'a> Sk...
fn update( &mut self, _ctx: &mut Context, _engine_data: &mut (), ) -> GameResult<Option<SceneChangeEvent<SceneName>>> { if self.exiting { Ok(Some(SceneChangeEvent::PopScene)) } else { Ok(None) } } fn key_down_event( &mut se...
Ok(()) }
random_line_split
skills_scene.rs
use std::path::Path; use uorustlibs::skills::Skills; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self, Text}; use ggez::{Context, GameResult}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; pub struct
{ pages: Vec<Text>, exiting: bool, } impl<'a> SkillsScene { pub fn new() -> BoxedScene<'a, SceneName, ()> { let skills = Skills::new( &Path::new("./assets/skills.idx"), &Path::new("./assets/skills.mul"), ); let text = match skills { Ok(skills) =>...
SkillsScene
identifier_name
and.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/. // //! AND implementation. //! //! Will be automatically included when including `filter::Filter`, so importing th...
<T, U>(T, U); impl<T, U> FailableAnd<T, U> { pub fn new(a: T, b: U) -> FailableAnd<T, U> { FailableAnd(a, b) } } impl<N, T, U, E> FailableFilter<N> for FailableAnd<T, U> where T: FailableFilter<N, Error = E>, U: FailableFilter<N, Error = E> { type Error = E; fn filter(&self, e...
FailableAnd
identifier_name
and.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/. // //! AND implementation. //! //! Will be automatically included when including `filter::Filter`, so importing th...
}
{ Ok(self.0.filter(e)? && self.1.filter(e)?) }
identifier_body
and.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/. // //! AND implementation. //! //! Will be automatically included when including `filter::Filter`, so importing th...
}
}
random_line_split
thread-local-in-ctfe.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 ...
() -> u32 { A //~^ ERROR thread-local statics cannot be accessed at compile-time } fn main() {}
f
identifier_name
thread-local-in-ctfe.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 ...
#[thread_local] static A: u32 = 1; static B: u32 = A; //~^ ERROR thread-local statics cannot be accessed at compile-time static C: &u32 = &A; //~^ ERROR thread-local statics cannot be accessed at compile-time const D: u32 = A; //~^ ERROR thread-local statics cannot be accessed at compile-time const E: &u32 = &A; /...
#![feature(const_fn, thread_local)]
random_line_split
thread-local-in-ctfe.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 ...
{}
identifier_body
lib.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...
pub fn main_args(args: &[String]) -> int { let matches = match getopts::getopts(args.tail(), opts().as_slice()) { Ok(m) => m, Err(err) => { println!("{}", err); return 1; } }; if matches.opt_present("h") || matches.opt_present("help") { usage(args[0]...
{ println!("{}", getopts::usage(format!("{} [options] <input>", argv0).as_slice(), opts().as_slice())); }
identifier_body
lib.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...
}; info!("going to format"); let started = time::precise_time_ns(); match matches.opt_str("w").as_ref().map(|s| s.as_slice()) { Some("html") | None => { match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc"))) { Ok(()) => {} ...
{ println!("input error: {}", s); return 1; }
conditional_block
lib.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...
(args: &[String]) -> int { let matches = match getopts::getopts(args.tail(), opts().as_slice()) { Ok(m) => m, Err(err) => { println!("{}", err); return 1; } }; if matches.opt_present("h") || matches.opt_present("help") { usage(args[0].as_slice()); ...
main_args
identifier_name
lib.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...
/// and files and then generates the necessary rustdoc output for formatting. fn acquire_input(input: &str, matches: &getopts::Matches) -> Result<Output, String> { match matches.opt_str("r").as_ref().map(|s| s.as_slice()) { Some("rust") => Ok(rust_input(input, matches)), Some("json"...
/// Looks inside the command line arguments to extract the relevant input format
random_line_split
set_cover_test.rs
mod bit_vector; mod set_cover; use set_cover::minimum_set_cover; #[test] fn test_disjoint()
#[test] fn test_one() { test( vec![ vec![0, 1, 2], vec![0], vec![1], vec![2], ], vec![0], ); } #[test] fn test_two() { test( vec![ vec![0, 1], vec![1, 2], vec![2, 3], ], vec...
{ test( vec![ vec![0], vec![1], vec![2], ], vec![0, 1, 2], ); }
identifier_body