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 |
|---|---|---|---|---|
issue-11192.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 ... | ptr = box Foo { x: ptr.x + 1 };
println!("access {}", foo.x);
};
test(&*ptr);
//~^ ERROR: cannot borrow `*ptr` as immutable
} | let mut test = |foo: &Foo| {
println!("access {}", foo.x); | random_line_split |
issue-11192.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 ... | (&mut self) {
println!("drop {}", self.x);
}
}
fn main() {
let mut ptr: Box<_> = box Foo { x: 0 };
let mut test = |foo: &Foo| {
println!("access {}", foo.x);
ptr = box Foo { x: ptr.x + 1 };
println!("access {}", foo.x);
};
test(&*ptr);
//~^ ERROR: cannot borrow `... | drop | identifier_name |
textedit.rs | extern crate rustty;
use rustty::{
Terminal,
Cell,
Event,
Style,
Color,
Attr,
};
struct | {
pos: Position,
lpos: Position,
style: Style,
}
#[derive(Copy, Clone)]
struct Position {
x: usize,
y: usize,
}
fn main() {
let mut cursor = Cursor {
pos: Position { x: 0, y: 0 },
lpos: Position { x: 0, y: 0 },
style: Style::with_color(Color::Red),
};
let mut t... | Cursor | identifier_name |
textedit.rs | extern crate rustty;
use rustty::{
Terminal,
Cell,
Event,
Style,
Color,
Attr,
}; | pos: Position,
lpos: Position,
style: Style,
}
#[derive(Copy, Clone)]
struct Position {
x: usize,
y: usize,
}
fn main() {
let mut cursor = Cursor {
pos: Position { x: 0, y: 0 },
lpos: Position { x: 0, y: 0 },
style: Style::with_color(Color::Red),
};
let mut term... |
struct Cursor { | random_line_split |
textedit.rs | extern crate rustty;
use rustty::{
Terminal,
Cell,
Event,
Style,
Color,
Attr,
};
struct Cursor {
pos: Position,
lpos: Position,
style: Style,
}
#[derive(Copy, Clone)]
struct Position {
x: usize,
y: usize,
}
fn main() {
let mut cursor = Cursor {
pos: Position {... |
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
term[cursor.pos.y][cursor.pos.x].set_bg(cursor.style);
term.swap_buffers().unwrap();
}
}
}
| {
term[cursor.lpos.y][cursor.lpos.x].set_bg(Style::default());
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y = 0;
} | conditional_block |
fmt.rs | //! Utilities for formatting and printing `String`s.
//!
//! This module contains the runtime support for the [`format!`] syntax extension.
//! This macro is implemented in the compiler to emit calls to this module in
//! order to format arguments at runtime into strings.
//!
//! # Usage
//!
//! The [`format!`] macro i... | rgs.estimated_capacity();
let mut output = string::String::with_capacity(capacity);
output.write_fmt(args).expect("a formatting trait implementation returned an error");
output
}
| identifier_body | |
fmt.rs | //! Utilities for formatting and printing `String`s.
//!
//! This module contains the runtime support for the [`format!`] syntax extension.
//! This macro is implemented in the compiler to emit calls to this module in
//! order to format arguments at runtime into strings.
//!
//! # Usage
//!
//! The [`format!`] macro i... | -> string::String {
let capacity = args.estimated_capacity();
let mut output = string::String::with_capacity(capacity);
output.write_fmt(args).expect("a formatting trait implementation returned an error");
output
}
| <'_>) | identifier_name |
fmt.rs | //! Utilities for formatting and printing `String`s.
//!
//! This module contains the runtime support for the [`format!`] syntax extension.
//! This macro is implemented in the compiler to emit calls to this module in
//! order to format arguments at runtime into strings.
//!
//! # Usage
//!
//! The [`format!`] macro i... | //! [`Formatter`] struct. In order to help with this, the [`Formatter`] struct also
//! provides some helper methods.
//!
//! Additionally, the return value of this function is [`fmt::Result`] which is a
//! type alias of [`Result`]`<(), `[`std::fmt::Error`]`>`. Formatting implementations
//! should ensure that they pr... | //!
//! Your type will be passed as `self` by-reference, and then the function
//! should emit output into the `f.buf` stream. It is up to each format trait
//! implementation to correctly adhere to the requested formatting parameters.
//! The values of these parameters will be listed in the fields of the | random_line_split |
maps.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::mem;
use std::ffi::CString;
use cassandra_sys::*;
struct Pair {
key: String,
value: i32,
}
fn insert_into_maps(session: &mut CassSession, key: &str, items: Vec<Pair>)... | print_error(future);
}
cass_future_free(future);
cass_statement_free(statement);
Ok(())
}
}
fn select_from_maps(session: &mut CassSession, key: &str) -> Result<(), CassError> {
unsafe {
let query = "SELECT items FROM examples.maps WHERE key =?";
le... | {
unsafe {
let query = "INSERT INTO examples.maps (key, items) VALUES (?, ?);";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 2);
cass_statement_bind_string(statement, 0, CString::new(key).unwrap().as_ptr());
let collection = cass_collection_new(CASS_COL... | identifier_body |
maps.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::mem;
use std::ffi::CString;
use cassandra_sys::*;
struct Pair {
key: String,
value: i32,
}
fn insert_into_maps(session: &mut CassSession, key: &str, items: Vec<Pair>)... | let future = &mut *cass_session_execute(session, statement);
cass_future_wait(future);
let rc = cass_future_error_code(future);
if rc!= CASS_OK {
print_error(future);
}
cass_future_free(future);
cass_statement_free(statement);
Ok(())
}
}... | cass_collection_append_int32(collection, item.value);
}
cass_statement_bind_collection(statement, 1, collection);
cass_collection_free(collection);
| random_line_split |
maps.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::mem;
use std::ffi::CString;
use cassandra_sys::*;
struct Pair {
key: String,
value: i32,
}
fn insert_into_maps(session: &mut CassSession, key: &str, items: Vec<Pair>)... | }
Ok(())
}
rc => Err(rc),
};
cass_future_free(future);
cass_statement_free(statement);
result
}
}
fn main() {
unsafe {
let items = vec![Pair {
key: "apple".to_owned(),
... | {
let row = cass_result_first_row(result);
let iterator = cass_iterator_from_map(cass_row_get_column(row, 0));
while cass_iterator_next(iterator) == cass_true {
let mut item_key = mem::zeroed();
let mut item_ke... | conditional_block |
maps.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::mem;
use std::ffi::CString;
use cassandra_sys::*;
struct | {
key: String,
value: i32,
}
fn insert_into_maps(session: &mut CassSession, key: &str, items: Vec<Pair>) -> Result<(), CassError> {
unsafe {
let query = "INSERT INTO examples.maps (key, items) VALUES (?,?);";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 2);
... | Pair | identifier_name |
edition-keywords-2018-2018.rs | // run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_as... | // OK
// one_async::async(); // ERROR, reserved
// one_async::r#async(); // ERROR, unresolved name
// two_async::async(); // ERROR, reserved
two_async::r#async(); // OK
}
mod one_async {
// produces_async! {} // ERROR, reserved
}
mod two_async {
produces_async_raw! {} // OK
}
fn main() {}
| {} | conditional_block |
edition-keywords-2018-2018.rs | // run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_as... | mod one_async {
// produces_async! {} // ERROR, reserved
}
mod two_async {
produces_async_raw! {} // OK
}
fn main() {} | }
| random_line_split |
edition-keywords-2018-2018.rs | // run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_as... | () {}
| main | identifier_name |
edition-keywords-2018-2018.rs | // run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_as... | {} | identifier_body | |
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::p... |
send_profile_data(category,
meta,
&profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
... | {
signpost::end(category as u32, &[0, 0, 0, (category as usize) >> 4]);
} | conditional_block |
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::p... | ScriptAttachLayout = 0x60,
ScriptConstellationMsg = 0x61,
ScriptDevtoolsMsg = 0x62,
ScriptDocumentEvent = 0x63,
ScriptDomEvent = 0x64,
ScriptEvaluate = 0x65,
ScriptEvent = 0x66,
ScriptFileRead = 0x67,
ScriptImageCacheMsg = 0x68,
ScriptInputEvent = 0x69,
ScriptNetworkEvent = 0... | ImageDecoding = 0x50,
ImageSaving = 0x51, | random_line_split |
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::p... | {
RootWindow,
IFrame,
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum TimerMetadataReflowType {
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan:... | TimerMetadataFrameType | identifier_name |
lib.rs | //! # Feature gates
//!
//! This crate declares the set of past and present unstable features in the compiler.
//! Feature gate checking itself is done in `rustc_ast_passes/src/feature_gate.rs`
//! at the moment.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a co... | use std::num::NonZeroU32;
#[derive(Clone, Copy)]
pub enum State {
Accepted,
Active { set: fn(&mut Features, Span) },
Removed { reason: Option<&'static str> },
Stabilized { reason: Option<&'static str> },
}
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
... | #[cfg(test)]
mod tests;
use rustc_span::{edition::Edition, symbol::Symbol, Span};
use std::fmt; | random_line_split |
lib.rs | //! # Feature gates
//!
//! This crate declares the set of past and present unstable features in the compiler.
//! Feature gate checking itself is done in `rustc_ast_passes/src/feature_gate.rs`
//! at the moment.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a co... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
State::Accepted {.. } => write!(f, "accepted"),
State::Active {.. } => write!(f, "active"),
State::Removed {.. } => write!(f, "removed"),
State::Stabilized {.. } => write!(f, "stabilized"),
... | fmt | identifier_name |
lib.rs | //! # Feature gates
//!
//! This crate declares the set of past and present unstable features in the compiler.
//! Feature gate checking itself is done in `rustc_ast_passes/src/feature_gate.rs`
//! at the moment.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a co... |
pub fn is_nightly_build(&self) -> bool {
match *self {
UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
UnstableFeatures::Disallow => false,
}
}
}
fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
if let Some(info) = ACTIVE_FEATURES.iter... | {
// `true` if this is a feature-staged build, i.e., on the beta or stable channel.
let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
// Returns whether `krate` should be counted as unstable
let is_unstable_crate = |var: &str| {
krate.map... | identifier_body |
const-bound.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 ... | {
/*foo(1);
foo("hi".to_string());
foo(vec![1, 2, 3]);
foo(F{field: 42});
foo((1, 2));
foo(@1);*/
foo(Box::new(1));
} | identifier_body | |
const-bound.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 ... | { field: isize }
pub fn main() {
/*foo(1);
foo("hi".to_string());
foo(vec![1, 2, 3]);
foo(F{field: 42});
foo((1, 2));
foo(@1);*/
foo(Box::new(1));
}
| F | identifier_name |
htmlimageelement.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 app_units::Au;
use dom::attr::Attr;
use dom::attr::AttrValue;
use dom::bindings::cell::DOMRefCell;
use dom::bi... |
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPer... | {
(*self.unsafe_get()).url.borrow_for_layout().clone()
} | identifier_body |
htmlimageelement.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 app_units::Au;
use dom::attr::Attr;
use dom::attr::AttrValue;
use dom::bindings::cell::DOMRefCell;
use dom::bi... | (element: &Element, attr: Atom, value: u32) {
// This setter is a bit weird: the IDL type is unsigned long, but it's parsed as
// a dimension for rendering.
let value = if value > UNSIGNED_LONG_MAX {
0
} else {
value
};
let dim = LengthOrPercentageOrAuto::Length(Au::from_px(value... | image_dimension_setter | identifier_name |
htmlimageelement.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 app_units::Au;
use dom::attr::Attr;
use dom::attr::AttrValue;
use dom::bindings::cell::DOMRefCell;
use dom::bi... |
if let Some(h) = height {
image.SetHeight(h);
}
Ok(image)
}
}
pub trait LayoutHTMLImageElementHelpers {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>>;
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>;
fn get_width(&self... | {
image.SetWidth(w);
} | conditional_block |
htmlimageelement.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 app_units::Au;
use dom::attr::Attr;
use dom::attr::AttrValue;
use dom::bindings::cell::DOMRefCell;
use dom::bi... | fn Height(&self) -> u32 {
let node = self.upcast::<Node>();
let rect = node.get_bounding_content_box();
rect.size.height.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn SetHeight(&self, value: u32) {
image_dimension_setter(self.upcast(), ato... | // https://html.spec.whatwg.org/multipage/#dom-img-height | random_line_split |
manager.rs | use super::*;
use crate::app::{ddns, settings, user, vfs};
#[derive(Clone)]
pub struct Manager {
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
}
impl Manager {
pub fn new(
settings_manager: settings::Manager,
user_manager: user::Mana... |
pub fn apply(&self, config: &Config) -> Result<(), Error> {
if let Some(new_settings) = &config.settings {
self.settings_manager
.amend(new_settings)
.map_err(|_| Error::Unspecified)?;
}
if let Some(mount_dirs) = &config.mount_dirs {
self.vfs_manager
.set_mount_dirs(&mount_dirs)
.map_err... | {
Self {
settings_manager,
user_manager,
vfs_manager,
ddns_manager,
}
} | identifier_body |
manager.rs | use super::*;
use crate::app::{ddns, settings, user, vfs};
#[derive(Clone)]
pub struct Manager {
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
}
impl Manager {
pub fn new(
settings_manager: settings::Manager,
user_manager: user::Mana... | for old_user in old_users
.iter()
.filter(|old_user|!users.iter().any(|u| u.name == old_user.name))
{
self.user_manager
.delete(&old_user.name)
.map_err(|_| Error::Unspecified)?;
}
// Insert new users
for new_user in users
.iter()
.filter(|u|!old_users.iter().any(|old_user|... | // Delete users that are not in new list | random_line_split |
manager.rs | use super::*;
use crate::app::{ddns, settings, user, vfs};
#[derive(Clone)]
pub struct | {
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
}
impl Manager {
pub fn new(
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
) -> Self {
Self {
setti... | Manager | identifier_name |
manager.rs | use super::*;
use crate::app::{ddns, settings, user, vfs};
#[derive(Clone)]
pub struct Manager {
settings_manager: settings::Manager,
user_manager: user::Manager,
vfs_manager: vfs::Manager,
ddns_manager: ddns::Manager,
}
impl Manager {
pub fn new(
settings_manager: settings::Manager,
user_manager: user::Mana... |
if let Some(ddns_config) = &config.ydns {
self.ddns_manager
.set_config(&ddns_config)
.map_err(|_| Error::Unspecified)?;
}
if let Some(ref users) = config.users {
let old_users: Vec<user::User> =
self.user_manager.list().map_err(|_| Error::Unspecified)?;
// Delete users that are not in ne... | {
self.vfs_manager
.set_mount_dirs(&mount_dirs)
.map_err(|_| Error::Unspecified)?;
} | conditional_block |
insert_usage_mysql.rs | use chrono::{offset::Utc, DateTime};
use rustorm::{pool, DbError, FromDao, Pool, ToColumnNames, ToDao, ToTableName};
/// Run using:
/// ```sh
/// cargo run --example insert_usage_mysql --features "with-mysql"
/// ```
fn main() {
mod for_insert {
use super::*;
#[derive(Debug, PartialEq, ToDao, ToCol... | };
let tom_hanks = for_insert::Actor {
first_name: "TOM".into(),
last_name: "HANKS".to_string(),
};
println!("tom_cruise: {:#?}", tom_cruise);
println!("tom_hanks: {:#?}", tom_hanks);
let actors: Result<Vec<for_retrieve::Actor>, DbError> = em.insert(&[&tom_cruise, &tom_hanks]);
... | random_line_split | |
insert_usage_mysql.rs | use chrono::{offset::Utc, DateTime};
use rustorm::{pool, DbError, FromDao, Pool, ToColumnNames, ToDao, ToTableName};
/// Run using:
/// ```sh
/// cargo run --example insert_usage_mysql --features "with-mysql"
/// ```
fn | () {
mod for_insert {
use super::*;
#[derive(Debug, PartialEq, ToDao, ToColumnNames, ToTableName)]
pub struct Actor {
pub first_name: String,
pub last_name: String,
}
}
mod for_retrieve {
use super::*;
#[derive(Debug, FromDao, ToColumn... | main | identifier_name |
randomplay.rs | //! A bot playing randomly, but still following the rules.
| pub fn genmove(goban: &mut board::Board, player: board::Colour) -> board::Vertex {
let size = goban.get_size();
let mut rng = task_rng();
let mut i = 0u;
// try at most 10 random moves
while i < 10 {
let (x, y) = (rng.gen_range(1u, size+1), rng.gen_range(1u, size+1));
if goban.play(p... | use std::rand::{task_rng, Rng};
use board;
| random_line_split |
randomplay.rs | //! A bot playing randomly, but still following the rules.
use std::rand::{task_rng, Rng};
use board;
pub fn genmove(goban: &mut board::Board, player: board::Colour) -> board::Vertex {
let size = goban.get_size();
let mut rng = task_rng();
let mut i = 0u;
// try at most 10 random moves
while i < ... |
i = i+1;
}
// if we reach this point, random failed, we go for a more deterministic
// approach
for x in range(1u, size+1) {
for y in range(1u, size+1) {
if goban.play(player, x, y){
return board::Put(x,y);
}
}
}
// can play nothin... | {
return board::Put(x,y);
} | conditional_block |
randomplay.rs | //! A bot playing randomly, but still following the rules.
use std::rand::{task_rng, Rng};
use board;
pub fn | (goban: &mut board::Board, player: board::Colour) -> board::Vertex {
let size = goban.get_size();
let mut rng = task_rng();
let mut i = 0u;
// try at most 10 random moves
while i < 10 {
let (x, y) = (rng.gen_range(1u, size+1), rng.gen_range(1u, size+1));
if goban.play(player, x, y){
... | genmove | identifier_name |
randomplay.rs | //! A bot playing randomly, but still following the rules.
use std::rand::{task_rng, Rng};
use board;
pub fn genmove(goban: &mut board::Board, player: board::Colour) -> board::Vertex | }
// can play nothing?
board::Pass
}
| {
let size = goban.get_size();
let mut rng = task_rng();
let mut i = 0u;
// try at most 10 random moves
while i < 10 {
let (x, y) = (rng.gen_range(1u, size+1), rng.gen_range(1u, size+1));
if goban.play(player, x, y){
return board::Put(x,y);
}
i = i+1;
... | identifier_body |
performancetiming.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PerformanceTimingBinding;
use dom::bindings::js::{JSRef, Temporary};
use dom... | {
reflector_: Reflector,
navigationStart: u64,
navigationStartPrecise: f64,
}
impl PerformanceTiming {
pub fn new_inherited(navStart: u64, navStartPrecise: f64)
-> PerformanceTiming {
PerformanceTiming {
reflector_: Reflector::new(),
navigationS... | PerformanceTiming | identifier_name |
performancetiming.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PerformanceTimingBinding;
use dom::bindings::js::{JSRef, Temporary};
use dom... | }
impl<'a> PerformanceTimingMethods for JSRef<'a, PerformanceTiming> {
fn NavigationStart(&self) -> u64 {
self.navigationStart
}
fn NavigationStartPrecise(&self) -> f64 {
self.navigationStartPrecise
}
}
impl Reflectable for PerformanceTiming {
fn reflector<'a>(&'a self) -> &'a Ref... | }
pub trait PerformanceTimingMethods {
fn NavigationStart(&self) -> u64;
fn NavigationStartPrecise(&self) -> f64; | random_line_split |
key.rs | use anyhow::{anyhow, Context, Result};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{
de::{self, Deserializer, Visitor},
Deserialize, Serialize, Serializer,
};
use smallvec::SmallVec;
use std::{
convert::{TryFrom, TryInto},
ops::Deref,
result,
};
#[derive(Debug, Clone, Copy, ... |
key if key.starts_with('f') => {
let num = key[1..].parse().context("invalid F key")?;
if!(1..=12).contains(&num) {
return Err(anyhow!("F key must be between 1-12"));
}
KeyCode::F(num)
}
unknown =>... | {
let bytes = key.as_bytes();
KeyCode::Char(bytes[0] as char)
} | conditional_block |
key.rs | use anyhow::{anyhow, Context, Result};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{
de::{self, Deserializer, Visitor},
Deserialize, Serialize, Serializer,
};
use smallvec::SmallVec;
use std::{
convert::{TryFrom, TryInto},
ops::Deref,
result,
};
#[derive(Debug, Clone, Copy, ... |
}
impl Deref for Key {
type Target = KeyCode;
fn deref(&self) -> &Self::Target {
&self.0.code
}
}
impl TryFrom<&str> for Key {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let value = value.to_ascii_lowercase();
let modifier_split =... | {
self.0.modifiers.contains(KeyModifiers::CONTROL)
} | identifier_body |
key.rs | use anyhow::{anyhow, Context, Result};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{
de::{self, Deserializer, Visitor},
Deserialize, Serialize, Serializer,
};
use smallvec::SmallVec;
use std::{
convert::{TryFrom, TryInto},
ops::Deref,
result,
};
#[derive(Debug, Clone, Copy, ... | () {
test_key!("j", KeyCode::Char('j') => KeyModifiers::NONE);
test_key!("f1", KeyCode::F(1) => KeyModifiers::NONE);
test_key!("K", KeyCode::Char('k') => KeyModifiers::NONE);
test_key!("ctrl+b", KeyCode::Char('b') => KeyModifiers::CONTROL);
test_key!("CTRL+B", KeyCode::Char('b') ... | valid_keys | identifier_name |
key.rs | use anyhow::{anyhow, Context, Result};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{
de::{self, Deserializer, Visitor},
Deserialize, Serialize, Serializer,
};
use smallvec::SmallVec;
use std::{
convert::{TryFrom, TryInto},
ops::Deref,
result,
};
#[derive(Debug, Clone, Copy, ... | "pageup" => KeyCode::PageUp,
"pagedown" => KeyCode::PageDown,
"tab" => KeyCode::Tab,
"backtab" => KeyCode::BackTab,
"delete" => KeyCode::Delete,
"insert" => KeyCode::Insert,
"unknown" => KeyCode::Null,
"escape" => KeyCode::E... | "end" => KeyCode::End, | random_line_split |
lang_items.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 ... | FnTraitLangItem, "fn", fn_trait;
FnMutTraitLangItem, "fn_mut", fn_mut_trait;
FnOnceTraitLangItem, "fn_once", fn_once_trait;
EqTraitLangItem, "eq", eq_trait;
OrdTraitLa... |
DerefTraitLangItem, "deref", deref_trait;
DerefMutTraitLangItem, "deref_mut", deref_mut_trait;
| random_line_split |
issue-2311-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <A>(b: A) -> foo<A> {
foo {
x: b
}
}
pub fn main() { }
| foo | identifier_name |
issue-2311-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
trait clam<A> {
fn get(self) -> A;
}
struct foo<A> {
x: A,
}
impl<A> foo<A> {
pub fn bar<B,C:clam<A>>(&self, _c: C) -> B {
panic!();
}
}
fn foo<A>(b: A) -> foo<A> {
foo {
x: b
}
}
pub fn main() { } | // except according to those terms. | random_line_split |
main.rs | use std::error::Error;
use std::path::{Path, PathBuf};
use yaml_rust::{Yaml, YamlEmitter, YamlLoader};
/// List of directories containing files to expand. The first tuple element is the source
/// directory, while the second tuple element is the destination directory.
#[rustfmt::skip]
static TO_EXPAND: &[(&str, &str)]... | }
Mode::Generate => {
std::fs::write(dest, buf.as_bytes())
.with_context(|| format!("failed to write to {}", self.path(dest)))?;
}
}
Ok(())
}
fn path<'a>(&self, path: &'a Path) -> impl std::fmt::Display + 'a {
path.s... | random_line_split | |
main.rs | use std::error::Error;
use std::path::{Path, PathBuf};
use yaml_rust::{Yaml, YamlEmitter, YamlLoader};
/// List of directories containing files to expand. The first tuple element is the source
/// directory, while the second tuple element is the destination directory.
#[rustfmt::skip]
static TO_EXPAND: &[(&str, &str)]... | () {
if let Err(err) = App::from_args().and_then(|app| app.run()) {
eprintln!("error: {}", err);
let mut source = err.as_ref() as &dyn Error;
while let Some(err) = source.source() {
eprintln!("caused by: {}", err);
source = err;
}
std::process::exit(... | main | identifier_name |
mod.rs | #![allow(dead_code, unused_macros)]
pub mod callback;
#[macro_use]
#[path = "../../src/utils/memzeroize.rs"]
pub mod zeroize;
#[path = "../../src/utils/environment.rs"]
pub mod environment;
pub mod pool;
pub mod crypto;
pub mod did;
pub mod wallet;
pub mod ledger;
pub mod anoncreds;
pub mod types;
pub mod pairwise;... | () -> i32 {
setup();
pool::create_and_open_pool_ledger(constants::POOL).unwrap()
}
pub fn tear_down_with_pool(pool_handle: i32) {
pool::close(pool_handle).unwrap();
tear_down();
}
pub fn setup_with_wallet_and_pool() -> (i32, i32) {
let wallet_handle = setup_with_wallet();
let pool_handle = poo... | setup_with_pool | identifier_name |
mod.rs | #![allow(dead_code, unused_macros)]
pub mod callback;
#[macro_use]
#[path = "../../src/utils/memzeroize.rs"]
pub mod zeroize;
#[path = "../../src/utils/environment.rs"]
pub mod environment;
pub mod pool;
pub mod crypto;
pub mod did;
pub mod wallet;
pub mod ledger;
pub mod anoncreds;
pub mod types;
pub mod pairwise;... | } | random_line_split | |
mod.rs | #![allow(dead_code, unused_macros)]
pub mod callback;
#[macro_use]
#[path = "../../src/utils/memzeroize.rs"]
pub mod zeroize;
#[path = "../../src/utils/environment.rs"]
pub mod environment;
pub mod pool;
pub mod crypto;
pub mod did;
pub mod wallet;
pub mod ledger;
pub mod anoncreds;
pub mod types;
pub mod pairwise;... |
pub fn tear_down() {
test::cleanup_storage();
}
pub fn setup_with_wallet() -> i32 {
setup();
wallet::create_and_open_default_wallet().unwrap()
}
pub fn setup_with_plugged_wallet() -> i32 {
setup();
wallet::create_and_open_plugged_wallet().unwrap()
}
pub fn tear_down_with_wallet(wallet_handle: i... | {
test::cleanup_storage();
logger::set_default_logger();
} | identifier_body |
cstore.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 ... | -> @crate_metadata {
return *cstore.metas.get(&cnum);
}
pub fn get_crate_hash(cstore: &CStore, cnum: ast::CrateNum) -> @str {
let cdata = get_crate_data(cstore, cnum);
decoder::get_crate_hash(cdata.data)
}
pub fn get_crate_vers(cstore: &CStore, cnum: ast::CrateNum) -> @str {
let cda... | };
}
pub fn get_crate_data(cstore: &CStore, cnum: ast::CrateNum) | random_line_split |
cstore.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 ... | <'a>(cstore: &'a CStore) -> &'a [CrateSource] {
cstore.used_crate_sources.as_slice()
}
pub fn get_used_crates(cstore: &CStore, prefer: LinkagePreference)
-> ~[(ast::CrateNum, Option<Path>)]
{
let mut ret = ~[];
for src in cstore.used_crate_sources.iter() {
ret.push((src.cnum, match prefer {
... | get_used_crate_sources | identifier_name |
relay.rs | // Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// ... |
test_endpoint_2 = generate_random_endpoint(); };
assert_eq!(true, relay_map.add_client(test_public_id.clone(),
test_endpoint_1.clone()));
assert_eq!(true, relay_map.contains_relay_for(&test_id));
assert_eq!(true, relay_map.contains_endp... | { break; } | conditional_block |
relay.rs | // Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// ... | (our_id: &Id) -> RelayMap {
RelayMap {
relay_map: BTreeMap::new(),
lookup_map: HashMap::new(),
unknown_connections: HashMap::new(),
our_name: our_id.name(),
}
}
/// Adds an IP Node info to the relay map if the relay map has open
/// slots. Th... | new | identifier_name |
relay.rs | // Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// ... | /// Returns false if the endpoint is already assigned to a different name.
pub fn add_client(&mut self, relay_info: PublicId, relay_endpoint: Endpoint) -> bool {
// always reject our own id
if self.our_name == relay_info.name() {
return false;
}
// impose limit on num... | random_line_split | |
relay.rs | // Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// ... |
/// Returns Option<NameType> if an endpoint is found
pub fn lookup_endpoint(&self, relay_endpoint: &Endpoint) -> Option<Address> {
match self.lookup_map.get(relay_endpoint) {
Some(name) => Some(name.clone()),
None => None
}
}
/// This returns a pair of the stor... | {
self.lookup_map.contains_key(relay_endpoint)
} | identifier_body |
bgmacro.rs | use std::default::Default;
use std::env;
use std::path::Path;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base;
use syntax::fold::Folder;
use syntax::parse;
use syntax::parse::token;
use syntax::ptr::P;
use syntax::util::small_vector::SmallVector;
use bindgen::{Bindings, BindgenOptions, LinkType, Logger, s... | }
}
match parser.token {
// Match [ident]
token::Ident(val, _) => {
let val = parser.id_to_interned_str(val);
span.hi = parser.span.hi;
parser.bump();
// Bools are simply encoded as idents
... | {
let mut parser = cx.new_parser_from_tts(tts);
let mut args_good = true;
loop {
let mut name: Option<String> = None;
let mut span = parser.span;
// Check for [ident=]value and if found save ident to name
if parser.look_ahead(1, |t| t == &token::Eq) {
match pars... | identifier_body |
bgmacro.rs | use std::default::Default;
use std::env;
use std::path::Path;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base;
use syntax::fold::Folder;
use syntax::parse;
use syntax::parse::token;
use syntax::ptr::P;
use syntax::util::small_vector::SmallVector;
use bindgen::{Bindings, BindgenOptions, LinkType, Logger, s... | }
}
if parser.check(&token::Eof) {
return args_good
}
if parser.eat(&token::Comma).is_err() {
cx.span_err(parser.span, "invalid argument format");
return false
}
}
}
// I'm sure there's a nicer way of doing it
fn as_str<'a>(o... | random_line_split | |
bgmacro.rs | use std::default::Default;
use std::env;
use std::path::Path;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base;
use syntax::fold::Folder;
use syntax::parse;
use syntax::parse::token;
use syntax::ptr::P;
use syntax::util::small_vector::SmallVector;
use bindgen::{Bindings, BindgenOptions, LinkType, Logger, s... | <'a, 'b:'a> {
sp: codemap::Span,
cx: &'a base::ExtCtxt<'b>
}
impl<'a, 'b> Logger for MacroLogger<'a, 'b> {
fn error(&self, msg: &str) {
self.cx.span_err(self.sp, msg)
}
fn warn(&self, msg: &str) {
self.cx.span_warn(self.sp, msg)
}
}
struct BindgenResult {
items: Option<Sma... | MacroLogger | identifier_name |
bgmacro.rs | use std::default::Default;
use std::env;
use std::path::Path;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base;
use syntax::fold::Folder;
use syntax::parse;
use syntax::parse::token;
use syntax::ptr::P;
use syntax::util::small_vector::SmallVector;
use bindgen::{Bindings, BindgenOptions, LinkType, Logger, s... |
},
_ => {
cx.span_err(span, "invalid argument format");
return false
}
}
}
}
if parser.check(&token::Eof) {
return args_good
}
if parser.... | {
cx.span_err(span, "invalid argument");
args_good = false;
} | conditional_block |
item.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
//... | pub struct TodoListItemExternalModel {
pub text: String,
pub is_done: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct AddItemTodoListRequestModel {
pub token: String,
pub todo_list_id: String,
pub todo_list_item: TodoListItemExternalModel,
}
#[derive... | random_line_split | |
item.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
//... | {
pub text: String,
pub is_done: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct TodoListItemExternalModel {
pub text: String,
pub is_done: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct AddItemTodoListRe... | TodoListItemModel | identifier_name |
overloaded-calls-bad.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 s = S {
x: 3,
y: 3,
};
let ans = s("what"); //~ ERROR mismatched types
let ans = s(); //~ ERROR this function takes 1 parameter but 0 parameters were supplied
let ans = s("burma", "shave");
//~^ ERROR this function takes 1 parameter but 2 parameters were supplied
} | identifier_body | |
overloaded-calls-bad.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 ... | extern "rust-call" fn call_mut(&mut self, (z,): (isize,)) -> isize {
self.x * self.y * z
}
}
fn main() {
let mut s = S {
x: 3,
y: 3,
};
let ans = s("what"); //~ ERROR mismatched types
let ans = s(); //~ ERROR this function takes 1 parameter but 0 parameters were supp... | y: isize,
}
impl FnMut<(isize,),isize> for S { | random_line_split |
overloaded-calls-bad.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 s = S {
x: 3,
y: 3,
};
let ans = s("what"); //~ ERROR mismatched types
let ans = s(); //~ ERROR this function takes 1 parameter but 0 parameters were supplied
let ans = s("burma", "shave");
//~^ ERROR this function takes 1 parameter but 2 parameters were supplied... | main | identifier_name |
trailing_zeros.rs | use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::conversion::traits::WrappingFrom;
use malachite_base::num::logic::traits::TrailingZeros;
use malachite_base::slices::slice_leading_zeros;
use natural::InnerNatural::{Large, Small};
use natural::Natural;
use platform::Limb;
/// Interpretin... |
}
| {
match *self {
natural_zero!() => None,
Natural(Small(small)) => Some(TrailingZeros::trailing_zeros(small)),
Natural(Large(ref limbs)) => Some(limbs_trailing_zeros(limbs)),
}
} | identifier_body |
trailing_zeros.rs | use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::conversion::traits::WrappingFrom;
use malachite_base::num::logic::traits::TrailingZeros;
use malachite_base::slices::slice_leading_zeros;
use natural::InnerNatural::{Large, Small};
use natural::Natural;
use platform::Limb;
/// Interpretin... | /// Time: worst case O(n)
///
/// Additional memory: worst case O(1)
///
/// where n = `self.significant_bits()`
///
/// # Examples
/// ```
/// extern crate malachite_base;
/// extern crate malachite_nz;
///
/// use malachite_base::num::basic::traits::Zero;
/// use ma... | impl Natural {
/// Returns the number of trailing zeros in the binary expansion of a `Natural` (equivalently,
/// the multiplicity of 2 in its prime factorization) or `None` is the `Natural` is 0.
/// | random_line_split |
trailing_zeros.rs | use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::conversion::traits::WrappingFrom;
use malachite_base::num::logic::traits::TrailingZeros;
use malachite_base::slices::slice_leading_zeros;
use natural::InnerNatural::{Large, Small};
use natural::Natural;
use platform::Limb;
/// Interpretin... | (xs: &[Limb]) -> u64 {
let zeros = slice_leading_zeros(xs);
let remaining_zeros = TrailingZeros::trailing_zeros(xs[zeros]);
(u64::wrapping_from(zeros) << Limb::LOG_WIDTH) + remaining_zeros
}
impl Natural {
/// Returns the number of trailing zeros in the binary expansion of a `Natural` (equivalently,
... | limbs_trailing_zeros | identifier_name |
foo.rs | // Like the `long-linker-command-lines` test this test attempts to blow
// a command line limit for running the linker. Unlike that test, however,
// this test is testing `cmd.exe` specifically rather than the OS.
//
// Unfortunately `cmd.exe` has a 8192 limit which is relatively small
// in the grand scheme of things ... | let me = env::current_exe().unwrap();
let bat = me.parent()
.unwrap()
.join("foo.bat");
let bat_linker = format!("linker={}", bat.display());
for i in (1..).map(|i| i * 10) {
println!("attempt: {}", i);
let file = tmpdir.join("bar.rs");
let mut f = BufWriter::new(F... | {
if !cfg!(windows) {
return
}
let tmpdir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let ok = tmpdir.join("ok");
let not_ok = tmpdir.join("not_ok");
if env::var("YOU_ARE_A_LINKER").is_ok() {
match env::args_os().find(|a| a.to_string_lossy().contains("@")) {
So... | identifier_body |
foo.rs | // Like the `long-linker-command-lines` test this test attempts to blow
// a command line limit for running the linker. Unlike that test, however,
// this test is testing `cmd.exe` specifically rather than the OS.
//
// Unfortunately `cmd.exe` has a 8192 limit which is relatively small
// in the grand scheme of things ... | () {
if!cfg!(windows) {
return
}
let tmpdir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let ok = tmpdir.join("ok");
let not_ok = tmpdir.join("not_ok");
if env::var("YOU_ARE_A_LINKER").is_ok() {
match env::args_os().find(|a| a.to_string_lossy().contains("@")) {
... | main | identifier_name |
foo.rs | // Like the `long-linker-command-lines` test this test attempts to blow
// a command line limit for running the linker. Unlike that test, however,
// this test is testing `cmd.exe` specifically rather than the OS.
//
// Unfortunately `cmd.exe` has a 8192 limit which is relatively small
// in the grand scheme of things ... | }
} | }
break | random_line_split |
foo.rs | // Like the `long-linker-command-lines` test this test attempts to blow
// a command line limit for running the linker. Unlike that test, however,
// this test is testing `cmd.exe` specifically rather than the OS.
//
// Unfortunately `cmd.exe` has a 8192 limit which is relatively small
// in the grand scheme of things ... |
let tmpdir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let ok = tmpdir.join("ok");
let not_ok = tmpdir.join("not_ok");
if env::var("YOU_ARE_A_LINKER").is_ok() {
match env::args_os().find(|a| a.to_string_lossy().contains("@")) {
Some(file) => {
let file = file.... | {
return
} | conditional_block |
standard.rs | use std::sync::Arc;
use std::marker::PhantomData;
use par_exec::{Executor, WorkAmount, JobIterBuild, ExecutorJobError, JobExecuteError};
use super::PopulationFit;
use super::super::individual::IndividualManager;
use super::super::super::set::{Set, SetManager};
use super::super::super::set::union;
pub trait RetrieveFi... | <WA>(&self, population: Arc<Self::Pop>, exec: &mut Self::Exec) -> Result<Self::Fits, Self::Err>
where WA: WorkAmount, <Self::Exec as Executor>::JIB: JobIterBuild<WA>
{
let population_size = population.size();
match exec.try_execute_job(
WA::new(population_size),
move ... | fit | identifier_name |
standard.rs | use std::sync::Arc;
use std::marker::PhantomData;
use par_exec::{Executor, WorkAmount, JobIterBuild, ExecutorJobError, JobExecuteError};
use super::PopulationFit;
use super::super::individual::IndividualManager;
use super::super::super::set::{Set, SetManager};
use super::super::super::set::union;
pub trait RetrieveFi... |
}
| {
let exec: ParallelExecutor<_> = Default::default();
let mut exec = exec.start(|| LocalContext {
set_manager: set::vec::Manager::new(),
indiv_manager: IndivManager,
}).unwrap();
use std::sync::Arc;
let population = Arc::new((0 .. 1024).collect::<Vec<_>>(... | identifier_body |
standard.rs | use std::sync::Arc;
use std::marker::PhantomData;
use par_exec::{Executor, WorkAmount, JobIterBuild, ExecutorJobError, JobExecuteError};
use super::PopulationFit;
use super::super::individual::IndividualManager;
use super::super::super::set::{Set, SetManager};
use super::super::super::set::union;
pub trait RetrieveFi... | }
}
struct LocalContext {
set_manager: set::vec::Manager<(f64, usize)>,
indiv_manager: IndivManager,
}
impl RetrieveFitsManager for LocalContext {
type FitsM = set::vec::Manager<(f64, usize)>;
fn retrieve(&mut self) -> &mut Self::FitsM {
&mut self.s... | }
fn fitness(&mut self, indiv: &Self::I) -> Result<Self::FI, Self::E> {
Ok(1.0 / *indiv as f64) | random_line_split |
typeck-default-trait-impl-trait-where-clause.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
foo::<i32>();
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
} | identifier_body | |
typeck-default-trait-impl-trait-where-clause.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | //~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
}
fn main() {
foo::<i32>();
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
} | fn test() {
bar::<Option<i32>>(); | random_line_split |
typeck-default-trait-impl-trait-where-clause.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T:NotImplemented>() { }
fn test() {
bar::<Option<i32>>();
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
}
fn main() {
foo::<i32>();
//~^ ERROR the trait `NotImplemented` is not implemented for the type `core::option::Option<i32>`
}
| bar | identifier_name |
connection.rs | use std::ptr;
use std::ffi::CString;
use error::{RuntimeError, ErrorKind};
use super::super::x11::ScreenID;
use super::ffi;
use super::screen::Screen;
use super::XID;
use super::event::{Event, EventIterator};
use super::atom::{InternAtomCookie, InternAtomReply};
pub struct Connection {
pub ptr: *mut ffi::xcb_co... |
pub fn flush(&self) {
unsafe {
ffi::xcb_flush(self.ptr);
}
}
pub fn intern_atom(&self, name: &str, existing_only: bool) -> InternAtomCookie {
let c_name = CString::new(name).unwrap();
let xcb_cookie = unsafe {
ffi::xcb_intern_atom(
self.ptr,
... | {
EventIterator::new(self.ptr)
} | identifier_body |
connection.rs | use std::ptr;
use std::ffi::CString;
use error::{RuntimeError, ErrorKind};
use super::super::x11::ScreenID;
use super::ffi;
use super::screen::Screen;
use super::XID;
use super::event::{Event, EventIterator};
use super::atom::{InternAtomCookie, InternAtomReply};
pub struct Connection {
pub ptr: *mut ffi::xcb_co... | (&self, screen_id: &ScreenID) -> Result<Screen, RuntimeError> {
let setup = unsafe { ffi::xcb_get_setup(self.ptr) };
if setup == ptr::null() {
return Err(RuntimeError::new(
ErrorKind::XCB,
"Getting XCB connection setup failed".to_string()
));
}
let mut... | screen_of_display | identifier_name |
connection.rs | use std::ptr;
use std::ffi::CString;
use error::{RuntimeError, ErrorKind};
use super::super::x11::ScreenID;
use super::ffi;
use super::screen::Screen;
use super::XID;
use super::event::{Event, EventIterator};
use super::atom::{InternAtomCookie, InternAtomReply};
pub struct Connection {
pub ptr: *mut ffi::xcb_co... |
None
}
}
| {
return Some(
unsafe {
(*error).error_code
}
)
} | conditional_block |
connection.rs | use std::ptr;
use std::ffi::CString;
use error::{RuntimeError, ErrorKind};
use super::super::x11::ScreenID;
use super::ffi;
use super::screen::Screen;
use super::XID;
use super::event::{Event, EventIterator};
use super::atom::{InternAtomCookie, InternAtomReply};
pub struct Connection {
pub ptr: *mut ffi::xcb_co... | Ok(XID {
id: id
})
}
pub fn wait_for_event(&self) -> Option<Event> {
let event_ptr = unsafe {
ffi::xcb_wait_for_event(self.ptr)
};
if event_ptr.is_null() {
return None;
}
Some(
Event::new(event_ptr)
)
}
pub fn poll_event... | ErrorKind::XCB,
"Generating XID failed".to_string()
));
}
| random_line_split |
resource_thread.rs | auth_cache: Arc<RwLock<AuthCache>>,
hsts_list: Arc<RwLock<HstsList>>,
connector: Arc<Pool<Connector>>,
}
impl ProgressSender {
//XXXjdm return actual error
pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> {
match *self {
ProgressSender::Channel(ref c) => c.send(msg).map_err... | network_error: Option<NetworkError>) -> Result<ProgressSender, ()> {
match start_chan {
LoadConsumer::Channel(start_chan) => {
let (progress_chan, progress_port) = ipc::channel().unwrap();
let result = start_chan.send(LoadResponse {
metadata: meta... | fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata, | random_line_split |
resource_thread.rs | auth_cache: Arc<RwLock<AuthCache>>,
hsts_list: Arc<RwLock<HstsList>>,
connector: Arc<Pool<Connector>>,
}
impl ProgressSender {
//XXXjdm return actual error
pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> {
match *self {
ProgressSender::Channel(ref c) => c.send(msg).map_err(... | {
/// The receiver which receives a message on load cancellation
cancel_receiver: Receiver<()>,
/// The `CancellationListener` is unique to this `ResourceId`
resource_id: ResourceId,
/// If we haven't initiated any cancel requests, then the loaders ask
/// the listener to remove the `ResourceId... | CancellableResource | identifier_name |
multi.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | sets: BTreeMap<BlockNumber, Box<ValidatorSet>>,
block_number: RwLock<BlockNumberLookup>,
}
impl Multi {
pub fn new(set_map: BTreeMap<BlockNumber, Box<ValidatorSet>>) -> Self {
assert!(set_map.get(&0u64).is_some(), "ValidatorSet has to be specified from block 0.");
Multi {
sets: set_map,
block_number: RwLo... | pub struct Multi { | random_line_split |
multi.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (&self, header: &Header, call: &Call) -> Result<Vec<u8>, String> {
self.correct_set_by_number(0).1.genesis_epoch_data(header, call)
}
fn is_epoch_end(&self, _first: bool, chain_head: &Header) -> Option<Vec<u8>> {
let (set_block, set) = self.correct_set_by_number(chain_head.number());
let first = set_block == c... | genesis_epoch_data | identifier_name |
multi.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
fn count_with_caller(&self, bh: &H256, caller: &Call) -> usize {
self.correct_set(BlockId::Hash(*bh))
.map_or_else(usize::max_value, |set| set.count_with_caller(bh, caller))
}
fn report_malicious(&self, validator: &Address, set_block: BlockNumber, block: BlockNumber, proof: Bytes) {
self.correct_set_by_num... | {
self.correct_set(BlockId::Hash(*bh))
.map_or_else(Default::default, |set| set.get_with_caller(bh, nonce, caller))
} | identifier_body |
rlptraits.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | /// Apends value to the end of stream, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append(&"cat").append(&"dog");
/// let out = stream.out();
/// assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd'... |
/// Initializes the `Stream` as a list.
fn new_list(len: usize) -> Self;
| random_line_split |
rlptraits.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | (&self) -> ElasticArray1024<u8> {
let mut s = RlpStream::new();
self.rlp_append(&mut s);
s.drain()
}
}
/// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list
pub trait RlpEncodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
}
... | rlp_bytes | identifier_name |
rlptraits.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
}
/// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list
pub trait RlpEncodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
}
/// RLP encoding stream
pub trait Stream: Sized {
/// Initializes instance of empty `Stream`.
fn new() ... | {
let mut s = RlpStream::new();
self.rlp_append(&mut s);
s.drain()
} | identifier_body |
map3one.rs | use itertools::izip;
use mli::{Backward, Forward, Train};
use ndarray::{Array, Array3};
use num_traits::Zero;
use std::ops::Add;
#[derive(Clone, Debug)]
pub struct Map3One<G>(pub G);
impl<G> Forward for Map3One<G>
where
G: Forward,
{
type Input = Array3<G::Input>;
type Internal = Array3<G::Internal>;
... |
impl<G> Backward for Map3One<G>
where
G: Backward,
G::TrainDelta: Clone + Add + Zero,
{
type OutputDelta = Array3<G::OutputDelta>;
type InputDelta = Array3<G::InputDelta>;
type TrainDelta = G::TrainDelta;
fn backward(
&self,
input: &Self::Input,
internal: &Self::Interna... | let output_array = Array::from_shape_vec(input.raw_dim(), output_vec).unwrap();
(internal_array, output_array)
}
} | random_line_split |
map3one.rs | use itertools::izip;
use mli::{Backward, Forward, Train};
use ndarray::{Array, Array3};
use num_traits::Zero;
use std::ops::Add;
#[derive(Clone, Debug)]
pub struct | <G>(pub G);
impl<G> Forward for Map3One<G>
where
G: Forward,
{
type Input = Array3<G::Input>;
type Internal = Array3<G::Internal>;
type Output = Array3<G::Output>;
fn forward(&self, input: &Self::Input) -> (Self::Internal, Self::Output) {
let both = input.iter().map(|input| self.0.forward(... | Map3One | identifier_name |
map3one.rs | use itertools::izip;
use mli::{Backward, Forward, Train};
use ndarray::{Array, Array3};
use num_traits::Zero;
use std::ops::Add;
#[derive(Clone, Debug)]
pub struct Map3One<G>(pub G);
impl<G> Forward for Map3One<G>
where
G: Forward,
{
type Input = Array3<G::Input>;
type Internal = Array3<G::Internal>;
... |
}
| {
self.0.train(train_delta);
} | identifier_body |
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/.
//! Multi-threading
//!
//! = Examples
//!
//! ----
//! let mut array = [1u8; 1024];
//! {
//! let res = scoped(|... | //! for i in 0..SIZE {
//! assert!(array[i] == 2);
//! }
//! ----
pub use lrs_thread::{
Builder, spawn, scoped, JoinGuard, cpu_count, CpuMask, cpus, set_cpus, unshare,
current_cpu, join_namespace, thread_id, exit, deschedule, enter_strict_mode,
at_exit,
};
pub use lrs_thread::ids::{
UserIds, GroupI... | random_line_split | |
borrowck-uniq-via-lend.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 ... | {
} | identifier_body | |
borrowck-uniq-via-lend.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 ... | { g: H }
struct H { h: Box<int> }
let mut v = F {f: G {g: H {h: box 3}}};
borrow(&*v.f.g.h);
}
fn aliased_imm() {
let mut v = box 3i;
let _w = &v;
borrow(&*v);
}
fn aliased_mut() {
let mut v = box 3i;
let _w = &mut v;
borrow(&*v); //~ ERROR cannot borrow `*v`
}
fn aliased_other()... | G | identifier_name |
borrowck-uniq-via-lend.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 ... | struct G { g: H }
struct H { h: Box<int> }
let mut v = F {f: G {g: H {h: box 3}}};
borrow(&*v.f.g.h);
}
fn aliased_imm() {
let mut v = box 3i;
let _w = &v;
borrow(&*v);
}
fn aliased_mut() {
let mut v = box 3i;
let _w = &mut v;
borrow(&*v); //~ ERROR cannot borrow `*v`
}
fn ali... | borrow(&*v.f);
}
fn local_recs() {
struct F { f: G } | random_line_split |
distinct.rs | use std::collections::{HashMap, HashSet};
use std::collections::hash_state::DefaultState;
use std::hash::{hash, Hash, SipHasher};
use std::default::Default;
use communication::Data;
use communication::pact::Exchange;
use construction::{Stream, GraphBuilder};
use construction::operators::unary::UnaryNotifyExt;
use se... | (&self) -> Stream<G, D> {
let mut elements: HashMap<_, HashSet<_, DefaultState<SipHasher>>> = HashMap::new();
let exch = Exchange::new(|x| hash::<_,SipHasher>(&x));
self.unary_notify(exch, "Distinct", vec![], move |input, output, notificator| {
while let Some((time, data)) = input.pu... | distinct | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.