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 |
|---|---|---|---|---|
query04.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use {Arrangements, Experiment, Collections};
// -- $ID$
// -- TPC-H/TPC-R Order Priority Checking Query (Q4)
// ... |
})
.count_total()
.probe_with(probe);
} | {
None
} | conditional_block |
backend_termion.rs | #[cfg(feature = "termion")]
#[test]
fn backend_termion_should_only_write_diffs() -> Result<(), Box<dyn std::error::Error>> | })?;
terminal.draw(|f| {
f.render_widget(Paragraph::new("ab"), area);
})?;
terminal.draw(|f| {
f.render_widget(Paragraph::new("abc"), area);
})?;
}
let expected = {
use termion::{color, cursor, style};
let mut s = String::new();
... | {
use std::{fmt::Write, io::Cursor};
let mut bytes = Vec::new();
let mut stdout = Cursor::new(&mut bytes);
{
use tui::{
backend::TermionBackend, layout::Rect, widgets::Paragraph, Terminal, TerminalOptions,
Viewport,
};
let backend = TermionBackend::new(&m... | identifier_body |
backend_termion.rs | #[cfg(feature = "termion")]
#[test]
fn backend_termion_should_only_write_diffs() -> Result<(), Box<dyn std::error::Error>> {
use std::{fmt::Write, io::Cursor};
let mut bytes = Vec::new();
let mut stdout = Cursor::new(&mut bytes);
{
use tui::{
backend::TermionBackend, layout::Rect, w... | };
assert_eq!(std::str::from_utf8(&bytes)?, expected);
Ok(())
} | s | random_line_split |
backend_termion.rs | #[cfg(feature = "termion")]
#[test]
fn | () -> Result<(), Box<dyn std::error::Error>> {
use std::{fmt::Write, io::Cursor};
let mut bytes = Vec::new();
let mut stdout = Cursor::new(&mut bytes);
{
use tui::{
backend::TermionBackend, layout::Rect, widgets::Paragraph, Terminal, TerminalOptions,
Viewport,
};... | backend_termion_should_only_write_diffs | identifier_name |
const-block-non-item-statement-2.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 ... | () {}
| main | identifier_name |
const-block-non-item-statement-2.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 ... | {} | identifier_body | |
const-block-non-item-statement-2.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. | // <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.
const A: usize = { 1; 2 };
//~^ ERROR statements in constants are unstable
const B: usize = { { } 2 };
//~^ ERROR statements in constants are unstable
m... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
lib.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! FFI bindings to d3d9.
#![cfg(windows)]
extern crate winapi;
use winapi::*;
#[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm"))] | extern "system" {
pub fn D3DPERF_BeginEvent(col: D3DCOLOR, wszName: LPCWSTR) -> INT;
pub fn D3DPERF_EndEvent() -> INT;
pub fn D3DPERF_GetStatus() -> DWORD;
pub fn D3DPERF_QueryRepeatFrame() -> BOOL;
pub fn D3DPERF_SetMarker(col: D3DCOLOR, wszName: LPCWSTR) -> ();
pub fn D3DPERF_SetOptions(dwOpti... | random_line_split | |
logging-right-crate.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | extern crate logging_right_crate;
pub fn main() {
// this function panicks if logging is turned on
logging_right_crate::foo::<int>();
} | random_line_split | |
logging-right-crate.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
// this function panicks if logging is turned on
logging_right_crate::foo::<int>();
}
| main | identifier_name |
logging-right-crate.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
// this function panicks if logging is turned on
logging_right_crate::foo::<int>();
} | identifier_body | |
mod.rs | pub use self::cache::*;
pub use self::combiners::*;
pub use self::generators::*;
pub use self::modifiers::*;
pub use self::selectors::*;
pub use self::transformers::*;
mod cache;
mod combiners;
mod generators;
mod modifiers;
mod selectors;
mod transformers;
/// Base trait for noise functions.
///
/// A noise function... | (&self, point: T) -> f64 {
M::get(*self, point)
}
}
/// Trait for functions that require a seed before generating their values
pub trait Seedable {
/// Set the seed for the function implementing the `Seedable` trait
fn set_seed(self, seed: u32) -> Self;
/// Getter to retrieve the seed from the... | get | identifier_name |
mod.rs | pub use self::cache::*;
pub use self::combiners::*;
pub use self::generators::*;
pub use self::modifiers::*;
pub use self::selectors::*;
pub use self::transformers::*;
mod cache;
mod combiners;
mod generators;
mod modifiers;
mod selectors;
mod transformers;
/// Base trait for noise functions.
///
/// A noise function... | #[inline]
fn get(&self, point: T) -> f64 {
M::get(*self, point)
}
}
/// Trait for functions that require a seed before generating their values
pub trait Seedable {
/// Set the seed for the function implementing the `Seedable` trait
fn set_seed(self, seed: u32) -> Self;
/// Getter to re... | fn get(&self, point: T) -> f64;
}
impl<'a, T, M: NoiseFn<T>> NoiseFn<T> for &'a M { | random_line_split |
mod.rs | pub use self::cache::*;
pub use self::combiners::*;
pub use self::generators::*;
pub use self::modifiers::*;
pub use self::selectors::*;
pub use self::transformers::*;
mod cache;
mod combiners;
mod generators;
mod modifiers;
mod selectors;
mod transformers;
/// Base trait for noise functions.
///
/// A noise function... |
}
/// Trait for functions that require a seed before generating their values
pub trait Seedable {
/// Set the seed for the function implementing the `Seedable` trait
fn set_seed(self, seed: u32) -> Self;
/// Getter to retrieve the seed from the function
fn seed(&self) -> u32;
}
| {
M::get(*self, point)
} | identifier_body |
linkage-visibility.rs | // Copyright 2013 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 ... |
// We're testing linkage visibility; the compiler warns us, but we want to
// do the runtime check that these functions aren't exported.
#![allow(private_no_mangle_fns)]
use std::dynamic_lib::DynamicLibrary;
#[no_mangle]
pub fn foo() { bar(); }
pub fn foo2<T>() {
fn bar2() {
bar();
}
bar2();
}
... | random_line_split | |
linkage-visibility.rs | // Copyright 2013 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 test() {
let lib = DynamicLibrary::open(None).unwrap();
unsafe {
assert!(lib.symbol::<isize>("foo").is_ok());
assert!(lib.symbol::<isize>("baz").is_err());
assert!(lib.symbol::<isize>("bar").is_err());
}
}
| { } | identifier_body |
linkage-visibility.rs | // Copyright 2013 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 ... | () { }
#[allow(dead_code)]
#[no_mangle]
fn baz() { }
pub fn test() {
let lib = DynamicLibrary::open(None).unwrap();
unsafe {
assert!(lib.symbol::<isize>("foo").is_ok());
assert!(lib.symbol::<isize>("baz").is_err());
assert!(lib.symbol::<isize>("bar").is_err());
}
}
| bar | identifier_name |
weak_lang_items.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 ... | tcx.sess.err(&format!("language item required, but not found: `{}`",
stringify!($name)));
}
}
)*
}
impl<'a, 'tcx> Context<'a, 'tcx> {
fn register(&mut self, name: &str, span: Span) {
$(if name == stringify!($name) {
i... | } else if lang_items::$item == lang_items::OomLangItem {
tcx.sess.err(&format!("`#[alloc_error_handler]` function required, \
but not found"));
} else { | random_line_split |
floatfns.rs | //! Functions operating on float numbers.
use libc;
use std::mem;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsDouble, EmacsInt, EmacsUint, Lisp_Object, MOST_NEGATIVE_FIXNUM,
MOST_POSITIVE_FIXNUM};
use remacs_sys::{Qarith_error, Qinteger_or_marker_p, Qnumberp, Qrange_error};
use remacs_sys::buil... |
/// Return the exponential ARG1 ** ARG2.
#[lisp_fn]
pub fn expt(arg1: LispObject, arg2: LispObject) -> LispObject {
if let (Some(x), Some(y)) = (arg1.as_fixnum(), arg2.as_fixnum()) {
if y >= 0 && y <= u32::max_value() as EmacsInt {
return LispObject::from_fixnum(x.pow(y as u32));
}
... | {
let exponent = exponent.as_fixnum_or_error();
let significand = sgnfcand.any_to_float_or_error();
let result = libm::ldexp(significand, exponent as libc::c_int);
LispObject::from_float(result)
} | identifier_body |
floatfns.rs | //! Functions operating on float numbers.
use libc;
use std::mem;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsDouble, EmacsInt, EmacsUint, Lisp_Object, MOST_NEGATIVE_FIXNUM,
MOST_POSITIVE_FIXNUM};
use remacs_sys::{Qarith_error, Qinteger_or_marker_p, Qnumberp, Qrange_error};
use remacs_sys::buil... | pub fn fceiling(arg: LispObject) -> LispObject {
let d = arg.as_float_or_error();
LispObject::from_float(d.ceil())
}
/// Return the largest integer no greater than ARG, as a float.
/// (Round toward -inf.)
#[lisp_fn]
pub fn ffloor(arg: LispObject) -> LispObject {
let d = arg.as_float_or_error();
LispOb... |
/// Return the smallest integer no less than ARG, as a float.
/// (Round toward +inf.)
#[lisp_fn] | random_line_split |
floatfns.rs | //! Functions operating on float numbers.
use libc;
use std::mem;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsDouble, EmacsInt, EmacsUint, Lisp_Object, MOST_NEGATIVE_FIXNUM,
MOST_POSITIVE_FIXNUM};
use remacs_sys::{Qarith_error, Qinteger_or_marker_p, Qnumberp, Qrange_error};
use remacs_sys::buil... | else if args.len() == 1 {
-next
} else {
next
}
}
}
ArithOp::Mult => accum *= next,
ArithOp::Div => if args.len() > 1 && argnum == 0 {
accum = next;
} ... | {
accum - next
} | conditional_block |
floatfns.rs | //! Functions operating on float numbers.
use libc;
use std::mem;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsDouble, EmacsInt, EmacsUint, Lisp_Object, MOST_NEGATIVE_FIXNUM,
MOST_POSITIVE_FIXNUM};
use remacs_sys::{Qarith_error, Qinteger_or_marker_p, Qnumberp, Qrange_error};
use remacs_sys::buil... | (i1: EmacsInt, i2: EmacsInt) -> EmacsInt {
i1 / i2
}
fn round2(i1: EmacsInt, i2: EmacsInt) -> EmacsInt {
// The division operator gives us one remainder R, but we want the
// remainder R1 on the other side of 0 if R1 is closer to 0 than R
// is; because we want to round to even, we also want R1 if R an... | truncate2 | identifier_name |
main.rs | extern crate crypto;
use crypto::ripemd160;
use crypto::digest::Digest;
fn ripemd_str(string: &str) -> String {
let mut ripemd = ripemd160::Ripemd160::new();
ripemd.input_str(string);
ripemd.result_str()
}
fn main() {
println!("{}", ripemd_str("Rosetta Code"));
}
#[cfg(test)]
mod tests {
use sup... | }
} | "b0e20b6e3116640286ed3a87a5713079b21f5189"); | random_line_split |
main.rs | extern crate crypto;
use crypto::ripemd160;
use crypto::digest::Digest;
fn ripemd_str(string: &str) -> String {
let mut ripemd = ripemd160::Ripemd160::new();
ripemd.input_str(string);
ripemd.result_str()
}
fn main() |
#[cfg(test)]
mod tests {
use super::ripemd_str;
#[test]
fn ripemd160() {
assert_eq!(ripemd_str("Rosetta Code"),
"b3be159860842cebaa7174c8fff0aa9e50a5199f");
assert_eq!(ripemd_str(""), "9c1185a5c5e9fc54612808977ee8f548b2258d31");
assert_eq!(ripemd_str("ABCDEFGHIJ... | {
println!("{}", ripemd_str("Rosetta Code"));
} | identifier_body |
main.rs | extern crate crypto;
use crypto::ripemd160;
use crypto::digest::Digest;
fn ripemd_str(string: &str) -> String {
let mut ripemd = ripemd160::Ripemd160::new();
ripemd.input_str(string);
ripemd.result_str()
}
fn main() {
println!("{}", ripemd_str("Rosetta Code"));
}
#[cfg(test)]
mod tests {
use sup... | () {
assert_eq!(ripemd_str("Rosetta Code"),
"b3be159860842cebaa7174c8fff0aa9e50a5199f");
assert_eq!(ripemd_str(""), "9c1185a5c5e9fc54612808977ee8f548b2258d31");
assert_eq!(ripemd_str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"),
"b0e20b6... | ripemd160 | identifier_name |
guard.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/. */
//! Machinery to conditionally expose things.
use js::jsapi::{HandleObject, JSContext};
use util::prefs::get_pref... | }
/// A condition to expose things.
pub enum Condition {
/// The condition is satisfied if the function returns true.
Func(unsafe fn(*mut JSContext, HandleObject) -> bool),
/// The condition is satisfied if the preference is set.
Pref(&'static str),
/// The condition is always satisfied.
Satisf... | } | random_line_split |
guard.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/. */
//! Machinery to conditionally expose things.
use js::jsapi::{HandleObject, JSContext};
use util::prefs::get_pref... | (&self, cx: *mut JSContext, obj: HandleObject) -> Option<T> {
if self.condition.is_satisfied(cx, obj) {
Some(self.value)
} else {
None
}
}
}
/// A condition to expose things.
pub enum Condition {
/// The condition is satisfied if the function returns true.
Fu... | expose | identifier_name |
guard.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/. */
//! Machinery to conditionally expose things.
use js::jsapi::{HandleObject, JSContext};
use util::prefs::get_pref... |
}
| {
match *self {
Condition::Pref(name) => get_pref(name).as_boolean().unwrap_or(false),
Condition::Func(f) => f(cx, obj),
Condition::Satisfied => true,
}
} | identifier_body |
contact.rs | use crate::math::{Point, Vector};
use crate::query::ContactKinematic;
use na::{self, RealField, Unit};
use slotmap::Key;
use std::mem;
slotmap::new_key_type! {
/// A contact identifier which is unique within a contact manifold.
pub struct ContactId;
}
/// Geometric description of a contact.
#[derive(Debug, Pa... |
/// The sine of angular regularization for the first solid.
#[inline]
pub fn sin_angular1(&self) -> N {
self.sin_angular1
}
/// The sine angular regularization for the second solid.
#[inline]
pub fn sin_angular2(&self) -> N {
self.sin_angular2
}
}
| {
self.cos_angular2
} | identifier_body |
contact.rs | use crate::math::{Point, Vector};
use crate::query::ContactKinematic;
use na::{self, RealField, Unit};
use slotmap::Key;
use std::mem;
slotmap::new_key_type! {
/// A contact identifier which is unique within a contact manifold.
pub struct ContactId;
}
/// Geometric description of a contact.
#[derive(Debug, Pa... | (world1: Point<N>, world2: Point<N>, normal: Unit<Vector<N>>) -> Contact<N> {
let depth = -normal.dot(&(world2 - world1));
Self::new(world1, world2, normal, depth)
}
}
impl<N: RealField> Contact<N> {
/// Reverts the contact normal and swaps `world1` and `world2`.
#[inline]
pub fn flip(&... | new_wo_depth | identifier_name |
contact.rs | use crate::math::{Point, Vector};
use crate::query::ContactKinematic;
use na::{self, RealField, Unit};
use slotmap::Key;
use std::mem;
slotmap::new_key_type! {
/// A contact identifier which is unique within a contact manifold.
pub struct ContactId;
}
/// Geometric description of a contact.
#[derive(Debug, Pa... | sin_angular2: angular2.sin(),
}
}
/// The linear prediction.
#[inline]
pub fn linear(&self) -> N {
self.linear
}
/// Sets linear prediction.
#[inline]
pub fn set_linear(&mut self, val: N) {
self.linear = val
}
/// The angular regularization ... | random_line_split | |
entities.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/.
//! Data structures containing extracted URL, mention, tag, and media information.
//!
//! These structures are meant... | <'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
{
let opt = Option::deserialize(deserializer)?;
Ok(opt.unwrap_or_default())
}
| nullable_str | identifier_name |
entities.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/.
//! Data structures containing extracted URL, mention, tag, and media information.
//!
//! These structures are meant... | pub media_type: MediaType,
///The t.co link from the original text.
pub url: String,
///For media entities corresponding to videos, this contains extra information about the linked
///video.
pub video_info: Option<VideoInfo>,
///Media alt text, if present.
pub ext_alt_text: Option<String... | pub source_status_id: Option<u64>,
///The type of media being represented.
#[serde(rename = "type")] | random_line_split |
dispatcher.rs | use frame::Frame;
use genet_abi::{
context::Context,
decoder::{DecoderBox, ExecType, Metadata, WorkerBox},
fixed::MutFixed,
layer::{Layer, Parent},
};
use profile::Profile;
pub struct Dispatcher {
runners: Vec<Runner>,
}
impl Dispatcher {
pub fn new(typ: &ExecType, profile: &Profile) -> Dispat... | }
pub fn process_frame(&mut self, frame: &mut Frame) {
let mut indices = frame.fetch_tree_indices();
let mut layers = frame.fetch_layers();
let mut offset = 0;
let mut runners = self.runners();
loop {
let len = layers.len() - offset;
for index in ... | pub fn runners(&mut self) -> Vec<OnceRunner> {
self.runners
.iter_mut()
.map(|r| OnceRunner::new(r))
.collect() | random_line_split |
dispatcher.rs | use frame::Frame;
use genet_abi::{
context::Context,
decoder::{DecoderBox, ExecType, Metadata, WorkerBox},
fixed::MutFixed,
layer::{Layer, Parent},
};
use profile::Profile;
pub struct Dispatcher {
runners: Vec<Runner>,
}
impl Dispatcher {
pub fn new(typ: &ExecType, profile: &Profile) -> Dispat... | else {
None
}
}
}
pub struct OnceRunner<'a> {
runner: &'a mut Runner,
used: bool,
}
impl<'a> OnceRunner<'a> {
fn new(runner: &'a mut Runner) -> OnceRunner {
OnceRunner {
runner,
used: false,
}
}
fn execute(&mut self, layers: &[MutFi... | {
Some(self.decoder.new_worker(&self.ctx))
} | conditional_block |
dispatcher.rs | use frame::Frame;
use genet_abi::{
context::Context,
decoder::{DecoderBox, ExecType, Metadata, WorkerBox},
fixed::MutFixed,
layer::{Layer, Parent},
};
use profile::Profile;
pub struct Dispatcher {
runners: Vec<Runner>,
}
impl Dispatcher {
pub fn new(typ: &ExecType, profile: &Profile) -> Dispat... | (&mut self) {
self.worker = if self.metadata.exec_type == self.typ {
Some(self.decoder.new_worker(&self.ctx))
} else {
None
}
}
}
pub struct OnceRunner<'a> {
runner: &'a mut Runner,
used: bool,
}
impl<'a> OnceRunner<'a> {
fn new(runner: &'a mut Runner) -... | reset | identifier_name |
write_test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
use crate::test_helpers::{
arb_hash_batch, arb_list_of_hash_batches, test_append_empty_impl, test_append_many_impl,
MockHashStore, TestAccumulator,
};
use diem_crypto::hash::ACCUMULATOR_PLACEHOLDER_HASH;
use diem_t... | fn test_append_many(batches in arb_list_of_hash_batches(10, 10)) {
test_append_many_impl(batches);
}
#[test]
fn test_append_empty(leaves in arb_hash_batch(100)) {
test_append_empty_impl(leaves)
}
} |
#[test] | random_line_split |
write_test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
use crate::test_helpers::{
arb_hash_batch, arb_list_of_hash_batches, test_append_empty_impl, test_append_many_impl,
MockHashStore, TestAccumulator,
};
use diem_crypto::hash::ACCUMULATOR_PLACEHOLDER_HASH;
use diem_t... |
#[test]
fn test_append_one() {
let mut store = MockHashStore::new();
store.verify(&[]).unwrap();
let mut leaves = Vec::new();
for v in 0..100 {
let hash = HashValue::random();
let (root_hash, writes) =
TestAccumulator::append(&store, leaves.len() as LeafCount, &[hash]).unw... | {
let store = MockHashStore::new();
assert_eq!(
TestAccumulator::append(&store, 0, &[]).unwrap(),
(*ACCUMULATOR_PLACEHOLDER_HASH, Vec::new())
);
} | identifier_body |
write_test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
use crate::test_helpers::{
arb_hash_batch, arb_list_of_hash_batches, test_append_empty_impl, test_append_many_impl,
MockHashStore, TestAccumulator,
};
use diem_crypto::hash::ACCUMULATOR_PLACEHOLDER_HASH;
use diem_t... | () {
let mut store = MockHashStore::new();
store.verify(&[]).unwrap();
let mut leaves = Vec::new();
for v in 0..100 {
let hash = HashValue::random();
let (root_hash, writes) =
TestAccumulator::append(&store, leaves.len() as LeafCount, &[hash]).unwrap();
store.put_man... | test_append_one | identifier_name |
env.rs | use std::ops::{Deref, DerefMut};
use std::collections::HashMap;
use std::iter::FromIterator;
use std::cell::RefCell;
use rand::IsaacRng;
use rand::distributions::{Range, Sample};
use common_util::IntType;
use syntax_tree::*;
use eval::types::*;
use eval::eval_functions::eval_expr;
use error::*;
/// The Roller runtim... | (&self, id: Ident) -> NameInfo {
if let Some(_) = self.var_ns.get(&id) {
NameInfo::Var
}
else if let Some(_) = self.fun_ns.get(&id) {
NameInfo::Fun
}
else {
NameInfo::Empty
}
}
/// Returns the value of the variable with the given identifier.
pub fn get_var<'a>(&'a self, id: &Ident) -> ParseResu... | get_name_info | identifier_name |
env.rs | use std::ops::{Deref, DerefMut};
use std::collections::HashMap;
use std::iter::FromIterator;
use std::cell::RefCell;
use rand::IsaacRng;
use rand::distributions::{Range, Sample};
use common_util::IntType;
use syntax_tree::*;
use eval::types::*;
use eval::eval_functions::eval_expr;
use error::*;
/// The Roller runtim... | ,
None => Err(RollerErr::EvalError(EvalErr::NoFunFound(id.to_owned() ))),
}
}
fn ns_from_args(names: &Vec<Ident>, args: Vec<Value>) -> ParseResult<HashMap<Ident, Value>>
{
// chech whether the lengths match
if names.len()!= args.len() {
return Err(RollerErr::EvalError(
EvalErr::WrongNumParams{expect... | {
if self.call_stack.borrow().deref().len() > self.max_call_depth {
return Err(RollerErr::EvalError(EvalErr::ReachedMaxCallDepth));
}
// the fumction's local namespace
let local_ns = try!(Self::ns_from_args(&fun.params, args));
// add the function's local namespace
self.call_stack.borrow_m... | conditional_block |
env.rs | use std::ops::{Deref, DerefMut};
use std::collections::HashMap;
use std::iter::FromIterator;
use std::cell::RefCell;
use rand::IsaacRng;
use rand::distributions::{Range, Sample};
use common_util::IntType;
use syntax_tree::*;
use eval::types::*;
use eval::eval_functions::eval_expr;
use error::*;
/// The Roller runtim... | /// Returns the value of the variable with the given identifier.
pub fn get_var<'a>(&'a self, id: &Ident) -> ParseResult<Value> {
// check the last element of the call stack
if let Some(ref hm) = self.call_stack.borrow().deref().last() {
if let Some(ref val) = hm.get(id) {
// check if we found the variable... | random_line_split | |
surface.rs | // This is a part of Sonorous.
// Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon.
// See README.md for details.
//
// Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or
// the MIT license <http://opensource.org/licenses/MIT>, at your option. This file may no... |
/// Same as `WhOpt` but does not contain `()`.
pub trait Wh {
/// Returns a rectangular area.
fn wh(&self) -> (u16,u16);
}
impl XyOpt for () {
#[inline(always)]
fn xy_opt(&self) -> Option<(i16,i16)> { None }
}
// Rust: we can't define these with `impl<T:Xy> XyOpt for T` due to the ambiguity.
impl XyO... | /// Returns a rectangular area if any.
fn wh_opt(&self) -> Option<(u16,u16)>;
} | random_line_split |
surface.rs | // This is a part of Sonorous.
// Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon.
// See README.md for details.
//
// Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or
// the MIT license <http://opensource.org/licenses/MIT>, at your option. This file may no... |
}
impl<'r,T:Wh> Wh for &'r T {
#[inline(always)]
fn wh(&self) -> (u16,u16) { (*self).wh() }
}
/// A helper trait for defining every implementations for types `(T1,T2)` where `T1` and `T2` is
/// convertible to an integer.
trait ToInt16 {
/// Converts to `i16`.
fn to_i16(&self) -> i16;
/// Convert... | { self.get_size() } | identifier_body |
surface.rs | // This is a part of Sonorous.
// Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon.
// See README.md for details.
//
// Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or
// the MIT license <http://opensource.org/licenses/MIT>, at your option. This file may no... | (&self, x: uint, y: uint) -> Option<Color> {
if x < self.width && y < self.height {
Some(self.get_pixel(x, y))
} else {
None
}
}
/// Sets a pixel to given position. (C: `putpixel`)
pub fn put_pixel(&mut self, x: uint, y: uint, c: Color) {
self.pixels[... | get_pixel_checked | identifier_name |
tendermint.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 s = r#"{
"params": {
"gasLimitBoundDivisor": "0x0400",
"validators": {
"list": ["0xc6d9d2cd449a754c494264e1809c50e34d64562b"]
},
"blockReward": "0x50"
}
}"#;
let _deserialized: Tendermint = serde_json::from_str(s).unwrap();
}
}
| tendermint_deserialization | identifier_name |
tendermint.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... | "gasLimitBoundDivisor": "0x0400",
"validators": {
"list": ["0xc6d9d2cd449a754c494264e1809c50e34d64562b"]
},
"blockReward": "0x50"
}
}"#;
let _deserialized: Tendermint = serde_json::from_str(s).unwrap();
}
} | random_line_split | |
slice.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use anyhow::{anyhow, Error, Result};
use blobrepo::BlobRepo;
use c... | }
let mut head_generation_groups: BTreeMap<u64, Vec<ChangesetId>> = BTreeMap::new();
stream::iter(heads.into_iter().map(|csid| async move {
match repo.get_generation_number(ctx.clone(), csid).await? {
Some(gen) => Ok(Some((csid, gen))),
None => Err(anyhow!(
"... | {
let heads = underived_heads(ctx, repo, derivers, heads.as_slice()).await?;
if skiplist_index.indexed_node_count() == 0 {
// This skiplist index is not populated. Generate a single
// slice with all heads.
info!(
ctx.logger(),
"Repository not sliced as skiplist... | identifier_body |
slice.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use anyhow::{anyhow, Error, Result};
use blobrepo::BlobRepo;
use c... |
} else {
// This commit is in a new generation group.
let gen_group = (gen.value() / slice_size) * slice_size;
new_heads_groups.insert(parent, gen_group);
}
}
}
// Add all commits we've seen to the ... | {
heads.push(parent);
} | conditional_block |
slice.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use anyhow::{anyhow, Error, Result};
use blobrepo::BlobRepo;
use c... | }
/// Slice a respository into a sequence of slices for derivation.
///
/// For large repositories with a long history, computing the full set of
/// commits before beginning backfilling is slow, and cannot be resumed
/// if interrupted.
///
/// This function makes large repositories more tractible by using the
/// sk... | .try_collect::<Vec<_>>()
.await?;
Ok(parents_with_generations) | random_line_split |
slice.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use anyhow::{anyhow, Error, Result};
use blobrepo::BlobRepo;
use c... | (
ctx: &CoreContext,
repo: &BlobRepo,
derivers: &[Arc<dyn DerivedUtils>],
heads: &[ChangesetId],
) -> Result<HashSet<ChangesetId>> {
derivers
.iter()
.map(|deriver| async move {
Ok::<_, Error>(stream::iter(
deriver
.pending(ctx.clone(), re... | underived_heads | identifier_name |
mod.rs | //! Unified interface for communicating with different trackers.
use std::old_io::{IoResult};
use std::old_io::net::ip::{SocketAddr, IpAddr};
use types::{Timepoint};
pub mod udp;
/// Information pertaining to the swarm we are in.
pub struct AnnounceInfo {
/// Number of leechers in the swarm.
pub leechers: i... | {
/// Number of leechers in the swarm.
pub leechers: i32,
/// Number of seeders in the swarm.
pub seeders: i32,
/// Number of downloads for this torrent.
pub downloads: i32
}
/// Statistics for our download session.
#[derive(Copy)]
pub struct TransferStatus {
/// Number of bytes downloa... | ScrapeInfo | identifier_name |
mod.rs | //! Unified interface for communicating with different trackers.
use std::old_io::{IoResult};
use std::old_io::net::ip::{SocketAddr, IpAddr};
use types::{Timepoint};
pub mod udp;
/// Information pertaining to the swarm we are in.
pub struct AnnounceInfo {
/// Number of leechers in the swarm.
pub leechers: i... | }
/// Interface for communicating with an generic tracker.
pub trait Tracker {
/// Returns the local ip address that is being used to communicate with the tracker.
fn local_ip(&mut self) -> IpAddr;
/// Returns information about the swarm for a particular torrent file without
/// joining the swarm.
... | pub remaining: i64,
/// Number of bytes uploaded so far.
pub uploaded: i64 | random_line_split |
ifmt-bad-arg.rs | // Copyright 2013 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 ... | () {
// bad arguments to the format! call
format!("{}"); //~ ERROR: invalid reference to argument
format!("{1}", 1); //~ ERROR: invalid reference to argument `1`
//~^ ERROR: argument never used
format!("{foo}"); //~ ERROR: no argument named `foo`
... | main | identifier_name |
ifmt-bad-arg.rs | // Copyright 2013 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 ... | format!("{0}");
//~^ ERROR invalid reference to argument `0` (no arguments given)
format!("{0} {1}", 1);
//~^ ERROR invalid reference to argument `1` (there is 1 argument)
format!("{0} {1} {2}", 1, 2);
//~^ ERROR invalid reference to argument `2` (there are 2 arguments)
format!("{0} {1}")... | random_line_split | |
ifmt-bad-arg.rs | // Copyright 2013 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 ... |
// bad number of arguments, see #15780
format!("{0}");
//~^ ERROR invalid reference to argument `0` (no arguments given)
format!("{0} {1}", 1);
//~^ ERROR invalid reference to argument `1` (there is 1 argument)
format!("{0} {1} {2}", 1, 2);
//~^ ERROR invalid reference to argument `2` (t... | {
// bad arguments to the format! call
format!("{}"); //~ ERROR: invalid reference to argument
format!("{1}", 1); //~ ERROR: invalid reference to argument `1`
//~^ ERROR: argument never used
format!("{foo}"); //~ ERROR: no argument named `foo`
... | identifier_body |
utils.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.
*/
use std::char;
use std::ops::Range;
pub fn get_prefix_bounds(prefix: impl AsRef<str>) -> Range<String> {
let mut upper = prefix.as_ref()... |
#[test]
fn test_get_prefix_bounds_multiple() {
let prefix = "comm"; // prefix of commit
let end = "comn";
let range = get_prefix_bounds(prefix);
assert_eq!(range.start.as_str(), prefix);
assert_eq!(range.end.as_str(), end);
}
#[test]
fn test_get_prefix_boun... | {
let prefix = "z";
let end = "{";
let range = get_prefix_bounds(prefix);
assert_eq!(range.start.as_str(), prefix);
assert_eq!(range.end.as_str(), end);
} | identifier_body |
utils.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.
*/
use std::char;
use std::ops::Range;
pub fn get_prefix_bounds(prefix: impl AsRef<str>) -> Range<String> {
let mut upper = prefix.as_ref()... | assert_eq!(range.end.as_str(), end);
}
} | fn test_get_prefix_bounds_unicode() {
let prefix = "\u{1F36A}"; // Cookie Emoji
let end = "\u{1F36B}";
let range = get_prefix_bounds(prefix);
assert_eq!(range.start.as_str(), prefix); | random_line_split |
utils.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.
*/
use std::char;
use std::ops::Range;
pub fn get_prefix_bounds(prefix: impl AsRef<str>) -> Range<String> {
let mut upper = prefix.as_ref()... | () {
let prefix = "a";
let end = "b";
let range = get_prefix_bounds(prefix);
assert_eq!(range.start.as_str(), prefix);
assert_eq!(range.end.as_str(), end);
}
#[test]
fn test_get_prefix_bounds_ending_with_z() {
let prefix = "z";
let end = "{";
... | test_get_prefix_bounds_one_letter | identifier_name |
utils.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.
*/
use std::char;
use std::ops::Range;
pub fn get_prefix_bounds(prefix: impl AsRef<str>) -> Range<String> {
let mut upper = prefix.as_ref()... |
last_char_code = next_val;
}
upper.push(last_char);
prefix.as_ref().to_string()..upper
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_prefix_bounds_one_letter() {
let prefix = "a";
let end = "b";
let range = get_prefix_bounds(prefix);
as... | {
last_char = c;
break;
} | conditional_block |
macros.rs | //
//
//
/// Returns true if the passed exppression matches the pattern
#[macro_export]
macro_rules! is
{
($val:expr, $p:pat) => ( match $val { $p => true, _ => false } );
}
#[doc(hidden)]
#[macro_export]
macro_rules! _count
{
() => {0};
($a:expr) => {1};
($a:expr, $($b:expr),+) => {1+_count!($($b),+)};
}
/// Def... |
/// A safe wrapper around the `type_name` intrinsic
#[macro_export]
macro_rules! type_name
{
($t:ty) => ( $crate::macros::type_name::<$t>() );
}
/// Iterator helper, desugars to a.zip(b)
#[macro_export]
macro_rules! zip
{
($a:expr, $b:expr) => ( $a.zip($b) );
}
/// Iterator helper, desugars to a.chain(b).chain(b2... | {
// SAFE: All intrinsics are unsafe, no matter how safe they really are
unsafe { ::core::intrinsics::type_name::<T>() }
} | identifier_body |
macros.rs | //
//
//
/// Returns true if the passed exppression matches the pattern
#[macro_export]
macro_rules! is
{
($val:expr, $p:pat) => ( match $val { $p => true, _ => false } );
}
#[doc(hidden)]
#[macro_export]
macro_rules! _count
{
() => {0};
($a:expr) => {1};
($a:expr, $($b:expr),+) => {1+_count!($($b),+)};
}
/// Def... | <T:?::core::marker::Sized>() -> &'static str {
// SAFE: All intrinsics are unsafe, no matter how safe they really are
unsafe { ::core::intrinsics::type_name::<T>() }
}
/// A safe wrapper around the `type_name` intrinsic
#[macro_export]
macro_rules! type_name
{
($t:ty) => ( $crate::macros::type_name::<$t>() );
}
/... | type_name | identifier_name |
macros.rs | //
//
//
/// Returns true if the passed exppression matches the pattern
#[macro_export]
macro_rules! is
{
($val:expr, $p:pat) => ( match $val { $p => true, _ => false } );
}
#[doc(hidden)]
#[macro_export]
macro_rules! _count
{
() => {0};
($a:expr) => {1};
($a:expr, $($b:expr),+) => {1+_count!($($b),+)};
}
/// Def... | }
/// A safe wrapper around the `type_name` intrinsic
#[macro_export]
macro_rules! type_name
{
($t:ty) => ( $crate::macros::type_name::<$t>() );
}
/// Iterator helper, desugars to a.zip(b)
#[macro_export]
macro_rules! zip
{
($a:expr, $b:expr) => ( $a.zip($b) );
}
/// Iterator helper, desugars to a.chain(b).chain(b... | pub fn type_name<T: ?::core::marker::Sized>() -> &'static str {
// SAFE: All intrinsics are unsafe, no matter how safe they really are
unsafe { ::core::intrinsics::type_name::<T>() } | random_line_split |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | {
/// The initial URLs to load.
pub urls: Vec<String>,
/// The rendering backend to use (`-r`).
pub render_backend: BackendType,
/// How many threads to use for CPU rendering (`-t`).
///
/// FIXME(pcwalton): This is not currently used. All rendering is sequential.
pub n_render_threads... | Opts | identifier_name |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... |
pub fn from_cmdline_args(args: &[String]) -> Option<Opts> {
let app_name = args[0].to_str();
let args = args.tail();
let opts = vec!(
getopts::optflag("c", "cpu", "CPU rendering"),
getopts::optopt("o", "output", "Output file", "output.png"),
getopts::optopt("r", "rendering", "Rend... | {
io::stderr().write_line(msg).unwrap();
os::set_exit_status(1);
} | identifier_body |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | } else if "core-graphics" == backend_str.as_slice() {
CoreGraphicsBackend
} else if "core-graphics-accelerated" == backend_str.as_slice() {
CoreGraphicsAcceleratedBackend
} else if "cairo" == backend_str.as_slice() {
CairoBackend
... | Some(backend_str) => {
if "direct2d" == backend_str.as_slice() {
Direct2DBackend | random_line_split |
utils.rs | use std::ptr;
use std::io;
use std::fs::{create_dir, remove_dir_all, read_dir, remove_file, remove_dir};
use std::fs::{metadata};
use std::path::{Path, PathBuf};
use std::path::Component::Normal;
use std::io::Error as IoError;
use std::io::ErrorKind::{AlreadyExists, NotFound};
use std::ffi::CString;
use std::env::curre... |
}
| {
if self.0 {
unsafe { setfsuid(0) };
if unsafe { setfsuid(0) } != 0 {
let err = io::Error::last_os_error();
error!("Can't return fs uid back to zero: {}. Aborting.", err);
panic!("Can't return fs uid back to zero: {}. Aborting.", err);
... | identifier_body |
utils.rs | use std::ptr;
use std::io;
use std::fs::{create_dir, remove_dir_all, read_dir, remove_file, remove_dir};
use std::fs::{metadata};
use std::path::{Path, PathBuf};
use std::path::Component::Normal;
use std::io::Error as IoError;
use std::io::ErrorKind::{AlreadyExists, NotFound};
use std::ffi::CString;
use std::env::curre... | (uid: u32, gid: u32) -> FsUidGuard {
if uid!= 0 || gid!= 0 {
unsafe { setfsuid(uid) };
if unsafe { setfsuid(uid) }!= uid as i32 {
error!("Can't set fs gid to open socket: {}. Ignoring.",
io::Error::last_os_error());
}
unsafe { s... | set | identifier_name |
utils.rs | use std::ptr;
use std::io;
use std::fs::{create_dir, remove_dir_all, read_dir, remove_file, remove_dir};
use std::fs::{metadata};
use std::path::{Path, PathBuf};
use std::path::Component::Normal;
use std::io::Error as IoError;
use std::io::ErrorKind::{AlreadyExists, NotFound};
use std::ffi::CString;
use std::env::curre... |
pub fn clean_dir(dir: &Path, remove_dir_itself: bool) -> Result<(), String> {
if let Err(e) = metadata(dir) {
if e.kind() == NotFound {
return Ok(());
} else {
return Err(format!("Can't stat dir {:?}: {}", dir, e));
}
}
// We temporarily change root, so that ... | return Err(format!(concat!("Can't create dir {:?}: {} ",
"path already exists but not a directory"), dir, e));
}
}
} | random_line_split |
page.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::cell::DOMRefCell;
use dom::bindings::js::{JS, Root};
use dom::document::Document;
use dom::wind... |
}
/// Information for one frame in the browsing context.
#[derive(JSTraceable, HeapSizeOf)]
#[must_root]
pub struct Frame {
/// The document for this frame.
pub document: JS<Document>,
/// The window object for this frame.
pub window: JS<Window>,
}
| {
*self.frame.borrow_mut() = frame;
} | identifier_body |
page.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::cell::DOMRefCell;
use dom::bindings::js::{JS, Root};
use dom::document::Document;
use dom::wind... | (&self) -> Root<Window> {
Root::from_ref(&*self.frame.borrow().as_ref().unwrap().window)
}
pub fn document(&self) -> Root<Document> {
Root::from_ref(&*self.frame.borrow().as_ref().unwrap().document)
}
// must handle root case separately
pub fn remove(&self, id: PipelineId) -> Optio... | window | identifier_name |
page.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::cell::DOMRefCell;
use dom::bindings::js::{JS, Root};
use dom::document::Document;
use dom::wind... |
popped
}
}
impl Page {
pub fn set_reflow_status(&self, status: bool) -> bool {
let old = self.needs_reflow.get();
self.needs_reflow.set(status);
old
}
#[allow(unrooted_must_root)]
pub fn set_frame(&self, frame: Option<Frame>) {
*self.frame.borrow_mut() = fr... | {
self.stack.extend(page.children.borrow().iter().cloned());
} | conditional_block |
page.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::cell::DOMRefCell;
use dom::bindings::js::{JS, Root};
use dom::document::Document;
use dom::wind... | pub window: JS<Window>,
} | /// The document for this frame.
pub document: JS<Document>,
/// The window object for this frame. | random_line_split |
circular_counter.rs | fn | (a: &Vec<i32>) -> Vec<i32> {
let mut a2 = a.clone();
let mut i = 0;
let mut b = vec![];
while a2.len() > 0 {
i = (i + 2) % a2.len();
b.push(a2[i]);
a2.remove(i);
}
b
}
fn main() {
let a = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let b = circular_counter(&a);
println!... | circular_counter | identifier_name |
circular_counter.rs | fn circular_counter(a: &Vec<i32>) -> Vec<i32> |
fn main() {
let a = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let b = circular_counter(&a);
println!("{:?}", b);
}
#[test]
fn test() {
assert_eq!(
circular_counter(
&vec![1, 2, 3, 4, 5, 6, 7, 8, 9]
),
vec![3, 6, 9, 4, 8, 5, 2, 7, 1]
);
}
| {
let mut a2 = a.clone();
let mut i = 0;
let mut b = vec![];
while a2.len() > 0 {
i = (i + 2) % a2.len();
b.push(a2[i]);
a2.remove(i);
}
b
} | identifier_body |
circular_counter.rs | fn circular_counter(a: &Vec<i32>) -> Vec<i32> {
let mut a2 = a.clone();
let mut i = 0;
let mut b = vec![];
while a2.len() > 0 {
i = (i + 2) % a2.len();
b.push(a2[i]);
a2.remove(i);
}
b
}
fn main() {
let a = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let b = circular_counte... | } | ); | random_line_split |
issue-51191.rs | // Copyright 2016 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 immref(&self) {
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not declared as mutable [E0596]
//~^^ ERROR cannot borrow data in a `&` reference as mutable [E0596]
}
fn mtblref(&mut self) {
(&mut self).bar();
//~^ ERROR cannot borro... | //~^ ERROR cannot borrow `self` as mutable, as it is not declared as mutable [E0596]
}
fn mtbl(mut self) {
(&mut self).bar(); | random_line_split |
issue-51191.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (self) {
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not declared as mutable [E0596]
}
fn mtbl(mut self) {
(&mut self).bar();
}
fn immref(&self) {
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not declared as... | imm | identifier_name |
issue-51191.rs | // Copyright 2016 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 imm(self) {
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not declared as mutable [E0596]
}
fn mtbl(mut self) {
(&mut self).bar();
}
fn immref(&self) {
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not... | {
//~^ WARN function cannot return without recursing
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not declared as mutable [E0596]
} | identifier_body |
lib.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | /// The arguments to execute.
///
/// The first argument should be an absolute or relative path to the binary to execute.
///
/// No PATH lookup will be performed unless a PATH environment variable is specified.
///
/// No shell expansion will take place.
///
pub argv: Vec<String>,
///
/// The env... | random_line_split | |
lib.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | (mut self) -> Self {
self.execution_attempts = vec![];
self
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ExecutionStats {
uploaded_bytes: usize,
uploaded_file_count: usize,
upload: Duration,
remote_queue: Option<Duration>,
remote_input_fetch: Option<Duration>,
remote_execu... | without_execution_attempts | identifier_name |
main.rs | extern crate byteorder;
use std::collections::HashMap;
use std::io::Write;
use byteorder::{LittleEndian, WriteBytesExt};
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct Frac(u64, u64);
type Memory = HashMap<Frac, f64>;
fn simplify(Frac(a, b): Frac) -> Frac {
fn gcd(x: u64, y: u64) -> u64 {
if y == 0... | (base_note: f64, fractions: &[Frac], step: u64) -> f64 {
let mut sum = 0_f64;
for &Frac(a, b) in fractions {
let freq = (base_note / (b as f64)) * (a as f64);
sum += sine_wave(freq, step);
}
sum / (fractions.len() as f64)
}
fn linear_envelope(sample: f64, duration: u64, progress: u64) ... | sine_waves | identifier_name |
main.rs | extern crate byteorder;
use std::collections::HashMap;
use std::io::Write;
use byteorder::{LittleEndian, WriteBytesExt};
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct Frac(u64, u64);
type Memory = HashMap<Frac, f64>;
fn simplify(Frac(a, b): Frac) -> Frac {
fn gcd(x: u64, y: u64) -> u64 {
if y == 0... |
fn remember(note_set: &[Frac], memory: &mut Memory) {
let increase = 0.1_f64;
for note in note_set {
let val = match memory.get(note) {
Some(v) => v + increase,
None => increase,
};
memory.insert(note.clone(), val);
}
}
/// step to a set of notes that minim... | {
for (n, val) in memory.iter_mut() {
*val *= 0.75;
}
} | identifier_body |
main.rs | extern crate byteorder;
use std::collections::HashMap;
use std::io::Write;
use byteorder::{LittleEndian, WriteBytesExt};
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct Frac(u64, u64);
type Memory = HashMap<Frac, f64>;
fn simplify(Frac(a, b): Frac) -> Frac {
fn gcd(x: u64, y: u64) -> u64 {
if y == 0... | sum / (fractions.len() as f64)
}
fn linear_envelope(sample: f64, duration: u64, progress: u64) -> f64 {
sample * (progress as f64) / (duration as f64)
}
fn output_pcm() {
let mut notes = vec![Frac(1, 2), Frac(1, 1), Frac(1, 3), Frac(1, 5), Frac(1, 7)];
let mut memory = Memory::new();
let mut j=0;... | random_line_split | |
main.rs | extern crate byteorder;
use std::collections::HashMap;
use std::io::Write;
use byteorder::{LittleEndian, WriteBytesExt};
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct Frac(u64, u64);
type Memory = HashMap<Frac, f64>;
fn simplify(Frac(a, b): Frac) -> Frac {
fn gcd(x: u64, y: u64) -> u64 {
if y == 0... |
}
}
}
best
}
type PCM_Sample = i16;
static PCM_HZ: u64 = 44100_u64;
static STEPS_PER_SEC: u64 = 4;
static BASE_NOTE: f64 = 250_f64;
type Endianness = LittleEndian;
fn sine_wave(freq: f64, step: u64) -> f64 {
(2.0*std::f64::consts::PI*(step as f64)*freq/(PCM_HZ as f64)).sin()
}
fn si... | {
best = note_set2;
best_score = score;
} | conditional_block |
group.rs | /*!
Group Icons and Cursors.
References:
* http://msdn.microsoft.com/en-us/library/ms997538.aspx
* https://devblogs.microsoft.com/oldnewthing/20120720-00/?p=7083
* https://github.com/MathewSachin/NIco/wiki/Ico,-Cur-and-PE-Formats
# Examples
The following example prints all group icon resource names which contain a ... |
/// Reassemble the file.
#[cfg(feature = "std")]
pub fn write(&self, dest: &mut dyn io::Write) -> io::Result<()> {
// Start by appending the header
dest.write(self.image.as_bytes())?;
// Write all the icon entries
let entries = self.entries();
let mut image_offset = (6 + entries.len() * 16) as u32;
for ... | {
self.resources.root()?
.get_dir(self.ty().into())?
.get_dir(id.into())?
.first_data()?
.bytes().map_err(FindError::Pe)
} | identifier_body |
group.rs | /*!
Group Icons and Cursors.
References:
* http://msdn.microsoft.com/en-us/library/ms997538.aspx
* https://devblogs.microsoft.com/oldnewthing/20120720-00/?p=7083
* https://github.com/MathewSachin/NIco/wiki/Ico,-Cur-and-PE-Formats
# Examples
The following example prints all group icon resource names which contain a ... | {
pub idReserved: u16,
pub idType: u16,
pub idCount: u16,
pub idEntries: [GRPICONDIRENTRY; 0],
}
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct GRPICONDIRENTRY {
pub bWidth: u8,
pub bHeight: u8,
pub bColorCount: u8,
pub bReserved: u8,
pub wPlanes: u16,
pub wBitCount: u16,
pub dwBytesInRe... | GRPICONDIR | identifier_name |
group.rs | /*!
Group Icons and Cursors.
References:
* http://msdn.microsoft.com/en-us/library/ms997538.aspx
* https://devblogs.microsoft.com/oldnewthing/20120720-00/?p=7083
* https://github.com/MathewSachin/NIco/wiki/Ico,-Cur-and-PE-Formats |
```
// Aqcuire the resources of a Portable Executable file
let resources: pelite::resources::Resources;
# fn example(resources: pelite::resources::Resources<'_>) {
// Iterate over the group icons in the resources and throw away any invalid results
// If the resources contain no group icons the iterator is empty
for (... |
# Examples
The following example prints all group icon resource names which contain a PNG image. | random_line_split |
exhaustive_vec_permutations.rs | use itertools::Itertools;
use malachite_base::vecs::exhaustive_vec_permutations;
fn exhaustive_vec_permutations_helper(cs: &str, out: &[&str]) {
let cs = cs.chars().collect_vec();
let css: Vec<String> = exhaustive_vec_permutations(cs)
.map(|ds| ds.into_iter().collect())
.collect();
assert_eq!... | "24135", "24153", "24315", "24351", "24513", "24531", "25134", "25143", "25314",
"25341", "25413", "25431", "31245", "31254", "31425", "31452", "31524", "31542",
"32145", "32154", "32415", "32451", "32514", "32541", "34125", "34152", "34215",
"34251", "34512", "34521", "3... | {
exhaustive_vec_permutations_helper("", &[""]);
exhaustive_vec_permutations_helper("1", &["1"]);
exhaustive_vec_permutations_helper("12", &["12", "21"]);
exhaustive_vec_permutations_helper("123", &["123", "132", "213", "231", "312", "321"]);
exhaustive_vec_permutations_helper(
"1234",
... | identifier_body |
exhaustive_vec_permutations.rs | use itertools::Itertools;
use malachite_base::vecs::exhaustive_vec_permutations;
fn | (cs: &str, out: &[&str]) {
let cs = cs.chars().collect_vec();
let css: Vec<String> = exhaustive_vec_permutations(cs)
.map(|ds| ds.into_iter().collect())
.collect();
assert_eq!(css.iter().map(String::as_str).collect_vec().as_slice(), out);
}
#[test]
fn test_exhaustive_vec_permutations() {
... | exhaustive_vec_permutations_helper | identifier_name |
exhaustive_vec_permutations.rs | use itertools::Itertools;
use malachite_base::vecs::exhaustive_vec_permutations;
fn exhaustive_vec_permutations_helper(cs: &str, out: &[&str]) {
let cs = cs.chars().collect_vec();
let css: Vec<String> = exhaustive_vec_permutations(cs)
.map(|ds| ds.into_iter().collect())
.collect();
assert_eq!... | "abcd",
&[
"abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac",
"bdca", "cabd", "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca",
"dcab", "dcba",
],
);
} | "53124", "53142", "53214", "53241", "53412", "53421", "54123", "54132", "54213",
"54231", "54312", "54321",
],
);
exhaustive_vec_permutations_helper( | random_line_split |
traits-assoc-type-in-supertrait.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <F:Foo<Key=i32>>(f: F) -> i32 {
f.fold(0, |a,b| a + b)
}
fn main() {
let x = sum_foo(vec![11, 10, 1].into_iter());
assert_eq!(x, 22);
}
| sum_foo | identifier_name |
traits-assoc-type-in-supertrait.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = sum_foo(vec![11, 10, 1].into_iter());
assert_eq!(x, 22);
} | identifier_body | |
traits-assoc-type-in-supertrait.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub trait Foo: Iterator<Item=<Self as Foo>::Key> {
type Key;
}
impl Foo for IntoIter<i32> {
type Key = i32;
}
fn sum_foo<F:Foo<Key=i32>>(f: F) -> i32 {
f.fold(0, |a,b| a + b)
}
fn main() {
let x = sum_foo(vec![11, 10, 1].into_iter());
assert_eq!(x, 22);
} | random_line_split | |
panic.rs | //! Intrinsics for panic handling
use interrupt;
#[lang = "eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality() {}
/// Required to handle panics
#[lang = "panic_fmt"]
#[no_mangle]
pub extern "C" fn rust_begin_unwind(fmt: ::core::fmt::Arguments, file: &str, line: u32) ->! {
println!("PANIC: {}", ... | () ->! {
loop {
unsafe { interrupt::halt(); }
}
}
| _Unwind_Resume | identifier_name |
panic.rs | //! Intrinsics for panic handling
use interrupt;
#[lang = "eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality() {}
/// Required to handle panics
#[lang = "panic_fmt"]
#[no_mangle]
pub extern "C" fn rust_begin_unwind(fmt: ::core::fmt::Arguments, file: &str, line: u32) ->! |
#[lang = "oom"]
#[no_mangle]
pub extern fn rust_oom() ->! {
panic!("kernel memory allocation failed");
}
#[allow(non_snake_case)]
#[no_mangle]
/// Required to handle panics
pub extern "C" fn _Unwind_Resume() ->! {
loop {
unsafe { interrupt::halt(); }
}
}
| {
println!("PANIC: {}", fmt);
println!("FILE: {}", file);
println!("LINE: {}", line);
unsafe { interrupt::stack_trace(); }
println!("HALT");
loop {
unsafe { interrupt::halt(); }
}
} | identifier_body |
panic.rs | //! Intrinsics for panic handling
use interrupt;
#[lang = "eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality() {}
/// Required to handle panics | #[lang = "panic_fmt"]
#[no_mangle]
pub extern "C" fn rust_begin_unwind(fmt: ::core::fmt::Arguments, file: &str, line: u32) ->! {
println!("PANIC: {}", fmt);
println!("FILE: {}", file);
println!("LINE: {}", line);
unsafe { interrupt::stack_trace(); }
println!("HALT");
loop {
unsafe { in... | random_line_split | |
dataflow.rs | })
}
impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> {
fn has_bitset_for_nodeid(&self, n: ast::NodeId) -> bool {
assert!(n!= ast::DUMMY_NODE_ID);
self.nodeid_to_index.contains_key(&n)
}
}
impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O> {
... | cfg: &cfg::CFG,
cfgidx: CFGIndex) {
cfg.graph.each_outgoing_edge(cfgidx, |_e_idx, edge| { | random_line_split | |
dataflow.rs | }
pub trait BitwiseOperator {
/// Joins two predecessor bits together, typically either `|` or `&`
fn join(&self, succ: uint, pred: uint) -> uint;
}
/// Parameterization for the precise form of data flow that is used.
pub trait DataFlowOperator : BitwiseOperator {
/// Specifies the initial value for each ... | else {
"".to_string()
};
try!(ps.synth_comment(format!("id {}: {}{}{}", id, entry_str,
gens_str, kills_str)));
try!(pp::space(&mut ps.s));
}
Ok(())
}
}
fn build_nodeid_to_index(decl: Option<&ast::FnDecl>... | {
format!(" kill: {}", bits_to_string(kills))
} | conditional_block |
dataflow.rs | //! the entry-node in the graph.
struct Formals<'a> {
entry: CFGIndex,
index: &'a mut NodeMap<CFGIndex>,
}
let mut formals = Formals { entry: entry, index: index };
visit::walk_fn_decl(&mut formals, decl);
impl<'a, 'v> visit::Visitor<'v> for Formals<'a... | Union | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.