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 |
|---|---|---|---|---|
logger.rs | extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_logger::Filter;
use lo... | #[macro_export]
macro_rules! try_log {
($expr:expr) => (match $expr {
Ok(val) => val,
Err(err) => {
error!("try_log! | {}", err);
return Err(From::from(err))
}
})
}
macro_rules! _map_err {
($lvl:expr, $expr:expr) => (
|err| {
log!($lvl, "{... | random_line_split | |
eo_view.rs | // std imports
use std::mem;
// external imports
use num::traits::Num;
// local imports
use sralgebra::MagmaBase;
use super::eo_traits::{ERO, ECO};
use view::MatrixView;
use traits::{Shape, MatrixBuffer, Strided};
/// Implementation of Elementary row operations.
impl<'a, T:MagmaBase + Num> ERO<T> for MatrixView<'... | fn ero_scale_add(&mut self,
i : usize,
j : isize,
scale : T
)-> &mut MatrixView<'a, T> {
debug_assert! (i < self.num_rows());
let m = self.matrix();
// Compute j-th row in m (by doing offset)
let j = j + (self.start_row() as isize);
debug... | #[inline] | random_line_split |
eo_view.rs |
// std imports
use std::mem;
// external imports
use num::traits::Num;
// local imports
use sralgebra::MagmaBase;
use super::eo_traits::{ERO, ECO};
use view::MatrixView;
use traits::{Shape, MatrixBuffer, Strided};
/// Implementation of Elementary row operations.
impl<'a, T:MagmaBase + Num> ERO<T> for MatrixView<... | }
// Update offsets
offset_a += 1;
offset_b += 1;
}
self
}
}
/******************************************************
*
* Unit tests
*
*******************************************************/
#[cfg(test)]
mod test{
//use super::*;
}
/*... | {
debug_assert! (i < self.num_cols());
let m = self.matrix();
// Compute j-th column in m (by doing offset)
let j = j + (self.start_col() as isize);
debug_assert! (j >= 0);
let j = j as usize;
debug_assert!(j < m.num_cols());
let ptr = m.as_ptr();
... | identifier_body |
eo_view.rs |
// std imports
use std::mem;
// external imports
use num::traits::Num;
// local imports
use sralgebra::MagmaBase;
use super::eo_traits::{ERO, ECO};
use view::MatrixView;
use traits::{Shape, MatrixBuffer, Strided};
/// Implementation of Elementary row operations.
impl<'a, T:MagmaBase + Num> ERO<T> for MatrixView<... | (&mut self,
i : usize,
j : isize,
scale : T
)-> &mut MatrixView<'a, T> {
debug_assert! (i < self.num_cols());
let m = self.matrix();
// Compute j-th column in m (by doing offset)
let j = j + (self.start_col() as isize);
debug_assert! (j >= 0... | eco_scale_add | identifier_name |
mount.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 base::prelude::*;
use core::{mem};
use core::ops::{BitOr, Not, BitAnd};
use cty::{c_ulong, MS_RDONLY, MS_NOSUID, ... | (self, other: MountFlags) -> MountFlags {
MountFlags(self.0 | other.0)
}
}
impl BitAnd for MountFlags {
type Output = MountFlags;
fn bitand(self, other: MountFlags) -> MountFlags {
MountFlags(self.0 & other.0)
}
}
impl Not for MountFlags {
type Output = MountFlags;
fn not(self)... | bitor | identifier_name |
mount.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 base::prelude::*;
use core::{mem};
use core::ops::{BitOr, Not, BitAnd};
use cty::{c_ulong, MS_RDONLY, MS_NOSUID, ... |
}
impl BitAnd for MountFlags {
type Output = MountFlags;
fn bitand(self, other: MountFlags) -> MountFlags {
MountFlags(self.0 & other.0)
}
}
impl Not for MountFlags {
type Output = MountFlags;
fn not(self) -> MountFlags {
MountFlags(!self.0)
}
}
pub const MOUNT_NONE: MountFla... | {
MountFlags(self.0 | other.0)
} | identifier_body |
mount.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 base::prelude::*;
use core::{mem};
use core::ops::{BitOr, Not, BitAnd};
use cty::{c_ulong, MS_RDONLY, MS_NOSUID, ... | #[doc = "* link:man:mount(2) and MS_DIRSYNC therein"]
flag MOUNT_DIR_SYNC = MS_DIRSYNC;
#[doc = "Don't update the access times of files on this filesystem.\n"]
#[doc = "= See also"]
#[doc = "* link:man:mount(2) and MS_NOATIME therein"]
flag MOUNT_NO_ACCESS_TIME = MS_NOATIME;
#[doc = "Don't... | #[doc = "= See also"] | random_line_split |
font_template.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 std::io;
use std::io::File;
/// Platform specific font representation for Linux.
/// The identifier is an abs... | {
pub bytes: Vec<u8>,
pub identifier: String,
}
impl FontTemplateData {
pub fn new(identifier: &str, font_data: Option<Vec<u8>>) -> FontTemplateData {
let bytes = match font_data {
Some(bytes) => {
bytes
},
None => {
// TODO: Hand... | FontTemplateData | identifier_name |
font_template.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 std::io;
use std::io::File;
/// Platform specific font representation for Linux.
/// The identifier is an abs... |
}
| {
let bytes = match font_data {
Some(bytes) => {
bytes
},
None => {
// TODO: Handle file load failure!
let mut file = File::open_mode(&Path::new(identifier), io::Open, io::Read).unwrap();
file.read_to_end().unwra... | identifier_body |
font_template.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 std::io;
use std::io::File;
/// Platform specific font representation for Linux.
/// The identifier is an abs... | ,
};
FontTemplateData {
bytes: bytes,
identifier: identifier.to_string(),
}
}
}
| {
// TODO: Handle file load failure!
let mut file = File::open_mode(&Path::new(identifier), io::Open, io::Read).unwrap();
file.read_to_end().unwrap()
} | conditional_block |
font_template.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 std::io;
use std::io::File;
| /// The identifier is an absolute path, and the bytes
/// field is the loaded data that can be passed to
/// freetype and azure directly.
pub struct FontTemplateData {
pub bytes: Vec<u8>,
pub identifier: String,
}
impl FontTemplateData {
pub fn new(identifier: &str, font_data: Option<Vec<u8>>) -> FontTempl... | /// Platform specific font representation for Linux. | random_line_split |
issue-21400.rs | // run-pass
// Regression test for #21400 which itself was extracted from
// stackoverflow.com/questions/28031155/is-my-borrow-checker-drunk/28031580
fn main() {
let mut t = Test;
assert_eq!(t.method1("one"), Ok(1));
assert_eq!(t.method2("two"), Ok(2));
assert_eq!(t.test(), Ok(2));
}
| }
fn method2(self: &mut Test, _arg: &str) -> Result<usize, &str> {
Ok(2)
}
fn test(self: &mut Test) -> Result<usize, &str> {
let s = format!("abcde");
// (Originally, this invocation of method2 was saying that `s`
// does not live long enough.)
let data = match ... | struct Test;
impl Test {
fn method1(&mut self, _arg: &str) -> Result<usize, &str> {
Ok(1) | random_line_split |
issue-21400.rs | // run-pass
// Regression test for #21400 which itself was extracted from
// stackoverflow.com/questions/28031155/is-my-borrow-checker-drunk/28031580
fn main() {
let mut t = Test;
assert_eq!(t.method1("one"), Ok(1));
assert_eq!(t.method2("two"), Ok(2));
assert_eq!(t.test(), Ok(2));
}
struct Test;
imp... |
}
// Below is a closer match for the original test that was failing to compile
pub struct GitConnect;
impl GitConnect {
fn command(self: &mut GitConnect, _s: &str) -> Result<Vec<Vec<u8>>, &str> {
unimplemented!()
}
pub fn git_upload_pack(self: &mut GitConnect) -> Result<String, &str> {
... | {
let s = format!("abcde");
// (Originally, this invocation of method2 was saying that `s`
// does not live long enough.)
let data = match self.method2(&*s) {
Ok(r) => r,
Err(e) => return Err(e)
};
Ok(data)
} | identifier_body |
issue-21400.rs | // run-pass
// Regression test for #21400 which itself was extracted from
// stackoverflow.com/questions/28031155/is-my-borrow-checker-drunk/28031580
fn main() {
let mut t = Test;
assert_eq!(t.method1("one"), Ok(1));
assert_eq!(t.method2("two"), Ok(2));
assert_eq!(t.test(), Ok(2));
}
struct Test;
imp... | (self: &mut GitConnect) -> Result<String, &str> {
let c = format!("git-upload-pack");
let mut out = String::new();
let data = self.command(&c)?;
for line in data.iter() {
out.push_str(&format!("{:?}", line));
}
Ok(out)
}
}
| git_upload_pack | identifier_name |
order_code.rs | #[derive(Clone, PartialEq)]
pub struct OrderCode {
pub value: String,
}
impl OrderCode {
pub fn new(year: i32, number: usize) -> OrderCode {
let code = format!("{:04}{:08}", year, number);
return OrderCode { value: code };
}
}
impl FromStr for OrderCode {
type Err = String;
fn fro... | // value object
#[allow(dead_code)]
use std::str::FromStr;
| random_line_split | |
order_code.rs | // value object
#[allow(dead_code)]
use std::str::FromStr;
#[derive(Clone, PartialEq)]
pub struct | {
pub value: String,
}
impl OrderCode {
pub fn new(year: i32, number: usize) -> OrderCode {
let code = format!("{:04}{:08}", year, number);
return OrderCode { value: code };
}
}
impl FromStr for OrderCode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
... | OrderCode | identifier_name |
vimawesome.rs | use std::io;
use std::process::{Command, Stdio};
use std::rc::Rc;
use std::thread;
use serde_json;
use glib;
use gtk;
use gtk::prelude::*;
use super::store::PlugInfo;
pub fn call<F>(query: Option<String>, cb: F)
where
F: FnOnce(io::Result<DescriptionList>) + Send +'static,
{
thread::spawn(move || {
... |
fn request(query: Option<&str>) -> io::Result<DescriptionList> {
let child = Command::new("curl")
.arg("-s")
.arg(format!(
"https://vimawesome.com/api/plugins?query={}&page=1",
query.unwrap_or("")
))
.stdout(Stdio::piped())
.spawn()?;
let out = child... | cb.take().unwrap()(result.take().unwrap());
Continue(false)
})
});
} | random_line_split |
vimawesome.rs | use std::io;
use std::process::{Command, Stdio};
use std::rc::Rc;
use std::thread;
use serde_json;
use glib;
use gtk;
use gtk::prelude::*;
use super::store::PlugInfo;
pub fn call<F>(query: Option<String>, cb: F)
where
F: FnOnce(io::Result<DescriptionList>) + Send +'static,
{
thread::spawn(move || {
... | {
pub plugins: Box<[Description]>,
}
impl DescriptionList {
fn empty() -> DescriptionList {
DescriptionList {
plugins: Box::new([]),
}
}
}
#[derive(Deserialize, Debug, Clone)]
pub struct Description {
pub name: String,
pub github_url: Option<String>,
pub author: Op... | DescriptionList | identifier_name |
vimawesome.rs | use std::io;
use std::process::{Command, Stdio};
use std::rc::Rc;
use std::thread;
use serde_json;
use glib;
use gtk;
use gtk::prelude::*;
use super::store::PlugInfo;
pub fn call<F>(query: Option<String>, cb: F)
where
F: FnOnce(io::Result<DescriptionList>) + Send +'static,
{
thread::spawn(move || {
... |
}
pub fn build_result_panel<F: Fn(PlugInfo) +'static>(
list: &DescriptionList,
add_cb: F,
) -> gtk::ScrolledWindow {
let scroll = gtk::ScrolledWindow::new(
Option::<>k::Adjustment>::None,
Option::<>k::Adjustment>::None,
);
scroll.get_style_context().add_class("view");
let p... | {
Err(io::Error::new(
io::ErrorKind::Other,
format!(
"curl exit with error:\n{}",
match out.status.code() {
Some(code) => format!("Exited with status code: {}", code),
None => "Process terminated by signal".to_owned(... | conditional_block |
osstringext.rs | use std::ffi::OsStr;
#[cfg(not(target_os = "windows"))]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "windows")]
use INVALID_UTF8;
#[cfg(target_os = "windows")]
trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
#[doc(hidden)]
pub trait OsStrExt2 {
fn starts_with(&s... | for (i, b) in self.as_bytes().iter().enumerate() {
if b!= &byte { return &OsStr::from_bytes(&self.as_bytes()[i..]); }
}
&*self
}
fn split_at(&self, i: usize) -> (&OsStr, &OsStr) {
(&OsStr::from_bytes(&self.as_bytes()[..i]), &OsStr::from_bytes(&self.as_bytes()[i..]))
... | }
(&*self, &OsStr::from_bytes(&self.as_bytes()[self.len_()..self.len_()]))
}
fn trim_left_matches(&self, byte: u8) -> &OsStr { | random_line_split |
osstringext.rs | use std::ffi::OsStr;
#[cfg(not(target_os = "windows"))]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "windows")]
use INVALID_UTF8;
#[cfg(target_os = "windows")]
trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
#[doc(hidden)]
pub trait OsStrExt2 {
fn starts_with(&s... | (&self, byte: u8) -> bool {
for b in self.as_bytes() {
if b == &byte { return true; }
}
false
}
fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) {
for (i, b) in self.as_bytes().iter().enumerate() {
if b == &byte { return (&OsStr::from_bytes(&self.as_... | contains_byte | identifier_name |
osstringext.rs | use std::ffi::OsStr;
#[cfg(not(target_os = "windows"))]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "windows")]
use INVALID_UTF8;
#[cfg(target_os = "windows")]
trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
#[doc(hidden)]
pub trait OsStrExt2 {
fn starts_with(&s... |
}
if count > 0 {
return (count, Some(count));
}
(0, None)
}
}
impl<'a> DoubleEndedIterator for OsSplit<'a> {
fn next_back(&mut self) -> Option<&'a OsStr> {
if self.pos == 0 { return None; }
let start = self.pos;
for b in self.val[..self.pos].... | { count += 1; } | conditional_block |
osstringext.rs | use std::ffi::OsStr;
#[cfg(not(target_os = "windows"))]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "windows")]
use INVALID_UTF8;
#[cfg(target_os = "windows")]
trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
#[doc(hidden)]
pub trait OsStrExt2 {
fn starts_with(&s... |
fn trim_left_matches(&self, byte: u8) -> &OsStr {
for (i, b) in self.as_bytes().iter().enumerate() {
if b!= &byte { return &OsStr::from_bytes(&self.as_bytes()[i..]); }
}
&*self
}
fn split_at(&self, i: usize) -> (&OsStr, &OsStr) {
(&OsStr::from_bytes(&self.as_by... | {
for (i, b) in self.as_bytes().iter().enumerate() {
if b == &byte { return (&OsStr::from_bytes(&self.as_bytes()[..i]), &OsStr::from_bytes(&self.as_bytes()[i+1..])); }
}
(&*self, &OsStr::from_bytes(&self.as_bytes()[self.len_()..self.len_()]))
} | identifier_body |
stack.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) Nathan Zadoks <nathan@nathan7.eu>
// 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 o... | /// the following contract:
///
/// * The base address of the stack must be aligned to
/// a [`STACK_ALIGNMENT`][align]-byte boundary.
/// * Every address between the base and the limit must be readable and writable.
///
/// [align]: constant.STACK_ALIGNMENT.html
pub trait Stack {
/// Returns the base address... | random_line_split | |
bootstrapper.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
client::{CoordinatorMessage, StateSyncClient},
coordinator::StateSyncCoordinator,
executor_proxy::{ExecutorProxy, ExecutorProxyTrait},
network::{StateSyncEvents, StateSyncSender},
};
use diem_config::{config:... |
pub fn bootstrap_with_executor_proxy<E: ExecutorProxyTrait +'static>(
runtime: Runtime,
network: Vec<(NodeNetworkId, StateSyncSender, StateSyncEvents)>,
state_sync_to_mempool_sender: mpsc::Sender<diem_mempool::CommitNotification>,
node_config: &NodeConfig,
waypoint: Waypoint... | } | random_line_split |
bootstrapper.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
client::{CoordinatorMessage, StateSyncClient},
coordinator::StateSyncCoordinator,
executor_proxy::{ExecutorProxy, ExecutorProxyTrait},
network::{StateSyncEvents, StateSyncSender},
};
use diem_config::{config:... | {
_runtime: Runtime,
coordinator_sender: mpsc::UnboundedSender<CoordinatorMessage>,
}
impl StateSyncBootstrapper {
pub fn bootstrap(
network: Vec<(NodeNetworkId, StateSyncSender, StateSyncEvents)>,
state_sync_to_mempool_sender: mpsc::Sender<diem_mempool::CommitNotification>,
storag... | StateSyncBootstrapper | identifier_name |
bootstrapper.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
client::{CoordinatorMessage, StateSyncClient},
coordinator::StateSyncCoordinator,
executor_proxy::{ExecutorProxy, ExecutorProxyTrait},
network::{StateSyncEvents, StateSyncSender},
};
use diem_config::{config:... |
pub fn bootstrap_with_executor_proxy<E: ExecutorProxyTrait +'static>(
runtime: Runtime,
network: Vec<(NodeNetworkId, StateSyncSender, StateSyncEvents)>,
state_sync_to_mempool_sender: mpsc::Sender<diem_mempool::CommitNotification>,
node_config: &NodeConfig,
waypoint: Waypoin... | {
let runtime = Builder::new_multi_thread()
.thread_name("state-sync")
.enable_all()
.build()
.expect("[State Sync] Failed to create runtime!");
let executor_proxy = ExecutorProxy::new(storage, executor, reconfig_event_subscriptions);
Self::bootst... | identifier_body |
rcvr-borrowed-to-slice.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 x = vec!(1, 2, 3);
let y = call_sum(x.as_slice());
println!("y=={}", y);
assert_eq!(y, 6);
let x = vec!(1, 2, 3);
let y = x.as_slice().sum_();
println!("y=={}", y);
assert_eq!(y, 6);
let x = vec!(1, 2, 3);
let y = x.as_slice().sum_();
println!("y=={}", y);
assert_... | identifier_body | |
rcvr-borrowed-to-slice.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 x = vec!(1, 2, 3);
let y = call_sum(x.as_slice());
println!("y=={}", y);
assert_eq!(y, 6);
let x = vec!(1, 2, 3);
let y = x.as_slice().sum_();
println!("y=={}", y);
assert_eq!(y, 6);
let x = vec!(1, 2, 3);
let y = x.as_slice().sum_();
println!("y=={}", y);
assert_eq... | pub fn main() { | random_line_split |
rcvr-borrowed-to-slice.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 ... | (x: &[int]) -> int { x.sum_() }
pub fn main() {
let x = vec!(1, 2, 3);
let y = call_sum(x.as_slice());
println!("y=={}", y);
assert_eq!(y, 6);
let x = vec!(1, 2, 3);
let y = x.as_slice().sum_();
println!("y=={}", y);
assert_eq!(y, 6);
let x = vec!(1, 2, 3);
let y = x.as_slice(... | call_sum | identifier_name |
attr.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 ... | (&mut self) -> Vec<Gc<ast::MetaItem>> {
match self.token {
token::LPAREN => self.parse_meta_seq(),
_ => Vec::new()
}
}
}
| parse_optional_meta | identifier_name |
attr.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 lo = self.span.lo;
let ident = self.parse_ident();
let name = self.id_to_interned_str(ident);
match self.token {
token::EQ => {
self.bump();
let lit = self.parse_lit();
// FIXME #623 Non-string... | return e
} | random_line_split |
attr.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 ... |
token::DOC_COMMENT(s) => {
// we need to get the position of this token before we bump.
let Span { lo, hi,.. } = self.span;
self.bump();
attr::mk_sugared_doc_attr(attr::mk_attr_id(),
... | {
self.parse_attribute(true)
} | conditional_block |
attr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn parse_optional_meta(&mut self) -> Vec<Gc<ast::MetaItem>> {
match self.token {
token::LPAREN => self.parse_meta_seq(),
_ => Vec::new()
}
}
}
| {
self.parse_seq(&token::LPAREN,
&token::RPAREN,
seq_sep_trailing_disallowed(token::COMMA),
|p| p.parse_meta_item()).node
} | identifier_body |
traits-conditional-dispatch.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 ... | <T:Get>(t: &T) -> T {
(*t).get()
}
fn main() {
assert_eq!(get_it(&1_u32), 1_u32);
assert_eq!(get_it(&1_u16), 1_u16);
assert_eq!(get_it(&Some(1_u16)), Some(1_u16));
assert_eq!(get_it(&box 1i), box 1i);
}
| get_it | identifier_name |
traits-conditional-dispatch.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 get_it<T:Get>(t: &T) -> T {
(*t).get()
}
fn main() {
assert_eq!(get_it(&1_u32), 1_u32);
assert_eq!(get_it(&1_u16), 1_u16);
assert_eq!(get_it(&Some(1_u16)), Some(1_u16));
assert_eq!(get_it(&box 1i), box 1i);
}
| { box get_it(&**self) } | identifier_body |
traits-conditional-dispatch.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 ... | assert_eq!(get_it(&1_u32), 1_u32);
assert_eq!(get_it(&1_u16), 1_u16);
assert_eq!(get_it(&Some(1_u16)), Some(1_u16));
assert_eq!(get_it(&box 1i), box 1i);
} | (*t).get()
}
fn main() { | random_line_split |
lib.rs | pub struct Actor {
x: i32,
y: i32
}
impl Actor {
fn follow(self, dir: &Direction) -> Actor |
}
#[derive(PartialEq, Debug)]
pub enum Direction {
North,
East,
South,
West,
}
impl Direction {
// (Left turn, Right turn)
fn turns(&self) -> (Direction, Direction) {
match *self {
Direction::North => (Direction::West, Direction::East),
Direction::East => (Dire... | {
match *dir {
Direction::North => Actor { x: self.x, y: self.y + 1 },
Direction::East => Actor { x: self.x + 1, y: self.y },
Direction::South => Actor { x: self.x, y: self.y - 1 },
Direction::West => Actor { x: self.x - 1, y: self.y }
}
} | identifier_body |
lib.rs | pub struct Actor {
x: i32,
y: i32
}
impl Actor {
fn follow(self, dir: &Direction) -> Actor {
match *dir {
Direction::North => Actor { x: self.x, y: self.y + 1 },
Direction::East => Actor { x: self.x + 1, y: self.y }, | }
#[derive(PartialEq, Debug)]
pub enum Direction {
North,
East,
South,
West,
}
impl Direction {
// (Left turn, Right turn)
fn turns(&self) -> (Direction, Direction) {
match *self {
Direction::North => (Direction::West, Direction::East),
Direction::East => (Direc... | Direction::South => Actor { x: self.x, y: self.y - 1 },
Direction::West => Actor { x: self.x - 1, y: self.y }
}
} | random_line_split |
lib.rs | pub struct Actor {
x: i32,
y: i32
}
impl Actor {
fn follow(self, dir: &Direction) -> Actor {
match *dir {
Direction::North => Actor { x: self.x, y: self.y + 1 },
Direction::East => Actor { x: self.x + 1, y: self.y },
Direction::South => Actor { x: self.x, y: self... | (self) -> Self {
Robot(self.0, self.1.turns().0)
}
pub fn advance(self) -> Self {
Robot(self.0.follow(&self.1), self.1)
}
fn obey(self, code: &str) -> Self {
match code {
"R" => self.turn_right(),
"L" => self.turn_left(),
"A" => self.advance(... | turn_left | identifier_name |
gqtp_request.rs | use std::io;
use std::io::Cursor;
use std::io::prelude::*;
use std::borrow::Cow;
use std::net::TcpStream;
use std::string::FromUtf8Error;
use byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
const RECV_BUF_SIZE: usize = 8192;
const GQTP_HEADER_SIZE: usize = 24;
#[derive(Debug)]
pub enum GQTPError {
InvalidPro... |
}
impl From<FromUtf8Error> for GQTPError {
fn from(err: FromUtf8Error) -> GQTPError {
GQTPError::EncodingError(err)
}
}
/// Request [GQTP protocol](http://groonga.org/docs/spec/gqtp.html) over TcpStream
pub struct GQTPRequest<'a> {
addr: Cow<'a, str>,
}
impl<'a> Default for GQTPRequest<'a> {
... | {
GQTPError::IO(err)
} | identifier_body |
gqtp_request.rs | use std::io;
use std::io::Cursor;
use std::io::prelude::*;
use std::borrow::Cow;
use std::net::TcpStream;
use std::string::FromUtf8Error;
use byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
const RECV_BUF_SIZE: usize = 8192;
const GQTP_HEADER_SIZE: usize = 24;
#[derive(Debug)]
pub enum GQTPError {
InvalidPro... |
let _ = try!(buf.read_i16::<BigEndian>());
let _ = try!(buf.read_u8());
let flags = try!(buf.read_u8());
if!((flags & 0x01) == 0x01 || (flags & 0x02) == 0x02) {
return Err(GQTPError::InvalidProtocol);
}
let status = try!(buf.read_u16::<BigEndian>());
... | {
return Err(GQTPError::InvalidProtocol);
} | conditional_block |
gqtp_request.rs | use std::io;
use std::io::Cursor;
use std::io::prelude::*;
use std::borrow::Cow;
use std::net::TcpStream;
use std::string::FromUtf8Error;
use byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
const RECV_BUF_SIZE: usize = 8192;
const GQTP_HEADER_SIZE: usize = 24;
#[derive(Debug)]
pub enum | {
InvalidProtocol,
InvalidBodySize,
StatusError(u16),
IO(io::Error),
EncodingError(FromUtf8Error),
}
impl From<io::Error> for GQTPError {
fn from(err: io::Error) -> GQTPError {
GQTPError::IO(err)
}
}
impl From<FromUtf8Error> for GQTPError {
fn from(err: FromUtf8Error) -> GQTPE... | GQTPError | identifier_name |
issue_922.rs | use juniper::*;
struct Query;
#[juniper::graphql_object]
impl Query {
fn characters() -> Vec<CharacterValue> {
vec![
Into::into(Human {
id: 0,
name: "human-32".to_owned(),
}),
Into::into(Droid {
id: 1,
name... |
}
type Schema = juniper::RootNode<'static, Query, EmptyMutation<()>, EmptySubscription<()>>;
#[tokio::test]
async fn test_fragment_on_interface() {
let query = r#"
query Query {
characters {
...CharacterFragment
}
}
fragment CharacterFragment on Cha... | {
self.name.clone()
} | identifier_body |
issue_922.rs | use juniper::*;
struct Query;
#[juniper::graphql_object]
impl Query {
fn characters() -> Vec<CharacterValue> {
vec![
Into::into(Human {
id: 0,
name: "human-32".to_owned(),
}),
Into::into(Droid {
id: 1,
name... | }
}
#[derive(juniper::GraphQLObject)]
#[graphql(impl = CharacterValue)]
struct Droid {
pub id: i32,
pub name: String,
}
#[juniper::graphql_interface]
impl Character for Droid {
fn id(&self) -> i32 {
self.id
}
fn name(&self) -> String {
self.name.clone()
}
}
type Schema = ... | self.id
}
fn name(&self) -> String {
self.name.clone() | random_line_split |
issue_922.rs | use juniper::*;
struct Query;
#[juniper::graphql_object]
impl Query {
fn characters() -> Vec<CharacterValue> {
vec![
Into::into(Human {
id: 0,
name: "human-32".to_owned(),
}),
Into::into(Droid {
id: 1,
name... | {
pub id: i32,
pub name: String,
}
#[juniper::graphql_interface]
impl Character for Droid {
fn id(&self) -> i32 {
self.id
}
fn name(&self) -> String {
self.name.clone()
}
}
type Schema = juniper::RootNode<'static, Query, EmptyMutation<()>, EmptySubscription<()>>;
#[tokio::te... | Droid | identifier_name |
mouse.rs | //!
//! A module for describing Mouse state.
//!
//! The `Ui` will continuously maintain the latest Mouse state, necessary for widget logic.
//!
use position::Point;
/// Represents the current state of a mouse button.
#[derive(Clone, Copy, Debug)]
pub enum ButtonState {
/// The mouse is currently up.
Up,
... | (xy: Point,
left: ButtonState,
middle: ButtonState,
right: ButtonState) -> Mouse {
Mouse { xy: xy, left: left, middle: middle, right: right, unknown: ButtonState::Up }
}
/// Return the mouse state with its position relative to the given position.
pub fn ... | new | identifier_name |
mouse.rs | //!
//! A module for describing Mouse state.
//!
//! The `Ui` will continuously maintain the latest Mouse state, necessary for widget logic.
//!
use position::Point;
/// Represents the current state of a mouse button.
#[derive(Clone, Copy, Debug)]
pub enum ButtonState {
/// The mouse is currently up.
Up,
... | /// Left mouse button state.
pub left: ButtonState,
/// Middle mouse button state.
pub middle: ButtonState,
/// Right mouse button state.
pub right: ButtonState,
/// Unknown button state.
pub unknown: ButtonState,
}
impl Mouse {
/// Constructor for a Mouse struct.
pub fn new(xy... | pub struct Mouse {
/// Position of the mouse cursor.
pub xy: Point, | random_line_split |
test_resource.rs | use rustler::{Env, ResourceArc};
use std::sync::RwLock;
pub struct TestResource {
test_field: RwLock<i32>,
}
/// This one is designed to look more like pointer data, to increase the
/// chance of segfaults if the implementation is wrong.
pub struct ImmutableResource {
a: u32,
b: u32,
}
pub fn | (env: Env) -> bool {
rustler::resource!(TestResource, env);
rustler::resource!(ImmutableResource, env);
true
}
#[rustler::nif]
pub fn resource_make() -> ResourceArc<TestResource> {
ResourceArc::new(TestResource {
test_field: RwLock::new(0),
})
}
#[rustler::nif]
pub fn resource_set_integer_... | on_load | identifier_name |
test_resource.rs | use rustler::{Env, ResourceArc};
use std::sync::RwLock;
pub struct TestResource {
test_field: RwLock<i32>,
}
/// This one is designed to look more like pointer data, to increase the
/// chance of segfaults if the implementation is wrong.
pub struct ImmutableResource {
a: u32,
b: u32,
}
pub fn on_load(env... |
// Count how many instances of `ImmutableResource` are currently alive globally.
#[rustler::nif]
pub fn resource_immutable_count() -> u32 {
COUNT.load(Ordering::SeqCst) as u32
}
| {
ResourceArc::new(ImmutableResource::new(u))
} | identifier_body |
test_resource.rs | use rustler::{Env, ResourceArc};
use std::sync::RwLock;
pub struct TestResource {
test_field: RwLock<i32>,
}
/// This one is designed to look more like pointer data, to increase the
/// chance of segfaults if the implementation is wrong.
pub struct ImmutableResource {
a: u32,
b: u32,
}
pub fn on_load(env... | "ok"
}
#[rustler::nif]
pub fn resource_get_integer_field(resource: ResourceArc<TestResource>) -> i32 {
*resource.test_field.read().unwrap()
}
use std::sync::atomic::{AtomicUsize, Ordering};
lazy_static::lazy_static! {
static ref COUNT: AtomicUsize = AtomicUsize::new(0);
}
impl ImmutableResource {
fn... | *test_field = n;
| random_line_split |
pin.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <lionel@svkt.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENS... | PortId::PortC => (sysctl::periph::gpio::PORT_C, reg::PORT_C),
PortId::PortD => (sysctl::periph::gpio::PORT_D, reg::PORT_D),
PortId::PortE => (sysctl::periph::gpio::PORT_E, reg::PORT_E),
PortId::PortF => (sysctl::periph::gpio::PORT_F, reg::PORT_F),
};
periph.ensure_enabled();
let pi... |
// Retrieve GPIO port peripheral to enable it
let (periph, regs) = match pid {
PortId::PortA => (sysctl::periph::gpio::PORT_A, reg::PORT_A),
PortId::PortB => (sysctl::periph::gpio::PORT_B, reg::PORT_B), | random_line_split |
pin.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <lionel@svkt.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENS... | (&self) -> GpioLevel {
match self.regs.data.data(self.index) {
true => High,
false => Low,
}
}
/// Sets output GPIO direction.
fn set_direction(&self, dir: GpioDirection) {
self.regs.dir.set_dir(self.index,
match dir {
In => reg::Por... | level | identifier_name |
pin.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <lionel@svkt.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENS... |
/// Returns input GPIO level.
fn level(&self) -> GpioLevel {
match self.regs.data.data(self.index) {
true => High,
false => Low,
}
}
/// Sets output GPIO direction.
fn set_direction(&self, dir: GpioDirection) {
self.regs.dir.set_dir(self.index,
match dir {... | {
self.set_level(false);
} | identifier_body |
nodelist.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::NodeListBinding;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object... |
pub fn Length(&self) -> u32 {
match self.list_type {
Simple(ref elems) => elems.len() as u32,
Children(ref node) => node.children().len() as u32
}
}
pub fn Item(&self, index: u32) -> Option<AbstractNode<ScriptView>> {
match self.list_type {
_ if... | {
NodeList::new(window, Children(node))
} | identifier_body |
nodelist.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::NodeListBinding;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object... | (window: @mut Window, elements: ~[AbstractNode<ScriptView>]) -> @mut NodeList {
NodeList::new(window, Simple(elements))
}
pub fn new_child_list(window: @mut Window, node: AbstractNode<ScriptView>) -> @mut NodeList {
NodeList::new(window, Children(node))
}
pub fn Length(&self) -> u32 {
... | new_simple_list | identifier_name |
nodelist.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::NodeListBinding;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object... | fn GetParentObject(&self, _cx: *JSContext) -> Option<@mut Reflectable> {
Some(self.window as @mut Reflectable)
}
} | random_line_split | |
htmllinkelement.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::attr::{Attr, AttrValue};
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::HTMLLinkElemen... | (element: JSRef<Element>, name: &Atom) -> Option<String> {
let elem = element.get_attribute(ns!(""), name).root();
elem.map(|e| e.value().as_slice().to_string())
}
fn is_stylesheet(value: &Option<String>) -> bool {
match *value {
Some(ref value) => {
value.as_slice().split(HTML_SPACE_CH... | get_attr | identifier_name |
htmllinkelement.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::attr::{Attr, AttrValue};
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::HTMLLinkElemen... |
}
fn get_attr(element: JSRef<Element>, name: &Atom) -> Option<String> {
let elem = element.get_attribute(ns!(""), name).root();
elem.map(|e| e.value().as_slice().to_string())
}
fn is_stylesheet(value: &Option<String>) -> bool {
match *value {
Some(ref value) => {
value.as_slice().spli... | {
let element = HTMLLinkElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLLinkElementBinding::Wrap)
} | identifier_body |
htmllinkelement.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::attr::{Attr, AttrValue};
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::HTMLLinkElemen... |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLLinkElement> {
let element = HTMLLinkElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLLinkElementBinding::Wrap)
... | } | random_line_split |
xtc.rs | //! This module serves as the entry point into Xt's main binary.
// This file is part of Xt.
// This is the Xt text editor; it edits text.
// Copyright (C) 2016-2018 The Xt Developers
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
/... |
fn main() {
let _args = retrieve_arguments();
let log = init_logger();
info!(log, "Xt (core) loading..");
warn!(
log,
"Xt (core) has no configuration file. Reverting to defaults."
);
error!(log, "Xt Core is not ready for deployment. Halt.");
unimplemented!();
}
| {
App::new("xt-core")
.version("0.1.0")
.author("Dom Rodriguez <shymega@shymega.org.uk>")
.about("Core backend for Xt.")
.arg(
Arg::with_name("verbose")
.short("v")
.multiple(true)
.required(false)
.help("Set... | identifier_body |
xtc.rs | //! This module serves as the entry point into Xt's main binary.
// This file is part of Xt.
// This is the Xt text editor; it edits text.
// Copyright (C) 2016-2018 The Xt Developers
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
/... | () -> ArgMatches<'static> {
App::new("xt-core")
.version("0.1.0")
.author("Dom Rodriguez <shymega@shymega.org.uk>")
.about("Core backend for Xt.")
.arg(
Arg::with_name("verbose")
.short("v")
.multiple(true)
.required(false)
... | retrieve_arguments | identifier_name |
xtc.rs | //! This module serves as the entry point into Xt's main binary. |
// This is the Xt text editor; it edits text.
// Copyright (C) 2016-2018 The Xt Developers
// 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 (at your o... |
// This file is part of Xt. | random_line_split |
for_each.rs | use {Future, Task, Poll};
use stream::Stream;
/// A stream combinator which executes a unit closure over each item on a
/// stream.
///
/// This structure is returned by the `Stream::for_each` method.
pub struct ForEach<S, F> {
stream: S, | f: F,
}
pub fn new<S, F>(s: S, f: F) -> ForEach<S, F>
where S: Stream,
F: FnMut(S::Item) -> Result<(), S::Error> + Send +'static
{
ForEach {
stream: s,
f: f,
}
}
impl<S, F> Future for ForEach<S, F>
where S: Stream,
F: FnMut(S::Item) -> Result<(), S::Error> + Sen... | random_line_split | |
for_each.rs | use {Future, Task, Poll};
use stream::Stream;
/// A stream combinator which executes a unit closure over each item on a
/// stream.
///
/// This structure is returned by the `Stream::for_each` method.
pub struct ForEach<S, F> {
stream: S,
f: F,
}
pub fn | <S, F>(s: S, f: F) -> ForEach<S, F>
where S: Stream,
F: FnMut(S::Item) -> Result<(), S::Error> + Send +'static
{
ForEach {
stream: s,
f: f,
}
}
impl<S, F> Future for ForEach<S, F>
where S: Stream,
F: FnMut(S::Item) -> Result<(), S::Error> + Send +'static
{
type I... | new | identifier_name |
for_each.rs | use {Future, Task, Poll};
use stream::Stream;
/// A stream combinator which executes a unit closure over each item on a
/// stream.
///
/// This structure is returned by the `Stream::for_each` method.
pub struct ForEach<S, F> {
stream: S,
f: F,
}
pub fn new<S, F>(s: S, f: F) -> ForEach<S, F>
where S: Stre... |
Err(e) => return Poll::Err(e),
}
}
Ok(None) => return Poll::Ok(()),
Err(e) => return Poll::Err(e),
}
}
}
fn schedule(&mut self, task: &mut Task) {
self.stream.schedule(task)
}
}
| {} | conditional_block |
for_each.rs | use {Future, Task, Poll};
use stream::Stream;
/// A stream combinator which executes a unit closure over each item on a
/// stream.
///
/// This structure is returned by the `Stream::for_each` method.
pub struct ForEach<S, F> {
stream: S,
f: F,
}
pub fn new<S, F>(s: S, f: F) -> ForEach<S, F>
where S: Stre... |
}
| {
self.stream.schedule(task)
} | identifier_body |
lib.rs | // Need this for rusty_peg
#![recursion_limit = "256"]
// I hate this lint.
#![allow(unused_parens)]
// The builtin tests don't cover the CLI and so forth, and it's just
// too darn annoying to try and make them do so.
#![cfg_attr(test, allow(dead_code))]
extern crate ascii_canvas;
extern crate atty;
extern crate bit_... | extern crate unicode_xid;
#[cfg(test)]
extern crate rand;
// hoist the modules that define macros up earlier
#[macro_use]
mod rust;
#[macro_use]
mod log;
mod api;
mod build;
mod collections;
mod file_text;
mod grammar;
mod lexer;
mod lr1;
mod message;
mod normalize;
mod parser;
mod kernel_set;
mod session;
mod tls;
... | extern crate term; | random_line_split |
credentials.rs | use crate::errors::*;
use dirs;
use failure::Error;
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use toml::Value;
use url::Url;
/// Representation of a Chef configuration.
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct Config {
/// The URL to the Chef Server orga... | () {
let cfg = Config::from_str(CREDENTIALS, "default").unwrap();
assert_eq!(cfg.organization_path().unwrap(), "/organizations/bedrock")
}
#[test]
fn test_default_profile_name() {
std::env::remove_var("CHEF_PROFILE");
assert_eq!(select_profile_name(None), String::from("defau... | test_organization_path | identifier_name |
credentials.rs | use crate::errors::*;
use dirs;
use failure::Error;
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use toml::Value;
use url::Url;
/// Representation of a Chef configuration.
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct Config {
/// The URL to the Chef Server orga... | Err(ChefError::DuplicateClientNameError(profile).into())
} else if self.node_name.is_some() {
self.node_name
.as_ref()
.ok_or_else(|| {
ChefError::UnparseableConfigError(format!(
"failed to read node name for profi... | /// `node_name` interchangeably; `client_name` is preferred, and a `DuplicateClientNameError` will
/// be returned if both `client_name` and `node_name` are used.
pub fn client_name(&self) -> Result<&str, Error> {
let profile = self.profile.clone();
if self.client_name.is_some() && self.node... | random_line_split |
credentials.rs | use crate::errors::*;
use dirs;
use failure::Error;
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use toml::Value;
use url::Url;
/// Representation of a Chef configuration.
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct Config {
/// The URL to the Chef Server orga... | "failed to read client name for profile: {}",
profile
))
.into()
})
.and_then(|n| Ok(n.as_ref()))
} else {
Err(ChefError::UnparseableConfigError(format!(
"No node_nam... | {
let profile = self.profile.clone();
if self.client_name.is_some() && self.node_name.is_some() {
Err(ChefError::DuplicateClientNameError(profile).into())
} else if self.node_name.is_some() {
self.node_name
.as_ref()
.ok_or_else(|| {
... | identifier_body |
main.rs | // 0.096s on A4-5000 (1.5 GHz)
extern crate permutohedron;
use std::collections::HashMap;
fn main() {
let input = include_str!("input.txt");
// Obtain locations and route possibilities
let mut locations: Vec<&str> = Vec::new();
let mut routes: HashMap<[&str;2], usize> = HashMap::new();
for line in... |
}
// Calculate the shortest and longest distances/routes
let mut shortest_distance: usize = 65535;
let mut shortest_route: Vec<&str> = Vec::new();
let mut longest_distance: usize = 0;
let mut longest_route: Vec<&str> = Vec::new();
for permutation in permutohedron::Heap::new(&mut locations)... | { locations.push(words[2]); } | conditional_block |
main.rs | // 0.096s on A4-5000 (1.5 GHz)
extern crate permutohedron;
use std::collections::HashMap;
fn main() {
let input = include_str!("input.txt");
// Obtain locations and route possibilities
let mut locations: Vec<&str> = Vec::new();
let mut routes: HashMap<[&str;2], usize> = HashMap::new();
for line in... | (input: &Vec<&str>, map: &HashMap<[&str;2],usize>) -> usize {
let mut distance: usize = 0;
let mut iterator = input.iter();
let mut previous = iterator.next().unwrap();
for next in iterator {
distance += *map.get(&[previous.clone(),next.clone()]).unwrap();
previous = next;
}
retu... | calculate_distance | identifier_name |
main.rs | // 0.096s on A4-5000 (1.5 GHz)
extern crate permutohedron;
use std::collections::HashMap;
fn main() | let mut longest_route: Vec<&str> = Vec::new();
for permutation in permutohedron::Heap::new(&mut locations) {
let distance = calculate_distance(&permutation, &routes);
if distance < shortest_distance {
shortest_route = permutation.clone();
shortest_distance = distance;
... | {
let input = include_str!("input.txt");
// Obtain locations and route possibilities
let mut locations: Vec<&str> = Vec::new();
let mut routes: HashMap<[&str;2], usize> = HashMap::new();
for line in input.lines() {
let words = line.split_whitespace().collect::<Vec<&str>>();
let (fir... | identifier_body |
main.rs | // 0.096s on A4-5000 (1.5 GHz)
extern crate permutohedron;
use std::collections::HashMap;
fn main() {
let input = include_str!("input.txt");
// Obtain locations and route possibilities
let mut locations: Vec<&str> = Vec::new();
let mut routes: HashMap<[&str;2], usize> = HashMap::new();
for line in... | } | for x in iterator { print!(" -> {}", x); }
print!("\n"); | random_line_split |
argument-passing.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 a = X {x: 1};
let mut b = 2;
let mut c = 3;
assert_eq!(f1(&mut a, &mut b, c), 6);
assert_eq!(a.x, 0);
assert_eq!(b, 10);
assert_eq!(f2(a.x, |x| a.x = 50), 0);
assert_eq!(a.x, 50);
}
| main | identifier_name |
argument-passing.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
stru... | // http://rust-lang.org/COPYRIGHT.
// | random_line_split |
argument-passing.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let mut a = X {x: 1};
let mut b = 2;
let mut c = 3;
assert_eq!(f1(&mut a, &mut b, c), 6);
assert_eq!(a.x, 0);
assert_eq!(b, 10);
assert_eq!(f2(a.x, |x| a.x = 50), 0);
assert_eq!(a.x, 50);
}
| { f(1); return a; } | identifier_body |
test-commands-transfer.rs | mod helpers;
use crate::helpers::prelude::*;
#[test]
fn test_command_transfer() | assert_eq!(
0,
main_with_args(
&["rooster", "transfer", "youtube", "videos@example.com"],
&mut CursorInputOutput::new("", "xxxx\n"),
&rooster_file
)
);
let mut io = CursorInputOutput::new("", "xxxx\n");
assert_eq!(
0,
main_with... | {
let rooster_file = tempfile();
assert_eq!(
0,
main_with_args(
&["rooster", "init", "--force-for-tests"],
&mut CursorInputOutput::new("", "\nxxxx\n"),
&rooster_file
)
);
assert_eq!(
0,
main_with_args(
&["rooster", ... | identifier_body |
test-commands-transfer.rs | mod helpers;
use crate::helpers::prelude::*;
#[test]
fn | () {
let rooster_file = tempfile();
assert_eq!(
0,
main_with_args(
&["rooster", "init", "--force-for-tests"],
&mut CursorInputOutput::new("", "\nxxxx\n"),
&rooster_file
)
);
assert_eq!(
0,
main_with_args(
&["rooster... | test_command_transfer | identifier_name |
test-commands-transfer.rs | mod helpers;
use crate::helpers::prelude::*;
#[test]
fn test_command_transfer() {
let rooster_file = tempfile();
assert_eq!(
0,
main_with_args(
&["rooster", "init", "--force-for-tests"],
&mut CursorInputOutput::new("", "\nxxxx\n"),
&rooster_file
)
... | &["rooster", "transfer", "youtube", "videos@example.com"],
&mut CursorInputOutput::new("", "xxxx\n"),
&rooster_file
)
);
let mut io = CursorInputOutput::new("", "xxxx\n");
assert_eq!(
0,
main_with_args(&["rooster", "list"], &mut io, &rooster_file)... |
assert_eq!(
0,
main_with_args( | random_line_split |
lib.rs | extern crate sudoku;
use sudoku::Sudoku;
fn read_sudokus(sudokus_str: &str) -> Vec<Sudoku> {
let sudokus_str = sudokus_str.replace("\r\n", "\n");
let mut sudokus = vec![];
for i in 0.. {
// 9 lines with 9 cells each + 1 linefeed character per line
// + 1 LF char between each sudoku
... |
}
}
#[test]
fn correct_solution_hard_sudokus() {
let sudokus = read_sudokus( include_str!("../sudokus/hard_sudokus.txt") );
let solved_sudokus = read_sudokus( include_str!("../sudokus/solved_hard_sudokus.txt") );
for (i, (sudoku, solved_sudoku)) in sudokus.into_iter().zip(solved_sudokus).enumerate() {... | {
panic!("Found multiple solutions to sudoku with unique solution or none at all for {}th sudoku:\n{}", i, sudoku);
} | conditional_block |
lib.rs | extern crate sudoku;
use sudoku::Sudoku;
fn | (sudokus_str: &str) -> Vec<Sudoku> {
let sudokus_str = sudokus_str.replace("\r\n", "\n");
let mut sudokus = vec![];
for i in 0.. {
// 9 lines with 9 cells each + 1 linefeed character per line
// + 1 LF char between each sudoku
// 9*(9+1) + 1
let rg = 0+i*91..90+i*91;
... | read_sudokus | identifier_name |
lib.rs | extern crate sudoku;
use sudoku::Sudoku;
fn read_sudokus(sudokus_str: &str) -> Vec<Sudoku> {
let sudokus_str = sudokus_str.replace("\r\n", "\n");
let mut sudokus = vec![];
for i in 0.. {
// 9 lines with 9 cells each + 1 linefeed character per line
// + 1 LF char between each sudoku
... |
#[test]
fn solve_1() {
let sudoku_str =
"___2___63
3____54_1
__1__398_
_______9_
___538___
_3_______
_263__5__
5_37____8
47___1___";
let mut sudoku = Sudoku::from_str(sudoku_str).unwrap();
sudoku.solve();
println!("{}", sudoku);
}
#[test]
fn solve_2() {
let sudoku_str = "\
7__|4__|__2
21_|3_5|46_... | sudokus
} | random_line_split |
lib.rs | extern crate sudoku;
use sudoku::Sudoku;
fn read_sudokus(sudokus_str: &str) -> Vec<Sudoku> {
let sudokus_str = sudokus_str.replace("\r\n", "\n");
let mut sudokus = vec![];
for i in 0.. {
// 9 lines with 9 cells each + 1 linefeed character per line
// + 1 LF char between each sudoku
... |
#[test]
fn correct_solution_easy_sudokus() {
let sudokus = read_sudokus( include_str!("../sudokus/easy_sudokus.txt") );
let solved_sudokus = read_sudokus( include_str!("../sudokus/solved_easy_sudokus.txt") );
for (i, (sudoku, solved_sudoku)) in sudokus.into_iter().zip(solved_sudokus).enumerate() {
... | {
let sudoku_str =
"___2___63
3____54_1
__1__398_
_______9_
___538___
_3_______
_263__5__
5_37____8";
Sudoku::from_str(sudoku_str).unwrap();
} | identifier_body |
lib.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... |
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
#[cfg(feature = "with-syntex")]
include!(concat!(env!("OUT_DIR"), "/lib.rs"));
#[cfg(not(feature = "with-syntex"))]
include!("lib.rs.in"); | // Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. | random_line_split |
ops.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! DAG and Id operations (mostly traits)
use crate::clone::CloneData;
use crate::default_impl;
use crate::errors::NotFoundError;
use crate:... | /// Actual implementation might have faster paths.
///
/// The `roots & ancestors(heads)` portion filters out bogus roots for
/// compatibility, if the callsite does not provide bogus roots, it
/// could be simplified to just `roots`.
async fn reachable_roots(&self, roots: NameSet, heads: NameSe... | /// `roots & (heads | parents(only(heads, roots & ancestors(heads))))`. | random_line_split |
ops.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! DAG and Id operations (mostly traits)
use crate::clone::CloneData;
use crate::default_impl;
use crate::errors::NotFoundError;
use crate:... |
// Convert IdLazySet to IdStaticSet. Bypass hash lookups.
if let Some(set) = set.as_any().downcast_ref::<IdLazySet>() {
if None < version && version <= Some(self.map_version()) {
let set: IdStaticSet = set.to_static()?;
return Ok(set.spans);
}
... | {
if None < version && version <= Some(self.map_version()) {
return Ok(set.spans.clone());
}
} | conditional_block |
ops.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! DAG and Id operations (mostly traits)
use crate::clone::CloneData;
use crate::default_impl;
use crate::errors::NotFoundError;
use crate:... | (&self, set: NameSet) -> Result<NameSet> {
default_impl::merges(self, set).await
}
/// Calculates one "greatest common ancestor" of the given set.
///
/// If there are no common ancestors, return None.
/// If there are multiple greatest common ancestors, pick one arbitrarily.
/// Use `g... | merges | identifier_name |
ops.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! DAG and Id operations (mostly traits)
use crate::clone::CloneData;
use crate::default_impl;
use crate::errors::NotFoundError;
use crate:... |
}
#[async_trait::async_trait]
impl Parents for &(dyn DagAlgorithm + Send + Sync) {
async fn parent_names(&self, name: VertexName) -> Result<Vec<VertexName>> {
DagAlgorithm::parent_names(*self, name).await
}
}
#[async_trait::async_trait]
impl<'a> Parents for Box<dyn Fn(VertexName) -> Result<Vec<Vertex... | {
DagAlgorithm::parent_names(self, name).await
} | identifier_body |
mouse.rs | use nalgebra::Point2;
use num::Zero;
use std::collections::HashSet;
use std::ops::Deref;
use event::{ElementState, Event, MouseButton, React};
use input::state::{CompositeState, Element, Input, InputDifference, InputState, InputTransition,
Snapshot, State};
use BoolExt;
impl Element for MouseButton... | self.live.proximity = false;
}
Event::MouseMoved(x, y) => {
self.live.position = Point2::new(x, y);
}
_ => {}
}
}
}
impl Snapshot for Mouse {
fn snapshot(&mut self) {
self.snapshot = self.live.clone();
}
}
#[de... | }
Event::MouseInput(ElementState::Released, button) => {
self.live.buttons.remove(&button);
}
Event::MouseLeft => { | random_line_split |
mouse.rs | use nalgebra::Point2;
use num::Zero;
use std::collections::HashSet;
use std::ops::Deref;
use event::{ElementState, Event, MouseButton, React};
use input::state::{CompositeState, Element, Input, InputDifference, InputState, InputTransition,
Snapshot, State};
use BoolExt;
impl Element for MouseButton... |
}
}
}
impl Snapshot for Mouse {
fn snapshot(&mut self) {
self.snapshot = self.live.clone();
}
}
#[derive(Clone)]
pub struct MouseState {
buttons: HashSet<MouseButton>,
position: Point2<i32>,
proximity: bool,
}
impl MouseState {
fn new() -> Self {
MouseState {
... | {} | conditional_block |
mouse.rs | use nalgebra::Point2;
use num::Zero;
use std::collections::HashSet;
use std::ops::Deref;
use event::{ElementState, Event, MouseButton, React};
use input::state::{CompositeState, Element, Input, InputDifference, InputState, InputTransition,
Snapshot, State};
use BoolExt;
impl Element for MouseButton... |
}
impl React for Mouse {
fn react(&mut self, event: &Event) {
match *event {
Event::MouseEntered => {
self.live.proximity = true;
}
Event::MouseInput(ElementState::Pressed, button) => {
self.live.buttons.insert(button);
}
... | {
self.transition(MouseProximity)
.map(|state| (MouseProximity, state))
} | identifier_body |
mouse.rs | use nalgebra::Point2;
use num::Zero;
use std::collections::HashSet;
use std::ops::Deref;
use event::{ElementState, Event, MouseButton, React};
use input::state::{CompositeState, Element, Input, InputDifference, InputState, InputTransition,
Snapshot, State};
use BoolExt;
impl Element for MouseButton... | () -> Self {
Mouse::default()
}
}
impl Default for Mouse {
fn default() -> Self {
Mouse {
live: MouseState::new(),
snapshot: MouseState::new(),
}
}
}
impl Deref for Mouse {
type Target = MouseState;
fn deref(&self) -> &Self::Target {
&self.l... | new | identifier_name |
config.rs | use std::io::prelude::*;
use std::{env, fs};
use std::fs::{File, OpenOptions};
use std::path::PathBuf; |
use serde_json;
use serde_json::Error;
#[derive(Serialize, Deserialize)]
pub struct Config {
pub username: String,
pub access_token: String
}
impl Clone for Config {
fn clone(&self) -> Config {
Config {
username: self.username.clone(),
access_token: self.access_token.clone... | use clap::ArgMatches;
use std::io::{BufReader, BufWriter, Write};
use evidence::json_ops; | random_line_split |
config.rs | use std::io::prelude::*;
use std::{env, fs};
use std::fs::{File, OpenOptions};
use std::path::PathBuf;
use clap::ArgMatches;
use std::io::{BufReader, BufWriter, Write};
use evidence::json_ops;
use serde_json;
use serde_json::Error;
#[derive(Serialize, Deserialize)]
pub struct Config {
pub username: String,
p... | {
let gh_path = {
let mut xs = config_path;
xs.push("gh");
xs
};
if !gh_path.exists() {
let _ = fs::create_dir(&gh_path);
}
gh_path
} | identifier_body | |
config.rs | use std::io::prelude::*;
use std::{env, fs};
use std::fs::{File, OpenOptions};
use std::path::PathBuf;
use clap::ArgMatches;
use std::io::{BufReader, BufWriter, Write};
use evidence::json_ops;
use serde_json;
use serde_json::Error;
#[derive(Serialize, Deserialize)]
pub struct Config {
pub username: String,
p... | () -> PathBuf {
match env::home_dir() {
Some(path) => path,
None => panic!("$HOME directory not found")
}
}
// Ensures the config directory exists. Creates the directory if it doesn't.
// $HOME/.config is the expected config directory. Returns the
// PathBuf after ensure it exists.
fn ens... | get_home_dir | identifier_name |
tray.rs | //! This modules only contains a function to create a tray icon.
extern crate systray;
extern crate tempfile;
use std::sync::{Arc, Mutex};
use library::Queue;
use command::Command;
/// Creates a tray icon with some buttons to send commands to the server.
pub fn start_tray(queue: &Arc<Mutex<Queue>>) {
if let Ok(... | tray.add_menu_item(&"Stop".to_string(), move |_| {
let mut q = q.lock().unwrap();
q.push(Command::Stop, None);
}).ok();
tray.add_menu_separator().ok();
let q = Arc::clone(queue);
tray.add_menu_item(&"Previous album".to_string(), move |_| {
le... | {
// This is stupid, but I have no other way to do this
// Read the icon file at compilation into an array ...
const BYTES: &[u8] = include_bytes!("../assets/icons/icon.ico");
// ... then write this icon file to a temporary file ...
use std::io::Write;
let mut tmp_file =... | conditional_block |
tray.rs | //! This modules only contains a function to create a tray icon.
extern crate systray;
extern crate tempfile;
use std::sync::{Arc, Mutex};
use library::Queue;
use command::Command;
/// Creates a tray icon with some buttons to send commands to the server.
pub fn start_tray(queue: &Arc<Mutex<Queue>>) | let q = Arc::clone(queue);
tray.add_menu_item(&"Stop".to_string(), move |_| {
let mut q = q.lock().unwrap();
q.push(Command::Stop, None);
}).ok();
tray.add_menu_separator().ok();
let q = Arc::clone(queue);
tray.add_menu_item(&"Previous album".to_... | {
if let Ok(mut tray) = systray::Application::new() {
// This is stupid, but I have no other way to do this
// Read the icon file at compilation into an array ...
const BYTES: &[u8] = include_bytes!("../assets/icons/icon.ico");
// ... then write this icon file to a temporary file ..... | identifier_body |
tray.rs | //! This modules only contains a function to create a tray icon.
extern crate systray;
extern crate tempfile;
use std::sync::{Arc, Mutex};
use library::Queue;
use command::Command;
/// Creates a tray icon with some buttons to send commands to the server.
pub fn start_tray(queue: &Arc<Mutex<Queue>>) {
if let Ok(... | tray.add_menu_item(&"Quit".to_string(), move |_| {
let mut q = q.lock().unwrap();
q.push(Command::StopServer, None);
}).ok();
tray.wait_for_message();
}
} | let q = Arc::clone(queue); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.