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 |
|---|---|---|---|---|
lib.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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs"));
}
macro_rules! reexport_computed_values {
( $( { $name: ident, $boxed: expr } )+ ) => {
/// Types for [computed values][computed].
///
/// [computed]: https://drafts.csswg.org/css-cascade/#computed
pub mod computed_valu... | pub mod gecko_properties { | random_line_split |
lib.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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | <W, T>(
dest: &mut CssWriter<W>,
list: &[T],
) -> fmt::Result
where
W: Write,
T: ToCss,
{
if list.is_empty() {
return Ok(());
}
list[0].to_css(dest)?;
for item in list.iter().skip(1) {
dest.write_str(", ")?;
item.to_css(dest)?;
}
Ok(())
}
#[cfg(feature... | serialize_comma_separated_list | identifier_name |
lib.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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... |
}
| {
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
} | identifier_body |
event_box.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! GtkEventBox — A widget used to catch events for widgets which do not have their own windo... | self) -> bool {
unsafe { to_bool(ffi::gtk_event_box_get_visible_window(GTK_EVENT_BOX(self.pointer))) }
}
}
impl_drop!(EventBox);
impl_TraitWidget!(EventBox);
impl ::ContainerTrait for EventBox {}
impl ::BinTrait for EventBox {}
| t_visible_window(& | identifier_name |
event_box.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! GtkEventBox — A widget used to catch events for widgets which do not have their own windo... | }
impl_drop!(EventBox);
impl_TraitWidget!(EventBox);
impl ::ContainerTrait for EventBox {}
impl ::BinTrait for EventBox {} | pub fn get_visible_window(&self) -> bool {
unsafe { to_bool(ffi::gtk_event_box_get_visible_window(GTK_EVENT_BOX(self.pointer))) }
} | random_line_split |
event_box.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! GtkEventBox — A widget used to catch events for widgets which do not have their own windo... | pub fn get_above_child(&self) -> bool {
unsafe { to_bool(ffi::gtk_event_box_get_above_child(GTK_EVENT_BOX(self.pointer))) }
}
pub fn set_visible_window(&self, visible_window: bool) {
unsafe {
ffi::gtk_event_box_set_visible_window(GTK_EVENT_BOX(self.pointer), to_gboolean(visible_... | unsafe {
ffi::gtk_event_box_set_above_child(GTK_EVENT_BOX(self.pointer), to_gboolean(above_child))
}
}
| identifier_body |
dpapi.rs | // Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... | pOptionalEntropy: *mut DATA_BLOB,
pvReserved: PVOID,
pPromptStruct: *mut CRYPTPROTECT_PROMPTSTRUCT,
dwFlags: DWORD,
pDataOut: *mut DATA_BLOB,
) -> BOOL;
pub fn CryptProtectDataNoUI(
pDataIn: *mut DATA_BLOB,
szDataDescr: LPCWSTR,
pOptionalEntropy: *... | pDataIn: *mut DATA_BLOB,
ppszDataDescr: *mut LPWSTR, | random_line_split |
htmltableelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers, AttrValue};
use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTML... | }
fn before_remove_attr(&self, attr: JSRef<Attr>) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("bgcolor") => self.background_color.set(None),
&atom!("border") => self.border.set(None),
... | {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("bgcolor") => {
self.background_color.set(str::parse_legacy_color(&attr.value()).ok())
}
&atom!("border") => {
//... | identifier_body |
htmltableelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers, AttrValue};
use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTML... | (&self) -> Option<u32> {
self.border.get()
}
fn get_cellspacing(&self) -> Option<u32> {
self.cellspacing.get()
}
fn get_width(&self) -> LengthOrPercentageOrAuto {
self.width.get()
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLTableElement> {
fn super_type<'b>(&'b self)... | get_border | identifier_name |
htmltableelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers, AttrValue};
use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTML... |
fn get_width(&self) -> LengthOrPercentageOrAuto {
self.width.get()
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLTableElement> {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlele... | }
fn get_cellspacing(&self) -> Option<u32> {
self.cellspacing.get()
} | random_line_split |
object-lifetime-default-from-rptr-mut.rs | // run-pass
// Test that the lifetime of the enclosing `&` is used for the object
// lifetime bound.
// pretty-expanded FIXME #23616
#![allow(dead_code)]
trait Test {
fn foo(&self) { }
}
struct SomeStruct<'a> {
t: &'a mut dyn Test,
u: &'a mut (dyn Test+'a),
}
fn a<'a>(t: &'a mut dyn Test, mut ss: SomeS... | <'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) {
ss.u = t;
}
fn c<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) {
ss.t = t;
}
fn d<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) {
ss.u = t;
}
fn main() {
}
| b | identifier_name |
object-lifetime-default-from-rptr-mut.rs | // run-pass
// Test that the lifetime of the enclosing `&` is used for the object
// lifetime bound.
// pretty-expanded FIXME #23616
#![allow(dead_code)]
| trait Test {
fn foo(&self) { }
}
struct SomeStruct<'a> {
t: &'a mut dyn Test,
u: &'a mut (dyn Test+'a),
}
fn a<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) {
ss.t = t;
}
fn b<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) {
ss.u = t;
}
fn c<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<... | random_line_split | |
object-lifetime-default-from-rptr-mut.rs | // run-pass
// Test that the lifetime of the enclosing `&` is used for the object
// lifetime bound.
// pretty-expanded FIXME #23616
#![allow(dead_code)]
trait Test {
fn foo(&self) { }
}
struct SomeStruct<'a> {
t: &'a mut dyn Test,
u: &'a mut (dyn Test+'a),
}
fn a<'a>(t: &'a mut dyn Test, mut ss: SomeS... |
fn d<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) {
ss.u = t;
}
fn main() {
}
| {
ss.t = t;
} | identifier_body |
time.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 ... | extern {
pub fn mach_absolute_time() -> u64;
pub fn mach_timebase_info(info: *mut libc::mach_timebase_info) -> libc::c_int;
}
impl SteadyTime {
pub fn now() -> SteadyTime {
SteadyTime {
t: unsafe { mach_absolute_time() },
}
}
... |
pub struct SteadyTime {
t: u64
}
| random_line_split |
time.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 ... |
}
}
}
| {
Duration::seconds(self.t.tv_sec as i64 - 1 - other.t.tv_sec as i64) +
Duration::nanoseconds(self.t.tv_nsec as i64 + NSEC_PER_SEC -
other.t.tv_nsec as i64)
} | conditional_block |
time.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 ... |
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod inner {
use libc;
use time::Duration;
use ops::Sub;
const NSEC_PER_SEC: i64 = 1_000_000_000;
pub struct SteadyTime {
t: libc::timespec,
}
// Apparently android provides this in some other library?
// Bitrig... | {
let info = info();
let diff = self.t as i64 - other.t as i64;
Duration::nanoseconds(diff * info.numer as i64 / info.denom as i64)
} | identifier_body |
time.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
t: u64
}
extern {
pub fn mach_absolute_time() -> u64;
pub fn mach_timebase_info(info: *mut libc::mach_timebase_info) -> libc::c_int;
}
impl SteadyTime {
pub fn now() -> SteadyTime {
SteadyTime {
t: unsafe { mach_absolute_time() },
... | SteadyTime | identifier_name |
keyframes_rule.rs | _properties::AnimatableLonghand;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use selectors::parser::SelectorParseError;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuar... | ///
/// This is used to know when to override the keyframe animation style.
pub declared_timing_function: bool,
}
impl KeyframesStep {
#[inline]
fn new(percentage: KeyframePercentage,
value: KeyframesStepValue,
guard: &SharedRwLockReadGuard) -> Self {
let declared_timi... | pub value: KeyframesStepValue,
/// Wether a animation-timing-function declaration exists in the list of
/// declarations. | random_line_split |
keyframes_rule.rs | ::AnimatableLonghand;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use selectors::parser::SelectorParseError;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std... | (&self) -> &[KeyframePercentage] {
&self.0
}
/// A dummy public function so we can write a unit test for this.
pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector {
KeyframeSelector(percentages)
}
/// Parse a keyframe selector from CSS input.
p... | percentages | identifier_name |
keyframes_rule.rs | ::AnimatableLonghand;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use selectors::parser::SelectorParseError;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std... |
Err(err) => {
iter.parser.declarations.clear();
let error = ContextualParseError::UnsupportedKeyframePropertyDeclaration(err.slice, err.error);
context.log_css_error(self.error_context, err.location, error);
}
}
... | {
block.extend(iter.parser.declarations.drain(), Importance::Normal);
} | conditional_block |
keyframes_rule.rs | ::AnimatableLonghand;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use selectors::parser::SelectorParseError;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std... |
}
impl KeyframePercentage {
/// Trivially constructs a new `KeyframePercentage`.
#[inline]
pub fn new(value: f32) -> KeyframePercentage {
debug_assert!(value >= 0. && value <= 1.);
KeyframePercentage(value)
}
fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<KeyframePercentag... | {
serialize_percentage(self.0, dest)
} | identifier_body |
unit_graph.rs | use std::collections::{HashMap, VecDeque, HashSet};
use nom::types::CompleteStr;
use petgraph::graph::{UnGraph, NodeIndex, DefaultIx};
use bigdecimal::BigDecimal;
use num_traits::One;
use crate::canonical::CanonicalUnit;
use crate::ast::*;
use crate::ir::ConversionRatio;
pub type UnitID = usize;
#[derive(Debug, Clo... |
/// Creates the given unit if it does not exist yet
///
/// If it does exist, this function will return an error
pub fn insert_unit(&mut self, name: UnitName<'a>, span: Span<'a>) -> Result<UnitID, DuplicateUnit<'a>> {
if self.unit_ids.contains_key(&name) {
return Err(DuplicateUnit(... | {
match self.units.get(unit) {
Some(&(ref name, _)) => name,
None => unreachable!("Looked up an ID that did not exist"),
}
} | identifier_body |
unit_graph.rs | use std::collections::{HashMap, VecDeque, HashSet};
use nom::types::CompleteStr;
use petgraph::graph::{UnGraph, NodeIndex, DefaultIx};
use bigdecimal::BigDecimal;
use num_traits::One;
use crate::canonical::CanonicalUnit;
use crate::ast::*;
use crate::ir::ConversionRatio;
pub type UnitID = usize;
#[derive(Debug, Clo... |
let node = CanonicalUnit::from(id);
let graph_id = self.conversions.add_node(node.clone());
assert!(self.graph_ids.insert(node, graph_id).is_none(),
"bug: failed to detect duplicate declaration");
Ok(id)
}
/// Adds the given conversion ratio to the graph
pub fn... | "bug: failed to detect duplicate declaration");
self.units.push((name, span)); | random_line_split |
unit_graph.rs | use std::collections::{HashMap, VecDeque, HashSet};
use nom::types::CompleteStr;
use petgraph::graph::{UnGraph, NodeIndex, DefaultIx};
use bigdecimal::BigDecimal;
use num_traits::One;
use crate::canonical::CanonicalUnit;
use crate::ast::*;
use crate::ir::ConversionRatio;
pub type UnitID = usize;
#[derive(Debug, Clo... |
else {
unreachable!();
}
}
factor
}
}
#[derive(Debug, Clone)]
pub struct UnitGraph<'a> {
unit_ids: HashMap<UnitName<'a>, UnitID>,
units: Vec<(UnitName<'a>, Span<'a>)>,
graph_ids: HashMap<CanonicalUnit, NodeIndex<DefaultIx>>,
conversions: UnG... | {
factor *= ratio.left.value / ratio.right.value;
current = ratio.left.unit;
} | conditional_block |
unit_graph.rs | use std::collections::{HashMap, VecDeque, HashSet};
use nom::types::CompleteStr;
use petgraph::graph::{UnGraph, NodeIndex, DefaultIx};
use bigdecimal::BigDecimal;
use num_traits::One;
use crate::canonical::CanonicalUnit;
use crate::ast::*;
use crate::ir::ConversionRatio;
pub type UnitID = usize;
#[derive(Debug, Clo... | {
start: CanonicalUnit,
end: CanonicalUnit,
ratio_path: Vec<ConversionRatio>,
}
impl ConversionPath {
/// Reduces the path into the factor that transforms start to end
pub fn conversion_factor(self) -> BigDecimal {
let mut factor = BigDecimal::one();
let mut current = self.start;
... | ConversionPath | identifier_name |
errors.rs | // Copyright 2016 Jonas mg
// See the 'AUTHORS' file at the top-level directory for a full list of authors.
//
// 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 s... |
}
impl fmt::Display for AsciiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
AsciiError::ControlChar(pos) => write!(f, "{} at position {}", self.description(), pos),
AsciiError::NonAscii(ch) => write!(f, "{} ({})", self.description(), ch),
}
... | {
match *self {
AsciiError::ControlChar(_) => "contain ASCII control character",
AsciiError::NonAscii(_) => "contain non US-ASCII character",
}
} | identifier_body |
errors.rs | // Copyright 2016 Jonas mg
// See the 'AUTHORS' file at the top-level directory for a full list of authors.
//
// 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 s... | (&self) -> &str {
match *self {
AsciiError::ControlChar(_) => "contain ASCII control character",
AsciiError::NonAscii(_) => "contain non US-ASCII character",
}
}
}
impl fmt::Display for AsciiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *se... | description | identifier_name |
errors.rs | // Copyright 2016 Jonas mg
// See the 'AUTHORS' file at the top-level directory for a full list of authors.
//
// 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 s... | fn cause(&self) -> Option<&error::Error> {
None
}
fn description(&self) -> &str {
match *self {
AsciiError::ControlChar(_) => "contain ASCII control character",
AsciiError::NonAscii(_) => "contain non US-ASCII character",
}
}
}
impl fmt::Display for Ascii... |
impl error::Error for AsciiError { | random_line_split |
modules.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | (io_path: &str, sync_cfg: SyncConfig, net_cfg: NetworkConfiguration, log_settings: &LogConfig) -> BootArgs {
let service_config = ServiceConfiguration {
sync: sync_cfg,
net: net_cfg,
io_path: io_path.to_owned(),
};
// initialisation payload is passed via stdin
let service_payload = serialize(&service_config)... | sync_arguments | identifier_name |
modules.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | if let Some(ref file) = log_settings.file {
cli_args.push("--log-file".to_owned());
cli_args.push(file.to_owned());
}
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
... | random_line_split | |
modules.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | cli_args.push(file.to_owned());
}
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
_client: Arc<BlockChainClient>,
_snapshot_service: Arc<SnapshotService>,
_provide... | {
let service_config = ServiceConfiguration {
sync: sync_cfg,
net: net_cfg,
io_path: io_path.to_owned(),
};
// initialisation payload is passed via stdin
let service_payload = serialize(&service_config).expect("Any binary-derived struct is serializable by definition");
// client service url and logging set... | identifier_body |
modules.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
if let Some(ref file) = log_settings.file {
cli_args.push("--log-file".to_owned());
cli_args.push(file.to_owned());
}
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
... | {
cli_args.push("-l".to_owned());
cli_args.push(mode.to_owned());
} | conditional_block |
memory.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... |
}
| {
trace!("Successfully called stat() for: {:?}", filename);
Ok(())
} | conditional_block |
memory.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | unsafe { libc::close(fd) };
let custom_error = Error::new(ErrorKind::Other, "Maximum allowed file size for prefetching exceeded!");
Err(custom_error)
} else {
// Manually fault in all pages
let result = unsafe { libc::readahead(fd, 0, stat.st_size as usize) };
if re... | {
trace!("Caching file: {:?}", filename);
let file = File::open(filename)?;
let fd = file.into_raw_fd();
// We are interested in file size
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
unsafe {
libc::fstat(fd, &mut stat);
};
if stat.st_mode & libc::S_ISUID == libc:... | identifier_body |
memory.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called posix_fadvise() for: {:?}", filename);
let result = unsafe {
libc::madvise(
addr as *mut libc::c_void,
... | random_line_split | |
memory.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | {
pub filename: PathBuf,
pub addr: usize,
pub len: usize,
}
impl MemoryMapping {
pub fn new(filename: &Path, addr: usize, len: usize) -> MemoryMapping {
MemoryMapping {
filename: PathBuf::from(filename),
addr,
len,
}
}
}
#[cfg(target_pointer_wid... | MemoryMapping | identifier_name |
dropck_tarena_cycle_checked.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 ... | (&self) -> usize {
match self.get() {
None => 1,
Some(c) => c.id.count(),
}
}
}
impl<'a> C<'a> {
fn new() -> C<'a> {
C { id: Id::new(), v: Vec::new() }
}
}
fn f<'a>(arena: &'a TypedArena<C<'a>>) {
let c1 = arena.alloc(C::new());
let c2 = arena.alloc(... | count | identifier_name |
dropck_tarena_cycle_checked.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 c = s::next_count();
println!("building Id {}", c);
Id { orig_count: c, count: c }
}
pub fn count(&self) -> usize {
println!("Id::count on {} returns {}", self.orig_count, self.count);
self.count
}
}
impl Drop for Id {
... | impl Id {
pub fn new() -> Id { | random_line_split |
tessellation.rs | #[macro_use]
extern crate glium;
use glium::Surface;
use glium::glutin;
use glium::index::PrimitiveType;
mod support;
fn main() {
use glium::DisplayBuild;
// building the display, ie. the main object
let display = glutin::WindowBuilder::new()
.build_glium()
.unwrap();
// building the ... |
glium::VertexBuffer::new(&display,
vec![
Vertex { position: [-0.5, -0.5] },
Vertex { position: [ 0.0, 0.5] },
Vertex { position: [ 0.5, -0.5] },
]
)
};
// building the index buffer
let index_buffer = glium::IndexBuff... | struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position); | random_line_split |
tessellation.rs | #[macro_use]
extern crate glium;
use glium::Surface;
use glium::glutin;
use glium::index::PrimitiveType;
mod support;
fn main() {
use glium::DisplayBuild;
// building the display, ie. the main object
let display = glutin::WindowBuilder::new()
.build_glium()
.unwrap();
// building the ... | ,
_ => ()
}
}
support::Action::Continue
});
}
| {
if tess_level >= 2 {
tess_level -= 1;
println!("New tessellation level: {}", tess_level);
}
} | conditional_block |
tessellation.rs | #[macro_use]
extern crate glium;
use glium::Surface;
use glium::glutin;
use glium::index::PrimitiveType;
mod support;
fn | () {
use glium::DisplayBuild;
// building the display, ie. the main object
let display = glutin::WindowBuilder::new()
.build_glium()
.unwrap();
// building the vertex buffer, which contains all the vertices that we will draw
let vertex_buffer = {
#[derive(Copy, Clone)]
... | main | identifier_name |
utils.rs | extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice; |
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-access-numeric-constants-using-the-float-trait
pub trait Castd {
fn d(self: &Self) -> f64;
}
impl Castd for f32 {
fn d(self: &Self) ->... | use self::num::Float;
// use std::ops;
use std::f32;
use std::f64; | random_line_split |
utils.rs | extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice;
use self::num::Float;
// use std::ops;
use std::f32;
use std::f64;
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-acce... |
}
self
}
}
// **********************************************
// pub fn sinc2(y: &mut f64) -> &mut f64 {
// if *y!= 0f64 {
// *y = (*y*f64::consts::PI).sin()/(*y*f64::pi());
// } else {
// *y = 1f64;
// }
// y
// }
//
// pub fn sinc(y: &mut [f64]) -> &mut [f64] {
... | {
*yi = 1f64;
} | conditional_block |
utils.rs | extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice;
use self::num::Float;
// use std::ops;
use std::f32;
use std::f64;
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-acce... |
}
pub trait FloatConst {
fn pi() -> Self;
}
impl FloatConst for f32 {
fn pi() -> Self { f32::consts::PI }
}
impl FloatConst for f64 {
fn pi() -> Self { f64::consts::PI }
}
pub fn linspace_vec<'a, T: 'a>(start: T, stop: T, len: usize) ->
Vec<T>
where T: Float {
let zero: T = T::zero();
let... | {*self as f64} | identifier_body |
utils.rs | extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice;
use self::num::Float;
// use std::ops;
use std::f32;
use std::f64;
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-acce... | (self) -> Self {
for yi in (*self).iter_mut() {
if *yi!= 0f64 {
*yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
} else {
*yi = 1f64;
}
}
self
}
}
// **********************************************
// pub fn sinc2... | sinc | identifier_name |
p052.rs | //! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 1... |
problem!("142857", solve);
| {
compute().to_string()
} | identifier_body |
p052.rs | //! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 1... | return n
}
}
fn solve() -> String {
compute().to_string()
}
problem!("142857", solve); | if ds != (n * 6).into_digit_histogram() { continue }
| random_line_split |
p052.rs | //! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 1... | () -> String {
compute().to_string()
}
problem!("142857", solve);
| solve | identifier_name |
p052.rs | //! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 1... |
if ds!= (n * 5).into_digit_histogram() { continue }
if ds!= (n * 6).into_digit_histogram() { continue }
return n
}
}
fn solve() -> String {
compute().to_string()
}
problem!("142857", solve);
| { continue } | conditional_block |
cdn.rs | use std::fs;
use std::io;
use std::io::{BufRead, Read, Write};
use std::path;
use hyper;
use resource_loaders;
pub struct Loader {
prefix: String,
cache_dir: String,
client: hyper::Client
}
impl Loader {
pub fn new(prefix: &str, cache_dir: &str) -> Loader {
fs::create_dir_all(cache_dir).unwrap();
... | let data = load_from_stream(&mut response);
let file = self.cache_dir.clone() + path;
fs::create_dir_all(path::Path::new(file.as_str()).parent().unwrap()).unwrap();
let mut f = fs::File::create(file).unwrap();
write_to_stream(&mut f, &mime, &data);
return Some((mime, data));
}
}
impl res... | {
let url = self.prefix.clone() + path;
let mut response = match self.client.get(&url).send() {
Ok(r) => r, _ => return None
};
if response.status != hyper::status::StatusCode::Ok {
return None;
}
let mime = resource_loaders::path_to_mime(path).map(|x| x.to_owned()).unwrap_or_else... | identifier_body |
cdn.rs | use std::fs;
use std::io;
use std::io::{BufRead, Read, Write};
use std::path;
use hyper;
use resource_loaders;
pub struct Loader {
prefix: String,
cache_dir: String,
client: hyper::Client
}
impl Loader {
pub fn new(prefix: &str, cache_dir: &str) -> Loader {
fs::create_dir_all(cache_dir).unwrap();
... |
let mut f = match fs::File::open(file) {
Ok(f) => io::BufReader::new(f), _ => return None
};
let mut mime = String::new();
f.read_line(&mut mime).unwrap();
return Some((mime.trim().to_owned(), load_from_stream(&mut f)));
}
fn load_from_cdn(&self, path: &str) -> Option<(String, Vec<u8>)... | fn load_from_cache(&self, path: &str) -> Option<(String, Vec<u8>)> {
let file = self.cache_dir.clone() + path; | random_line_split |
cdn.rs | use std::fs;
use std::io;
use std::io::{BufRead, Read, Write};
use std::path;
use hyper;
use resource_loaders;
pub struct Loader {
prefix: String,
cache_dir: String,
client: hyper::Client
}
impl Loader {
pub fn new(prefix: &str, cache_dir: &str) -> Loader {
fs::create_dir_all(cache_dir).unwrap();
... | (write: &mut Write, mime: &String, data: &Vec<u8>) {
write.write_all(format!("{}\n", mime).as_bytes()).unwrap();
write.write_all(data.as_slice()).unwrap();
}
| write_to_stream | identifier_name |
jstraceable.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 syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable... | else {
cx.span_err(sp, "#[dom_struct] applied to something other than a struct");
anno
}
}
/// Provides the hook to expand `#[derive(JSTraceable)]` into an implementation of `JSTraceable`
///
/// The expansion basically calls `trace()` on all of the fields of the struct/enum, erroring if they do n... | {
let mut item2 = (*item).clone();
item2.attrs.push(quote_attr!(cx, #[must_root]));
item2.attrs.push(quote_attr!(cx, #[privatize]));
item2.attrs.push(quote_attr!(cx, #[derive(JSTraceable)]));
// The following attributes are only for internal usage
item2.attrs.push(quote_... | conditional_block |
jstraceable.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 syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable... |
/// Provides the hook to expand `#[derive(JSTraceable)]` into an implementation of `JSTraceable`
///
/// The expansion basically calls `trace()` on all of the fields of the struct/enum, erroring if they do not
/// implement the method.
pub fn expand_jstraceable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &A... | {
if let Annotatable::Item(item) = anno {
let mut item2 = (*item).clone();
item2.attrs.push(quote_attr!(cx, #[must_root]));
item2.attrs.push(quote_attr!(cx, #[privatize]));
item2.attrs.push(quote_attr!(cx, #[derive(JSTraceable)]));
// The following attributes are only for in... | identifier_body |
jstraceable.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 syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable... |
for &FieldInfo { ref self_, span,.. } in fields {
stmts.push(call_trace(span, self_.clone()));
}
cx.expr_block(cx.block(trait_span, stmts, None))
} | Struct(ref fs) | EnumMatching(_, _, ref fs) => fs,
_ => cx.span_bug(trait_span, "impossible substructure in `jstraceable`")
}; | random_line_split |
jstraceable.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 syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable... | (cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable,
push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: ty::Path::new(vec!("dom","bindings","trace","JSTraceable")),
additional_bounds: Vec::ne... | expand_jstraceable | identifier_name |
signus.rs | use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn create_and_store_my_did(seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_s... |
did::key_for_local_did(get_wallet_handle(), did)
.wait()
.map_err(VcxError::from)
}
| {
return Ok(::utils::constants::VERKEY.to_string());
} | conditional_block |
signus.rs | use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn create_and_store_my_did(seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_s... | did::create_and_store_my_did(get_wallet_handle(), &my_did_json.to_string())
.wait()
.map_err(VcxError::from)
}
pub fn get_local_verkey(did: &str) -> VcxResult<String> {
if settings::indy_mocks_enabled() {
return Ok(::utils::constants::VERKEY.to_string());
}
did::key_for_local_did... | random_line_split | |
signus.rs | use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn | (seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_string(), ::utils::constants::VERKEY.to_string()));
}
let my_did_json = json!({"seed": seed, "method_name": method_name});
did::create_and_... | create_and_store_my_did | identifier_name |
signus.rs | use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn create_and_store_my_did(seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_s... | {
if settings::indy_mocks_enabled() {
return Ok(::utils::constants::VERKEY.to_string());
}
did::key_for_local_did(get_wallet_handle(), did)
.wait()
.map_err(VcxError::from)
} | identifier_body | |
test_common.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... |
macro_rules! test {
($name: expr, $skip: expr) => {
::json_tests::test_common::run_test_path(::std::path::Path::new(concat!("res/ethereum/tests/", $name)), &$skip, do_json_test);
}
}
#[macro_export]
macro_rules! declare_test {
(skip => $arr: expr, $id: ident, $name: expr) => {
#[test]
#[allow(non_snake_case... | {
let mut data = Vec::new();
let mut file = File::open(&path).expect("Error opening test file");
file.read_to_end(&mut data).expect("Error reading test file");
let results = runner(&data);
let empty: [String; 0] = [];
assert_eq!(results, empty);
} | identifier_body |
test_common.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... | }) {
run_test_path(&p, skip, runner)
}
} else {
let mut path = p.to_path_buf();
path.set_extension("json");
run_test_file(&path, runner)
}
}
pub fn run_test_file(path: &Path, runner: fn (json_data: &[u8]) -> Vec<String>) {
let mut data = Vec::new();
let mut file = File::open(&path).expect("Error opening... | {
Some(e.path())
} | conditional_block |
test_common.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... | }
} | random_line_split | |
test_common.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... | (path: &Path, runner: fn (json_data: &[u8]) -> Vec<String>) {
let mut data = Vec::new();
let mut file = File::open(&path).expect("Error opening test file");
file.read_to_end(&mut data).expect("Error reading test file");
let results = runner(&data);
let empty: [String; 0] = [];
assert_eq!(results, empty);
}
macro... | run_test_file | identifier_name |
extern-types-pointer-cast.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert_eq!((MAGIC as *const Bar<A>) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<Bar<A>>) as usize, MAGIC);
} | fn main() {
assert_eq!((MAGIC as *const A) as usize, MAGIC);
assert_eq!((MAGIC as *const Foo) as usize, MAGIC); | random_line_split |
extern-types-pointer-cast.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
assert_eq!((MAGIC as *const A) as usize, MAGIC);
assert_eq!((MAGIC as *const Foo) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<A>) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<Bar<A>>) as usize, MAGIC);
} | identifier_body | |
extern-types-pointer-cast.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert_eq!((MAGIC as *const A) as usize, MAGIC);
assert_eq!((MAGIC as *const Foo) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<A>) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<Bar<A>>) as usize, MAGIC);
}
| main | identifier_name |
num.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `Finite<T>` struct.
use core::nonzero::Zeroable;
use num::Float;
use std::ops::Deref;
/// Encapsulates t... | (value: T) -> Option<Finite<T>> {
if value.is_finite() {
Some(Finite(value))
} else {
None
}
}
/// Create a new `Finite<T: Float>`.
#[inline]
pub fn wrap(value: T) -> Finite<T> {
assert!(value.is_finite(), "Finite<T> doesn't encapsulate unrestrict... | new | identifier_name |
num.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `Finite<T>` struct.
use core::nonzero::Zeroable;
use num::Float;
use std::ops::Deref;
/// Encapsulates t... | type Target = T;
fn deref(&self) -> &T {
let &Finite(ref value) = self;
value
}
} |
impl<T: Float> Deref for Finite<T> { | random_line_split |
num.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `Finite<T>` struct.
use core::nonzero::Zeroable;
use num::Float;
use std::ops::Deref;
/// Encapsulates t... | else {
None
}
}
/// Create a new `Finite<T: Float>`.
#[inline]
pub fn wrap(value: T) -> Finite<T> {
assert!(value.is_finite(), "Finite<T> doesn't encapsulate unrestricted value.");
Finite(value)
}
}
impl<T: Float> Deref for Finite<T> {
type Target = T;
... | {
Some(Finite(value))
} | conditional_block |
jupyter_message.rs | // Copyright 2020 The Evcxr Authors.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | header["msg_type"] = JsonValue::String(msg_type.to_owned());
header["username"] = JsonValue::String("kernel".to_owned());
header["msg_id"] = JsonValue::String(Uuid::new_v4().to_string());
header["date"] = JsonValue::String(Utc::now().to_rfc3339());
JupyterMessage {
z... |
// Creates a new child message of this message. ZMQ identities are not transferred.
pub(crate) fn new_message(&self, msg_type: &str) -> JupyterMessage {
let mut header = self.header.clone(); | random_line_split |
jupyter_message.rs | // Copyright 2020 The Evcxr Authors.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
fn from_raw_message(raw_message: RawMessage) -> Result<JupyterMessage> {
fn message_to_json(message: &[u8]) -> Result<JsonValue> {
Ok(json::parse(std::str::from_utf8(message)?)?)
}
if raw_message.jparts.len() < 4 {
bail!("Insufficient message parts {}", raw_message... | {
Self::from_raw_message(RawMessage::read(connection)?)
} | identifier_body |
jupyter_message.rs | // Copyright 2020 The Evcxr Authors.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | else {
String::new()
};
let mut parts: Vec<&[u8]> = Vec::new();
for part in &self.zmq_identities {
parts.push(part);
}
parts.push(DELIMITER);
parts.push(hmac.as_bytes());
for part in &self.jparts {
parts.push(part);
}
... | {
let mut mac = mac_template.clone();
self.digest(&mut mac);
hex::encode(mac.finalize().into_bytes().as_slice())
} | conditional_block |
jupyter_message.rs | // Copyright 2020 The Evcxr Authors.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | (connection: &Connection) -> Result<RawMessage> {
Self::from_multipart(connection.socket.recv_multipart(0)?, connection)
}
pub(crate) fn from_multipart(
mut multipart: Vec<Vec<u8>>,
connection: &Connection,
) -> Result<RawMessage> {
let delimiter_index = multipart
... | read | identifier_name |
json_port.rs | // see json_port.erl
extern crate erl_ext;
extern crate rustc_serialize;
extern crate num;
extern crate byteorder;
// use std::num::ToPrimitive;
use std::io;
use std::io::Write;
use num::bigint::ToBigInt;
use num::traits::FromPrimitive;
use num::traits::ToPrimitive;
use rustc_serialize::json::{self, Json};
use byteo... | try!(encoder.encode_term(response));
try!(encoder.flush());
}
// response packet size
let out_packet_size = wrtr.len() as u16;
try!(w.write_u16::<BigEndian>(out_packet_size));
// response term itself
try!(w.write_all... | {
// encode response term
let mut encoder = erl_ext::Encoder::new(&mut wrtr,
true, true, true);
try!(encoder.write_prelude()); | random_line_split |
json_port.rs | // see json_port.erl
extern crate erl_ext;
extern crate rustc_serialize;
extern crate num;
extern crate byteorder;
// use std::num::ToPrimitive;
use std::io;
use std::io::Write;
use num::bigint::ToBigInt;
use num::traits::FromPrimitive;
use num::traits::ToPrimitive;
use rustc_serialize::json::{self, Json};
use byteo... |
fn read_write_loop<R: io::Read, W: io::Write>(mut r: R, mut w: W) -> Result<(), Error> {
loop {
// {packet, 2}
let _in_packet_size = r.read_u16::<BigEndian>();
{
let mut decoder = erl_ext::Decoder::new(&mut r);
assert!(true == try!(decoder.read_prelude()));
... | {
let in_f = io::stdin();
let out_f = io::stdout();
match read_write_loop(in_f, out_f) {
Err(Error::ByteorderUnexpectedEOF) => (), // port was closed
Err(ref err) =>
panic!("Error: '{}'", err),
Ok(()) => () // unreachable in this example
};
} | identifier_body |
json_port.rs | // see json_port.erl
extern crate erl_ext;
extern crate rustc_serialize;
extern crate num;
extern crate byteorder;
// use std::num::ToPrimitive;
use std::io;
use std::io::Write;
use num::bigint::ToBigInt;
use num::traits::FromPrimitive;
use num::traits::ToPrimitive;
use rustc_serialize::json::{self, Json};
use byteo... | (json_bytes: Vec<u8>) -> erl_ext::Eterm {
// Vec<u8> to utf-8 String
let json_string = match String::from_utf8(json_bytes) {
Ok(s) => s,
Err(_) =>
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::Atom(String::from("bad_utf8"))))
... | bytes_to_json | identifier_name |
framed_rectangle.rs | use {
Backend,
Color,
Colorable,
Dimensions,
Frameable,
Scalar,
Sizeable,
Widget,
};
use widget;
/// A filled rectangle widget that may or may not have some frame.
#[derive(Copy, Clone, Debug)]
pub struct | {
/// Data necessary and common for all widget builder types.
pub common: widget::CommonBuilder,
/// Unique styling for the **FramedRectangle**.
pub style: Style,
}
/// Unique kind for the Widget.
pub const KIND: widget::Kind = "FramedRectangle";
widget_style!{
KIND;
/// Unique styling for th... | FramedRectangle | identifier_name |
framed_rectangle.rs | use {
Backend,
Color,
Colorable,
Dimensions,
Frameable,
Scalar,
Sizeable,
Widget,
};
use widget;
/// A filled rectangle widget that may or may not have some frame.
#[derive(Copy, Clone, Debug)]
pub struct FramedRectangle {
/// Data necessary and common for all widget builder types.... | /// Shape styling for the inner rectangle.
- color: Color { theme.shape_color }
/// The thickness of the frame.
- frame: Scalar { theme.frame_width }
/// The color of the frame.
- frame_color: Color { theme.frame_color }
}
}
impl FramedRectangle {
/// Build a ne... | widget_style!{
KIND;
/// Unique styling for the **FramedRectangle** widget.
style Style { | random_line_split |
lib.rs | // Copyright 2012-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-MI... | else {
cx.bug("Incorrect number of arguments to `rand` in `derive(Rand)`")
};
let rand_ident = vec!(
cx.ident_of("rand"),
cx.ident_of("Rand"),
cx.ident_of("rand")
);
let rand_call = |cx: &mut ExtCtxt, span| {
cx.expr_call_global(span,
... | {
&substr.nonself_args[0]
} | conditional_block |
lib.rs | // Copyright 2012-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-MI... | <F>(cx: &mut ExtCtxt,
trait_span: Span,
ctor_path: ast::Path,
summary: &StaticFields,
mut rand_call: F)
-> P<Expr> where
F: FnMut(&mut ExtCtxt, Span) -> P<Expr>,
{
let path = cx.expr_path(ctor_pa... | rand_thing | identifier_name |
lib.rs | // Copyright 2012-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-MI... | push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("rand", "Rand")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
methods: vec!... |
pub fn expand_deriving_rand(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable, | random_line_split |
lib.rs | // Copyright 2012-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-MI... | Borrowed(None, ast::Mutability::Mutable))
),
ret_ty: Self_,
attributes: Vec::new(),
combine_substructure: combine_substructure(Box::new(|a, b, c| {
rand_substructure(a, b, c)
}))
}
... | {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("rand", "Rand")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
methods: vec!(
MethodDef {
name: "rand",
... | identifier_body |
sanity.rs | use WinVersion;
use super::Cache;
pub fn | (cache: &mut Cache) {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might mess up the expansion. This currently means:
- Featur... | sanity_check_features | identifier_name |
sanity.rs | use WinVersion;
use super::Cache;
pub fn sanity_check_features(cache: &mut Cache) {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might... | } | } | random_line_split |
sanity.rs | use WinVersion;
use super::Cache;
pub fn sanity_check_features(cache: &mut Cache) {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might... |
}
if let Some(ref winver) = feat.winver {
if!winver.is_simple() {
for &ref range in winver.ranges() {
weird_vers.insert(range.end);
}
suspect.push("complex-winver");
}
}
if suspect.len()!= 0 {
... | {
suspect.push("non-desktop-app");
} | conditional_block |
sanity.rs | use WinVersion;
use super::Cache;
pub fn sanity_check_features(cache: &mut Cache) | }
}
if let Some(ref winver) = feat.winver {
if!winver.is_simple() {
for &ref range in winver.ranges() {
weird_vers.insert(range.end);
}
suspect.push("complex-winver");
}
}
if suspect... | {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might mess up the expansion. This currently means:
- Features with upper limits... | identifier_body |
lib.rs | //! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readi... | //! CLIENT => {
//! // The server just shuts down the socket, let's just exit
//! // from our event loop.
//! return;
//! }
//! _ => unreachable!(),
//! }
//! }
//! }
//!
//! ```
#![doc(html_root_url = "https://docs.rs/mio/... | //! } | random_line_split |
lib.rs | //! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readi... |
}
| {
// Round up.
let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI;
duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64)
} | identifier_body |
lib.rs | //! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readi... | (duration: Duration) -> u64 {
// Round up.
let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI;
duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64)
}
}
| millis | identifier_name |
main.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#![no_std]
#![no_main]
#![feature(alloc)]
#![feature(alloc_error_handler)]
#![feature(asm)]
#![feature(global_asm)]
#![feature(... | #[macro_use]
extern crate log;
mod app;
mod audio;
mod debug;
mod device;
mod exception;
mod macros;
mod memory;
mod null_output;
mod palette;
mod sound_buffer;
mod util;
mod video_buffer;
mod video_renderer;
use core::alloc::Layout;
use core::panic::PanicInfo;
use cortex_a::asm;
use linked_list_allocator::LockedHeap... | #![feature(range_contains)]
extern crate alloc; | random_line_split |
main.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#![no_std]
#![no_main]
#![feature(alloc)]
#![feature(alloc_error_handler)]
#![feature(asm)]
#![feature(global_asm)]
#![feature(... | (info: &PanicInfo) ->! {
//interrupt::disable();
print!("ERROR: {}\n", info);
loop {
asm::wfe()
}
}
raspi3_boot::entry!(start);
| on_panic | identifier_name |
main.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#![no_std]
#![no_main]
#![feature(alloc)]
#![feature(alloc_error_handler)]
#![feature(asm)]
#![feature(global_asm)]
#![feature(... | let vectors = &__exception_vectors_start as *const _ as u64;
VBAR_EL1.set(vectors);
barrier::isb(barrier::SY);
}
print!("Initializing MMU...\n");
unsafe {
memory::mmu::init_page_table();
memory::mmu::init();
}
print!("Initializing heap...\n");
unsafe {
... | {
extern "C" {
//noinspection RsStaticConstNaming
static __exception_vectors_start: u64;
}
print!("Initializing console ...\n");
{
let dma_range = memory::dma_heap_range();
let gpio = device::gpio::GPIO::new(memory::map::GPIO_BASE);
let mut mbox = device::mbox::Mb... | identifier_body |
json.rs | use std::collections::HashMap;
use std::fmt;
use std::mem;
use serde::de::{self, Deserializer, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use crate::bail;
use crate::errors::FinchResult;
use crate::filtering::FilterParams;
pub use crate::serialization::mash::{read_ma... |
pub fn to_sketches(&self) -> FinchResult<Vec<Sketch>> {
let empty_hashmap = HashMap::new();
let mut sketches = Vec::with_capacity(self.sketches.len());
let sketch_params = self.get_params()?;
for sketch in &self.sketches {
let filters = sketch.filters.as_ref().unwrap_or... | {
let json_sketches: Vec<JsonSketch> = sketches.iter().map(|x| (*x).clone().into()).collect();
let sketch_params = SketchParams::from_sketches(&sketches)?;
// TODO: the scale isn't actually harmonized between the sketches at
// this point; it probably should be?
let (hash_type, h... | identifier_body |
json.rs | use std::collections::HashMap;
use std::fmt;
use std::mem;
use serde::de::{self, Deserializer, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use crate::bail;
use crate::errors::FinchResult;
use crate::filtering::FilterParams;
pub use crate::serialization::mash::{read_ma... | pub num_valid_kmers: Option<u64>,
pub comment: Option<String>,
pub filters: Option<HashMap<String, String>>,
pub hashes: Vec<KmerCount>,
}
impl JsonSketch {
pub fn new(
name: &str,
length: u64,
n_kmers: u64,
kmercounts: Vec<KmerCount>,
filters: &HashMap<Strin... |
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct JsonSketch {
pub name: String,
pub seq_length: Option<u64>, | random_line_split |
json.rs | use std::collections::HashMap;
use std::fmt;
use std::mem;
use serde::de::{self, Deserializer, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use crate::bail;
use crate::errors::FinchResult;
use crate::filtering::FilterParams;
pub use crate::serialization::mash::{read_ma... | <S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut hash_list = Vec::with_capacity(self.hashes.len());
let mut kmer_list = Vec::with_capacity(self.hashes.len());
let mut count_list = Vec::with_capacity(self.hashes.len());
for hash in &self.... | serialize | identifier_name |
exhaustive_natural_range.rs | use itertools::Itertools;
use malachite_base::num::basic::traits::{One, Zero};
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::strings::ToDebugString;
use malachite_nz::natural::exhaustive::exhaustive_natural_range;
use malachite_nz::natural::Natural;
fn expected_range_len(a: &Natural, b: &... | () {
exhaustive_natural_range_helper(Natural::ZERO, Natural::ZERO, "[]");
exhaustive_natural_range_helper(Natural::ZERO, Natural::ONE, "[0]");
exhaustive_natural_range_helper(
Natural::ZERO,
Natural::exact_from(10),
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]",
);
exhaustive_natural_rang... | test_exhaustive_natural_range | identifier_name |
exhaustive_natural_range.rs | use itertools::Itertools;
use malachite_base::num::basic::traits::{One, Zero};
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::strings::ToDebugString;
use malachite_nz::natural::exhaustive::exhaustive_natural_range;
use malachite_nz::natural::Natural;
fn expected_range_len(a: &Natural, b: &... | {
exhaustive_natural_range(Natural::ONE, Natural::ZERO);
} | identifier_body | |
exhaustive_natural_range.rs | use itertools::Itertools;
use malachite_base::num::basic::traits::{One, Zero};
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::strings::ToDebugString;
use malachite_nz::natural::exhaustive::exhaustive_natural_range;
use malachite_nz::natural::Natural;
fn expected_range_len(a: &Natural, b: &... | assert_eq!(xs, values);
let len = expected_range_len(&a, &b);
assert_eq!(exhaustive_natural_range(a.clone(), b.clone()).count(), len);
let mut init = exhaustive_natural_range(a, b)
.rev()
.skip(len.saturating_sub(20))
.collect_vec();
init.reverse();
assert_eq!(xs, init.to_de... | .collect_vec()
.to_debug_string(); | random_line_split |
generic-tuple-style-enum.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... | // gdb-check:$4 = {{-1}}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print case1
// lldb-check:[...]$0 = Case1(0, 31868, 31868, 31868, 31868)
// lldb-command:print case2
// lldb-check:[...]$1 = Case2(0, 286331153, 28633115... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.