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 |
|---|---|---|---|---|
mod.rs | //! Basic 2D object and shader.
use std::rc::Rc;
use glium::{ Display, Frame };
use texture::{ Texture, TextureRef };
use mesh::Mesh;
use shader::ShaderType;
use transform::Transform;
use renderer::{ Renderer, Renderable };
use rect::Rect;
use cgmath::Matrix4;
use id::Id;
/// 2D Sprite vertex type
#[derive(Copy, Clo... | (&mut self, display: &Display, rect: Rect)
{
self.mesh = Sprite::build_mesh(display, self.width, self.height, &rect);
self.rect = rect;
}
}
impl Renderable<Shader> for Sprite
{
fn draw(&self, renderer: &Renderer<Shader>, target: &mut Frame, parent: &Matrix4<f32>)
{
let uniforms... | rect | identifier_name |
mod.rs | //! Basic 2D object and shader.
use std::rc::Rc;
use glium::{ Display, Frame };
use texture::{ Texture, TextureRef };
use mesh::Mesh;
use shader::ShaderType;
use transform::Transform;
use renderer::{ Renderer, Renderable };
use rect::Rect;
use cgmath::Matrix4;
use id::Id;
/// 2D Sprite vertex type
#[derive(Copy, Clo... | let x = rect.x as f32;
let y = rect.y as f32;
let w = rect.width as f32;
let h = rect.height as f32;
let verties = [
Vertex { position: [ 0.0, height], texture_position: [ x, y+h] },
Vertex { position: [ 0.0, 0.0], texture_position: [ x, y] },
... |
fn build_mesh(display: &Display, width: f32, height: f32, rect: &Rect)
-> Mesh<Vertex>
{ | random_line_split |
mod.rs | pub doc_all: bool,
pub json_messages: bool,
}
#[derive(Clone, Default)]
pub struct TargetConfig {
pub ar: Option<PathBuf>,
pub linker: Option<PathBuf>,
pub overrides: HashMap<String, BuildOutput>,
}
pub type PackagesToBuild<'a> = [(&'a Package, Vec<(&'a Target, &'a Profile)>)];
/// A glorified ca... | pub release: bool,
pub test: bool, | random_line_split | |
mod.rs | kind: if target.for_host() {Kind::Host} else {default_kind},
}
})
}).collect::<Vec<_>>();
let mut cx = Context::new(ws, resolve, packages, config,
build_config, profiles)?;
let mut queue = JobQueue::new(&cx);
cx.prepare()?;
cx.probe_... | .with_extension("d");
let dep_info_loc = fingerprint::dep_info_loc(cx, unit);
let cwd = cx.config.cwd().to_path_buf();
rustc.args(&cx.incremental_args(unit)?);
rustc.args(&cx.rustflags_args(unit)?);
let json_messages = cx.build_config.json_messages;
let package_id = unit.pkg.package_id().clone(... | {
root.join(&cx.file_stem(unit))
} | conditional_block |
mod.rs | kind: if target.for_host() {Kind::Host} else {default_kind},
}
})
}).collect::<Vec<_>>();
let mut cx = Context::new(ws, resolve, packages, config,
build_config, profiles)?;
let mut queue = JobQueue::new(&cx);
cx.prepare()?;
cx.probe_... | (rustc: &mut ProcessBuilder,
build_state: &BuildMap,
build_scripts: &BuildScripts,
pass_l_flag: bool,
current_id: &PackageId) -> CargoResult<()> {
for key in build_scripts.to_link.iter() {
let output = build_... | add_native_deps | identifier_name |
utils.rs | use traits::Coord;
#[cfg(test)]
pub use self::test_utils::find_cell;
impl Coord for (i32, i32) {
fn from_2d(x: i32, y: i32) -> Self { (x, y) }
fn x(&self) -> i32 { self.0 }
fn y(&self) -> i32 { self.1 }
}
#[cfg(test)]
mod test_utils {
use traits::Cell; |
let found = cells.iter()
.find(|c| c.coord().x() == x && c.coord().y() == y)
.unwrap();
found.clone()
}
} | use traits::Coord;
pub fn find_cell<C: Cell + Clone>(cells: &[C], x: i32, y: i32) -> C {
assert!(cells.iter().any(|c| c.coord().x() == x && c.coord().y() == y)); | random_line_split |
utils.rs | use traits::Coord;
#[cfg(test)]
pub use self::test_utils::find_cell;
impl Coord for (i32, i32) {
fn from_2d(x: i32, y: i32) -> Self { (x, y) }
fn x(&self) -> i32 { self.0 }
fn y(&self) -> i32 { self.1 }
}
#[cfg(test)]
mod test_utils {
use traits::Cell;
use traits::Coord;
pub fn | <C: Cell + Clone>(cells: &[C], x: i32, y: i32) -> C {
assert!(cells.iter().any(|c| c.coord().x() == x && c.coord().y() == y));
let found = cells.iter()
.find(|c| c.coord().x() == x && c.coord().y() == y)
.unwrap();
found.clone()
}
}
| find_cell | identifier_name |
utils.rs | use traits::Coord;
#[cfg(test)]
pub use self::test_utils::find_cell;
impl Coord for (i32, i32) {
fn from_2d(x: i32, y: i32) -> Self { (x, y) }
fn x(&self) -> i32 { self.0 }
fn y(&self) -> i32 |
}
#[cfg(test)]
mod test_utils {
use traits::Cell;
use traits::Coord;
pub fn find_cell<C: Cell + Clone>(cells: &[C], x: i32, y: i32) -> C {
assert!(cells.iter().any(|c| c.coord().x() == x && c.coord().y() == y));
let found = cells.iter()
.find(|c| c.coord().x() == x && c.coor... | { self.1 } | identifier_body |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... | use js::jsval::JSVal;
use servo_atoms::Atom;
#[dom_struct]
pub struct MessageEvent {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEvent {
pub fn new_uninitialized(global: &GlobalScope) -> Root<MessageEvent> {
MessageEvent::new_initialized(global... | random_line_split | |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... |
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DOMString {
self.lastEventId.clone()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
self.origin.clone()
} | identifier_body |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... | (&self, _cx: *mut JSContext) -> JSVal {
self.data.get()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DO... | Data | 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/. */
//! Selecting the default global allocator for Servo
#![cfg_attr(all(feature = "unstable", windows), feature(allo... | }
#[cfg(all(feature = "unstable", windows))]
mod platform {
extern crate alloc_system;
extern crate kernel32;
pub use self::alloc_system::System as Allocator;
use self::kernel32::{GetProcessHeap, HeapSize, HeapValidate};
use std::os::raw::c_void;
/// Get the size of a heap block.
pub unsa... | jemallocator::usable_size(ptr)
} | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Selecting the default global allocator for Servo
#![cfg_attr(all(feature = "unstable", windows), feature(allo... |
}
#[cfg(all(feature = "unstable", windows))]
mod platform {
extern crate alloc_system;
extern crate kernel32;
pub use self::alloc_system::System as Allocator;
use self::kernel32::{GetProcessHeap, HeapSize, HeapValidate};
use std::os::raw::c_void;
/// Get the size of a heap block.
pub uns... | {
jemallocator::usable_size(ptr)
} | 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/. */
//! Selecting the default global allocator for Servo
#![cfg_attr(all(feature = "unstable", windows), feature(allo... |
HeapSize(heap, 0, ptr) as usize
}
}
#[cfg(not(feature = "unstable"))]
mod platform {
use std::os::raw::c_void;
/// Without `#[global_allocator]` we cannot be certain of what allocator is used
/// or how it is linked. We therefore disable memory reporting. (Return zero.)
pub unsafe extern... | {
ptr = *(ptr as *const *const c_void).offset(-1);
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Selecting the default global allocator for Servo
#![cfg_attr(all(feature = "unstable", windows), feature(allo... | (mut ptr: *const c_void) -> usize {
let heap = GetProcessHeap();
if HeapValidate(heap, 0, ptr) == 0 {
ptr = *(ptr as *const *const c_void).offset(-1);
}
HeapSize(heap, 0, ptr) as usize
}
}
#[cfg(not(feature = "unstable"))]
mod platform {
use std::os::raw::c_void;
... | usable_size | identifier_name |
main.rs | (&self) -> Result<Vec<CompiledModule>> {
self.mode.compiled_modules(&self.get_package_dir())
}
/// Prepare an OnDiskStateView that is ready to use. Library modules will be preloaded into the
/// storage if `load_libraries` is true.
///
/// NOTE: this is the only way to get a state view in M... | get_library_modules | identifier_name | |
main.rs | #[structopt(
long,
default_value = DEFAULT_DEP_MODE,
global = true,
parse(try_from_str = parse_mode_from_string),
)]
mode: Mode,
/// Print additional diagnostics
#[structopt(short = "v", global = true)]
verbose: bool,
#[structopt(subcommand)]
cmd: Command,... | storage_dir: String,
/// Directory storing build artifacts produced by compilation
#[structopt(long, short = "d", default_value = DEFAULT_BUILD_DIR, global = true)]
build_dir: String,
/// Dependency inclusion mode | random_line_split | |
main.rs | load_libraries {
self.mode.prepare(&self.get_package_dir(), false)?;
// preload the storage with library modules (if such modules do not exist yet)
let lib_modules = self.get_library_modules()?;
let new_modules: Vec<_> = lib_modules
.into_iter()
... |
fn explain_publish_changeset(changeset: &ChangeSet, state: &OnDiskStateView) {
// publish effects should contain no resources
assert!(changeset.resources().next().is_none());
// total bytes written across all accounts
let mut total_bytes_written = 0;
for (addr, name, blob_opt) in changeset.modules... | {
let gas_schedule = &vm_genesis::genesis_gas_schedule::INITIAL_GAS_SCHEDULE;
let cost_strategy = if let Some(gas_budget) = gas_budget {
let max_gas_budget = u64::MAX
.checked_div(gas_schedule.gas_constants.gas_unit_scaling_factor)
.unwrap();
if gas_budget >= max_gas_budg... | identifier_body |
prefs.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 resource_files::resources_dir_path;
use rustc_serialize::json::{Json, ToJson};
use std::borrow::ToOwned;
use s... |
pub fn as_string(&self) -> Option<&str> {
match *self {
PrefValue::String(ref value) => {
Some(&value)
},
_ => None
}
}
}
impl ToJson for PrefValue {
fn to_json(&self) -> Json {
match *self {
PrefValue::Boolean(x) => ... | {
match *self {
PrefValue::Boolean(value) => {
Some(value)
},
_ => None
}
} | identifier_body |
prefs.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 resource_files::resources_dir_path;
use rustc_serialize::json::{Json, ToJson};
use std::borrow::ToOwned;
use s... | }
pub fn as_boolean(&self) -> Option<bool> {
match *self {
PrefValue::Boolean(value) => {
Some(value)
},
_ => None
}
}
pub fn as_string(&self) -> Option<&str> {
match *self {
PrefValue::String(ref value) => {
... | Json::String(x) => PrefValue::String(x),
_ => return Err(())
};
Ok(value) | random_line_split |
prefs.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 resource_files::resources_dir_path;
use rustc_serialize::json::{Json, ToJson};
use std::borrow::ToOwned;
use s... | (data: Json) -> Result<Pref, ()> {
let value = try!(PrefValue::from_json(data));
Ok(Pref::new_default(value))
}
pub fn value(&self) -> &Arc<PrefValue> {
match *self {
Pref::NoDefault(ref x) => x,
Pref::WithDefault(ref default, ref override_value) => {
... | from_json | identifier_name |
multicol.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/. */
//! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/
#![deny(unsafe_code)]
use block::BlockFlow;
us... | }
} | impl fmt::Debug for MulticolFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "MulticolFlow: {:?}", self.block_flow) | random_line_split |
multicol.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/. */
//! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/
#![deny(unsafe_code)]
use block::BlockFlow;
us... |
fn as_block<'a>(&'a self) -> &'a BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
// FIXME(SimonSapin) http://dev.w3.org/csswg/css-sizing/#multicol-intrinsic
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) ... | {
&mut self.block_flow
} | identifier_body |
multicol.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/. */
//! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/
#![deny(unsafe_code)]
use block::BlockFlow;
us... | (&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn updat... | compute_absolute_position | identifier_name |
lib.rs | // Copyright 2013-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... | else {
Some(&values[self.gen_range(0, values.len())])
}
}
/// Shuffle a mutable slice in place.
///
/// # Example
///
/// ```rust
/// use std::rand::{thread_rng, Rng};
///
/// let mut rng = thread_rng();
/// let mut y = [1, 2, 3];
/// rng.shuffle(&mut y)... | {
None
} | conditional_block |
lib.rs | // Copyright 2013-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... | (&mut self) -> u32 {
fn next<T: rand::Rng>(t: &mut T) -> u32 {
use std::rand::Rng;
t.next_u32()
}
next(&mut self.inner)
}
}
pub fn rng() -> MyRng<rand::ThreadRng> {
MyRng { inner: rand::thread_rng() }
}
pub fn weak_rng... | next_u32 | identifier_name |
lib.rs | // Copyright 2013-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... |
}
impl Rand for XorShiftRng {
fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
let mut tuple: (u32, u32, u32, u32) = rng.gen();
while tuple == (0, 0, 0, 0) {
tuple = rng.gen();
}
let (x, y, z, w) = tuple;
XorShiftRng { x: x, y: y, z: z, w: w }
}
}
/// A wrappe... | {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng::from_seed called with an all zero seed.");
XorShiftRng {
x: seed[0],
y: seed[1],
z: seed[2],
w: seed[3]
}
} | identifier_body |
lib.rs | // Copyright 2013-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... | /// interval `[0, 1)`.
///
/// By default this is implemented in terms of `next_u32`, but a
/// random number generator which can generate numbers satisfying
/// the requirements directly can overload this for performance.
/// It is required that the return value lies in `[0, 1)`.
///
//... | fn next_u64(&mut self) -> u64 {
((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
}
/// Return the next random f32 selected from the half-open | random_line_split |
decoder.rs | use super::{
read::{BorrowReader, Reader},
BorrowDecoder, Decoder,
};
use crate::{config::Config, error::DecodeError, utils::Sealed};
/// A Decoder that reads bytes from a given reader `R`.
///
/// This struct should rarely be used.
/// In most cases, prefer any of the `decode` functions.
///
/// The ByteOrder... | (&self) -> &Self::C {
&self.config
}
#[inline]
fn claim_bytes_read(&mut self, n: usize) -> Result<(), DecodeError> {
// C::LIMIT is a const so this check should get compiled away
if let Some(limit) = C::LIMIT {
// Make sure we don't accidentally overflow `bytes_read`
... | config | identifier_name |
decoder.rs | use super::{
read::{BorrowReader, Reader},
BorrowDecoder, Decoder,
};
use crate::{config::Config, error::DecodeError, utils::Sealed};
/// A Decoder that reads bytes from a given reader `R`.
///
/// This struct should rarely be used.
/// In most cases, prefer any of the `decode` functions.
///
/// The ByteOrder... |
}
| {
// C::LIMIT is a const so this check should get compiled away
if C::LIMIT.is_some() {
// We should always be claiming more than we unclaim, so this should never underflow
self.bytes_read -= n;
}
} | identifier_body |
decoder.rs | use super::{
read::{BorrowReader, Reader},
BorrowDecoder, Decoder,
};
use crate::{config::Config, error::DecodeError, utils::Sealed};
/// A Decoder that reads bytes from a given reader `R`.
///
/// This struct should rarely be used.
/// In most cases, prefer any of the `decode` functions.
///
/// The ByteOrder... | &self.config
}
#[inline]
fn claim_bytes_read(&mut self, n: usize) -> Result<(), DecodeError> {
// C::LIMIT is a const so this check should get compiled away
if let Some(limit) = C::LIMIT {
// Make sure we don't accidentally overflow `bytes_read`
self.bytes_re... |
fn config(&self) -> &Self::C { | random_line_split |
decoder.rs | use super::{
read::{BorrowReader, Reader},
BorrowDecoder, Decoder,
};
use crate::{config::Config, error::DecodeError, utils::Sealed};
/// A Decoder that reads bytes from a given reader `R`.
///
/// This struct should rarely be used.
/// In most cases, prefer any of the `decode` functions.
///
/// The ByteOrder... |
} else {
Ok(())
}
}
#[inline]
fn unclaim_bytes_read(&mut self, n: usize) {
// C::LIMIT is a const so this check should get compiled away
if C::LIMIT.is_some() {
// We should always be claiming more than we unclaim, so this should never underflow
... | {
Ok(())
} | conditional_block |
aspect_frame.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! A frame that constrains its child to a particular aspect ratio
use libc::c_float;
u... | self,
x_align: f32,
y_align: f32,
ratio: f32,
obey_child: bool) -> () {
unsafe {
ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child));
}
}
}... | t(& | identifier_name |
aspect_frame.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! A frame that constrains its child to a particular aspect ratio
use libc::c_float;
u... | y_align: f32,
ratio: f32,
obey_child: bool) -> () {
unsafe {
ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child));
}
}
}
impl_drop!(AspectFrame);
impl_Tra... |
pub fn set(&self,
x_align: f32, | random_line_split |
aspect_frame.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! A frame that constrains its child to a particular aspect ratio
use libc::c_float;
u... |
impl_drop!(AspectFrame);
impl_TraitWidget!(AspectFrame);
impl ::FrameTrait for AspectFrame {}
impl ::ContainerTrait for AspectFrame {}
|
unsafe {
ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child));
}
}
} | identifier_body |
mousesquare.rs | extern crate libxdo_sys;
use libxdo_sys::*;
use std::ptr::null;
use std::time::Duration;
unsafe fn move_it(xdo: *const xdo_t, rel_x: i32, rel_y: i32, times: i32) {
for _ in 0..times {
if xdo_move_mouse_relative(xdo, rel_x, rel_y)!= 0 {
panic!("Failed to move mouse.");
}
std::th... | xdo_free(xdo);
}
} | move_it(xdo, 0, 10, 20);
move_it(xdo, -10, 0, 20);
move_it(xdo, 0, -10, 20);
| random_line_split |
mousesquare.rs | extern crate libxdo_sys;
use libxdo_sys::*;
use std::ptr::null;
use std::time::Duration;
unsafe fn move_it(xdo: *const xdo_t, rel_x: i32, rel_y: i32, times: i32) {
for _ in 0..times {
if xdo_move_mouse_relative(xdo, rel_x, rel_y)!= 0 {
panic!("Failed to move mouse.");
}
std::th... | () {
unsafe {
let xdo = xdo_new(null());
if xdo.is_null() {
panic!("Failed to init libxdo.");
}
move_it(xdo, 10, 0, 20);
move_it(xdo, 0, 10, 20);
move_it(xdo, -10, 0, 20);
move_it(xdo, 0, -10, 20);
xdo_free(xdo);
}
}
| main | identifier_name |
mousesquare.rs | extern crate libxdo_sys;
use libxdo_sys::*;
use std::ptr::null;
use std::time::Duration;
unsafe fn move_it(xdo: *const xdo_t, rel_x: i32, rel_y: i32, times: i32) |
fn main() {
unsafe {
let xdo = xdo_new(null());
if xdo.is_null() {
panic!("Failed to init libxdo.");
}
move_it(xdo, 10, 0, 20);
move_it(xdo, 0, 10, 20);
move_it(xdo, -10, 0, 20);
move_it(xdo, 0, -10, 20);
xdo_free(xdo);
}
}
| {
for _ in 0..times {
if xdo_move_mouse_relative(xdo, rel_x, rel_y) != 0 {
panic!("Failed to move mouse.");
}
std::thread::sleep(Duration::from_millis(10));
}
} | identifier_body |
mousesquare.rs | extern crate libxdo_sys;
use libxdo_sys::*;
use std::ptr::null;
use std::time::Duration;
unsafe fn move_it(xdo: *const xdo_t, rel_x: i32, rel_y: i32, times: i32) {
for _ in 0..times {
if xdo_move_mouse_relative(xdo, rel_x, rel_y)!= 0 |
std::thread::sleep(Duration::from_millis(10));
}
}
fn main() {
unsafe {
let xdo = xdo_new(null());
if xdo.is_null() {
panic!("Failed to init libxdo.");
}
move_it(xdo, 10, 0, 20);
move_it(xdo, 0, 10, 20);
move_it(xdo, -10, 0, 20);
mo... | {
panic!("Failed to move mouse.");
} | conditional_block |
context.rs | use std::fmt;
/// We re-export winit so it's easy for people to use the same version as we are
/// without having to mess around figuring it out.
pub use winit;
use crate::audio;
use crate::conf;
use crate::error::GameResult;
use crate::filesystem::Filesystem;
use crate::graphics;
use crate::input::{gamepad, keyboard,... |
}
| {
// Do nothing.
} | identifier_body |
context.rs | use std::fmt;
/// We re-export winit so it's easy for people to use the same version as we are
/// without having to mess around figuring it out.
pub use winit;
use crate::audio;
use crate::conf;
use crate::error::GameResult;
use crate::filesystem::Filesystem;
use crate::graphics;
use crate::input::{gamepad, keyboard,... | () -> Self {
DebugId
}
pub fn get(_ctx: &Context) -> Self {
DebugId
}
pub fn assert(&self, _ctx: &Context) {
// Do nothing.
}
}
| new | identifier_name |
context.rs | use std::fmt;
/// We re-export winit so it's easy for people to use the same version as we are
/// without having to mess around figuring it out.
pub use winit;
use crate::audio;
use crate::conf;
use crate::error::GameResult;
use crate::filesystem::Filesystem;
use crate::graphics;
use crate::input::{gamepad, keyboard,... | /// ```
pub fn add_zipfile_bytes<B>(mut self, bytes: B) -> Self
where
B: Into<Cow<'static, [u8]>>,
{
let cow = bytes.into();
self.memory_zip_files.push(cow);
self
}
/// Specifies whether or not to load the `conf.toml` file if it
/// exists and use its setting... | random_line_split | |
context.rs | use std::fmt;
/// We re-export winit so it's easy for people to use the same version as we are
/// without having to mess around figuring it out.
pub use winit;
use crate::audio;
use crate::conf;
use crate::error::GameResult;
use crate::filesystem::Filesystem;
use crate::graphics;
use crate::input::{gamepad, keyboard,... | ;
Context::from_conf(config, fs)
}
}
#[cfg(debug_assertions)]
use std::sync::atomic::{AtomicU32, Ordering};
#[cfg(debug_assertions)]
static DEBUG_ID_COUNTER: AtomicU32 = AtomicU32::new(0);
/// This is a type that contains a unique ID for each `Context` and
/// is contained in each thing created from the ... | {
self.conf
} | conditional_block |
cylinder_support_map.rs | use num::Signed;
use na::{Rotate, Transform, Norm};
use na;
use support_map::SupportMap;
use shape::Cylinder;
use math::{Scalar, Point, Vect};
impl<P, M> SupportMap<P, M> for Cylinder<<P::Vect as Vect>::Scalar>
where P: Point,
M: Transform<P> + Rotate<P::Vect> {
fn | (&self, m: &M, dir: &P::Vect) -> P {
let local_dir = m.inv_rotate(dir);
let mut vres = local_dir.clone();
let negative = local_dir[1].is_negative();
vres[1] = na::zero();
if na::is_zero(&vres.normalize_mut()) {
vres = na::zero()
}
else {
... | support_point | identifier_name |
cylinder_support_map.rs | use num::Signed;
use na::{Rotate, Transform, Norm};
use na;
use support_map::SupportMap;
use shape::Cylinder;
use math::{Scalar, Point, Vect};
impl<P, M> SupportMap<P, M> for Cylinder<<P::Vect as Vect>::Scalar>
where P: Point,
M: Transform<P> + Rotate<P::Vect> {
fn support_point(&self, m: &M, dir: ... | vres[1] = self.half_height()
}
m.transform(&(na::orig::<P>() + vres))
}
}
| {
let local_dir = m.inv_rotate(dir);
let mut vres = local_dir.clone();
let negative = local_dir[1].is_negative();
vres[1] = na::zero();
if na::is_zero(&vres.normalize_mut()) {
vres = na::zero()
}
else {
vres = vres * self.radius();
... | identifier_body |
cylinder_support_map.rs | use num::Signed;
use na::{Rotate, Transform, Norm};
use na;
use support_map::SupportMap;
use shape::Cylinder;
use math::{Scalar, Point, Vect};
impl<P, M> SupportMap<P, M> for Cylinder<<P::Vect as Vect>::Scalar>
where P: Point,
M: Transform<P> + Rotate<P::Vect> {
fn support_point(&self, m: &M, dir: ... |
m.transform(&(na::orig::<P>() + vres))
}
} | }
else {
vres[1] = self.half_height()
} | random_line_split |
cylinder_support_map.rs | use num::Signed;
use na::{Rotate, Transform, Norm};
use na;
use support_map::SupportMap;
use shape::Cylinder;
use math::{Scalar, Point, Vect};
impl<P, M> SupportMap<P, M> for Cylinder<<P::Vect as Vect>::Scalar>
where P: Point,
M: Transform<P> + Rotate<P::Vect> {
fn support_point(&self, m: &M, dir: ... |
else {
vres = vres * self.radius();
}
if negative {
vres[1] = -self.half_height()
}
else {
vres[1] = self.half_height()
}
m.transform(&(na::orig::<P>() + vres))
}
}
| {
vres = na::zero()
} | conditional_block |
p079.rs | //! [Problem 79](https://projecteuler.net/problem=79) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate topological_sort as tsort;
use std::fs::File;
use std::io::{self, BufRea... | fn solve(file: File) -> io::Result<String> {
let mut ts = TopologicalSort::new();
for line in BufReader::new(file).lines() {
let line = try!(line);
let ds = line.trim().chars();
for (prec, succ) in ds.clone().zip(ds.skip(1)) {
ts.add_dependency(prec, succ);
}
}
... | random_line_split | |
p079.rs | //! [Problem 79](https://projecteuler.net/problem=79) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate topological_sort as tsort;
use std::fs::File;
use std::io::{self, BufRea... | (file: File) -> io::Result<String> {
let mut ts = TopologicalSort::new();
for line in BufReader::new(file).lines() {
let line = try!(line);
let ds = line.trim().chars();
for (prec, succ) in ds.clone().zip(ds.skip(1)) {
ts.add_dependency(prec, succ);
}
}
let s ... | solve | identifier_name |
p079.rs | //! [Problem 79](https://projecteuler.net/problem=79) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate topological_sort as tsort;
use std::fs::File;
use std::io::{self, BufRea... |
problem!("73162890", "p079_keylog.txt", solve);
| {
let mut ts = TopologicalSort::new();
for line in BufReader::new(file).lines() {
let line = try!(line);
let ds = line.trim().chars();
for (prec, succ) in ds.clone().zip(ds.skip(1)) {
ts.add_dependency(prec, succ);
}
}
let s = ts.map(|d| d.to_string()).collect... | identifier_body |
refresh.rs | use std::net::SocketAddr;
use std::sync::mpsc::SyncSender;
use bip_handshake::Handshaker;
use bip_util::bt::{self, NodeId};
use mio::EventLoop;
use message::find_node::FindNodeRequest;
use routing::node::NodeStatus;
use routing::table::{self, RoutingTable};
use transaction::MIDGenerator;
use worker::ScheduledTask;
us... | {
/// Refresh is in progress.
Refreshing,
/// Refresh failed in a fatal way.
Failed,
}
pub struct TableRefresh {
id_generator: MIDGenerator,
curr_refresh_bucket: usize,
}
impl TableRefresh {
pub fn new(id_generator: MIDGenerator) -> TableRefresh {
TableRefresh {
id_gen... | RefreshStatus | identifier_name |
refresh.rs | use std::net::SocketAddr;
use std::sync::mpsc::SyncSender;
use bip_handshake::Handshaker;
use bip_util::bt::{self, NodeId};
use mio::EventLoop; |
use message::find_node::FindNodeRequest;
use routing::node::NodeStatus;
use routing::table::{self, RoutingTable};
use transaction::MIDGenerator;
use worker::ScheduledTask;
use worker::handler::DhtHandler;
const REFRESH_INTERVAL_TIMEOUT: u64 = 6000;
pub enum RefreshStatus {
/// Refresh is in progress.
Refresh... | random_line_split | |
refresh.rs | use std::net::SocketAddr;
use std::sync::mpsc::SyncSender;
use bip_handshake::Handshaker;
use bip_util::bt::{self, NodeId};
use mio::EventLoop;
use message::find_node::FindNodeRequest;
use routing::node::NodeStatus;
use routing::table::{self, RoutingTable};
use transaction::MIDGenerator;
use worker::ScheduledTask;
us... |
let target_id = flip_id_bit_at_index(table.node_id(), self.curr_refresh_bucket);
info!("bip_dht: Performing a refresh for bucket {}",
self.curr_refresh_bucket);
// Ping the closest questionable node
for node in table.closest_nodes(target_id)
.filter(|n| n.statu... | {
self.curr_refresh_bucket = 0;
} | conditional_block |
document_condition.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/. */
//! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document)
//! initially in CSS C... | f, dest: &mut W) -> fmt::Result
where W: fmt::Write {
let mut iter = self.0.iter();
let first = iter.next()
.expect("Empty DocumentCondition, should contain at least one URL matching function");
first.to_css(dest)?;
for url_matching_function in iter {
dest.... | >(&sel | identifier_name |
document_condition.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/. */
//! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document)
//! initially in CSS C... | ToCss for UrlMatchingFunction {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write {
match *self {
UrlMatchingFunction::Url(ref url) => {
url.to_css(dest)
},
UrlMatchingFunction::UrlPrefix(ref url_prefix) => {
des... | false
}
}
impl | identifier_body |
document_condition.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/. */
//! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document)
//! initially in CSS C... | fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write {
let mut iter = self.0.iter();
let first = iter.next()
.expect("Empty DocumentCondition, should contain at least one URL matching function");
first.to_css(dest)?;
for url_matching_function in ite... | }
}
impl ToCss for DocumentCondition { | random_line_split |
error.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... | (err: EthCryptoError) -> Self {
Error::EthCrypto(err)
}
}
| from | identifier_name |
error.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... |
impl From<EthKeyError> for Error {
fn from(err: EthKeyError) -> Self {
Error::EthKey(err)
}
}
impl From<EthCryptoError> for Error {
fn from(err: EthCryptoError) -> Self {
Error::EthCrypto(err)
}
} | } | random_line_split |
root_variables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use fnv::{FnvHashMap, FnvHashSet};
use graphql_ir::{
FragmentDefinition, FragmentSpread, NamedItem, OperationDefinition, Progra... | self.visited_fragments
.insert(fragment.name.item, result.clone());
result
}
}
}
impl<'s> Visitor for VaraiblesVisitor<'s> {
const NAME: &'static str = "VaraiblesVisitor";
const VISIT_ARGUMENTS: bool = true;
const VISIT_DIRECTIVES: bool = true;
fn vi... | {
// Break cycles by initially caching a version that is empty.
// If the current fragment is reached again, it won't have any
// root variables to add to its parents. The traversal below will
// find any root variables and update the cached version of the
// ... | conditional_block |
root_variables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use fnv::{FnvHashMap, FnvHashSet};
use graphql_ir::{
FragmentDefinition, FragmentSpread, NamedItem, OperationDefinition, Progra... | (&mut self, spread: &FragmentSpread) {
self.visit_directives(&spread.directives);
let fragment = self
.program
.fragment(spread.fragment.item)
.expect("Expect fragment to exist.");
// Detect root variables being passed as the value of @arguments;
// reco... | visit_fragment_spread | identifier_name |
root_variables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use fnv::{FnvHashMap, FnvHashSet};
use graphql_ir::{
FragmentDefinition, FragmentSpread, NamedItem, OperationDefinition, Progra... | .entry(var.name.item)
.or_insert_with(|| Variable {
name: var.name,
type_: def.type_.clone(),
});
}
}
}
}
// ... | if !fragment.variable_definitions.is_empty() {
for arg in spread.arguments.iter() {
if let Value::Variable(var) = &arg.value.item {
if let Some(def) = fragment.variable_definitions.named(var.name.item) {
self.variable_map | random_line_split |
root_variables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use fnv::{FnvHashMap, FnvHashSet};
use graphql_ir::{
FragmentDefinition, FragmentSpread, NamedItem, OperationDefinition, Progra... |
}
struct VaraiblesVisitor<'s> {
variable_map: VariableMap,
visited_fragments: &'s mut Visited,
program: &'s Program<'s>,
local_variables: FnvHashSet<StringKey>,
}
impl<'s> VaraiblesVisitor<'s> {
fn new(
program: &'s Program<'s>,
visited_fragments: &'s mut Visited,
local_va... | {
let mut visitor = VaraiblesVisitor::new(
self.program,
&mut self.visited_fragments,
Default::default(),
);
visitor.visit_operation(operation);
visitor.variable_map
} | identifier_body |
surface.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of cancer.
//
// cancer 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
// (a... | ontext: *mut c_void, width: u32, height: u32) -> Self {
unsafe {
CGContextTranslateCTM(context, 0.0, height as CGFloat);
CGContextScaleCTM(context, 1.0, -1.0);
Surface(cairo_quartz_surface_create_for_cg_context(context, width as c_uint, height as c_uint))
}
}
}
impl Drop for Surface {
fn drop(&mut self... | w(c | identifier_name |
surface.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of cancer.
//
// cancer 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
// (a... |
use ffi::cairo::*;
use ffi::cairo::platform::*;
#[derive(Debug)]
pub struct Surface(pub *mut cairo_surface_t);
unsafe impl Send for Surface { }
impl Surface {
pub fn flush(&self) {
unsafe {
cairo_surface_flush(self.0);
}
}
}
#[cfg(all(unix, not(target_os = "macos")))]
impl Surface {
pub fn new(connection... | // along with cancer. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
surface.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of cancer.
//
// cancer 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
// (a... |
impl Drop for Surface {
fn drop(&mut self) {
unsafe {
cairo_surface_destroy(self.0);
}
}
}
| unsafe {
CGContextTranslateCTM(context, 0.0, height as CGFloat);
CGContextScaleCTM(context, 1.0, -1.0);
Surface(cairo_quartz_surface_create_for_cg_context(context, width as c_uint, height as c_uint))
}
}
} | identifier_body |
ffi.rs | // @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/msg
//
// This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)]
/// The `Ipc` enum is a POSIX Standard
/// for System ... | pub gid: i64, // owner's group id.
pub cuid: i64, // creator's user id.
pub cgid: i64, // creator's group id.
pub mode: u16, // access modes.
pub seq: u16, // slot usage sequence number.
pub key: i64, // key.
} | random_line_split | |
ffi.rs | // @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/msg
//
// This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)]
/// The `Ipc` enum is a POSIX Standard
/// for System ... | {
pub uid: i64, // owner's user id.
pub gid: i64, // owner's group id.
pub cuid: i64, // creator's user id.
pub cgid: i64, // creator's group id.
pub mode: u16, // access modes.
pub seq: u16, // slot usage sequence number.
pub key: i64, // key.
}
| IpcPerm | identifier_name |
env.rs | use std::collections::HashMap;
use std::cell::{Ref, RefCell};
use std::rc::Rc;
use types::{Expr, Symbol};
#[derive(Clone, Debug)]
struct EnvImpl {
symbols: HashMap<String, Expr>,
parent: Option<Env>,
}
#[derive(Clone, Debug)]
pub struct Env(Rc<RefCell<EnvImpl>>);
impl Env {
pub fn new(symbols: HashMap<S... | (&self, symbol: &str) -> Option<Expr> {
let borrowed: Ref<EnvImpl> = (*self.0).borrow();
let self_lookup = borrowed.symbols.get(symbol).cloned();
match self_lookup {
Some(value) => Some(value),
None => match borrowed.parent.clone() {
Some(parent) => parent... | lookup | identifier_name |
env.rs | use std::collections::HashMap;
use std::cell::{Ref, RefCell};
use std::rc::Rc;
use types::{Expr, Symbol};
#[derive(Clone, Debug)]
struct EnvImpl {
symbols: HashMap<String, Expr>,
parent: Option<Env>,
}
#[derive(Clone, Debug)]
pub struct Env(Rc<RefCell<EnvImpl>>); | Env( Rc::new( RefCell::new( EnvImpl {
symbols: symbols,
parent: parent,
})))
}
pub fn lookup(&self, symbol: &str) -> Option<Expr> {
let borrowed: Ref<EnvImpl> = (*self.0).borrow();
let self_lookup = borrowed.symbols.get(symbol).cloned();
match sel... |
impl Env {
pub fn new(symbols: HashMap<String, Expr>, parent: Option<Env>) -> Self { | random_line_split |
main.rs | use rand::Rng; //trait
use std::cmp::Ordering;
use std::io; // prelude
fn main() | Ordering::Equal => {
println!("you win");
break;}
,
}
}
}
| {
println!("猜数");
let secret_number = rand::thread_rng().gen_range(0..100);
println!("神秘数字是: {}", secret_number);
loop {
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect(" 无法读取行");
// shadow
let guess: u32 = match guess.trim().parse::<u32>() {... | identifier_body |
main.rs | use rand::Rng; //trait
use std::cmp::Ordering;
use std::io; // prelude
fn main() {
println!("猜数");
let secret_number = rand::thread_rng().gen_range(0..100);
println!("神秘数字是: {}", secret_number);
loop {
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect(" 无法读取行"... | } | random_line_split | |
main.rs | use rand::Rng; //trait
use std::cmp::Ordering;
use std::io; // prelude
fn | () {
println!("猜数");
let secret_number = rand::thread_rng().gen_range(0..100);
println!("神秘数字是: {}", secret_number);
loop {
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect(" 无法读取行");
// shadow
let guess: u32 = match guess.trim().parse::<u32>(... | main | identifier_name |
types.rs |
use read::Sexp;
use std::rc::Rc;
use std::cell::{RefCell, Ref};
use std::collections::HashMap;
use itertools::*;
#[derive(PartialEq, Clone, Debug)]
pub struct TRef(Rc<RefCell<Option<Type>>>);
impl TRef {
fn new() -> Self {
TRef(Rc::new(RefCell::new(None)))
}
fn get(&self) -> Ref<Option<Type>> ... | else {
unreachable!()
}
}
_ => false,
}
}
fn unify(t1: &Type, t2: &Type) -> Result<(), (Type, Type)> {
match (t1, t2) {
(&Type::Unit, &Type::Unit) |
(&Type::Bool, &Type::Bool) |
(&Type::Int, &Type::Int) => Ok(()),
(&Type::Fun(ref t1s,... | {
occur(r1, t2)
} | conditional_block |
types.rs |
use read::Sexp;
use std::rc::Rc;
use std::cell::{RefCell, Ref};
use std::collections::HashMap;
use itertools::*;
#[derive(PartialEq, Clone, Debug)]
pub struct TRef(Rc<RefCell<Option<Type>>>);
impl TRef {
fn new() -> Self {
TRef(Rc::new(RefCell::new(None)))
}
fn get(&self) -> Ref<Option<Type>> ... |
#[derive(Debug, Clone)]
pub enum Ast {
Unit,
Bool(bool),
Int(i64),
Quote(Sexp),
Let(Vec<(String, Type, Ast)>, Vec<Ast>),
Var(String),
App(Box<Ast>, Vec<Ast>),
IfElse(Box<Ast>, Box<Ast>, Box<Ast>),
If(Box<Ast>, Box<Ast>),
Add(Vec<Ast>),
Fn(Type, Vec<(String, Type)>, Vec<Ast>... | {
Type::Var(TRef::new())
} | identifier_body |
types.rs | use read::Sexp;
use std::rc::Rc;
use std::cell::{RefCell, Ref};
use std::collections::HashMap;
use itertools::*;
#[derive(PartialEq, Clone, Debug)]
pub struct TRef(Rc<RefCell<Option<Type>>>);
impl TRef {
fn new() -> Self {
TRef(Rc::new(RefCell::new(None)))
}
fn get(&self) -> Ref<Option<Type>> {... | IfElse(Box<Ast>, Box<Ast>, Box<Ast>),
If(Box<Ast>, Box<Ast>),
Add(Vec<Ast>),
Fn(Type, Vec<(String, Type)>, Vec<Ast>),
}
fn deref_typ(t: Type) -> Type {
match t {
Type::Fun(t1s, t2) => {
Type::Fun(t1s.into_iter().map(deref_typ).collect(),
Box::new(deref_typ(... | random_line_split | |
types.rs |
use read::Sexp;
use std::rc::Rc;
use std::cell::{RefCell, Ref};
use std::collections::HashMap;
use itertools::*;
#[derive(PartialEq, Clone, Debug)]
pub struct TRef(Rc<RefCell<Option<Type>>>);
impl TRef {
fn new() -> Self {
TRef(Rc::new(RefCell::new(None)))
}
fn get(&self) -> Ref<Option<Type>> ... | (env: &mut InferenceEnv, e: &Ast) -> Type {
use self::Ast::*;
match *e {
Unit => Type::Unit,
Bool(_) => Type::Bool,
Int(_) => Type::Int,
Quote(ref ast) => Type::Sexp,
Add(ref es) => {
for e in es {
unify(&Type::Int, &g(env, e)).unwrap();
... | g | identifier_name |
kmain.rs | pub use prelude::*;
use mm::paging;
use super::multiboot;
extern {
static kernel_end: u64;
}
fn print_mem(base: u64, length: u64, mem_type: multiboot::MemType) {
log!("base: 0x{:X}, len: 0x{:X}, type: {:?}",
base,
length,
mem_type);
}
#[lang="start"]
#[no_mangle]
#[allow(unused_varia... |
log!("");
log!("memory map:");
let mboot = multiboot::Multiboot::new(mboot_ptr, paging::phys_to_virt);
mboot.find_memory(print_mem);
// unsafe {
// let pml4t = ::core::slice::from_raw_parts(pml4t_ptr as *const paging::PML4Entry, 512);
// }
hang();
}
fn hang() ->! {
log!("syst... | {
log!("not booted by multiboot!");
log!("expected: 0x{:X}, was: 0x{:X}",
multiboot::SIGNATURE_RAX,
mboot_sig);
hang();
} | conditional_block |
kmain.rs | pub use prelude::*;
use mm::paging;
use super::multiboot;
extern {
static kernel_end: u64;
}
fn print_mem(base: u64, length: u64, mem_type: multiboot::MemType) {
log!("base: 0x{:X}, len: 0x{:X}, type: {:?}",
base,
length,
mem_type);
}
#[lang="start"]
#[no_mangle]
#[allow(unused_varia... | {
log!("system hangs now");
loop {}
} | identifier_body | |
kmain.rs | pub use prelude::*;
use mm::paging;
use super::multiboot;
extern {
static kernel_end: u64;
}
fn print_mem(base: u64, length: u64, mem_type: multiboot::MemType) {
log!("base: 0x{:X}, len: 0x{:X}, type: {:?}",
base,
length,
mem_type);
}
#[lang="start"]
#[no_mangle]
#[allow(unused_varia... | (mboot_sig: u64, mboot_ptr: u64, pml4t_ptr: u64) ->! {
log!("Hello World, this is kernel");
log!("Hello {0}, with println parameter \"{0}\"", "World");
log!("kernel base address 0x{:X}", paging::KERNEL_BASE);
log!("kernel ends at 0x{:X}", kernel_end);
if multiboot::SIGNATURE_RAX!= mboot_sig {... | kmain | identifier_name |
kmain.rs | use super::multiboot;
extern {
static kernel_end: u64;
}
fn print_mem(base: u64, length: u64, mem_type: multiboot::MemType) {
log!("base: 0x{:X}, len: 0x{:X}, type: {:?}",
base,
length,
mem_type);
}
#[lang="start"]
#[no_mangle]
#[allow(unused_variables)]
extern "C" fn kmain(mboot_sig:... | pub use prelude::*;
use mm::paging; | random_line_split | |
background.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Background", inherited=False) %>... | animation_value_type="discrete",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
)}
${helpers.single_keyword(
"background-clip",
"border-box padding-box content-box",
extra_gecko_values="text",
vector=True, extra_prefixes="webkit",
gecko_enum_prefix="StyleGeome... | spec="https://drafts.csswg.org/css-backgrounds/#the-background-attachment", | random_line_split |
test_assert.rs | #![feature(plugin, custom_attribute)]
#![plugin(rustproof)]
#![allow(dead_code)]
#![allow(unused_attributes)]
fn main() { }
// Should be valid
#[condition(pre="x: i32 == 10i32", post="true")]
fn valid_simple_assertion(x: i32) {
assert!(x > 0);
} | #[condition(pre="x: i32 == 10i32", post="true")]
fn invalid_simple_assertion(x: i32) {
assert!(x < 10);
}
//FIXME: This portion doesn't work currently.
/*
// Should be valid
#[condition(pre="x: i32 == 10i32", post="true")]
fn valid_simple_assertion_eq(x: i32) {
assert_eq!(x, 10);
}
// Should be invalid
#[con... |
// Should be invalid | random_line_split |
test_assert.rs | #![feature(plugin, custom_attribute)]
#![plugin(rustproof)]
#![allow(dead_code)]
#![allow(unused_attributes)]
fn main() { }
// Should be valid
#[condition(pre="x: i32 == 10i32", post="true")]
fn | (x: i32) {
assert!(x > 0);
}
// Should be invalid
#[condition(pre="x: i32 == 10i32", post="true")]
fn invalid_simple_assertion(x: i32) {
assert!(x < 10);
}
//FIXME: This portion doesn't work currently.
/*
// Should be valid
#[condition(pre="x: i32 == 10i32", post="true")]
fn valid_simple_assertion_eq(x: i32)... | valid_simple_assertion | identifier_name |
test_assert.rs | #![feature(plugin, custom_attribute)]
#![plugin(rustproof)]
#![allow(dead_code)]
#![allow(unused_attributes)]
fn main() |
// Should be valid
#[condition(pre="x: i32 == 10i32", post="true")]
fn valid_simple_assertion(x: i32) {
assert!(x > 0);
}
// Should be invalid
#[condition(pre="x: i32 == 10i32", post="true")]
fn invalid_simple_assertion(x: i32) {
assert!(x < 10);
}
//FIXME: This portion doesn't work currently.
/*
// Should... | { } | identifier_body |
collection.rs | extern crate rayon;
extern crate serde_json;
use self::rayon::prelude::*;
use self::serde_json::Value as Json;
use std::fmt;
use error::IngestResult;
use error::IngestError;
use objects::import::Importable;
use objects::reference::Ref;
use objects::utils;
use runtime::Runtime;
use types::{ImportResult, StorageEngine... | let json_chunks = json.as_object()
.and_then(|map| Some((map.get("data"), map.get("links"), map.get("meta"))));
match json_chunks {
Some((Some(data), Some(links), Some(meta))) => {
let pagination_data = meta.as_object().and_then(|meta_map| {
me... | .unwrap_or((0, 1))
}
fn from_json(json: &Json) -> IngestResult<Collection> { | random_line_split |
collection.rs | extern crate rayon;
extern crate serde_json;
use self::rayon::prelude::*;
use self::serde_json::Value as Json;
use std::fmt;
use error::IngestResult;
use error::IngestError;
use objects::import::Importable;
use objects::reference::Ref;
use objects::utils;
use runtime::Runtime;
use types::{ImportResult, StorageEngine... | <S: ThreadedAPI>(&self, api: &S, url: &str) -> IngestResult<Collection> {
utils::parse_response(api.url(url)).and_then(|json| Collection::from_json(&json))
}
fn import_page<T: StorageEngine, S: ThreadedAPI>(
&self,
runtime: &Runtime<T, S>,
follow_refs: bool,
since: i64,
... | get_collection | identifier_name |
collection.rs | extern crate rayon;
extern crate serde_json;
use self::rayon::prelude::*;
use self::serde_json::Value as Json;
use std::fmt;
use error::IngestResult;
use error::IngestError;
use objects::import::Importable;
use objects::reference::Ref;
use objects::utils;
use runtime::Runtime;
use types::{ImportResult, StorageEngine... |
}
impl Importable for Collection {
fn import<T: StorageEngine, S: ThreadedAPI>(
&self,
runtime: &Runtime<T, S>,
follow_refs: bool,
since: i64,
) -> ImportResult {
let num_pages = (self.total as f64 / self.page_size as f64).ceil() as usize + 1;
self.links
... | {
self.page
.par_iter()
.map(|item| item.import(runtime, follow_refs, since))
.reduce(|| (0, 0), |(p1, f1), (p2, f2)| (p1 + p2, f1 + f2))
} | identifier_body |
issue-3904.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... |
fn exit(print: ErrPrinter, prog: &str, arg: &str) {
print(prog, arg);
}
struct X<'a> {
err: ErrPrinter<'a>
}
impl<'a> X<'a> {
pub fn boom(self) {
exit(self.err, "prog", "arg");
}
}
pub fn main(){
let val = X {
err: example_err,
};
val.boom();
}
| {
println!("{}: {}", prog, arg)
} | identifier_body |
issue-3904.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... | (prog: &str, arg: &str) {
println!("{}: {}", prog, arg)
}
fn exit(print: ErrPrinter, prog: &str, arg: &str) {
print(prog, arg);
}
struct X<'a> {
err: ErrPrinter<'a>
}
impl<'a> X<'a> {
pub fn boom(self) {
exit(self.err, "prog", "arg");
}
}
pub fn main(){
let val = X {
err: exa... | example_err | identifier_name |
issue-3904.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... | } | val.boom(); | random_line_split |
alloc.rs | #![no_std]
#![feature(alloc)]
extern crate cortex_m;
extern crate stm32f0_hal as hal;
#[macro_use(interrupt)]
extern crate stm32f0x2;
extern crate alloc;
use alloc::Vec;
use stm32f0x2::EXTI;
use hal::{gpio, rcc};
static mut V: Option<Vec<u8>> = None;
fn main() {
hal::allocator::setup(5000);
unsafe {
... |
}
})
}
| {
let l = v.len();
v.push(l as u8);
} | conditional_block |
alloc.rs | #![no_std]
#![feature(alloc)]
extern crate cortex_m;
extern crate stm32f0_hal as hal;
#[macro_use(interrupt)]
extern crate stm32f0x2;
extern crate alloc;
use alloc::Vec;
use stm32f0x2::EXTI;
use hal::{gpio, rcc};
static mut V: Option<Vec<u8>> = None;
fn | () {
hal::allocator::setup(5000);
unsafe {
V = Some(Vec::new());
}
let p0 = gpio::Input::setup(gpio::Pin::PA0);
rcc::init(); // Full Speed 48Mhz
p0.init_interrupt();
loop {}
}
interrupt!(EXTI0_1, pa0_cb);
fn pa0_cb() {
cortex_m::interrupt::free(|cs| {
let exti = EXTI.b... | main | identifier_name |
alloc.rs | #![no_std]
#![feature(alloc)]
extern crate cortex_m;
extern crate stm32f0_hal as hal;
#[macro_use(interrupt)]
extern crate stm32f0x2;
extern crate alloc;
use alloc::Vec;
use stm32f0x2::EXTI;
use hal::{gpio, rcc};
static mut V: Option<Vec<u8>> = None;
fn main() {
hal::allocator::setup(5000);
unsafe {
... | }
})
} | } | random_line_split |
alloc.rs | #![no_std]
#![feature(alloc)]
extern crate cortex_m;
extern crate stm32f0_hal as hal;
#[macro_use(interrupt)]
extern crate stm32f0x2;
extern crate alloc;
use alloc::Vec;
use stm32f0x2::EXTI;
use hal::{gpio, rcc};
static mut V: Option<Vec<u8>> = None;
fn main() {
hal::allocator::setup(5000);
unsafe {
... | {
cortex_m::interrupt::free(|cs| {
let exti = EXTI.borrow(cs);
exti.pr.write(|w| w.pif0().set_bit());
unsafe {
if let Some(ref mut v) = V {
let l = v.len();
v.push(l as u8);
}
}
})
} | identifier_body | |
lib.rs | #![deny(
missing_debug_implementations,
missing_copy_implementations,
warnings,
trivial_numeric_casts,
unstable_features,
unused,
future_incompatible
)]
#![allow(clippy::upper_case_acronyms)]
pub mod clock;
pub mod db;
pub mod pg;
pub mod server_id;
pub mod test;
pub mod types;
use hybrid_... | let rows = pool.get().unwrap().query("select 1 as id from test").unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows.get(0).get::<u32, &str>("id"), 1);
}
#[test]
fn test_insert() {
let mut conn = super::db::TestConnection::new();
conn.add_test_execute(r"insert into ... | conn.add_test_query("select 1 as id from test", vec![row]);
let pool = super::db::Pool::TestPool(conn); | random_line_split |
lib.rs | #![deny(
missing_debug_implementations,
missing_copy_implementations,
warnings,
trivial_numeric_casts,
unstable_features,
unused,
future_incompatible
)]
#![allow(clippy::upper_case_acronyms)]
pub mod clock;
pub mod db;
pub mod pg;
pub mod server_id;
pub mod test;
pub mod types;
use hybrid_... |
#[cfg(test)]
mod tests {
#[test]
fn test_select() {
let mut conn = super::db::TestConnection::new();
let mut row = super::db::TestRow::new();
row.insert("id", 1);
conn.add_test_query("select 1 as id from test", vec![row]);
let pool = super::db::Pool::TestPool(conn);
... | {
let mut raw_timestamp: Vec<u8> = Vec::new();
timestamp.write_bytes(&mut raw_timestamp)?;
Ok(db::HexSlice::new(raw_timestamp))
} | identifier_body |
lib.rs | #![deny(
missing_debug_implementations,
missing_copy_implementations,
warnings,
trivial_numeric_casts,
unstable_features,
unused,
future_incompatible
)]
#![allow(clippy::upper_case_acronyms)]
pub mod clock;
pub mod db;
pub mod pg;
pub mod server_id;
pub mod test;
pub mod types;
use hybrid_... | () {
let mut conn = super::db::TestConnection::new();
conn.add_test_execute(r"insert into test \(id\) values\(1\)", 1);
let pool = super::db::Pool::TestPool(conn);
let res = pool.get().unwrap().execute("insert into test (id) values(1)").unwrap();
assert_eq!(res, 1);
}
}
| test_insert | identifier_name |
pat_util.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 ... | // except according to those terms.
use hir::def::Def;
use hir::def_id::DefId;
use hir::{self, HirId, PatKind};
use syntax::ast;
use syntax_pos::Span;
use std::iter::{Enumerate, ExactSizeIterator};
pub struct EnumerateAndAdjust<I> {
enumerate: Enumerate<I>,
gap_pos: usize,
gap_len: usize,
}
impl<I> Iter... | random_line_split | |
pat_util.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 ... | (&self) -> Option<hir::Mutability> {
// FIXME(tschottdorf): contains_explicit_ref_binding() must be removed
// for #42640 (default match binding modes).
//
// See #44848.
self.pats.iter()
.filter_map(|pat| pat.contains_explicit_ref_binding())
.max_... | contains_explicit_ref_binding | identifier_name |
pat_util.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 ... |
pub fn simple_ident(&self) -> Option<ast::Ident> {
match self.node {
PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, None) |
PatKind::Binding(hir::BindingAnnotation::Mutable, _, ident, None) => Some(ident),
_ => None,
}
}
/// Return vari... | {
let mut contains_bindings = false;
self.walk(|p| {
match p.node {
PatKind::Binding(..) | PatKind::Wild => {
contains_bindings = true;
false // there's at least one binding/wildcard, can short circuit now.
}
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.