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 |
|---|---|---|---|---|
mutated_accounts_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::compiler::{as_module, compile_units};
use move_core_types::{
account_address::AccountAddress,
gas_schedule::{GasAlgebra, GasUnits},
identifier::Identifier,
language_storage::ModuleId,
value::{serialize_val... | () {
let code = r#"
module M {
resource struct Foo { a: bool }
public fun get(addr: address): bool acquires Foo {
borrow_global<Foo>(addr).a
}
public fun flip(addr: address) acquires Foo {
let f_ref = borrow_global_mut<Foo>(addr... | mutated_accounts | identifier_name |
mutated_accounts_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::compiler::{as_module, compile_units};
use move_core_types::{
account_address::AccountAddress,
gas_schedule::{GasAlgebra, GasUnits},
identifier::Identifier,
language_storage::ModuleId,
value::{serialize_val... | m.serialize(&mut blob).unwrap();
let mut storage = InMemoryStorage::new();
let module_id = ModuleId::new(TEST_ADDR, Identifier::new("M").unwrap());
storage.publish_or_overwrite_module(module_id.clone(), blob);
let vm = MoveVM::new();
let mut sess = vm.new_session(&storage);
let cost_table... | {
let code = r#"
module M {
resource struct Foo { a: bool }
public fun get(addr: address): bool acquires Foo {
borrow_global<Foo>(addr).a
}
public fun flip(addr: address) acquires Foo {
let f_ref = borrow_global_mut<Foo>(addr);
... | identifier_body |
issue-27868.rs | // Copyright 2018 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, _elem: T) {
println!("In add_assign.");
}
}
fn main() {
let mut vec = MyVec(vec![0]);
let mut vecvec = vec![vec];
vecvec[0] += {
vecvec = vec![];
//~^ ERROR cannot assign to `vecvec` because it is borrowed [E0506]
0
};
}
| add_assign | identifier_name |
issue-27868.rs | // Copyright 2018 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 vec = MyVec(vec![0]);
let mut vecvec = vec![vec];
vecvec[0] += {
vecvec = vec![];
//~^ ERROR cannot assign to `vecvec` because it is borrowed [E0506]
0
};
} | identifier_body | |
issue-27868.rs | // Copyright 2018 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 main() {
let mut vec = MyVec(vec![0]);
let mut vecvec = vec![vec];
vecvec[0] += {
vecvec = vec![];
//~^ ERROR cannot assign to `vecvec` because it is borrowed [E0506]
0
};
} | fn add_assign(&mut self, _elem: T) {
println!("In add_assign.");
}
}
| random_line_split |
graph.rs | ///Graph module, contains a simple graph structure which is when typechecking to find
///functions which are mutually recursive
use std::iter::repeat; | #[derive(PartialEq, Copy, Clone, Debug)]
pub struct VertexIndex(usize);
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct EdgeIndex(usize);
impl VertexIndex {
fn get(&self) -> usize { let VertexIndex(v) = *self; v }
}
impl EdgeIndex {
fn get(&self) -> usize { let EdgeIndex(v) = *self; v }
}
pub struct Verte... | use std::cmp::min;
| random_line_split |
graph.rs | ///Graph module, contains a simple graph structure which is when typechecking to find
///functions which are mutually recursive
use std::iter::repeat;
use std::cmp::min;
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct VertexIndex(usize);
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct EdgeIndex(usize);
impl ... | {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
let v4 = graph.new_vertex(());
let v5 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
graph.connect(v3, v4);
... | identifier_body | |
graph.rs | ///Graph module, contains a simple graph structure which is when typechecking to find
///functions which are mutually recursive
use std::iter::repeat;
use std::cmp::min;
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct VertexIndex(usize);
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct EdgeIndex(usize);
impl ... |
}
self.connections.push(connected);
}
}
}
#[test]
fn test_tarjan() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v... | {
break
} | conditional_block |
graph.rs | ///Graph module, contains a simple graph structure which is when typechecking to find
///functions which are mutually recursive
use std::iter::repeat;
use std::cmp::min;
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct VertexIndex(usize);
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct EdgeIndex(usize);
impl ... | (&self) -> usize { let VertexIndex(v) = *self; v }
}
impl EdgeIndex {
fn get(&self) -> usize { let EdgeIndex(v) = *self; v }
}
pub struct Vertex<T> {
pub value: T,
edges: Vec<EdgeIndex>
}
struct Edge {
from: VertexIndex,
to: VertexIndex
}
pub struct Graph<T> {
edges: Vec<Edge>,
vertices: V... | get | identifier_name |
ast.rs | pub struct ModuleDecl {
pub name: Ident,
pub endname: Ident,
pub components: Vec<ComponentDecl>,
pub entities: Vec<EntityDecl>
}
pub struct EntityDecl {
pub name: Ident,
pub endname: Ident,
pub generics: Option<Vec<GenericDecl>>,
pub ports: Option<Vec<PortDecl>>,
pub wires: Vec<Wire... | {
pub name: Ident,
pub dir: Direction,
pub class: Ident
}
pub struct AttributeDef {
pub name: Ident,
pub typename: Ident,
pub value: ConstExpr
}
pub struct WireDecl {
pub name: Ident,
pub class: Ident
}
pub enum EntityInst {
Short(EntityInstShort),
Long(EntityInstLong)
}
pub... | PortDecl | identifier_name |
ast.rs | pub struct ModuleDecl {
pub name: Ident,
pub endname: Ident,
pub components: Vec<ComponentDecl>,
pub entities: Vec<EntityDecl>
}
pub struct EntityDecl {
pub name: Ident,
pub endname: Ident,
pub generics: Option<Vec<GenericDecl>>,
pub ports: Option<Vec<PortDecl>>,
pub wires: Vec<Wire... | }
pub struct AttributeDef {
pub name: Ident,
pub typename: Ident,
pub value: ConstExpr
}
pub struct WireDecl {
pub name: Ident,
pub class: Ident
}
pub enum EntityInst {
Short(EntityInstShort),
Long(EntityInstLong)
}
pub struct EntityInstShort {
pub name: Ident,
pub ports: CommaLi... | random_line_split | |
baseline_reinforce.rs | use crate::{
domains::Batch,
fa::StateActionUpdate,
policies::Policy,
Function,
Handler, | #[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct BaselineREINFORCE<B, P> {
#[weights]
pub policy: P,
pub baseline: B,
pub alpha: f64,
pub gamma: f64,
}
impl<B, P> BaselineREINFORCE<B, P> {
... | };
| random_line_split |
baseline_reinforce.rs | use crate::{
domains::Batch,
fa::StateActionUpdate,
policies::Policy,
Function,
Handler,
};
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct BaselineREINFORCE<B, P> {
#[weights]
pub p... | (&mut self, batch: &'m Batch<S, P::Action>) -> Result<Self::Response, Self::Error> {
let mut ret = 0.0;
batch.iter().map(|t| {
let s = t.from.state();
let baseline = self.baseline.evaluate((s, &t.action));
ret = t.reward + self.gamma * ret;
self.policy.... | handle | identifier_name |
binprocess.rs | use std::process::exit;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::ffi::CString;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use shell::Shell;
use posix;
use opts;
use posix::ReadPipe;
use posix::WritePipe;
use posix::Pgid;
use exec::Arg;
use exec::Process;
use exec::ProcessInner;
use exec:... |
fn str2c(s: String) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| CString::new("<string-with-nul>").unwrap())
}
impl BinProcess {
pub fn new(cmd: &String, b: PathBuf) -> Self {
let cb = str2c(cmd.to_owned());
BinProcess {
argv: vec![cb.as_ptr(), 0 as *const _],
... | fn pb2c(pb: PathBuf) -> CString {
os2c(pb.as_os_str())
} | random_line_split |
binprocess.rs | use std::process::exit;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::ffi::CString;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use shell::Shell;
use posix;
use opts;
use posix::ReadPipe;
use posix::WritePipe;
use posix::Pgid;
use exec::Arg;
use exec::Process;
use exec::ProcessInner;
use exec:... |
}
| {
self.inner.ch_stdout = Some(write);
self
} | identifier_body |
binprocess.rs | use std::process::exit;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::ffi::CString;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use shell::Shell;
use posix;
use opts;
use posix::ReadPipe;
use posix::WritePipe;
use posix::Pgid;
use exec::Arg;
use exec::Process;
use exec::ProcessInner;
use exec:... |
Arg::Rd(rd) => {
self.inner.rds.push(rd);
}
}
// TODO: this is not a perfect way to do this
for new_arg in v {
let arg = str2c(new_arg);
self.argv[self.m_args.len()] = arg.as_ptr();
self.argv.push(0 as *const _);
... | {
for l in lines {
v.push(l);
}
} | conditional_block |
binprocess.rs | use std::process::exit;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::ffi::CString;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use shell::Shell;
use posix;
use opts;
use posix::ReadPipe;
use posix::WritePipe;
use posix::Pgid;
use exec::Arg;
use exec::Process;
use exec::ProcessInner;
use exec:... | (&mut self, new_arg: Arg) -> &Process {
// downconvert args to Strings as we add them
let mut v = Vec::new();
match new_arg {
Arg::Str(s) => {
v.push(s);
}
Arg::Bl(lines) => {
for l in lines {
v.push(l);
... | push_arg | identifier_name |
stdin.rs | use std::io::{Read, Result, Error};
use libc::{self, c_void, size_t};
use sync::NotThreadSafe;
use buf::CopyingBufReader;
lazy_static! {
static ref STDIN: NotThreadSafe<CopyingBufReader<Stdin>> = {
NotThreadSafe::new(CopyingBufReader::new(Stdin::new()))
};
} | unsafe { STDIN.get().as_mut().unwrap() }
}
pub struct Stdin;
impl Stdin {
fn new() -> Stdin {
Stdin {}
}
}
impl Read for Stdin {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let ret = unsafe {
libc::read(
libc::STDIN_FILENO,
buf.as_... |
pub fn stdin() -> &'static mut CopyingBufReader<Stdin> { | random_line_split |
stdin.rs | use std::io::{Read, Result, Error};
use libc::{self, c_void, size_t};
use sync::NotThreadSafe;
use buf::CopyingBufReader;
lazy_static! {
static ref STDIN: NotThreadSafe<CopyingBufReader<Stdin>> = {
NotThreadSafe::new(CopyingBufReader::new(Stdin::new()))
};
}
pub fn stdin() -> &'static mut CopyingBufR... |
}
}
| {
Ok(ret as usize)
} | conditional_block |
stdin.rs | use std::io::{Read, Result, Error};
use libc::{self, c_void, size_t};
use sync::NotThreadSafe;
use buf::CopyingBufReader;
lazy_static! {
static ref STDIN: NotThreadSafe<CopyingBufReader<Stdin>> = {
NotThreadSafe::new(CopyingBufReader::new(Stdin::new()))
};
}
pub fn stdin() -> &'static mut CopyingBufR... |
pub struct Stdin;
impl Stdin {
fn new() -> Stdin {
Stdin {}
}
}
impl Read for Stdin {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let ret = unsafe {
libc::read(
libc::STDIN_FILENO,
buf.as_mut_ptr() as *mut c_void,
buf.... | {
unsafe { STDIN.get().as_mut().unwrap() }
} | identifier_body |
stdin.rs | use std::io::{Read, Result, Error};
use libc::{self, c_void, size_t};
use sync::NotThreadSafe;
use buf::CopyingBufReader;
lazy_static! {
static ref STDIN: NotThreadSafe<CopyingBufReader<Stdin>> = {
NotThreadSafe::new(CopyingBufReader::new(Stdin::new()))
};
}
pub fn stdin() -> &'static mut CopyingBufR... | (&mut self, buf: &mut [u8]) -> Result<usize> {
let ret = unsafe {
libc::read(
libc::STDIN_FILENO,
buf.as_mut_ptr() as *mut c_void,
buf.len() as size_t
)
};
if ret == -1 {
Err(Error::last_os_error())
} el... | read | identifier_name |
trait-generic.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <U, F>(&self, mut f: F) -> Vec<U> where F: FnMut(&T) -> U {
let mut r = Vec::new();
for i in self.iter() {
r.push(f(i));
}
r
}
}
fn foo<U, T: map<U>>(x: T) -> Vec<String> {
x.map(|_e| "hi".to_string() )
}
fn bar<U:to_str,T:map<U>>(x: T) -> Vec<String> {
x.map(|_e... | map | identifier_name |
trait-generic.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | for i in self.iter() {
r.push(f(i));
}
r
}
}
fn foo<U, T: map<U>>(x: T) -> Vec<String> {
x.map(|_e| "hi".to_string() )
}
fn bar<U:to_str,T:map<U>>(x: T) -> Vec<String> {
x.map(|_e| _e.to_string_() )
}
pub fn main() {
assert_eq!(foo(vec!(1i)), vec!("hi".to_string()))... | }
impl<T> map<T> for Vec<T> {
fn map<U, F>(&self, mut f: F) -> Vec<U> where F: FnMut(&T) -> U {
let mut r = Vec::new(); | random_line_split |
trait-generic.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
assert_eq!(foo(vec!(1i)), vec!("hi".to_string()));
assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("4".to_string(), "5".to_string()));
assert_eq!(bar::<String, Vec<String> >(vec!("x".to_string(), "y".to_string())),
vec!("x".to_string(), "y".to_string()));
assert_eq!(bar::<(), Vec<()>... | identifier_body | |
adjancency_list.rs | extern crate fasttrack;
use fasttrack::adjancency_list;
use fasttrack::edge::Edge;
use fasttrack::route_node::RouteNode;
#[test]
fn adjancency_list_is_built_correctly() {
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 0, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weigh... | () {
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 10, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weight: 20});
routes.push(RouteNode{from: 1, to: 0, weight: 20});
let adj_list = adjancency_list::construct(routes);
assert_eq!(11, adj_list.len());
}
| list_size_is_correct_even_if_missing_some_nodes | identifier_name |
adjancency_list.rs | extern crate fasttrack;
use fasttrack::adjancency_list;
use fasttrack::edge::Edge;
use fasttrack::route_node::RouteNode;
#[test]
fn adjancency_list_is_built_correctly() {
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 0, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weigh... | {
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 10, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weight: 20});
routes.push(RouteNode{from: 1, to: 0, weight: 20});
let adj_list = adjancency_list::construct(routes);
assert_eq!(11, adj_list.len());
} | identifier_body | |
adjancency_list.rs | extern crate fasttrack;
use fasttrack::adjancency_list;
use fasttrack::edge::Edge;
use fasttrack::route_node::RouteNode;
#[test]
fn adjancency_list_is_built_correctly() {
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 0, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weigh... | assert_eq!(11, adj_list.len());
} | random_line_split | |
testrunner.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
| use crate::dom::bindings::error::{Error, ErrorResult};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use ipc_channel::ipc::IpcSender... | use bluetooth_traits::BluetoothRequest;
use crate::dom::bindings::codegen::Bindings::TestRunnerBinding;
use crate::dom::bindings::codegen::Bindings::TestRunnerBinding::TestRunnerMethods; | random_line_split |
testrunner.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use bluetooth_traits::BluetoothRequest;
use crate::dom::bindings::codegen::Bindings::TestRunnerBinding;
use crate... |
fn get_bluetooth_thread(&self) -> IpcSender<BluetoothRequest> {
self.global().as_window().bluetooth_thread()
}
}
impl TestRunnerMethods for TestRunner {
// https://webbluetoothcg.github.io/web-bluetooth/tests#setBluetoothMockDataSet
fn SetBluetoothMockDataSet(&self, dataSetName: DOMString) ->... | {
reflect_dom_object(
Box::new(TestRunner::new_inherited()),
global,
TestRunnerBinding::Wrap,
)
} | identifier_body |
testrunner.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use bluetooth_traits::BluetoothRequest;
use crate::dom::bindings::codegen::Bindings::TestRunnerBinding;
use crate... | (&self, dataSetName: DOMString) -> ErrorResult {
let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
self.get_bluetooth_thread()
.send(BluetoothRequest::Test(String::from(dataSetName), sender))
.unwrap();
match receiver.recv().unwrap(... | SetBluetoothMockDataSet | identifier_name |
ascii.rs | //! Operations on ASCII `[u8]`.
use crate::ascii;
use crate::fmt::{self, Write};
use crate::iter;
use crate::mem;
use crate::ops;
#[lang = "slice_u8"]
#[cfg(not(test))]
impl [u8] {
/// Checks if all bytes in this slice are within the ASCII range.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23... | (&mut self) -> Option<u8> {
self.inner.next_back()
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::ExactSizeIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
#[unstable(featur... | next_back | identifier_name |
ascii.rs | //! Operations on ASCII `[u8]`.
use crate::ascii;
use crate::fmt::{self, Write};
use crate::iter;
use crate::mem;
use crate::ops;
#[lang = "slice_u8"]
#[cfg(not(test))]
impl [u8] {
/// Checks if all bytes in this slice are within the ASCII range.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23... |
// We always read the first word unaligned, which means `align_offset` is
// 0, we'd read the same value again for the aligned read.
let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
let start = s.as_ptr();
// SAFETY: We verify `len < USIZE_SIZE` above.
let fi... | {
return s.iter().all(|b| b.is_ascii());
} | conditional_block |
ascii.rs | //! Operations on ASCII `[u8]`.
use crate::ascii;
use crate::fmt::{self, Write};
use crate::iter;
use crate::mem;
use crate::ops;
#[lang = "slice_u8"]
#[cfg(not(test))]
impl [u8] {
/// Checks if all bytes in this slice are within the ASCII range.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23... |
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::ExactSizeIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Dis... | {
self.inner.next_back()
} | identifier_body |
ascii.rs | //! Operations on ASCII `[u8]`.
use crate::ascii;
use crate::fmt::{self, Write};
use crate::iter;
use crate::mem;
use crate::ops;
#[lang = "slice_u8"]
#[cfg(not(test))]
impl [u8] {
/// Checks if all bytes in this slice are within the ASCII range.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23... | /// Converts this slice to its ASCII lower case equivalent in-place.
///
/// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
/// but non-ASCII letters are unchanged.
///
/// To return a new lowercased value without modifying the existing one, use
/// [`to_ascii_lowercase`].
///
//... | }
| random_line_split |
gamepadevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::... | Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
&init.gamepad,
))
}
}
impl GamepadEventMethods for GamepadEvent {
// https://w3c.github.io/gamepad/#gamepadevent-interface
fn Gamepad(&self) -> DomRoot<Gamepad> {
DomRoot::from_re... | init: &GamepadEventBinding::GamepadEventInit,
) -> Fallible<DomRoot<GamepadEvent>> {
Ok(GamepadEvent::new(
&window.global(), | random_line_split |
gamepadevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::... | (gamepad: &Gamepad) -> GamepadEvent {
GamepadEvent {
event: Event::new_inherited(),
gamepad: Dom::from_ref(gamepad),
}
}
pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: bool,
cancelable: bool,
gamepad: &Gamepad,
) -> Do... | new_inherited | identifier_name |
gamepadevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::... |
pub fn new_with_type(
global: &GlobalScope,
event_type: GamepadEventType,
gamepad: &Gamepad,
) -> DomRoot<GamepadEvent> {
let name = match event_type {
GamepadEventType::Connected => "gamepadconnected",
GamepadEventType::Disconnected => "gamepaddisconnec... | {
let ev = reflect_dom_object(Box::new(GamepadEvent::new_inherited(&gamepad)), global);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
ev
} | identifier_body |
htmlstyleelement.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::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::... | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLStyleElement> {
let element = HTMLStyleElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLStyleElementBinding::Wrap)
}
}
pub trait StyleElementHelpers {
... | new | identifier_name |
htmlstyleelement.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::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::... |
fn child_inserted(&self, child: JSRef<Node>) {
match self.super_type() {
Some(ref s) => s.child_inserted(child),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() {
self.parse_own_css();
}
}
fn bi... | {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
} | identifier_body |
htmlstyleelement.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::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::... |
}
}
| {
self.parse_own_css();
} | conditional_block |
htmlstyleelement.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::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::... | }
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLStyleElement> {
let element = HTMLStyleElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLStyleElementBindin... | HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLStyleElement, localName, prefix, document)
} | 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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use pl... | handle.is_italic()));
Ok(())
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
self.data().ok()
} else {
None
}
}
///... | self.is_valid = handle.is_ok();
let handle = handle?;
self.descriptor = Some(FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(), | 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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use pl... |
})
}
/// Returns the font data along with the distance between this font's descriptor and the given
/// descriptor, if the font can be loaded.
pub fn data_for_approximate_descriptor(&mut self,
font_context: &FontContextHandle,
... | {
None
} | 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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use pl... | (&mut self) -> Result<Arc<FontTemplateData>, IoError> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return Ok(data)
}
assert!(self.strong_ref.is_none());
l... | data | 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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use pl... |
}
| {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return Ok(data)
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(FontTemplateData::new(self... | identifier_body |
shootout-k-nucleotide.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted prov... | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE ... | // the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
// | random_line_split |
shootout-k-nucleotide.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted prov... |
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in 0..frame {
code = code.push_ch... | {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => panic!("{}", c as char),
}
} | identifier_body |
shootout-k-nucleotide.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted prov... | <R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key!= &l[..key.len()]).skip(1)
{
res.push_all(l.trim().as_bytes());
}
res.into_ascii_uppercase()
}
fn main() {
let input = if std::env::var_os("RUS... | get_sequence | identifier_name |
extended.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... |
let new_private_sec = SecretKey::from_slice(&SECP256K1, &*new_private)
.expect("Private key belongs to the field [0..CURVE_ORDER) (checked above); So initializing can never fail; qed");
let mut new_public = PublicKey::from_secret_key(&SECP256K1, &new_private_sec)
.expect("Valid private key produces valid pub... | { return Err(Error::MissingIndex); } | conditional_block |
extended.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... | let (master_key, chain_code) = derivation::seed_pair(seed);
Ok(ExtendedKeyPair::with_secret(
Secret::from_unsafe_slice(&*master_key).map_err(|_| DerivationError::InvalidSeed)?,
chain_code,
))
}
pub fn secret(&self) -> &ExtendedSecret {
&self.secret
}
pub fn public(&self) -> &ExtendedPublic {
&self... | public: extended_public,
}
}
pub fn with_seed(seed: &[u8]) -> Result<ExtendedKeyPair, DerivationError> { | random_line_split |
extended.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... | <T>(private_key: H256, chain_code: H256, index: Derivation<T>) -> (H256, H256) where T: Label {
match index {
Derivation::Soft(index) => private_soft(private_key, chain_code, index),
Derivation::Hard(index) => private_hard(private_key, chain_code, index),
}
}
fn hmac_pair(data: &[u8], private_key: H256, ch... | private | identifier_name |
extended.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 test_extended<F>(f: F, test_private: H256) where F: Fn(ExtendedSecret) -> ExtendedSecret {
let (private_seed, chain_code) = master_chain_basic();
let extended_secret = ExtendedSecret::with_code(Secret::from_slice(&*private_seed), chain_code);
let derived = f(extended_secret);
assert_eq!(**derived.as_raw()... | {
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
.expect("Seed should be valid H128")
.to_vec();
derivation::seed_pair(&*seed)
} | identifier_body |
lib.rs | #![crate_name = "abc"]
#![crate_type = "lib"]
#![doc(html_root_url = "https://daviddonna.github.io/abc-rs/")]
#![warn(missing_docs)]
//! Runs Karaboga's Artificial Bee Colony algorithm in parallel.
//!
//! To take advantage of this crate, the user must implement the
//! [`Solution`](trait.Solution.html) trait for a t... | //! // As long as it's run some rounds at a time, you can keep running it.
//! let best_after_20 = hive.run_for_rounds(10).unwrap();
//!
//! // The algorithm doesn't guarantee improvement in any number of rounds,
//! // but it always keeps its all-time best.
//! assert!(best_after_20.fitness >= best... | //! // Once built, the hive can be run for a number of rounds.
//! let best_after_10 = hive.run_for_rounds(10).unwrap();
//! | random_line_split |
no-send-res-ports.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: Port<()>) -> foo {
foo {
_x: x
}
}
let x = foo(Port(Rc::new(())));
Thread::spawn(move|| {
//~^ ERROR `core::marker::Send` is not implemented
let y = x;
println!("{:?}", y);
});
}
| foo | identifier_name |
no-send-res-ports.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 y = x;
println!("{:?}", y); | random_line_split |
no-send-res-ports.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 ... | //~^ ERROR `core::marker::Send` is not implemented
let y = x;
println!("{:?}", y);
});
}
| {
#[derive(Debug)]
struct foo {
_x: Port<()>,
}
#[unsafe_destructor]
impl Drop for foo {
fn drop(&mut self) {}
}
fn foo(x: Port<()>) -> foo {
foo {
_x: x
}
}
let x = foo(Port(Rc::new(())));
Thread::spawn(move|| { | identifier_body |
mod.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 | // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either ... | // licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the | random_line_split |
lib.rs | //! `Cask` is a key-value store backed by a log-structured hash table which is inspired by
//! [bitcask](https://github.com/basho/bitcask/).
//!
//! Keys are indexed in a `HashMap` and values are written to an append-only log. To avoid the log
//! from getting filled with stale data (updated/deleted entries) a compacti... | mod util;
pub use cask::{Cask, CaskOptions, SyncStrategy}; | random_line_split | |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
pub mod nom7 {
use nom7::bytes::streaming::{tag, take_until};
use nom7::error::{Error, ParseError};
use nom7::ErrorConvert;
use nom7::IResult;
/// Reimplementation of `take_until_and_consume` for nom 7
///
/// `take_until` does not consume t... |
drop(CString::from_raw(s));
}
/// Convert an u8-array of data into a hexadecimal representation
pub fn to_hex(input: &[u8]) -> String {
static CHARS: &'static [u8] = b"0123456789abcdef";
return input.iter().map(
|b| vec![char::from(CHARS[(b >> 4) as usize]), char::from(CHARS[(b & 0xf) as usize])... | {
return;
} | conditional_block |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
pub mod nom7 {
use nom7::bytes::streaming::{tag, take_until};
use nom7::error::{Error, ParseError};
use nom7::ErrorConvert;
use nom7::IResult;
/// Reimplementation of `take_until_and_consume` for nom 7
///
/// `take_until` does not consume t... | (s: *mut c_char) {
if s.is_null() {
return;
}
drop(CString::from_raw(s));
}
/// Convert an u8-array of data into a hexadecimal representation
pub fn to_hex(input: &[u8]) -> String {
static CHARS: &'static [u8] = b"0123456789abcdef";
return input.iter().map(
|b| vec![char::from(CHAR... | rs_cstring_free | identifier_name |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
pub mod nom7 {
use nom7::bytes::streaming::{tag, take_until};
use nom7::error::{Error, ParseError};
use nom7::ErrorConvert;
use nom7::IResult;
/// Reimplementation of `take_until_and_consume` for nom 7
///
/// `take_until` does not consume t... |
}
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
);
#[cfg(not(feature = "debug-validate"))]
#[... | {
// use full path to disambiguate nom `bits` from this current function name
nom7::bits::bits(parser)
} | identifier_body |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
pub mod nom7 {
use nom7::bytes::streaming::{tag, take_until}; |
/// Reimplementation of `take_until_and_consume` for nom 7
///
/// `take_until` does not consume the matched tag, and
/// `take_until_and_consume` was removed in nom 7. This function
/// provides an implementation (specialized for `&[u8]`).
pub fn take_until_and_consume<'a, E: ParseError<&'a [u... | use nom7::error::{Error, ParseError};
use nom7::ErrorConvert;
use nom7::IResult; | random_line_split |
io.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::rt::io::{io_error, IoError};
/// Helper for catching an I/O error and wrapping it in a Result object. Th... | <T>(cb: &fn() -> T) -> Result<T, IoError> {
let mut err = None;
let ret = io_error::cond.trap(|e| err = Some(e)).inside(cb);
match err {
Some(e) => Err(e),
None => Ok(ret),
}
}
| result | identifier_name |
io.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::rt::io::{io_error, IoError};
/// Helper for catching an I/O error and wrapping it in a Result object. Th... | {
let mut err = None;
let ret = io_error::cond.trap(|e| err = Some(e)).inside(cb);
match err {
Some(e) => Err(e),
None => Ok(ret),
}
} | identifier_body | |
io.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::rt::io::{io_error, IoError};
/// Helper for catching an I/O error and wrapping it in a Result object. Th... | } | match err {
Some(e) => Err(e),
None => Ok(ret),
} | random_line_split |
texture.rs | // Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | /// Check if it's one of the cube kinds.
pub fn is_cube(&self) -> bool {
match *self {
Kind::Cube(_) | Kind::CubeArray(_, _) => true,
_ => false,
}
}
}
/// Describes a subvolume of a texture, which image data can be uploaded into.
#[allow(missing_docs)]
#[derive(Eq,... | random_line_split | |
texture.rs | // Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | {
/// No additional sample information
Single,
/// MultiSampled Anti-Aliasing (MSAA)
Multi(NumSamples),
/// Coverage Sampling Anti-Aliasing (CSAA/EQAA)
Coverage(NumSamples, NumFragments),
}
impl From<NumSamples> for AaMode {
fn from(ns: NumSamples) -> AaMode {
if ns > 1 {
... | AaMode | identifier_name |
texture.rs | // Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
/// Check if it's one of the cube kinds.
pub fn is_cube(&self) -> bool {
match *self {
Kind::Cube(_) | Kind::CubeArray(_, _) => true,
_ => false,
}
}
}
/// Describes a subvolume of a texture, which image data can be uploaded into.
#[allow(missing_docs)]
#[derive(Eq... | {
match *self {
Kind::D1(..) | Kind::D2(..) | Kind::D3(..) | Kind::Cube(..) => None,
Kind::D1Array(_, a) => Some(a),
Kind::D2Array(_, _, a, _) => Some(a),
Kind::CubeArray(_, a) => Some(a),
}
} | identifier_body |
engine.rs | use autocomplete::AutoCompleter;
use autocomplete::Completion;
use runner::Runner;
use externalrunner::ExternalRunner;
use externalautocompleter::ExternalAutoCompleter;
use std::collections::HashMap;
use itertools::Itertools;
use toml;
pub trait Engine {
fn get_completions(&self, query: &str) -> Box<Iterator<Item ... | let runner_configs = config.get("runner").expect("expected runner configs").as_array().expect("array");
let mut runners: Vec<Box<ExternalRunner>> = Vec::new();
for runner in runner_configs {
println!("Runner: {:?}", runner);
runners.push(ExternalRunner::new(
... | }
pub fn get_runners(config: &toml::value::Table) -> HashMap<String, Vec<Box<ExternalRunner>>> { | random_line_split |
engine.rs | use autocomplete::AutoCompleter;
use autocomplete::Completion;
use runner::Runner;
use externalrunner::ExternalRunner;
use externalautocompleter::ExternalAutoCompleter;
use std::collections::HashMap;
use itertools::Itertools;
use toml;
pub trait Engine {
fn get_completions(&self, query: &str) -> Box<Iterator<Item ... | (config: &toml::value::Table) -> DefaultEngine {
DefaultEngine {
completers: DefaultEngine::get_completers(config),
runners: DefaultEngine::get_runners(config),
}
}
pub fn get_completers(config: &toml::value::Table) -> Vec<Box<AutoCompleter>> {
let maybe_completio... | new | identifier_name |
node.rs | use super::constants::NODE;
use indy_api_types::validation::Validatable;
use super::super::crypto::did::ShortDidValue;
#[derive(Serialize, PartialEq, Debug)]
pub struct | {
#[serde(rename = "type")]
pub _type: String,
pub dest: ShortDidValue,
pub data: NodeOperationData
}
impl NodeOperation {
pub fn new(dest: ShortDidValue, data: NodeOperationData) -> NodeOperation {
NodeOperation {
_type: NODE.to_string(),
dest,
data
... | NodeOperation | identifier_name |
node.rs | use super::constants::NODE;
use indy_api_types::validation::Validatable;
use super::super::crypto::did::ShortDidValue;
#[derive(Serialize, PartialEq, Debug)]
pub struct NodeOperation {
#[serde(rename = "type")]
pub _type: String,
pub dest: ShortDidValue,
pub data: NodeOperationData
}
impl NodeOperati... |
Ok(())
}
}
| {
return Err(String::from("Invalid data json: Fields node_ip, node_port, client_ip, client_port must be specified together"));
} | conditional_block |
node.rs | use super::constants::NODE;
use indy_api_types::validation::Validatable;
use super::super::crypto::did::ShortDidValue;
#[derive(Serialize, PartialEq, Debug)]
pub struct NodeOperation {
#[serde(rename = "type")]
pub _type: String,
pub dest: ShortDidValue,
pub data: NodeOperationData
}
impl NodeOperati... | VALIDATOR,
OBSERVER
}
#[derive(Serialize, PartialEq, Debug, Deserialize)]
pub struct NodeOperationData {
#[serde(skip_serializing_if = "Option::is_none")]
pub node_ip: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub node_port: Option<i32>,
#[serde(skip_serializing_if =... | pub enum Services { | random_line_split |
hash.rs | implement `IterBytes`,
* and the implementation of `Hash` below will take care of
* the rest. This is the recommended approach, since constructing
* good keyed hash functions is quite difficult.
*/
pub trait Hash {
/**
* Compute a "keyed" hash of the value implementing the trait,
* taking `k0` and `k... | [ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, ]
];
let k0 = 0x_07_06_05_04_03_02_01_00_u64;
let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08_u64;
let mut buf : ~[u8] = ~[];
let mut t = 0;
let stream_inc = &State(k0,k1);
let stream_full = &State(k0,k1);
fn to_hex_str(r: &[u8,..8]) -> ~s... | random_line_split | |
hash.rs | built using such "keyed hash functions" cannot
* be made to perform linearly by an attacker controlling the
* hashtable's contents.
*
* In practical terms, we implement this using the SipHash 2-4
* function and require most types to only implement the
* IterBytes trait, that feeds SipHash... | test_hash_uint | identifier_name | |
hash.rs | `IterBytes`,
* and the implementation of `Hash` below will take care of
* the rest. This is the recommended approach, since constructing
* good keyed hash functions is quite difficult.
*/
pub trait Hash {
/**
* Compute a "keyed" hash of the value implementing the trait,
* taking `k0` and `k1` as "key... |
self.v3 ^= m;
compress!(self.v0, self.v1, self.v2, self.v3);
compress!(self.v0, self.v1, self.v2, self.v3);
self.v0 ^= m;
self.ntail = 0;
}
// Buffered tail is now flushed, process new input.
let len = length - needed;
let e... | {
needed = 8 - self.ntail;
if length < needed {
let mut t = 0;
while t < length {
self.tail[self.ntail+t] = msg[t];
t += 1;
}
self.ntail += length;
return;
}
... | conditional_block |
hash.rs | -> u64;
}
impl<A:Hash> HashUtil for A {
#[inline(always)]
fn hash(&self) -> u64 { self.hash_keyed(0,0) }
}
/// Streaming hash-functions should implement this.
pub trait Streaming {
fn input(&self, (&const [u8]));
// These can be refactored some when we have default methods.
fn result_bytes(&self)... | {
let val64 = 0xdeadbeef_deadbeef_u64;
val64.hash() == val64.hash();
let val32 = 0xdeadbeef_u32;
val32.hash() == val32.hash();
} | identifier_body | |
command_loop.rs | extern crate i3ipc;
use i3ipc::I3Connection;
use std::io;
use std::io::Write;
fn | () {
println!("Executes i3 commands in a loop. Enter \"q\" at any time to quit.");
let mut connection = I3Connection::connect().expect("failed to connect");
let stdin = io::stdin();
let mut stdout = io::stdout();
loop {
print!(">>> ");
stdout.flush().unwrap();
let mut command... | main | identifier_name |
command_loop.rs | extern crate i3ipc;
use i3ipc::I3Connection;
use std::io;
use std::io::Write;
fn main() | if outcome.success {
println!("success");
} else {
println!("failure");
if let Some(e) = outcome.error.as_ref() {
println!("{}", e);
}
}
}
}
// the socket closes when `connection` goe... | {
println!("Executes i3 commands in a loop. Enter \"q\" at any time to quit.");
let mut connection = I3Connection::connect().expect("failed to connect");
let stdin = io::stdin();
let mut stdout = io::stdout();
loop {
print!(">>> ");
stdout.flush().unwrap();
let mut command_te... | identifier_body |
command_loop.rs | extern crate i3ipc;
use i3ipc::I3Connection;
use std::io;
use std::io::Write;
fn main() {
println!("Executes i3 commands in a loop. Enter \"q\" at any time to quit.");
let mut connection = I3Connection::connect().expect("failed to connect");
let stdin = io::stdin();
let mut stdout = io::stdout();
... |
}
}
}
// the socket closes when `connection` goes out of scope
}
| {
println!("{}", e);
} | conditional_block |
command_loop.rs | extern crate i3ipc;
use i3ipc::I3Connection;
use std::io;
use std::io::Write;
fn main() {
println!("Executes i3 commands in a loop. Enter \"q\" at any time to quit.");
let mut connection = I3Connection::connect().expect("failed to connect");
let stdin = io::stdin();
let mut stdout = io::stdout();
... | command_text.pop(); // throw away the \n
if command_text == "q" {
break;
}
let outcomes = connection
.run_command(&command_text)
.expect("failed to send command")
.outcomes;
for outcome in outcomes {
if outcome.success {
... | stdin.read_line(&mut command_text).unwrap(); | random_line_split |
fullscreen.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io::{self, Write};
mod support;
#[cfg(target_os = "android")]
android_start!(main);
fn main() {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerat... | _ => ()
}
}
} | random_line_split | |
fullscreen.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io::{self, Write};
mod support;
#[cfg(target_os = "android")]
android_start!(main);
fn | () {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
io::stdout().flush().unwrap();
... | main | identifier_name |
fullscreen.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io::{self, Write};
mod support;
#[cfg(target_os = "android")]
android_start!(main);
fn main() | let window = glutin::WindowBuilder::new()
.with_title("Hello world!")
.with_fullscreen(monitor)
.build()
.unwrap();
let _ = unsafe { window.make_current() };
let context = support::load(&window);
for event in window.wait_events() {
context.draw_frame((0.0, 1.0... | {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
io::stdout().flush().unwrap();
... | identifier_body |
util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
pub fn path_div() -> ~str { ~":" }
#[cfg(target_os = "win32")]
pub fn path_div() -> ~str { ~";" }
pub fn logv(config: config, s: ~str) {
debug!("%s", s);
if config.verbose { io::println(s); }
}
| { ~"PATH" } | identifier_body |
util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
| { io::println(s); } | conditional_block |
util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub fn lib_path_env_var() -> ~str { ~"DYLD_LIBRARY_PATH" }
#[cfg(target_os = "win32")]
pub fn lib_path_env_var() -> ~str { ~"PATH" }
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
pub fn path_div() -> ~str { ~":" }
#[cfg(target_os = "win32")]
pub fn path_div() -> ~str { ~";" }
... |
#[cfg(target_os = "macos")] | random_line_split |
util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> ~str { ~"PATH" }
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
pub fn path_div() -> ~str { ~":" }
#[cfg(target_os = "win32")]
pub fn path_div() -> ~str { ~";" }
pub fn logv(config: config, s: ~str) {
debug!("%s", s);
if config.verbose { io::println(s); }
}
| lib_path_env_var | identifier_name |
match-range-fail.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 ... | //~^^ ERROR only char and numeric types are allowed in range
//~| start type: &'static str
//~| end type: &'static str
match "wow" {
10... "what" => ()
};
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: _
//~| end type: &'static str
match 5 {
... | fn main() {
match "wow" {
"bar" ... "foo" => { }
}; | random_line_split |
match-range-fail.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 ... | //~| expected char
//~| found integral variable
}
| {
match "wow" {
"bar" ... "foo" => { }
};
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: &'static str
//~| end type: &'static str
match "wow" {
10 ... "what" => ()
};
//~^^ ERROR only char and numeric types are allowed in range
//~| sta... | identifier_body |
match-range-fail.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
match "wow" {
"bar"... "foo" => { }
};
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: &'static str
//~| end type: &'static str
match "wow" {
10... "what" => ()
};
//~^^ ERROR only char and numeric types are allowed in range
//~| st... | main | identifier_name |
tridiagonal.rs | use ndarray::*;
use ndarray_linalg::*;
// Solve `Ax=b` for tridiagonal matrix
fn solve() -> Result<(), error::LinalgError> |
// Solve `Ax=b` for many b with fixed A
fn factorize() -> Result<(), error::LinalgError> {
let mut a: Array2<f64> = random((3, 3));
a[[0, 2]] = 0.0;
a[[2, 0]] = 0.0;
let f = a.factorize_tridiagonal()?; // LU factorize A (A is *not* consumed)
for _ in 0..10 {
let b: Array1<f64> = random(3);... | {
let mut a: Array2<f64> = random((3, 3));
let b: Array1<f64> = random(3);
a[[0, 2]] = 0.0;
a[[2, 0]] = 0.0;
let _x = a.solve_tridiagonal(&b)?;
Ok(())
} | identifier_body |
tridiagonal.rs | use ndarray::*;
use ndarray_linalg::*;
// Solve `Ax=b` for tridiagonal matrix
fn solve() -> Result<(), error::LinalgError> {
let mut a: Array2<f64> = random((3, 3));
let b: Array1<f64> = random(3);
a[[0, 2]] = 0.0;
a[[2, 0]] = 0.0;
let _x = a.solve_tridiagonal(&b)?;
Ok(())
}
// Solve `Ax=b` fo... | () {
solve().unwrap();
factorize().unwrap();
}
| main | identifier_name |
tridiagonal.rs | use ndarray::*;
use ndarray_linalg::*;
// Solve `Ax=b` for tridiagonal matrix
fn solve() -> Result<(), error::LinalgError> {
let mut a: Array2<f64> = random((3, 3));
let b: Array1<f64> = random(3);
a[[0, 2]] = 0.0;
a[[2, 0]] = 0.0;
let _x = a.solve_tridiagonal(&b)?;
Ok(())
}
// Solve `Ax=b` fo... | Ok(())
}
fn main() {
solve().unwrap();
factorize().unwrap();
} | random_line_split | |
lib.rs | #![feature(macro_rules, log_syntax, trace_macros)]
#![allow(unused_variable)]
#![allow(dead_code)]
extern crate serialize;
extern crate url;
extern crate time;
use std::iter::Peekable;
use std::vec::MoveItems;
use self::client::{JsonClient, Client, JsonResult, JsonError};
use self::sub::Subreddit;
use self::user::{U... |
pub fn set_batch_size(val: u32) {
batch_size.replace(Some(val));
}
/// Login to reddit. Returns `Ok(Session)` on success, `Err(AuthError("reason"))` on failure.
pub fn login(user: &str, pass: &str) -> RedditResult<Session> {
let url = make_url("api/login");
let params = params! {
"user":... | {
batch_size.get().map_or(50u32, |val| *val)
} | identifier_body |
lib.rs | #![feature(macro_rules, log_syntax, trace_macros)]
#![allow(unused_variable)]
#![allow(dead_code)]
extern crate serialize;
extern crate url;
extern crate time;
use std::iter::Peekable;
use std::vec::MoveItems;
use self::client::{JsonClient, Client, JsonResult, JsonError};
use self::sub::Subreddit;
use self::user::{U... | (url_part: &str) -> Url {
let url = format!("{}/{}", BASE_URL, url_part);
Url::parse(url[]).unwrap()
}
/// Struct representing an authenticated user session;
/// required by any API endpoint that submits changes to reddit, such as posting to subreddits, replying to comments, etc.
pub struct Session {
... | make_url | identifier_name |
lib.rs | #![feature(macro_rules, log_syntax, trace_macros)]
#![allow(unused_variable)]
#![allow(dead_code)]
extern crate serialize;
extern crate url;
extern crate time;
use std::iter::Peekable;
use std::vec::MoveItems;
use self::client::{JsonClient, Client, JsonResult, JsonError};
use self::sub::Subreddit;
use self::user::{U... |
next
}
}
/// A trait for data types that should be fetched in batches, if possible.
pub trait Batched {
/// Get the next batch of length `size` or smaller,
/// starting after `last` if provided, the beginning if not.
/// If no (more) results are available, return an empty vector.
fn bat... | {
let batch = Batched::batch(next.as_ref(), self.size);
if !batch.is_empty() {
self.current = batch.move_iter().peekable();
}
} | conditional_block |
lib.rs | #![feature(macro_rules, log_syntax, trace_macros)]
#![allow(unused_variable)]
#![allow(dead_code)]
extern crate serialize;
extern crate url;
extern crate time;
use std::iter::Peekable;
use std::vec::MoveItems;
use self::client::{JsonClient, Client, JsonResult, JsonError};
use self::sub::Subreddit;
use self::user::{U... | at_utc(tmspec)
}
/// Lightweight utilities for working with `serialize::json::Json`.
pub mod json {
use serialize::json::Json;
use time::Tm;
/// Get a u64 from the given JSON and key, convert
/// it to a Tm in UTC, assuming it is POSIX time
pub fn find_utc(json: &Json, key: &str) -> Option... | // is, according to Wolfram|Alpha, about 300 billion years in the future.
// I think it's safe to say that we can deal with this later.
let tmspec = Timespec::new(seconds as i64, 0); | random_line_split |
mod.rs | //! Implementations of the Wayland backends using the system `libwayland`
use crate::protocol::ArgumentType;
use wayland_sys::common::{wl_argument, wl_array};
#[cfg(any(test, feature = "client_system"))]
pub mod client;
#[cfg(any(test, feature = "server_system"))]
pub mod server;
/// Magic static for wayland objects... | {
for (typ, arg) in signature.iter().zip(arglist.iter()) {
if let ArgumentType::Array(_) = typ {
// Safety: the arglist provided arglist must be valid for associated signature
// and contains pointers to boxed arrays as appropriate
let _ = unsafe { Box::from_raw(arg.a as ... | identifier_body | |
mod.rs | //! Implementations of the Wayland backends using the system `libwayland`
use crate::protocol::ArgumentType;
use wayland_sys::common::{wl_argument, wl_array};
#[cfg(any(test, feature = "client_system"))]
pub mod client;
#[cfg(any(test, feature = "server_system"))]
pub mod server;
/// Magic static for wayland objects... |
}
}
| {
// Safety: the arglist provided arglist must be valid for associated signature
// and contains pointers to boxed arrays as appropriate
let _ = unsafe { Box::from_raw(arg.a as *mut wl_array) };
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.