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 |
|---|---|---|---|---|
interop.rs |
use std::os::raw::c_char;
use std;
use util;
use d3dx;
use shared_dx9::util::write_log_file;
use global_state::HookState;
use types::interop::*;
lazy_static! {
pub static ref LOG_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
}
unsafe fn loggit(prefix: &str, category: *const c_char, message: *const c_... |
#[allow(unused)]
#[no_mangle]
pub unsafe extern "stdcall" fn OnInitialized(
callbacks: *mut ManagedCallbacks,
global_state_pointer: u64,
) -> i32 {
use std::ffi::CStr;
use std::ffi::CString;
let on_init_error_code = 666;
// reinit global state pointer. technically we only really need to do ... | {
match d3dx::save_texture(index, filepath) {
Ok(_) => true,
Err(e) => {
write_log_file(&format!("failed to save texture: {:?}", e));
false
}
}
} | identifier_body |
interop.rs | use std::os::raw::c_char;
use std;
use util;
use d3dx;
use shared_dx9::util::write_log_file;
use global_state::HookState;
use types::interop::*;
lazy_static! {
pub static ref LOG_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
}
unsafe fn loggit(prefix: &str, category: *const c_char, message: *const c_ch... |
#[allow(unused)]
#[no_mangle]
pub unsafe extern "stdcall" fn LogInfo(category: *const c_char, message: *const c_char) -> () {
loggit("", category, message);
}
#[allow(unused)]
#[no_mangle]
pub unsafe extern "stdcall" fn LogWarn(category: *const c_char, message: *const c_char) -> () {
loggit("WARN", category, ... | write_log_file(&format!("[{}]: {}", category, message));
} else {
write_log_file(&format!("[{}:{}]: {}", prefix, category, message));
};
} | random_line_split |
inherited_table.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedTable", inherited=True, ... | gecko_constant_prefix="NS_STYLE_BORDER",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")}
${helpers.single_keyword("empty-cells", "show hide",
gecko_constant_prefix="... | ${helpers.single_keyword("border-collapse", "separate collapse", | random_line_split |
quick_union.rs | use std::fmt;
use super::UF;
pub struct UnionFind {
id: Vec<usize>
}
impl UnionFind {
fn root_of(&self, p: usize) -> usize {
let mut rid = self.id[p];
while rid!= self.id[rid] {
rid = self.id[rid];
}
rid
}
}
impl UF for UnionFind { | fn new(n: usize) -> UnionFind {
UnionFind { id: (0..n).collect() }
}
// Check if p and q have the same root.
fn connected(&self, p: usize, q: usize) -> bool {
self.root_of(p) == self.root_of(q)
}
// To merge components containing p and q,
// set the id of p's root to the id... | // Integer array id[] of length N.
// Interpretation: id[i] is parent of i.
// Root of i is id[id[id[...id[i]...]]]. | random_line_split |
quick_union.rs | use std::fmt;
use super::UF;
pub struct UnionFind {
id: Vec<usize>
}
impl UnionFind {
fn root_of(&self, p: usize) -> usize {
let mut rid = self.id[p];
while rid!= self.id[rid] {
rid = self.id[rid];
}
rid
}
}
impl UF for UnionFind {
// Integer array id[] of ... |
}
| {
for i in self.id.iter() {
try!(write!(f, "{} ", i));
}
Ok(())
} | identifier_body |
quick_union.rs | use std::fmt;
use super::UF;
pub struct UnionFind {
id: Vec<usize>
}
impl UnionFind {
fn | (&self, p: usize) -> usize {
let mut rid = self.id[p];
while rid!= self.id[rid] {
rid = self.id[rid];
}
rid
}
}
impl UF for UnionFind {
// Integer array id[] of length N.
// Interpretation: id[i] is parent of i.
// Root of i is id[id[id[...id[i]...]]].
fn... | root_of | identifier_name |
core-std.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut r = thread_rng();
let mut v = Vec::new();
let mut i = 0;
while i < 1500 {
let rv = vec![i; r.gen_range(0, i + 1)];
if r.gen() {
let mut t = v.clone();
t.push_all(&rv);
v = t;
}
else {
let mut t = rv.clone();
... | vec_append | identifier_name |
core-std.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
else {
swap(&mut v, &mut rv);
v.push_all(&rv);
}
}
}
fn is_utf8_ascii() {
let mut v : Vec<u8> = Vec::new();
for _ in 0..20000 {
v.push('b' as u8);
if str::from_utf8(&v).is_err() {
panic!("from_utf8 panicked");
}
}
}
fn is_utf... | {
v.push_all(&rv);
} | conditional_block |
core-std.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn is_utf8_ascii() {
let mut v : Vec<u8> = Vec::new();
for _ in 0..20000 {
v.push('b' as u8);
if str::from_utf8(&v).is_err() {
panic!("from_utf8 panicked");
}
}
}
fn is_utf8_multibyte() {
let s = "b¢€𤭢";
let mut v : Vec<u8> = Vec::new();
for _ in 0..5000 {... | {
let mut r = thread_rng();
let mut v = Vec::new();
for i in 0..1500 {
let mut rv = vec![i; r.gen_range(0, i + 1)];
if r.gen() {
v.push_all(&rv);
}
else {
swap(&mut v, &mut rv);
v.push_all(&rv);
}
}
} | identifier_body |
core-std.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
bench!(shift_push);
bench!(vec_plus);
bench!(vec_append);
bench!(vec_push_all);
bench!(is_utf8_ascii);
bench!(is_utf8_multibyte);
}
fn maybe_run_test<F>(argv: &[String], name: String, test: F) where F: FnOnce() {
let mut run_test = false;
if env::var_os("RUST_BENCH").is_some() {
... | } | random_line_split |
interact.rs | //! `PathExplorer` that allows interactive exploration
use rune::explorer::explorer::PathExplorer;
use rune::explorer::interactive::Command;
use rune::context::rune_ctx::RuneContext;
use rune::context::context::{Context, Evaluate, MemoryRead, RegisterRead};
use rune::engine::rune::RuneControl;
use rune::memory::seg_me... | (&self, ctx: &mut RuneContext<SegMem, RuneRegFile>) {
let mut z3: z3::Z3 = Default::default();
let result = ctx.solve(&mut z3);
println!("{:?}", result);
self.console.print_success("Results:");
/*
for (k, v) in &ctx.syms {
if let Some(res) = result.get(v) {
... | query_constraints | identifier_name |
interact.rs | //! `PathExplorer` that allows interactive exploration
use rune::explorer::explorer::PathExplorer;
use rune::explorer::interactive::Command;
use rune::context::rune_ctx::RuneContext;
use rune::context::context::{Context, Evaluate, MemoryRead, RegisterRead};
use rune::engine::rune::RuneControl;
use rune::memory::seg_me... | } else {
ctx.reg_read(tokens[1])
}
};
let op_2 = {
if tokens[2].len() > 2 && &tokens[2][0..2] == "0x" {
let const_v = u64::from_str_radix(&tokens[2][2..], 16)
.expect("In... | ctx.mem_read(addr, 64) | random_line_split |
interact.rs | //! `PathExplorer` that allows interactive exploration
use rune::explorer::explorer::PathExplorer;
use rune::explorer::interactive::Command;
use rune::context::rune_ctx::RuneContext;
use rune::context::context::{Context, Evaluate, MemoryRead, RegisterRead};
use rune::engine::rune::RuneControl;
use rune::memory::seg_me... |
fn next(&mut self, ctx: &mut Self::Ctx) -> RuneControl {
if self.single_step || self.bp.contains(&ctx.ip()) {
self.console.print_info(&format!("Halted at {:#x}", ctx.ip()));
loop {
self.single_step = match self.console.read_command()[0] {
Command... | {
InteractiveExplorer {
cmd_q: Vec::new(),
console: Default::default(),
single_step: false,
bp: Vec::new(),
}
} | identifier_body |
mod.rs | use core::ptr::RawPtr;
use core::ptr::{copy_nonoverlapping_memory, set_memory};
use core::mem::transmute;
use core::prelude::*;
use core;
use kernel::process::Process;
use kernel::mm;
use platform::io;
#[cfg(target_word_size = "32")] pub use self::elf32::{Ehdr, Phdr, Auxv, AuxvValue, AT_NULL};
#[cfg(target_word_size ... | else {
mm::Flags::zero()
};
task.mmap(vaddr, mem_size, flags);
copy_nonoverlapping_memory(vaddr, buffer.offset(file_pos), file_size);
set_memory(vaddr.offset(file_size as int), 0, mem_size - file_size);
}
}
impl ELFIdent {
unsafe fn load(&self) -> Option<&Ehdr> {
... | {
mm::RW
} | conditional_block |
mod.rs | use core::ptr::RawPtr;
use core::ptr::{copy_nonoverlapping_memory, set_memory};
use core::mem::transmute;
use core::prelude::*;
use core;
use kernel::process::Process;
use kernel::mm;
use platform::io;
#[cfg(target_word_size = "32")] pub use self::elf32::{Ehdr, Phdr, Auxv, AuxvValue, AT_NULL};
#[cfg(target_word_size ... | {
ei_mag: [u8,..4],
ei_class: u8,
ei_data: u8,
ei_version: u8,
ei_osabi: u8,
ei_abiversion: u8,
ei_pad: [u8,..7]
}
impl self::Ehdr {
pub unsafe fn spawn_process(&self) -> Process {
let mut task = Process::new();
//TODO: Verify file integrity
let buffer: *const u... | ELFIdent | identifier_name |
mod.rs | use core::ptr::RawPtr;
use core::ptr::{copy_nonoverlapping_memory, set_memory};
use core::mem::transmute;
use core::prelude::*;
use core;
use kernel::process::Process;
use kernel::mm;
use platform::io;
#[cfg(target_word_size = "32")] pub use self::elf32::{Ehdr, Phdr, Auxv, AuxvValue, AT_NULL};
#[cfg(target_word_size ... | {
unsafe {
let ident: &ELFIdent = transmute(buffer);
ident.load().map(|e| { e.spawn_process().enter() });
}
} | identifier_body | |
mod.rs | use core::ptr::RawPtr;
use core::ptr::{copy_nonoverlapping_memory, set_memory};
use core::mem::transmute;
use core::prelude::*;
use core;
use kernel::process::Process;
use kernel::mm;
use platform::io;
#[cfg(target_word_size = "32")] pub use self::elf32::{Ehdr, Phdr, Auxv, AuxvValue, AT_NULL};
#[cfg(target_word_size ... |
match (*pheader).p_type {
PT_NULL => {}
PT_LOAD => (*pheader).load(&task, buffer),
PT_DYNAMIC => (*pheader).load(&task, buffer),
PT_GNU_STACK => {
if!((*pheader).p_flags &!PT_X).is_zero() {
// We don... | random_line_split | |
issue-14959.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {} | let send_file = alloy.find::<SendFile>().unwrap();
send_file(res);
Status::Continue
}
} | random_line_split |
issue-14959.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 ... | (&self) { } }
trait Ingot<R, S> {
fn enter(&mut self, _: &mut R, _: &mut S, a: &mut Alloy) -> Status;
}
#[allow(dead_code)]
struct HelloWorld;
struct SendFile;
struct Alloy;
enum Status {
Continue
}
impl Alloy {
fn find<T>(&self) -> Option<T> {
None
}
}
impl<'b> Fn<(&'b mut (Response+'b),)> ... | dummy | identifier_name |
issue-14959.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 ... | }
trait Request { fn dummy(&self) { } }
trait Ingot<R, S> {
fn enter(&mut self, _: &mut R, _: &mut S, a: &mut Alloy) -> Status;
}
#[allow(dead_code)]
struct HelloWorld;
struct SendFile;
struct Alloy;
enum Status {
Continue
}
impl Alloy {
fn find<T>(&self) -> Option<T> {
None
}
}
impl<'b> Fn... | { } | identifier_body |
table_rowgroup.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... |
});
}
fn assign_block_size(&mut self, _: &LayoutContext) {
debug!("assign_block_size: assigning block_size for table_rowgroup");
self.block_flow.assign_block_size_for_table_like_flow(self.spacing.vertical());
}
fn compute_stacking_relative_position(&mut self, layout_context: &... | {
let child_table_row = child_flow.as_mut_table_row();
child_table_row.populate_collapsed_border_spacing(
collapsed_inline_direction_border_widths_for_table,
&mut collapsed_block_direction_border_widths_for_table);
} | conditional_block |
table_rowgroup.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... |
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_thr... | } | random_line_split |
table_rowgroup.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... |
fn repair_style(&mut self, new_style: &::ServoArc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Overflow {
self.block_flow.compute_overflow()
}
fn contains_roots_of_absolute_flow_tree(&self) -> bool {
self.block_flow.contains_r... | {
self.block_flow.collect_stacking_contexts_for_block(state,
StackingContextCollectionFlags::NEVER_CREATES_CONTAINING_BLOCK);
} | identifier_body |
table_rowgroup.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... | (&self) -> &TableRowGroupFlow {
self
}
fn as_mut_block(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
let _scope = layout_debug_scope!("table_rowgroup::bubble_inlin... | as_table_rowgroup | identifier_name |
manifest.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Structs for reading and writing manifests of flash boot stage images.
//!
//! Note: The structs below must match the definitions in
//! sw/device/silicon_creator/lib... | pub life_cycle_state: u32,
}
impl Default for ManifestUsageConstraints {
fn default() -> Self {
Self {
selector_bits: 0,
device_id: LifecycleDeviceId {
device_id: [MANIFEST_USAGE_CONSTRAINT_UNSELECTED_WORD_VAL;
8usize],
},
... | random_line_split | |
manifest.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Structs for reading and writing manifests of flash boot stage images.
//!
//! Note: The structs below must match the definitions in
//! sw/device/silicon_creator/lib... | {
pub selector_bits: u32,
pub device_id: LifecycleDeviceId,
pub manuf_state_creator: u32,
pub manuf_state_owner: u32,
pub life_cycle_state: u32,
}
impl Default for ManifestUsageConstraints {
fn default() -> Self {
Self {
selector_bits: 0,
device_id: LifecycleDev... | ManifestUsageConstraints | identifier_name |
font.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use app_units::Au;
use euclid::{Point2D, Rect, Size2D};
use font_template::FontTemplateDescriptor;
use ordered_flo... | {
let value = TEXT_SHAPING_PERFORMANCE_COUNTER.load(Ordering::SeqCst);
TEXT_SHAPING_PERFORMANCE_COUNTER.store(0, Ordering::SeqCst);
value
} | identifier_body | |
font.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use app_units::Au;
use euclid::{Point2D, Rect, Size2D};
use font_template::FontTemplateDescriptor;
use ordered_flo... | pub fn new(handle: FontHandle,
variant: font_variant_caps::T,
descriptor: FontTemplateDescriptor,
requested_pt_size: Au,
actual_pt_size: Au,
font_key: webrender_api::FontKey) -> Font {
let metrics = handle.metrics();
Font {
... | random_line_split | |
font.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use app_units::Au;
use euclid::{Point2D, Rect, Size2D};
use font_template::FontTemplateDescriptor;
use ordered_flo... | (advance: Au, ascent: Au, descent: Au) -> RunMetrics {
let bounds = Rect::new(Point2D::new(Au(0), -ascent),
Size2D::new(advance, ascent + descent));
// TODO(Issue #125): support loose and tight bounding boxes; using the
// ascent+descent and advance is sometimes t... | new | identifier_name |
font.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use app_units::Au;
use euclid::{Point2D, Rect, Size2D};
use font_template::FontTemplateDescriptor;
use ordered_flo... |
let offset = prev_glyph_id.map(|prev| {
let h_kerning = Au::from_f64_px(self.glyph_h_kerning(prev, glyph_id));
advance += h_kerning;
Point2D::new(h_kerning, Au(0))
});
let glyph = GlyphData::new(glyph_id, advance, offset, true, true);... | {
advance += letter_spacing;
} | conditional_block |
expr-if-struct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
enum mood { happy, sad, }
impl Eq for mood {
fn eq(&self, other: &mood) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &mood) -> bool {!(*self).eq(other) }
}
fn test_tag() {
let rs = if true { happy } else { sad };
assert_eq!(rs, happy);
}
pub fn main() { test_r... | {
let rs = if true { I {i: 100} } else { I {i: 101} };
assert_eq!(rs.i, 100);
} | identifier_body |
expr-if-struct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
assert_eq!(rs, happy);
}
pub fn main() { test_rec(); test_tag(); }
| { sad } | conditional_block |
expr-if-struct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let rs = if true { happy } else { sad };
assert_eq!(rs, happy);
}
pub fn main() { test_rec(); test_tag(); } | random_line_split | |
expr-if-struct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | { happy, sad, }
impl Eq for mood {
fn eq(&self, other: &mood) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &mood) -> bool {!(*self).eq(other) }
}
fn test_tag() {
let rs = if true { happy } else { sad };
assert_eq!(rs, happy);
}
pub fn main() { test_rec(); test_... | mood | identifier_name |
sieve.rs | /*
* This file is part of the uutils coreutils package.
*
* (c) kwantam <kwantam@gmail.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
use std::iter::{Chain, Cycle, Map};
use std::slice::Iter;
/// A lazy Sieve of Eratosthenes.
///
... | let (c2key, _) = self.data[child2];
if c1key < c2key {
(child1, c1key)
} else {
(child2, c2key)
}
};
if minkey < key {
self.data.swap(minidx, idx);
idx = minid... | {
let ret = self.data.swap_remove(0);
let mut idx = 0;
let len = self.data.len();
let (key, _) = self.data[0];
loop {
let child1 = 2 * idx + 1;
let child2 = 2 * idx + 2;
// no more children
if child1 >= len {
break... | identifier_body |
sieve.rs | /*
* This file is part of the uutils coreutils package.
*
* (c) kwantam <kwantam@gmail.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
use std::iter::{Chain, Cycle, Map};
use std::slice::Iter;
/// A lazy Sieve of Eratosthenes.
///
... | (&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
#[inline]
fn next(&mut self) -> Option<u64> {
while let Some(n) = self.inner.next() {
let mut prime = true;
while let Some((next, inc)) = self.filts.peek() {
// need to keep checking the min... | size_hint | identifier_name |
sieve.rs | /*
* This file is part of the uutils coreutils package.
*
* (c) kwantam <kwantam@gmail.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
use std::iter::{Chain, Cycle, Map};
use std::slice::Iter;
/// A lazy Sieve of Eratosthenes.
///
... | type Item = u64;
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(1, None)
}
#[inline]
fn next(&mut self) -> Option<u64> {
let increment = self.increment.next().unwrap(); // infinite iterator, no check necessary
let ret = self.next;
self.next = ret + i... | impl Iterator for Wheel { | random_line_split |
sieve.rs | /*
* This file is part of the uutils coreutils package.
*
* (c) kwantam <kwantam@gmail.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
use std::iter::{Chain, Cycle, Map};
use std::slice::Iter;
/// A lazy Sieve of Eratosthenes.
///
... |
// find lesser child
let (c1key, _) = self.data[child1];
let (minidx, minkey) = if child2 >= len {
(child1, c1key)
} else {
let (c2key, _) = self.data[child2];
if c1key < c2key {
(child1, c1key)
... | {
break;
} | conditional_block |
list.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | Some(Ok(dt)) => Some(dt),
Some(Err(e)) => {
trace_error(&e);
None
}
};
let end = match cmd.value_of("end-time").map(::chrono::naive::NaiveDateTime::from_str) {
None => None,
Some(Ok(dt)) => Some(dt),
Some(Err(e)) => {
tr... | None => None, | random_line_split |
list.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | (rt: &Runtime) -> i32 {
let (_, cmd) = rt.cli().subcommand();
let cmd = cmd.unwrap(); // checked in main()
let start = match cmd.value_of("start-time").map(::chrono::naive::NaiveDateTime::from_str) {
None => None,
Some(Ok(dt)) => Some(dt),
Some(Err(e)) => {
trace... | list | identifier_name |
list.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... |
let list_not_ended = cmd.is_present("list-not-ended");
let start_time_filter = |timetracking: &FileLockEntry| {
start.map(|s| match timetracking.get_start_datetime() {
Ok(Some(dt)) => dt >= s,
Ok(None) => {
warn!("Funny things are happening: Timetracking has... | {
let (_, cmd) = rt.cli().subcommand();
let cmd = cmd.unwrap(); // checked in main()
let start = match cmd.value_of("start-time").map(::chrono::naive::NaiveDateTime::from_str) {
None => None,
Some(Ok(dt)) => Some(dt),
Some(Err(e)) => {
trace_error(&e);
... | identifier_body |
delete-crate.rs | // Purge all references to a crate from the database.
//
// Please be super sure you want to do this before running this.
//
// Usage:
// cargo run --bin delete-crate crate-name
#![deny(warnings)]
#[macro_use]
extern crate cargo_registry;
extern crate postgres;
extern crate time;
use std::env;
use std::io;
use ... |
fn delete(tx: &postgres::Transaction) {
let name = match env::args().nth(1) {
None => { println!("needs a crate-name argument"); return }
Some(s) => s,
};
let krate = Crate::find_by_name(tx, &name).unwrap();
print!("Are you sure you want to delete {} ({}) [y/N]: ", name, krate.id);
... | {
match env::var(s).ok() {
Some(s) => s,
None => panic!("must have `{}` defined", s),
}
} | identifier_body |
delete-crate.rs | // Purge all references to a crate from the database.
//
// Please be super sure you want to do this before running this.
//
// Usage:
// cargo run --bin delete-crate crate-name
#![deny(warnings)]
#[macro_use]
extern crate cargo_registry;
extern crate postgres;
extern crate time;
use std::env;
use std::io;
use ... | (s: &str) -> String {
match env::var(s).ok() {
Some(s) => s,
None => panic!("must have `{}` defined", s),
}
}
fn delete(tx: &postgres::Transaction) {
let name = match env::args().nth(1) {
None => { println!("needs a crate-name argument"); return }
Some(s) => s,
};
l... | env | identifier_name |
delete-crate.rs | // Purge all references to a crate from the database.
//
// Please be super sure you want to do this before running this.
//
// Usage:
// cargo run --bin delete-crate crate-name
#![deny(warnings)]
#[macro_use]
extern crate cargo_registry;
extern crate postgres;
extern crate time;
use std::env;
use std::io;
use ... | None => panic!("must have `{}` defined", s),
}
}
fn delete(tx: &postgres::Transaction) {
let name = match env::args().nth(1) {
None => { println!("needs a crate-name argument"); return }
Some(s) => s,
};
let krate = Crate::find_by_name(tx, &name).unwrap();
print!("Are you s... | fn env(s: &str) -> String {
match env::var(s).ok() {
Some(s) => s, | random_line_split |
awakener.rs | pub use self::pipe::Awakener;
/// Default *nix awakener implementation
mod pipe {
use {io, Evented, EventSet, PollOpt, Selector, Token, TryRead, TryWrite};
use unix::{self, PipeReader, PipeWriter};
/*
*
* ===== Awakener =====
*
*/
pub struct Awakener {
reader: PipeReader,
... | ,
_ => return,
}
}
}
fn reader(&self) -> &PipeReader {
&self.reader
}
}
impl Evented for Awakener {
fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
... | {} | conditional_block |
awakener.rs | pub use self::pipe::Awakener;
/// Default *nix awakener implementation
mod pipe {
use {io, Evented, EventSet, PollOpt, Selector, Token, TryRead, TryWrite};
use unix::{self, PipeReader, PipeWriter};
/*
*
* ===== Awakener =====
*
*/
pub struct Awakener {
reader: PipeReader,
... | (&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
self.reader().reregister(selector, token, interest, opts)
}
fn deregister(&self, selector: &mut Selector) -> io::Result<()> {
self.reader().deregister(selector)
}
}
... | reregister | identifier_name |
awakener.rs | pub use self::pipe::Awakener;
/// Default *nix awakener implementation
mod pipe {
use {io, Evented, EventSet, PollOpt, Selector, Token, TryRead, TryWrite};
use unix::{self, PipeReader, PipeWriter};
/*
*
* ===== Awakener =====
*
*/
pub struct Awakener {
reader: PipeReader,
... |
fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> {
self.reader().reregister(selector, token, interest, opts)
}
fn deregister(&self, selector: &mut Selector) -> io::Result<()> {
self.reader().deregister(sel... | {
self.reader().register(selector, token, interest, opts)
} | identifier_body |
awakener.rs | pub use self::pipe::Awakener;
/// Default *nix awakener implementation
mod pipe {
use {io, Evented, EventSet, PollOpt, Selector, Token, TryRead, TryWrite};
use unix::{self, PipeReader, PipeWriter};
/*
*
* ===== Awakener =====
*
*/
pub struct Awakener {
reader: PipeReader,
... | io: Io,
}
impl Awakener {
pub fn new() -> io::Result<Awakener> {
Ok(Awakener {
io: Io::new(try!(eventfd())),
})
}
pub fn wakeup(&self) -> io::Result<()> {
unsafe {
let io: &mut Io = mem::transmute(&self.io);
... | pub use nix::sys::eventfd::*;
}
pub struct Awakener { | random_line_split |
content_disposition.rs | // # References
//
// "The Content-Disposition Header Field" https://www.ietf.org/rfc/rfc2183.txt
// "The Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)" https://www.ietf.org/rfc/rfc6266.txt
// "Returning Values from Forms: multipart/form-data" https://www.ietf.org/rfc/rfc2388.txt
// Browser... | /// A `Content-Disposition` header, (re)defined in [RFC6266](https://tools.ietf.org/html/rfc6266)
///
/// The Content-Disposition response header field is used to convey
/// additional information about how to process the response payload, and
/// also can be used to attach additional metadata, such as the filename
///... | }
| random_line_split |
content_disposition.rs | // # References
//
// "The Content-Disposition Header Field" https://www.ietf.org/rfc/rfc2183.txt
// "The Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)" https://www.ietf.org/rfc/rfc6266.txt
// "Returning Values from Forms: multipart/form-data" https://www.ietf.org/rfc/rfc2388.txt
// Browser... | disposition: DispositionType::Attachment,
parameters: vec![
DispositionParam::Filename(
Charset::Ext("UTF-8".to_owned()),
None,
"image.jpg".bytes().collect()) ]
};
assert_eq!(a, b);
let a = [b"at... | {
assert!(ContentDisposition::parse_header([b"".to_vec()].as_ref()).is_err());
let a = [b"form-data; dummy=3; name=upload;\r\n filename=\"sample.png\"".to_vec()];
let a: ContentDisposition = ContentDisposition::parse_header(a.as_ref()).unwrap();
let b = ContentDisposition {
... | identifier_body |
content_disposition.rs | // # References
//
// "The Content-Disposition Header Field" https://www.ietf.org/rfc/rfc2183.txt
// "The Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)" https://www.ietf.org/rfc/rfc6266.txt
// "Returning Values from Forms: multipart/form-data" https://www.ietf.org/rfc/rfc2388.txt
// Browser... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self, f)
}
}
impl fmt::Display for ContentDisposition {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.disposition {
DispositionType::Inline => try!(write!(f, "inline")),
DispositionTy... | fmt_header | identifier_name |
content_disposition.rs | // # References
//
// "The Content-Disposition Header Field" https://www.ietf.org/rfc/rfc2183.txt
// "The Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)" https://www.ietf.org/rfc/rfc6266.txt
// "Returning Values from Forms: multipart/form-data" https://www.ietf.org/rfc/rfc2388.txt
// Browser... | ,
parameters: Vec::new(),
};
for section in sections {
let mut parts = section.splitn(2, '=');
let key = if let Some(key) = parts.next() {
key.trim()
} else {
return Err(::Error::Header);
... | {
DispositionType::Ext(disposition.to_owned())
} | conditional_block |
isr.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.o... | fn isr_rtc();
// fn isr_reserved3();
// fn isr_wwdt();
// fn isr_m0sub();
// fn isr_c_can0();
fn isr_qei();
}
#[allow(non_upper_case_globals)]
const ISRCount: usize = 53;
#[allow(non_upper_case_globals)]
#[link_section=".isr_vector_nvic"]
#[no_mangle]
pub static NVICVectors: [Option<unsafe extern fn()>; I... | // fn isr_c_can1();
// fn isr_reserved2();
// fn isr_adchs();
// fn isr_atimer(); | random_line_split |
tex.rs | // Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (ti: TextureInfo) -> ImageInfo {
ImageInfo {
xoffset: 0,
yoffset: 0,
zoffset: 0,
width: ti.width,
height: ti.height,
depth: ti.depth,
format: ti.format,
mipmap: 0,
}
}
}
impl From<TextureInfo> for Surfac... | from | identifier_name |
tex.rs | // Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | /// Enhanced Quality Anti-Aliasing
Eqaa(NumSamples, NumFragments),
}
/// Describes the color components of each texel.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[repr(u8)]
pub enum Components {
/// Red only
R,
/// Red and green
RG,
/// Red, green, blue
RGB,
... | #[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum AaMode {
/// MultiSampled Anti-Aliasing
Msaa(NumSamples), | random_line_split |
tex.rs | // Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
}
impl Default for TextureInfo {
fn default() -> TextureInfo {
TextureInfo {
width: 0,
height: 1,
depth: 1,
levels:!0,
kind: Kind::D2,
format: RGBA8,
}
}
}
impl TextureInfo {
/// Create a new empty texture info.
p... | {
ImageInfo {
xoffset: 0,
yoffset: 0,
zoffset: 0,
width: 0,
height: 1,
depth: 1,
format: RGBA8,
mipmap: 0
}
} | identifier_body |
config.rs | use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::io::{Error, ErrorKind};
use toml;
#[derive(Clone)]
pub struct Config {
config: toml::Value,
}
impl Config {
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Config, Error> |
pub fn from_string(toml: &str) -> Result<Config, Error> {
let config = match toml.parse() {
Ok(config) => config,
Err(_) => {
return Err(Error::new(ErrorKind::InvalidData,
"Syntax error - config file is not valid TOML"))
... | {
let mut fd = try!(File::open(path));
let mut toml = String::new();
try!(fd.read_to_string(&mut toml));
Config::from_string(&toml)
} | identifier_body |
config.rs | use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::io::{Error, ErrorKind};
use toml;
#[derive(Clone)]
pub struct Config {
config: toml::Value,
}
impl Config {
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Config, Error> {
let mut fd = try!(File::open(path));
let mu... | Ok(config) => config,
Err(_) => {
return Err(Error::new(ErrorKind::InvalidData,
"Syntax error - config file is not valid TOML"))
}
};
Ok(Config { config: config })
}
pub fn lookup<'a>(&'a self, path: &'a s... | let config = match toml.parse() { | random_line_split |
config.rs | use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::io::{Error, ErrorKind};
use toml;
#[derive(Clone)]
pub struct Config {
config: toml::Value,
}
impl Config {
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Config, Error> {
let mut fd = try!(File::open(path));
let mu... | (toml: &str) -> Result<Config, Error> {
let config = match toml.parse() {
Ok(config) => config,
Err(_) => {
return Err(Error::new(ErrorKind::InvalidData,
"Syntax error - config file is not valid TOML"))
}
};
... | from_string | identifier_name |
config.rs | use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::io::{Error, ErrorKind};
use toml;
#[derive(Clone)]
pub struct Config {
config: toml::Value,
}
impl Config {
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Config, Error> {
let mut fd = try!(File::open(path));
let mu... |
};
Ok(Config { config: config })
}
pub fn lookup<'a>(&'a self, path: &'a str) -> Option<&'a toml::Value> {
self.config.lookup(path)
}
}
| {
return Err(Error::new(ErrorKind::InvalidData,
"Syntax error - config file is not valid TOML"))
} | conditional_block |
cell_renderer_text.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | () -> Option<CellRendererText> {
let tmp_pointer = unsafe { ffi::gtk_cell_renderer_text_new() as *mut ffi::C_GtkWidget };
check_pointer!(tmp_pointer, CellRendererText)
}
fn set_fixed_height_from_font(&self, number_of_rows: i32) {
unsafe { ffi::gtk_cell_renderer_text_set_fixed_height_fr... | new | identifier_name |
cell_renderer_text.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
fn set_fixed_height_from_font(&self, number_of_rows: i32) {
unsafe { ffi::gtk_cell_renderer_text_set_fixed_height_from_font(GTK_CELL_RENDERER_TEXT(self.pointer), number_of_rows) }
}
}
impl_drop!(CellRendererText);
impl_TraitWidget!(CellRendererText);
impl gtk::CellRendererTrait for CellRendererText ... | {
let tmp_pointer = unsafe { ffi::gtk_cell_renderer_text_new() as *mut ffi::C_GtkWidget };
check_pointer!(tmp_pointer, CellRendererText)
} | identifier_body |
cell_renderer_text.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
impl_drop!(CellRendererText);
impl_TraitWidget!(CellRendererText);
impl gtk::CellRendererTrait for CellRendererText {}
impl_widget_events!(CellRendererText); | fn set_fixed_height_from_font(&self, number_of_rows: i32) {
unsafe { ffi::gtk_cell_renderer_text_set_fixed_height_from_font(GTK_CELL_RENDERER_TEXT(self.pointer), number_of_rows) }
}
} | random_line_split |
class-cast-to-trait.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self) { self.meow(); }
}
pub impl cat {
fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
error!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
error!("Not hungry!");
return false;
}
}
}
priv impl cat {
fn meow(&mut self) {
err... | speak | identifier_name |
class-cast-to-trait.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
pub impl cat {
fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
error!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
error!("Not hungry!");
return false;
}
}
}
priv impl cat {
fn meow(&mut self) {
error!("Meow");
self.meow... | { self.meow(); } | identifier_body |
class-cast-to-trait.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
pub impl cat {
fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
error!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
error!("Not hungry!");
return false;
}
}
}
priv impl cat {
fn meow(&mut self) {
error!("Meow");
self.meows... | random_line_split | |
class-cast-to-trait.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
else {
error!("Not hungry!");
return false;
}
}
}
priv impl cat {
fn meow(&mut self) {
error!("Meow");
self.meows += 1u;
if self.meows % 5u == 0u {
self.how_hungry += 1;
}
}
}
fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat {
cat {
... | {
error!("OM NOM NOM");
self.how_hungry -= 2;
return true;
} | conditional_block |
machinelearning.rs | #![cfg(feature = "machinelearning")]
extern crate rusoto_core;
extern crate rusoto_machinelearning;
use rusoto_core::Region;
use rusoto_machinelearning::{
DescribeBatchPredictionsInput, DescribeDataSourcesInput, DescribeEvaluationsInput,
MachineLearning, MachineLearningClient,
};
// This service isn't availa... |
#[tokio::test]
async fn should_describe_evaluations() {
let client = MachineLearningClient::new(Region::UsEast1);
let request = DescribeEvaluationsInput::default();
match client.describe_evaluations(request).await {
Ok(_) => (),
Err(e) => assert!(e
.to_string()
.conta... | {
let client = MachineLearningClient::new(Region::UsEast1);
let request = DescribeDataSourcesInput::default();
match client.describe_data_sources(request).await {
Ok(_) => (),
Err(e) => assert!(e
.to_string()
.contains("AmazonML is no longer available to new customer... | identifier_body |
machinelearning.rs | #![cfg(feature = "machinelearning")]
extern crate rusoto_core;
extern crate rusoto_machinelearning;
use rusoto_core::Region;
use rusoto_machinelearning::{
DescribeBatchPredictionsInput, DescribeDataSourcesInput, DescribeEvaluationsInput,
MachineLearning, MachineLearningClient,
};
// This service isn't availa... |
match client.describe_data_sources(request).await {
Ok(_) => (),
Err(e) => assert!(e
.to_string()
.contains("AmazonML is no longer available to new customers")),
};
}
#[tokio::test]
async fn should_describe_evaluations() {
let client = MachineLearningClient::new(Region... | random_line_split | |
machinelearning.rs | #![cfg(feature = "machinelearning")]
extern crate rusoto_core;
extern crate rusoto_machinelearning;
use rusoto_core::Region;
use rusoto_machinelearning::{
DescribeBatchPredictionsInput, DescribeDataSourcesInput, DescribeEvaluationsInput,
MachineLearning, MachineLearningClient,
};
// This service isn't availa... | () {
let client = MachineLearningClient::new(Region::UsEast1);
let request = DescribeEvaluationsInput::default();
match client.describe_evaluations(request).await {
Ok(_) => (),
Err(e) => assert!(e
.to_string()
.contains("AmazonML is no longer available to new customer... | should_describe_evaluations | identifier_name |
rmdir.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Alex Lyon <arcterus@mail.com>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
// spell-checker:ignore (ToDO) ENOTDIR
#[macro_use]
extern crate uucore;
us... | println!("{}: removing directory, {}", util_name(), path.quote());
}
remove_dir(path).map_err(|error| Error { error, path })
}
// POSIX: https://pubs.opengroup.org/onlinepubs/009696799/functions/rmdir.html
#[cfg(not(windows))]
const NOT_EMPTY_CODES: &[i32] = &[libc::ENOTEMPTY, libc::EEXIST];
// 145 is... | fn remove_single(path: &Path, opts: Opts) -> Result<(), Error<'_>> {
if opts.verbose { | random_line_split |
rmdir.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Alex Lyon <arcterus@mail.com>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
// spell-checker:ignore (ToDO) ENOTDIR
#[macro_use]
extern crate uucore;
us... |
#[derive(Clone, Copy, Debug)]
struct Opts {
ignore: bool,
parents: bool,
verbose: bool,
}
pub fn uu_app<'a>() -> App<'a> {
App::new(uucore::util_name())
.version(crate_version!())
.about(ABOUT)
.override_usage(format_usage(USAGE))
.setting(AppSettings::InferLongArgs)
... | {
if let Some(code) = error.raw_os_error() {
if NOT_EMPTY_CODES.contains(&code) {
return true;
}
// If --ignore-fail-on-non-empty is used then we want to ignore all errors
// for non-empty directories, even if the error was e.g. because there's
// no permission. S... | identifier_body |
rmdir.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Alex Lyon <arcterus@mail.com>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
// spell-checker:ignore (ToDO) ENOTDIR
#[macro_use]
extern crate uucore;
us... | (args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().get_matches_from(args);
let opts = Opts {
ignore: matches.is_present(OPT_IGNORE_FAIL_NON_EMPTY),
parents: matches.is_present(OPT_PARENTS),
verbose: matches.is_present(OPT_VERBOSE),
};
for path in matches
.... | uumain | identifier_name |
rmdir.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Alex Lyon <arcterus@mail.com>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
// spell-checker:ignore (ToDO) ENOTDIR
#[macro_use]
extern crate uucore;
us... |
set_exit_code(1);
// If `foo` is a symlink to a directory then `rmdir foo/` may give
// a "not a directory" error. This is confusing as `rm foo/` says
// "is a directory".
// This differs from system to system. Some don't give an error.
// Windo... | {
continue;
} | conditional_block |
threadpool.rs | use crate::board::Board;
use crate::moves::Move;
use crate::transposition_table::TranspositionTable;
use crate::util::ChessError;
use rand::{self, Rng};
use std::mem;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex, RwLock};
use std::thread;
use std::time::Duration;
type Worker =... |
pub fn abort_and_clear(&self) {
self.abort();
while *self.thinking.lock().unwrap() {
thread::sleep(Duration::from_millis(50));
}
let _ = self.take_result();
}
}
| {
mem::replace(&mut *self.result_mutex.lock().unwrap(), None)
} | identifier_body |
threadpool.rs | use crate::board::Board;
use crate::moves::Move;
use crate::transposition_table::TranspositionTable;
use crate::util::ChessError;
use rand::{self, Rng};
use std::mem;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex, RwLock};
use std::thread;
use std::time::Duration;
type Worker =... |
}
}
}
*result_mutex.lock().unwrap() = Some(Ok((best_move.unwrap(), best_score)));
*thinking.lock().unwrap() = false;
main_signal.notify_all();
});
}
pub fn has_result(&self) -> bool {
self.result_mutex.lock().... | {
best_move = Some(mv);
best_score = val;
} | conditional_block |
threadpool.rs | use crate::board::Board;
use crate::moves::Move;
use crate::transposition_table::TranspositionTable;
use crate::util::ChessError;
use rand::{self, Rng};
use std::mem;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex, RwLock};
use std::thread;
use std::time::Duration;
type Worker =... | {
Done { mv: Move, val: isize },
}
pub struct Threadpool {
handles: Vec<Worker>,
result_chan: Arc<Mutex<Receiver<JobResult>>>,
jobs: Arc<JobQueue>,
abort: Arc<RwLock<bool>>,
main_signal: Arc<Condvar>,
result_mutex: Arc<Mutex<Option<Result<(Move, isize), ChessError>>>>,
thinking: Arc<Mu... | JobResult | identifier_name |
threadpool.rs | use crate::board::Board;
use crate::moves::Move;
use crate::transposition_table::TranspositionTable;
use crate::util::ChessError;
use rand::{self, Rng};
use std::mem;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex, RwLock};
use std::thread;
use std::time::Duration;
type Worker =... | fn new() -> JobQueue {
JobQueue {
jobs: Mutex::new(Vec::new()),
jobs_available: Condvar::new(),
}
}
fn next_job(&self) -> Job {
let job;
loop {
match self.jobs.lock().unwrap().pop() {
Some(j) => {
job = ... | random_line_split | |
module.rs | //! Intermediate representation for modules (AKA C++ namespaces).
use clang;
use parse::{ClangSubItemParser, ParseError, ParseResult};
use parse_one;
use super::context::{BindgenContext, ItemId};
/// A module, as in, a C++ namespace.
#[derive(Clone, Debug)]
pub struct Module {
/// The name of the module, or none ... | cursor.visit(|cursor| {
parse_one(ctx, cursor, Some(module_id), children)
})
});
Ok(ParseResult::AlreadyResolved(module_id))
}
_ => Err(ParseError::Continue),
}
}
} | use clangll::*;
match cursor.kind() {
CXCursor_Namespace => {
let module_id = ctx.module(cursor);
ctx.with_module(module_id, |ctx, children| { | random_line_split |
module.rs | //! Intermediate representation for modules (AKA C++ namespaces).
use clang;
use parse::{ClangSubItemParser, ParseError, ParseResult};
use parse_one;
use super::context::{BindgenContext, ItemId};
/// A module, as in, a C++ namespace.
#[derive(Clone, Debug)]
pub struct Module {
/// The name of the module, or none ... |
/// Get this module's children.
pub fn children(&self) -> &[ItemId] {
&self.children_ids
}
}
impl ClangSubItemParser for Module {
fn parse(cursor: clang::Cursor,
ctx: &mut BindgenContext)
-> Result<ParseResult<Self>, ParseError> {
use clangll::*;
matc... | {
&mut self.children_ids
} | identifier_body |
module.rs | //! Intermediate representation for modules (AKA C++ namespaces).
use clang;
use parse::{ClangSubItemParser, ParseError, ParseResult};
use parse_one;
use super::context::{BindgenContext, ItemId};
/// A module, as in, a C++ namespace.
#[derive(Clone, Debug)]
pub struct Module {
/// The name of the module, or none ... | (cursor: clang::Cursor,
ctx: &mut BindgenContext)
-> Result<ParseResult<Self>, ParseError> {
use clangll::*;
match cursor.kind() {
CXCursor_Namespace => {
let module_id = ctx.module(cursor);
ctx.with_module(module_id, |ctx, children| ... | parse | identifier_name |
highlight.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 ... | (src: &str, class: Option<&str>, id: Option<&str>) -> String {
debug!("highlighting: ================\n{}\n==============", src);
let sess = parse::new_parse_sess();
let fm = parse::string_to_filemap(&sess,
src.to_string(),
"<stdin>... | highlight | identifier_name |
highlight.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 ... | "macro-nonterminal"
} else {
""
}
}
// This is the start of an attribute. We're going to want to
// continue highlighting it as an attribute until the ending ']' is
// seen, so skip out early. Down b... | if lexer.peek().tok.is_ident() {
is_macro_nonterminal = true; | random_line_split |
highlight.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 ... | else {
try!(write!(out, "<span class='{}'>{}</span>", klass,
Escape(snip.as_slice())));
}
}
write!(out, "</pre>\n")
}
| {
try!(write!(out, "{}", Escape(snip.as_slice())));
} | conditional_block |
highlight.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 ... |
/// Exhausts the `lexer` writing the output into `out`.
///
/// The general structure for this method is to iterate over each token,
/// possibly giving it an HTML span with a class specifying what flavor of token
/// it's used. All source code emission is done as slices from the source map,
/// not from the tokens t... | {
debug!("highlighting: ================\n{}\n==============", src);
let sess = parse::new_parse_sess();
let fm = parse::string_to_filemap(&sess,
src.to_string(),
"<stdin>".to_string());
let mut out = io::MemWriter::new();
... | identifier_body |
cr4.rs | use core::fmt;
/// Read the current value from `$cr4`.
///
/// # Safety
/// + Reading from control registers while not in kernel mode will cause
/// a general protection fault.
pub unsafe fn read() -> Flags {
let result: usize;
asm!( "mov $0, cr4"
: "=r"(result)
::: "intel" );
Flags {... |
bitflags! {
/// Bitflags present in `$cr4`
///
/// Documentation taken from
/// [wikipedia](https://en.wikipedia.org/wiki/Control_register#CR4).
pub flags Flags: usize {
/// Virtual 8086 Mode Extensions
///
/// If set, enables support for the virtual interrupt flag (VIF) i... | {
asm!( "mov cr4, $0"
:: "r"(flags.bits)
:: "intel");
} | identifier_body |
cr4.rs | use core::fmt;
/// Read the current value from `$cr4`.
///
/// # Safety
/// + Reading from control registers while not in kernel mode will cause
/// a general protection fault.
pub unsafe fn read() -> Flags {
let result: usize;
asm!( "mov $0, cr4"
: "=r"(result)
::: "intel" );
Flags {... | ///
/// If unset, page size is 4 KiB, else page size is increased to 4 MiB
/// (if PAE is enabled or the processor is in Long Mode this bit is
/// ignored).
const PSE = 1 << 4
, /// Physical Address Extension
///
/// If set, changes page table layout to trans... | const DE = 1 << 3
, /// Page Size Extension | random_line_split |
cr4.rs | use core::fmt;
/// Read the current value from `$cr4`.
///
/// # Safety
/// + Reading from control registers while not in kernel mode will cause
/// a general protection fault.
pub unsafe fn read() -> Flags {
let result: usize;
asm!( "mov $0, cr4"
: "=r"(result)
::: "intel" );
Flags {... | (flags: Flags) {
asm!( "mov cr4, $0"
:: "r"(flags.bits)
:: "intel");
}
bitflags! {
/// Bitflags present in `$cr4`
///
/// Documentation taken from
/// [wikipedia](https://en.wikipedia.org/wiki/Control_register#CR4).
pub flags Flags: usize {
/// Virtual 8086 Mode Extens... | write | identifier_name |
i_before_e_except_after_c.rs | // http://rosettacode.org/wiki/I_before_E_except_after_C
#[cfg(not(test))]
use std::fs::File;
#[cfg(not(test))]
use std::io::Read;
#[cfg(not(test))]
use std::path::Path;
enum | {
Nothing, //Nothing of interest seen so far
C, //Last seen a 'c'
Ce, //Last seen a 'c' followed by an 'e'
Ci, //Last seen a 'c' followed by an 'i'
E, //Last seen an 'e' not preceded by a 'c'
I //Last seen an 'i' not preceded by a 'c'
}
struct Occ... | MatchState | identifier_name |
i_before_e_except_after_c.rs | // http://rosettacode.org/wiki/I_before_E_except_after_C
#[cfg(not(test))]
use std::fs::File;
#[cfg(not(test))]
use std::io::Read;
#[cfg(not(test))]
use std::path::Path;
enum MatchState {
Nothing, //Nothing of interest seen so far
C, //Last seen a 'c'
Ce, //Last seen a 'c' followed by a... | //tracks what pattern prefix was recognized so far (details at MatchState).
//Each time a full pattern is matched the corresponding saw_* variable is set
//to true to record its presence for the current word (They are not added
//directly to result to ensure that words having multiple occurrences of one... |
fn count_occurrences(data: &str) -> Occurrences {
//The counting process is implemented by a state machine. The state variable | random_line_split |
borrowck-univariant-enum.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
newvar(isize)
}
pub fn main() {
// Test that borrowck treats enums with a single variant
// specially.
let x = &Cell::new(5);
let y = &Cell::new(newtype::newvar(3));
let z = match y.get() {
newtype::newvar(b) => {
x.set(x.get() + 1);
x.get() * b
}
};
ass... | newtype | identifier_name |
borrowck-univariant-enum.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | // except according to those terms.
// run-pass
#![allow(non_camel_case_types)]
use std::cell::Cell;
#[derive(Copy, Clone)]
enum newtype {
newvar(isize)
}
pub fn main() {
// Test that borrowck treats enums with a single variant
// specially.
let x = &Cell::new(5);
let y = &Cell::new(newtype::n... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
borrowck-univariant-enum.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
};
assert_eq!(z, 18);
}
| {
x.set(x.get() + 1);
x.get() * b
} | conditional_block |
devices.rs | //! The following is an adaptation of the "pa_devs.c" official PortAudio C example.
extern crate portaudio;
use portaudio as pa;
const INTERLEAVED: bool = true;
const LATENCY: pa::Time = 0.0; // Ignored by PortAudio::is_*_format_supported.
const STANDARD_SAMPLE_RATES: [f64; 13] = [
8000.0, 9600.0, 11025.0, 12000.... | () {
match run() {
Ok(_) => {}
e => {
eprintln!("Example failed with the following: {:?}", e);
}
}
}
fn run() -> Result<(), pa::Error> {
let pa = pa::PortAudio::new()?;
let num_devices = pa.device_count()?;
println!("Number of devices = {}", num_devices);
p... | main | identifier_name |
devices.rs | //! The following is an adaptation of the "pa_devs.c" official PortAudio C example.
extern crate portaudio;
use portaudio as pa;
const INTERLEAVED: bool = true;
const LATENCY: pa::Time = 0.0; // Ignored by PortAudio::is_*_format_supported.
const STANDARD_SAMPLE_RATES: [f64; 13] = [
8000.0, 9600.0, 11025.0, 12000.... |
println!(
"Supported standard sample rates for half-duplex 16-bit {} channel input:",
in_channels
);
for &sample_rate in &STANDARD_SAMPLE_RATES {
if pa
.is_input_format_supported(input_params, sample_rate)
.is_ok()
{
... | {
let pa = pa::PortAudio::new()?;
let num_devices = pa.device_count()?;
println!("Number of devices = {}", num_devices);
println!("Defualt input device: {:?}", pa.default_input_device());
println!("Defualt output device: {:?}", pa.default_output_device());
println!("All devices:");
for de... | identifier_body |
devices.rs | //! The following is an adaptation of the "pa_devs.c" official PortAudio C example.
extern crate portaudio;
use portaudio as pa;
const INTERLEAVED: bool = true;
const LATENCY: pa::Time = 0.0; // Ignored by PortAudio::is_*_format_supported.
const STANDARD_SAMPLE_RATES: [f64; 13] = [
8000.0, 9600.0, 11025.0, 12000.... |
}
println!(
"Supported standard sample rates for half-duplex 16-bit {} channel output:",
out_channels
);
for &sample_rate in &STANDARD_SAMPLE_RATES {
if pa
.is_output_format_supported(output_params, sample_rate)
.is_ok()... | {
println!("\t{}hz", sample_rate);
} | conditional_block |
devices.rs | //! The following is an adaptation of the "pa_devs.c" official PortAudio C example.
extern crate portaudio;
use portaudio as pa;
const INTERLEAVED: bool = true;
const LATENCY: pa::Time = 0.0; // Ignored by PortAudio::is_*_format_supported.
const STANDARD_SAMPLE_RATES: [f64; 13] = [
8000.0, 9600.0, 11025.0, 12000.... | Ok(())
} | }
| random_line_split |
windows.rs | use Func;
use kernel32;
use Lib;
use winapi::DWORD;
use Symbol;
#[test]
fn works_getlasterror() {
unsafe {
let lib = Lib::new("kernel32.dll").unwrap();
let gle: Func<extern "system" fn() -> DWORD> = lib.find_func("GetLastError").unwrap();
kernel32::SetLastError(42);
assert_eq!(kerne... | () {
unsafe { Lib::new("kernel23").err().unwrap() };
}
| fails_new_kernel23 | identifier_name |
windows.rs | use Func;
use kernel32;
use Lib;
use winapi::DWORD;
use Symbol;
#[test]
fn works_getlasterror() {
unsafe {
let lib = Lib::new("kernel32.dll").unwrap(); | }
#[test]
fn works_getlasterror0() {
unsafe {
let lib = Lib::new("kernel32.dll").unwrap();
let gle: Func<extern "system" fn() -> DWORD> = lib.find_func("GetLastError\0").unwrap();
kernel32::SetLastError(42);
assert_eq!(kernel32::GetLastError(), gle.get()());
}
}
#[test]
fn fail... | let gle: Func<extern "system" fn() -> DWORD> = lib.find_func("GetLastError").unwrap();
kernel32::SetLastError(42);
assert_eq!(kernel32::GetLastError(), gle.get()());
} | random_line_split |
windows.rs | use Func;
use kernel32;
use Lib;
use winapi::DWORD;
use Symbol;
#[test]
fn works_getlasterror() |
#[test]
fn works_getlasterror0() {
unsafe {
let lib = Lib::new("kernel32.dll").unwrap();
let gle: Func<extern "system" fn() -> DWORD> = lib.find_func("GetLastError\0").unwrap();
kernel32::SetLastError(42);
assert_eq!(kernel32::GetLastError(), gle.get()());
}
}
#[test]
fn fails... | {
unsafe {
let lib = Lib::new("kernel32.dll").unwrap();
let gle: Func<extern "system" fn() -> DWORD> = lib.find_func("GetLastError").unwrap();
kernel32::SetLastError(42);
assert_eq!(kernel32::GetLastError(), gle.get()());
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.