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 |
|---|---|---|---|---|
fixed_bug_long_thin_box_one_shot_manifold3.rs | /*!
* # Expected behaviour:
* The box stands vertically until it falls asleep.
* The box should not fall (horizontally) on the ground.
* The box should not traverse the ground.
*
* # Symptoms:
* The long, thin, box fails to collide with the plane: it just ignores it.
*
* # Cause: | * contact surface is small, all contacts will be invalidated whenever the incremental contact
* manifold will get a new point from the one-shot generator.
*
* # Solution:
* Rotate the object wrt the contact center, not wrt the object center.
*
* # Limitations of the solution:
* This will create only a three-poi... | * The one shot contact manifold generator was incorrect in this case. This generator rotated the
* object wrt its center to sample the contact manifold. If the object is long and the theoretical | random_line_split |
fixed_bug_long_thin_box_one_shot_manifold3.rs | /*!
* # Expected behaviour:
* The box stands vertically until it falls asleep.
* The box should not fall (horizontally) on the ground.
* The box should not traverse the ground.
*
* # Symptoms:
* The long, thin, box fails to collide with the plane: it just ignores it.
*
* # Cause:
* The one shot contact manifo... | () {
/*
* World
*/
let mut world = World::new();
world.set_gravity(Vector3::new(r!(0.0), r!(-9.81), r!(0.0)));
/*
* Plane
*/
let ground_shape = ShapeHandle::new(Plane::new(Vector3::y_axis()));
ColliderDesc::new(ground_shape).build(&mut world);
/*
* Create the box
... | main | identifier_name |
button.rs | //! Easy use of buttons.
use peripheral;
/// The user button.
pub static BUTTONS: [Button; 1] = [Button { i: 0 }];
/// A single button.
pub struct Button {
i: u8,
}
impl Button {
/// Read the state of the button.
pub fn pressed(&self) -> bool {
let idr = &peripheral::gpioa().idr;
| match self.i {
0 => idr.read().idr0(),
_ => false
}
}
}
/// Initializes the necessary stuff to enable the button.
///
/// # Safety
///
/// - Must be called once
/// - Must be called in an interrupt-free environment
pub unsafe fn init() {
let rcc = peripheral::rcc_mut();
... | random_line_split | |
button.rs | //! Easy use of buttons.
use peripheral;
/// The user button.
pub static BUTTONS: [Button; 1] = [Button { i: 0 }];
/// A single button.
pub struct | {
i: u8,
}
impl Button {
/// Read the state of the button.
pub fn pressed(&self) -> bool {
let idr = &peripheral::gpioa().idr;
match self.i {
0 => idr.read().idr0(),
_ => false
}
}
}
/// Initializes the necessary stuff to enable the button.
///
/// # S... | Button | identifier_name |
js.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/. */
//! Smart pointers for the JS-managed DOM objects.
//!
//! The DOM is made up of Rust types whose lifetime is enti... | <'a>(&'a self) -> &'a Reflector {
unsafe {
(*self.unsafe_get()).reflector()
}
}
}
impl<T: Reflectable> JS<T> {
/// Returns an unsafe pointer to the interior of this JS object without touching the borrow
/// flags. This is the only method that be safely accessed from layout. (The... | reflector | identifier_name |
js.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/. */
//! Smart pointers for the JS-managed DOM objects.
//!
//! The DOM is made up of Rust types whose lifetime is enti... |
}
/// Root a rootable `Option<Option>` type (used for `Option<Option<JS<T>>>`)
pub trait OptionalOptionalRootedRootable<T> {
fn root<'a, 'b>(&self) -> Option<Option<Root<'a, 'b, T>>>;
}
impl<T: Reflectable> OptionalOptionalRootedRootable<T> for Option<Option<JS<T>>> {
fn root<'a, 'b>(&self) -> Option<Option<... | {
self.as_ref().map(|inner| inner.root())
} | identifier_body |
js.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/. */
//! Smart pointers for the JS-managed DOM objects.
//!
//! The DOM is made up of Rust types whose lifetime is enti... | }
}
}
impl<T: Reflectable> JS<T> {
/// Create a new JS-owned value wrapped from a raw Rust pointer.
pub unsafe fn from_raw(raw: *const T) -> JS<T> {
JS {
ptr: raw
}
}
/// Root this JS-owned value to prevent its collection as garbage.
pub fn root<'a, 'b>(&se... | ptr: addr as *const Worker | random_line_split |
column_family.rs | // Copyright 2020 Tyler Neely
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writ... | name: name.into(),
options,
}
}
}
/// An opaque type used to represent a column family. Returned from some functions, and used
/// in others
pub struct ColumnFamily {
pub(crate) inner: *mut ffi::rocksdb_column_family_handle_t,
}
/// A specialized opaque type used to represent a... | Self { | random_line_split |
column_family.rs | // Copyright 2020 Tyler Neely
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writ... | {
pub(crate) name: String,
pub(crate) options: Options,
}
impl ColumnFamilyDescriptor {
// Create a new column family descriptor with the specified name and options.
pub fn new<S>(name: S, options: Options) -> Self
where
S: Into<String>,
{
Self {
name: name.into(),
... | ColumnFamilyDescriptor | identifier_name |
issue-662-cannot-find-T-in-this-scope.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct RefPtr<T> {
pub a: T,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>,
}
impl<T> Default... | () -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct nsMainThreadPtrHolder<T> {
pub a: T,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>,
}
impl<T> Default for nsMainThreadPtrHolder<T> {
fn default() -> Self {
unsafe... | default | identifier_name |
issue-662-cannot-find-T-in-this-scope.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct RefPtr<T> { | }
impl<T> Default for RefPtr<T> {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct nsMainThreadPtrHolder<T> {
pub a: T,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>,
}
impl<T> Default for nsMainThreadPtrHolde... | pub a: T,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>, | random_line_split |
thread.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use protocol::JsonPacketStream;
use rustc_serialize::json;
... | struct ReconfigureReply {
from: String
}
pub struct ThreadActor {
name: String,
}
impl ThreadActor {
pub fn new(name: String) -> ThreadActor {
ThreadActor {
name: name,
}
}
}
impl Actor for ThreadActor {
fn name(&self) -> String {
self.name.clone()
}
f... | from: String,
__type__: String,
}
#[derive(RustcEncodable)] | random_line_split |
thread.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use protocol::JsonPacketStream;
use rustc_serialize::json;
... | ,
"reconfigure" => {
stream.write_json_packet(&ReconfigureReply { from: self.name() });
ActorMessageStatus::Processed
}
_ => ActorMessageStatus::Ignored,
})
}
}
| {
let msg = ThreadResumedReply {
from: self.name(),
__type__: "resumed".to_owned(),
};
stream.write_json_packet(&msg);
ActorMessageStatus::Processed
} | conditional_block |
thread.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use protocol::JsonPacketStream;
use rustc_serialize::json;
... | (&self,
registry: &ActorRegistry,
msg_type: &str,
_msg: &json::Object,
stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"attach" => {
let msg = ThreadAttachedReply {... | handle_message | identifier_name |
main.rs | use gtk::prelude::*;
use relm::Widget;
use relm_derive::{widget, Msg};
/// The messages sent to the `Win` widget.
#[derive(Msg)]
pub enum Msg {
Increment,
Quit,
}
/// The model the `Win` widget uses.
/// This is current count of the counter.
pub struct Model {
counter: u64,
}
/// The widget containing th... | },
delete_event(_, _) => (Msg::Quit, Inhibit(false)),
}
}
}
fn main() {
// Run the application.
Win::run(()).expect("Win::run failed");
} | random_line_split | |
main.rs | use gtk::prelude::*;
use relm::Widget;
use relm_derive::{widget, Msg};
/// The messages sent to the `Win` widget.
#[derive(Msg)]
pub enum Msg {
Increment,
Quit,
}
/// The model the `Win` widget uses.
/// This is current count of the counter.
pub struct Model {
counter: u64,
}
/// The widget containing th... |
// Quit the application
Msg::Quit => gtk::main_quit(),
}
}
// This macro builds the application.
view! {
gtk::Window {
gtk::Box {
// The label showing the text.
gtk::Label {
// The text in the label. Wi... | {
self.model.counter += 1;
} | conditional_block |
main.rs | use gtk::prelude::*;
use relm::Widget;
use relm_derive::{widget, Msg};
/// The messages sent to the `Win` widget.
#[derive(Msg)]
pub enum Msg {
Increment,
Quit,
}
/// The model the `Win` widget uses.
/// This is current count of the counter.
pub struct Model {
counter: u64,
}
/// The widget containing th... | () {
// Run the application.
Win::run(()).expect("Win::run failed");
}
| main | identifier_name |
db.rs | use super::{
entities::*,
error::RepoError,
repositories::*,
util::{
geo::{MapBbox, MapPoint},
time::{Timestamp, TimestampMs},
},
};
use anyhow::Result as Fallible;
type Result<T> = std::result::Result<T, RepoError>;
#[derive(Clone, Debug)]
pub struct MostPopularTagsParams {
p... | // status matches one of the given values
pub status: Option<Vec<ReviewStatus>>,
pub include_bbox: Option<MapBbox>,
pub exclude_bbox: Option<MapBbox>,
pub categories: Vec<&'a str>,
pub ids: Vec<&'b str>,
pub hash_tags: Vec<String>,
pub text_tags: Vec<String>,
pub text: Optio... | random_line_split | |
db.rs | use super::{
entities::*,
error::RepoError,
repositories::*,
util::{
geo::{MapBbox, MapPoint},
time::{Timestamp, TimestampMs},
},
};
use anyhow::Result as Fallible;
type Result<T> = std::result::Result<T, RepoError>;
#[derive(Clone, Debug)]
pub struct MostPopularTagsParams {
p... | <'a, 'b> {
// status = None: Don't filter by review status, i.e. return all entries
// independent of their current review status
// status = Some(empty vector): Exclude all invisible/inexistent entries, i.e.
// return only visible/existent entries
// status = Some(non-empty vector... | IndexQuery | identifier_name |
msgsend-pipes.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 ... | }
responses.send(count);
//println!("server exiting");
}
fn run(args: &[~str]) {
let (to_parent, from_child) = channel();
let size = from_str::<uint>(args[1]).unwrap();
let workers = from_str::<uint>(args[2]).unwrap();
let num_bytes = 100;
let start = time::precise_time_s();
let mu... | random_line_split | |
msgsend-pipes.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 ... |
}
}
responses.send(count);
//println!("server exiting");
}
fn run(args: &[~str]) {
let (to_parent, from_child) = channel();
let size = from_str::<uint>(args[1]).unwrap();
let workers = from_str::<uint>(args[2]).unwrap();
let num_bytes = 100;
let start = time::precise_time_s();... | { } | conditional_block |
msgsend-pipes.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 ... |
fn run(args: &[~str]) {
let (to_parent, from_child) = channel();
let size = from_str::<uint>(args[1]).unwrap();
let workers = from_str::<uint>(args[2]).unwrap();
let num_bytes = 100;
let start = time::precise_time_s();
let mut worker_results = Vec::new();
let from_parent = if workers == 1... | {
let mut count: uint = 0;
let mut done = false;
while !done {
match requests.recv_opt() {
Ok(get_count) => { responses.send(count.clone()); }
Ok(bytes(b)) => {
//println!("server: received {:?} bytes", b);
count += b;
}
Err(..) => { do... | identifier_body |
msgsend-pipes.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 ... | (requests: &Receiver<request>, responses: &Sender<uint>) {
let mut count: uint = 0;
let mut done = false;
while!done {
match requests.recv_opt() {
Ok(get_count) => { responses.send(count.clone()); }
Ok(bytes(b)) => {
//println!("server: received {:?} bytes", b);
... | server | identifier_name |
util.rs | /* Copyright 2013 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writi... | {
// nothing yet
// update as insert operation takes more options;
// intended for non-mask-type options
}
pub enum QUERY_FLAG {
// bit 0 reserved
CUR_TAILABLE = 1 << 1,
SLAVE_OK = 1 << 2,
OPLOG_REPLAY = 1 << 3, // driver should not set
NO_CUR_TIMEOUT = 1 << 4,
AWAIT_... | INSERT_OPTION | identifier_name |
util.rs | /* Copyright 2013 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writi... | }
impl TagSet {
pub fn new(tag_list : &[(&str, &str)]) -> TagSet {
let mut tags = TreeMap::new();
for tag_list.iter().advance |&(field, val)| {
tags.insert(field.to_owned(), val.to_owned());
}
TagSet { tags : tags }
}
pub fn get_ref<'a>(&'a self, field : ~str) ->... | }
Ok(ts)
} | random_line_split |
font.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 geom::{Point2D, Rect, Size2D};
use std::borrow::ToOwned;
use std::mem;
use std::slice;
use std::rc::Rc;
use st... | pub fonts: SmallVec8<Rc<RefCell<Font>>>,
}
impl FontGroup {
pub fn new(fonts: SmallVec8<Rc<RefCell<Font>>>) -> FontGroup {
FontGroup {
fonts: fonts,
}
}
}
pub struct RunMetrics {
// may be negative due to negative width (i.e., kerning of '.' in 'P.T.')
pub advance_width... | pub struct FontGroup { | random_line_split |
font.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 geom::{Point2D, Rect, Size2D};
use std::borrow::ToOwned;
use std::mem;
use std::slice;
use std::rc::Rc;
use st... | ;
debug!("{} font table[{}] with family={}, face={}",
status, tag.tag_to_str(),
self.handle.family_name(), self.handle.face_name());
return result;
}
#[inline]
pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> {
let codepoint = match self.... | { "Didn't find" } | conditional_block |
font.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 geom::{Point2D, Rect, Size2D};
use std::borrow::ToOwned;
use std::mem;
use std::slice;
use std::rc::Rc;
use st... | (advance: Au, ascent: Au, descent: Au) -> RunMetrics {
let bounds = Rect(Point2D(Au(0), -ascent),
Size2D(advance, ascent + descent));
// TODO(Issue #125): support loose and tight bounding boxes; using the
// ascent+descent and advance is sometimes too generous and
... | new | identifier_name |
font.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 geom::{Point2D, Rect, Size2D};
use std::borrow::ToOwned;
use std::mem;
use std::slice;
use std::rc::Rc;
use st... |
pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel {
let handle = &self.handle;
self.glyph_advance_cache.find_or_create(&glyph, |glyph| {
match handle.glyph_h_advance(*glyph) {
Some(adv) => adv,
None => 10f64 as FractionalPixel // FIXME... | {
self.handle.glyph_h_kerning(first_glyph, second_glyph)
} | identifier_body |
rename-directory.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... |
pub fn main() { rename_directory() }
| {
let tmpdir = TempDir::new("rename_directory").ok().expect("rename_directory failed");
let tmpdir = tmpdir.path();
let old_path = tmpdir.join("foo/bar/baz");
fs::create_dir_all(&old_path).unwrap();
let test_file = &old_path.join("temp.txt");
File::create(test_file).unwrap();
let new_path ... | identifier_body |
rename-directory.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... | pub fn main() { rename_directory() } | random_line_split | |
rename-directory.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... | () { rename_directory() }
| main | identifier_name |
enum-discrim-autosizing.rs | // run-pass
#![allow(dead_code)]
#![allow(overflowing_literals)]
use std::mem::size_of;
enum Ei8 {
Ai8 = -1,
Bi8 = 0
}
enum Eu8 {
Au8 = 0,
Bu8 = 0x80
}
enum Ei16 {
Ai16 = -1,
Bi16 = 0x80
}
enum Eu16 {
Au16 = 0,
Bu16 = 0x8000
}
enum Ei32 {
Ai32 = -1,
Bi32 = 0x8000
}
enum | {
Au32 = 0,
Bu32 = 0x8000_0000
}
enum Ei64 {
Ai64 = -1,
Bi64 = 0x8000_0000
}
pub fn main() {
assert_eq!(size_of::<Ei8>(), 1);
assert_eq!(size_of::<Eu8>(), 1);
assert_eq!(size_of::<Ei16>(), 2);
assert_eq!(size_of::<Eu16>(), 2);
assert_eq!(size_of::<Ei32>(), 4);
assert_eq!(size_... | Eu32 | identifier_name |
enum-discrim-autosizing.rs | // run-pass
#![allow(dead_code)]
#![allow(overflowing_literals)]
use std::mem::size_of;
enum Ei8 {
Ai8 = -1,
Bi8 = 0
}
enum Eu8 {
Au8 = 0,
Bu8 = 0x80
}
enum Ei16 {
Ai16 = -1,
Bi16 = 0x80
}
enum Eu16 {
Au16 = 0,
Bu16 = 0x8000
} |
enum Ei32 {
Ai32 = -1,
Bi32 = 0x8000
}
enum Eu32 {
Au32 = 0,
Bu32 = 0x8000_0000
}
enum Ei64 {
Ai64 = -1,
Bi64 = 0x8000_0000
}
pub fn main() {
assert_eq!(size_of::<Ei8>(), 1);
assert_eq!(size_of::<Eu8>(), 1);
assert_eq!(size_of::<Ei16>(), 2);
assert_eq!(size_of::<Eu16>(), 2);
... | random_line_split | |
mod.rs | use rand::{thread_rng, Rng};
pub mod model;
mod grid;
pub use self::grid::Grid;
pub use self::model::Model;
// A direction that the snake head can travel in
#[derive(Clone, Copy, PartialEq)]
pub enum Direction {
Up,
Down,
Left,
Right,
}
impl Direction {
pub fn is_opposite_direction(&self, other:... | (&self) -> bool {
match *self {
GridCell::Food => true,
_ => false,
}
}
}
// A cell locaiton in the arena
#[derive(Clone, Copy)]
pub struct CellLocation {
x: usize,
y: usize,
}
impl CellLocation {
pub fn get_neighbour(&self, direction: Direction) -> CellLocation... | is_food | identifier_name |
mod.rs | use rand::{thread_rng, Rng};
pub mod model;
mod grid;
pub use self::grid::Grid;
pub use self::model::Model;
// A direction that the snake head can travel in
#[derive(Clone, Copy, PartialEq)]
pub enum Direction {
Up,
Down,
Left,
Right,
}
impl Direction {
pub fn is_opposite_direction(&self, other:... | #[derive(Clone)]
pub enum GridCell {
Empty,
Food,
SnakePart,
}
impl GridCell {
pub fn change_cell(&mut self, value: GridCell) {
*self = value;
}
pub fn is_empty(&self) -> bool {
match *self {
GridCell::Empty => true,
_ => false,
}
}
pub ... | }
}
// A cell in the grid is either empty, occupied by a snake part (with a direction the
// tail should continue in when it hits it), or contains a piece of food. | random_line_split |
s3.rs | //! This implements S3 sync for the symbolserver.
use std::result::Result as StdResult;
use std::env;
use std::io::{Read, Cursor};
use rusoto::{ProvideAwsCredentials, AwsCredentials, CredentialsError,
ChainProvider};
use rusoto::s3::{S3Client, ListObjectsRequest, GetObjectRequest, Object,
... | (&self) -> &str {
self.url.host_str().unwrap()
}
fn bucket_prefix(&self) -> String {
let path = self.url.path().trim_matches('/');
if path.len() == 0 {
"".into()
} else {
format!("{}/", path)
}
}
fn object_to_remote_sdk(&self, obj: Object... | bucket_name | identifier_name |
s3.rs | //! This implements S3 sync for the symbolserver.
use std::result::Result as StdResult;
use std::env;
use std::io::{Read, Cursor};
use rusoto::{ProvideAwsCredentials, AwsCredentials, CredentialsError,
ChainProvider};
use rusoto::s3::{S3Client, ListObjectsRequest, GetObjectRequest, Object,
... |
let mut rv = vec![];
for obj in out.contents.unwrap_or_else(|| vec![]) {
if let Some(remote_sdk) = self.object_to_remote_sdk(obj) {
rv.push(remote_sdk);
}
}
Ok(rv)
}
/// Downloads a given remote SDK and returns a reader to the
/// by... | return Err(err).chain_err(|| "Failed to fetch SDKs from S3")?;
}
}; | random_line_split |
s3.rs | //! This implements S3 sync for the symbolserver.
use std::result::Result as StdResult;
use std::env;
use std::io::{Read, Cursor};
use rusoto::{ProvideAwsCredentials, AwsCredentials, CredentialsError,
ChainProvider};
use rusoto::s3::{S3Client, ListObjectsRequest, GetObjectRequest, Object,
... |
}
fn filename_from_key(key: &str) -> Option<&str> {
key.rsplitn(2, '/').next()
}
fn unquote_etag(quoted_etag: Option<String>) -> Option<String> {
quoted_etag.and_then(|etag| {
if etag.len() > 2 && &etag[..1] == "\"" && &etag[etag.len() - 1..] == "\"" {
Some(etag[1..etag.len() - 1].into())... | {
if_chain! {
if let Some(ref access_key) = self.access_key;
if let Some(ref secret_key) = self.secret_key;
then {
Ok(AwsCredentials::new(access_key.to_string(),
secret_key.to_string(),
... | identifier_body |
mod.rs | // include/uapi/asm-generic/socket.h
// arch/alpha/include/uapi/asm/socket.h
// tools/include/uapi/asm-generic/socket.h
// arch/mips/include/uapi/asm/socket.h
pub const SOL_SOCKET: ::c_int = 1;
// Defined in unix/linux_like/mod.rs
// pub const SO_DEBUG: ::c_int = 1;
pub const SO_REUSEADDR: ::c_int = 2;
pub const SO_TY... | pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23;
pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24;
pub const SO_BINDTODEVICE: ::c_int = 25;
pub const SO_ATTACH_FILTER: ::c_int = 26;
pub const SO_DETACH_FILTER: ::c_int = 27;
pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER;
pub const SO_PEERNAME: ::c_i... | // pub const SO_SNDTIMEO_OLD: ::c_int = 21;
pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; | random_line_split |
tests.rs | // Copyright (c) 2016-2021 Snowplow Analytics Ltd. All rights reserved.
//
// This program is licensed to you under the Apache License Version 2.0, and
// you may not use this file except in compliance with the Apache License
// Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
// http://www.apac... | assert_eq!(false, super::is_proper_sub_tree(&dag, child2_idx));
assert_eq!(true, super::is_proper_sub_tree(&dag, root_idx));
} | dag.add_edge(child1_idx, grandchild_idx, ()).ok().unwrap();
| random_line_split |
tests.rs | // Copyright (c) 2016-2021 Snowplow Analytics Ltd. All rights reserved.
//
// This program is licensed to you under the Apache License Version 2.0, and
// you may not use this file except in compliance with the Apache License
// Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
// http://www.apac... | () {
let mut dag = Dag::<Task, ()>::new();
let parent = make_task("root", &vec![]);
let idx = dag.add_node(parent);
let task_child1 = make_task("child1", &vec![]);
dag.add_child(idx, (), task_child1);
let task_child2 = make_task("child2", &vec![]);
let (_, child2) = dag.add_child(idx, (),... | recursive_find_ok | identifier_name |
tests.rs | // Copyright (c) 2016-2021 Snowplow Analytics Ltd. All rights reserved.
//
// This program is licensed to you under the Apache License Version 2.0, and
// you may not use this file except in compliance with the Apache License
// Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
// http://www.apac... |
}
#[test]
fn get_tasks_in_order_basic() {
let mut dag = Dag::<Task, ()>::new();
let parent = make_task("root", &vec![]);
let root_idx: NodeIndex = dag.add_node(parent);
let child1 = make_task("child1", &vec![]);
let child2 = make_task("child2", &vec![]);
dag.add_child(root_idx, (), child1... | {
panic!("couldn't find value");
} | conditional_block |
tests.rs | // Copyright (c) 2016-2021 Snowplow Analytics Ltd. All rights reserved.
//
// This program is licensed to you under the Apache License Version 2.0, and
// you may not use this file except in compliance with the Apache License
// Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
// http://www.apac... | super::get_tasks_in_order(&dag, &vec![root_idx], &mut actual);
compare_tasks(expected, actual);
}
#[test]
fn check_valid_subtree() {
// root <-- start here
// / \
// child1 child2
// \
// grandchild
//
let mut dag = Dag::<Task, ()>::new();
let parent = make_task("root", &... | {
let mut dag = Dag::<Task, ()>::new();
let parent = make_task("root", &vec![]);
let root_idx: NodeIndex = dag.add_node(parent);
let child1 = make_task("child1", &vec![]);
let child2 = make_task("child2", &vec![]);
dag.add_child(root_idx, (), child1);
let (_, child2_idx) = dag.add_child... | identifier_body |
graph500-bfs.rs | // xfail-pretty
// 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
//... | do neighbors.each() |k| {
if is_gray(&colors[*k]) {
color = gray(*k);
false
}
else { true }
};
color
}
gray(parent) => { black(parent) ... | random_line_split | |
graph500-bfs.rs | // xfail-pretty
// 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
//... | (i: node_id, j: node_id, scale: uint, r: @rand::Rng)
-> (node_id, node_id) {
let A = 0.57;
let B = 0.19;
let C = 0.19;
if scale == 0u {
(i, j)
}
else {
let i = i * 2i64;
let j = j * 2i64;
let scale = scale - 1u;
... | choose_edge | identifier_name |
graph500-bfs.rs | // xfail-pretty
// 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
//... |
let mut i = 0;
while par::any(colors, is_gray_factory) {
// Do the BFS.
info!("PBFS iteration %?", i);
i += 1;
let old_len = colors.len();
let color = arc::ARC(colors);
let color_vec = arc::get(&color); // FIXME #3387 requires this temp
colors = do par... | {
let r: ~fn(c: &color) -> bool = is_gray;
r
} | identifier_body |
graph500-bfs.rs | // xfail-pretty
// 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
//... |
};
if!status { return status }
// 2. Each tree edge connects vertices whose BFS levels differ by
// exactly one.
info!(~"Verifying tree edges...");
let status = do tree.alli() |k, parent| {
if *parent!= root && *parent!= -1i64 {
level[*parent] == level[k] - 1
... | {
while parent != root {
if vec::contains(path, &parent) {
status = false;
}
path.push(parent);
parent = tree[parent];
}
// The length of the path back to the root is the current
// leve... | conditional_block |
tlsf.rs | //
// Copyright 2017 yvt, all rights reserved.
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may
// not be copied, modified,or distributed except
// according to those terms.
//
#![feature(test)]
extern crate test;
extern crate unreachable;
extern crate xalloc;
... | #[bench]
fn sys_stack(b: &mut Bencher) {
let mut v = Vec::with_capacity(65536);
b.iter(|| {
for _ in 0..65536 {
v.push(Box::new(1u32));
}
while let Some(_) = v.pop() {}
});
} | }
});
}
| random_line_split |
tlsf.rs | //
// Copyright 2017 yvt, all rights reserved.
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may
// not be copied, modified,or distributed except
// according to those terms.
//
#![feature(test)]
extern crate test;
extern crate unreachable;
extern crate xalloc;
... |
}
for x in v.iter_mut() {
if let Some(x) = x.take() {
sa.dealloc_unchecked(x);
}
}
});
}
#[bench]
fn sys_random(b: &mut Bencher) {
let mut v: Vec<_> = (0..512).map(|_| None).collect();
b.iter(|| {
let mut r = Xorshift32(0x11451419);
... | {
v[i] = Some(sa.alloc(1u32).unchecked_unwrap().0);
} | conditional_block |
tlsf.rs | //
// Copyright 2017 yvt, all rights reserved.
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may
// not be copied, modified,or distributed except
// according to those terms.
//
#![feature(test)]
extern crate test;
extern crate unreachable;
extern crate xalloc;
... | (b: &mut Bencher) {
let mut v: Vec<_> = (0..512).map(|_| None).collect();
b.iter(|| {
let mut r = Xorshift32(0x11451419);
for _ in 0..65536 {
let i = ((r.next() >> 8) & 511) as usize;
if v[i].is_some() {
v[i].take();
} else {
v[... | sys_random | identifier_name |
tlsf.rs | //
// Copyright 2017 yvt, all rights reserved.
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may
// not be copied, modified,or distributed except
// according to those terms.
//
#![feature(test)]
extern crate test;
extern crate unreachable;
extern crate xalloc;
... | {
let mut v = Vec::with_capacity(65536);
b.iter(|| {
for _ in 0..65536 {
v.push(Box::new(1u32));
}
while let Some(_) = v.pop() {}
});
} | identifier_body | |
restrictions.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,
cmt: &mc::cmt_<'tcx>) -> RestrictionResult<'tcx> {
debug!("restrict(cmt={:?})", cmt);
let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
match cmt.cat.clone() {
Categorization::Rvalue(..) => {
// Effectively, rvalues are ... | restrict | identifier_name |
restrictions.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 ... |
}
| {
match result {
RestrictionResult::Safe => RestrictionResult::Safe,
RestrictionResult::SafeIf(base_lp, mut base_vec) => {
let v = LpExtend(base_lp, cmt.mutbl, elem);
let lp = Rc::new(LoanPath::new(v, cmt.ty));
base_vec.push(lp.clone());
... | identifier_body |
restrictions.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 ... |
Categorization::Deref(cmt_base, pk) => {
match pk {
mc::Unique => {
// R-Deref-Send-Pointer
//
// When we borrow the interior of a box, we
// cannot permit the base to be muta... | random_line_split | |
status_reporter.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
errors::{BuildProjectError, Error},
source_for_location, FsSourceReader, SourceReader,
};
use common::Diagno... | error => {
error!("{}", error);
}
}
}
fn print_project_error(&self, error: &BuildProjectError) {
match error {
BuildProjectError::ValidationErrors { errors } => {
for diagnostic in errors {
self.print_diagno... | Error::Cancelled => {
info!("Compilation cancelled due to new changes.");
} | random_line_split |
status_reporter.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
errors::{BuildProjectError, Error},
source_for_location, FsSourceReader, SourceReader,
};
use common::Diagno... | {
source_reader: Box<dyn SourceReader + Send + Sync>,
root_dir: PathBuf,
}
impl ConsoleStatusReporter {
pub fn new(root_dir: PathBuf) -> Self {
Self {
root_dir,
source_reader: Box::new(FsSourceReader),
}
}
}
impl ConsoleStatusReporter {
fn print_error(&self... | ConsoleStatusReporter | identifier_name |
status_reporter.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
errors::{BuildProjectError, Error},
source_for_location, FsSourceReader, SourceReader,
};
use common::Diagno... |
Error::Cancelled => {
info!("Compilation cancelled due to new changes.");
}
error => {
error!("{}", error);
}
}
}
fn print_project_error(&self, error: &BuildProjectError) {
match error {
BuildProjectErr... | {
for error in errors {
self.print_project_error(error);
}
} | conditional_block |
status_reporter.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
errors::{BuildProjectError, Error},
source_for_location, FsSourceReader, SourceReader,
};
use common::Diagno... |
}
impl StatusReporter for ConsoleStatusReporter {
fn build_starts(&self) {}
fn build_completes(&self) {}
fn build_errors(&self, error: &Error) {
self.print_error(error);
if!matches!(error, Error::Cancelled) {
error!("Compilation failed.");
}
}
}
| {
let printer = DiagnosticPrinter::new(|source_location| {
source_for_location(&self.root_dir, source_location, self.source_reader.as_ref())
});
error!("{}", printer.diagnostic_to_string(diagnostic));
} | identifier_body |
explicit-self-generic.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 mut m: Box<_> = box linear_map::<(),()>();
assert_eq!(m.len(), 0);
}
| main | identifier_name |
explicit-self-generic.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 ... |
#[derive(Copy, Clone)]
struct LM { resize_at: usize, size: usize }
enum HashMap<K,V> {
HashMap_(LM, Vec<(K,V)>)
}
fn linear_map<K,V>() -> HashMap<K,V> {
HashMap::HashMap_(LM{
resize_at: 32,
size: 0}, Vec::new())
}
impl<K,V> HashMap<K,V> {
pub fn len(&mut self) -> usize {
match *s... | random_line_split | |
explicit-self-generic.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 main() {
let mut m: Box<_> = box linear_map::<(),()>();
assert_eq!(m.len(), 0);
}
| {
match *self {
HashMap::HashMap_(ref l, _) => l.size
}
} | identifier_body |
bitwise.rs | // -*- rust -*-
// 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
// ... | () {
assert!((-1000 as uint >> 3u == 2305843009213693827u));
}
fn general() {
let mut a: int = 1;
let mut b: int = 2;
a ^= b;
b ^= a;
a = a ^ b;
debug!(a);
debug!(b);
assert!((b == 1));
assert!((a == 2));
assert!((!0xf0 & 0xff == 0xf));
assert!((0xf0 | 0xf == 0xff));
... | target | identifier_name |
bitwise.rs | // -*- rust -*-
// 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
// ... | {
general();
target();
} | identifier_body | |
bitwise.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. This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(target_arch ... | // -*- rust -*-
// 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.
// | random_line_split | |
sdl2.rs | use self::sdl2::event::Event;
use self::sdl2::keyboard::Keycode;
use self::sdl2::pixels::{Color, PixelFormatEnum};
use self::sdl2::rect::Rect;
use self::sdl2::render::{Texture, TextureCreator, WindowCanvas};
use self::sdl2::video::WindowContext;
use sdl2;
use std::collections::HashMap;
use std::path::Path;
use std::syn... | let texture_creator = canvas.texture_creator();
canvas.set_draw_color(Color::RGB(0, 0, 0));
canvas.clear();
let mut events = sdl_context.event_pump().unwrap();
let font = ttf_context
.load_font(Path::new("assets/OpenSans-Regular.ttf"), 48)
.expect("could no... | let mut canvas = window.into_canvas().accelerated().build().unwrap(); | random_line_split |
sdl2.rs | use self::sdl2::event::Event;
use self::sdl2::keyboard::Keycode;
use self::sdl2::pixels::{Color, PixelFormatEnum};
use self::sdl2::rect::Rect;
use self::sdl2::render::{Texture, TextureCreator, WindowCanvas};
use self::sdl2::video::WindowContext;
use sdl2;
use std::collections::HashMap;
use std::path::Path;
use std::syn... | let w = (SCREEN_W as u32) * (scale_h as u32);
let h = (SCREEN_H as u32) * (scale_v as u32);
info!("display scale = ({}, {}).", scale_h, scale_v);
// SDL 2 initialization
let sdl_context = sdl2::init().unwrap();
let ttf_context = sdl2::ttf::init().unwrap();
let vi... | {
use crate::backend::BackendMessage::*;
use crate::emulator::EmulationMessage::*;
info!("starting the main application thread.");
// Input bindings
let key_binds = match get_key_bindings::<Keycode>(
&config.get_keyboard_binding(),
&keycode_from_symbol_h... | identifier_body |
sdl2.rs | use self::sdl2::event::Event;
use self::sdl2::keyboard::Keycode;
use self::sdl2::pixels::{Color, PixelFormatEnum};
use self::sdl2::rect::Rect;
use self::sdl2::render::{Texture, TextureCreator, WindowCanvas};
use self::sdl2::video::WindowContext;
use sdl2;
use std::collections::HashMap;
use std::path::Path;
use std::syn... |
}
}
last_key = Some(keycode);
}
Event::KeyUp {
keycode: Some(keycode),
..
} if!paused => {
if let Some(keypad_ke... | {
if let Some(keypad_key) = key_binds.get(&keycode) {
tx.send(KeyDown(*keypad_key)).unwrap();
}
} | conditional_block |
sdl2.rs | use self::sdl2::event::Event;
use self::sdl2::keyboard::Keycode;
use self::sdl2::pixels::{Color, PixelFormatEnum};
use self::sdl2::rect::Rect;
use self::sdl2::render::{Texture, TextureCreator, WindowCanvas};
use self::sdl2::video::WindowContext;
use sdl2;
use std::collections::HashMap;
use std::path::Path;
use std::syn... | ;
impl BackendSDL2 {
fn render_display<'a>(
tc: &'a TextureCreator<WindowContext>,
wc: &mut WindowCanvas,
frame_buffer: &[RGB],
scale_h: u32,
scale_v: u32,
) -> Texture<'a> {
let (w, w_scale) = (SCREEN_W as i32, scale_h as i32);
let (h, h_scale) = (SCREEN... | BackendSDL2 | identifier_name |
main.rs | use std::net::{TcpListener};
use std::io::{BufReader, BufWriter, BufRead, Write};
use std::thread;
fn main() {
let listener = match TcpListener::bind("127.0.0.1:8888") {
Ok(v) => { println!("127.0.0.1:8888 binded."); v },
Err(e) => { panic!("bind failed : {:?}", e) }
};
let mut threads = v... | client.peer_addr().unwrap(),
line.trim());
},
Ok(_) => {
break
}
Err(e) => {
println!("[LOG][ERROR] read error! {:?}", e);
... | random_line_split | |
main.rs | use std::net::{TcpListener};
use std::io::{BufReader, BufWriter, BufRead, Write};
use std::thread;
fn main() | match reader.read_line(&mut line) {
Ok(_len) if _len > 0 => {
println!("[{:?}] {}",
client.peer_addr().unwrap(),
line.trim());
},
Ok(_) => {
... | {
let listener = match TcpListener::bind("127.0.0.1:8888") {
Ok(v) => { println!("127.0.0.1:8888 binded."); v },
Err(e) => { panic!("bind failed : {:?}", e) }
};
let mut threads = vec![];
for stream in listener.incoming() {
let client = match stream {
Ok(v) => { pri... | identifier_body |
main.rs | use std::net::{TcpListener};
use std::io::{BufReader, BufWriter, BufRead, Write};
use std::thread;
fn | () {
let listener = match TcpListener::bind("127.0.0.1:8888") {
Ok(v) => { println!("127.0.0.1:8888 binded."); v },
Err(e) => { panic!("bind failed : {:?}", e) }
};
let mut threads = vec![];
for stream in listener.incoming() {
let client = match stream {
Ok(v) => { ... | main | identifier_name |
main.rs | use std::net::{TcpListener};
use std::io::{BufReader, BufWriter, BufRead, Write};
use std::thread;
fn main() {
let listener = match TcpListener::bind("127.0.0.1:8888") {
Ok(v) => { println!("127.0.0.1:8888 binded."); v },
Err(e) => { panic!("bind failed : {:?}", e) }
};
let mut threads = v... |
}
}
}
| {} | conditional_block |
scheduler.rs | /* diosix virtual CPU scheduler
*
* This is, for now, really really simple.
* Making it fairer and adaptive to workloads is the ultimate goal.
*
* (c) Chris Williams, 2018-2021.
*
* See LICENSE for usage and copying.
*/
use super::lock::Mutex;
use alloc::collections::vec_deque::VecDeque;
use hashbrown::hash_m... | ()
{
/* perform integrity checks */
#[cfg(feature = "integritychecks")]
{
if let Err(val) = pcore::PhysicalCore::integrity_check()
{
hvalert!("CPU private stack overflowed (0x{:x}). Halting!", val);
loop {}
}
}
/* avoid blocking on the house keeping l... | housekeeping | identifier_name |
scheduler.rs | /* diosix virtual CPU scheduler
*
* This is, for now, really really simple.
* Making it fairer and adaptive to workloads is the ultimate goal.
*
* (c) Chris Williams, 2018-2021.
*
* See LICENSE for usage and copying.
*/
use super::lock::Mutex;
use alloc::collections::vec_deque::VecDeque;
use hashbrown::hash_m... | (Some(v), false) =>
{
let timeslice_length = TIMESLICE_LENGTH.to_exact(frequency);
let mut last_scheduled_at = v.to_exact(frequency);
/* if the capsule we're running in is valid then perform a time slice check.
if it's not valid, ensure the capsule is ... | {
let time_now = hardware::scheduler_get_timer_now();
let frequency = hardware::scheduler_get_timer_frequency();
if time_now.is_none() || frequency.is_none()
{
/* check to see if anything needs to run and bail out if
no timer hardware can be found (and yet we're still getting IRQs?) */
... | identifier_body |
scheduler.rs | /* diosix virtual CPU scheduler
*
* This is, for now, really really simple.
* Making it fairer and adaptive to workloads is the ultimate goal.
*
* (c) Chris Williams, 2018-2021.
*
* See LICENSE for usage and copying.
*/
use super::lock::Mutex;
use alloc::collections::vec_deque::VecDeque;
use hashbrown::hash_m... | Ok(())
}
/* make a decision on whether to run another virtual core,
or return to the currently running core (if possible).
ping() is called when a scheduler timer IRQ comes in */
pub fn ping()
{
let time_now = hardware::scheduler_get_timer_now();
let frequency = hardware::scheduler_get_timer_frequenc... | <= returns OK, or error code on failure */
pub fn start() -> Result<(), Cause>
{
hardware::scheduler_timer_start(); | random_line_split |
types.rs | use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Severity {
Unknown,
Low,
Medium,
High,
Critical,
}
impl Default for Severity {
fn default() -> Self {
Self::Unknown
}
}
impl fmt... | () -> Self {
Self::Unknown
}
}
#[derive(Deserialize)]
#[serde(transparent)]
pub struct Avgs {
pub avgs: Vec<Avg>,
}
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct Avg {
pub name: String,
pub packages: Vec<String>,
pub status: Status,
#[serde(rename = "type")]
pub kind... | default | identifier_name |
types.rs | use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Severity {
Unknown,
Low,
Medium,
High,
Critical,
}
impl Default for Severity {
fn default() -> Self {
Self::Unknown
}
}
impl fmt... | #[derive(PartialOrd, Ord, PartialEq, Eq)]
pub struct Affected {
pub package: String,
pub cves: Vec<String>,
pub severity: Severity,
pub status: Status,
pub fixed: Option<String>,
pub kind: Vec<String>,
}
impl Affected {
pub fn new(package: &str) -> Self {
Self {
package:... | pub severity: Severity,
pub fixed: Option<String>,
pub issues: Vec<String>,
}
| random_line_split |
main.rs | #[macro_use]
extern crate clap;
extern crate sdl2;
use clap::App;
use sdl2::event::Event;
use std::fs::File;
use std::path::Path;
use std::thread;
use std::time::Duration;
mod cpu;
mod display;
mod emulator;
mod keypad;
mod memory;
mod speaker;
use crate::cpu::*;
use crate::display::*;
use crate::emulator::Emulator... | Err(_) => panic!("The specified ROM file does not exist"),
};
emulator.load_rom(&mut rom_file).unwrap();
// Initialize rodeo
// This needs to be done before SDL2 initialization: https://github.com/RustAudio/rodio/issues/214
rodio::default_output_device();
// Initialize SDL2
let sdl2... | random_line_split | |
main.rs | #[macro_use]
extern crate clap;
extern crate sdl2;
use clap::App;
use sdl2::event::Event;
use std::fs::File;
use std::path::Path;
use std::thread;
use std::time::Duration;
mod cpu;
mod display;
mod emulator;
mod keypad;
mod memory;
mod speaker;
use crate::cpu::*;
use crate::display::*;
use crate::emulator::Emulator... | {
sdl2_timing.performance_counter()
} | identifier_body | |
main.rs | #[macro_use]
extern crate clap;
extern crate sdl2;
use clap::App;
use sdl2::event::Event;
use std::fs::File;
use std::path::Path;
use std::thread;
use std::time::Duration;
mod cpu;
mod display;
mod emulator;
mod keypad;
mod memory;
mod speaker;
use crate::cpu::*;
use crate::display::*;
use crate::emulator::Emulator... | (sdl2_timing: &sdl2::TimerSubsystem) -> u64 {
sdl2_timing.performance_counter()
}
| get_time | identifier_name |
calendar.rs | // Evelyn: Your personal assistant, project manager and calendar
// Copyright (C) 2017 Gregory Jensen
//
// This program 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
//... |
match request_model_de {
Ok(request_model) => {
let session_token_model = validate_session!(processor_data, request_model);
match calendar::calendar_add_event(request_model, session_token_model, processor_data) {
None => {
RouterOutput {
... | pub fn calendar_add_event_processor(
router_input: RouterInput,
processor_data: Arc<processing::ProcessorData>,
) -> RouterOutput {
let request_model_de: Result<calendar_model::CalendarAddEventRequestModel, _> = serde_json::from_str(&router_input.request_body); | random_line_split |
calendar.rs | // Evelyn: Your personal assistant, project manager and calendar
// Copyright (C) 2017 Gregory Jensen
//
// This program 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
//... | }
}
,
Err(e) => {
trace!("{}", e);
let response = calendar_model::CalendarAddEventResponseModel {
error: Some(From::from(EvelynServiceError::CouldNotDecodeTheRequestPayload(e))),
};
RouterOutput {
response_body... | {
let session_token_model = validate_session!(processor_data, request_model);
match calendar::calendar_add_event(request_model, session_token_model, processor_data) {
None => {
RouterOutput {
response_body: serde_json::to_string(&calen... | conditional_block |
calendar.rs | // Evelyn: Your personal assistant, project manager and calendar
// Copyright (C) 2017 Gregory Jensen
//
// This program 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
//... | (
router_input: RouterInput,
processor_data: Arc<processing::ProcessorData>,
) -> RouterOutput {
let request_model_de: Result<calendar_model::CalendarAddEventRequestModel, _> = serde_json::from_str(&router_input.request_body);
match request_model_de {
Ok(request_model) => {
let sess... | calendar_add_event_processor | identifier_name |
calendar.rs | // Evelyn: Your personal assistant, project manager and calendar
// Copyright (C) 2017 Gregory Jensen
//
// This program 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
//... | })
.unwrap(),
}
},
}
},
Err(e) => {
trace!("{}", e);
let response = calendar_model::CalendarAddEventResponseModel {
error: ... | {
let request_model_de: Result<calendar_model::CalendarAddEventRequestModel, _> = serde_json::from_str(&router_input.request_body);
match request_model_de {
Ok(request_model) => {
let session_token_model = validate_session!(processor_data, request_model);
match calendar::calend... | identifier_body |
expr-if-struct.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 ... | ;
assert!((rs.i == 100));
}
enum mood { happy, sad, }
impl cmp::Eq for mood {
fn eq(&self, other: &mood) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &mood) -> bool {!(*self).eq(other) }
}
fn test_tag() {
let rs = if true { happy } else { sad };
assert!((rs ... | { I {i: 101} } | conditional_block |
expr-if-struct.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 ... |
// -*- rust -*-
// Tests for if as expressions returning nominal types
struct I { i: int }
fn test_rec() {
let rs = if true { I {i: 100} } else { I {i: 101} };
assert!((rs.i == 100));
}
enum mood { happy, sad, }
impl cmp::Eq for mood {
fn eq(&self, other: &mood) -> bool {
((*self) as uint) == ... | random_line_split | |
expr-if-struct.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 ... | () { test_rec(); test_tag(); }
| main | identifier_name |
logger.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use rocksdb::{DBInfoLogLevel as InfoLogLevel, Logger};
// TODO(yiwu): abstract the Logger interface.
#[derive(Default)]
pub struct RocksdbLogger;
impl Logger for RocksdbLogger {
fn logv(&self, log_level: InfoLogLevel, log: &str) {
match lo... | (&self, log_level: InfoLogLevel, log: &str) {
match log_level {
InfoLogLevel::Header => info!(#"raftdb_log_header", "{}", log),
InfoLogLevel::Debug => debug!(#"raftdb_log", "{}", log),
InfoLogLevel::Info => info!(#"raftdb_log", "{}", log),
InfoLogLevel::Warn => wa... | logv | identifier_name |
logger.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use rocksdb::{DBInfoLogLevel as InfoLogLevel, Logger};
// TODO(yiwu): abstract the Logger interface.
#[derive(Default)]
pub struct RocksdbLogger;
impl Logger for RocksdbLogger {
fn logv(&self, log_level: InfoLogLevel, log: &str) {
match lo... | }
}
}
#[derive(Default)]
pub struct RaftDBLogger;
impl Logger for RaftDBLogger {
fn logv(&self, log_level: InfoLogLevel, log: &str) {
match log_level {
InfoLogLevel::Header => info!(#"raftdb_log_header", "{}", log),
InfoLogLevel::Debug => debug!(#"raftdb_log", "{}", log... | InfoLogLevel::Error => error!(#"rocksdb_log", "{}", log),
InfoLogLevel::Fatal => crit!(#"rocksdb_log", "{}", log),
_ => {} | random_line_split |
logger.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use rocksdb::{DBInfoLogLevel as InfoLogLevel, Logger};
// TODO(yiwu): abstract the Logger interface.
#[derive(Default)]
pub struct RocksdbLogger;
impl Logger for RocksdbLogger {
fn logv(&self, log_level: InfoLogLevel, log: &str) {
match lo... |
}
| {
match log_level {
InfoLogLevel::Header => info!(#"raftdb_log_header", "{}", log),
InfoLogLevel::Debug => debug!(#"raftdb_log", "{}", log),
InfoLogLevel::Info => info!(#"raftdb_log", "{}", log),
InfoLogLevel::Warn => warn!(#"raftdb_log", "{}", log),
I... | identifier_body |
mod.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | pub mod nfs_records;
pub mod nfs2_records;
pub mod nfs3_records;
pub mod nfs4_records;
pub mod nfs4;
pub mod nfs;
pub mod log;
//#[cfg(feature = "lua")]
//pub mod lua; | */
pub mod types;
pub mod rpc_records; | random_line_split |
pair.rs |
use error::{NcclError, ErrorKind};
use value::Value;
use ::TryInto;
use std::ops::{Index, IndexMut};
use std::error::Error;
/// Struct that contains configuration information.
///
/// Examples:
///
/// ```
/// let p = nccl::parse_file("examples/config.nccl").unwrap();
/// let ports = p["server"]["port"].keys_as::<i6... |
/// Test if a pair has a key.
///
/// Examples:
///
/// ```
/// use nccl::NcclError;
/// let mut p = nccl::parse_file("examples/config.nccl").unwrap();
/// assert!(p.has_key("server"));
/// assert!(p["server"]["port"].has_key(80));
/// ```
pub fn has_key<T>(&self, key: T) -... | {
if !self.has_key(&pair.key) {
self.value.push(pair);
} else {
self[&pair.key].value = pair.value;
}
} | identifier_body |
pair.rs | use error::{NcclError, ErrorKind};
use value::Value;
use ::TryInto;
use std::ops::{Index, IndexMut};
use std::error::Error;
/// Struct that contains configuration information.
///
/// Examples:
///
/// ```
/// let p = nccl::parse_file("examples/config.nccl").unwrap();
/// let ports = p["server"]["port"].keys_as::<i64... | /// Gets the value of a key as a specified type, if there is only one.
///
/// Examples:
///
/// ```
/// let p = nccl::parse_file("examples/long.nccl").unwrap();
/// assert!(!p["bool too"].value_as::<bool>().unwrap());
/// ```
pub fn value_as<T>(&self) -> Result<T, Box<dyn Error>> wh... | }
}
| random_line_split |
pair.rs |
use error::{NcclError, ErrorKind};
use value::Value;
use ::TryInto;
use std::ops::{Index, IndexMut};
use std::error::Error;
/// Struct that contains configuration information.
///
/// Examples:
///
/// ```
/// let p = nccl::parse_file("examples/config.nccl").unwrap();
/// let ports = p["server"]["port"].keys_as::<i6... | else {
None
}
}
/// Gets the value of a key as a specified type, if there is only one.
///
/// Examples:
///
/// ```
/// let p = nccl::parse_file("examples/long.nccl").unwrap();
/// assert!(!p["bool too"].value_as::<bool>().unwrap());
/// ```
pub fn value_as... | {
Some(self.value[0].key.clone())
} | conditional_block |
pair.rs |
use error::{NcclError, ErrorKind};
use value::Value;
use ::TryInto;
use std::ops::{Index, IndexMut};
use std::error::Error;
/// Struct that contains configuration information.
///
/// Examples:
///
/// ```
/// let p = nccl::parse_file("examples/config.nccl").unwrap();
/// let ports = p["server"]["port"].keys_as::<i6... | (&self, path: Vec<Value>) -> bool {
if path.is_empty() {
true
} else if self.has_key(path[0].clone()) {
self[path[0].clone()].has_path(path[1..path.len()].to_vec())
} else {
false
}
}
/// Traverses a Pair using a slice, adding the item if it d... | has_path | identifier_name |
trackevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::audiotrack::AudioTrack;
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::... |
}
impl TrackEventMethods for TrackEvent {
// https://html.spec.whatwg.org/multipage/#dom-trackevent-track
fn GetTrack(&self) -> Option<VideoTrackOrAudioTrackOrTextTrack> {
match &self.track {
Some(MediaTrack::Video(VideoTrack)) => Some(
VideoTrackOrAudioTrackOrTextTrack::Vi... | {
Ok(TrackEvent::new(
&window.global(),
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
&init.track,
))
} | identifier_body |
trackevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::audiotrack::AudioTrack;
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::... | {
Video(Dom<VideoTrack>),
Audio(Dom<AudioTrack>),
Text(Dom<TextTrack>),
}
#[dom_struct]
pub struct TrackEvent {
event: Event,
track: Option<MediaTrack>,
}
impl TrackEvent {
#[allow(unrooted_must_root)]
fn new_inherited(track: &Option<VideoTrackOrAudioTrackOrTextTrack>) -> TrackEvent {
... | MediaTrack | identifier_name |
trackevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::audiotrack::AudioTrack;
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::... | type_: DOMString,
init: &TrackEventBinding::TrackEventInit,
) -> Fallible<DomRoot<TrackEvent>> {
Ok(TrackEvent::new(
&window.global(),
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
&init.track,
))
}
}
... |
pub fn Constructor(
window: &Window, | random_line_split |
text.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/. */
//! Text layout.
use layout::box::{RenderBox, RenderBoxBase, TextRenderBox, UnscannedTextRenderBoxClass};
use gf... |
}
| {
match *self {
UnscannedTextRenderBoxClass(text_box) => copy text_box.text,
_ => fail!(~"unsupported operation: box.raw_text() on non-unscanned text box."),
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.