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 |
|---|---|---|---|---|
lib.rs | #![feature(plugin)]
#![plugin(interpolate_idents)]
#[macro_use]
extern crate apache2;
use apache2::{Request, Status, server_banner, server_description, server_built, show_mpm,
apr_version_string, apu_version_string, Cookie, time_now};
apache2_module!(info_rs, b"mod_info_rs\0");
fn unwrap_str<'a>(wrapped: Option<... | try!(r.write(format!("<p>Server: {}:{} (via {})</p>", server_name, server_port, local_ip)));
let description = unwrap_str(server_description());
let banner = unwrap_str(server_banner());
try!(r.write(format!("<p>Server Description/Banner: {} / {}</p>", description, banner)));
let mmp = unwrap_str(show_... | {
if get!(r.handler()) != "server-info-rs" {
return Ok(Status::DECLINED)
}
r.set_content_type("text/html");
r.set_last_modified(time_now());
try!(r.write("<!doctype html><html><head><meta charset=\"utf-8\"><title>Apache Info</title></head><body>"));
try!(r.write("<h1>Apache Server Informatio... | identifier_body |
rom_bls461_64.rs | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this f... | pub const HASH_TYPE: usize = 32;
pub const AESKEY: usize = 16; | pub const SEXTIC_TWIST: SexticTwist = SexticTwist::M_TYPE;
pub const ATE_BITS: usize = 78;
pub const SIGN_OF_X: SignOfX = SignOfX::NEGATIVEX; | random_line_split |
node.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | fn clone(&self) -> Node {
match *self {
Node::Empty => Node::Empty,
Node::Leaf(ref k, ref v) => Node::Leaf(k.clone(), v.clone()),
Node::Extension(ref k, ref v) => Node::Extension(k.clone(), v.clone()),
Node::Branch(ref k, ref v) => {
let mut branch = [NodeKey::new(), NodeKey::new(), NodeKey::new(), N... | Branch([NodeKey; 16], Option<DBValue>)
}
impl Clone for Node { | random_line_split |
node.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | (node_rlp: &[u8]) -> Node {
let r = Rlp::new(node_rlp);
match r.prototype() {
// either leaf or extension - decode first item with NibbleSlice::???
// and use is_leaf return to figure out which.
// if leaf, second item is a value (is_data())
// if extension, second item is a node (either SHA3 to be look... | decoded | identifier_name |
node.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | Some(ref n) => { stream.append(&&**n); },
None => { stream.append_empty_data(); },
}
stream.out()
},
Node::Empty => {
let mut stream = RlpStream::new();
stream.append_empty_data();
stream.out()
}
}
}
/// Encode the node, adding it to `journal` if necessary and return the RLP... | {
match *self {
Node::Leaf(ref slice, ref value) => {
let mut stream = RlpStream::new_list(2);
stream.append(&&**slice);
stream.append(&&**value);
stream.out()
},
Node::Extension(ref slice, ref raw_rlp) => {
let mut stream = RlpStream::new_list(2);
stream.append(&&**slice);
stream... | identifier_body |
errors.rs | //! # Errors
//!
//! Rust doesn't have exceptions, so errors are expressed as a variant on
//! the standard library [`Result`]() type that implements the [`Error`]()
//! trait.
//! The problem with the `Error` trait is that it can be cumbersome to implement
//! manually, and leads to a lot of conversion boiletplate.
//... | (err: Error) -> IronError {
match err {
e @ Error { kind: ErrorKind::PersonNotFound, state: _ } => IronError::new(e, Status::NotFound),
e => IronError::new(e, Status::InternalServerError),
}
}
}
| from | identifier_name |
errors.rs | //! # Errors
//!
//! Rust doesn't have exceptions, so errors are expressed as a variant on
//! the standard library [`Result`]() type that implements the [`Error`]()
//! trait.
//! The problem with the `Error` trait is that it can be cumbersome to implement
//! manually, and leads to a lot of conversion boiletplate.
//... | error_chain! {
foreign_links {
redis::RedisError, RedisError;
serde_json::Error, JsonError;
}
errors {
NotAnId {
description("the given value isn't a valid id")
display("the given value isn't a valid id")
}
PersonNotFound {
description... | use redis;
use serde_json;
| random_line_split |
errors.rs | //! # Errors
//!
//! Rust doesn't have exceptions, so errors are expressed as a variant on
//! the standard library [`Result`]() type that implements the [`Error`]()
//! trait.
//! The problem with the `Error` trait is that it can be cumbersome to implement
//! manually, and leads to a lot of conversion boiletplate.
//... |
}
| {
match err {
e @ Error { kind: ErrorKind::PersonNotFound, state: _ } => IronError::new(e, Status::NotFound),
e => IronError::new(e, Status::InternalServerError),
}
} | identifier_body |
i686_unknown_linux_gnu.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> Target {
let mut base = super::linux_base::opts();
base.pre_link_args.push("-m32".to_string());
Target {
data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(),
llvm_target: "i686-unknown-linux-gnu".to_string(),
target_endian: "little".to_string(),
... | target | identifier_name |
i686_unknown_linux_gnu.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | target_os: "linux".to_string(),
options: base,
}
} | target_pointer_width: "32".to_string(),
arch: "x86".to_string(), | random_line_split |
i686_unknown_linux_gnu.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let mut base = super::linux_base::opts();
base.pre_link_args.push("-m32".to_string());
Target {
data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(),
llvm_target: "i686-unknown-linux-gnu".to_string(),
target_endian: "little".to_string(),
target_point... | identifier_body | |
day07.rs | use std::io::Read;
use itertools::Itertools;
use crate::common::ordered;
fn read_input(input: &mut dyn Read) -> Vec<usize> {
let mut buf = String::new();
input.read_to_string(&mut buf).unwrap();
let mut crabs: Vec<usize> = buf
.trim_end()
.split(',')
.map(|s| s.parse().unwrap())
... | else {
min = mid1 + 1
}
}
// Ternary search isn't effective at such small intervals so we iterate the remaining part
(min..=max).map(callback).min().unwrap()
}
pub fn part2(input: &mut dyn Read) -> String {
let groups: Vec<_> = read_input(input).into_iter().dedup_with_count().coll... | {
max = mid2 - 1
} | conditional_block |
day07.rs | use std::io::Read;
use itertools::Itertools;
use crate::common::ordered;
fn read_input(input: &mut dyn Read) -> Vec<usize> {
let mut buf = String::new();
input.read_to_string(&mut buf).unwrap();
let mut crabs: Vec<usize> = buf
.trim_end()
.split(',')
.map(|s| s.parse().unwrap())
... |
#[cfg(test)]
mod tests {
use crate::test_implementation;
use super::*;
const SAMPLE: &[u8] = &*b"16,1,2,0,4,2,7,1,2,14";
#[test]
fn sample_part1() {
test_implementation(part1, SAMPLE, 37);
}
#[test]
fn sample_part2() {
test_implementation(part2, SAMPLE, 168);
}
... | {
let groups: Vec<_> = read_input(input).into_iter().dedup_with_count().collect();
let min = groups.first().unwrap().1;
let max = groups.last().unwrap().1;
ternary_search(min, max, |pos| cost_at2(pos, &groups)).to_string()
} | identifier_body |
day07.rs | use std::io::Read;
use itertools::Itertools;
use crate::common::ordered;
fn read_input(input: &mut dyn Read) -> Vec<usize> {
let mut buf = String::new();
input.read_to_string(&mut buf).unwrap();
let mut crabs: Vec<usize> = buf
.trim_end()
.split(',')
.map(|s| s.parse().unwrap())
... | (end: usize) -> usize {
(end * (1 + end)) / 2
}
fn cost_at2(pos: usize, groups: &[(usize, usize)]) -> usize {
groups
.iter()
.map(|&(number, new_pos)| {
let (first, last) = ordered(pos, new_pos);
number * sum_until(last - first)
})
.sum()
}
fn ternary_sear... | sum_until | identifier_name |
day07.rs | use std::io::Read;
use itertools::Itertools;
use crate::common::ordered;
fn read_input(input: &mut dyn Read) -> Vec<usize> {
let mut buf = String::new();
input.read_to_string(&mut buf).unwrap();
let mut crabs: Vec<usize> = buf
.trim_end()
.split(',')
.map(|s| s.parse().unwrap())
... | .sum()
}
pub fn part1(input: &mut dyn Read) -> String {
let crabs = read_input(input);
let median = crabs[crabs.len() / 2 + (crabs.len() % 2)];
cost_at(median, &crabs).to_string()
}
pub fn sum_until(end: usize) -> usize {
(end * (1 + end)) / 2
}
fn cost_at2(pos: usize, groups: &[(usize, usiz... | }) | random_line_split |
ppm_writer.rs | extern crate ppm;
use std::io;
use ppm::PPMWriter;
fn main() {
let width = 200;
let height = 100;
let image_data = generate_image_data(width, height);
let stdout = io::stdout();
let mut out = stdout.lock();
let mut writer = PPMWriter::new(&mut out);
writer.write(&image_data[..], width, ... | (width: usize, height: usize) -> Vec<f32> {
let mut image_data = Vec::new();
for y in 0..height {
for x in 0..width {
let r = x as f32 / width as f32;
let g = y as f32 / height as f32;
let b = 0.2;
image_data.push(r);
image_data.push(g);
... | generate_image_data | identifier_name |
ppm_writer.rs | extern crate ppm;
use std::io;
use ppm::PPMWriter;
fn main() {
let width = 200;
let height = 100;
let image_data = generate_image_data(width, height);
let stdout = io::stdout();
let mut out = stdout.lock();
let mut writer = PPMWriter::new(&mut out);
writer.write(&image_data[..], width, ... | }
image_data
} |
image_data.push(r);
image_data.push(g);
image_data.push(b);
} | random_line_split |
ppm_writer.rs | extern crate ppm;
use std::io;
use ppm::PPMWriter;
fn main() {
let width = 200;
let height = 100;
let image_data = generate_image_data(width, height);
let stdout = io::stdout();
let mut out = stdout.lock();
let mut writer = PPMWriter::new(&mut out);
writer.write(&image_data[..], width, ... | {
let mut image_data = Vec::new();
for y in 0..height {
for x in 0..width {
let r = x as f32 / width as f32;
let g = y as f32 / height as f32;
let b = 0.2;
image_data.push(r);
image_data.push(g);
image_data.push(b);
}
... | identifier_body | |
csssupportsrule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser;
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindings::codegen::B... |
}
impl SpecificCSSRule for CSSSupportsRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::SUPPORTS_RULE
}
fn get_css(&self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
self.suppor... | {
let mut input = Parser::new(&text);
let cond = SupportsCondition::parse(&mut input);
if let Ok(cond) = cond {
let global = self.global();
let win = global.as_window();
let url = win.Document().url();
let quirks_mode = win.Document().quirks_mode()... | identifier_body |
csssupportsrule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser;
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindings::codegen::B... |
}
}
impl SpecificCSSRule for CSSSupportsRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::SUPPORTS_RULE
}
fn get_css(&self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
self.... | {
let global = self.global();
let win = global.as_window();
let url = win.Document().url();
let quirks_mode = win.Document().quirks_mode();
let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports),
... | conditional_block |
csssupportsrule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser;
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindings::codegen::B... | (&self, text: DOMString) {
let mut input = Parser::new(&text);
let cond = SupportsCondition::parse(&mut input);
if let Ok(cond) = cond {
let global = self.global();
let win = global.as_window();
let url = win.Document().url();
let quirks_mode = win... | set_condition_text | identifier_name |
csssupportsrule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser;
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindings::codegen::B... | use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::cssconditionrule::CSSConditionRule;
use dom::cssrule::SpecificCSSRule;
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use dom_struct::dom_struct;
use style::parser::{LengthParsingMode, ParserConte... | use dom::bindings::js::Root; | random_line_split |
tests.rs | use scanner::tokenize;
use scanner::tokens::Token;
use scanner::tokens::Token::*;
|
assert_eq!(expected, actual);
}
#[test]
fn scan_base_command() {
let expected: Vec<Token> = vec![
Base,
Ident("name".to_string()),
Lparen,
Ident("A50".to_string()),
Rparen,
Dot];
let actual = tokenize("base name (A50).");
assert_eq!(expected, actua... | #[test]
fn scan_terminals() {
let expected = vec![Lparen, Rparen, Dot];
let actual = tokenize("()."); | random_line_split |
tests.rs | use scanner::tokenize;
use scanner::tokens::Token;
use scanner::tokens::Token::*;
#[test]
fn scan_terminals() {
let expected = vec![Lparen, Rparen, Dot];
let actual = tokenize("().");
assert_eq!(expected, actual);
}
#[test]
fn | () {
let expected: Vec<Token> = vec![
Base,
Ident("name".to_string()),
Lparen,
Ident("A50".to_string()),
Rparen,
Dot];
let actual = tokenize("base name (A50).");
assert_eq!(expected, actual);
}
#[test]
fn scan_end_command() {
let expected = vec![End... | scan_base_command | identifier_name |
tests.rs | use scanner::tokenize;
use scanner::tokens::Token;
use scanner::tokens::Token::*;
#[test]
fn scan_terminals() |
#[test]
fn scan_base_command() {
let expected: Vec<Token> = vec![
Base,
Ident("name".to_string()),
Lparen,
Ident("A50".to_string()),
Rparen,
Dot];
let actual = tokenize("base name (A50).");
assert_eq!(expected, actual);
}
#[test]
fn scan_end_command()... | {
let expected = vec![Lparen, Rparen, Dot];
let actual = tokenize("().");
assert_eq!(expected, actual);
} | identifier_body |
input.rs | use std::collections::HashMap;
use std::time::Instant;
use glium::glutin::{
dpi::PhysicalPosition,
event::{ElementState, Event, KeyboardInput, MouseButton, VirtualKeyCode, WindowEvent},
};
pub struct InputState {
/// Position of the mouse
pub mouse_pos: (f64, f64),
/// Previous position of the mou... | (&self) -> (f64, f64) {
let (px, py) = self.prev_mouse_pos;
let (x, y) = self.mouse_pos;
(x - px, y - py)
}
/// Update the state with an event
pub fn update(&mut self, event: &Event<()>) {
if let Event::WindowEvent { ref event,.. } = *event {
match *event {
... | d_mouse | identifier_name |
input.rs | use std::collections::HashMap;
use std::time::Instant;
use glium::glutin::{
dpi::PhysicalPosition,
event::{ElementState, Event, KeyboardInput, MouseButton, VirtualKeyCode, WindowEvent},
};
pub struct InputState {
/// Position of the mouse
pub mouse_pos: (f64, f64),
/// Previous position of the mou... | WindowEvent::CursorMoved {
position: PhysicalPosition { x, y },
..
} => {
self.mouse_pos = (x, y);
}
WindowEvent::MouseInput {
state: ElementState::Pressed,
... | /// Update the state with an event
pub fn update(&mut self, event: &Event<()>) {
if let Event::WindowEvent { ref event, .. } = *event {
match *event { | random_line_split |
usbscan.rs | // Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... | usLanguageId: USHORT,
}}
pub type PDEVICE_DESCRIPTOR = *mut DEVICE_DESCRIPTOR;
//132
pub const FILE_DEVICE_USB_SCAN: ULONG = 0x8000;
pub const IOCTL_INDEX: ULONG = 0x0800;
//143
pub const IOCTL_GET_USB_DESCRIPTOR: ULONG
= CTL_CODE!(FILE_DEVICE_USB_SCAN, IOCTL_INDEX + 8, METHOD_BUFFERED, FILE_ANY_ACCESS); | STRUCT!{struct DEVICE_DESCRIPTOR {
usVendorId: USHORT,
usProductId: USHORT,
usBcdDevice: USHORT, | random_line_split |
mod.rs | use malachite_base::num::logic::traits::{BitConvertible, BitIterable, SignificantBits};
use malachite_nz::natural::Natural;
use malachite_nz::platform::Limb;
use std::iter::repeat;
pub fn natural_op_bits(bit_fn: &dyn Fn(bool, bool) -> bool, x: &Natural, y: &Natural) -> Natural {
let bit_zip: Box<dyn Iterator<Item ... | else {
Box::new(x.limbs().chain(repeat(0)).zip(y.limbs()))
};
let mut and_limbs = Vec::new();
for (x, y) in limb_zip {
and_limbs.push(limb_fn(x, y));
}
Natural::from_owned_limbs_asc(and_limbs)
}
pub mod and;
pub mod count_ones;
pub mod from_bits;
pub mod get_bit;
pub mod hamming_di... | {
Box::new(x.limbs().zip(y.limbs().chain(repeat(0))))
} | conditional_block |
mod.rs | use malachite_base::num::logic::traits::{BitConvertible, BitIterable, SignificantBits};
use malachite_nz::natural::Natural;
use malachite_nz::platform::Limb;
use std::iter::repeat;
pub fn natural_op_bits(bit_fn: &dyn Fn(bool, bool) -> bool, x: &Natural, y: &Natural) -> Natural {
let bit_zip: Box<dyn Iterator<Item ... |
pub mod and;
pub mod count_ones;
pub mod from_bits;
pub mod get_bit;
pub mod hamming_distance;
pub mod index_of_next_false_bit;
pub mod index_of_next_true_bit;
pub mod or;
pub mod set_bit;
pub mod to_bits;
pub mod trailing_zeros;
pub mod xor;
| {
let limb_zip: Box<dyn Iterator<Item = (Limb, Limb)>> = if x.limb_count() >= y.limb_count() {
Box::new(x.limbs().zip(y.limbs().chain(repeat(0))))
} else {
Box::new(x.limbs().chain(repeat(0)).zip(y.limbs()))
};
let mut and_limbs = Vec::new();
for (x, y) in limb_zip {
and_limb... | identifier_body |
mod.rs | use malachite_base::num::logic::traits::{BitConvertible, BitIterable, SignificantBits};
use malachite_nz::natural::Natural;
use malachite_nz::platform::Limb;
use std::iter::repeat;
pub fn natural_op_bits(bit_fn: &dyn Fn(bool, bool) -> bool, x: &Natural, y: &Natural) -> Natural {
let bit_zip: Box<dyn Iterator<Item ... | (limb_fn: &dyn Fn(Limb, Limb) -> Limb, x: &Natural, y: &Natural) -> Natural {
let limb_zip: Box<dyn Iterator<Item = (Limb, Limb)>> = if x.limb_count() >= y.limb_count() {
Box::new(x.limbs().zip(y.limbs().chain(repeat(0))))
} else {
Box::new(x.limbs().chain(repeat(0)).zip(y.limbs()))
};
l... | natural_op_limbs | identifier_name |
mod.rs | use malachite_base::num::logic::traits::{BitConvertible, BitIterable, SignificantBits};
use malachite_nz::natural::Natural;
use malachite_nz::platform::Limb;
use std::iter::repeat;
pub fn natural_op_bits(bit_fn: &dyn Fn(bool, bool) -> bool, x: &Natural, y: &Natural) -> Natural {
let bit_zip: Box<dyn Iterator<Item ... | and_limbs.push(limb_fn(x, y));
}
Natural::from_owned_limbs_asc(and_limbs)
}
pub mod and;
pub mod count_ones;
pub mod from_bits;
pub mod get_bit;
pub mod hamming_distance;
pub mod index_of_next_false_bit;
pub mod index_of_next_true_bit;
pub mod or;
pub mod set_bit;
pub mod to_bits;
pub mod trailing_zero... | for (x, y) in limb_zip { | random_line_split |
directional.rs | use std::f32;
use color::Color;
use intersection::Intersection;
use material::Material;
use math::{Vector3, EPSILON};
use ray::Ray;
use super::Light;
pub struct Directional {
pub direction: Vector3,
inverse_direction: Vector3,
pub color: Color,
intensity: f32,
diffuse: bool,
specular: bool,
... | (
&self,
intersection: &Intersection,
material: &Material,
distance_to_light: f32,
) -> Option<Color> {
if!self.diffuse {
return None;
}
let dot = self.inverse_direction.dot(&intersection.normal);
if dot > 0.0 {
Some(
... | diffuse_color | identifier_name |
directional.rs | use std::f32;
use color::Color;
use intersection::Intersection;
use material::Material;
use math::{Vector3, EPSILON};
use ray::Ray;
use super::Light;
pub struct Directional {
pub direction: Vector3,
inverse_direction: Vector3,
pub color: Color,
intensity: f32,
diffuse: bool,
specular: bool,
... |
let dot = self.inverse_direction.dot(&intersection.normal);
if dot > 0.0 {
Some(
(self.color * material.diffuse_color(intersection.texture_coord))
* dot
* self.intensity(distance_to_light),
)
} else {
... | {
return None;
} | conditional_block |
directional.rs | use std::f32;
use color::Color;
use intersection::Intersection;
use material::Material;
use math::{Vector3, EPSILON};
use ray::Ray;
use super::Light;
pub struct Directional {
pub direction: Vector3,
inverse_direction: Vector3,
pub color: Color,
intensity: f32,
diffuse: bool,
specular: bool,
... |
}
| {
if !self.specular {
return None;
}
let dot = ray
.direction
.dot(&self.inverse_direction.reflect(&intersection.normal));
if dot > 0.0 {
let spec = dot.powf(material.specular_exponent);
Some(
(self.color * mat... | identifier_body |
directional.rs | use std::f32;
use color::Color;
use intersection::Intersection;
use material::Material;
use math::{Vector3, EPSILON};
use ray::Ray;
use super::Light;
pub struct Directional {
pub direction: Vector3,
inverse_direction: Vector3,
pub color: Color, | }
impl Directional {
pub fn new(
direction: Vector3,
color: Color,
intensity: f32,
diffuse: bool,
specular: bool,
) -> Self {
let normalized_direction = direction.normalize();
Self {
direction: normalized_direction,
inverse_directi... | intensity: f32,
diffuse: bool,
specular: bool, | random_line_split |
mod.rs | pub mod interval_tree;
pub mod plain_tree;
pub mod interval;
use base::{Node, TreeDeref, TreeRepr};
pub trait AppliedTree<N: Node>: TreeDeref<N> + Sized {
/// Constructs a new AppliedTree
fn new(items: Vec<(N::K, N::V)>) -> Self {
Self::with_repr(TreeRepr::new(items))
}
/// Constructs a new ... | (nodes: Vec<Option<N>>) -> Self {
Self::with_repr(TreeRepr::with_nodes(nodes))
}
fn with_repr(repr: TreeRepr<N>) -> Self;
unsafe fn with_shape(items: Vec<Option<(N::K, N::V)>>) -> Self;
}
| with_nodes | identifier_name |
mod.rs | pub mod interval_tree;
pub mod plain_tree;
pub mod interval;
use base::{Node, TreeDeref, TreeRepr};
pub trait AppliedTree<N: Node>: TreeDeref<N> + Sized {
/// Constructs a new AppliedTree
fn new(items: Vec<(N::K, N::V)>) -> Self {
Self::with_repr(TreeRepr::new(items))
}
/// Constructs a new ... | fn with_repr(repr: TreeRepr<N>) -> Self;
unsafe fn with_shape(items: Vec<Option<(N::K, N::V)>>) -> Self;
} | random_line_split | |
mod.rs | pub mod interval_tree;
pub mod plain_tree;
pub mod interval;
use base::{Node, TreeDeref, TreeRepr};
pub trait AppliedTree<N: Node>: TreeDeref<N> + Sized {
/// Constructs a new AppliedTree
fn new(items: Vec<(N::K, N::V)>) -> Self {
Self::with_repr(TreeRepr::new(items))
}
/// Constructs a new ... |
fn with_nodes(nodes: Vec<Option<N>>) -> Self {
Self::with_repr(TreeRepr::with_nodes(nodes))
}
fn with_repr(repr: TreeRepr<N>) -> Self;
unsafe fn with_shape(items: Vec<Option<(N::K, N::V)>>) -> Self;
}
| {
Self::with_repr(TreeRepr::with_sorted(sorted))
} | identifier_body |
mod.rs | We then try to compile a program for arm-linux-androideabi
// 3. The compiler has a host of linux and a target of android, so it loads
// macros from the *linux* libstd.
// 4. The macro generates a #[thread_local] field, but the android libstd does
// not use #[thread_local]
// 5. Compile error about structs wit... | drop | identifier_name | |
mod.rs | = "rust1", since = "1.0.0")]
pub struct Key<T> {
// The key itself may be tagged with #[thread_local], and this `Key` is
// stored as a `static`, and it's not valid for a static to reference the
// address of another thread_local static. For this reason we kinda wonkily
// work around this by generatin... | #[cfg_attr(all(any(target_os = "macos", target_os = "linux"),
not(target_arch = "aarch64")),
thread_local)]
pub static $name: ::std::thread_local::__impl::KeyInner<$t> =
__thread_local_inner!($init, $t);
);
($init:expr, $t:ty) => ({
#... | );
(pub static $name:ident: $t:ty = $init:expr) => ( | random_line_split |
mod.rs | "rust1", since = "1.0.0")]
pub struct Key<T> {
// The key itself may be tagged with #[thread_local], and this `Key` is
// stored as a `static`, and it's not valid for a static to reference the
// address of another thread_local static. For this reason we kinda wonkily
// work around this by generating ... |
None => State::Destroyed,
}
}
}
/// Deprecated
#[unstable(feature = "std_misc")]
#[deprecated(since = "1.0.0",
reason = "function renamed to state() and returns more info")]
pub fn destroyed(&'static self) -> bool { self.state() == State::Destro... | {
match *cell.get() {
Some(..) => State::Valid,
None => State::Uninitialized,
}
} | conditional_block |
main.rs | _slice_ext)]
#![feature(fnbox)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(unboxed_closures)]
#![feature(unsafe_no_drop_flag)]
#![feature(unwind_attributes)]
#![feature(vec_push_all)]
#![no_std]
#[macro_use]
extern crate alloc;
#[macro_use]
extern crate collections;
use alloc::boxed::Box;
use colle... | };
macro_rules! exception {
($name:expr) => ({
exception_inner!($name);
loop {
do_sys_exit(usize::MAX);
}
})
};
macro_rules! exception_error {
($name:expr) => ({
let error = regs.ip;
regs.ip = regs.cs;... | debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) });
}
debug!("\n");
}
}) | random_line_split |
main.rs | slice_ext)]
#![feature(fnbox)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(unboxed_closures)]
#![feature(unsafe_no_drop_flag)]
#![feature(unwind_attributes)]
#![feature(vec_push_all)]
#![no_std]
#[macro_use]
extern crate alloc;
#[macro_use]
extern crate collections;
use alloc::boxed::Box;
use collec... | () ->! {
loop {
asm!("cli" : : : : "intel", "volatile");
let mut halt = true;
{
let contexts = ::env().contexts.lock();
for i in 1..contexts.len() {
if let Some(context) = contexts.get(i) {
if context.interrupted {
... | idle_loop | identifier_name |
main.rs | slice_ext)]
#![feature(fnbox)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(unboxed_closures)]
#![feature(unsafe_no_drop_flag)]
#![feature(unwind_attributes)]
#![feature(vec_push_all)]
#![no_std]
#[macro_use]
extern crate alloc;
#[macro_use]
extern crate collections;
use alloc::boxed::Box;
use collec... |
_ => {
cmd.push(key_event.character);
console.write(&[key_event.character as u8]);
}
},
... | {
console.command = Some(cmd.clone());
cmd.clear();
console.write(&[10]);
} | conditional_block |
main.rs | slice_ext)]
#![feature(fnbox)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(unboxed_closures)]
#![feature(unsafe_no_drop_flag)]
#![feature(unwind_attributes)]
#![feature(vec_push_all)]
#![no_std]
#[macro_use]
extern crate alloc;
#[macro_use]
extern crate collections;
use alloc::boxed::Box;
use collec... |
/// Event loop
fn event_loop() ->! {
{
let mut console = env().console.lock();
console.instant = false;
}
let mut cmd = String::new();
loop {
loop {
let mut console = env().console.lock();
match env().events.lock().pop_front() {
Some(eve... | {
loop {
env().on_poll();
unsafe { context_switch(false) };
}
} | identifier_body |
main.rs | extern crate rand;
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn | () {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
print!("secret_number is {}\n", secret_number);
loop {
// 为什么必须在loop里面做new
let mut guess = String::new();
println!("Please input your number:");
io::stdin()
.read_l... | main | identifier_name |
main.rs | extern crate rand;
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
print!("secret_number is {}\n", secret_number);
loop {
// 为什么必须在loop里面做new
let mut guess = String::new();
... | }
} | random_line_split | |
main.rs | extern crate rand;
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn main() | println!("your guess : {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("less"),
Ordering::Equal => {
println!("you win");
break;
}
Ordering::Greater => println!("big"),
}
}
} | {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
print!("secret_number is {}\n", secret_number);
loop {
// 为什么必须在loop里面做new
let mut guess = String::new();
println!("Please input your number:");
io::stdin()
.read_lin... | identifier_body |
main.rs | extern crate rand;
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
print!("secret_number is {}\n", secret_number);
loop {
// 为什么必须在loop里面做new
let mut guess = String::new();
... | ing::Greater => println!("big"),
}
}
} | println!("you win");
break;
}
Order | conditional_block |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | (name: &str, description: &str) {
println!("\t{:<35} {}", name, description);
}
println!("Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:", app);
print_option("bubble-widths", "Bubble intrinsic widths separately like other engines.");
print_option("disable-text-aa", "... | print_option | identifier_name |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | // set of options. This is mostly useful for unit tests that
// run through a code path which queries the cmd line options.
if OPTIONS == ptr::null_mut() {
set_opts(default_opts());
}
mem::transmute(OPTIONS)
}
} | #[inline]
pub fn get<'a>() -> &'a Opts {
unsafe {
// If code attempts to retrieve the options and they haven't
// been set by the platform init code, just return a default | random_line_split |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... |
// Always use CPU painting on android.
#[cfg(target_os="android")]
static FORCE_CPU_PAINTING: bool = true;
#[cfg(not(target_os="android"))]
static FORCE_CPU_PAINTING: bool = false;
pub fn default_opts() -> Opts {
Opts {
url: String::new(),
paint_threads: 1,
gpu_painting: false,
... | {
let mut stderr = io::stderr();
stderr.write_all(msg.as_bytes()).unwrap();
stderr.write_all(b"\n").unwrap();
env::set_exit_status(1);
} | identifier_body |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... |
let devtools_port = opt_match.opt_default("devtools", "6000").map(|port| {
port.parse().unwrap()
});
let webdriver_port = opt_match.opt_default("webdriver", "7000").map(|port| {
port.parse().unwrap()
});
let initial_window_size = match opt_match.opt_str("resolution") {
So... | {
paint_threads = 1;
layout_threads = 1;
bubble_inline_sizes_separately = true;
} | conditional_block |
build.rs | use std::io::Error;
// Grpc related files used by tonic are generated here. Those files re-generate for each build
// so it's up to date.
//
// Grpc related files used by grpcio are maintained at src/proto/grpcio. tests/grpc_build.rs makes
// sure they are up to date.
fn main() -> Result<(), Error> |
Ok(())
}
| {
#[cfg(feature = "gen-tonic")]
tonic_build::configure()
.build_server(cfg!(feature = "build-server"))
.build_client(cfg!(feature = "build-client"))
.format(false)
.compile(
&[
"src/proto/opentelemetry-proto/opentelemetry/proto/common/v1/common.proto",... | identifier_body |
build.rs | use std::io::Error;
// Grpc related files used by tonic are generated here. Those files re-generate for each build
// so it's up to date.
//
// Grpc related files used by grpcio are maintained at src/proto/grpcio. tests/grpc_build.rs makes
// sure they are up to date.
fn | () -> Result<(), Error> {
#[cfg(feature = "gen-tonic")]
tonic_build::configure()
.build_server(cfg!(feature = "build-server"))
.build_client(cfg!(feature = "build-client"))
.format(false)
.compile(
&[
"src/proto/opentelemetry-proto/opentelemetry/proto/comm... | main | identifier_name |
build.rs |
// Grpc related files used by tonic are generated here. Those files re-generate for each build
// so it's up to date.
//
// Grpc related files used by grpcio are maintained at src/proto/grpcio. tests/grpc_build.rs makes
// sure they are up to date.
fn main() -> Result<(), Error> {
#[cfg(feature = "gen-tonic")]
... | use std::io::Error; | random_line_split | |
docopt_macro_use_case.rs | // stolen from here: https://github.com/docopt/docopt.rs
#![feature(plugin)]
#![plugin(docopt_macros)]
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
docopt!(Args derive Debug, "
Naval Fate.
Usage:
naval_fate.py ship new <name>...
naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
... | () {
let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
println!("{:?}", args);
}
| main | identifier_name |
docopt_macro_use_case.rs | // stolen from here: https://github.com/docopt/docopt.rs
#![feature(plugin)]
#![plugin(docopt_macros)]
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
docopt!(Args derive Debug, "
Naval Fate.
Usage:
naval_fate.py ship new <name>...
naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
... | {
let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
println!("{:?}", args);
} | identifier_body | |
docopt_macro_use_case.rs | // stolen from here: https://github.com/docopt/docopt.rs
#![feature(plugin)]
#![plugin(docopt_macros)]
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
docopt!(Args derive Debug, "
Naval Fate.
Usage:
naval_fate.py ship new <name>...
naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
... | naval_fate.py (-h | --help)
naval_fate.py --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
");
fn main() {
let args: Args = Args::docopt().decode().unwrap_or_e... | random_line_split | |
lib.rs | //! A simple crate for executing work on a thread pool, and getting back a
//! future.
//!
//! This crate provides a simple thread pool abstraction for running work
//! externally from the current thread that's running. An instance of `Future`
//! is handed back to represent that the work may be done later, and further... | /// This thread pool will hand out futures representing the completed work
/// that happens on the thread pool itself, and the futures can then be later
/// composed with other work as part of an overall computation.
///
/// The worker threads associated with a thread pool are kept alive so long as
/// there is an open... | use futures::sync::oneshot::{channel, Sender, Receiver};
use futures::executor::{self, Run, Executor};
/// A thread pool intended to run CPU intensive work.
/// | random_line_split |
lib.rs | //! A simple crate for executing work on a thread pool, and getting back a
//! future.
//!
//! This crate provides a simple thread pool abstraction for running work
//! externally from the current thread that's running. An instance of `Future`
//! is handed back to represent that the work may be done later, and further... |
/// Create CpuPool with configured parameters
pub fn create(&mut self) -> CpuPool {
let pool = CpuPool {
inner: Arc::new(Inner {
queue: MsQueue::new(),
cnt: AtomicUsize::new(1),
size: self.pool_size,
after_start: self.after_st... | {
self.before_stop = Some(Arc::new(f));
self
} | identifier_body |
lib.rs | //! A simple crate for executing work on a thread pool, and getting back a
//! future.
//!
//! This crate provides a simple thread pool abstraction for running work
//! externally from the current thread that's running. An instance of `Future`
//! is handed back to represent that the work may be done later, and further... | {
Run(Run),
Close,
}
impl CpuPool {
/// Creates a new thread pool with `size` worker threads associated with it.
///
/// The returned handle can use `execute` to run work on this thread pool,
/// and clones can be made of it to get multiple references to the same
/// thread pool.
///
... | Message | identifier_name |
url.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | (url: &str) {
use std;
let _ = std::process::Command::new("xdg-open").arg(url).spawn();
}
| open | identifier_name |
url.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
unsafe {
shell::ShellExecuteA(ptr::null_mut(),
CString::new("open").unwrap().as_ptr(),
CString::new(url.to_owned().replace("\n", "%0A")).unwrap().as_ptr(),
ptr::null(),
ptr::null(),
shell::Normal);
}
}
#[cfg(any(target_os="macos", target_os="freebsd"))]
pub fn open(url: &str) {
use std;
let _ = s... | random_line_split | |
url.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | {
use std;
let _ = std::process::Command::new("xdg-open").arg(url).spawn();
} | identifier_body | |
issue-7573.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 ... | () {
remove_package_from_database();
}
| main | identifier_name |
issue-7573.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 ... | local_path: ~str,
junk: ~str
}
impl CrateId {
fn new(s: &str) -> CrateId {
CrateId {
local_path: s.to_owned(),
junk: ~"wutevs"
}
}
}
pub fn remove_package_from_database() {
let mut lines_to_use: ~[&CrateId] = ~[]; //~ ERROR cannot infer an appropriate lifeti... | random_line_split | |
issue-7573.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 ... | {
remove_package_from_database();
} | identifier_body | |
json_merge.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use super::{Json, JsonRef, JsonType};
use crate::codec::{Error, Result};
use std::collections::BTreeMap;
impl Json {
/// `merge` is the implementation for JSON_MERGE in mysql
/// <https://dev.mysql.com/doc/refman/5.7/en/json-modification-funct... | <'a> {
Ref(JsonRef<'a>),
Owned(Json),
}
impl<'a> MergeUnit<'a> {
fn as_ref(&self) -> JsonRef<'_> {
match self {
MergeUnit::Ref(r) => *r,
MergeUnit::Owned(o) => o.as_ref(),
}
}
fn into_owned(self) -> Json {
match self {
MergeUnit::Ref(r) =>... | MergeUnit | identifier_name |
json_merge.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use super::{Json, JsonRef, JsonType};
use crate::codec::{Error, Result};
use std::collections::BTreeMap;
impl Json {
/// `merge` is the implementation for JSON_MERGE in mysql
/// <https://dev.mysql.com/doc/refman/5.7/en/json-modification-funct... |
}
Json::from_ref_array(buf)
}
// See `mergeBinaryObject()` in TiDB `json/binary_function.go`
fn merge_binary_object(objects: &mut Vec<JsonRef>) -> Result<Json> {
let mut kv_map: BTreeMap<String, Json> = BTreeMap::new();
for j in objects.drain(..) {
let elem_count = j.get_elem_count();
... | {
let child_count = j.get_elem_count();
for i in 0..child_count {
buf.push(j.array_get_elem(i)?);
}
} | conditional_block |
json_merge.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use super::{Json, JsonRef, JsonType};
use crate::codec::{Error, Result};
use std::collections::BTreeMap;
impl Json {
/// `merge` is the implementation for JSON_MERGE in mysql
/// <https://dev.mysql.com/doc/refman/5.7/en/json-modification-funct... |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_merge() {
let test_cases = vec![
vec![r#"{"a": 1}"#, r#"{"b": 2}"#, r#"{"a": 1, "b": 2}"#],
vec![r#"{"a": 1}"#, r#"{"a": 2}"#, r#"{"a": [1, 2]}"#],
vec![r#"{"a": 1}"#, r#"{"a": [2, 3]}"#, r#"{"a": [1, 2, 3]}... | random_line_split | |
json_merge.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use super::{Json, JsonRef, JsonType};
use crate::codec::{Error, Result};
use std::collections::BTreeMap;
impl Json {
/// `merge` is the implementation for JSON_MERGE in mysql
/// <https://dev.mysql.com/doc/refman/5.7/en/json-modification-funct... |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_merge() {
let test_cases = vec![
vec![r#"{"a": 1}"#, r#"{"b": 2}"#, r#"{"a": 1, "b": 2}"#],
vec![r#"{"a": 1}"#, r#"{"a": 2}"#, r#"{"a": [1, 2]}"#],
vec![r#"{"a": 1}"#, r#"{"a": [2, 3]}"#, r#"{"a": [1, 2, 3]... | {
let mut kv_map: BTreeMap<String, Json> = BTreeMap::new();
for j in objects.drain(..) {
let elem_count = j.get_elem_count();
for i in 0..elem_count {
let key = j.object_get_key(i);
let val = j.object_get_val(i)?;
let key = String::from_utf8(key.to_owned()).ma... | identifier_body |
text.rs | , and nothing else can.
///
/// The flow keeps track of the fragments contained by all non-leaf DOM nodes. This is necessary
/// for correct painting order. Since we compress several leaf fragments here, the mapping must
/// be adjusted.
fn flush_clump_to_list(&mut self,
m... | let letter_spacing;
let word_spacing;
let text_rendering;
let word_break;
{
let in_fragment = self.clump.front().unwrap();
let font_style = in_fragment.style().clone_font();
let inherited_text_style = in_fragment... | {
debug!("TextRunScanner: flushing {} fragments in range", self.clump.len());
debug_assert!(!self.clump.is_empty());
match self.clump.front().unwrap().specific {
SpecificFragmentInfo::UnscannedText(_) => {}
_ => {
debug_assert!(self.clump.len() == 1,
... | identifier_body |
text.rs | Some(range.begin() + ByteIndex(run_info.text.len() as isize))
}
_ => None
};
let (mut start_position, mut end_position) = (0, 0);
for (byte_index, character) in text.char_indices() {
if!char... | unscanned_text_fragment_info.selection = None;
} | random_line_split | |
text.rs | None => bidi::Level::ltr(),
};
// Break the run if the new character has a different explicit script than the
// previous characters.
//
// TODO: Special handling of paired punctuation ch... | () | identifier_name | |
lib.rs | #![doc(html_root_url = "http://garrensmith.com/mango_smoothie/")]
//! Mango Smoothie
//! Mango Smoothie is a [CouchDB Mango](http://docs.couchdb.org/en/latest/api/database/find.html) /
//! [Cloudant Query](https://docs.cloudant.com/cloudant_query.html) client library.
//!
//! # Create Indexes
//!
//! To create an inde... | #[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate hyper;
pub mod http;
pub mod errors;
mod database;
pub use database::database; | //! assert_eq!(doc["class"], "mammal");
//! ```
| random_line_split |
handler.rs | use super::Message;
use super::responder::{MessageResponder,ResponderError};
use super::verify::{MessageVerifier,MessageVerifierError};
use std::sync::mpsc::SendError;
pub enum MessageHandlingError {
VerificationError,
ResponseError
}
impl From<ResponderError> for MessageHandlingError {
fn | (_: ResponderError) -> MessageHandlingError {
MessageHandlingError::ResponseError
}
}
impl From<MessageVerifierError> for MessageHandlingError {
fn from(_: MessageVerifierError) -> MessageHandlingError {
MessageHandlingError::VerificationError
}
}
pub struct MessageHandler {
message_ve... | from | identifier_name |
handler.rs | use super::Message;
use super::responder::{MessageResponder,ResponderError};
use super::verify::{MessageVerifier,MessageVerifierError};
use std::sync::mpsc::SendError;
pub enum MessageHandlingError {
VerificationError,
ResponseError
}
impl From<ResponderError> for MessageHandlingError {
fn from(_: Respond... |
}
| {
try!(self.message_verifier.verify(&message));
try!(self.message_responder.respond(message, send));
Ok(())
} | identifier_body |
handler.rs | use super::Message;
use super::responder::{MessageResponder,ResponderError};
use super::verify::{MessageVerifier,MessageVerifierError};
use std::sync::mpsc::SendError;
pub enum MessageHandlingError {
VerificationError,
ResponseError
}
impl From<ResponderError> for MessageHandlingError {
fn from(_: Respond... | message_verifier: MessageVerifier,
message_responder: MessageResponder
}
impl MessageHandler {
pub fn new(message_verifier: MessageVerifier, message_responder: MessageResponder) -> MessageHandler {
MessageHandler {
message_verifier: message_verifier,
message_responder: messa... | }
pub struct MessageHandler { | random_line_split |
rfc2616.rs | //! Values taken from RFC 2616
use std::fmt;
use std::str::FromStr;
use std::ascii::AsciiExt;
/// OCTET: any 8-bit sequence of data (typechecking ensures this to be true)
#[inline]
pub fn is_octet(_: u8) -> bool { true }
/// CHAR: any US-ASCII character (octets 0 - 127)
#[inline]
pub fn is_char(octet: u8) -> bool { ... |
TEXT = <any OCTET except CTLs,
but including LWS>
A CRLF is allowed in the definition of TEXT only as part of a header
field continuation. It is expected that the folding LWS will be
replaced with a single SP before interpretation of the TEXT value.
*/
/// HEX: "A" |... | that are not intended to be interpreted by the message parser. Words
of *TEXT MAY contain characters from character sets other than ISO-
8859-1 [22] only when encoded according to the rules of RFC 2047
[14]. | random_line_split |
rfc2616.rs | //! Values taken from RFC 2616
use std::fmt;
use std::str::FromStr;
use std::ascii::AsciiExt;
/// OCTET: any 8-bit sequence of data (typechecking ensures this to be true)
#[inline]
pub fn is_octet(_: u8) -> bool { true }
/// CHAR: any US-ASCII character (octets 0 - 127)
#[inline]
pub fn is_char(octet: u8) -> bool { ... | (octet: u8) -> bool {
(octet >= b'A' && octet <= b'F') ||
(octet >= b'a' && octet <= b'f') ||
is_digit(octet)
}
/// token = 1*<any CHAR except CTLs or separators>
#[inline]
pub fn is_token_item(o: u8) -> bool {
is_char(o) &&!is_ctl(o) &&!is_separator(o)
}
#[inline]
pub fn is_token(s: &String)... | is_hex | identifier_name |
rfc2616.rs | //! Values taken from RFC 2616
use std::fmt;
use std::str::FromStr;
use std::ascii::AsciiExt;
/// OCTET: any 8-bit sequence of data (typechecking ensures this to be true)
#[inline]
pub fn is_octet(_: u8) -> bool { true }
/// CHAR: any US-ASCII character (octets 0 - 127)
#[inline]
pub fn is_char(octet: u8) -> bool |
/// UPALPHA: any US-ASCII uppercase letter "A".."Z">
#[inline]
pub fn is_upalpha(octet: u8) -> bool { octet >= b'A' && octet <= b'Z' }
/// LOALPHA: any US-ASCII lowercase letter "a".."z">
#[inline]
pub fn is_loalpha(octet: u8) -> bool { octet >= b'a' && octet <= b'z' }
/// ALPHA: UPALPHA | LOALPHA
#[inline]
pub fn ... | { octet < 128 } | identifier_body |
arith-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn main() {
... | // http://rust-lang.org/COPYRIGHT.
// | random_line_split |
arith-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let i32_c: int = 0x10101010;
assert!(i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3) ==
i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3));
} | identifier_body | |
arith-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let i32_c: int = 0x10101010;
assert!(i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3) ==
i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3));
}
| main | identifier_name |
day14.rs | extern crate clap;
extern crate regex;
use clap::App;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::collections::HashMap;
#[derive(Debug, Clone)]
struct ReindeerFlight {
speed : u32,
flight_time : u32,
rest_time : u32
}
impl ReindeerFlight {
fn new(spe... | } | flight | random_line_split |
day14.rs | extern crate clap;
extern crate regex;
use clap::App;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::collections::HashMap;
#[derive(Debug, Clone)]
struct ReindeerFlight {
speed : u32,
flight_time : u32,
rest_time : u32
}
impl ReindeerFlight {
fn new(spe... |
}
}
}
points
}
fn calculate_flight_distance(time : u32, flight_data : HashMap<String, ReindeerFlight>) -> HashMap<String, u32> {
let mut res = HashMap::new();
for (key, value) in flight_data {
let cycle = value.flight_time + value.rest_time;
let full_cycles = time /... | {
*x += 1;
} | conditional_block |
day14.rs | extern crate clap;
extern crate regex;
use clap::App;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::collections::HashMap;
#[derive(Debug, Clone)]
struct ReindeerFlight {
speed : u32,
flight_time : u32,
rest_time : u32
}
impl ReindeerFlight {
fn new(spe... | {
let mut flight = HashMap::new();
for s in input {
let re = Regex::new(r"^(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.").unwrap();
for cap in re.captures_iter(s) {
let name : String = String::from(cap.at(1).unwrap());
let flight_spee... | identifier_body | |
day14.rs | extern crate clap;
extern crate regex;
use clap::App;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::collections::HashMap;
#[derive(Debug, Clone)]
struct ReindeerFlight {
speed : u32,
flight_time : u32,
rest_time : u32
}
impl ReindeerFlight {
fn new(spe... | (time : u32, flight_data : HashMap<String, ReindeerFlight>) -> HashMap<String, u32> {
let mut res = HashMap::new();
for (key, value) in flight_data {
let cycle = value.flight_time + value.rest_time;
let full_cycles = time / cycle;
let mut distance : f64 = full_cycles as f64 * value.spe... | calculate_flight_distance | identifier_name |
equation_numbers.rs | use crate::{mesh::PointId, StrError};
use russell_lab::GenericMatrix;
use std::fmt;
/// Alias for DOF index
pub type DofIndex = usize;
/// DOF index: Displacement along the first dimension
pub const DOF_UX: DofIndex = 0;
/// DOF index: Displacement along the second dimension | pub const DOF_UY: DofIndex = 1;
/// DOF index: Displacement along the third dimension
pub const DOF_UZ: DofIndex = 2;
/// DOF index: Rotation around the first axis
pub const DOF_RX: DofIndex = 3;
/// DOF index: Rotation around the second axis
pub const DOF_RY: DofIndex = 4;
/// DOF index: Rotation around the third ... | random_line_split | |
equation_numbers.rs | use crate::{mesh::PointId, StrError};
use russell_lab::GenericMatrix;
use std::fmt;
/// Alias for DOF index
pub type DofIndex = usize;
/// DOF index: Displacement along the first dimension
pub const DOF_UX: DofIndex = 0;
/// DOF index: Displacement along the second dimension
pub const DOF_UY: DofIndex = 1;
/// DOF ... | (&self) -> usize {
self.count as usize
}
/// Returns the equation number corresponding to a point-DOF pair
pub fn get_equation_number(&self, point_id: PointId, dof_index: DofIndex) -> Result<usize, StrError> {
if self.numbers[point_id][dof_index] < 0 {
return Err("equation numbe... | get_number_of_equations | identifier_name |
equation_numbers.rs | use crate::{mesh::PointId, StrError};
use russell_lab::GenericMatrix;
use std::fmt;
/// Alias for DOF index
pub type DofIndex = usize;
/// DOF index: Displacement along the first dimension
pub const DOF_UX: DofIndex = 0;
/// DOF index: Displacement along the second dimension
pub const DOF_UY: DofIndex = 1;
/// DOF ... |
/// Returns the current total number of equations (DOFs)
pub fn get_number_of_equations(&self) -> usize {
self.count as usize
}
/// Returns the equation number corresponding to a point-DOF pair
pub fn get_equation_number(&self, point_id: PointId, dof_index: DofIndex) -> Result<usize, StrE... | {
if self.numbers[point_id][dof_index] < 0 {
self.numbers[point_id][dof_index] = self.count;
self.count += 1;
}
} | identifier_body |
equation_numbers.rs | use crate::{mesh::PointId, StrError};
use russell_lab::GenericMatrix;
use std::fmt;
/// Alias for DOF index
pub type DofIndex = usize;
/// DOF index: Displacement along the first dimension
pub const DOF_UX: DofIndex = 0;
/// DOF index: Displacement along the second dimension
pub const DOF_UY: DofIndex = 1;
/// DOF ... |
Ok(self.numbers[point_id][dof_index] as usize)
}
}
impl fmt::Display for EquationNumbers {
/// Generates a string representation of the EquationNumbers
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.numbers)
}
}
| {
return Err("equation number has not been set");
} | conditional_block |
common.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/.
*
* Copyright 2017 - Dario Ostuni <dario.ostuni@gmail.com>
*
*/
#[derive(Serialize, Deserialize, Debug, Partia... | pub struct Player
{
pub name: String,
pub points: u64,
pub position: Point,
pub id: u64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Overview
{
pub players: Vec<Player>,
pub grid: Vec<Vec<Option<u64>>>,
pub turns_left: u64,
pub ms_for_turn: u64,
pub tokens: Vec<Point>,
... | random_line_split | |
common.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/.
*
* Copyright 2017 - Dario Ostuni <dario.ostuni@gmail.com>
*
*/
#[derive(Serialize, Deserialize, Debug, Partia... |
{
Move(Direction),
Nothing,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum ServerResponse
{
Ok,
Error(String),
}
#[derive(Serialize, Deserialize, Debug)]
pub enum ClientMessage
{
HandShake(ClientRole),
Command(ClientCommand),
}
| ClientCommand | identifier_name |
issue-21400.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 method2(self: &mut Test, _arg: &str) -> Result<usize, &str> {
Ok(2)
}
fn test(self: &mut Test) -> Result<usize, &str> {
let s = format!("abcde");
// (Originally, this invocation of method2 was saying that `s`
// does not live long enough.)
let data = match self.m... |
impl Test {
fn method1(&mut self, _arg: &str) -> Result<usize, &str> {
Ok(1)
} | random_line_split |
issue-21400.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (self: &mut GitConnect, _s: &str) -> Result<Vec<Vec<u8>>, &str> {
unimplemented!()
}
pub fn git_upload_pack(self: &mut GitConnect) -> Result<String, &str> {
let c = format!("git-upload-pack");
let mut out = String::new();
let data = self.command(&c)?;
for line in data.... | command | identifier_name |
build.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fs;
use std::io;
use std::path::Path;
fn check_signed_source() -> io::Result<()> {
// Check if lib.rs is in sync with the Thr... | () -> io::Result<()> {
check_signed_source()
}
| main | identifier_name |
build.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fs;
use std::io;
use std::path::Path;
fn check_signed_source() -> io::Result<()> {
// Check if lib.rs is in sync with the Thr... | }
fn main() -> io::Result<()> {
check_signed_source()
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.