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
move_semantics2.rs
// Make me compile without changing line 9! Scroll down for hints :) pub fn main()
fn fill_vec(vec: &mut Vec<i32>) { vec.push(22); vec.push(44); vec.push(66); } // So `vec0` is being *moved* into the function `fill_vec` when we call it on // line 6, which means it gets dropped at the end of `fill_vec`, which means we // can't use `vec0` again on line 9 (or anywhere else in...
{ let mut vec0 = Vec::new(); fill_vec(&mut vec0); // Do not change the following line! println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0); vec0.push(88); println!("{} has length {} content `{:?}`", "vec1", vec0.len(), vec0); }
identifier_body
move_semantics2.rs
// Make me compile without changing line 9! Scroll down for hints :) pub fn main() { let mut vec0 = Vec::new(); fill_vec(&mut vec0); // Do not change the following line! println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0); vec0.push(88); println!("{} has length {} content ...
// `fill_vec` call for that matter). We could fix this in a few ways, try them // all! // 1. Make another, separate version of the data that's in `vec0` and pass that // to `fill_vec` instead. // 2. Make `fill_vec` borrow its argument instead of taking ownership of it, // and then copy the data within the function in o...
// line 6, which means it gets dropped at the end of `fill_vec`, which means we // can't use `vec0` again on line 9 (or anywhere else in `main` after the
random_line_split
move_semantics2.rs
// Make me compile without changing line 9! Scroll down for hints :) pub fn main() { let mut vec0 = Vec::new(); fill_vec(&mut vec0); // Do not change the following line! println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0); vec0.push(88); println!("{} has length {} content ...
(vec: &mut Vec<i32>) { vec.push(22); vec.push(44); vec.push(66); } // So `vec0` is being *moved* into the function `fill_vec` when we call it on // line 6, which means it gets dropped at the end of `fill_vec`, which means we // can't use `vec0` again on line 9 (or anywhere else in `main` after...
fill_vec
identifier_name
contact_model.rs
#![allow(missing_docs)] use downcast_rs::Downcast; use na::{DVector, RealField}; use ncollide::query::ContactId; use crate::detection::ColliderContactManifold; use crate::material::MaterialsCoefficientsTable; use crate::object::{BodyHandle, BodySet, ColliderHandle}; use crate::solver::{ConstraintSet, IntegrationParam...
manifolds: &[ColliderContactManifold<N, Handle, CollHandle>], ground_j_id: &mut usize, j_id: &mut usize, jacobians: &mut [N], constraints: &mut ConstraintSet<N, Handle, CollHandle, ContactId>, ); /// Stores all the impulses found by the solver into a cache for warmstarti...
random_line_split
main.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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, inc...
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial ...
random_line_split
main.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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, inc...
() -> Result<(), Box<dyn std::error::Error>> { let args: Vec<String> = ::std::env::args().collect(); if args.len() >= 2 { match &args[1][..] { "client" => return client::main().await, "server" => return server::main().await, _ => () } } println!("usag...
main
identifier_name
main.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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, inc...
{ let args: Vec<String> = ::std::env::args().collect(); if args.len() >= 2 { match &args[1][..] { "client" => return client::main().await, "server" => return server::main().await, _ => () } } println!("usage: {} [client | server] ADDRESS", args[0]); ...
identifier_body
get.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
(rt: &Runtime) { let scmd = rt.cli().subcommand_matches("get").unwrap(); let id = scmd.value_of("id").unwrap(); // safe by clap let path = PathBuf::from(id); let store = Some(rt.store().path().clone()); let path = StoreId::new(store, path).unwrap_or_else(|e| trace_error_exit(&e, 1)); debug...
get
identifier_name
get.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
use libimagstore::storeid::StoreId; use retrieve::print_entry; pub fn get(rt: &Runtime) { let scmd = rt.cli().subcommand_matches("get").unwrap(); let id = scmd.value_of("id").unwrap(); // safe by clap let path = PathBuf::from(id); let store = Some(rt.store().path().clone()); let path = Store...
random_line_split
get.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
{ let scmd = rt.cli().subcommand_matches("get").unwrap(); let id = scmd.value_of("id").unwrap(); // safe by clap let path = PathBuf::from(id); let store = Some(rt.store().path().clone()); let path = StoreId::new(store, path).unwrap_or_else(|e| trace_error_exit(&e, 1)); debug!("path = {:?}"...
identifier_body
mod.rs
mod areas; mod area_frame_allocator; mod paging; mod info; use self::paging::{PAGE_SIZE, PhysicalAddress}; use self::area_frame_allocator::{AreaFrameAllocator}; use spin::{Once, Mutex, MutexGuard}; pub use self::paging::{Page, VirtualAddress}; pub use self::paging::entry::{EntryFlags}; pub const KERNEL_OFFSET: usize...
/// Align upwards. Returns the smallest x with alignment `align` /// so that x >= addr. The alignment must be a power of 2. pub fn align_up(addr: usize, align: usize) -> usize { align_down(addr + align - 1, align) } pub fn init(boot_info: &::bootinfo::BootInfo) { println!("Initializing Memory"); areas::i...
{ if align.is_power_of_two() { addr & !(align - 1) } else if align == 0 { addr } else { panic!("`align` must be a power of 2"); } }
identifier_body
mod.rs
mod areas; mod area_frame_allocator; mod paging; mod info; use self::paging::{PAGE_SIZE, PhysicalAddress}; use self::area_frame_allocator::{AreaFrameAllocator}; use spin::{Once, Mutex, MutexGuard}; pub use self::paging::{Page, VirtualAddress}; pub use self::paging::entry::{EntryFlags}; pub const KERNEL_OFFSET: usize...
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] pub struct Frame { number: usize, } impl Frame { fn containing_address(address: PhysicalAddress) -> Frame { Frame { number: address.get() / PAGE_SIZE } } fn start_address(&self) -> PhysicalAddress { PhysicalAddress::new(self...
MEMORY_CONTROLLER.try().expect("Memory not yet initialized").lock() } //TODO Figure out if we want Copy and Clone on this
random_line_split
mod.rs
mod areas; mod area_frame_allocator; mod paging; mod info; use self::paging::{PAGE_SIZE, PhysicalAddress}; use self::area_frame_allocator::{AreaFrameAllocator}; use spin::{Once, Mutex, MutexGuard}; pub use self::paging::{Page, VirtualAddress}; pub use self::paging::entry::{EntryFlags}; pub const KERNEL_OFFSET: usize...
else if align == 0 { addr } else { panic!("`align` must be a power of 2"); } } /// Align upwards. Returns the smallest x with alignment `align` /// so that x >= addr. The alignment must be a power of 2. pub fn align_up(addr: usize, align: usize) -> usize { align_down(addr + align - 1, alig...
{ addr & !(align - 1) }
conditional_block
mod.rs
mod areas; mod area_frame_allocator; mod paging; mod info; use self::paging::{PAGE_SIZE, PhysicalAddress}; use self::area_frame_allocator::{AreaFrameAllocator}; use spin::{Once, Mutex, MutexGuard}; pub use self::paging::{Page, VirtualAddress}; pub use self::paging::entry::{EntryFlags}; pub const KERNEL_OFFSET: usize...
(start: Frame, end: Frame) -> FrameIter { FrameIter { start: start, end: end, } } } struct FrameIter { start: Frame, end: Frame, } impl Iterator for FrameIter { type Item = Frame; fn next(&mut self) -> Option<Frame> { if self.start <= self.end { ...
range_inclusive
identifier_name
utils.rs
// Copyright 2014 Jonathan Eyolfson use libc::{c_char, c_int, c_void, size_t, uint32_t, uint64_t}; #[repr(C)] pub type wl_argument = uint64_t; #[repr(C)] pub struct wl_array { pub size: size_t, pub alloc: size_t, pub data: *mut c_void, } #[repr(C)] pub type wl_dispatcher_func_t = extern fn( _: *cons...
;
wl_object
identifier_name
utils.rs
// Copyright 2014 Jonathan Eyolfson use libc::{c_char, c_int, c_void, size_t, uint32_t, uint64_t}; #[repr(C)] pub type wl_argument = uint64_t; #[repr(C)] pub struct wl_array { pub size: size_t, pub alloc: size_t, pub data: *mut c_void, } #[repr(C)] pub type wl_dispatcher_func_t = extern fn( _: *cons...
pub next: *mut wl_list, } #[repr(C)] pub type wl_log_func_t = extern fn(_: *const c_char,...); #[repr(C)] pub struct wl_message { pub name: *const c_char, pub signature: *const c_char, pub types: *mut *const wl_interface, } #[repr(C)] pub struct wl_object;
random_line_split
4_04_system_of_systems.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // example 4-04: System of Systems use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { systems: Vec<ParticleSystem>, } // A simple particle type struct Particle { position: Point2<f32>, ve...
struct ParticleSystem { particles: Vec<Particle>, origin: Point2<f32>, } impl ParticleSystem { fn new(num: i32, position: Point2<f32>) -> Self { let origin = position; // An origin point for where particles are birthed let mut particles = Vec::new(); // Initialise the Vector for _i...
random_line_split
4_04_system_of_systems.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // example 4-04: System of Systems use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { systems: Vec<ParticleSystem>, } // A simple particle type struct Particle { position: Point2<f32>, ve...
} } struct ParticleSystem { particles: Vec<Particle>, origin: Point2<f32>, } impl ParticleSystem { fn new(num: i32, position: Point2<f32>) -> Self { let origin = position; // An origin point for where particles are birthed let mut particles = Vec::new(); // Initialise the Vector ...
{ false }
conditional_block
4_04_system_of_systems.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // example 4-04: System of Systems use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct
{ systems: Vec<ParticleSystem>, } // A simple particle type struct Particle { position: Point2<f32>, velocity: Vector2<f32>, acceleration: Vector2<f32>, life_span: f32, } impl Particle { fn new(l: Point2<f32>) -> Self { let acceleration = vec2(0.0, 0.05); let velocity = vec2(r...
Model
identifier_name
mongo.rs
extern crate bson; extern crate mongo_driver; use bson::Bson; use mongo_driver::CommandAndFindOptions; use mongo_driver::client::{ClientPool, Uri}; use mongo_driver::collection::UpdateOptions; use mongo_driver::flags::UpdateFlag; use config::DBConfig; use objects::{utils, Object}; use storage::error::{StoreError, Sto...
{ config: DBConfig, pool: ClientPool, } impl MongoStore { pub fn new(config: &DBConfig) -> StoreResult<MongoStore> { let conn = MongoStore::conn( config.username.as_str(), config.password.as_str(), config.host.as_str(), config.port, ); ...
MongoStore
identifier_name
mongo.rs
extern crate bson; extern crate mongo_driver; use bson::Bson; use mongo_driver::CommandAndFindOptions; use mongo_driver::client::{ClientPool, Uri}; use mongo_driver::collection::UpdateOptions;
use config::DBConfig; use objects::{utils, Object}; use storage::error::{StoreError, StoreResult}; use storage::storage::{Storage, StorageStatus}; pub struct MongoStore { config: DBConfig, pool: ClientPool, } impl MongoStore { pub fn new(config: &DBConfig) -> StoreResult<MongoStore> { let conn = ...
use mongo_driver::flags::UpdateFlag;
random_line_split
mongo.rs
extern crate bson; extern crate mongo_driver; use bson::Bson; use mongo_driver::CommandAndFindOptions; use mongo_driver::client::{ClientPool, Uri}; use mongo_driver::collection::UpdateOptions; use mongo_driver::flags::UpdateFlag; use config::DBConfig; use objects::{utils, Object}; use storage::error::{StoreError, Sto...
_ => None, }, _ => None, }) }); res }) .fold(None, |max, cur| match max { Some(val) => Some(::std::cmp::max(val, cu...
{ Some(datetime.timestamp()) }
conditional_block
heap.rs
use std::cell::UnsafeCell; use std::mem; use std::ptr; /// `BytesRef` refers to a slice in tantivy's custom `Heap`. #[derive(Copy, Clone)] pub struct BytesRef { pub start: u32, pub stop: u32, } /// Object that can be allocated in tantivy's custom `Heap`. pub trait HeapAllocable { fn with_addr(addr: u32) -...
else { (self.buffer.len() as u32) - self.used } } pub fn allocate_space(&mut self, num_bytes: usize) -> u32 { let addr = self.used; self.used += num_bytes as u32; let buffer_len = self.buffer.len(); if self.used > buffer_len as u32 { self.buffer....
{ 0u32 }
conditional_block
heap.rs
use std::cell::UnsafeCell; use std::mem; use std::ptr; /// `BytesRef` refers to a slice in tantivy's custom `Heap`. #[derive(Copy, Clone)] pub struct BytesRef { pub start: u32, pub stop: u32, } /// Object that can be allocated in tantivy's custom `Heap`. pub trait HeapAllocable { fn with_addr(addr: u32) -...
fn get_slice(&self, start: u32, stop: u32) -> &[u8] { &self.buffer[start as usize..stop as usize] } fn get_mut_slice(&mut self, start: u32, stop: u32) -> &mut [u8] { &mut self.buffer[start as usize..stop as usize] } fn allocate_and_set(&mut self, data: &[u8]) -> BytesRef { ...
random_line_split
heap.rs
use std::cell::UnsafeCell; use std::mem; use std::ptr; /// `BytesRef` refers to a slice in tantivy's custom `Heap`. #[derive(Copy, Clone)] pub struct BytesRef { pub start: u32, pub stop: u32, } /// Object that can be allocated in tantivy's custom `Heap`. pub trait HeapAllocable { fn with_addr(addr: u32) -...
(&mut self, start: u32, stop: u32) -> &mut [u8] { &mut self.buffer[start as usize..stop as usize] } fn allocate_and_set(&mut self, data: &[u8]) -> BytesRef { let start = self.allocate_space(data.len()); let stop = start + data.len() as u32; self.get_mut_slice(start, stop).clone_...
get_mut_slice
identifier_name
stylesheet_loader.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 https://mozilla.org/MPL/2.0/. */ use crate::document_loader::LoadType; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::...
fn resource_timing(&self) -> &ResourceFetchTiming { &self.resource_timing } fn submit_resource_timing(&mut self) { network_listener::submit_timing(self) } } impl ResourceTimingListener for StylesheetContext { fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) { ...
{ &mut self.resource_timing }
identifier_body
stylesheet_loader.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 https://mozilla.org/MPL/2.0/. */ use crate::document_loader::LoadType; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::...
{ // NB: `media` is just an option so we avoid cloning it. LinkElement { media: Option<MediaList> }, Import(Arc<Stylesheet>), } /// The context required for asynchronously loading an external stylesheet. pub struct StylesheetContext { /// The element that initiated the request. elem: Trusted<HTMLE...
StylesheetContextSource
identifier_name
stylesheet_loader.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 https://mozilla.org/MPL/2.0/. */ use crate::document_loader::LoadType; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::...
, } if let Some(ref shadow_root) = self.shadow_root { shadow_root.root().invalidate_stylesheets(); } else { document.invalidate_stylesheets(); } // FIXME: Revisit once consensus is reached at: // https://github.com...
{ Stylesheet::update_from_bytes( &stylesheet, &data, protocol_encoding_label, Some(environment_encoding), final_url, Some(&loader), ...
conditional_block
stylesheet_loader.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 https://mozilla.org/MPL/2.0/. */ use crate::document_loader::LoadType; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::...
&self, source: StylesheetContextSource, url: ServoUrl, cors_setting: Option<CorsSettings>, integrity_metadata: String, ) { let document = document_from_node(self.elem); let shadow_root = containing_shadow_root(self.elem).map(|sr| Trusted::new(&*sr)); l...
pub fn load(
random_line_split
solve.rs
// http://rosettacode.org/wiki/24_game/Solve //! Modeled after [the Scala solution] //! //! [the Scala solution]: http://rosettacode.org/wiki/24_game/Solve#Scala #![feature(slice_patterns)] extern crate num; extern crate permutohedron; use num::rational::{Ratio, Rational}; use num::traits::Zero; use permutohedron::He...
() { let mut r = rationals![1, 3, 7, 9]; assert_eq!(solve(&mut r[..], 24), Some("(9 / (3 / (1 + 7)))".to_string())); }
test_solve
identifier_name
solve.rs
// http://rosettacode.org/wiki/24_game/Solve //! Modeled after [the Scala solution] //! //! [the Scala solution]: http://rosettacode.org/wiki/24_game/Solve#Scala #![feature(slice_patterns)] extern crate num; extern crate permutohedron; use num::rational::{Ratio, Rational}; use num::traits::Zero; use permutohedron::He...
/// for a vector of rationals r, find the combination of arithmentic operations that yield /// `target_val` as a result (if such combination exists) fn solve(r: &mut [Rational], target_val: isize) -> Option<String> { // need to sort because next_permutation() // returns permutations in lexicographic order ...
{ let mut r = rationals![1, 3, 7, 9]; let sol = solve(&mut r[..], 24).unwrap_or("no solution found".to_string()); println!("{}", sol); }
identifier_body
solve.rs
// http://rosettacode.org/wiki/24_game/Solve //! Modeled after [the Scala solution] //! //! [the Scala solution]: http://rosettacode.org/wiki/24_game/Solve#Scala #![feature(slice_patterns)] extern crate num; extern crate permutohedron; use num::rational::{Ratio, Rational}; use num::traits::Zero; use permutohedron::He...
fn test_solve() { let mut r = rationals![1, 3, 7, 9]; assert_eq!(solve(&mut r[..], 24), Some("(9 / (3 / (1 + 7)))".to_string())); }
#[ignore]
random_line_split
self_authentication.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
// // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. //! Self-authentication example. // For explanation of lint checks, run `rustc -W help` or see // https://github. // com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%2...
// // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied.
random_line_split
self_authentication.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
() {}
main
identifier_name
self_authentication.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
{}
identifier_body
domparser.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::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::D...
Ok(DOMParser::new(global.as_window())) } } impl<'a> DOMParserMethods for JSRef<'a, DOMParser> { // http://domparsing.spec.whatwg.org/#the-domparser-interface fn ParseFromString(self, s: DOMString, ty: DOMParserBinding::SupportedType) ...
random_line_split
domparser.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::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::D...
(self, s: DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<Temporary<Document>> { let window = self.window.root(); let url = window.r().get_url(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty ...
ParseFromString
identifier_name
domparser.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::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::D...
} } }
{ //FIXME: this should probably be FromParser when we actually parse the string (#3756). Ok(Document::new(window.r(), Some(url.clone()), IsHTMLDocument::NonHTMLDocument, Some(content_type), ...
conditional_block
domparser.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::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::D...
None, DocumentSource::NotFromParser)) } } } }
{ let window = self.window.root(); let url = window.r().get_url(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned(); match ty { Text_html => { let document = Document::new(window.r(), Some(url.clone()), ...
identifier_body
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codeg...
#[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLAppletElement> { let element = HTMLAppletElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAppletE...
{ HTMLAppletElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
identifier_body
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codeg...
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLAppletElement> { let element = HTMLAppletElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAppletElementBinding::Wrap) } } impl HTMLAppletElem...
new
identifier_name
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codeg...
impl VirtualMethods for HTMLAppletElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("name") => AttrValue::from_atom...
make_atomic_setter!(SetName, "name"); }
random_line_split
test_client.rs
t your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GN...
let len = logs.len(); match filter.limit { Some(limit) if limit <= len => logs.split_off(len - limit), _ => logs, } } fn last_hashes(&self) -> LastHashes { unimplemented!(); } fn best_block_header(&self) -> encoded::Header { self.block_header(BlockId::Hash(self.chain_info().best_block_hash)) .e...
random_line_split
test_client.rs
your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU...
(&self, id: BlockId) -> Option<encoded::Block> { self.block_hash(id) .and_then(|hash| self.blocks.read().get(&hash).cloned()) .map(encoded::Block::new) } fn block_extra_info(&self, id: BlockId) -> Option<BTreeMap<String, String>> { self.block(id) .map(|block| block.view().header()) .map(|header| self...
block
identifier_name
test_client.rs
your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU...
// works only if blocks are one after another 1 -> 2 -> 3 fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute> { Some(TreeRoute { ancestor: H256::new(), index: 0, blocks: { let numbers_read = self.numbers.read(); let mut adding = false; let mut blocks = Vec::new(); for (_, h...
{ match id { BlockId::Number(number) if (number as usize) < self.blocks.read().len() => BlockStatus::InChain, BlockId::Hash(ref hash) if self.blocks.read().get(hash).is_some() => BlockStatus::InChain, BlockId::Latest | BlockId::Pending | BlockId::Earliest => BlockStatus::InChain, _ => BlockStatus::Unknown...
identifier_body
test_client.rs
your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU...
else { None } } fn latest_balance(&self, address: &Address) -> U256 { self.balance(address, BlockId::Latest).unwrap() } fn storage_at(&self, address: &Address, position: &H256, id: BlockId) -> Option<H256> { if let BlockId::Latest = id { Some(self.storage.read().get(&(address.clone(), position.clone(...
{ Some(self.balances.read().get(address).cloned().unwrap_or_else(U256::zero)) }
conditional_block
cleanup-rvalue-scopes-cf.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 _x = AddFlags(1).get(); //~ ERROR value does not live long enough let _x = &*arg(&AddFlags(1)); //~ ERROR value does not live long enough let ref _x = *arg(&AddFlags(1)); //~ ERROR value does not live long enough let &ref _x = arg(&AddFlags(1)); //~ ERROR value does not live long enough let _x =...
random_line_split
cleanup-rvalue-scopes-cf.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 ...
{ bits: u64 } fn AddFlags(bits: u64) -> AddFlags { AddFlags { bits: bits } } fn arg<'a>(x: &'a AddFlags) -> &'a AddFlags { x } impl AddFlags { fn get<'a>(&'a self) -> &'a AddFlags { self } } pub fn main() { let _x = arg(&AddFlags(1)); //~ ERROR value does not live long enough let _x...
AddFlags
identifier_name
mod.rs
pub mod semantic; #[derive(Debug)] pub struct Program(pub Vec<Function>); #[derive(Debug)] pub struct Function { pub name: String, pub returns: Type, pub statements: Vec<Statement> } #[derive(Debug)] pub enum Statement { Block(Vec<Statement>), Declare(Type, String, Expression), Assign(String,...
{ Neg } #[derive(Debug, Clone)] pub enum BinaryOp { Add, Sub, Mul, Div, Mod } #[derive(Debug, Clone)] pub enum Type { Unknown, Error, Any, Void, Int, Char, Bool, Str, Array(Box<Type>), Pair(Box<Type>, Box<Type>) } impl PartialEq for Type { fn eq(&s...
UnaryOp
identifier_name
mod.rs
pub mod semantic; #[derive(Debug)] pub struct Program(pub Vec<Function>); #[derive(Debug)] pub struct Function { pub name: String, pub returns: Type, pub statements: Vec<Statement> } #[derive(Debug)] pub enum Statement { Block(Vec<Statement>), Declare(Type, String, Expression), Assign(String,...
} #[derive(Debug, Clone)] pub enum Type { Unknown, Error, Any, Void, Int, Char, Bool, Str, Array(Box<Type>), Pair(Box<Type>, Box<Type>) } impl PartialEq for Type { fn eq(&self, other: &Type) -> bool { match *self { Type::Unknown => false, ...
Div, Mod
random_line_split
canvasgradient.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 cssparser::RGBA; use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradien...
}
{ let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => { FillOrStrokeStyle::LinearGradient( LinearGradientStyle::new(gradient.x0, gradient.y0, gradie...
identifier_body
canvasgradient.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 cssparser::RGBA; use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradien...
FillOrStrokeStyle::LinearGradient( LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) }, CanvasGradientStyle::Radial(ref gradie...
fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => {
random_line_split
canvasgradient.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 cssparser::RGBA; use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradien...
{ Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } ...
CanvasGradientStyle
identifier_name
canvasgradient.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 cssparser::RGBA; use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradien...
} } }
{ FillOrStrokeStyle::RadialGradient( RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) }
conditional_block
track.rs
use chill::DocumentId; use id3::Tag; use Uri; #[derive(Serialize, Deserialize, Debug)] pub struct Track { #[serde(rename="type")] _type: String, pub name: String, pub number: u32, pub artist: DocumentId, pub album: DocumentId, pub uris: Vec<Uri>, } impl Track { pub fn new(name: &str, ...
{ pub name: String, pub number: u32, pub artist: String, pub album: String, pub uri: Uri, } impl DecodedTrack { pub fn from_tag(tag: Tag, uri: Uri) -> Option<DecodedTrack> { let artist = match tag.artist() { Some(artist) => artist, None => return None, ...
DecodedTrack
identifier_name
track.rs
use chill::DocumentId; use id3::Tag; use Uri; #[derive(Serialize, Deserialize, Debug)] pub struct Track { #[serde(rename="type")] _type: String, pub name: String, pub number: u32, pub artist: DocumentId, pub album: DocumentId, pub uris: Vec<Uri>, } impl Track { pub fn new(name: &str, ...
#[derive(Serialize, Deserialize, Debug)] pub struct DecodedTrack { pub name: String, pub number: u32, pub artist: String, pub album: String, pub uri: Uri, } impl DecodedTrack { pub fn from_tag(tag: Tag, uri: Uri) -> Option<DecodedTrack> { let artist = match tag.artist() { S...
}
random_line_split
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1...
(mut out_port: pm::OutputPort, verbose: bool) -> pm::Result<()> { for &(note, dur) in MELODY.iter().cycle() { let note_on = MidiMessage { status: 0x90 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose { println!("{}", note...
play
identifier_name
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1...
}; if verbose { println!("{}", note_off); } out_port.write_message(note_off)?; // short pause thread::sleep(Duration::from_millis(100)); } Ok(()) }
{ for &(note, dur) in MELODY.iter().cycle() { let note_on = MidiMessage { status: 0x90 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose { println!("{}", note_on) } out_port.write_message(note_on)?; ...
identifier_body
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1...
Options: -h --help Show this screen. -v --verbose Print what's being done Omitting <device-id> will list the available devices. "#; #[derive(Debug, RustcDecodable)] struct Args { arg_device_id: i32, flag_verbose: bool, } fn print_devices(pm: &pm::PortMidi) { for dev in pm.devices().unwra...
random_line_split
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1...
out_port.write_message(note_on)?; // note hold time before sending note off thread::sleep(Duration::from_millis(dur as u64 * 400)); let note_off = MidiMessage { status: 0x80 + CHANNEL, data1: note, data2: 100, data3: 0, }; ...
{ println!("{}", note_on) }
conditional_block
aaaa.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *
* See the License for the specific language governing permissions and * limitations under the License. */ //! Parser for AAAA text form use std::net::Ipv6Addr; use std::str::FromStr; use crate::error::*; /// Parse the RData from a set of Tokens pub fn parse<'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> Pars...
* http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
random_line_split
aaaa.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
{ let address: Ipv6Addr = tokens .next() .ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv6 address".to_string()))) .and_then(|s| Ipv6Addr::from_str(s).map_err(Into::into))?; Ok(address) }
identifier_body
aaaa.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
<'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> ParseResult<Ipv6Addr> { let address: Ipv6Addr = tokens .next() .ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv6 address".to_string()))) .and_then(|s| Ipv6Addr::from_str(s).map_err(Into::into))?; Ok(address) }
parse
identifier_name
integration_test.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
() { tink_daead::init(); let kh = tink_core::keyset::Handle::new(&tink_daead::aes_siv_key_template()).unwrap(); // NOTE: save the keyset to a safe location. DO NOT hardcode it in source code. // Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. // See https://github...
example
identifier_name
integration_test.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
// Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. // See https://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets. let d = tink_daead::new(&kh).unwrap(); let msg = b"this data needs to be encrypted"; let aad = b"this da...
random_line_split
integration_test.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
assert_eq!(msg, &pt[..]); } #[test] fn test_deterministic_aead_init() { // Check for AES-SIV key manager. tink_daead::init(); assert!(tink_core::registry::get_key_manager(tink_tests::AES_SIV_TYPE_URL).is_ok()); }
{ tink_daead::init(); let kh = tink_core::keyset::Handle::new(&tink_daead::aes_siv_key_template()).unwrap(); // NOTE: save the keyset to a safe location. DO NOT hardcode it in source code. // Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. // See https://github.co...
identifier_body
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<...
else { None } } } pub struct Children<'a, N: 'a, Ix: IndexType>(&'a Dag<N, Edge, Ix>, ::daggy::Children<N, Edge, Ix>); impl<'a, N: 'a, Ix: IndexType> Iterator for Children<'a, N, Ix> { type Item = (u32, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if let Some((edge, n...
{ let edge = self.0.edge_weight(edge).unwrap(); Some((port(node, edge.source), edge.target)) }
conditional_block
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<...
} pub fn remove_outgoing_edges(&mut self, node: NodeIndex<Ix>) { let mut walker = self.dag.children(node); while let Some(e) = walker.next_edge(&self.dag) { self.dag.remove_edge(e); } } } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn add_node(&mut self, weight...
random_line_split
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<...
} pub struct Edges<'a, Ix: IndexType>(::daggy::RawEdges<'a, Edge, Ix>, usize); impl<'a, Ix: IndexType> Iterator for Edges<'a, Ix> { type Item = (Port<Ix>, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if self.1 < self.0.len() { let e = &self.0[self.1]; self.1 += 1; ...
{ WouldBreak::WouldCycle }
identifier_body
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<...
(&mut self, node: NodeIndex<Ix>) { let mut walker = self.dag.children(node); while let Some(e) = walker.next_edge(&self.dag) { self.dag.remove_edge(e); } } } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> { self.da...
remove_outgoing_edges
identifier_name
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword;
// #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use config::Config; use clap::ArgMatches; use colored::*; use question::{Answer, Question}; use std::process; use std::{env, fs}; fn main() { /* This makes panic! pretty */ // setup_panic!(); /* Defin...
extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml;
random_line_split
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword; extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml; // #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use ...
(matches: &ArgMatches) { if!ssh::get_directory().exists() { fs::create_dir_all(ssh::get_directory()).unwrap(); } let name = matches.value_of("name").unwrap(); let addr = matches.value_of("addr").unwrap(); ssh::generate_key( &ssh::get_directory().to_str().unwrap(), &format!("...
handle_generate
identifier_name
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword; extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml; // #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use ...
let pub_path = keywoman::generate_root(ks_path, pass); /* Print about our success */ println!(""); println!("{}", "✨ A new keystore was generated for you ✨".green()); println!("Your root public key can be found here: '{}'", pub_path); } fn handle_load(matches: &ArgMatches) {}
{ eprintln!("{}", "The two passwords did not match!".red()); process::exit(2); }
conditional_block
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword; extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml; // #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use ...
fn handle_generate(matches: &ArgMatches) { if!ssh::get_directory().exists() { fs::create_dir_all(ssh::get_directory()).unwrap(); } let name = matches.value_of("name").unwrap(); let addr = matches.value_of("addr").unwrap(); ssh::generate_key( &ssh::get_directory().to_str().unwrap()...
{ /* This makes panic! pretty */ // setup_panic!(); /* Define our CLI App */ let m = cli::create().get_matches(); /* In this block we can unwrap quite viciously because clap will protect us */ match m.subcommand() { ("setup", Some(m)) => handle_setup(m), ("load", Some(m)) => ha...
identifier_body
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied...
() -> Coordinate { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); loop { input.clear(); print!("row? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let r...
read_coordinate
identifier_name
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied...
}; match Coordinate::new(row, col) { None => { println!("coordinate out of playable range"); continue; } Some(c) => return c, } } } // pub fn write_search_graph(graph: &mcts::ThudGraph, state: &ThudState) { // println!("to play: {:?}", state.active_role()); // m...
{ println!("bad col"); continue; }
conditional_block
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied...
print!("col? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let col: u8 = match input.trim().parse() { Ok(c) if c <= 14 => c, _ => { println!("bad col"); continue; } }...
{ let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); loop { input.clear(); print!("row? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let row: u8 = match...
identifier_body
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied...
.expect("could not read from stdin"); let row: u8 = match input.trim().parse() { Ok(r) if r <= 14 => r, _ => { println!("bad row"); continue; } }; input.clear(); print!("col? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&m...
stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok()
random_line_split
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-androi...
// http://rust-lang.org/COPYRIGHT.
random_line_split
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} fn zzz() {()}
{ // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b000100010...
identifier_body
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() {()}
zzz
identifier_name
macros.rs
// Most of our lookups follow the same pattern - macro out the repetition. macro_rules! ares_call { ( $ares_call:ident, $channel:expr, $name:expr, $dns_class:expr, $query_type:expr, $callback:expr, $handler:expr ) => {{ let c_name = CString::new($n...
$dns_class as c_int, $query_type as c_int, Some($callback), c_arg as *mut c_void, ); } panic::propagate(); }}; } macro_rules! ares_query { ($($arg:tt)*) => { ares_call!(ares_query, $($arg)*) } } macro_rules! ares_searc...
$channel, c_name.as_ptr(),
random_line_split
lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&mut self, color: color::Color) -> io::IoResult<bool> { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(self.ti .strings .find_equiv(&("setab")) .unwrap() ...
bg
identifier_name
lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some() { inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n) ...
let mut file = entry.unwrap(); let ti = parse(&mut file, false);
random_line_split
lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn dim_if_necessary(&self, color: color::Color) -> color::Color { if color >= self.num_colors && color >= 8 && color < 16 { color-8 } else { color } } /// Returns the contained stream pub fn unwrap(self) -> T { self.out } /// Gets an immutable reference to the stream ...
{ let mut cap = self.ti.strings.find_equiv(&("sgr0")); if cap.is_none() { // are there any terminals that have color/attrs and not sgr0? // Try falling back to sgr, then op cap = self.ti.strings.find_equiv(&("sgr")); if cap.is_none() { cap ...
identifier_body
lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
let mut file = entry.unwrap(); let ti = parse(&mut file, false); if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some()...
{ if "cygwin" == term { // msys terminal return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8}); } return Err(entry.unwrap_err()); }
conditional_block
silence.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, BotConfig}; use ::core::{EventQueue, Message}; use ::action::{ActionHandler, ActionGroup}; // Action Implementation ---------...
(&mut self, bot: &mut Bot, _: &BotConfig, _: &mut EventQueue) -> ActionGroup { if let Some(server) = bot.get_server(&self.message.server_id) { server.silence_active_effects() } vec![] } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ...
run
identifier_name
silence.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, BotConfig}; use ::core::{EventQueue, Message}; use ::action::{ActionHandler, ActionGroup}; // Action Implementation ---------...
vec![] } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[Action] [SilenceActiveEffects] Server #{}", self.message.server_id ) } }
{ server.silence_active_effects() }
conditional_block
silence.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt;
// Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, BotConfig}; use ::core::{EventQueue, Message}; use ::action::{ActionHandler, ActionGroup}; // Action Implementation ------------------------------------------------------ pub struct Action { message: Message } impl A...
random_line_split
extendableevent.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::EventBinding::{self, EventMethods}; use dom::bindings::codegen::Bindings::Ex...
() -> ExtendableEventBinding::ExtendableEventInit { ExtendableEventBinding::ExtendableEventInit { parent: EventBinding::EventInit::default(), } } }
default
identifier_name
extendableevent.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::EventBinding::{self, EventMethods}; use dom::bindings::codegen::Bindings::Ex...
// Step 2 // TODO add a extended_promises array to enqueue the `val` Ok(()) } // https://dom.spec.whatwg.org/#dom-event-istrusted pub fn IsTrusted(&self) -> bool { self.event.IsTrusted() } } impl Default for ExtendableEventBinding::ExtendableEventInit { fn default(...
{ return Err(Error::InvalidState); }
conditional_block
extendableevent.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::EventBinding::{self, EventMethods}; use dom::bindings::codegen::Bindings::Ex...
} }
}
random_line_split
extendableevent.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::EventBinding::{self, EventMethods}; use dom::bindings::codegen::Bindings::Ex...
// https://w3c.github.io/ServiceWorker/#wait-until-method pub fn WaitUntil(&self, _cx: *mut JSContext, _val: HandleValue) -> ErrorResult { // Step 1 if!self.extensions_allowed { return Err(Error::InvalidState); } // Step 2 // TODO add a extended_promises arr...
{ Ok(ExtendableEvent::new(worker, Atom::from(type_), init.parent.bubbles, init.parent.cancelable)) }
identifier_body
float.rs
use super::sort::{sort_by}; use num_traits::{Float, zero}; use unreachable::UncheckedOptionExt; /// Sorts floating point numbers efficiently. /// The ordering used is /// | -inf | < 0 | -0 | +0 | > 0 | +inf | NaN | pub fn sort_floats<T: Float>(v: &mut [T])
// Skip NaNs already in place while rnan > 0 && v[rnan].is_nan() { rnan -= 1; } let mut p = rnan; while p > 0 { p -= 1; if v[p].is_nan() { v.swap(p, rnan); rnan -= 1; } } // Sort the non-NaN part with efficient comparisons sort_by(...
{ /* * We don't have hardware support for a total order on floats. NaN is not * smaller or greater than any number. We want NaNs to be last, so we could * just use is_nan() in the comparison function. It turns out that this hurts * performance a lot, and in most cases we probably don't have any ...
identifier_body
float.rs
use super::sort::{sort_by}; use num_traits::{Float, zero}; use unreachable::UncheckedOptionExt; /// Sorts floating point numbers efficiently. /// The ordering used is /// | -inf | < 0 | -0 | +0 | > 0 | +inf | NaN | pub fn sort_floats<T: Float>(v: &mut [T]) { /* * We don't have hardware support for a total ord...
for x in v[left..].iter() { if *x!= zero() { break; } if x.is_sign_negative() { neg_zeros += 1; } else { zeros += 1; } } for x in v[left..].iter_mut() { if neg_zeros > 0 { *x = Float::neg_zero(); neg_...
// Count zeros of each type and then fill them in in the right order let mut zeros = 0; let mut neg_zeros = 0;
random_line_split
float.rs
use super::sort::{sort_by}; use num_traits::{Float, zero}; use unreachable::UncheckedOptionExt; /// Sorts floating point numbers efficiently. /// The ordering used is /// | -inf | < 0 | -0 | +0 | > 0 | +inf | NaN | pub fn sort_floats<T: Float>(v: &mut [T]) { /* * We don't have hardware support for a total ord...
<T: Float>(v: &[T]) -> usize { if v.len() == 0 { return 0; } let mut hi = v.len() - 1; let mut left = 0; while left < hi { let mid = ((hi - left) / 2) + left; if v[mid] < zero() { left = mid + 1; } else { hi = mid; } } while left < v.len(...
find_first_zero
identifier_name
float.rs
use super::sort::{sort_by}; use num_traits::{Float, zero}; use unreachable::UncheckedOptionExt; /// Sorts floating point numbers efficiently. /// The ordering used is /// | -inf | < 0 | -0 | +0 | > 0 | +inf | NaN | pub fn sort_floats<T: Float>(v: &mut [T]) { /* * We don't have hardware support for a total ord...
} for x in v[left..].iter_mut() { if neg_zeros > 0 { *x = Float::neg_zero(); neg_zeros -= 1; } else if zeros > 0 { *x = zero(); zeros -= 1; } else { break; } } } /// Find the first zero in `v`. /// If there is no...
{ zeros += 1; }
conditional_block
unix.rs
/* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use std::io::{Result, Error}; use ::libc; use self::c_types::{c_passwd, getpwuid};...
() -> Result<String> { // Get effective user id let uid = geteuid(); // Try to find username for uid let passwd: *const c_passwd = getpwuid(uid); if passwd.is_null() { return Err(Error::last_os_error()) } // Extract username from passwd struct let pw_name: *const libc::c_char =...
getusername
identifier_name
unix.rs
/* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use std::io::{Result, Error}; use ::libc; use self::c_types::{c_passwd, getpwuid};...
pub unsafe fn getusername() -> Result<String> { // Get effective user id let uid = geteuid(); // Try to find username for uid let passwd: *const c_passwd = getpwuid(uid); if passwd.is_null() { return Err(Error::last_os_error()) } // Extract username from passwd struct let pw_na...
}
random_line_split
unix.rs
/* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use std::io::{Result, Error}; use ::libc; use self::c_types::{c_passwd, getpwuid};...
// Extract username from passwd struct let pw_name: *const libc::c_char = (*passwd).pw_name; let username = String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string(); Ok(username) }
{ return Err(Error::last_os_error()) }
conditional_block