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 |
|---|---|---|---|---|
font_chooser_dialog.rs | // Copyright 2013-2015, The Gtk-rs 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>
use ffi;
use FFIWidget;
use cast::{GTK_WINDOW};
use glib::translate::ToGlibPtr;
struct_Widge... | }
}
impl_drop!(FontChooserDialog);
impl_TraitWidget!(FontChooserDialog);
impl ::ContainerTrait for FontChooserDialog {}
impl ::BinTrait for FontChooserDialog {}
impl ::WindowTrait for FontChooserDialog {}
impl ::DialogTrait for FontChooserDialog {}
impl ::FontChooserTrait for FontChooserDialog {} | random_line_split | |
sound-api.rs | #[macro_use]
extern crate hlua;
fn main() {
let mut lua = hlua::Lua::new();
lua.openlibs(); |
// we create a fill an array named `Sound` which will be used as a class-like interface
{
let mut sound_namespace = lua.empty_array("Sound");
// creating the `Sound.new` function
sound_namespace.set("new", hlua::function0(|| Sound::new()));
}
lua.execute::<()>(r#"
s = ... | random_line_split | |
sound-api.rs | #[macro_use]
extern crate hlua;
fn main() {
let mut lua = hlua::Lua::new();
lua.openlibs();
// we create a fill an array named `Sound` which will be used as a class-like interface
{
let mut sound_namespace = lua.empty_array("Sound");
// creating the `Sound.new` function
sound_... | () -> Sound {
Sound {
playing: false
}
}
pub fn play(&mut self) {
println!("playing");
self.playing = true;
}
pub fn stop(&mut self) {
println!("stopping");
self.playing = false;
}
pub fn is_playing(&self) -> bool {
self.play... | new | identifier_name |
sound-api.rs | #[macro_use]
extern crate hlua;
fn main() | print("is the sound playing:", s:is_playing());
"#).unwrap();
}
// this `Sound` struct is the object that we will use to demonstrate hlua
struct Sound {
playing: bool,
}
// this macro implements the required trait so that we can *push* the object to lua
// (ie. move it inside lua)
implement_lua_push... | {
let mut lua = hlua::Lua::new();
lua.openlibs();
// we create a fill an array named `Sound` which will be used as a class-like interface
{
let mut sound_namespace = lua.empty_array("Sound");
// creating the `Sound.new` function
sound_namespace.set("new", hlua::function0(|| Sou... | identifier_body |
xrtest.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/. */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL w... |
pub fn new(global: &GlobalScope) -> DomRoot<XRTest> {
reflect_dom_object(
Box::new(XRTest::new_inherited()),
global,
XRTestBinding::Wrap,
)
}
fn device_obtained(
&self,
response: Result<IpcSender<MockDeviceMsg>, XRError>,
trusted... | {
XRTest {
reflector: Reflector::new(),
devices_connected: DomRefCell::new(vec![]),
}
} | identifier_body |
xrtest.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/. */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL w... | {
reflector: Reflector,
devices_connected: DomRefCell<Vec<Dom<FakeXRDevice>>>,
}
impl XRTest {
pub fn new_inherited() -> XRTest {
XRTest {
reflector: Reflector::new(),
devices_connected: DomRefCell::new(vec![]),
}
}
pub fn new(global: &GlobalScope) -> DomRo... | XRTest | identifier_name |
xrtest.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/. */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL w... | fn device_obtained(
&self,
response: Result<IpcSender<MockDeviceMsg>, XRError>,
trusted: TrustedPromise,
) {
let promise = trusted.root();
if let Ok(sender) = response {
let device = FakeXRDevice::new(&self.global(), sender);
self.devices_connected... | global,
XRTestBinding::Wrap,
)
}
| random_line_split |
xrtest.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/. */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL w... |
}),
);
for device in rooted_devices.drain(..) {
device.disconnect(sender.clone());
}
};
p
}
}
| {
let trusted = trusted
.take()
.expect("DisconnectAllDevices disconnected more devices than expected");
let _ =
task_source.queue_with_canceller(trusted.resolve_task(()), &canceller);
... | conditional_block |
readme.rs | #[macro_use]
extern crate linxal;
extern crate ndarray;
use linxal::types::{c32, LinxalMatrix};
use linxal::eigenvalues::Eigen;
use linxal::solve_linear::SolveLinear;
use ndarray::{arr1, arr2};
fn f1() {
let m = arr2(&[[1.0f32, 2.0],
[-2.0, 1.0]]);
let r = m.eigenvalues();
assert!(r.is... |
fn main() {
f1();
f2();
}
| {
let m = arr2(&[[1.0f32, 2.0],
[-2.0, 1.0]]);
let r = Eigen::compute(&m, false, false);
assert!(r.is_ok());
let r = r.unwrap();
let true_evs = arr1(&[c32::new(1.0, 2.0), c32::new(1.0, -2.0)]);
assert_eq_within_tol!(true_evs, r.values, 0.01);
let b = arr1(&[-1.0, 1.0]);... | identifier_body |
readme.rs | #[macro_use]
extern crate linxal;
extern crate ndarray;
use linxal::types::{c32, LinxalMatrix};
use linxal::eigenvalues::Eigen;
use linxal::solve_linear::SolveLinear;
use ndarray::{arr1, arr2};
fn f1() {
let m = arr2(&[[1.0f32, 2.0],
[-2.0, 1.0]]);
let r = m.eigenvalues();
assert!(r.is... |
let b = arr1(&[-1.0, 1.0]);
let x = m.solve_linear(&b).unwrap();
let true_x = arr1(&[-0.6, -0.2]);
assert_eq_within_tol!(x, true_x, 0.0001);
}
fn f2() {
let m = arr2(&[[1.0f32, 2.0],
[-2.0, 1.0]]);
let r = Eigen::compute(&m, false, false);
assert!(r.is_ok());
let ... | assert_eq_within_tol!(true_evs, r, 0.01); | random_line_split |
readme.rs | #[macro_use]
extern crate linxal;
extern crate ndarray;
use linxal::types::{c32, LinxalMatrix};
use linxal::eigenvalues::Eigen;
use linxal::solve_linear::SolveLinear;
use ndarray::{arr1, arr2};
fn f1() {
let m = arr2(&[[1.0f32, 2.0],
[-2.0, 1.0]]);
let r = m.eigenvalues();
assert!(r.is... | () {
let m = arr2(&[[1.0f32, 2.0],
[-2.0, 1.0]]);
let r = Eigen::compute(&m, false, false);
assert!(r.is_ok());
let r = r.unwrap();
let true_evs = arr1(&[c32::new(1.0, 2.0), c32::new(1.0, -2.0)]);
assert_eq_within_tol!(true_evs, r.values, 0.01);
let b = arr1(&[-1.0, 1.0... | f2 | identifier_name |
task-perf-one-million.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 start_chan = wait_port.recv();
let (sum_port, sum_chan) = stream::<int>();
start_chan.send(sum_chan);
let sum = sum_port.recv();
error!("How many tasks? %d tasks.", sum);
}
| {
let args = os::args();
let args = if os::getenv(~"RUST_BENCH").is_some() {
~[~"", ~"30"]
} else if args.len() <= 1u {
~[~"", ~"10"]
} else {
args
};
let children = uint::from_str(args[1]).get();
let (wait_port, wait_chan) = stream();
do task::spawn {
ca... | identifier_body |
task-perf-one-million.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 ... | (children: uint, parent_wait_chan: &Chan<Chan<Chan<int>>>) {
let wait_ports: ~[Port<Chan<Chan<int>>>] = do vec::from_fn(children) |_| {
let (wait_port, wait_chan) = stream::<Chan<Chan<int>>>();
do task::spawn {
calc(children / 2, &wait_chan);
}
wait_port
};
let ... | calc | identifier_name |
task-perf-one-million.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 children = uint::from_str(args[1]).get();
let (wait_port, wait_chan) = stream();
do task::spawn {
calc(children, &wait_chan);
};
let start_chan = wait_port.recv();
let (sum_port, sum_chan) = stream::<int>();
start_chan.send(sum_chan);
let sum = sum_port.recv();
error!... | {
args
} | conditional_block |
task-perf-one-million.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 for concurrent tasks
use core::comm::*;
fn calc(children: uint, parent_wait_chan: &Chan<Chan<Chan<int>>>) {
let wait_ports: ~[Port<Chan<Chan<int>>>] = do vec::from_fn(children) |_| {
let (wait_port, wait_chan) = stream::<Chan<Chan<int>>>();
do task::spawn {
calc(children / 2, ... | random_line_split | |
mod.rs | //! A simple adapter designe solely to print messages on the console.
//!
//! Useful for logging.
use foxbox_taxonomy::api::{ Error, InternalError, User };
use foxbox_taxonomy::channel::*;
use foxbox_taxonomy::manager::*;
use foxbox_taxonomy::services::*;
use foxbox_taxonomy::values::{ Value };
use std::collections::... |
};
(id, result)
})
.collect()
}
}
impl Console {
pub fn init(adapt: &Arc<AdapterManager>) -> Result<(), Error> {
let service_console_id = Console::service_console_id();
let setter_stdout_id = Console::setter_stdout_id();
let adapt... | {
Err(Error::InternalError(InternalError::NoSuchChannel(id.clone())))
} | conditional_block |
mod.rs | //! A simple adapter designe solely to print messages on the console.
//!
//! Useful for logging.
use foxbox_taxonomy::api::{ Error, InternalError, User };
use foxbox_taxonomy::channel::*;
use foxbox_taxonomy::manager::*;
use foxbox_taxonomy::services::*;
use foxbox_taxonomy::values::{ Value };
use std::collections::... | (&self, mut values: HashMap<Id<Channel>, Value>, user: User) -> ResultMap<Id<Channel>, (), Error> {
values.drain()
.map(|(id, value)| {
let result = {
if id == self.setter_stdout_id {
if let Value::String(s) = value {
... | send_values | identifier_name |
mod.rs | //! A simple adapter designe solely to print messages on the console.
//!
//! Useful for logging.
use foxbox_taxonomy::api::{ Error, InternalError, User };
use foxbox_taxonomy::channel::*;
use foxbox_taxonomy::manager::*;
use foxbox_taxonomy::services::*;
use foxbox_taxonomy::values::{ Value };
use std::collections::... | fn send_values(&self, mut values: HashMap<Id<Channel>, Value>, user: User) -> ResultMap<Id<Channel>, (), Error> {
values.drain()
.map(|(id, value)| {
let result = {
if id == self.setter_stdout_id {
if let Value::String(s) = value {
... | set.drain(..).map(|id| {
(id.clone(), Err(Error::InternalError(InternalError::NoSuchChannel(id))))
}).collect()
}
| random_line_split |
astconv.rs | <AC:AstConv,RS:RegionScope + Clone +'static>(
this: &AC,
rscope: &RS,
def_id: ast::DefId,
decl_generics: &ty::Generics,
self_ty: Option<ty::t>,
path: &ast::Path) -> ty::substs
{
/*!
*
* Given a path `path` that refers to an item `I` with the
* declared generics `decl_generics`... | ast_path_substs | identifier_name | |
astconv.rs | (&Some(_), &None) => {
let res = rscope.anon_region(path.span);
let r = get_region_reporting_err(this.tcx(), path.span, &None, res);
opt_vec::with(r)
}
(&Some(_), &Some(_)) => {
opt_vec::with(
ast_region_to_region(this,
... | result.substs.clone(),
trait_store,
a_seq_ty.mutbl,
bounds);
}
_ => {}
}
}
... | {
let result = ast_path_to_trait_ref(
this, rscope, trait_def_id, None, path);
let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
... | conditional_block |
astconv.rs | (&Some(_), &None) => {
let res = rscope.anon_region(path.span);
let r = get_region_reporting_err(this.tcx(), path.span, &None, res);
opt_vec::with(r)
}
(&Some(_), &Some(_)) => {
opt_vec::with(
ast_region_to_region(this,
... | fmt!("wrong number of type arguments: expected %u but found %u",
decl_generics.type_param_defs.len(),
supplied_type_parameter_count));
}
let tps = path.segments
.iter()
.flat_map(|s| s.types.iter())
.map(|a_t| ast_t... | path.segments.iter().flat_map(|s| s.types.iter()).len();
if decl_generics.type_param_defs.len() != supplied_type_parameter_count {
this.tcx().sess.span_fatal(
path.span, | random_line_split |
astconv.rs | let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
ty::vstore_slice(r) => {
ty::RegionTraitStore(r)
}
... | {
match self_info.explicit_self.node {
ast::sty_static => None,
ast::sty_value => {
Some(self_info.untransformed_self_ty)
}
ast::sty_region(ref lifetime, mutability) => {
let region =
ast_region_to_region(this, r... | identifier_body | |
lib.rs | //#![feature(iter_arith_traits)]
//#![feature(conservative_impl_trait)]
//#![feature(reflect_marker)]
#![feature(specialization)]
extern crate byteorder;
extern crate densearray;
extern crate float;
extern crate iter_utils;
#[cfg(feature = "mkldnn")]
extern crate mkl_dnn;
//extern crate neuralops_kernels;
//extern cra... | pub mod archs_mkl;
pub mod checkpoint;
pub mod class_loss;
pub mod common;
pub mod conv;
pub mod conv_gemm;
#[cfg(feature = "mkldnn")]
pub mod conv_mkldnn;
#[cfg(feature = "mkl")]
pub mod conv_mkl;
#[cfg(not(feature = "mkl"))]
pub mod conv_nnpack;
pub mod data;
pub mod deconv;
pub mod dropout;
pub mod dummy;
pub mod in... |
pub mod affine;
pub mod archs;
#[cfg(feature = "mkldnn")] | random_line_split |
player.rs | use rand::Rng;
use super::{Gun, PowerupKind};
use geometry::{Advance, Collide, Point, Position, Size, Vector};
use geometry_derive::{Advance, Position};
/// The `Player` is the rocket controlled by the user
#[derive(Default, Advance, Position)]
pub struct Player {
pub vector: Vector,
pub is_dead: bool,
pu... | }
} | fn radius(&self) -> f32 {
6.0 | random_line_split |
player.rs | use rand::Rng;
use super::{Gun, PowerupKind};
use geometry::{Advance, Collide, Point, Position, Size, Vector};
use geometry_derive::{Advance, Position};
/// The `Player` is the rocket controlled by the user
#[derive(Default, Advance, Position)]
pub struct Player {
pub vector: Vector,
pub is_dead: bool,
pu... | (&self) -> f32 {
6.0
}
}
| radius | identifier_name |
reflect.rs | = self.bcx;
let str_ty = ty::mk_str_slice(bcx.tcx(), ty::ReStatic, ast::MutImmutable);
let scratch = rvalue_scratch_datum(bcx, str_ty, "");
let len = C_uint(bcx.ccx(), s.get().len());
let c_str = PointerCast(bcx, C_cstr(bcx.ccx(), s, false), Type::i8p(bcx.ccx()));
Store(bcx, c_s... | "visit_{}", ty_name).as_slice()),
self.visitor_items.as_slice()).expect(
format!("couldn't find visit method for {}", ty_name).as_slice());
let method = match self.visitor_items[mth_idx] {
ty::MethodTraitItem(ref method) =>... | let fcx = self.bcx.fcx;
let tcx = self.bcx.tcx();
let mth_idx = ty::impl_or_trait_item_idx(token::str_to_ident(format!( | random_line_split |
reflect.rs | self.bcx;
let str_ty = ty::mk_str_slice(bcx.tcx(), ty::ReStatic, ast::MutImmutable);
let scratch = rvalue_scratch_datum(bcx, str_ty, "");
let len = C_uint(bcx.ccx(), s.get().len());
let c_str = PointerCast(bcx, C_cstr(bcx.ccx(), s, false), Type::i8p(bcx.ccx()));
Store(bcx, c_str... |
pub fn c_mt(&mut self, mt: &ty::mt) -> Vec<ValueRef> {
vec!(self.c_uint(mt.mutbl as uint),
self.c_tydesc(mt.ty))
}
pub fn visit(&mut self, ty_name: &str, args: &[ValueRef]) {
let fcx = self.bcx.fcx;
let tcx = self.bcx.tcx();
let mth_idx = ty::impl_or_trait_item_i... | {
let bcx = self.bcx;
let static_ti = get_tydesc(bcx.ccx(), t);
glue::lazily_emit_visit_glue(bcx.ccx(), &*static_ti);
PointerCast(bcx, static_ti.tydesc, self.tydesc_ty.ptr_to())
} | identifier_body |
reflect.rs | bare_fn(tcx, method.fty.clone());
debug!("Emit call visit method: visit_{}: {}", ty_name, ty_to_string(tcx, mth_ty));
let v = self.visitor_val;
debug!("passing {} args:", args.len());
let mut bcx = self.bcx;
for (i, a) in args.iter().enumerate() {
debug!("arg {}: {}",... | emit_calls_to_trait_visit_ty | identifier_name | |
lib.rs | #![crate_type = "dylib"]
extern crate libc;
extern crate qpick;
use std::ffi::{CStr, CString};
/// Get an immutable reference from a raw pointer
macro_rules! ref_from_ptr {
($p: ident) => {
unsafe {
assert!(!$p.is_null());
&*$p
}
};
}
/// Get the object referenced by ... | (
path: *mut libc::c_char,
start_shard: libc::uint32_t,
end_shard: libc::uint32_t,
) -> *mut Qpick {
let path = cstr_to_str(path);
let qpick = Qpick::from_path_with_shard_range(path.to_string(), start_shard..end_shard);
to_raw_ptr(qpick)
}
make_free_fn!(qpick_free, *mut Qpick);
#[no_mangle]
pub... | qpick_init_with_shard_range | identifier_name |
lib.rs | #![crate_type = "dylib"]
extern crate libc;
extern crate qpick;
use std::ffi::{CStr, CString};
/// Get an immutable reference from a raw pointer
macro_rules! ref_from_ptr {
($p: ident) => {
unsafe {
assert!(!$p.is_null());
&*$p
}
};
}
/// Get the object referenced by ... |
make_free_fn!(qpick_search_results_free, *mut qpick::SearchResults);
make_free_fn!(qpick_search_item_free, *mut QpickSearchItem);
// --- end iterators ---
#[no_mangle]
pub extern "C" fn qpick_get(
ptr: *mut Qpick,
query: *mut libc::c_char,
count: libc::uint32_t,
with_tfidf: libc::uint8_t,
) -> *mut ... | {
let res = mutref_from_ptr!(ptr);
// let mut iter = res.items.iter();
match res.next() {
Some(qid_sc) => to_raw_ptr(QpickSearchItem {
qid: qid_sc.id,
sc: qid_sc.sc,
}),
None => ::std::ptr::null_mut(),
}
} | identifier_body |
lib.rs | #![crate_type = "dylib"]
extern crate libc;
extern crate qpick;
use std::ffi::{CStr, CString};
/// Get an immutable reference from a raw pointer
macro_rules! ref_from_ptr {
($p: ident) => {
unsafe {
assert!(!$p.is_null());
&*$p
}
};
}
/// Get the object referenced by ... |
use qpick::Qpick;
// `#[no_mangle]` warns for lifetime parameters,
// a known issue: https://github.com/rust-lang/rust/issues/40342
#[no_mangle]
pub extern "C" fn qpick_init(path: *mut libc::c_char) -> *mut Qpick {
let path = cstr_to_str(path);
let qpick = Qpick::from_path(path.to_string());
to_raw_ptr(qp... | }
pub fn to_raw_ptr<T>(v: T) -> *mut T {
Box::into_raw(Box::new(v))
} | random_line_split |
client.rs | #![deny(warnings)]
#![feature(vec_push_all, test)]
extern crate hyper;
extern crate test;
use std::fmt;
use std::io::{self, Read, Write, Cursor};
use std::net::SocketAddr;
use std::time::Duration;
use hyper::net;
static README: &'static [u8] = include_bytes!("../README.md");
struct MockStream {
read: Cursor<Ve... |
}
impl Write for MockStream {
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
// we're mocking, what do we care.
Ok(msg.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[derive(Clone, Debug)]
struct Foo;
impl hyper::header::Header for Foo {
fn header_na... | {
self.read.read(buf)
} | identifier_body |
client.rs | #![deny(warnings)]
#![feature(vec_push_all, test)]
extern crate hyper;
extern crate test;
use std::fmt;
use std::io::{self, Read, Write, Cursor};
use std::net::SocketAddr;
use std::time::Duration;
use hyper::net;
static README: &'static [u8] = include_bytes!("../README.md");
struct MockStream {
read: Cursor<Ve... | ;
impl net::NetworkConnector for MockConnector {
type Stream = MockStream;
fn connect(&self, _: &str, _: u16, _: &str) -> hyper::Result<MockStream> {
Ok(MockStream::new())
}
}
#[bench]
fn bench_mock_hyper(b: &mut test::Bencher) {
let url = "http://127.0.0.1:1337/";
b.iter(|| {
let ... | MockConnector | identifier_name |
client.rs | #![deny(warnings)]
#![feature(vec_push_all, test)]
extern crate hyper;
extern crate test;
use std::fmt;
use std::io::{self, Read, Write, Cursor};
use std::net::SocketAddr;
use std::time::Duration;
use hyper::net;
static README: &'static [u8] = include_bytes!("../README.md");
struct MockStream {
read: Cursor<Ve... | Ok(MockStream::new())
}
}
#[bench]
fn bench_mock_hyper(b: &mut test::Bencher) {
let url = "http://127.0.0.1:1337/";
b.iter(|| {
let mut req = hyper::client::Request::with_connector(
hyper::Get, hyper::Url::parse(url).unwrap(), &MockConnector
).unwrap();
req.heade... |
impl net::NetworkConnector for MockConnector {
type Stream = MockStream;
fn connect(&self, _: &str, _: u16, _: &str) -> hyper::Result<MockStream> { | random_line_split |
serial.rs | use kern::arch::port::Port;
use spin::Mutex;
const SERIAL_PORT: u16 = 0x3f8; /* COM1 */
#[derive(Debug)]
pub struct Serial {
ports: [Port<u8>; 8]
}
pub static COM1: Mutex<Serial> = Mutex::new(Serial::new(SERIAL_PORT));
impl Serial {
pub const fn new(base: u16) -> Serial {
Serial {
por... | (&mut self, a: u8) {
while!self.is_transmit_empty() {
}
self.ports[0].write(a);
}
unsafe fn serial_received(&mut self) -> bool {
self.ports[5].read() & 0x1!= 0
}
pub unsafe fn read(&mut self) -> u8 {
while!self.serial_received() {
}
self.ports[... | write | identifier_name |
serial.rs | use kern::arch::port::Port;
use spin::Mutex;
const SERIAL_PORT: u16 = 0x3f8; /* COM1 */
#[derive(Debug)]
pub struct Serial { | impl Serial {
pub const fn new(base: u16) -> Serial {
Serial {
ports: [
Port::new(base),
Port::new(base + 1),
Port::new(base + 2),
Port::new(base + 3),
Port::new(base + 4),
Port::new(base + 5),
... | ports: [Port<u8>; 8]
}
pub static COM1: Mutex<Serial> = Mutex::new(Serial::new(SERIAL_PORT));
| random_line_split |
mod.rs | //! Unix-specific extension to the primitives in the `std::ffi` module.
//!
//! # Examples
//!
//! ```
//! use std::ffi::OsString;
//! use std::os::unix::ffi::OsStringExt;
//!
//! let bytes = b"foo".to_vec();
//! | //! let os_string = OsString::from_vec(bytes);
//! assert_eq!(os_string.to_str(), Some("foo"));
//!
//! // OsStringExt::into_vec
//! let bytes = os_string.into_vec();
//! assert_eq!(bytes, b"foo");
//! ```
//!
//! ```
//! use std::ffi::OsStr;
//! use std::os::unix::ffi::OsStrExt;
//!
//! let bytes = b"foo";
//!
//! // ... | //! // OsStringExt::from_vec | random_line_split |
http.rs | #[macro_use]
extern crate criterion;
#[macro_use]
extern crate combine;
use std::fmt;
use {
combine::{
many, many1,
parser::range::{range, take_while1},
stream::easy,
token, ParseError, Parser, RangeStream,
},
criterion::{black_box, Bencher, Criterion},
};
#[derive(Debug)]... |
criterion_group!(http, http_requests,);
criterion_main!(http);
| {
c.bench_function("http_requests_small", http_requests_small);
c.bench_function("http_requests_large", http_requests_large);
c.bench_function(
"http_requests_large_cheap_error",
http_requests_large_cheap_error,
);
} | identifier_body |
http.rs | #[macro_use]
extern crate criterion;
#[macro_use]
extern crate combine;
use std::fmt;
use {
combine::{
many, many1,
parser::range::{range, take_while1},
stream::easy,
token, ParseError, Parser, RangeStream,
},
criterion::{black_box, Bencher, Criterion},
};
#[derive(Debug)]... | version: &'a [u8],
}
#[derive(Debug)]
struct Header<'a> {
name: &'a [u8],
value: Vec<&'a [u8]>,
}
fn is_token(c: u8) -> bool {
match c {
128..=255
| 0..=31
| b'('
| b')'
| b'<'
| b'>'
| b'@'
| b','
| b';'
| b':'
| ... | uri: &'a [u8], | random_line_split |
http.rs | #[macro_use]
extern crate criterion;
#[macro_use]
extern crate combine;
use std::fmt;
use {
combine::{
many, many1,
parser::range::{range, take_while1},
stream::easy,
token, ParseError, Parser, RangeStream,
},
criterion::{black_box, Bencher, Criterion},
};
#[derive(Debug)]... | (c: u8) -> bool {
c >= b'0' && c <= b'9' || c == b'.'
}
fn end_of_line<'a, Input>() -> impl Parser<Input, Output = u8>
where
Input: RangeStream<Token = u8, Range = &'a [u8]>,
Input::Error: ParseError<Input::Token, Input::Range, Input::Position>,
{
(token(b'\r'), token(b'\n')).map(|_| b'\r').or(token(b'... | is_http_version | identifier_name |
css_provider.rs | // Copyright 2013-2015, The Gtk-rs 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>
use Error;
use CssProvider;
use ffi;
use glib::object::IsA;
use glib::translate::*;
use std::... | (&self, data: &str) -> Result<(), Error> {
unsafe {
let mut error = ptr::null_mut();
let _ = ffi::gtk_css_provider_load_from_data(self.to_glib_none().0, mut_override(data.as_bytes().as_ptr()),
data.len() as ssize_t, &mut error);
if error.is_null() { Ok(())... | load_from_data | identifier_name |
css_provider.rs | // Copyright 2013-2015, The Gtk-rs 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>
use Error;
use CssProvider;
use ffi;
use glib::object::IsA;
use glib::translate::*;
use std::... | } | random_line_split | |
css_provider.rs | // Copyright 2013-2015, The Gtk-rs 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>
use Error;
use CssProvider;
use ffi;
use glib::object::IsA;
use glib::translate::*;
use std::... | else { Err(from_glib_full(error)) }
}
}
}
| { Ok(()) } | conditional_block |
css_provider.rs | // Copyright 2013-2015, The Gtk-rs 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>
use Error;
use CssProvider;
use ffi;
use glib::object::IsA;
use glib::translate::*;
use std::... |
}
| {
unsafe {
let mut error = ptr::null_mut();
let _ = ffi::gtk_css_provider_load_from_data(self.to_glib_none().0, mut_override(data.as_bytes().as_ptr()),
data.len() as ssize_t, &mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
... | identifier_body |
rm.rs | use config::Config;
use errors::*; | SubCommand::with_name("rm")
.about("Removes a user")
.arg(
Arg::with_name("USER")
.help("Specifies the user")
.required(true)
.index(1)
)
}
pub fn call(args: &ArgMatches) -> Result<()> {
// Load the config
let config_file = arg... |
use clap::{App, Arg, ArgMatches, SubCommand};
pub fn setup<'a, 'b>() -> App<'a, 'b> { | random_line_split |
rm.rs | use config::Config;
use errors::*;
use clap::{App, Arg, ArgMatches, SubCommand};
pub fn setup<'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name("rm")
.about("Removes a user")
.arg(
Arg::with_name("USER")
.help("Specifies the user")
.required(true)
... |
// Store the config
config.store(config_file)?;
Ok(())
}
| {
bail!(format!("A user named '{}' does not exist", user)); // TODO Use proper error!
} | conditional_block |
rm.rs | use config::Config;
use errors::*;
use clap::{App, Arg, ArgMatches, SubCommand};
pub fn | <'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name("rm")
.about("Removes a user")
.arg(
Arg::with_name("USER")
.help("Specifies the user")
.required(true)
.index(1)
)
}
pub fn call(args: &ArgMatches) -> Result<()> {
// Load the conf... | setup | identifier_name |
rm.rs | use config::Config;
use errors::*;
use clap::{App, Arg, ArgMatches, SubCommand};
pub fn setup<'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name("rm")
.about("Removes a user")
.arg(
Arg::with_name("USER")
.help("Specifies the user")
.required(true)
... | {
// Load the config
let config_file = args.value_of("config").unwrap();
let mut config = Config::load(config_file)?;
// Remove the user, if existing
let user = args.value_of("USER").unwrap();
if config.users.remove(user).is_none() {
bail!(format!("A user named '{}' does not exist", use... | identifier_body | |
struct_list.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... |
pub fn len(&self) -> u32 { self.builder.len() }
// pub fn set(&self, index : uint, value : T) {
// }
}
impl <'a, T> Builder<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> {
pub fn borrow<'b>(&'b mut self) -> Builder<'b, T> {
Builder {builder : self.builder, marker : ::std::... | {
Builder { builder : builder, marker : ::std::marker::PhantomData }
} | identifier_body |
struct_list.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | fn clone(&self) -> Reader<'a, T> {
Reader { marker : self.marker, reader : self.reader }
}
}
impl <'a, T> Copy for Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> {}
impl <'a, T> Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> {
pub fn new<'b>(reader : ListReader<'b>) -> Reader<'b... | }
impl <'a, T> Clone for Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { | random_line_split |
struct_list.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | (&self, index : u32) -> <T as ::traits::OwnedStruct<'a>>::Reader {
self.get(index)
}
}
impl <'a, T> Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> {
pub fn get(self, index: u32) -> <T as ::traits::OwnedStruct<'a>>::Reader {
assert!(index < self.len());
FromStructReader::new(se... | index_move | identifier_name |
instruct_mq.rs | use crate::qaruntime::base::Instruct;
use crate::qaruntime::qamanagers::monitor_manager::MonitorManager;
use actix::{Actor, Addr, Context};
use amiquip::{
Channel, Connection, ConsumerMessage, ConsumerOptions, Exchange, ExchangeDeclareOptions,
ExchangeType, FieldTable, Publish, QueueDeclareOptions, Result,
};... | -> Result<()> {
let mut connection = Connection::insecure_open(&self.amqp)?;
let channel = connection.open_channel(None)?;
let exchange = channel.exchange_declare(
ExchangeType::Direct,
&self.exchange,
ExchangeDeclareOptions {
durable: false,
... | direct(&self) | identifier_name |
instruct_mq.rs | use crate::qaruntime::base::Instruct;
use crate::qaruntime::qamanagers::monitor_manager::MonitorManager;
use actix::{Actor, Addr, Context};
use amiquip::{
Channel, Connection, ConsumerMessage, ConsumerOptions, Exchange, ExchangeDeclareOptions,
ExchangeType, FieldTable, Publish, QueueDeclareOptions, Result,
};... | error!("[Monitor Manager] send instruct fail {}", e.to_string())
}
},
Err(e) => error!("[Monitor Manager] Instruct parse fail {}", e.to_string()),
}
}
other => ... | match serde_json::from_str(&data) {
Ok(v) => match self.morm.try_send::<Instruct>(v) {
Ok(_) => {}
Err(e) => { | random_line_split |
instruct_mq.rs | use crate::qaruntime::base::Instruct;
use crate::qaruntime::qamanagers::monitor_manager::MonitorManager;
use actix::{Actor, Addr, Context};
use amiquip::{
Channel, Connection, ConsumerMessage, ConsumerOptions, Exchange, ExchangeDeclareOptions,
ExchangeType, FieldTable, Publish, QueueDeclareOptions, Result,
};... | ctx.set_mailbox_capacity(1000); // 设置邮箱容量
self.consume_direct();
}
}
| identifier_body | |
windows.rs | use std::sync::mpsc::{channel, Sender, Receiver, TryRecvError, sync_channel, SyncSender};
use std::io::{Read, Write};
use std::{io, thread};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use named_pipe::{PipeOptions, OpenMode, PipeClient};
use libc;
fn run<F: FnOnce(&SyncSender<()>) -> io::Resul... | (name: &str) -> io::Result<IpcClient> {
let (send_tx, send_rx) = channel::<Vec<u8>>();
let (recv_tx, recv_rx) = channel::<Vec<u8>>();
let pid = unsafe { libc::getpid() as u32 };
let path = format!("\\\\.\\pipe\\messageipc_{}_{}", name, pid);
let mut servers = try!(PipeOp... | open_server | identifier_name |
windows.rs | use std::sync::mpsc::{channel, Sender, Receiver, TryRecvError, sync_channel, SyncSender};
use std::io::{Read, Write};
use std::{io, thread};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use named_pipe::{PipeOptions, OpenMode, PipeClient};
use libc;
fn run<F: FnOnce(&SyncSender<()>) -> io::Resul... |
pub struct IpcClient {
send: Sender<Vec<u8>>,
recv: Receiver<Vec<u8>>,
}
struct S<T>(T);
unsafe impl<T> Send for S<T> {}
impl IpcClient {
pub fn send(&self, message: Vec<u8>) -> bool {
self.send.send(message).is_ok()
}
pub fn recv(&self) -> Option<Vec<u8>> {
self... | {
let (sync_tx, sync_rx) = sync_channel(0);
thread::spawn(move || {
match f(&sync_tx) {
Ok(_) => {},
Err(_) => {
sync_tx.try_send(()).ok();
//println!("MIPC {} thread failed with {:?}", name, e);
}
};
});
sync... | identifier_body |
windows.rs | use std::sync::mpsc::{channel, Sender, Receiver, TryRecvError, sync_channel, SyncSender};
use std::io::{Read, Write};
use std::{io, thread};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use named_pipe::{PipeOptions, OpenMode, PipeClient};
use libc;
fn run<F: FnOnce(&SyncSender<()>) -> io::Resul... | pub fn try_recv(&self) -> Option<Option<Vec<u8>>> {
match self.recv.try_recv() {
Ok(buf) => Some(Some(buf)),
Err(TryRecvError::Empty) => Some(None),
Err(TryRecvError::Disconnected) => None
}
}
pub fn open_server(name: &str) -> io::Result<IpcClient... | random_line_split | |
command.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn env<K, V>(&mut self, key: K, value: V) -> &mut Command
where K: AsRef<OsStr>,
V: AsRef<OsStr>
{
self._env(key.as_ref(), value.as_ref());
self
}
fn _env(&mut self, key: &OsStr, value: &OsStr) {
self.env.push((key.to_owned(), value.to_owned()));
... | {
self.args.push(arg.to_owned());
} | identifier_body |
command.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | //! A thin wrapper around `Command` in the standard library which allows us to
//! read the arguments that are built up.
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::io;
use std::mem;
use std::process::{self, Output};
use rustc_target::spec::LldFlavor;
#[derive(Clone)]
pub struct Command {
program: Pr... | random_line_split | |
command.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self, key: &OsStr, value: &OsStr) {
self.env.push((key.to_owned(), value.to_owned()));
}
pub fn output(&mut self) -> io::Result<Output> {
self.command().output()
}
pub fn command(&self) -> process::Command {
let mut ret = match self.program {
Program::Normal(r... | _env | identifier_name |
dir_action.rs | //! Parsing the options for `DirAction`.
use crate::options::parser::MatchedFlags;
use crate::options::{flags, OptionsError, NumberSource};
use crate::fs::dir_action::{DirAction, RecurseOptions};
impl DirAction {
/// Determine which action to perform when trying to list a directory.
/// There are three pos... | }
}
else {
Ok(Self { tree, max_depth: None })
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::options::flags;
use crate::options::parser::Flag;
macro_rules! test {
($name:ident: $type:ident <- $inputs:expr; $stricts:expr => $result:expr) =... | let source = NumberSource::Arg(&flags::LEVEL);
Err(OptionsError::FailedParse(arg_str.to_string(), source, e))
}
| conditional_block |
dir_action.rs | //! Parsing the options for `DirAction`.
use crate::options::parser::MatchedFlags;
use crate::options::{flags, OptionsError, NumberSource};
use crate::fs::dir_action::{DirAction, RecurseOptions};
impl DirAction { | /// Determine which action to perform when trying to list a directory.
/// There are three possible actions, and they overlap somewhat: the
/// `--tree` flag is another form of recursion, so those two are allowed
/// to both be present, but the `--list-dirs` flag is used separately.
pub fn deduce(ma... | random_line_split | |
dir_action.rs | //! Parsing the options for `DirAction`.
use crate::options::parser::MatchedFlags;
use crate::options::{flags, OptionsError, NumberSource};
use crate::fs::dir_action::{DirAction, RecurseOptions};
impl DirAction {
/// Determine which action to perform when trying to list a directory.
/// There are three pos... | // examine the View, which should have already been deduced by now
Ok(Self::Recurse(RecurseOptions::deduce(matches, true)?))
}
else if recurse {
Ok(Self::Recurse(RecurseOptions::deduce(matches, false)?))
}
else if as_file {
Ok(Self::AsFile)... | {
let recurse = matches.has(&flags::RECURSE)?;
let as_file = matches.has(&flags::LIST_DIRS)?;
let tree = matches.has(&flags::TREE)?;
if matches.is_strict() {
// Early check for --level when it wouldn’t do anything
if ! recurse && ! tree && matches.count(&flags... | identifier_body |
dir_action.rs | //! Parsing the options for `DirAction`.
use crate::options::parser::MatchedFlags;
use crate::options::{flags, OptionsError, NumberSource};
use crate::fs::dir_action::{DirAction, RecurseOptions};
impl DirAction {
/// Determine which action to perform when trying to list a directory.
/// There are three pos... | (matches: &MatchedFlags<'_>, can_tree: bool) -> Result<Self, OptionsError> {
let recurse = matches.has(&flags::RECURSE)?;
let as_file = matches.has(&flags::LIST_DIRS)?;
let tree = matches.has(&flags::TREE)?;
if matches.is_strict() {
// Early check for --level when it woul... | deduce | identifier_name |
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling... | }
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum IFrameSandboxState {
IFrameSandboxed,
IFrameUnsandboxed
}
// We pass this info to various tasks, so it lives in a separate, cloneable struct.
#[derive(Clone, Copy, Deserialize, Serialize)]
pub struct Failure {
pub pipeli... | random_line_split | |
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling... | {
namespace_id: PipelineNamespaceId,
index: PipelineIndex
}
impl PipelineId {
pub fn new() -> PipelineId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_pipeline_id = namespace.next();
tls.set(... | PipelineId | identifier_name |
tests.rs | use State;
use GLOBALSINDEX;
use Type;
use raw;
use libc;
use std::task;
use std::any::AnyRefExt;
#[test]
fn test_state_init() {
let mut _s = State::new();
}
#[test]
#[should_fail]
fn test_error() |
#[test]
fn test_errorstr() {
let res = task::try::<()>(proc() {
let mut s = State::new();
s.errorstr("some err");
});
let err = res.unwrap_err();
let expected = "unprotected error in call to Lua API (some err)";
let s = err.as_ref::<String>();
if s.is_some() {
assert_eq... | {
let mut s = State::new();
s.pushinteger(42);
s.error()
} | identifier_body |
tests.rs | use State;
use GLOBALSINDEX;
use Type;
use raw;
use libc; | fn test_state_init() {
let mut _s = State::new();
}
#[test]
#[should_fail]
fn test_error() {
let mut s = State::new();
s.pushinteger(42);
s.error()
}
#[test]
fn test_errorstr() {
let res = task::try::<()>(proc() {
let mut s = State::new();
s.errorstr("some err");
});
let er... | use std::task;
use std::any::AnyRefExt;
#[test] | random_line_split |
tests.rs | use State;
use GLOBALSINDEX;
use Type;
use raw;
use libc;
use std::task;
use std::any::AnyRefExt;
#[test]
fn test_state_init() {
let mut _s = State::new();
}
#[test]
#[should_fail]
fn test_error() {
let mut s = State::new();
s.pushinteger(42);
s.error()
}
#[test]
fn test_errorstr() {
let res = t... |
}
#[test]
fn test_describe() {
let mut s = State::new();
assert_eq!(s.typename(1), "no value");
s.pushnil();
assert_eq!(s.typename(-1), "nil");
s.pushinteger(42);
assert_eq!(s.typename(-1), "number");
s.pushstring("test");
assert_eq!(s.typename(-1), "string");
s.pushboolean(true);... | {
let s = err.as_ref::<&'static str>();
if s.is_some() {
assert_eq!(*s.unwrap(), expected);
} else {
fail!("unexpected failure result");
}
} | conditional_block |
tests.rs | use State;
use GLOBALSINDEX;
use Type;
use raw;
use libc;
use std::task;
use std::any::AnyRefExt;
#[test]
fn test_state_init() {
let mut _s = State::new();
}
#[test]
#[should_fail]
fn test_error() {
let mut s = State::new();
s.pushinteger(42);
s.error()
}
#[test]
fn test_errorstr() {
let res = t... | () {
let mut s = State::new();
s.openlibs();
s.getfield(GLOBALSINDEX, "table");
assert_eq!(s.type_(-1), Some(Type::Table));
}
#[deriving(PartialEq,Eq,Show)]
enum CheckOptionEnum {
COEOne,
COETwo,
COEThree
}
#[test]
fn test_checkoption() {
let lst = [("one", COEOne), ("two", COETwo), (... | test_openlibs | identifier_name |
stylesheets.rs | frame_list};
use media_queries::{Device, MediaQueryList, parse_media_query_list};
use parking_lot::RwLock;
use parser::{ParserContext, ParserContextExtraData, log_css_error};
use properties::{PropertyDeclarationBlock, parse_property_declaration_list};
use selector_impl::TheSelectorImpl;
use selectors::parser::{Selector... | }
#[inline]
fn style(self) -> rule_filter::Style<'a, I> {
rule_filter::Style::new(self)
}
#[inline]
fn viewport(self) -> rule_filter::Viewport<'a, I> {
rule_filter::Viewport::new(self)
}
#[inline]
fn keyframes(self) -> rule_filter::Keyframes<'a, I> {
rule_f... | random_line_split | |
stylesheets.rs | _list};
use media_queries::{Device, MediaQueryList, parse_media_query_list};
use parking_lot::RwLock;
use parser::{ParserContext, ParserContextExtraData, log_css_error};
use properties::{PropertyDeclarationBlock, parse_property_declaration_list};
use selector_impl::TheSelectorImpl;
use selectors::parser::{Selector, par... | (self) -> rule_filter::Style<'a, I> {
rule_filter::Style::new(self)
}
#[inline]
fn viewport(self) -> rule_filter::Viewport<'a, I> {
rule_filter::Viewport::new(self)
}
#[inline]
fn keyframes(self) -> rule_filter::Keyframes<'a, I> {
rule_filter::Keyframes::new(self)
}... | style | identifier_name |
stylesheets.rs | _list};
use media_queries::{Device, MediaQueryList, parse_media_query_list};
use parking_lot::RwLock;
use parser::{ParserContext, ParserContextExtraData, log_css_error};
use properties::{PropertyDeclarationBlock, parse_property_declaration_list};
use selector_impl::TheSelectorImpl;
use selectors::parser::{Selector, par... |
return Some(rule)
}
self.stack.pop();
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
// TODO: track total number of rules in style-sheet for upper bound?
(0, None)
}
}
pub mod rule_filter {
//! Specific ... | {
if let Some(device) = self.device {
if rule.evaluate(device) {
self.stack.push(rule.rules.iter());
} else {
continue
}
} else {
... | conditional_block |
main.rs | lazy_static;
#[macro_use]
mod sorceries;
mod space;
mod identity;
mod motion;
mod landmark;
mod life;
mod mind;
mod substrate;
mod uci;
// Unlikely Command Integration
mod test_landmark;
use std::fs::OpenOptions;
use std::io;
use std::io::Write;
use std::process;
use ansi_term::Colour as Color;
use argparse::{Argu... | `--seconds` was passed"
.to_owned())
} else {
Ok(true)
}
};
if let Some(depth) = lookahead_depth {
confirm_bound_is_none(&bound)?;
bound = Some(LookaheadBound::Depth(depth, loo... | |b: &Option<LookaheadBound>| -> Result<bool, String> {
if b.is_some() {
Err("more than one of `--depth`, `--depth-sequence`, or \ | random_line_split |
main.rs | _static;
#[macro_use]
mod sorceries;
mod space;
mod identity;
mod motion;
mod landmark;
mod life;
mod mind;
mod substrate;
mod uci;
// Unlikely Command Integration
mod test_landmark;
use std::fs::OpenOptions;
use std::io;
use std::io::Write;
use std::process;
use ansi_term::Colour as Color;
use argparse::{ArgumentP... | let stop_thinking = get_time();
let thinking_time = stop_thinking - start_thinking;
(forecasts, depth, thinking_time)
}
#[derive(Serialize)]
struct Postcard {
world: String,
patch: TransitPatch,
hospitalization: Option<Agent>,
thinking_time: u64,
depth: u8,
counterreplies: Vec<Trans... | let (fs, ds) = iterative_deepening_kickoff::<T>(
&world, bound.duration(), false, déjà_vu_bound);
forecasts = fs;
depth = ds;
}
}
| conditional_block |
main.rs | static;
#[macro_use]
mod sorceries;
mod space;
mod identity;
mod motion;
mod landmark;
mod life;
mod mind;
mod substrate;
mod uci;
// Unlikely Command Integration
mod test_landmark;
use std::fs::OpenOptions;
use std::io;
use std::io::Write;
use std::process;
use ansi_term::Colour as Color;
use argparse::{ArgumentPa... | r: &str, bound: LookaheadBound, déjà_vu_bound: f32)
-> String {
let in_medias_res = WorldState::reconstruct(reminder);
let (mut forecasts, depth, sidereal) = forecast::<Patch>(in_medias_res,
bound,
... | ndence(reminde | identifier_name |
lib.rs | #![allow(dead_code)]
//! # tray\_rust - A Toy Ray Tracer in Rust
//!
//! tray\_rust is a toy physically based ray tracer built off of the techniques
//! discussed in [Physically Based Rendering](http://pbrt.org/). It began life as a port of
//! [tray](https://github.com/Twinklebear/tray) to [Rust](http://www.rust-lan... | //! Render times are formatted as hh:mm:ss and were measured using 144 threads on a machine with four
//! [Xeon E7-8890 v3](http://ark.intel.com/products/84685/Intel-Xeon-Processor-E7-8890-v3-45M-Cache-2_50-GHz)
//! CPUs. The machine is an early/engineering sample from Intel so your results may differ, but massive than... | //! | random_line_split |
main.rs | use std::net::{TcpListener,TcpStream};
use std::io::{BufReader,BufRead,Write,Result as IoResult};
use std::fs::File;
use std::collections::HashMap;
fn handle_connection(map: &HashMap<String,String>,mut stream: &mut TcpStream) -> IoResult<()>
{
let mut line = String::new();
let mut reader = BufReader::new(try!(stream... | {
try!(stream.write(format!("{}\n",data).as_bytes()));
}
else
{
try!(stream.write(b"not found\n"));
}
line.clear();
}
Ok(())
}
fn main()
{
let mut map = HashMap::new();
for line in BufReader::new(File::open("input.csv").unwrap()).lines()
{
if let Ok(line) = line
{
map.insert(String::from... | random_line_split | |
main.rs | use std::net::{TcpListener,TcpStream};
use std::io::{BufReader,BufRead,Write,Result as IoResult};
use std::fs::File;
use std::collections::HashMap;
fn handle_connection(map: &HashMap<String,String>,mut stream: &mut TcpStream) -> IoResult<()>
{
let mut line = String::new();
let mut reader = BufReader::new(try!(stream... | {
let mut map = HashMap::new();
for line in BufReader::new(File::open("input.csv").unwrap()).lines()
{
if let Ok(line) = line
{
map.insert(String::from(line.split(";").nth(1).unwrap()),line);
}
}
for stream in TcpListener::bind("0.0.0.0:1337").unwrap().incoming()
{
if let Ok(mut stream) = stream
{
... | identifier_body | |
main.rs | use std::net::{TcpListener,TcpStream};
use std::io::{BufReader,BufRead,Write,Result as IoResult};
use std::fs::File;
use std::collections::HashMap;
fn handle_connection(map: &HashMap<String,String>,mut stream: &mut TcpStream) -> IoResult<()>
{
let mut line = String::new();
let mut reader = BufReader::new(try!(stream... | ()
{
let mut map = HashMap::new();
for line in BufReader::new(File::open("input.csv").unwrap()).lines()
{
if let Ok(line) = line
{
map.insert(String::from(line.split(";").nth(1).unwrap()),line);
}
}
for stream in TcpListener::bind("0.0.0.0:1337").unwrap().incoming()
{
if let Ok(mut stream) = stream
... | main | identifier_name |
main.rs | use std::net::{TcpListener,TcpStream};
use std::io::{BufReader,BufRead,Write,Result as IoResult};
use std::fs::File;
use std::collections::HashMap;
fn handle_connection(map: &HashMap<String,String>,mut stream: &mut TcpStream) -> IoResult<()>
{
let mut line = String::new();
let mut reader = BufReader::new(try!(stream... |
line.clear();
}
Ok(())
}
fn main()
{
let mut map = HashMap::new();
for line in BufReader::new(File::open("input.csv").unwrap()).lines()
{
if let Ok(line) = line
{
map.insert(String::from(line.split(";").nth(1).unwrap()),line);
}
}
for stream in TcpListener::bind("0.0.0.0:1337").unwrap().incoming()... | {
try!(stream.write(b"not found\n"));
} | conditional_block |
unpark_mutex.rs | use std::cell::UnsafeCell;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
/// A "lock" around data `D`, which employs a *helping* strategy.
///
/// Used to ensure that concurrent `unpark` invocations lead to (1) `poll` being
/// invoked on only a single thread at a time (2) `poll` being i... |
/// Alert the mutex that polling completed with NotReady.
///
/// # Safety
///
/// Callable only from the `POLLING`/`REPOLL` states, i.e. between
/// successful calls to `notify` and `wait`/`complete`.
pub unsafe fn wait(&self, data: D) -> Result<(), D> {
*self.inner.get() = Some(d... | {
self.status.store(POLLING, SeqCst);
} | identifier_body |
unpark_mutex.rs | use std::cell::UnsafeCell;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
/// A "lock" around data `D`, which employs a *helping* strategy.
///
/// Used to ensure that concurrent `unpark` invocations lead to (1) `poll` being
/// invoked on only a single thread at a time (2) `poll` being i... | const REPOLL: usize = 2; // --> POLLING
// The task has finished executing (either successfully or with an error/panic)
const COMPLETE: usize = 3; // No transitions out
impl<D> UnparkMutex<D> {
pub fn new() -> UnparkMutex<D> {
UnparkMutex {
status: AtomicUsize::new(WAITING),
... | // of interest should move it to the REPOLL state
const POLLING: usize = 1; // --> WAITING, REPOLL, or COMPLETE
// The task is actively being polled, but will need to be re-polled upon
// completion to ensure that all events were observed. | random_line_split |
unpark_mutex.rs | use std::cell::UnsafeCell;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
/// A "lock" around data `D`, which employs a *helping* strategy.
///
/// Used to ensure that concurrent `unpark` invocations lead to (1) `poll` being
/// invoked on only a single thread at a time (2) `poll` being i... | (&self, data: D) -> Result<(), D> {
*self.inner.get() = Some(data);
match self.status.compare_exchange(POLLING, WAITING, SeqCst, SeqCst) {
// no unparks came in while we were running
Ok(_) => Ok(()),
// guaranteed to be in REPOLL state; just clobber the
... | wait | identifier_name |
constant-debug-locs.rs | // Copyright 2013-2015 The Rust Project Developers. See the 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// min-lldb-version... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
constant-debug-locs.rs | // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
let mut _constant = CONSTANT;
let mut _struct = STRUCT;
let mut _tuple_struct = TUPLE_STRUCT;
let mut _variant1 = VARIANT1;
let mut _variant2 = VARIANT2;
let mut _variant3 = VARIANT3;
let mut _string = STRING;
let mut _vec = VEC;
let mut _nested = NESTED;
let mut _unsafe_cel... | main | identifier_name |
iterator.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org> | // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.
extern crate fringe;
use ... | random_line_split | |
iterator.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at y... | {
let stack = OsStack::new(0).unwrap();
let mut gen = Generator::new(stack, move |yielder, ()| {
for i in 0.. { yielder.suspend(i) }
});
assert_eq!(gen.next(), Some(0));
assert_eq!(gen.next(), Some(1));
assert_eq!(gen.next(), Some(2));
unsafe { gen.unsafe_unwrap(); }
} | identifier_body | |
iterator.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at y... | () {
let stack = OsStack::new(0).unwrap();
let mut gen = Generator::new(stack, move |yielder, ()| {
for i in 0.. { yielder.suspend(i) }
});
assert_eq!(gen.next(), Some(0));
assert_eq!(gen.next(), Some(1));
assert_eq!(gen.next(), Some(2));
unsafe { gen.unsafe_unwrap(); }
}
| producer | identifier_name |
match-arm-statics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | } | issue_14576();
issue_15393(); | random_line_split |
match-arm-statics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
bits: uint
}
static FOO: Flags = Flags { bits: 0x01 };
static BAR: Flags = Flags { bits: 0x02 };
match (Flags { bits: 0x02 }) {
FOO => unreachable!(),
BAR => (),
_ => unreachable!()
}
}
fn main() {
assert_eq!(match (true, false) {
TRUE_TRUE => 1i,
... | Flags | identifier_name |
match-arm-statics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn issue_13731() {
enum A { A(()) }
static B: A = A(());
match A(()) {
B => ()
}
}
fn issue_15393() {
#![allow(dead_code)]
struct Flags {
bits: uint
}
static FOO: Flags = Flags { bits: 0x01 };
static BAR: Flags = Flags { bits: 0x02 };
match (Flags { bits: 0x0... | {
type Foo = (i32, i32);
static ON: Foo = (1, 1);
static OFF: Foo = (0, 0);
match (1, 1) {
OFF => unreachable!(),
ON => (),
_ => unreachable!()
}
enum C { D = 3, E = 4 }
static F : C = D;
assert_eq!(match D { F => 1i, _ => 2, }, 1);
} | identifier_body |
creader.rs | dump_crates(&sess.cstore);
warn_if_multiple_versions(sess.diagnostic(), &sess.cstore)
}
impl<'a, 'v> visit::Visitor<'v> for Env<'a> {
fn visit_view_item(&mut self, a: &ast::ViewItem) {
visit_view_item(self, a);
visit::walk_view_item(self, a);
}
fn visit_item(&mut self, a: &ast::Item... | lib: loader::Library)
-> (ast::CrateNum, Rc<cstore::crate_metadata>,
cstore::CrateSource) {
// Claim this crate number and cache it
let cnum = e.next_crate_num;
e.next_crate_num += 1;
// Stash paths for top-most crate locally if nece... | fn register_crate<'a>(e: &mut Env,
root: &Option<CratePaths>,
ident: &str,
name: &str,
span: Span, | random_line_split |
creader.rs | dump_crates(&sess.cstore);
warn_if_multiple_versions(sess.diagnostic(), &sess.cstore)
}
impl<'a, 'v> visit::Visitor<'v> for Env<'a> {
fn visit_view_item(&mut self, a: &ast::ViewItem) {
visit_view_item(self, a);
visit::walk_view_item(self, a);
}
fn visit_item(&mut self, a: &ast::Item)... |
fn warn_if_multiple_versions(diag: &SpanHandler, cstore: &CStore) {
let mut map = HashMap::new();
cstore.iter_crate_data(|cnum, data| {
match map.entry(data.name()) {
Vacant(entry) => { entry.set(vec![cnum]); },
Occupied(mut entry) => { entry.get_mut().push(cnum); },
}
... | {
debug!("resolved crates:");
cstore.iter_crate_data_origins(|_, data, opt_source| {
debug!(" name: {}", data.name());
debug!(" cnum: {}", data.cnum);
debug!(" hash: {}", data.hash());
opt_source.map(|cs| {
let CrateSource { dylib, rlib, cnum: _ } = cs;
... | identifier_body |
creader.rs | { continue }
diag.handler().warn(
format!("using multiple versions of crate `{}`", name).as_slice());
for dupe in dupes.into_iter() {
let data = cstore.get_crate_data(dupe);
diag.span_note(data.span, "used here");
loader::note_crate_name(diag, data.name()... | {
// try loading from target crates (only valid if there are
// no syntax extensions)
load_ctxt.triple = target_triple;
load_ctxt.os = self.env.sess.targ_cfg.os;
load_ctxt.filesearch = self.env.sess.target_filesearch();
let ... | conditional_block | |
creader.rs | dump_crates(&sess.cstore);
warn_if_multiple_versions(sess.diagnostic(), &sess.cstore)
}
impl<'a, 'v> visit::Visitor<'v> for Env<'a> {
fn visit_view_item(&mut self, a: &ast::ViewItem) {
visit_view_item(self, a);
visit::walk_view_item(self, a);
}
fn visit_item(&mut self, a: &ast::Item)... | (diag: &SpanHandler, cstore: &CStore) {
let mut map = HashMap::new();
cstore.iter_crate_data(|cnum, data| {
match map.entry(data.name()) {
Vacant(entry) => { entry.set(vec![cnum]); },
Occupied(mut entry) => { entry.get_mut().push(cnum); },
}
});
for (name, dupes)... | warn_if_multiple_versions | identifier_name |
repoconfig.rs | use std::collections::BTreeMap;
use std::default::Default;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use toml::{Parser, Value};
use toml::Value::Table;
pub struct Config {
fuzz: bool,
fuzz_cores: usize,
fuzz_seconds: usize,
fuzz_max_len: usize,
cross: bool,
}
impl Default for Conf... | (table: &BTreeMap<String, Value>) -> Result<Config, String> {
let mut config = Config::default();
if let Some(&Table(ref general)) = table.get("fuzz") {
if let Some(v) = general.get("enable").and_then(|k| k.as_bool()) {
config.set_fuzz(v as bool);
}
}
if let Some(&Table(re... | load_config_table | identifier_name |
repoconfig.rs | use std::collections::BTreeMap;
use std::default::Default;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use toml::{Parser, Value};
use toml::Value::Table;
pub struct Config {
fuzz: bool,
fuzz_cores: usize,
fuzz_seconds: usize,
fuzz_max_len: usize,
cross: bool,
}
impl Default for Conf... | fuzz_max_len: 64,
cross: true,
}
}
}
impl Config {
pub fn set_fuzz_cores(&mut self, cores: usize) -> &mut Self {
self.fuzz_cores = cores;
self
}
#[allow(dead_code)]
pub fn fuzz_cores(&self) -> usize {
self.fuzz_cores
}
pub fn set_fuz... | Config {
fuzz: true,
fuzz_cores: 1,
fuzz_seconds: 60, | random_line_split |
repoconfig.rs | use std::collections::BTreeMap;
use std::default::Default;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use toml::{Parser, Value};
use toml::Value::Table;
pub struct Config {
fuzz: bool,
fuzz_cores: usize,
fuzz_seconds: usize,
fuzz_max_len: usize,
cross: bool,
}
impl Default for Conf... |
if let Some(&Table(ref general)) = table.get("cross") {
if let Some(v) = general.get("enable").and_then(|k| k.as_bool()) {
config.set_cross(v as bool);
}
}
Ok(config)
}
| {
if let Some(v) = general.get("length").and_then(|k| k.as_integer()) {
config.set_fuzz_max_len(v as usize);
}
} | conditional_block |
repoconfig.rs | use std::collections::BTreeMap;
use std::default::Default;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use toml::{Parser, Value};
use toml::Value::Table;
pub struct Config {
fuzz: bool,
fuzz_cores: usize,
fuzz_seconds: usize,
fuzz_max_len: usize,
cross: bool,
}
impl Default for Conf... |
}
pub fn load_config(path: &Path) -> Result<Config, String> {
let cfg_txt = match File::open(path) {
Ok(mut f) => {
let mut cfg_txt = String::new();
f.read_to_string(&mut cfg_txt).unwrap();
cfg_txt
}
Err(e) => return Err(format!("Error opening config: {}... | {
self.cross
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.