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
project-fn-ret-contravariant.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 ...
//[ok]~^ ERROR compilation successful //[oneuse]~^^ ERROR compilation successful
{ }
identifier_body
project-fn-ret-contravariant.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 ...
<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) { let a = bar(foo, y); let b = bar(foo, x); (a, b) //[krisskross]~ ERROR 55:5: 55:6: lifetime mismatch [E0623] //[krisskross]~^ ERROR 55:8: 55:9: lifetime mismatch [E0623] } #[rustc_error] fn main() { } //[ok]~^ ERROR compilation successful //[oneuse]~^...
transmute
identifier_name
project-fn-ret-contravariant.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 main() { } //[ok]~^ ERROR compilation successful //[oneuse]~^^ ERROR compilation successful
(a, b) //[krisskross]~ ERROR 55:5: 55:6: lifetime mismatch [E0623] //[krisskross]~^ ERROR 55:8: 55:9: lifetime mismatch [E0623] } #[rustc_error]
random_line_split
plugin_class.rs
use node::inner_node::node_from_ptr; use node::{String, Uri}; use world::World; #[derive(Clone)] pub struct PluginClass<'w> { pub(crate) ptr: *const ::lilv_sys::LilvPluginClass, pub(crate) world: &'w World, } impl<'w> PluginClass<'w> { pub(crate) fn new(ptr: *const ::lilv_sys::LilvPluginClass, world: &Wor...
(&self) -> &Uri<'w> { unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_parent_uri(self.ptr)) } } pub fn uri(&self) -> &Uri<'w> { unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_uri(self.ptr)) } } pub fn label(&self) -> &String<'w> { unsafe { node_from_ptr(::lil...
parent_uri
identifier_name
plugin_class.rs
use node::inner_node::node_from_ptr; use node::{String, Uri}; use world::World; #[derive(Clone)] pub struct PluginClass<'w> { pub(crate) ptr: *const ::lilv_sys::LilvPluginClass, pub(crate) world: &'w World, } impl<'w> PluginClass<'w> { pub(crate) fn new(ptr: *const ::lilv_sys::LilvPluginClass, world: &Wor...
pub fn parent_uri(&self) -> &Uri<'w> { unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_parent_uri(self.ptr)) } } pub fn uri(&self) -> &Uri<'w> { unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_uri(self.ptr)) } } pub fn label(&self) -> &String<'w> { unsaf...
{ PluginClass { ptr, world } }
identifier_body
plugin_class.rs
use node::inner_node::node_from_ptr; use node::{String, Uri}; use world::World; #[derive(Clone)] pub struct PluginClass<'w> { pub(crate) ptr: *const ::lilv_sys::LilvPluginClass, pub(crate) world: &'w World, } impl<'w> PluginClass<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_parent_uri(self.ptr)) } } pub fn uri(&self) -> &Uri<'w> { unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_uri(self.ptr)) } } pub fn label(&self) -> &String<'w> { unsafe { node_from_ptr(::lilv_sys::lilv_plugin_cla...
pub(crate) fn new(ptr: *const ::lilv_sys::LilvPluginClass, world: &World) -> PluginClass { PluginClass { ptr, world } } pub fn parent_uri(&self) -> &Uri<'w> {
random_line_split
tree.rs
use std::io::{File, BufReader}; use std::container::Container; use std::io::{BufferedWriter}; use std::fmt::{Show, Formatter, FormatError};
pub trait TreeNode : Show { fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Option<Self>>; } #[deriving(PartialEq,Eq)] pub struct Tree<I> { instructions: Vec<I>, } pub struct TreeIterator<'a, I> { tree: &'a Tree<I>, i: uint, } impl<I: TreeNode> Tree<I> { pub fn new() -> Tree<I> { ...
use syntax::tokenize::{Tokenizer}; use result::BancResult;
random_line_split
tree.rs
use std::io::{File, BufReader}; use std::container::Container; use std::io::{BufferedWriter}; use std::fmt::{Show, Formatter, FormatError}; use syntax::tokenize::{Tokenizer}; use result::BancResult; pub trait TreeNode : Show { fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Option<Self>>; } #[deri...
}
{ for inst in self.instructions.iter() { inst.fmt(formatter); formatter.write_char('\n'); } Ok(()) }
identifier_body
tree.rs
use std::io::{File, BufReader}; use std::container::Container; use std::io::{BufferedWriter}; use std::fmt::{Show, Formatter, FormatError}; use syntax::tokenize::{Tokenizer}; use result::BancResult; pub trait TreeNode : Show { fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Option<Self>>; } #[deri...
(file: File) -> BancResult<Tree<I>> { let mut tokenizer = Tokenizer::<File>::from_file(file); Tree::parse(&mut tokenizer) } pub fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Tree<I>> { let mut tree = Tree::new(); while! tokenizer.eof() { let node: B...
parse_file
identifier_name
filemanager_thread.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 ipc_channel::ipc::IpcSender; use std::path::PathBuf; use uuid::Uuid; #[derive(Debug, Deserialize, Serialize)]...
#[derive(Deserialize, Serialize)] pub enum FileManagerThreadMsg { /// Select a single file, return triple (FileID, FileName, lastModified) SelectFile(IpcSender<FileManagerResult<SelectedFile>>), /// Select multiple files, return a vector of triples SelectFiles(IpcSender<FileManagerResult<Vec<SelectedFi...
// https://w3c.github.io/FileAPI/#dfn-type pub type_string: String, }
random_line_split
filemanager_thread.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 ipc_channel::ipc::IpcSender; use std::path::PathBuf; use uuid::Uuid; #[derive(Debug, Deserialize, Serialize)]...
{ pub id: Uuid, pub filename: PathBuf, pub modified: u64, // https://w3c.github.io/FileAPI/#dfn-type pub type_string: String, } #[derive(Deserialize, Serialize)] pub enum FileManagerThreadMsg { /// Select a single file, return triple (FileID, FileName, lastModified) SelectFile(IpcSender<Fi...
SelectedFile
identifier_name
regions-static-closure.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 ...
#![allow(unknown_features)] #![feature(box_syntax)] #![feature(unboxed_closures)] struct closure_box<'a> { cl: Box<FnMut() + 'a>, } fn box_it<'a>(x: Box<FnMut() + 'a>) -> closure_box<'a> { closure_box {cl: x} } fn call_static_closure(mut cl: closure_box<'static>) { cl.cl.call_mut(()) } pub fn main() { ...
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
regions-static-closure.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 cl_box = box_it(box || println!("Hello, world!")); call_static_closure(cl_box); }
main
identifier_name
app_result.rs
use std::io; use std::error::FromError; use std::fmt::{self, Display, Formatter}; use glob; /// The result used in the whole application. pub type AppResult<T> = Result<T, AppErr>; /// The generic error used in the whole application. pub struct AppErr { error: String } pub fn app_err(string: String) -> AppErr { ...
{ fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { writeln!(f, "{}", self.error) } } impl FromError<io::Error> for AppErr { fn from_error(err: io::Error) -> AppErr { AppErr { error: format!("{}", err) } } } impl FromError<glob::PatternError> for AppErr { fn from_error(err:...
impl Display for AppErr
random_line_split
app_result.rs
use std::io; use std::error::FromError; use std::fmt::{self, Display, Formatter}; use glob; /// The result used in the whole application. pub type AppResult<T> = Result<T, AppErr>; /// The generic error used in the whole application. pub struct AppErr { error: String } pub fn app_err(string: String) -> AppErr { ...
} impl FromError<io::Error> for AppErr { fn from_error(err: io::Error) -> AppErr { AppErr { error: format!("{}", err) } } } impl FromError<glob::PatternError> for AppErr { fn from_error(err: glob::PatternError) -> AppErr { AppErr { error: format!("{}", err) } } }
{ writeln!(f, "{}", self.error) }
identifier_body
app_result.rs
use std::io; use std::error::FromError; use std::fmt::{self, Display, Formatter}; use glob; /// The result used in the whole application. pub type AppResult<T> = Result<T, AppErr>; /// The generic error used in the whole application. pub struct AppErr { error: String } pub fn app_err(string: String) -> AppErr { ...
(string: String) -> AppErr { AppErr { error: string } } } impl Display for AppErr { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { writeln!(f, "{}", self.error) } } impl FromError<io::Error> for AppErr { fn from_error(err: io::Error) -> AppErr { AppErr { error: for...
from_string
identifier_name
harfbuzz.rs
pub fn entry_for_glyph(&self, i: usize, y_pos: &mut Au) -> ShapedGlyphEntry { assert!(i < self.count); unsafe { let glyph_info_i = self.glyph_infos.offset(i as isize); let pos_info_i = self.pos_infos.offset(i as isize); let x_offset = Shaper::fixed_to_float((*pos_i...
lyph_h_kerning_func(
identifier_name
harfbuzz.rs
_t, } pub struct ShapedGlyphEntry { codepoint: GlyphId, advance: Au, offset: Option<Point2D<Au>>, } impl ShapedGlyphData { pub fn new(buffer: *mut hb_buffer_t) -> ShapedGlyphData { unsafe { let mut glyph_count = 0; let glyph_infos = hb_buffer_get_glyph_infos(buffer, &mu...
// Otherwise, the bytes we have seen so far correspond to a non-contiguous set of // glyphs. Keep extending byte_range until we fill in all the holes in the glyph // span or reach the end of the text. } assert!(byte_range.len() > 0); ...
{ break }
conditional_block
harfbuzz.rs
_position_t, } pub struct ShapedGlyphEntry { codepoint: GlyphId, advance: Au, offset: Option<Point2D<Au>>, } impl ShapedGlyphData { pub fn new(buffer: *mut hb_buffer_t) -> ShapedGlyphData { unsafe { let mut glyph_count = 0; let glyph_infos = hb_buffer_get_glyph_infos(bu...
fixed_to_float(16, i) } } impl ShaperMethods for Shaper { /// Calculate the layout metrics associated with the given text when painted in a specific /// font. fn shape_text(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) { unsafe { let hb_buffer: *mut h...
fn fixed_to_float(i: hb_position_t) -> f64 {
random_line_split
harfbuzz.rs
_t, } pub struct ShapedGlyphEntry { codepoint: GlyphId, advance: Au, offset: Option<Point2D<Au>>, } impl ShapedGlyphData { pub fn new(buffer: *mut hb_buffer_t) -> ShapedGlyphData { unsafe { let mut glyph_count = 0; let glyph_infos = hb_buffer_get_glyph_infos(buffer, &mu...
fn fixed_to_float(i: hb_position_t) -> f64 { fixed_to_float(16, i) } } impl ShaperMethods for Shaper { /// Calculate the layout metrics associated with the given text when painted in a specific /// font. fn shape_text(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {...
{ float_to_fixed(16, f) }
identifier_body
thread.rs
use core::time::Duration; use crate::syscall; use alloc::string::String; pub struct Thread { name: Option<String>, stack_size: usize, stack_top: * const u8, id: ThreadId, } pub struct Builder { name: Option<String>, stack_size: usize, } impl Builder { const DEFAULT_SIZE: ...
pub fn stack_size(self, stack_size: usize) -> Self { Self { name: self.name, stack_size } } } #[derive(Clone)] pub struct ThreadId(u16); impl Thread { pub fn unpark(&self) { } pub fn id(&self) -> ThreadId { self.id.clone() } pub fn name(&se...
{ Self { name: Some(name), stack_size: self.stack_size } }
identifier_body
thread.rs
use core::time::Duration; use crate::syscall; use alloc::string::String; pub struct Thread { name: Option<String>, stack_size: usize, stack_top: * const u8, id: ThreadId, } pub struct Builder { name: Option<String>, stack_size: usize, } impl Builder { const DEFAULT_SIZE: ...
impl Thread { pub fn unpark(&self) { } pub fn id(&self) -> ThreadId { self.id.clone() } pub fn name(&self) -> Option<&str> { self.name.as_ref().map(|s| s.as_str()) } /* fn new(name: Option<String>, stack_size: usize) -> Thread { let (stack_memory, stack_size) = mapping::allocate_stack_memo...
pub struct ThreadId(u16);
random_line_split
thread.rs
use core::time::Duration; use crate::syscall; use alloc::string::String; pub struct Thread { name: Option<String>, stack_size: usize, stack_top: * const u8, id: ThreadId, } pub struct Builder { name: Option<String>, stack_size: usize, } impl Builder { const DEFAULT_SIZE: ...
(&self) { } pub fn id(&self) -> ThreadId { self.id.clone() } pub fn name(&self) -> Option<&str> { self.name.as_ref().map(|s| s.as_str()) } /* fn new(name: Option<String>, stack_size: usize) -> Thread { let (stack_memory, stack_size) = mapping::allocate_stack_memory(stack_size); Threa...
unpark
identifier_name
sprite_renderer.rs
/* use cgmath::Vector2; use gfx; use gfx_device_gl; use gfx_device_gl::{Resources}; use gfx::{Device, CommandQueue,FrameSync, GraphicsPoolExt, Surface, Swapchain, SwapchainExt, WindowExt}; use gfx::traits::DeviceExt; use graphics::render_thread::RenderPackage; type ColorFormat = gfx::format::Rgba8; const BL...
2 + (i * 4), 1 + (i * 4), 3 + (i * 4)]);//bottom right triangle } let (vertex_buffer, index_buffer) = render_package.device.create_vertex_buffer_with_slice(&vertex_info, &*index_info); let text_sampler = render_package.device.create_sampler_linear(); ...
let i = i as u16; index_info.extend(&[0 + (i * 4), 1 + (i * 4), 2 + (i * 4),//top left triangle
random_line_split
main.rs
//! # Beamium. //! //! Beamium scrap Prometheus endpoint and forward metrics to Warp10. extern crate backoff; extern crate bytes; extern crate cast; extern crate clap; extern crate core; extern crate ctrlc; extern crate flate2; extern crate futures; extern crate humantime; extern crate hyper; extern crate hyper_timeout...
// Bootstrap config let config_path = matches.value_of("config").unwrap_or(""); let config = match config::load_config(&config_path) { Ok(config) => config, Err(err) => { crit!("Fail to load config {}: {}", &config_path, err); std::process::abort(); } }; ...
{ // Setup a bare logger log::bootstrap(); let matches = App::new("beamium") .version(&*format!( "{} ({}#{})", env!("CARGO_PKG_VERSION"), COMMIT, PROFILE, )) .author("d33d33 <kevin@d33d33.fr>") .about("Send Prometheus metrics t...
identifier_body
main.rs
//! # Beamium. //! //! Beamium scrap Prometheus endpoint and forward metrics to Warp10. extern crate backoff; extern crate bytes; extern crate cast; extern crate clap; extern crate core; extern crate ctrlc; extern crate flate2; extern crate futures; extern crate humantime; extern crate hyper; extern crate hyper_timeout...
std::process::abort(); } }; if matches.is_present("t") { info!("config ok"); std::process::exit(0); } info!("starting"); // Setup logging match log::log(&config.parameters, matches.occurrences_of("v")) { Ok(()) => {} Err(err) => { ...
let config = match config::load_config(&config_path) { Ok(config) => config, Err(err) => { crit!("Fail to load config {}: {}", &config_path, err);
random_line_split
main.rs
//! # Beamium. //! //! Beamium scrap Prometheus endpoint and forward metrics to Warp10. extern crate backoff; extern crate bytes; extern crate cast; extern crate clap; extern crate core; extern crate ctrlc; extern crate flate2; extern crate futures; extern crate humantime; extern crate hyper; extern crate hyper_timeout...
() { // Setup a bare logger log::bootstrap(); let matches = App::new("beamium") .version(&*format!( "{} ({}#{})", env!("CARGO_PKG_VERSION"), COMMIT, PROFILE, )) .author("d33d33 <kevin@d33d33.fr>") .about("Send Prometheus metrics t...
main
identifier_name
main.rs
//! # Beamium. //! //! Beamium scrap Prometheus endpoint and forward metrics to Warp10. extern crate backoff; extern crate bytes; extern crate cast; extern crate clap; extern crate core; extern crate ctrlc; extern crate flate2; extern crate futures; extern crate humantime; extern crate hyper; extern crate hyper_timeout...
}; match fs::create_dir_all(&config.parameters.sink_dir) { Ok(()) => {} Err(err) => { crit!( "Fail to create sink directory {}: {}", &config.parameters.source_dir, err ); std::process::abort(); } }; ...
{ crit!( "Fail to create source directory {}: {}", &config.parameters.source_dir, err ); std::process::abort(); }
conditional_block
regex.rs
// Copyright (c) 2014 Michael Woerister // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publis...
() { let sm = compile(&Kleene(~Leaf('a'))); assert!(matches(&sm, "")); assert!(matches(&sm, "a")); assert!(matches(&sm, "aaa")); assert!(matches(&sm, "aaaaaaaaaaaaaaaaaaaaaaaaaa")); assert!(!matches(&sm, "b")); assert!(!matches(&sm, "caaaa")); assert!(!m...
test_kleene
identifier_name
regex.rs
// Copyright (c) 2014 Michael Woerister // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publis...
Seq(ref left, ref right) => { let (mut left_sm, left_start, left_end) = left.to_state_machine(); let (right_sm, right_start, right_end) = right.to_state_machine(); left_sm.consume(right_sm); left_sm.add_transition(left_end, right_start, Epsi...
{ let (mut sm, sub_start, sub_end) = sub.to_state_machine(); let start_state = sm.add_state(); let end_state = sm.add_state(); sm.add_transition(start_state, sub_start, Epsilon); sm.add_transition(sub_end, sub_start, Epsilon); ...
conditional_block
regex.rs
// Copyright (c) 2014 Michael Woerister // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publis...
assert!(!matches(&sm, "ab")); } #[test] fn test_seq() { let sm = compile(&Seq(~Leaf('a'), ~Seq(~Leaf('b'),~Leaf('c')))); assert!(!matches(&sm, "")); assert!(!matches(&sm, "a")); assert!(!matches(&sm, "ab")); assert!(matches(&sm, "abc")); assert!(!mat...
assert!(!matches(&sm, "b")); assert!(!matches(&sm, "caaaa")); assert!(!matches(&sm, "daaa")); assert!(!matches(&sm, "e"));
random_line_split
regex.rs
// Copyright (c) 2014 Michael Woerister // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publis...
fn matches(&(ref sm, start_state, ref end_states): &(StateMachine, StateId, ~[StateId]), s: &str) -> bool { let result_state = sm.run(start_state, s); end_states.iter().any(|&x| Some(x) == result_state) } #[test] fn test_kleene() { let sm = compile(&Kleene(~Leaf('a'))); ...
{ let (sm, start, end) = regex.to_state_machine(); let end_states = [end]; let end_states: StateSet = end_states.iter().map(|x| *x).collect(); let ToDfaResult { dfa, start_state, end_state_map } = sm.to_dfa(start, &end_states); let dfa_end_states = end_state_map.keys().map(|x| *x...
identifier_body
regions-close-associated-type-into-object.rs
trait X {} trait Iter { type Item: X; fn into_item(self) -> Self::Item; fn as_item(&self) -> &Self::Item; } fn bad1<T: Iter>(v: T) -> Box<dyn X +'static> { let item = v.into_item(); Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough } fn bad2<T: Iter>(v: T) -...
fn ok1<'a, T: Iter>(v: T) -> Box<dyn X + 'a> where T::Item : 'a { let item = v.into_item(); Box::new(item) // OK, T::Item : 'a is declared } fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<dyn X + 'a> where T::Item : Clone { let item = Clone::clone(w); Box::new(item) // OK, T::Item : 'a is ...
{ let item: Box<_> = Box::new(v.into_item()); Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough }
identifier_body
regions-close-associated-type-into-object.rs
trait X {} trait Iter { type Item: X; fn into_item(self) -> Self::Item; fn as_item(&self) -> &Self::Item; } fn bad1<T: Iter>(v: T) -> Box<dyn X +'static> { let item = v.into_item(); Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough } fn bad2<T: Iter>(v: T) -...
<'a, T: Iter>(v: T) -> Box<dyn X + 'a> where T::Item : 'a { let item = v.into_item(); Box::new(item) // OK, T::Item : 'a is declared } fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<dyn X + 'a> where T::Item : Clone { let item = Clone::clone(w); Box::new(item) // OK, T::Item : 'a is implied ...
ok1
identifier_name
regions-close-associated-type-into-object.rs
trait X {}
trait Iter { type Item: X; fn into_item(self) -> Self::Item; fn as_item(&self) -> &Self::Item; } fn bad1<T: Iter>(v: T) -> Box<dyn X +'static> { let item = v.into_item(); Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough } fn bad2<T: Iter>(v: T) -> Box<dyn X +'...
random_line_split
test.rs
extern crate rimd; use rimd::{SMF,SMFError}; use std::env::{args,Args}; use std::path::Path; fn
() { let mut args: Args = args(); args.next(); let pathstr = match args.next() { Some(s) => s, None => { panic!("Please pass a path to an SMF to test") }, }; println!("Reading: {}",pathstr); match SMF::from_file(&Path::new(&pathstr[..])) { Ok(smf) => { println...
main
identifier_name
test.rs
extern crate rimd; use rimd::{SMF,SMFError}; use std::env::{args,Args}; use std::path::Path; fn main() { let mut args: Args = args(); args.next(); let pathstr = match args.next() { Some(s) => s, None => { panic!("Please pass a path to an SMF to test") }, }; println!("Reading: {}",p...
println!("\n{}: {}\nevents:",tnum,track); tnum+=1; for event in track.events.iter() { println!(" {}",event.fmt_with_time_offset(time)); time += event.vtime; } } } Err(e) => { ...
println!("division: {}",smf.division); let mut tnum = 1; for track in smf.tracks.iter() { let mut time: u64 = 0;
random_line_split
test.rs
extern crate rimd; use rimd::{SMF,SMFError}; use std::env::{args,Args}; use std::path::Path; fn main()
time += event.vtime; } } } Err(e) => { match e { SMFError::InvalidSMFFile(s) => {println!("{}",s);} SMFError::Error(e) => {println!("io: {}",e);} SMFError::MidiError(e) => {println!("Midi Error: {...
{ let mut args: Args = args(); args.next(); let pathstr = match args.next() { Some(s) => s, None => { panic!("Please pass a path to an SMF to test") }, }; println!("Reading: {}",pathstr); match SMF::from_file(&Path::new(&pathstr[..])) { Ok(smf) => { println!("...
identifier_body
timezoneapi.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! ApiSet Contract for api-ms-win-core-timezone-l1 pub const TIME_ZONE_ID_INVALID: ::DWORD = 0xFFFFFFFF; STRUCT!{struct TIME_ZONE_INFORMATION { Bias: ::LONG, StandardName: [::WCHAR; 32], StandardDate: ::SYSTEMTIME, Stand...
pub type PDYNAMIC_TIME_ZONE_INFORMATION = *mut DYNAMIC_TIME_ZONE_INFORMATION;
random_line_split
component_ref.rs
use std::collections::HashMap; use ecs::Ecs; use entity::Entity; /// Immutable component access. pub struct ComponentRef<'a, C:'static> { ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>, } impl<'a, C> ComponentRef<'a, C> { pub fn new(ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a,...
} } /// Fetch a component from given entity. Do not search parent entities. pub fn get_local(self, Entity(idx): Entity) -> Option<&'a C> { self.data.get(&idx).map_or(None, |x| x.as_ref()) } } /// Mutable component access. pub struct ComponentRefMut<'a, C:'static> { ecs: &'a mut Ec...
{ self.data.get(&idx).expect("missing component").as_ref() }
conditional_block
component_ref.rs
use std::collections::HashMap; use ecs::Ecs; use entity::Entity; /// Immutable component access. pub struct ComponentRef<'a, C:'static> { ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>, } impl<'a, C> ComponentRef<'a, C> { pub fn new(ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a,...
/// Fetch a component from given entity. Do not search parent entities. pub fn get_local(self, Entity(idx): Entity) -> Option<&'a C> { self.data.get(&idx).map_or(None, |x| x.as_ref()) } } /// Mutable component access. pub struct ComponentRefMut<'a, C:'static> { ecs: &'a mut Ecs, /// Some(...
{ match find_parent(|Entity(idx)| self.data.contains_key(&idx), self.ecs, Entity(idx)) { None => { None } Some(Entity(idx)) => { self.data.get(&idx).expect("missing component").as_ref() } } }
identifier_body
component_ref.rs
use std::collections::HashMap; use ecs::Ecs; use entity::Entity; /// Immutable component access. pub struct ComponentRef<'a, C:'static> { ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>, } impl<'a, C> ComponentRef<'a, C> { pub fn
(ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a, C> { ComponentRef { ecs: ecs, data: data, } } /// Fetch a component from given entity or its parent. pub fn get(self, Entity(idx): Entity) -> Option<&'a C> { match find_parent(|Entity(idx...
new
identifier_name
component_ref.rs
use std::collections::HashMap; use ecs::Ecs; use entity::Entity; /// Immutable component access. pub struct ComponentRef<'a, C:'static> { ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>, } impl<'a, C> ComponentRef<'a, C> { pub fn new(ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a,...
// Copy-on-write: Make a local copy of inherited component // when asking for mutable access. let cow = self.data.get(&idx2) .expect("parent component lost").as_ref() .expect("missing component").clone(); self.data.ins...
random_line_split
parser.rs
/// Parsers for the message body of the VSL records /// /// This should not allocate memory but do primitive conversion when applicable /// To keep this simple they will be returning tuples. /// Format and comments are form `include/tbl/vsl_tags.h` and `include/tbl/vsl_tags_http.h`. /// /// Parsing: /// * numeric types...
named_parsed_symbol!(duration<Duration>); named_parsed_symbol!(port<Port>); named_parsed_symbol!(file_descriptor<FileDescriptor>); fn map_opt_duration(duration: Duration) -> Option<Duration> { if duration < 0.0 { None } else { Some(duration) } } named!(opt_duration<&[u8], Option<Duration> ...
named_parsed_symbol!(fech_mode<FetchMode>); named_parsed_symbol!(status<Status>); named_parsed_symbol!(time_stamp<TimeStamp>);
random_line_split
parser.rs
/// Parsers for the message body of the VSL records /// /// This should not allocate memory but do primitive conversion when applicable /// To keep this simple they will be returning tuples. /// Format and comments are form `include/tbl/vsl_tags.h` and `include/tbl/vsl_tags_http.h`. /// /// Parsing: /// * numeric types...
} named!(opt_duration<&[u8], Option<Duration> >, map!(duration, map_opt_duration)); // VSL record message parsers by tag named!(pub slt_begin<&[u8], (&str, VslIdent, &str)>, tuple!( symbol, // Type (b"sess", "req" or "bereq") vsl_ident, // Parent vxid symbol)); // Reason named!(pub s...
{ Some(duration) }
conditional_block
parser.rs
/// Parsers for the message body of the VSL records /// /// This should not allocate memory but do primitive conversion when applicable /// To keep this simple they will be returning tuples. /// Format and comments are form `include/tbl/vsl_tags.h` and `include/tbl/vsl_tags_http.h`. /// /// Parsing: /// * numeric types...
(duration: Duration) -> Option<Duration> { if duration < 0.0 { None } else { Some(duration) } } named!(opt_duration<&[u8], Option<Duration> >, map!(duration, map_opt_duration)); // VSL record message parsers by tag named!(pub slt_begin<&[u8], (&str, VslIdent, &str)>, tuple!( symbo...
map_opt_duration
identifier_name
parser.rs
/// Parsers for the message body of the VSL records /// /// This should not allocate memory but do primitive conversion when applicable /// To keep this simple they will be returning tuples. /// Format and comments are form `include/tbl/vsl_tags.h` and `include/tbl/vsl_tags_http.h`. /// /// Parsing: /// * numeric types...
named!(opt_duration<&[u8], Option<Duration> >, map!(duration, map_opt_duration)); // VSL record message parsers by tag named!(pub slt_begin<&[u8], (&str, VslIdent, &str)>, tuple!( symbol, // Type (b"sess", "req" or "bereq") vsl_ident, // Parent vxid symbol)); // Reason named!(pub slt...
{ if duration < 0.0 { None } else { Some(duration) } }
identifier_body
renderer-texture.rs
extern crate sdl2; use sdl2::pixels::PixelFormatEnum; use sdl2::rect::Rect; use sdl2::event::Event; use sdl2::keyboard::Keycode; pub fn main()
buffer[offset + 2] = 0; } } }).unwrap(); renderer.clear(); renderer.copy(&texture, None, Some(Rect::new_unwrap(100, 100, 256, 256))); renderer.copy_ex(&texture, None, Some(Rect::new_unwrap(450, 100, 256, 256)), 30.0, None, (false, false)); renderer.present(); ...
{ let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600) .position_centered() .opengl() .build() .unwrap(); let mut renderer = window.renderer().build().unwrap()...
identifier_body
renderer-texture.rs
extern crate sdl2; use sdl2::pixels::PixelFormatEnum; use sdl2::rect::Rect; use sdl2::event::Event; use sdl2::keyboard::Keycode; pub fn main() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 6...
}
// The rest of the game loop goes here... }
random_line_split
renderer-texture.rs
extern crate sdl2; use sdl2::pixels::PixelFormatEnum; use sdl2::rect::Rect; use sdl2::event::Event; use sdl2::keyboard::Keycode; pub fn main() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 6...
} } // The rest of the game loop goes here... } }
{}
conditional_block
renderer-texture.rs
extern crate sdl2; use sdl2::pixels::PixelFormatEnum; use sdl2::rect::Rect; use sdl2::event::Event; use sdl2::keyboard::Keycode; pub fn
() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600) .position_centered() .opengl() .build() .unwrap(); let mut renderer = window.renderer().build().unwrap();...
main
identifier_name
picture.rs
use chrono::naive::NaiveDateTime; use exif::{Exif, In, Tag}; use serde::{Deserialize, Serialize}; use validator::Validate; use anyhow::{Error, Result}; use image::GenericImageView; use image::{imageops, DynamicImage}; use crate::schema::pictures; use crate::utils::image_base_path; #[derive(Debug, Clone, Queryable, I...
} else { img.crop(mid_x - (width / 2), mid_y - (width / 2), width, width) } } else { img }; let new_img = img.resize_exact(600, 600, imageops::FilterType::CatmullRom); new_img.save(path)?; Ok(()) }
random_line_split
picture.rs
use chrono::naive::NaiveDateTime; use exif::{Exif, In, Tag}; use serde::{Deserialize, Serialize}; use validator::Validate; use anyhow::{Error, Result}; use image::GenericImageView; use image::{imageops, DynamicImage}; use crate::schema::pictures; use crate::utils::image_base_path; #[derive(Debug, Clone, Queryable, I...
let path = format!("{}/{}/large/{}", image_base_path(), picture.id, picture.image_file_name); let new_img = img.resize(800, 600, imageops::FilterType::CatmullRom); new_img.save(path)?; let path = format!( "{}/{}/thumbnail/{}", image_base_path(), picture.id, picture.image...
{ let path = format!( "{}/{}/original/{}", image_base_path(), picture.id, picture.image_file_name ); let exif = read_exif(&path)?; let orientation = match exif.get_field(Tag::Orientation, In::PRIMARY) { Some(orientation) => match orientation.value.get_uint(0) { ...
identifier_body
picture.rs
use chrono::naive::NaiveDateTime; use exif::{Exif, In, Tag}; use serde::{Deserialize, Serialize}; use validator::Validate; use anyhow::{Error, Result}; use image::GenericImageView; use image::{imageops, DynamicImage}; use crate::schema::pictures; use crate::utils::image_base_path; #[derive(Debug, Clone, Queryable, I...
(picture: &Picture) -> Result<()> { let path = format!( "{}/{}/original/{}", image_base_path(), picture.id, picture.image_file_name ); let exif = read_exif(&path)?; let orientation = match exif.get_field(Tag::Orientation, In::PRIMARY) { Some(orientation) => match...
generate_pictures
identifier_name
wasm.rs
pub struct NativeManager { } impl NativeManager { pub(crate) fn new() -> NativeManager { NativeManager { /*devices: Vec::new()*/ } } /// Do a search for controllers. Returns number of controllers. pub(crate) fn search(&mut self) -> (usize, usize) { /* let devices = find_devices(); // Add devices for mut ...
(&self, _i: usize, _state: &mut crate::hid::HidState) { /* if (state.output & crate::hid::Output::HapticStart as u32)!= 0 { self.rumble(i, true); state.output = 0; } else if (state.output & crate::hid::Output::HapticStop as u32)!= 0 { self.rumble(i, false); ...
poll_event
identifier_name
wasm.rs
pub struct NativeManager { } impl NativeManager { pub(crate) fn new() -> NativeManager
/// Do a search for controllers. Returns number of controllers. pub(crate) fn search(&mut self) -> (usize, usize) { /* let devices = find_devices(); // Add devices for mut i in devices { if self.devices.contains(&i) { continue; } open_joystick(&mut i); // Setup device for asynchronous reads...
{ NativeManager { /*devices: Vec::new()*/ } }
identifier_body
wasm.rs
pub struct NativeManager { } impl NativeManager { pub(crate) fn new() -> NativeManager { NativeManager { /*devices: Vec::new()*/ } } /// Do a search for controllers. Returns number of controllers. pub(crate) fn search(&mut self) -> (usize, usize) { /* let devices = find_devices(); // Add devices for mut ...
let effect = joystick_haptic(self.devices[index].fd); self.devices[index].min = min; self.devices[index].max = max; self.devices[index].id = id; self.devices[index].effect = effect; return (self.devices.len(), index); } }*/ (s...
let (_, id, _) = joystick_id(self.devices[index].fd);
random_line_split
sarsa_lambda.rs
use crate::{ domains::Transition, fa::ScaledGradientUpdate, policies::Policy, traces, Differentiable, Function, Handler, Parameterised, }; use rand::thread_rng; #[derive(Clone, Debug)] #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate"...
lse { let ns = t.to.state(); let na = self.policy.sample(&mut thread_rng(), ns); let nqsna = self.fa_theta.evaluate((ns, na)); let residual = t.reward + self.gamma * nqsna - qsa; self.fa_theta.handle(ScaledGradientUpdate { alpha: self.alpha *...
let residual = t.reward - qsa; self.fa_theta.handle(ScaledGradientUpdate { alpha: self.alpha * residual, jacobian: &self.trace, }).map_err(|_| ())?; self.trace.reset(); residual } e
conditional_block
sarsa_lambda.rs
use crate::{ domains::Transition, fa::ScaledGradientUpdate, policies::Policy, traces, Differentiable, Function, Handler, Parameterised, }; use rand::thread_rng; #[derive(Clone, Debug)] #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate"...
let nqsna = self.fa_theta.evaluate((ns, na)); let residual = t.reward + self.gamma * nqsna - qsa; self.fa_theta.handle(ScaledGradientUpdate { alpha: self.alpha * residual, jacobian: &self.trace, }).map_err(|_| ())?; residual ...
let s = t.from.state(); let qsa = self.fa_theta.evaluate((s, &t.action)); // Update trace with latest feature vector: self.trace.update(&self.fa_theta.grad((s, &t.action))); // Update weight vectors: let td_error = if t.terminated() { let residual = t.reward...
identifier_body
sarsa_lambda.rs
use crate::{ domains::Transition, fa::ScaledGradientUpdate, policies::Policy, traces, Differentiable, Function, Handler, Parameterised, }; use rand::thread_rng; #[derive(Clone, Debug)] #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate"...
, P, T> { #[weights] pub fa_theta: Q, pub policy: P, pub trace: T, pub alpha: f64, pub gamma: f64, } type Tr<S, A, Q, R> = traces::Trace<<Q as Differentiable<(S, A)>>::Jacobian, R>; impl<'m, S, Q, P, R> Handler<&'m Transition<S, P::Action>> for SARSALambda< Q, P, Tr<&'m S, &'m P::Action,...
RSALambda<Q
identifier_name
sarsa_lambda.rs
use crate::{ domains::Transition, fa::ScaledGradientUpdate, policies::Policy, traces,
Handler, Parameterised, }; use rand::thread_rng; #[derive(Clone, Debug)] #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate") )] pub struct Response { td_error: f64, } /// On-policy variant of Watkins' Q-learning with eligibility traces (aka /// "modified...
Differentiable, Function,
random_line_split
tsm_vte.rs
#![feature(libc)] extern crate libc; extern crate regex;
use libc::c_char; use libc::c_void; use libc::size_t; use std::ptr; use std::slice; use tsm_sys::*; #[test] fn tsm_vte_stuff_works() { let mut screen = ptr::null_mut(); let err = unsafe { tsm::tsm_screen_new(&mut screen, None, ptr::null_mut()) }; assert_eq!(0, err); let mut vte = ptr::null_mut(); ...
extern crate tsm_sys;
random_line_split
tsm_vte.rs
#![feature(libc)] extern crate libc; extern crate regex; extern crate tsm_sys; use libc::c_char; use libc::c_void; use libc::size_t; use std::ptr; use std::slice; use tsm_sys::*; #[test] fn tsm_vte_stuff_works() { let mut screen = ptr::null_mut(); let err = unsafe { tsm::tsm_screen_new(&mut screen, None, ptr...
{ string: String } let mut output = Output { string: "".to_string() }; let output_ptr: *mut c_void = &mut output as *mut _ as *mut c_void; unsafe { tsm::tsm_vte_new(&mut vte, screen, write_cb, output_ptr, None, ptr::null_mut() ) }; unsafe { tsm::tsm_vte_reset(vte) } unsafe { tsm::tsm_vte_hard_res...
Output
identifier_name
metrics.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use prometheus::*; use prometheus_static_metric::*; make_static_metric! { pub label_enum MvccConflictKind { prewrite_write_conflict, rolled_back, commit_lock_not_found, rollback_committed, acquire_pessimisti...
MvccDuplicateCmdCounterVec, "tikv_storage_mvcc_duplicate_cmd_counter", "Total number of duplicated commands", &["type"] ) .unwrap() }; pub static ref MVCC_CHECK_TXN_STATUS_COUNTER_VEC: MvccCheckTxnStatusCounterVec = { register_static_int_cou...
.unwrap() }; pub static ref MVCC_DUPLICATE_CMD_COUNTER_VEC: MvccDuplicateCmdCounterVec = { register_static_int_counter_vec!(
random_line_split
main.rs
use std::io::File; use map_generator::HeightMap; use coordinate_formula::CoordinateFormula; mod map_generator; mod coordinate_formula; static FILENAME: &'static str = "height_map.out"; fn main()
map_generator::drop_particles(drop_point.as_slice(), (x, y), &mut height_map); coordinate_formula = coordinate_formula.change_iteration(); } // output height map in YAML format let path = Path::new(FILENAME); let mut file = match File::create(&path) { Err(why) => fail!("couldn't create {}: {}", FIL...
{ let size = 50; let number_of_drop_points = 20; let min_particles = 400; let max_particles = 2000; let number_of_passes = 5; let mut coordinate_formula = CoordinateFormula::new(); let mut height_map: HeightMap = HeightMap::new(size); let drops: Vec<Box<Vec<int>>>; drops = Vec::from_fn(number_of_pas...
identifier_body
main.rs
use std::io::File; use map_generator::HeightMap; use coordinate_formula::CoordinateFormula; mod map_generator; mod coordinate_formula; static FILENAME: &'static str = "height_map.out"; fn
() { let size = 50; let number_of_drop_points = 20; let min_particles = 400; let max_particles = 2000; let number_of_passes = 5; let mut coordinate_formula = CoordinateFormula::new(); let mut height_map: HeightMap = HeightMap::new(size); let drops: Vec<Box<Vec<int>>>; drops = Vec::from_fn(number_of_...
main
identifier_name
main.rs
use std::io::File; use map_generator::HeightMap; use coordinate_formula::CoordinateFormula; mod map_generator; mod coordinate_formula; static FILENAME: &'static str = "height_map.out"; fn main() { let size = 50; let number_of_drop_points = 20; let min_particles = 400; let max_particles = 2000; let number_o...
for n in range(0u, size * size) { file.write_line(format!("- {}", *height_map.map.get_mut(n)).as_slice()); } }
random_line_split
init.rs
// // Copyright:: Copyright (c) 2016 Chef Software, Inc. // License:: Apache License, Version 2.0 // // 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...
<'c>() -> App<'c, 'c> { SubCommand::with_name(SUBCOMMAND_NAME) .about( "Initialize a Delivery project \ (and lots more!)", ) .args(&vec![ config_path_arg(), no_open_arg(), project_arg(), local_arg(), config_pr...
clap_subcommand
identifier_name
init.rs
// // Copyright:: Copyright (c) 2016 Chef Software, Inc. // License:: Apache License, Version 2.0 // // 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...
, } } } impl<'n> Options for InitClapOptions<'n> { fn merge_options_and_config(&self, config: Config) -> DeliveryResult<Config> { let project = try!(project::project_or_from_cwd(&self.project)); let new_config = config .set_user(&self.user) .set_server(&self.serve...
{ None }
conditional_block
init.rs
// // Copyright:: Copyright (c) 2016 Chef Software, Inc. // License:: Apache License, Version 2.0 // // 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...
config_path_arg(), no_open_arg(), project_arg(), local_arg(), config_project_arg(), ]) .args_from_usage( "--generator=[generator] 'Local path or Git repo URL to a \ custom ChefDK build_cookbook generator (default:github)...
random_line_split
init.rs
// // Copyright:: Copyright (c) 2016 Chef Software, Inc. // License:: Apache License, Version 2.0 // // 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...
.args(&pipeline_arg()) .args(&project_specific_args()) .args(&vec![a2_mode_arg()]) }
{ SubCommand::with_name(SUBCOMMAND_NAME) .about( "Initialize a Delivery project \ (and lots more!)", ) .args(&vec![ config_path_arg(), no_open_arg(), project_arg(), local_arg(), config_project_arg(), ...
identifier_body
metadata_basic.rs
#[macro_use] extern crate holmes; use holmes::simple::*; #[test] pub fn new_predicate_named_field() { single(&|holmes: &mut Engine, _| { holmes_exec!(holmes, { predicate!(test_pred([first string], bytes, uint64)) }) }) } #[test] pub fn new_predicate_doc_field() { single(&|holme...
() { single(&|holmes: &mut Engine, _| { holmes_exec!(holmes, { predicate!(test_pred([first string "This is the first element"], bytes, uint64) : "This is a test predicate") }) }) } #[test] pub fn predicate_roundtrip() { si...
new_predicate_doc_all
identifier_name
metadata_basic.rs
#[macro_use] extern crate holmes; use holmes::simple::*; #[test] pub fn new_predicate_named_field() { single(&|holmes: &mut Engine, _| { holmes_exec!(holmes, { predicate!(test_pred([first string], bytes, uint64)) }) }) } #[test] pub fn new_predicate_doc_field()
#[test] pub fn new_predicate_doc_all() { single(&|holmes: &mut Engine, _| { holmes_exec!(holmes, { predicate!(test_pred([first string "This is the first element"], bytes, uint64) : "This is a test predicate") }) }) } #[test]...
{ single(&|holmes: &mut Engine, _| { holmes_exec!(holmes, { predicate!(test_pred([first string "This is the first element"], bytes, uint64)) }) }) }
identifier_body
metadata_basic.rs
#[macro_use] extern crate holmes; use holmes::simple::*; #[test] pub fn new_predicate_named_field() { single(&|holmes: &mut Engine, _| { holmes_exec!(holmes, { predicate!(test_pred([first string], bytes, uint64)) }) }) } #[test] pub fn new_predicate_doc_field() { single(&|holme...
}) } #[test] pub fn predicate_roundtrip() { single(&|holmes: &mut Engine, _| { holmes_exec!(holmes, { predicate!(test_pred([first string "This is the first element"], bytes, uint64) : "This is a test predicate") })?; le...
})
random_line_split
mod.rs
pub mod packet; use std::net; use std::io; use std::time::Duration; use time; use protocol::raknet; macro_rules! check_raknet_packet { () => {}; } #[derive(Clone, Debug)] pub struct ServerInfo { pub name: String, pub protocol_version: String, pub client_version: String, pub players_count: u32, ...
use_security: false }.into(), raknet::types::Reliability::Reliable)?; //println!("{:?}", self.session.receive_packet()?); let listen_addr = self.session.listen_address().clone(); self.session.send_encapsulate(&raknet::packet::ClientHandshake { client_addr: list...
{ self.session.set_read_timeout(Some(Duration::from_millis(500)))?; let mtu = self.find_mtu()?; self.session.mtu = mtu as usize; self.session.set_read_timeout(Some(Duration::from_secs(5)))?; self.session.send_packet(&raknet::packet::OfflineConnectionRequest2 { magi...
identifier_body
mod.rs
pub mod packet; use std::net; use std::io; use std::time::Duration; use time; use protocol::raknet; macro_rules! check_raknet_packet { () => {}; } #[derive(Clone, Debug)] pub struct ServerInfo { pub name: String, pub protocol_version: String, pub client_version: String, pub players_count: u32, ...
(&mut self) -> io::Result<u16> { for mtu in (1..(1500 - 46 + 1) / 10).rev() { self.session.send_packet(&raknet::packet::OfflineConnectionRequest1 { magic: raknet::types::Magic, protocol_version: 8, mtu: vec![0; mtu * 10] }.into())?; ...
find_mtu
identifier_name
mod.rs
pub mod packet; use std::net; use std::io; use std::time::Duration; use time; use protocol::raknet; macro_rules! check_raknet_packet { () => {}; } #[derive(Clone, Debug)] pub struct ServerInfo { pub name: String, pub protocol_version: String, pub client_version: String, pub players_count: u32, ...
for mtu in (1..(1500 - 46 + 1) / 10).rev() { self.session.send_packet(&raknet::packet::OfflineConnectionRequest1 { magic: raknet::types::Magic, protocol_version: 8, mtu: vec![0; mtu * 10] }.into())?; match self.session.receive_...
fn find_mtu(&mut self) -> io::Result<u16> {
random_line_split
floatobject.rs
use libc::{c_int, c_double}; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PyFloat_Type: PyTypeObject; } #[inline(always)] pub unsafe fn PyFloat_Check(op : *mut PyObject) -> c_int { PyObject_TypeCheck(op, &mut PyFloat_Type) } #[inline(always)] pub unsafe fn PyFloat_Ch...
pub fn PyFloat_GetInfo() -> *mut PyObject; pub fn PyFloat_FromString(arg1: *mut PyObject) -> *mut PyObject; pub fn PyFloat_FromDouble(arg1: c_double) -> *mut PyObject; pub fn PyFloat_AsDouble(arg1: *mut PyObject) -> c_double; }
pub fn PyFloat_GetMin() -> c_double;
random_line_split
floatobject.rs
use libc::{c_int, c_double}; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PyFloat_Type: PyTypeObject; } #[inline(always)] pub unsafe fn
(op : *mut PyObject) -> c_int { PyObject_TypeCheck(op, &mut PyFloat_Type) } #[inline(always)] pub unsafe fn PyFloat_CheckExact(op : *mut PyObject) -> c_int { (Py_TYPE(op) == &mut PyFloat_Type) as c_int } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PyFloat_GetMax() -> c_double; pub ...
PyFloat_Check
identifier_name
floatobject.rs
use libc::{c_int, c_double}; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PyFloat_Type: PyTypeObject; } #[inline(always)] pub unsafe fn PyFloat_Check(op : *mut PyObject) -> c_int
#[inline(always)] pub unsafe fn PyFloat_CheckExact(op : *mut PyObject) -> c_int { (Py_TYPE(op) == &mut PyFloat_Type) as c_int } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PyFloat_GetMax() -> c_double; pub fn PyFloat_GetMin() -> c_double; pub fn PyFloat_GetInfo() -> *mut PyObject;...
{ PyObject_TypeCheck(op, &mut PyFloat_Type) }
identifier_body
brainruck.rs
use std::os; use std::str; use std::fmt; fn main() { let args = os::args(); if args.len() == 1 { fail!("no arguments"); } run(tokenize(parse_args(args))); } fn parse_args(args: ~[~str]) -> ~str { args[1] } fn tokenize(text: ~str) -> Vec<Token> { let mut tokens: Vec<Token> = Vec:...
#[test] fn testArgParser() { assert_eq!(parse_args(["brainruck".to_owned(), "><+-.,[]".to_owned()].to_owned()), "><+-.,[]".to_owned()); }
{ // Check the tokenizer is getting the right outputs. assert_eq!(tokenize("><+-.,[]".to_owned()).as_slice(), [Right, Left, Plus, Minus, Out, In, Jump, Loop].as_slice()); // Make sure junk is ignored. assert_eq!(tokenize(">a<b+c-d. ,1[2]3 ".to_owned()).as_slice(), [Right, ...
identifier_body
brainruck.rs
use std::os; use std::str; use std::fmt; fn main() { let args = os::args(); if args.len() == 1 { fail!("no arguments"); } run(tokenize(parse_args(args))); } fn parse_args(args: ~[~str]) -> ~str { args[1] } fn tokenize(text: ~str) -> Vec<Token> { let mut tokens: Vec<Token> = Vec:...
{ Right, Left, Plus, Minus, Out, In, Jump, Loop } impl fmt::Show for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f.buf, "{}", match *self { Right => '>', Left => '<', Plus => '+', Minus => '-', ...
Token
identifier_name
brainruck.rs
use std::os; use std::str; use std::fmt; fn main() { let args = os::args(); if args.len() == 1 { fail!("no arguments"); } run(tokenize(parse_args(args))); } fn parse_args(args: ~[~str]) -> ~str { args[1] } fn tokenize(text: ~str) -> Vec<Token> { let mut tokens: Vec<Token> = Vec:...
In => { match std::io::stdin().read_byte() { Ok(b) => {*data.get_mut(pointer) = b}, Err(e) => {fail!("{}", e)} } token_index += 1; }, Jump => { // Jump to end of the loop when t...
None => {} } token_index += 1; },
random_line_split
object-lifetime-default-elision.rs
// Test various cases where the old rules under lifetime elision // yield slightly different results than the new rules. #![allow(dead_code)] trait SomeTrait { fn dummy(&self) { } } struct SomeStruct<'a> { r: Box<dyn SomeTrait+'a> } fn deref<T>(ss: &T) -> T { // produces the type of a deref without worr...
<'a>(ss: &'a Box<dyn SomeTrait>) -> Box<dyn SomeTrait> { // Under old rules, the fully elaborated types of input/output were: // // for<'a,'b> fn(&'a Box<SomeTrait+'b>) -> Box<SomeTrait+'a> // // Under new rules the result is: // // for<'a> fn(&'a Box<SomeTrait+'static>) -> Box<SomeTrait+'st...
load0
identifier_name
object-lifetime-default-elision.rs
// Test various cases where the old rules under lifetime elision // yield slightly different results than the new rules.
#![allow(dead_code)] trait SomeTrait { fn dummy(&self) { } } struct SomeStruct<'a> { r: Box<dyn SomeTrait+'a> } fn deref<T>(ss: &T) -> T { // produces the type of a deref without worrying about whether a // move out would actually be legal loop { } } fn load0<'a>(ss: &'a Box<dyn SomeTrait>) -> ...
random_line_split
object-lifetime-default-elision.rs
// Test various cases where the old rules under lifetime elision // yield slightly different results than the new rules. #![allow(dead_code)] trait SomeTrait { fn dummy(&self) { } } struct SomeStruct<'a> { r: Box<dyn SomeTrait+'a> } fn deref<T>(ss: &T) -> T { // produces the type of a deref without worr...
fn load3<'a,'b>(ss: &'a dyn SomeTrait) -> &'b dyn SomeTrait { // Under old rules, the fully elaborated types of input/output were: // // for<'a,'b,'c>fn(&'a (SomeTrait+'c)) -> &'b (SomeTrait+'a) // // Based on the input/output types, the compiler could infer that // 'c : 'a // 'b :...
{ // Same as `load1` but with an explicit name thrown in for fun. ss }
identifier_body
uint.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 ...
#[cfg(target_endian = "little")] pub fn to_be(x: uint) -> uint { bswap(x) } #[cfg(target_endian = "big")] pub fn to_le(x: uint) -> uint { bswap(x) } #[cfg(target_endian = "little")] pub fn to_le(x: uint) -> uint { x }
{ x }
identifier_body
uint.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 ...
#[inline(always)] pub fn add_with_overflow(x: uint, y: uint) -> (uint, bool) { let (a, b) = ::u64::add_with_overflow(x as u64, y as u64); (a as uint, b) } #[cfg(target_word_size = "32")] #[inline(always)] pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) { let (a, b) = ::u32::sub_with_overflow(x a...
} #[cfg(target_word_size = "64")]
random_line_split
uint.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 ...
(x: uint, y: uint) -> (uint, bool) { let (a, b) = ::u32::sub_with_overflow(x as u32, y as u32); (a as uint, b) } #[cfg(target_word_size = "64")] #[inline(always)] pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) { let (a, b) = ::u64::sub_with_overflow(x as u64, y as u64); (a as uint, b) } #[...
sub_with_overflow
identifier_name
reward.rs
// 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 agreed to in writing, software // distributed ...
// Copyright 2021 The Grin Developers //
random_line_split
reward.rs
// Copyright 2021 The Grin 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 agree...
<K, B>( keychain: &K, builder: &B, key_id: &Identifier, fees: u64, test_mode: bool, ) -> Result<(Output, TxKernel), Error> where K: Keychain, B: ProofBuild, { let value = reward(fees); // TODO: proper support for different switch commitment schemes let switch = SwitchCommitmentType::Regular; let commit = key...
output
identifier_name
reward.rs
// Copyright 2021 The Grin 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 agree...
let msg = features.kernel_sig_msg()?; let sig = match test_mode { true => { let test_nonce = secp::key::SecretKey::from_slice(&secp, &[1; 32])?; aggsig::sign_from_key_id( &secp, keychain, &msg, value, &key_id, Some(&test_nonce), Some(&pubkey), )? } false => { aggsig::sign...
{ let value = reward(fees); // TODO: proper support for different switch commitment schemes let switch = SwitchCommitmentType::Regular; let commit = keychain.commit(value, key_id, switch)?; trace!("Block reward - Pedersen Commit is: {:?}", commit,); let proof = proof::create(keychain, builder, value, key_id, sw...
identifier_body
reward.rs
// Copyright 2021 The Grin 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 agree...
false => { aggsig::sign_from_key_id(&secp, keychain, &msg, value, &key_id, None, Some(&pubkey))? } }; let kernel = TxKernel { features: KernelFeatures::Coinbase, excess, excess_sig: sig, }; Ok((output, kernel)) }
{ let test_nonce = secp::key::SecretKey::from_slice(&secp, &[1; 32])?; aggsig::sign_from_key_id( &secp, keychain, &msg, value, &key_id, Some(&test_nonce), Some(&pubkey), )? }
conditional_block
main.rs
use api; use data; fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) { println!("{}", ds.target_count()); for record in ds.records() { println!("{}", record.0.some_record_meta()); } } fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) { if ds.len(...
() { println!("Hello, API!"); let ds = data::get_data(); println!("is_empty = {}, target_count = {}", ds.is_empty(), ds.target_count()); for record in ds.records() { println!("{:?}", record); } for record in ds.view_records(&api::DataSetView::new(vec![0])) { println!("{:?}", reco...
main
identifier_name
main.rs
use api; use data; fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) { println!("{}", ds.target_count()); for record in ds.records() { println!("{}", record.0.some_record_meta()); } } fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) { if ds.len(...
for record in ds.view_records(view) { println!("{}: {}", index, record.0.some_record_meta()); } view.add_index(index); test2(ds, view, index + 1) } fn main() { println!("Hello, API!"); let ds = data::get_data(); println!("is_empty = {}, target_count = {}", ds.is_empty(), ds.tar...
{ return }
conditional_block
main.rs
use api; use data; fn test<T: api::RecordMeta>(ds: &api::DataSet<T>)
fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) { if ds.len() == index { return } for record in ds.view_records(view) { println!("{}: {}", index, record.0.some_record_meta()); } view.add_index(index); test2(ds, view, index + 1) ...
{ println!("{}", ds.target_count()); for record in ds.records() { println!("{}", record.0.some_record_meta()); } }
identifier_body
main.rs
use api; use data; fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) { println!("{}", ds.target_count()); for record in ds.records() { println!("{}", record.0.some_record_meta()); } } fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) { if ds.len(...
test2(&ds, &mut api::DataSetView::empty(), 0); }
random_line_split
mod.rs
//! This module contains the basic RootMove structures, allowing for storage of the moves from a specific position //! alongside information about each of the moves. pub mod root_moves_list; use std::cmp::Ordering as CmpOrder; use pleco::core::score::*; use pleco::BitMove;
/// Keeps track of information of a move for the position to be searched. #[derive(Copy, Clone,Eq)] pub struct RootMove { pub score: i32, pub prev_score: i32, pub bit_move: BitMove, pub depth_reached: i16, } impl RootMove { /// Creates a new `RootMove`. #[inline] pub fn new(bit_move: BitM...
// 250 as this fits into 64 byte cache lines easily. const MAX_MOVES: usize = 250;
random_line_split
mod.rs
//! This module contains the basic RootMove structures, allowing for storage of the moves from a specific position //! alongside information about each of the moves. pub mod root_moves_list; use std::cmp::Ordering as CmpOrder; use pleco::core::score::*; use pleco::BitMove; // 250 as this fits into 64 byte cache lin...
(bit_move: BitMove) -> Self { RootMove { bit_move, score: NEG_INFINITE as i32, prev_score: NEG_INFINITE as i32, depth_reached: 0, } } /// Places the current score into the previous_score field, and then updates /// the score and depth. #[i...
new
identifier_name
mod.rs
//! This module contains the basic RootMove structures, allowing for storage of the moves from a specific position //! alongside information about each of the moves. pub mod root_moves_list; use std::cmp::Ordering as CmpOrder; use pleco::core::score::*; use pleco::BitMove; // 250 as this fits into 64 byte cache lin...
CmpOrder::Greater } } impl PartialOrd for RootMove { fn partial_cmp(&self, other: &RootMove) -> Option<CmpOrder> { Some(self.cmp(other)) } } impl PartialEq for RootMove { fn eq(&self, other: &RootMove) -> bool { self.score == other.score && self.prev_score == other.prev_score...
{ return CmpOrder::Less; }
conditional_block