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 |
|---|---|---|---|---|
adding_prob_src.rs | extern crate rand;
use rand::distributions::{Range, IndependentSample};
use af;
use af::{Array, Dim4, MatProp, DType};
use std::cell::{RefCell, Cell};
use initializations::uniform;
use utils;
use data::{Data, DataSource, DataParams, Normalize, Shuffle};
pub struct AddingProblemSource {
pub params: DataParams,
pu... |
self.iter.set(self.iter.get() + 1);
batch
}
fn info(&self) -> DataParams {
self.params.clone()
}
fn get_test_iter(&self, num_batch: u64) -> Data {
self.get_train_iter(num_batch)
}
fn get_validation_iter(&self, num_batch: u64) -> Option<Data> {
Some( self.get_train_iter(num_batch))
... | {
self.params.current_epoch.set(current_iter + 1);
self.iter.set(0);
} | conditional_block |
adding_prob_src.rs | extern crate rand;
use rand::distributions::{Range, IndependentSample};
use af;
use af::{Array, Dim4, MatProp, DType};
use std::cell::{RefCell, Cell};
use initializations::uniform;
use utils;
use data::{Data, DataSource, DataParams, Normalize, Shuffle};
pub struct AddingProblemSource {
pub params: DataParams,
pu... | (&self, batch_size: u64, bptt_unroll: u64) -> Array {
let dim1 = Dim4::new(&[batch_size, 1, bptt_unroll/2, 1]);
let ar1 = uniform::<f32>(dim1,-1.0, 1.0);
let between1 = Range::new(0, bptt_unroll/4);
let between2 = Range::new(bptt_unroll/4, bptt_unroll/2);
let mut rng1 = rand::thread_rng();
let ... | generate_input | identifier_name |
adding_prob_src.rs | extern crate rand;
use rand::distributions::{Range, IndependentSample};
use af;
use af::{Array, Dim4, MatProp, DType};
use std::cell::{RefCell, Cell};
use initializations::uniform;
use utils;
use data::{Data, DataSource, DataParams, Normalize, Shuffle};
pub struct AddingProblemSource {
pub params: DataParams,
pu... | iter: Cell::new(0),
offset: Cell::new(0.0f32),
bptt_unroll: bptt_unroll,
}
}
fn generate_input(&self, batch_size: u64, bptt_unroll: u64) -> Array {
let dim1 = Dim4::new(&[batch_size, 1, bptt_unroll/2, 1]);
let ar1 = uniform::<f32>(dim1,-1.0, 1.0);
let between1 = Range::new(0, bp... | {
assert!(bptt_unroll % 4 == 0, "The number of time steps has to be divisible by 4 for the adding problem");
let input_dims = Dim4::new(&[batch_size, 1, bptt_unroll, 1]);
let target_dims = Dim4::new(&[batch_size, 1, bptt_unroll, 1]);
let train_samples = 0.7 * max_samples as f32;
let test_samples = 0... | identifier_body |
lib.rs | #![recursion_limit = "256"]
//! This module provides the render environment.
//!
//! OrbTk has choosen the [tinyskia] crate to handle all 2D rendering
//! tasks. Implemented as wrapper functions, it consumes the native
//! rendering functions provided from tinyskia.
//!
//! [tinyskia]: https://docs.rs/tiny-skia
use s... | /// Draws the ctx of the pipeline.
fn draw_pipeline(&self, image: &mut RenderTarget) {
self.draw(image);
}
}
impl PartialEq for Box<dyn PipelineTrait> {
fn eq(&self, other: &Box<dyn PipelineTrait>) -> bool {
self.box_eq(other.as_any())
}
}
impl Clone for Box<dyn PipelineTrait> {
... | /// Clones self as box.
fn clone_box(&self) -> Box<dyn PipelineTrait>;
| random_line_split |
lib.rs | #![recursion_limit = "256"]
//! This module provides the render environment.
//!
//! OrbTk has choosen the [tinyskia] crate to handle all 2D rendering
//! tasks. Implemented as wrapper functions, it consumes the native
//! rendering functions provided from tinyskia.
//!
//! [tinyskia]: https://docs.rs/tiny-skia
use s... | {
pub width: f64,
pub height: f64,
}
/// Internal font helper.
#[derive(Default, Clone, PartialEq, Debug)]
pub struct FontConfig {
pub family: String,
pub font_size: f64,
}
impl ToString for FontConfig {
fn to_string(&self) -> String {
format!("{}px {}", self.font_size, self.family)
}... | TextMetrics | identifier_name |
tlb.rs | use memory::VAddr;
use super::{Page, VirtualPage};
/// Invalidate the TLB completely by reloading the CR3 register.
///
/// # Safety
/// + Causes a general protection fault if not executed in kernel mode.
pub unsafe fn flush_all() {
use cpu::control_regs::cr3;
cr3::write(cr3::read());
}
/// Something which ma... | (self) {
self.base().invlpg()
}
}
| invlpg | identifier_name |
tlb.rs | use memory::VAddr;
use super::{Page, VirtualPage};
/// Invalidate the TLB completely by reloading the CR3 register.
///
/// # Safety
/// + Causes a general protection fault if not executed in kernel mode.
pub unsafe fn flush_all() {
use cpu::control_regs::cr3;
cr3::write(cr3::read());
}
/// Something which ma... | }
impl Flush for VAddr {
#[inline]
unsafe fn invlpg(self) {
asm!( "invlpg [$0]"
:
: "r" (*self)
: "memory"
: "intel", "volatile" );
}
}
impl Flush for VirtualPage {
#[inline]
unsafe fn invlpg(self) {
self.base().invlpg()
}
} | random_line_split | |
tlb.rs | use memory::VAddr;
use super::{Page, VirtualPage};
/// Invalidate the TLB completely by reloading the CR3 register.
///
/// # Safety
/// + Causes a general protection fault if not executed in kernel mode.
pub unsafe fn flush_all() {
use cpu::control_regs::cr3;
cr3::write(cr3::read());
}
/// Something which ma... |
}
impl Flush for VirtualPage {
#[inline]
unsafe fn invlpg(self) {
self.base().invlpg()
}
}
| {
asm!( "invlpg [$0]"
:
: "r" (*self)
: "memory"
: "intel", "volatile" );
} | identifier_body |
outline.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" />
<%helpers:shorthand name="outline"
sub_... | <W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
use values::generics::border::BorderCornerRadius;
let LonghandsToSerialize {
_moz_outline_radius_topleft: &BorderCornerRadius(ref tl),
_moz_outline_radius_topright: &BorderCornerRadius(ref t... | to_css | identifier_name |
outline.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" />
<%helpers:shorthand name="outline"
sub_... |
}
</%helpers:shorthand>
| {
use values::generics::border::BorderCornerRadius;
let LonghandsToSerialize {
_moz_outline_radius_topleft: &BorderCornerRadius(ref tl),
_moz_outline_radius_topright: &BorderCornerRadius(ref tr),
_moz_outline_radius_bottomright: &BorderCornerRadiu... | identifier_body |
outline.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" />
<%helpers:shorthand name="outline"
sub_... |
if width.is_none() {
if let Ok(value) = input.try(|input| outline_width::parse(context, input)) {
width = Some(value);
any = true;
continue
}
}
break
}
if any {
Ok... | {
if let Ok(value) = input.try(|input| outline_style::parse(context, input)) {
style = Some(value);
any = true;
continue
}
} | conditional_block |
outline.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" />
<%helpers:shorthand name="outline"
sub_... | BorderRadius::serialize_rects(widths, heights, dest)
}
}
</%helpers:shorthand> | random_line_split | |
context.rs | use std::io;
use std::error;
use std::fmt;
use std::os::raw::{c_int, c_long};
use std::path::Path;
use ::get_error;
use ::rwops::RWops;
use ::version::Version;
use sys::ttf;
use super::font::{
internal_load_font,
internal_load_font_at_index,
internal_load_font_from_ll,
Font,
};
/// A context manager f... |
/// Returns whether library has been initialized already.
pub fn has_been_initialized() -> bool {
unsafe {
ttf::TTF_WasInit() == 1
}
}
| {
unsafe {
if ttf::TTF_WasInit() == 1 {
Err(InitError::AlreadyInitializedError)
} else if ttf::TTF_Init() == 0 {
Ok(Sdl2TtfContext)
} else {
Err(InitError::InitializationError(
io::Error::last_os_error()
))
}
... | identifier_body |
context.rs | use std::io;
use std::error;
use std::fmt;
use std::os::raw::{c_int, c_long};
use std::path::Path;
use ::get_error;
use ::rwops::RWops;
use ::version::Version;
use sys::ttf;
use super::font::{
internal_load_font,
internal_load_font_at_index,
internal_load_font_from_ll,
Font,
};
/// A context manager f... | <'ttf,'r>(&'ttf self, rwops: RWops<'r>, index: u32,
point_size: u16) -> Result<Font<'ttf,'r>, String> {
let raw = unsafe {
ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int,
index as c_long)
};
if (raw as *mut ()).is_null() {
Err(get... | load_font_at_index_from_rwops | identifier_name |
context.rs | use std::io;
use std::error;
use std::fmt;
use std::os::raw::{c_int, c_long};
use std::path::Path;
use ::get_error;
use ::rwops::RWops;
use ::version::Version;
use sys::ttf;
use super::font::{
internal_load_font,
internal_load_font_at_index,
internal_load_font_from_ll,
Font,
};
/// A context manager f... | if ttf::TTF_WasInit() == 1 {
Err(InitError::AlreadyInitializedError)
} else if ttf::TTF_Init() == 0 {
Ok(Sdl2TtfContext)
} else {
Err(InitError::InitializationError(
io::Error::last_os_error()
))
}
}
}
/// Retur... | /// Initializes the truetype font API and returns a context manager which will
/// clean up the library once it goes out of scope.
pub fn init() -> Result<Sdl2TtfContext, InitError> {
unsafe { | random_line_split |
term-gradient.rs | use calx::{term_color, PseudoTermColor};
fn print(t: &mut Box<term::StdoutTerminal>, c: PseudoTermColor) {
t.reset().unwrap();
let fg;
match c {
PseudoTermColor::Mixed { fore, back, mix: _ } => {
fg = u32::from(fore);
t.bg(u32::from(back)).unwrap();
}
PseudoT... | () {
let mut t = term::stdout().unwrap();
for x in 0..80 {
let a = (x as f32) / 80.0;
let c = calx::lerp(term_color::MAROON, term_color::YELLOW, a);
print(&mut t, c);
}
let _ = t.reset();
println!();
let mut path = calx::LerpPath::new((0.0f32, term_color::BLACK), (1.0f3... | main | identifier_name |
term-gradient.rs | use calx::{term_color, PseudoTermColor};
fn print(t: &mut Box<term::StdoutTerminal>, c: PseudoTermColor) {
t.reset().unwrap();
let fg;
match c {
PseudoTermColor::Mixed { fore, back, mix: _ } => {
fg = u32::from(fore);
t.bg(u32::from(back)).unwrap();
}
PseudoT... | }
let _ = t.reset();
println!();
}
| {
let mut t = term::stdout().unwrap();
for x in 0..80 {
let a = (x as f32) / 80.0;
let c = calx::lerp(term_color::MAROON, term_color::YELLOW, a);
print(&mut t, c);
}
let _ = t.reset();
println!();
let mut path = calx::LerpPath::new((0.0f32, term_color::BLACK), (1.0f32, ... | identifier_body |
term-gradient.rs | use calx::{term_color, PseudoTermColor};
fn print(t: &mut Box<term::StdoutTerminal>, c: PseudoTermColor) {
t.reset().unwrap();
let fg;
match c {
PseudoTermColor::Mixed { fore, back, mix: _ } => {
fg = u32::from(fore);
t.bg(u32::from(back)).unwrap();
}
PseudoT... | path.add((0.20, term_color::NAVY));
path.add((0.40, term_color::BLUE));
path.add((0.60, term_color::TEAL));
path.add((0.80, term_color::AQUA));
path.add((0.90, term_color::WHITE));
for x in 0..80 {
let a = (x as f32) / 80.0;
print(&mut t, path.sample(a));
}
let _ = t.rese... | let mut path = calx::LerpPath::new((0.0f32, term_color::BLACK), (1.0f32, term_color::YELLOW)); | random_line_split |
lib.rs | //! A C-compatible foreign function interface to Weld.
//!
//! This crate provides a C-compatible interface to the Weld library and is compiled as a shared
//! library and a static library.
//!
//! See the docs for the main Weld crate for more details on these functions.
use weld;
use libc::{c_char, c_void, int64_t, ... | (
code: *const c_char,
conf: weld_conf_t,
err: weld_error_t,
) -> weld_module_t {
let code = code.to_str();
let conf = conf as *mut weld::WeldConf;
let conf = &*conf;
let err = err as *mut weld::WeldError;
let err = &mut *err;
match weld::WeldModule::compile(code, conf) {
Ok(... | weld_module_compile | identifier_name |
lib.rs | //! A C-compatible foreign function interface to Weld.
//!
//! This crate provides a C-compatible interface to the Weld library and is compiled as a shared
//! library and a static library.
//!
//! See the docs for the main Weld crate for more details on these functions.
use weld;
use libc::{c_char, c_void, int64_t, ... |
}
#[no_mangle]
/// Creates a new configuration.
///
/// This function is a wrapper for `WeldConf::new`.
pub extern "C" fn weld_conf_new() -> weld_conf_t {
Box::into_raw(Box::new(weld::WeldConf::new())) as _
}
#[no_mangle]
/// Free a configuration.
///
/// The passsed configuration should have been allocated usin... | {
Box::from_raw(context);
} | conditional_block |
lib.rs | //! A C-compatible foreign function interface to Weld.
//!
//! This crate provides a C-compatible interface to the Weld library and is compiled as a shared
//! library and a static library.
//!
//! See the docs for the main Weld crate for more details on these functions.
use weld;
use libc::{c_char, c_void, int64_t, ... |
#[no_mangle]
/// Returns a Weld error message.
///
/// This function is a wrapper for `WeldError::message`.
pub unsafe extern "C" fn weld_error_message(err: weld_error_t) -> *const c_char {
let err = err as *mut weld::WeldError;
let err = &*err;
err.message().as_ptr()
}
#[no_mangle]
/// Frees a Weld erro... | {
let err = err as *mut weld::WeldError;
let err = &*err;
err.code() as _
} | identifier_body |
lib.rs | //! A C-compatible foreign function interface to Weld.
//!
//! This crate provides a C-compatible interface to the Weld library and is compiled as a shared
//! library and a static library.
//!
//! See the docs for the main Weld crate for more details on these functions.
use weld;
use libc::{c_char, c_void, int64_t, ... | err.code() as _
}
#[no_mangle]
/// Returns a Weld error message.
///
/// This function is a wrapper for `WeldError::message`.
pub unsafe extern "C" fn weld_error_message(err: weld_error_t) -> *const c_char {
let err = err as *mut weld::WeldError;
let err = &*err;
err.message().as_ptr()
}
#[no_mangle]
... | let err = err as *mut weld::WeldError;
let err = &*err; | random_line_split |
body.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::error::{Error, Fallible... | (bytes: Vec<u8>) -> Fallible<FetchedData> {
Ok(FetchedData::Text(String::from_utf8_lossy(&bytes).into_owned()))
}
#[allow(unsafe_code)]
fn run_json_data_algorithm(cx: *mut JSContext,
bytes: Vec<u8>) -> Fallible<FetchedData> {
let json_text = String::from_utf8_lossy(&bytes);
let j... | run_text_data_algorithm | identifier_name |
body.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::error::{Error, Fallible... | };
},
Err(err) => promise.reject_error(err),
}
}
// https://fetch.spec.whatwg.org/#concept-body-package-data
#[allow(unsafe_code)]
fn run_package_data_algorithm<T: BodyOperations + DomObject>(object: &T,
bytes: Vec<u8>,
... | {
// Step 5
let body = match object.take_body() {
Some(body) => body,
None => return,
};
let pkg_data_results = run_package_data_algorithm(object,
body,
body_type,
... | identifier_body |
body.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::error::{Error, Fallible... | Json(RootedTraceableBox<Heap<JSValue>>),
BlobData(DomRoot<Blob>),
FormData(DomRoot<FormData>),
ArrayBuffer(RootedTraceableBox<Heap<*mut JSObject>>),
}
// https://fetch.spec.whatwg.org/#concept-body-consume-body
#[allow(unrooted_must_root)]
pub fn consume_body<T: BodyOperations + DomObject>(object: &T, ... | }
pub enum FetchedData {
Text(String), | random_line_split |
lib.rs | // safesec/safesec-derive/src/lib.rs
// Copyright (C) 2017 authors and contributors (see AUTHORS file)
//
// This file is released under the MIT License.
// ===========================================================================
// Externs
// ========================================================================... | (&self) -> Option<u64> {
match self.num {
&syn::Lit::Int(num, _) => Some(num),
_ => None
}
}
}
fn impl_code_convert(ast: &syn::MacroInput) -> quote::Tokens {
if let syn::Body::Enum(ref body) = ast.body {
let name = &ast.ident;
let mut num = 0;
l... | to_u64 | identifier_name |
lib.rs | // safesec/safesec-derive/src/lib.rs
// Copyright (C) 2017 authors and contributors (see AUTHORS file)
//
// This file is released under the MIT License.
// ===========================================================================
// Externs
// ========================================================================... | }
}
}
} else {
panic!("#[derive(CodeConvert)] is only defined for enums not structs");
}
}
// ===========================================================================
// Tests
// ===========================================================================
// #[c... | self.clone() as u8 | random_line_split |
strings.rs | //! Functions operating on strings.
use std::ptr;
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{make_unibyte_string, make_uninit_multibyte_string,
string_to_multibyte as c_string_to_multibyte};
use remacs_sys::EmacsInt;
use lisp::LispObject;
use lisp::defsubr;
use multibyte;
pub static MI... |
/// Return the number of bytes in STRING.
/// If STRING is multibyte, this may be greater than the length of STRING.
#[lisp_fn]
pub fn string_bytes(string: LispObject) -> LispObject {
let string = string.as_string_or_error();
LispObject::from_natnum(string.len_bytes() as EmacsInt)
}
/// Return t if two strin... | {
LispObject::from_bool(object.is_string())
} | identifier_body |
strings.rs | //! Functions operating on strings.
use std::ptr;
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{make_unibyte_string, make_uninit_multibyte_string,
string_to_multibyte as c_string_to_multibyte};
use remacs_sys::EmacsInt;
use lisp::LispObject;
use lisp::defsubr;
use multibyte;
pub static MI... | let _ = string.as_string_or_error();
unsafe { LispObject::from(c_string_to_multibyte(string.to_raw())) }
}
/// Return a unibyte string with the same individual chars as STRING.
/// If STRING is unibyte, the result is STRING itself.
/// Otherwise it is a newly created string, with no text properties,
/// where ... | /// utf-8 sequence to an eight-bit character, not just bytes that don't form a
/// correct sequence.
#[lisp_fn]
pub fn string_to_multibyte(string: LispObject) -> LispObject { | random_line_split |
strings.rs | //! Functions operating on strings.
use std::ptr;
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{make_unibyte_string, make_uninit_multibyte_string,
string_to_multibyte as c_string_to_multibyte};
use remacs_sys::EmacsInt;
use lisp::LispObject;
use lisp::defsubr;
use multibyte;
pub static MI... |
}
/// Return non-nil if STRING1 is less than STRING2 in lexicographic order.
/// Case is significant.
#[lisp_fn]
pub fn string_lessp(string1: LispObject, string2: LispObject) -> LispObject {
let s1 = LispObject::symbol_or_string_as_string(string1);
let s2 = LispObject::symbol_or_string_as_string(string2);
... | {
string
} | conditional_block |
strings.rs | //! Functions operating on strings.
use std::ptr;
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{make_unibyte_string, make_uninit_multibyte_string,
string_to_multibyte as c_string_to_multibyte};
use remacs_sys::EmacsInt;
use lisp::LispObject;
use lisp::defsubr;
use multibyte;
pub static MI... | () {
let string = mock_unibyte_string!("Hello World");
let string2 = mock_unibyte_string!("World Hello");
assert_t!(string_lessp(string, string2));
assert_nil!(string_lessp(string2, string));
}
| test_stringlessp | identifier_name |
facts.rs | use crate::borrow_check::location::{LocationIndex, LocationTable};
use crate::dataflow::indexes::{BorrowIndex, MovePathIndex};
use polonius_engine::AllFacts as PoloniusFacts;
use polonius_engine::Atom;
use rustc_index::vec::Idx;
use rustc_middle::mir::Local;
use rustc_middle::ty::{RegionVid, TyCtxt};
use std::error::Er... | <T>(&self, rows: &[T], file_name: &str) -> Result<(), Box<dyn Error>>
where
T: FactRow,
{
let file = &self.dir.join(file_name);
let mut file = BufWriter::new(File::create(file)?);
for row in rows {
row.write(&mut file, self.location_table)?;
}
Ok(())
... | write_facts_to_path | identifier_name |
facts.rs | use crate::borrow_check::location::{LocationIndex, LocationTable};
use crate::dataflow::indexes::{BorrowIndex, MovePathIndex};
use polonius_engine::AllFacts as PoloniusFacts;
use polonius_engine::Atom;
use rustc_index::vec::Idx;
use rustc_middle::mir::Local;
use rustc_middle::ty::{RegionVid, TyCtxt};
use std::error::Er... | ;
write!(out, "{:?}{}", c.to_string(location_table), tail)?;
}
Ok(())
}
trait FactCell {
fn to_string(&self, location_table: &LocationTable) -> String;
}
impl<A: Debug> FactCell for A {
default fn to_string(&self, _location_table: &LocationTable) -> String {
format!("{:?}", self)
}... | { "\t" } | conditional_block |
facts.rs | use crate::borrow_check::location::{LocationIndex, LocationTable};
use crate::dataflow::indexes::{BorrowIndex, MovePathIndex};
use polonius_engine::AllFacts as PoloniusFacts;
use polonius_engine::Atom;
use rustc_index::vec::Idx;
use rustc_middle::mir::Local;
use rustc_middle::ty::{RegionVid, TyCtxt};
use std::error::Er... | wr.write_facts_to_path(self.[
loan_issued_at,
universal_region,
cfg_edge,
loan_killed_at,
subset_base,
loan_invalidated_at,
var_used_at,
var_defined_at,
var_dropped... | )?;
)*
}
}
write_facts_to_path! { | random_line_split |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::{ConsoleLogger, FileKey};
use fixture_tests::Fixture;
use fnv::FnvHashMap;
use graphql_ir::{build, Program};
use graphq... | .into_iter()
.map(|frag| relay_typegen::generate_operation_type(frag, &schema));
let mut fragments: Vec<_> = programs.typegen.fragments().collect();
fragments.sort_by_key(|frag| frag.name.item);
let fragment_strings = fragments
.into_iter()
.map(|frag| relay_typegen::generate_fr... | {
let mut sources = FnvHashMap::default();
sources.insert(FileKey::new(fixture.file_name), fixture.content);
let schema = test_schema();
let ast = parse(fixture.content, FileKey::new(fixture.file_name)).unwrap();
let ir = build(&schema, &ast.definitions).unwrap();
let program = Program::from_def... | identifier_body |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::{ConsoleLogger, FileKey};
use fixture_tests::Fixture;
use fnv::FnvHashMap;
use graphql_ir::{build, Program};
use graphq... | (fixture: &Fixture) -> Result<String, String> {
let mut sources = FnvHashMap::default();
sources.insert(FileKey::new(fixture.file_name), fixture.content);
let schema = test_schema();
let ast = parse(fixture.content, FileKey::new(fixture.file_name)).unwrap();
let ir = build(&schema, &ast.definitions)... | transform_fixture | identifier_name |
find.rs | use schema::*;
use diesel::*;
#[test]
fn find() {
use schema::users::table as users; | let connection = connection();
connection.execute("INSERT INTO users (id, name) VALUES (1, 'Sean'), (2, 'Tess')")
.unwrap();
assert_eq!(Ok(User::new(1, "Sean")), users.find(1).first(&connection));
assert_eq!(Ok(User::new(2, "Tess")), users.find(2).first(&connection));
assert_eq!(Ok(None::<U... | random_line_split | |
find.rs | use schema::*;
use diesel::*;
#[test]
fn find() {
use schema::users::table as users;
let connection = connection();
connection.execute("INSERT INTO users (id, name) VALUES (1, 'Sean'), (2, 'Tess')")
.unwrap();
assert_eq!(Ok(User::new(1, "Sean")), users.find(1).first(&connection));
assert_... | () {
use self::users_with_name_pk::table as users;
let connection = connection();
connection.execute("CREATE TABLE users_with_name_pk (name VARCHAR PRIMARY KEY)")
.unwrap();
connection.execute("INSERT INTO users_with_name_pk (name) VALUES ('Sean'), ('Tess')")
.unwrap();
assert_eq!(Ok... | find_with_non_serial_pk | identifier_name |
find.rs | use schema::*;
use diesel::*;
#[test]
fn find() |
table! {
users_with_name_pk (name) {
name -> VarChar,
}
}
#[test]
fn find_with_non_serial_pk() {
use self::users_with_name_pk::table as users;
let connection = connection();
connection.execute("CREATE TABLE users_with_name_pk (name VARCHAR PRIMARY KEY)")
.unwrap();
connection.... | {
use schema::users::table as users;
let connection = connection();
connection.execute("INSERT INTO users (id, name) VALUES (1, 'Sean'), (2, 'Tess')")
.unwrap();
assert_eq!(Ok(User::new(1, "Sean")), users.find(1).first(&connection));
assert_eq!(Ok(User::new(2, "Tess")), users.find(2).firs... | identifier_body |
mod.rs | use async_trait::async_trait;
use yaml_rust::Yaml;
mod assert;
mod assign;
mod delay;
mod exec;
mod request;
pub use self::assert::Assert;
pub use self::assign::Assign;
pub use self::delay::Delay;
pub use self::exec::Exec;
pub use self::request::Request;
use crate::benchmark::{Context, Pool, Reports};
use crate::con... | else {
None
}
}
}
pub fn extract<'a>(item: &'a Yaml, attr: &'a str) -> &'a str {
if let Some(s) = item[attr].as_str() {
s
} else {
if item[attr].as_hash().is_some() {
panic!("`{}` is required needs to be a string. Try adding quotes", attr);
} else {
panic!("Unknown node `{}` =>... | {
panic!("`{}` needs to be a string. Try adding quotes", attr);
} | conditional_block |
mod.rs | use async_trait::async_trait;
use yaml_rust::Yaml;
mod assert;
mod assign;
mod delay;
mod exec;
mod request;
pub use self::assert::Assert;
pub use self::assign::Assign;
pub use self::delay::Delay;
pub use self::exec::Exec;
pub use self::request::Request;
use crate::benchmark::{Context, Pool, Reports};
use crate::con... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n- name: {}\n duration: {}\n", self.name, self.duration)
}
}
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n- name: {}\n duration: {}\n status: {}\n", self.name, self.duration, self.status)
... | fmt | identifier_name |
mod.rs | use async_trait::async_trait;
use yaml_rust::Yaml;
mod assert;
mod assign;
mod delay;
mod exec; | mod request;
pub use self::assert::Assert;
pub use self::assign::Assign;
pub use self::delay::Delay;
pub use self::exec::Exec;
pub use self::request::Request;
use crate::benchmark::{Context, Pool, Reports};
use crate::config::Config;
use std::fmt;
#[async_trait]
pub trait Runnable {
async fn execute(&self, contex... | random_line_split | |
try_join_all.rs | use futures_util::future::*;
use std::future::Future;
use futures::executor::block_on;
use std::fmt::Debug;
fn assert_done<T, F>(actual_fut: F, expected: T)
where
T: PartialEq + Debug,
F: FnOnce() -> Box<dyn Future<Output = T> + Unpin>,
{
let output = block_on(actual_fut());
assert_eq!(output, expected... | #[test]
fn try_join_all_iter_lifetime() {
// In futures-rs version 0.1, this function would fail to typecheck due to an overly
// conservative type parameterization of `TryJoinAll`.
fn sizes<'a>(bufs: Vec<&'a [u8]>) -> Box<dyn Future<Output = Result<Vec<usize>, ()>> + Unpin> {
let iter = bufs.into_i... |
// TODO: needs more tests
}
| random_line_split |
try_join_all.rs | use futures_util::future::*;
use std::future::Future;
use futures::executor::block_on;
use std::fmt::Debug;
fn assert_done<T, F>(actual_fut: F, expected: T)
where
T: PartialEq + Debug,
F: FnOnce() -> Box<dyn Future<Output = T> + Unpin>,
{
let output = block_on(actual_fut());
assert_eq!(output, expected... |
#[test]
fn try_join_all_iter_lifetime() {
// In futures-rs version 0.1, this function would fail to typecheck due to an overly
// conservative type parameterization of `TryJoinAll`.
fn sizes<'a>(bufs: Vec<&'a [u8]>) -> Box<dyn Future<Output = Result<Vec<usize>, ()>> + Unpin> {
let iter = bufs.into... | {
assert_done(|| Box::new(try_join_all(vec![ok(1), ok(2)])), Ok::<_, usize>(vec![1, 2]));
assert_done(|| Box::new(try_join_all(vec![ok(1), err(2)])), Err(2));
assert_done(|| Box::new(try_join_all(vec![ok(1)])), Ok::<_, usize>(vec![1]));
// REVIEW: should this be implemented?
// assert_done(|| Box::n... | identifier_body |
try_join_all.rs | use futures_util::future::*;
use std::future::Future;
use futures::executor::block_on;
use std::fmt::Debug;
fn assert_done<T, F>(actual_fut: F, expected: T)
where
T: PartialEq + Debug,
F: FnOnce() -> Box<dyn Future<Output = T> + Unpin>,
{
let output = block_on(actual_fut());
assert_eq!(output, expected... | <'a>(bufs: Vec<&'a [u8]>) -> Box<dyn Future<Output = Result<Vec<usize>, ()>> + Unpin> {
let iter = bufs.into_iter().map(|b| ok::<usize, ()>(b.len()));
Box::new(try_join_all(iter))
}
assert_done(|| sizes(vec![&[1,2,3], &[], &[0]]), Ok(vec![3 as usize, 0, 1]));
}
#[test]
fn try_join_all_from_ite... | sizes | identifier_name |
pong.rs | use piston::event::*;
use piston::input::Button::Keyboard;
use piston::input::keyboard::Key;
use glutin_window::GlutinWindow as Window;
use piston::window::WindowSettings;
use opengl_graphics::{ GlGraphics, OpenGL };
use game_object::GameObject;
static OPENGL_VERSION: OpenGL = OpenGL::_3_2;
static SIZE: [u32; 2] = [51... | (&mut self, args: &UpdateArgs) {
let (ai_up, ai_down) = self.handle_ai_paddle();
Pong::handle_paddle(&mut self.p1, self.up, self.down, args.dt);
Pong::handle_paddle(&mut self.p2, ai_up, ai_down, args.dt);
Pong::handle_game_object(&mut self.p1, args.dt, false);
Pong::handle_game_... | update | identifier_name |
pong.rs | use piston::event::*;
use piston::input::Button::Keyboard;
use piston::input::keyboard::Key;
use glutin_window::GlutinWindow as Window;
use piston::window::WindowSettings;
use opengl_graphics::{ GlGraphics, OpenGL };
use game_object::GameObject;
static OPENGL_VERSION: OpenGL = OpenGL::_3_2;
static SIZE: [u32; 2] = [51... | fn start(&mut self) {
self.p1.pos = [self.p1.size[0] / 2.0 + 4.0, (SIZE[1] / 2) as f64];
self.p2.pos = [SIZE[0] as f64 - self.p2.size[0] / 2.0 - 4.0,
(SIZE[1] / 2) as f64];
self.reset();
}
fn reset(&mut self) {
use std::f64::consts::PI;
use rand;... | random_line_split | |
pong.rs | use piston::event::*;
use piston::input::Button::Keyboard;
use piston::input::keyboard::Key;
use glutin_window::GlutinWindow as Window;
use piston::window::WindowSettings;
use opengl_graphics::{ GlGraphics, OpenGL };
use game_object::GameObject;
static OPENGL_VERSION: OpenGL = OpenGL::_3_2;
static SIZE: [u32; 2] = [51... |
fn score(&mut self, player: Player) {
match player {
Player::Left => {
self.server = Player::Right;
self.p1_score += 1;
println!("Player 1 scored! {}-{}", self.p1_score,
self.p2_score);
}
Player::Ri... | {
if normal == [1.0, 0.0] {
a.pos[0] = b.pos[0] + b.size[0] / 2.0 + a.size[0] / 2.0;
} else if normal == [-1.0, 0.0] {
a.pos[0] = b.pos[0] - b.size[0] / 2.0 - a.size[0] / 2.0;
} else if normal == [0.0, 1.0] {
a.pos[1] = b.pos[1] + b.size[1] / 2.0 + a.size[1] /... | identifier_body |
pong.rs | use piston::event::*;
use piston::input::Button::Keyboard;
use piston::input::keyboard::Key;
use glutin_window::GlutinWindow as Window;
use piston::window::WindowSettings;
use opengl_graphics::{ GlGraphics, OpenGL };
use game_object::GameObject;
static OPENGL_VERSION: OpenGL = OpenGL::_3_2;
static SIZE: [u32; 2] = [51... |
}
}
| { pong.key_release(key); } | conditional_block |
display_list_builder.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/. */
//! Constructs display lists from render boxes.
use layout::box::RenderBox;
use layout::context::LayoutContext;
u... | (box: RenderBox) -> AbstractNode<()> {
unsafe {
transmute(box.node())
}
}
}
impl ExtraDisplayListData for Nothing {
fn new(_: RenderBox) -> Nothing {
()
}
}
impl ExtraDisplayListData for RenderBox {
fn new(box: RenderBox) -> RenderBox {
box
}
}
/// A ... | new | identifier_name |
display_list_builder.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/. */
//! Constructs display lists from render boxes.
use layout::box::RenderBox;
use layout::context::LayoutContext;
u... |
pub type Nothing = ();
impl ExtraDisplayListData for AbstractNode<()> {
fn new (box: RenderBox) -> AbstractNode<()> {
unsafe {
transmute(box.node())
}
}
}
impl ExtraDisplayListData for Nothing {
fn new(_: RenderBox) -> Nothing {
()
}
}
impl ExtraDisplayListData f... | /// store the nodes in the display list and have layout transmute them.
pub trait ExtraDisplayListData {
fn new(box: RenderBox) -> Self;
} | random_line_split |
randomx_hash.rs | extern crate mithril; | #[allow(overflowing_literals)]
fn test_gen_program_aes_1rx4() {
//nonce 1000 randomx-codegen
let input0 = m128i::from_i32(0x31903876, 0xbb7a2914, 0xb370f616, 0xd6f7e4f3);
let input1 = m128i::from_i32(0xb5a8ef67, 0x749809c8, 0xf349884a, 0x05c9f5ef);
let input2 = m128i::from_i32(0xa9a93ab0, 0x22e46d0a, 0x... |
use mithril::randomx::hash::{gen_program_aes_1rx4, gen_program_aes_4rx4};
use mithril::randomx::m128::m128i;
#[test] | random_line_split |
randomx_hash.rs | extern crate mithril;
use mithril::randomx::hash::{gen_program_aes_1rx4, gen_program_aes_4rx4};
use mithril::randomx::m128::m128i;
#[test]
#[allow(overflowing_literals)]
fn test_gen_program_aes_1rx4() {
//nonce 1000 randomx-codegen
let input0 = m128i::from_i32(0x31903876, 0xbb7a2914, 0xb370f616, 0xd6f7e4f3);
... | () {
let input0 = m128i::from_i32(0xb53a90c9, 0xf56f1bc9, 0x25a4424b, 0x727ab1b2);
let input1 = m128i::from_i32(0x70152fd1, 0x377f234d, 0xe8027504, 0xfed70bc4);
let input2 = m128i::from_i32(0xae1f977a, 0x841fdb02, 0x85b20930, 0xf22cf15b);
let input3 = m128i::from_i32(0x2fd5f11, 0x28e94c44, 0x8a756cec, 0... | test_gen_program_aes_4rx4 | identifier_name |
randomx_hash.rs | extern crate mithril;
use mithril::randomx::hash::{gen_program_aes_1rx4, gen_program_aes_4rx4};
use mithril::randomx::m128::m128i;
#[test]
#[allow(overflowing_literals)]
fn test_gen_program_aes_1rx4() | m128i::from_i32(0xf31272c9, 0x187f3e37, 0x9ed29677, 0x9cb3cad8)
);
assert_eq!(
result[29],
m128i::from_i32(0xb979c03b, 0xf3851cd4, 0x8053d5c4, 0xf167e714)
);
assert_eq!(
result[59],
m128i::from_i32(0x9edf9671, 0x351efb59, 0x3cd79767, 0x15624b91)
);
assert_... | {
//nonce 1000 randomx-codegen
let input0 = m128i::from_i32(0x31903876, 0xbb7a2914, 0xb370f616, 0xd6f7e4f3);
let input1 = m128i::from_i32(0xb5a8ef67, 0x749809c8, 0xf349884a, 0x05c9f5ef);
let input2 = m128i::from_i32(0xa9a93ab0, 0x22e46d0a, 0x1a1fe305, 0xb42708c0);
let input3 = m128i::from_i32(0x6824... | 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 ... | type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
let diff = self.t as u64 - other.t as u64;
let nanos = mul_div_u64(diff, NANOS_PER_SEC, frequency() as u64);
Duration::new(nanos / NANOS_PER_SEC, (nanos % NANOS_PER_SEC) as u32)
}
}
// Computes (value*numer)/den... | }
impl<'a> Sub for &'a SteadyTime { | 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 ... | {
t: libc::LARGE_INTEGER,
}
impl SteadyTime {
pub fn now() -> SteadyTime {
let mut t = SteadyTime { t: 0 };
unsafe { libc::QueryPerformanceCounter(&mut t.t); }
t
}
}
fn frequency() -> libc::LARGE_INTEGER {
static mut FREQUENCY: libc::LARGE_INTEGER = 0;
static ONCE: Once = ... | SteadyTime | identifier_name |
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 ... |
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
let diff = self.t as u64 - other.t as u64;
let nanos = mul_div_u64(diff, NANOS_PER_SEC, frequency() as u64);
Duration::new(nanos / NANOS_PER_SEC, (nanos % NANOS_PER_SEC) as u32)
... | {
static mut FREQUENCY: libc::LARGE_INTEGER = 0;
static ONCE: Once = Once::new();
unsafe {
ONCE.call_once(|| {
libc::QueryPerformanceFrequency(&mut FREQUENCY);
});
FREQUENCY
}
} | identifier_body |
settings_ui.rs | extern crate objc;
use super::consts::*;
use super::cocoa_util::*;
use pref::*;
use core_graphics::*;
use tickeys::Tickeys;
use std::sync::{ONCE_INIT, Once};
use objc::runtime::*;
use cocoa::base::{class,id,nil};
use cocoa::foundation::NSString;
use cocoa::appkit::NSApp;
// naive way of make this a singleton
static ... | (this: &mut Object, _cmd: Sel, sender: id)
{
println!("Remove Item");
unsafe
{
let filterList = Self::filterList();
let table: id = msg_send![this, filterListTable];
let selectedRow: i32 = msg_send![table, selectedRow];
if selectedRow >= 0
{
let _: id = msg_send![filterList, removeObjectAtI... | btnRemoveClicked | identifier_name |
settings_ui.rs | extern crate objc;
use super::consts::*;
use super::cocoa_util::*;
use pref::*;
use core_graphics::*;
use tickeys::Tickeys;
use std::sync::{ONCE_INIT, Once};
use objc::runtime::*;
use cocoa::base::{class,id,nil};
use cocoa::foundation::NSString;
use cocoa::appkit::NSApp;
// naive way of make this a singleton
static ... | let _:id = msg_send![NSApp(), activateIgnoringOtherApps:true];
}
//-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
extern fn numberOfRowsInTableView(this: &mut Object, _cmd: Sel, tableView: id) -> i32
{
unsafe
{
msg_send![Self::filterList(), count]
}
}
fn filterList() -> id
{
unsafe
... | //let _:id = msg_send![this, show]
println!("makeKeyAndOrderFront:");
let win:id = msg_send![this, window];
let _:id = msg_send![win, makeKeyAndOrderFront:nil]; | random_line_split |
settings_ui.rs | extern crate objc;
use super::consts::*;
use super::cocoa_util::*;
use pref::*;
use core_graphics::*;
use tickeys::Tickeys;
use std::sync::{ONCE_INIT, Once};
use objc::runtime::*;
use cocoa::base::{class,id,nil};
use cocoa::foundation::NSString;
use cocoa::appkit::NSApp;
// naive way of make this a singleton
static ... |
}
impl SettingsController for id
{
}
| {
false
} | identifier_body |
lib.rs | #![feature(plugin_registrar, macro_rules)]
#![crate_type = "dylib"]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::codemap::{Span};
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, DummyResult};
use rustc::plugin::Registry;
use Severity::{Note, Warning, Error, Fatal};
enum Severity {
... | ast::LitInt(i, ast::SignedIntLit(_, ast::Plus)) |
ast::LitInt(i, ast::UnsuffixedIntLit(ast::Plus)) => {
accumulator.push_str(format!("{}", i).as_slice());
}
ast::LitInt(i, ast::SignedIntLit(_, ast::Minus)) |
... | random_line_split | |
lib.rs | #![feature(plugin_registrar, macro_rules)]
#![crate_type = "dylib"]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::codemap::{Span};
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, DummyResult};
use rustc::plugin::Registry;
use Severity::{Note, Warning, Error, Fatal};
enum Severity {
... |
ast::LitInt(i, ast::SignedIntLit(_, ast::Minus)) |
ast::LitInt(i, ast::UnsuffixedIntLit(ast::Minus)) => {
accumulator.push_str(format!("-{}", i).as_slice());
}
ast::LitBool(b) => {
accumulato... | {
accumulator.push_str(format!("{}", i).as_slice());
} | conditional_block |
lib.rs | #![feature(plugin_registrar, macro_rules)]
#![crate_type = "dylib"]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::codemap::{Span};
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, DummyResult};
use rustc::plugin::Registry;
use Severity::{Note, Warning, Error, Fatal};
enum Severity {
... | (sev: Severity,
cx: &mut ExtCtxt, sp: Span, args: &[ast::TokenTree]) -> Box<base::MacResult+'static> {
// copied from syntax::ext::concat.
let es = match base::get_exprs_from_tts(cx, sp, args) {
Some(e) => e,
None => return base::DummyResult::expr(sp)
};
let mut accumulator... | expand_msg | identifier_name |
simd-intrinsic-generic-scatter.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | extern "platform-intrinsic" {
fn simd_scatter<T, P, M>(value: T, pointers: P, mask: M);
}
// CHECK-LABEL: @scatter_f32x2
#[no_mangle]
pub unsafe fn scatter_f32x2(pointers: Vec2<*mut f32>, mask: Vec2<i32>,
values: Vec2<f32>) {
// CHECK: call void @llvm.masked.scatter.v2f32.v2p0f32(<2... |
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Vec4<T>(pub T, pub T, pub T, pub T);
| random_line_split |
simd-intrinsic-generic-scatter.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
// CHECK: call void @llvm.masked.scatter.v2p0f32.v2p0p0f32(<2 x float*> {{.*}}, <2 x float**> {{.*}}, i32 {{.*}}, <2 x i1> {{.*}})
simd_scatter(values, pointers, mask)
} | identifier_body | |
simd-intrinsic-generic-scatter.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (pointers: Vec2<*mut *const f32>, mask: Vec2<i32>,
values: Vec2<*const f32>) {
// CHECK: call void @llvm.masked.scatter.v2p0f32.v2p0p0f32(<2 x float*> {{.*}}, <2 x float**> {{.*}}, i32 {{.*}}, <2 x i1> {{.*}})
simd_scatter(values, pointers, mask)
}
| scatter_pf32x2 | identifier_name |
bad.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 ... | () {
}
| main | identifier_name |
bad.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 ... | {
} | identifier_body | |
bad.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 ... | fn main() {
} | #[cfg(good)] | random_line_split |
oneshot.rs | //! A one-shot, futures-aware channel
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::error::Error;
use std::fmt;
use {Future, Poll, Async};
use lock::Lock;
use task::{self, Task};
/// A future representing the completion of a computation happening elsewhere i... | /// Creates a new futures-aware, one-shot channel.
///
/// This function is similar to Rust's channels found in the standard library.
/// Two halves are returned, the first of which is a `Sender` handle, used to
/// signal the end of a computation and provide its value. The second half is a
/// `Receiver` which impleme... | }
| random_line_split |
oneshot.rs | //! A one-shot, futures-aware channel
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::error::Error;
use std::fmt;
use {Future, Poll, Async};
use lock::Lock;
use task::{self, Task};
/// A future representing the completion of a computation happening elsewhere i... |
}
impl Error for Canceled {
fn description(&self) -> &str {
"oneshot canceled"
}
}
impl<T> Receiver<T> {
/// Gracefully close this receiver, preventing sending any future messages.
///
/// Any `send` operation which happens after this method returns is
/// guaranteed to fail. Once thi... | {
write!(fmt, "oneshot canceled")
} | identifier_body |
oneshot.rs | //! A one-shot, futures-aware channel
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::error::Error;
use std::fmt;
use {Future, Poll, Async};
use lock::Lock;
use task::{self, Task};
/// A future representing the completion of a computation happening elsewhere i... | (self, t: T) {
// First up, flag that this method was called and then store the data.
// Note that this lock acquisition should always succeed as it can only
// interfere with `poll` in `Receiver` which is only called when the
// `complete` flag is true, which we're setting here.
... | complete | identifier_name |
semaphore.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 ... |
#[test]
fn test_sem_as_cvar() {
/* Child waits and parent signals */
let (tx, rx) = channel();
let s = Arc::new(Semaphore::new(0));
let s2 = s.clone();
let _t = thread::spawn(move|| {
s2.acquire();
tx.send(()).unwrap();
});
s.rele... | {
let s = Arc::new(Semaphore::new(1));
let s2 = s.clone();
let _t = thread::spawn(move|| {
let _g = s2.access();
});
let _g = s.access();
} | identifier_body |
semaphore.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 ... | s2.release();
let _ = rx.recv();
});
s.acquire();
tx.send(()).unwrap();
}
#[test]
fn test_sem_multi_resource() {
// Parent and child both get in the critical section at the same
// time, and shake hands.
let s = Arc::new(Semaphore::new... | let _t = thread::spawn(move|| { | random_line_split |
semaphore.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 ... | () {
let s = Semaphore::new(1);
s.acquire();
s.release();
s.acquire();
}
#[test]
fn test_sem_basic() {
let s = Semaphore::new(1);
let _g = s.access();
}
#[test]
fn test_sem_as_mutex() {
let s = Arc::new(Semaphore::new(1));
let s2 ... | test_sem_acquire_release | identifier_name |
table.rs | //! This module implements the `table` cipher for fallback compatibility
use std::io::Cursor;
use crate::crypto::{
digest::{self, Digest, DigestType},
CipherResult,
CryptoMode,
StreamCipher,
};
use byteorder::{LittleEndian, ReadBytesExt};
use bytes::{BufMut, BytesMut};
const TABLE_SIZE: usize = 256u... |
fn buffer_size(&self, data: &[u8]) -> usize {
data.len()
}
}
#[test]
fn test_table_cipher() {
let message = "hello world";
let key = "keykeykk";
let mut enc = TableCipher::new(key.as_bytes(), CryptoMode::Encrypt);
let mut dec = TableCipher::new(key.as_bytes(), CryptoMode::Decrypt);
... | {
Ok(())
} | identifier_body |
table.rs | //! This module implements the `table` cipher for fallback compatibility
use std::io::Cursor;
use crate::crypto::{
digest::{self, Digest, DigestType},
CipherResult,
CryptoMode,
StreamCipher,
};
use byteorder::{LittleEndian, ReadBytesExt};
use bytes::{BufMut, BytesMut};
const TABLE_SIZE: usize = 256u... | let message = "hello world";
let key = "keykeykk";
let mut enc = TableCipher::new(key.as_bytes(), CryptoMode::Encrypt);
let mut dec = TableCipher::new(key.as_bytes(), CryptoMode::Decrypt);
let mut encrypted_msg = Vec::new();
enc.update(message.as_bytes(), &mut encrypted_msg).unwrap();
let m... | }
}
#[test]
fn test_table_cipher() { | random_line_split |
table.rs | //! This module implements the `table` cipher for fallback compatibility
use std::io::Cursor;
use crate::crypto::{
digest::{self, Digest, DigestType},
CipherResult,
CryptoMode,
StreamCipher,
};
use byteorder::{LittleEndian, ReadBytesExt};
use bytes::{BufMut, BytesMut};
const TABLE_SIZE: usize = 256u... |
CryptoMode::Decrypt => {
let mut t = [0u8; TABLE_SIZE];
for (idx, &item) in table.iter().enumerate() {
t[item as usize] = idx as u8;
}
t
}
},
}
}
fn proce... | {
let mut t = [0u8; TABLE_SIZE];
for i in 0..TABLE_SIZE {
t[i] = table[i] as u8;
}
t
} | conditional_block |
table.rs | //! This module implements the `table` cipher for fallback compatibility
use std::io::Cursor;
use crate::crypto::{
digest::{self, Digest, DigestType},
CipherResult,
CryptoMode,
StreamCipher,
};
use byteorder::{LittleEndian, ReadBytesExt};
use bytes::{BufMut, BytesMut};
const TABLE_SIZE: usize = 256u... | (key: &[u8], mode: CryptoMode) -> TableCipher {
let mut md5_digest = digest::with_type(DigestType::Md5);
md5_digest.update(key);
let mut key_digest = BytesMut::with_capacity(md5_digest.digest_len());
md5_digest.digest(&mut key_digest);
let mut bufr = Cursor::new(&key_digest[..])... | new | identifier_name |
util.rs | // Copyright 2012-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-MI... |
}
panic!("Cannot determine OS from triple");
}
#[cfg(target_os = "windows")]
pub fn make_new_path(path: &str) -> String {
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match env::var(lib_path_env_var()) {
Ok(curr) => {... | {
return os
} | conditional_block |
util.rs | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use common::Config;
#[cfg(target_os = "windows")]
use std::env;
/// Conversion table f... | // Copyright 2012-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 | random_line_split | |
util.rs | // Copyright 2012-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-MI... |
#[cfg(target_os = "windows")]
pub fn lib_path_env_var() -> &'static str { "PATH" }
#[cfg(target_os = "windows")]
pub fn path_div() -> &'static str { ";" }
pub fn logv(config: &Config, s: String) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
| {
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match env::var(lib_path_env_var()) {
Ok(curr) => {
format!("{}{}{}", path, path_div(), curr)
}
Err(..) => path.to_string()
}
} | identifier_body |
util.rs | // Copyright 2012-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-MI... | () -> &'static str { "PATH" }
#[cfg(target_os = "windows")]
pub fn path_div() -> &'static str { ";" }
pub fn logv(config: &Config, s: String) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
| lib_path_env_var | identifier_name |
chunking.rs | use serde::Deserialize;
use std::{
fmt,
fs::File,
io::{
BufReader,
BufWriter,
Read,
Write,
},
ops::Range,
path::{
Path,
PathBuf,
},
};
use anyhow::{
Context,
Result,
};
use serde::{
de::DeserializeOwned,
ser::Serialize,
};
u... | let chunks = load(chunks)?;
let grouped = iterator.group_by(|entry: &T| {
chunks
.filename_of(id_getter(entry))
.ok_or(format!("Could not find filename for {:?}", &entry))
.unwrap()
});
for (filename, items) in &grouped {
let mut path = PathBuf::from(out... | random_line_split | |
chunking.rs | use serde::Deserialize;
use std::{
fmt,
fs::File,
io::{
BufReader,
BufWriter,
Read,
Write,
},
ops::Range,
path::{
Path,
PathBuf,
},
};
use anyhow::{
Context,
Result,
};
use serde::{
de::DeserializeOwned,
ser::Serialize,
};
u... | (filename: &Path) -> Result<ChunkSpec> {
let file = File::open(filename)
.with_context(|| format!("Could not open chunk file {:?}", &filename))?;
let reader = BufReader::new(file);
let mut records = Reader::from_reader(reader);
let mut ranges = Vec::new();
for result in records.deserialize() ... | load | identifier_name |
chunking.rs | use serde::Deserialize;
use std::{
fmt,
fs::File,
io::{
BufReader,
BufWriter,
Read,
Write,
},
ops::Range,
path::{
Path,
PathBuf,
},
};
use anyhow::{
Context,
Result,
};
use serde::{
de::DeserializeOwned,
ser::Serialize,
};
u... |
}
impl SingleChunk {
pub fn contains(&self, index: &usize) -> bool {
self.endpoints.contains(index)
}
}
impl ChunkSpec {
pub fn filename_of(&self, index: usize) -> Option<PathBuf> {
self.ranges
.iter()
.find(|r| r.contains(&index))
.map(|c: &SingleChunk| P... | {
return Self {
endpoints: Range {
start: raw.start,
end: raw.stop + 1,
},
filename: raw.filename,
};
} | identifier_body |
htmlframeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::document::AbstractDocument;
use dom::htmlelement::HTM... |
pub fn MarginHeight(&self) -> DOMString {
None
}
pub fn SetMarginHeight(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginWidth(&self) -> DOMString {
None
}
pub fn SetMarginWidth(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())... | {
None
} | identifier_body |
htmlframeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::document::AbstractDocument;
use dom::htmlelement::HTM... | }
pub fn MarginHeight(&self) -> DOMString {
None
}
pub fn SetMarginHeight(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginWidth(&self) -> DOMString {
None
}
pub fn SetMarginWidth(&mut self, _height: &DOMString) -> ErrorResult {
O... | }
pub fn GetContentWindow(&self) -> Option<@mut WindowProxy> {
None | random_line_split |
htmlframeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::document::AbstractDocument;
use dom::htmlelement::HTM... | (&self) -> Option<AbstractDocument> {
None
}
pub fn GetContentWindow(&self) -> Option<@mut WindowProxy> {
None
}
pub fn MarginHeight(&self) -> DOMString {
None
}
pub fn SetMarginHeight(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Ma... | GetContentDocument | identifier_name |
checked_count_ones.rs | use integer::Integer;
use malachite_base::num::logic::traits::CountOnes;
impl Integer {
/// Counts the number of ones in the binary expansion of an `Integer`. If the `Integer` is
/// negative, the number of ones is infinite, so `None` is returned.
///
/// Time: worst case O(n)
///
/// Additiona... | else {
None
}
}
}
| {
Some(self.abs.count_ones())
} | conditional_block |
checked_count_ones.rs | use integer::Integer;
use malachite_base::num::logic::traits::CountOnes;
impl Integer {
/// Counts the number of ones in the binary expansion of an `Integer`. If the `Integer` is
/// negative, the number of ones is infinite, so `None` is returned.
///
/// Time: worst case O(n)
///
/// Additiona... | (&self) -> Option<u64> {
if self.sign {
Some(self.abs.count_ones())
} else {
None
}
}
}
| checked_count_ones | identifier_name |
checked_count_ones.rs | use integer::Integer;
use malachite_base::num::logic::traits::CountOnes;
impl Integer {
/// Counts the number of ones in the binary expansion of an `Integer`. If the `Integer` is
/// negative, the number of ones is infinite, so `None` is returned.
///
/// Time: worst case O(n)
///
/// Additiona... | /// ```
pub fn checked_count_ones(&self) -> Option<u64> {
if self.sign {
Some(self.abs.count_ones())
} else {
None
}
}
} | /// // 105 = 1101001b
/// assert_eq!(Integer::from(105).checked_count_ones(), Some(4));
/// assert_eq!(Integer::from(-105).checked_count_ones(), None);
/// // 10^12 = 1110100011010100101001010001000000000000b
/// assert_eq!(Integer::trillion().checked_count_ones(), Some(13)); | random_line_split |
checked_count_ones.rs | use integer::Integer;
use malachite_base::num::logic::traits::CountOnes;
impl Integer {
/// Counts the number of ones in the binary expansion of an `Integer`. If the `Integer` is
/// negative, the number of ones is infinite, so `None` is returned.
///
/// Time: worst case O(n)
///
/// Additiona... |
}
| {
if self.sign {
Some(self.abs.count_ones())
} else {
None
}
} | identifier_body |
unix_socket.rs | mod helper;
#[cfg(not(target_os = "windows"))]
mod tests {
use anyhow::Result;
use pretty_assertions::assert_eq;
use serde_cbor::de::from_slice;
use serde_cbor::ser::to_vec;
use tokio::task;
use pueue_lib::network::message::*;
use pueue_lib::network::protocol::*;
use super::*;
#[... |
let mut client = get_client_stream(&shared_settings).await?;
// Create a client that sends a message and instantly receives it
send_message(message, &mut client).await?;
let response_bytes = receive_bytes(&mut client).await?;
let _message: Message = from_slice(&response_bytes)?... | {
better_panic::install();
let (shared_settings, _tempdir) = helper::get_shared_settings();
let listener = get_listener(&shared_settings).await?;
let message = create_success_message("This is a test");
let original_bytes = to_vec(&message).expect("Failed to serialize message.");... | identifier_body |
unix_socket.rs | mod helper;
#[cfg(not(target_os = "windows"))]
mod tests {
use anyhow::Result;
use pretty_assertions::assert_eq;
use serde_cbor::de::from_slice;
use serde_cbor::ser::to_vec;
use tokio::task;
use pueue_lib::network::message::*;
use pueue_lib::network::protocol::*;
use super::*;
#[... | () -> Result<()> {
better_panic::install();
let (shared_settings, _tempdir) = helper::get_shared_settings();
let listener = get_listener(&shared_settings).await?;
let message = create_success_message("This is a test");
let original_bytes = to_vec(&message).expect("Failed to seri... | test_unix_socket | identifier_name |
unix_socket.rs | mod helper;
#[cfg(not(target_os = "windows"))]
mod tests {
use anyhow::Result;
use pretty_assertions::assert_eq;
use serde_cbor::de::from_slice;
use serde_cbor::ser::to_vec;
use tokio::task;
use pueue_lib::network::message::*;
use pueue_lib::network::protocol::*;
use super::*;
#[... | }
} | random_line_split | |
header.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... | use error::Result;
pub fn start(ui: &mut UI, src: &Path) -> Result<()> {
ui.begin(format!("Reading package header for {}", &src.display()))?;
ui.para("")?;
if let Ok(header) = artifact::get_artifact_header(src) {
io::stdout().write(format!("Package : {}\n", &src.display()).as_bytes())?;
... | random_line_split | |
header.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... | (ui: &mut UI, src: &Path) -> Result<()> {
ui.begin(format!("Reading package header for {}", &src.display()))?;
ui.para("")?;
if let Ok(header) = artifact::get_artifact_header(src) {
io::stdout().write(format!("Package : {}\n", &src.display()).as_bytes())?;
io::stdout().write(format!("... | start | identifier_name |
header.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... |
Ok(())
}
| {
ui.warn("Failed to read package header.")?;
} | conditional_block |
header.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... | {
ui.begin(format!("Reading package header for {}", &src.display()))?;
ui.para("")?;
if let Ok(header) = artifact::get_artifact_header(src) {
io::stdout().write(format!("Package : {}\n", &src.display()).as_bytes())?;
io::stdout().write(format!("Format Version : {}\n", header.format_ve... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.