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
elgamal.rs
: // 0 256 512 // | padding zeroes | gamma | padding zeroes | delta | let gamma = rectify(&gamma, 256); let delta = rectify(&delta, 256); let mut ct = vec![0; 512]; ct[0..256].copy_...
// Check test vector assert_eq!(dec.decrypt(&ct, true).unwrap(), msg); }
random_line_split
elgamal.rs
}; // γ = α^k mod p let gamma = ELGAMAL_G.modpow(&k, &ELGAMAL_P); (k, gamma) } /// Generates ElGamal keypairs. pub struct KeyPairGenerator; impl KeyPairGenerator { /// ElGamal key generation, following algorithm 8.17. pub fn generate() -> (PrivateKey, PublicKey) { // Select a random...
{ break k; }
conditional_block
elgamal.rs
u8; 256]; x.copy_from_slice(&buf[..]); PrivateKey(x) }; let pub_key = { let buf = rectify(&alpha_a, 256); let mut x = [0u8; 256]; x.copy_from_slice(&buf[..]); PublicKey(x) }; (priv_key, pub_key) } } pub struct...
self.encrypt_basic(&data).map(|(gamma, delta)| { if include_zeroes { // ElGamal ciphertext: // 0 1 257 258 514 // | 0 | padding zeroes | gamma | 0 | padding zeroes | delta | let gamma = rect...
// Message must be no more than 222 bytes if msg.len() > 222 { return Err(Error::InvalidMessage); } let mut rng = OsRng; let hash = Sha256::digest(msg); // ElGamal plaintext: // 0 1 33 // | nonzero byte | SHA256(msg) | msg...
identifier_body
elgamal.rs
0u8; 256]; x.copy_from_slice(&buf[..]); PrivateKey(x) }; let pub_key = { let buf = rectify(&alpha_a, 256); let mut x = [0u8; 256]; x.copy_from_slice(&buf[..]); PublicKey(x) }; (priv_key, pub_key) } } pub struc...
(gamma, delta): (BigUint, BigUint)) -> Vec<u8> { // γ^{-a} = γ^{p-1-a} let gamma_neg_a = gamma.modpow(&(&(*ELGAMAL_PM1)).sub(&self.0), &ELGAMAL_P); // m = (γ^{-a}) * δ mod p let m = gamma_neg_a.mul(delta).rem(&(*ELGAMAL_P)); m.to_bytes_be() } /// ElGamal decryption us...
_basic(&self,
identifier_name
nelder_mead.rs
//! Adaptive nelder-mead simplex algorithm. //! //! # References //! //! - [Implementing the Nelder-Mead simplex algorithm with adaptive parameters][ANMS] //! - [Nelder-Mead algorithm](http://var.scholarpedia.org/article/Nelder-Mead_algorithm) //! - [Nelder-Mead Method (Wikipedia)](https://en.wikipedia.org/wiki/Nelder–...
fn reflect_ask(&mut self) -> Vec<f64> { self.centroid .iter() .zip(self.highest().param.iter()) .map(|(&x0, &xh)| x0 + self.alpha * (x0 - xh)) .collect() } fn reflect_tell(&mut self, obs: Obs<Vec<f64>, V>) { if obs.value < self.lowest().value { ...
self.simplex.push(obs); if self.simplex.len() == self.dim() + 1 { self.simplex.sort_by(|a, b| a.value.cmp(&b.value)); self.update_centroid(); self.state = State::Reflect; } }
identifier_body
nelder_mead.rs
//! Adaptive nelder-mead simplex algorithm. //! //! # References //! //! - [Implementing the Nelder-Mead simplex algorithm with adaptive parameters][ANMS] //! - [Nelder-Mead algorithm](http://var.scholarpedia.org/article/Nelder-Mead_algorithm) //! - [Nelder-Mead Method (Wikipedia)](https://en.wikipedia.org/wiki/Nelder–...
.collect(); initial_simplex.push(x); } track!(Self::with_initial_simplex(params_domain, initial_simplex)) } /// Makes a new `NelderMeadOptimizer` with the given simplex. pub fn with_initial_simplex( params_domain: Vec<ContinuousDomain>, initial_sim...
x0 })
conditional_block
nelder_mead.rs
//! Adaptive nelder-mead simplex algorithm. //! //! # References //! //! - [Implementing the Nelder-Mead simplex algorithm with adaptive parameters][ANMS] //! - [Nelder-Mead algorithm](http://var.scholarpedia.org/article/Nelder-Mead_algorithm) //! - [Nelder-Mead Method (Wikipedia)](https://en.wikipedia.org/wiki/Nelder–...
> { params_domain: Vec<ContinuousDomain>, simplex: Vec<Obs<Vec<f64>, V>>, alpha: f64, beta: f64, gamma: f64, delta: f64, initial: Vec<Vec<f64>>, centroid: Vec<f64>, evaluating: Option<ObsId>, state: State<V>, } impl<V> NelderMeadOptimizer<V> where V: Ord, { /// Makes a ne...
lderMeadOptimizer<V
identifier_name
nelder_mead.rs
//! Adaptive nelder-mead simplex algorithm. //! //! # References //! //! - [Implementing the Nelder-Mead simplex algorithm with adaptive parameters][ANMS] //! - [Nelder-Mead algorithm](http://var.scholarpedia.org/article/Nelder-Mead_algorithm) //! - [Nelder-Mead Method (Wikipedia)](https://en.wikipedia.org/wiki/Nelder–...
self.state = State::ContractInside(obs); } } fn expand_ask(&mut self, prev: Vec<f64>) -> Vec<f64> { self.centroid .iter() .zip(prev.iter()) .map(|(&c, &x)| c + self.beta * (x - c)) .collect() } fn expand_tell(&mut self, prev: Obs<...
self.accept(obs); } else if obs.value < self.highest().value { self.state = State::ContractOutside(obs); } else {
random_line_split
mod.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/. */ #![allow(unsafe_code)] //! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s. use gecko_bind...
use std::char::{self, DecodeUtf16}; use std::fmt::{self, Write}; use std::hash::{Hash, Hasher}; use std::iter::Cloned; use std::mem; use std::ops::Deref; use std::slice; #[macro_use] #[allow(improper_ctypes, non_camel_case_types, missing_docs)] pub mod atom_macro { include!(concat!(env!("OUT_DIR"), "/gecko/atom_ma...
use std::borrow::{Cow, Borrow};
random_line_split
mod.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/. */ #![allow(unsafe_code)] //! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s. use gecko_bind...
(string: Cow<'a, str>) -> Atom { Atom::from(&*string) } } impl From<String> for Atom { #[inline] fn from(string: String) -> Atom { Atom::from(&*string) } } impl From<*mut nsAtom> for Atom { #[inline] fn from(ptr: *mut nsAtom) -> Atom { assert!(!ptr.is_null()); u...
from
identifier_name
mod.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/. */ #![allow(unsafe_code)] //! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s. use gecko_bind...
/// Get the atom as a slice of utf-16 chars. #[inline] pub fn as_slice(&self) -> &[u16] { unsafe { slice::from_raw_parts((*self.as_ptr()).mString, self.len() as usize) } } // NOTE: don't expose this, since it's slow, and easy to be misused. fn chars(&self) -> Decod...
{ self.0.mHash }
identifier_body
lookup_ref_delta_objects.rs
use std::convert::TryInto; use gix_hash::ObjectId; use crate::data::{entry::Header, input}; /// An iterator to resolve thin packs on the fly. pub struct LookupRefDeltaObjectsIter<I, LFn> { /// The inner iterator whose entries we will resolve. pub inner: I, lookup: LFn, /// The cached delta to provide...
Some(Ok(entry)) } } } _ => { if self.inserted_entries_length_in_bytes!= 0 { if let Header::OfsDelta { base_distance } = entry.header { // We hav...
Some(base_entry) => { let base_distance = self.shifted_pack_offset(entry.pack_offset) - base_entry.shifted_pack_offset; self.shift_entry_and_point_to_base_by_offset(&mut entry, base_distance);
random_line_split
lookup_ref_delta_objects.rs
use std::convert::TryInto; use gix_hash::ObjectId; use crate::data::{entry::Header, input}; /// An iterator to resolve thin packs on the fly. pub struct LookupRefDeltaObjectsIter<I, LFn> { /// The inner iterator whose entries we will resolve. pub inner: I, lookup: LFn, /// The cached delta to provide...
{ /// The original pack offset as mentioned in the entry we saw. This is used to find this as base object if deltas refer to it by /// old offset. pack_offset: u64, /// The new pack offset that is the shifted location of the pack entry in the pack. shifted_pack_offset: u64, /// The size change ...
Change
identifier_name
lookup_ref_delta_objects.rs
use std::convert::TryInto; use gix_hash::ObjectId; use crate::data::{entry::Header, input}; /// An iterator to resolve thin packs on the fly. pub struct LookupRefDeltaObjectsIter<I, LFn> { /// The inner iterator whose entries we will resolve. pub inner: I, lookup: LFn, /// The cached delta to provide...
} #[derive(Debug)] struct Change { /// The original pack offset as mentioned in the entry we saw. This is used to find this as base object if deltas refer to it by /// old offset. pack_offset: u64, /// The new pack offset that is the shifted location of the pack entry in the pack. shifted_pack_off...
{ let (min, max) = self.inner.size_hint(); max.map_or_else(|| (min * 2, None), |max| (min, Some(max * 2))) }
identifier_body
lib.rs
/* * This is NearDice contract: * * * */ // To conserve gas, efficient serialization is achieved through Borsh (http://borsh.io/) use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::wee_alloc; use near_sdk::json_types::{U64, U128}; use near_sdk::serde::{Deserialize, Serialize}; use near...
(&mut self, target: u8) -> HumanReadableDiceResult { // check called by real user NOT from other contracts let account_id = env::predecessor_account_id(); assert_eq!( account_id.clone(), env::signer_account_id(), "This method must be called directly from user...
roll_dice
identifier_name
lib.rs
/* * This is NearDice contract: * * * */ // To conserve gas, efficient serialization is achieved through Borsh (http://borsh.io/) use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::wee_alloc; use near_sdk::json_types::{U64, U128}; use near_sdk::serde::{Deserialize, Serialize}; use near...
else { self.accounts.insert(&account_id, &leftover); } // always update jack_pod before rolling dice self.jack_pod += self.rolling_fee; // rolling dice here let random_u8: u8 = env::random_seed().iter().fold(0_u8, |acc, x| acc.wrapping_add(*x)); let dice_poi...
{ self.accounts.remove(&account_id); }
conditional_block
lib.rs
/* * This is NearDice contract: * * * */ // To conserve gas, efficient serialization is achieved through Borsh (http://borsh.io/) use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::wee_alloc; use near_sdk::json_types::{U64, U128}; use near_sdk::serde::{Deserialize, Serialize}; use near...
//***********************/ // view functions //***********************/ fn get_hr_info(&self, index: u64) -> HumanReadableWinnerInfo { let info = self.win_history.get(index).expect("Error: no this item in winner history!"); HumanReadableWinnerInfo { user: info.user.clone()...
{ let account_id = env::signer_account_id(); // Use env::log to record logs permanently to the blockchain! env::log(format!("Saving greeting '{}' for account '{}'", message, account_id,).as_bytes()); }
identifier_body
lib.rs
/* * This is NearDice contract: * * * */ // To conserve gas, efficient serialization is achieved through Borsh (http://borsh.io/) use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::wee_alloc; use near_sdk::json_types::{U64, U128}; use near_sdk::serde::{Deserialize, Serialize}; use near...
// always update jack_pod before rolling dice self.jack_pod += self.rolling_fee; // rolling dice here let random_u8: u8 = env::random_seed().iter().fold(0_u8, |acc, x| acc.wrapping_add(*x)); let dice_point = self.dice_number as u16 * 6_u16 * random_u8 as u16 / 0x100_u16 + 1; ...
if leftover == 0 { self.accounts.remove(&account_id); } else { self.accounts.insert(&account_id, &leftover); }
random_line_split
parser.rs
use nom::{bytes::complete as bytes, character::complete as character, combinator, IResult}; use super::{ finder::FileSearcher, github::{GitHubIssue, GitHubPatch}, }; use serde::Deserialize; use std::{collections::HashMap, fs::File, io::prelude::*, path::Path}; pub mod issue; pub mod langs; pub mod source; us...
let desc_lines = todo .desc_lines .iter() .map(|s| s.to_string()) .collect::<Vec<_>>(); issue.body.descs_and_srcs.push((desc_lines, loc)); } pub fn from_files_in_directory( dir: &str, excludes: &Vec<String>, ) -> Result<IssueMap<()...
random_line_split
parser.rs
use nom::{bytes::complete as bytes, character::complete as character, combinator, IResult}; use super::{ finder::FileSearcher, github::{GitHubIssue, GitHubPatch}, }; use serde::Deserialize; use std::{collections::HashMap, fs::File, io::prelude::*, path::Path}; pub mod issue; pub mod langs; pub mod source; us...
(&mut self, todo: &ParsedTodo, loc: FileTodoLocation) { let title = todo.title.to_string(); let issue = self .todos .entry(title.clone()) .or_insert(Issue::new((), title)); if let Some(assignee) = todo.assignee.map(|s| s.to_string()) { if!issue.head....
add_parsed_todo
identifier_name
parser.rs
use nom::{bytes::complete as bytes, character::complete as character, combinator, IResult}; use super::{ finder::FileSearcher, github::{GitHubIssue, GitHubPatch}, }; use serde::Deserialize; use std::{collections::HashMap, fs::File, io::prelude::*, path::Path}; pub mod issue; pub mod langs; pub mod source; us...
let languages = languages.expect("impossible!"); // Open the file and load the contents let mut file = File::open(path) .map_err(|e| format!("could not open file: {}\n{}", path.display(), e))?; let mut contents = String::new(); file.read_to_st...
{ // TODO: Deadletter the file name as unsupported println!("possible TODO found in unsupported file: {:#?}", path); continue; }
conditional_block
nvm_buffer.rs
use std::cmp; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::ptr; use block::{AlignedBytes, BlockSize}; use nvm::NonVolatileMemory; use {ErrorKind, Result}; /// ジャーナル領域用のバッファ. /// /// 内部の`NonVolatileMemory`実装のアライメント制約(i.e., ストレージのブロック境界に揃っている)を満たしつつ、 /// ジャーナル領域への追記を効率化するのが目的. #[derive(Debug)] pub struct ...
tState, "self.position={}, write_len={}, self.len={}", self.position(), write_len, self.capacity() ); Ok(()) } } impl<N: NonVolatileMemory> NonVolatileMemory for JournalNvmBuffer<N> { fn sync(&mut self) -> Result<()> { track!(self.flush_wri...
), ErrorKind::Inconsisten
conditional_block
nvm_buffer.rs
use std::cmp; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::ptr; use block::{AlignedBytes, BlockSize}; use nvm::NonVolatileMemory; use {ErrorKind, Result}; /// ジャーナル領域用のバッファ. /// /// 内部の`NonVolatileMemory`実装のアライメント制約(i.e., ストレージのブロック境界に揃っている)を満たしつつ、 /// ジャーナル領域への追記を効率化するのが目的. #[derive(Debug)] pub struct ...
))?; assert_eq!(&buffer.nvm().as_bytes()[0..6], b"foobar"); Ok(()) } #[test] fn write_seek_write_flush() -> TestResult { // "連続"の判定は、ブロック単位で行われる // (シークしてもブロックを跨がないと"連続していない"と判定されない) let mut buffer = new_buffer(); track_io!(buffer.write_all(b"foo"))?; ...
lush(
identifier_name
nvm_buffer.rs
use std::cmp; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::ptr; use block::{AlignedBytes, BlockSize}; use nvm::NonVolatileMemory; use {ErrorKind, Result}; /// ジャーナル領域用のバッファ. /// /// 内部の`NonVolatileMemory`実装のアライメント制約(i.e., ストレージのブロック境界に揃っている)を満たしつつ、 /// ジャーナル領域への追記を効率化するのが目的. #[derive(Debug)] pub struct ...
// - 書き込みバッファのカバー範囲に重複する領域に対して、読み込み要求が発行された場合: // - 書き込みバッファの内容をフラッシュして、内部NVMに同期した後に、該当読み込み命令を処理 // - 書き込みバッファのカバー範囲に重複しない領域に対して、書き込み要求が発行された場合: // - 現状の書き込みバッファのデータ構造では、ギャップ(i.e., 連続しない複数部分領域)を表現することはできない // - そのため、一度古いバッファの内容をフラッシュした後に、該当書き込み要求を処理するためのバッファを作成する // // ジャーナル領域が発行した書き込み...
// - ジャーナル領域は定期的に本メソッドを呼び出す
random_line_split
nvm_buffer.rs
use std::cmp; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::ptr; use block::{AlignedBytes, BlockSize}; use nvm::NonVolatileMemory; use {ErrorKind, Result}; /// ジャーナル領域用のバッファ. /// /// 内部の`NonVolatileMemory`実装のアライメント制約(i.e., ストレージのブロック境界に揃っている)を満たしつつ、 /// ジャーナル領域への追記を効率化するのが目的. #[derive(Debug)] pub struct ...
ite_buf.aligned_resize(end); (&mut self.write_buf[start..end]).copy_from_slice(buf); self.position += buf.len() as u64; self.maybe_dirty = true; Ok(buf.len()) } else { // 領域に重複がないので、一度バッファの中身を書き戻す track!(self.flush_write_buf())?; ...
et) as usize; let end = start + buf.len(); self.wr
identifier_body
linked_list.rs
//! An intrusive linked list. //! //! ```ignore //! use intrusive::{define_list_node, linked_list::{List, ListLink}}; //! use std::sync::Arc; //! //! struct Thread { //! id: usize, //! link: ListLink<ThreadsNode>, //! } //! //! define_list_node!(ThreadsNode, Arc<Thread>, link); //! //! let mut threads = List::<...
link.prev.set(self.tail); link.next.set(None); self.tail = Some(link_ptr); Ok(()) } } /// Pops the element at the beginning of the list. `O(1)`. pub fn pop_front(&mut self) -> Option<L::Elem> { match self.head { Some(head) => uns...
{ self.head = Some(link_ptr); }
conditional_block
linked_list.rs
//! An intrusive linked list. //! //! ```ignore //! use intrusive::{define_list_node, linked_list::{List, ListLink}}; //! use std::sync::Arc; //! //! struct Thread { //! id: usize,
//! //! let mut threads = List::<ThreadsNode>::new(); //! let thread1 = Arc::new(Thread { id: 1, link: Default::default() }); //! threads.push_back(thread1); //! ``` //! use core::cell::Cell; use core::fmt::{self, Debug, Formatter}; use core::marker::PhantomData; use core::ops::ControlFlow; use core::ptr::NonNull; use ...
//! link: ListLink<ThreadsNode>, //! } //! //! define_list_node!(ThreadsNode, Arc<Thread>, link);
random_line_split
linked_list.rs
//! An intrusive linked list. //! //! ```ignore //! use intrusive::{define_list_node, linked_list::{List, ListLink}}; //! use std::sync::Arc; //! //! struct Thread { //! id: usize, //! link: ListLink<ThreadsNode>, //! } //! //! define_list_node!(ThreadsNode, Arc<Thread>, link); //! //! let mut threads = List::<...
(&self) -> Iter<'_, L> { Iter { current: self.head, _pd: &PhantomData, } } } impl<L: ListNode> Default for List<L> { fn default() -> Self { Self::new() } } pub struct Iter<'a, L: ListNode> { current: Option<NonNull<ListLink<L>>>, _pd: &'a PhantomData...
iter
identifier_name
view.rs
// Copyright (c) 2021 The vulkano developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be ...
(&self, _sampler: &Sampler) -> bool { true /* FIXME */ } } unsafe impl<I> ImageViewAbstract for ImageView<I> where I: ImageAccess, { #[inline] fn image(&self) -> &dyn ImageAccess { &self.image } #[inline] fn inner(&self) -> &UnsafeImageView { &self.inner } ...
can_be_sampled
identifier_name
view.rs
// Copyright (c) 2021 The vulkano developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be ...
/// Returns true if the view doesn't use components swizzling. /// /// Must be true when the view is used as a framebuffer attachment or TODO: I don't remember /// the other thing. fn identity_swizzle(&self) -> bool; /// Returns the [`ImageViewType`] of this image view. fn ty(&self) -> Ima...
fn array_layers(&self) -> Range<u32>; /// Returns the format of this view. This can be different from the parent's format. fn format(&self) -> Format;
random_line_split
view.rs
// Copyright (c) 2021 The vulkano developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be ...
#[inline] fn format(&self) -> Format { (**self).format() } #[inline] fn identity_swizzle(&self) -> bool { (**self).identity_swizzle() } #[inline] fn ty(&self) -> ImageViewType { (**self).ty() } #[inline] fn can_be_sampled(&self, sampler: &Sampler)...
{ (**self).array_layers() }
identifier_body
types.rs
//! Перечисляемые типы данных, используемые при работе с библиотекой use std::u32; /// Возможные типы данных базы данных #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[allow(dead_code)] #[allow(non_camel_case_types)] #[allow(deprecated)]// Позволяем deprecated внутри перечисления из-за https://github.com/rust-lang/ru...
/// Specifies the various modes of operation #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[allow(dead_code)] pub enum AuthMode { /// In this mode, the user session context returned can only ever be set with the server context /// specified in `svchp`. For encoding, the server handle uses the setting in the environ...
} impl Default for AttachMode { fn default() -> Self { AttachMode::Default } }
random_line_split
types.rs
//! Перечисляемые типы данных, используемые при работе с библиотекой use std::u32; /// Возможные типы данных базы данных #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[allow(dead_code)] #[allow(non_camel_case_types)] #[allow(deprecated)]// Позволяем deprecated внутри перечисления из-за https://github.com/rust-lang/ru...
/// For encoding, this value tells the server handle to use the setting in the environment handle. Default = 0, /// Use connection pooling. CPool = 1 << 9, } impl Default for AttachMode { fn default() -> Self { AttachMode::Default } } /// Specifies the various modes of operation #[derive(Clone, Copy, Debug, P...
de {
identifier_name
traits.rs
//! Architecture trait use crate::analysis::{Disasm, Mappable, RequisiteSet, Result, Trace}; use crate::arch::ArchName; use crate::ast::Literal; use crate::cli::Nameable; use crate::maths::{Numerical, Popcount}; use crate::memory::{Memory, Offset, Pointer, PtrNum}; use crate::reg::{Bitwise, State}; use num::Bounded; u...
at: Self::PtrVal, bus: &Memory<Self>, state: State<Self>, trace: &mut Trace<Self>, ) -> Result<(State<Self>, Self::PtrVal), Self>; } /// Trait for type-erased structures that accept an architecture parameter and /// are intended to be accessed with the `with_architecture!` macro. pu...
&self,
random_line_split
arabic.rs
//! Implementation of font shaping for Arabic scripts //! //! Code herein follows the specification at: //! <https://github.com/n8willis/opentype-shaping-documents/blob/master/opentype-shaping-arabic-general.md> use crate::error::{ParseError, ShapingError}; use crate::gsub::{self, FeatureMask, GlyphData, GlyphOrigin, ...
#[cfg(test)] mod tests { use super::*; // https://www.unicode.org/reports/tr53/#Demonstrating_AMTRA. mod reorder_marks { use super::*; #[test] fn test_artificial() { let cs = vec![ '\u{0618}', '\u{0619}', '\u{064E}', '\u{064F}', '\u{0654}', '\u{0658}', '...
}
random_line_split
arabic.rs
//! Implementation of font shaping for Arabic scripts //! //! Code herein follows the specification at: //! <https://github.com/n8willis/opentype-shaping-documents/blob/master/opentype-shaping-arabic-general.md> use crate::error::{ParseError, ShapingError}; use crate::gsub::{self, FeatureMask, GlyphData, GlyphOrigin, ...
if arabic_glyphs[previous_i].is_left_joining() && arabic_glyphs[i].is_right_joining() { arabic_glyphs[i].set_feature_tag(tag::FINA); match arabic_glyphs[previous_i].feature_tag() { tag::ISOL => arabic_glyphs[previous_i].set_feature_tag(tag::INIT), ...
{ continue; }
conditional_block
arabic.rs
//! Implementation of font shaping for Arabic scripts //! //! Code herein follows the specification at: //! <https://github.com/n8willis/opentype-shaping-documents/blob/master/opentype-shaping-arabic-general.md> use crate::error::{ParseError, ShapingError}; use crate::gsub::{self, FeatureMask, GlyphData, GlyphOrigin, ...
() { let cs = vec![ '\u{0618}', '\u{0619}', '\u{064E}', '\u{064F}', '\u{0654}', '\u{0658}', '\u{0653}', '\u{0654}', '\u{0651}', '\u{0656}', '\u{0651}', '\u{065C}', '\u{0655}', '\u{0650}', ]; let cs_exp = vec![ '\u{0654}', '\u{0658}', '\...
test_artificial
identifier_name
arabic.rs
//! Implementation of font shaping for Arabic scripts //! //! Code herein follows the specification at: //! <https://github.com/n8willis/opentype-shaping-documents/blob/master/opentype-shaping-arabic-general.md> use crate::error::{ParseError, ShapingError}; use crate::gsub::{self, FeatureMask, GlyphData, GlyphOrigin, ...
} impl From<&RawGlyph<()>> for ArabicGlyph { fn from(raw_glyph: &RawGlyph<()>) -> ArabicGlyph { // Since there's no `Char` to work out the `ArabicGlyph`s joining type when the glyph's // `glyph_origin` is `GlyphOrigin::Direct`, we fallback to `JoiningType::NonJoining` as // the safest appr...
{ self.extra_data.feature_tag = feature_tag }
identifier_body
kv.rs
内存索引中。 /// 类似地,当删除一个键时,kvs 将 rm 命令写入日志,然后从内存索引中删除该键。 /// 当使用 get 命令检索键的值时,它检索索引,如果找到了,就从对应的日志指针上加载命令,执行命令并返回结果。 /// /// kvs 启动时,就会按从旧到新的顺序从日志中遍历并执行命令,内存索引也会对应的重建。 /// /// 当日志条数达到给定阈值时,kvs 会其压缩为一个新日志,删除冗余日志以回收磁盘空间。 /// /// 注意,kvs 项目既是一个无状态命令行程序,也是一个包含有状态 KVStore 类型的库: /// 对于 CLI,使用 KV...
Err(KvsError::UnsupportCmdType) } } else { Ok(None) } } /// 查询 key 是否存在,如果存在,则记录 cmd 到日志,然后删除文件中的数据,再索引索引 fn delete(&mut self, k: String) -> Result<()> { if self.index.contains_key(&k) { let rm_cmd = Command::remove(k.clone()); ...
} else {
random_line_split
kv.rs
索引中。 /// 类似地,当删除一个键时,kvs 将 rm 命令写入日志,然后从内存索引中删除该键。 /// 当使用 get 命令检索键的值时,它检索索引,如果找到了,就从对应的日志指针上加载命令,执行命令并返回结果。 /// /// kvs 启动时,就会按从旧到新的顺序从日志中遍历并执行命令,内存索引也会对应的重建。 /// /// 当日志条数达到给定阈值时,kvs 会其压缩为一个新日志,删除冗余日志以回收磁盘空间。 /// /// 注意,kvs 项目既是一个无状态命令行程序,也是一个包含有状态 KVStore 类型的库: /// 对于 CLI,使用 KVSt...
mut entry_reader = reader.take(cmd_pos.len); let len = std::io::copy(&mut entry_reader, &mut compaction_writer)?; *cmd_pos = (compaction_gen, new_pos..new_pos + len).into(); new_pos += len; } compaction_writer.flush()?; // 删除过期的日志文件 let stale_gens: V...
(cmd_pos.pos))?; } let
conditional_block
kv.rs
索引中。 /// 类似地,当删除一个键时,kvs 将 rm 命令写入日志,然后从内存索引中删除该键。 /// 当使用 get 命令检索键的值时,它检索索引,如果找到了,就从对应的日志指针上加载命令,执行命令并返回结果。 /// /// kvs 启动时,就会按从旧到新的顺序从日志中遍历并执行命令,内存索引也会对应的重建。 /// /// 当日志条数达到给定阈值时,kvs 会其压缩为一个新日志,删除冗余日志以回收磁盘空间。 /// /// 注意,kvs 项目既是一个无状态命令行程序,也是一个包含有状态 KVStore 类型的库: /// 对于 CLI,使用 KVSt...
ult<Self> { // 打开目录,查看目录中的日志文件列表,将其加载进 kvs let using_path = path.into(); std::fs::create_dir_all(&using_path)?; let mut readers = HashMap::new(); // 索引以 btree map 的形式存储在内存中 let mut index: BTreeMap<String, CommandPos> = BTreeMap::new(); let gen_list = sorted_gen_li...
Res
identifier_name
output.rs
//! Types and functions related to graphical outputs //! //! This modules provides two main elements. The first is the //! [`OutputHandler`](struct.OutputHandler.html) type, which is a //! [`MultiGlobalHandler`](../environment/trait.MultiGlobalHandler.html) for //! use with the [`init_environment!`](../macro.init_envir...
(info: &mut OutputInfo, event: Event) { match event { Event::Geometry { x, y, physical_width, physical_height, subpixel, model, make, transform, } => { info.location = (x, y); info...
merge_event
identifier_name
output.rs
//! Types and functions related to graphical outputs //! //! This modules provides two main elements. The first is the //! [`OutputHandler`](struct.OutputHandler.html) type, which is a //! [`MultiGlobalHandler`](../environment/trait.MultiGlobalHandler.html) for //! use with the [`init_environment!`](../macro.init_envir...
/// included in [`new_default_environment!`](../macro.new_default_environment.html). /// /// It aggregates the output information and makes it available via the /// [`with_output_info`](fn.with_output_info.html) function. pub struct OutputHandler { outputs: Vec<(u32, Attached<WlOutput>)>, status_listeners: Rc<R...
/// A handler for `wl_output` /// /// This handler can be used for managing `wl_output` in the /// [`init_environment!`](../macro.init_environment.html) macro, and is automatically
random_line_split
output.rs
//! Types and functions related to graphical outputs //! //! This modules provides two main elements. The first is the //! [`OutputHandler`](struct.OutputHandler.html) type, which is a //! [`MultiGlobalHandler`](../environment/trait.MultiGlobalHandler.html) for //! use with the [`init_environment!`](../macro.init_envir...
}); } fn notify_status_listeners( output: &Attached<WlOutput>, info: &OutputInfo, mut ddata: DispatchData, listeners: &RefCell<Vec<rc::Weak<RefCell<OutputStatusCallback>>>>, ) { // Notify the callbacks listening for new outputs listeners.borrow_mut().retain(|lst| { if let Some(cb) ...
{ false }
conditional_block
command.rs
use std::fmt::Display; use GameContext; use data::Walkability; use engine::keys::{Key, KeyCode}; use ecs::traits::*; use graphics::cell::{CellFeature, StairDest, StairDir}; use logic::Action; use logic::entity::EntityQuery; use point::{Direction, Point}; use world::traits::*; use world::{self, World}; use super::debu...
fn cmd_teleport(context: &mut GameContext) -> CommandResult<()> { mes!(context.state.world, "Teleport where?"); let pos = select_tile(context, |_, _| ())?; if context.state.world.can_walk( pos, Walkability::MonstersBlocking, ) { cmd_add_action(context, Action::Teleport(pos...
{ select_tile(context, maybe_examine_tile).map(|_| ()) }
identifier_body
command.rs
use std::fmt::Display; use GameContext; use data::Walkability; use engine::keys::{Key, KeyCode}; use ecs::traits::*; use graphics::cell::{CellFeature, StairDest, StairDir}; use logic::Action; use logic::entity::EntityQuery; use point::{Direction, Point}; use world::traits::*; use world::{self, World}; use super::debu...
pub fn menu_choice(context: &mut GameContext, choices: Vec<String>) -> Option<usize> { renderer::with_mut(|rc| { rc.update(context); rc.query(&mut ChoiceLayer::new(choices)) }) } pub fn menu_choice_indexed<T: Display + Clone>( context: &mut GameContext, mut choices: Vec<T>, ) -> Comma...
use renderer::ui::layers::ChoiceLayer;
random_line_split
command.rs
use std::fmt::Display; use GameContext; use data::Walkability; use engine::keys::{Key, KeyCode}; use ecs::traits::*; use graphics::cell::{CellFeature, StairDest, StairDir}; use logic::Action; use logic::entity::EntityQuery; use point::{Direction, Point}; use world::traits::*; use world::{self, World}; use super::debu...
(start: Point, end: Point, world: &mut World) { world.marks.clear(); for pos in LineIter::new(start, end) { world.marks.add(pos, Color::new(255, 255, 255)); } world.marks.add(end, Color::new(255, 255, 255)); } /// Allow the player to choose a tile. pub fn select_tile<F>(context: &mut GameContex...
draw_line
identifier_name
main.rs
32 => '$', _ => return None, }; return Some(res) } } } make_encode_decode!{ 0 => 'a'; 1 => 'e'; 2 => 'i'; 3 => 'o'; 4 => 'r'; 5 => 'n'; 6 => 'l'; 7 =>'s'; 8 => 't'; 9 => 'u'; 10 => 'p'; 11 => 'c'; 12 => ...
.arg(Arg::with_name("wordlist") .required(true) .help("the wordlist file path, a plain-text UTF-8 file with each word separated by a newline") ) .arg(Arg::with_name("ignore-empty-wordlist") .long("ignore-empty-wordlist") .help...
let matches = App::new(format!("Rust Word Rectangle Finder o{}x{}", WORD_SQUARE_WIDTH, WORD_SQUARE_HEIGHT)) .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .setting(clap::AppSettings::SubcommandRequired) .subcommand(SubCommand::with_name("compu...
identifier_body
main.rs
32 => '$', _ => return None, }; return Some(res) } } } make_encode_decode!{ 0 => 'a'; 1 => 'e'; 2 => 'i'; 3 => 'o'; 4 => 'r'; 5 => 'n'; 6 => 'l'; 7 =>'s'; 8 => 't'; 9 => 'u'; 10 => 'p'; 11 => 'c'; 12 =>...
.setting(clap::AppSettings::SubcommandRequired) .subcommand(SubCommand::with_name("compute") .about("Does the actual computation.") .arg(Arg::with_name("threads") .default_value("4") .takes_value(true) .validator(|arg| { ...
.author(crate_authors!()) .about(crate_description!())
random_line_split
main.rs
32 => '$', _ => return None, }; return Some(res) } } } make_encode_decode!{ 0 => 'a'; 1 => 'e'; 2 => 'i'; 3 => 'o'; 4 => 'r'; 5 => 'n'; 6 => 'l'; 7 =>'s'; 8 => 't'; 9 => 'u'; 10 => 'p'; 11 => 'c'; 12 => '...
ernal:u32) -> CharSet { return CharSet{internal} } fn add(&mut self, val:u8) { if val > 31 {panic!("Invalid val {}", val)} self.internal |= 2u32.pow(val as u32) } fn and(&self, other:&Self) -> Self { Self{ internal: self.internal & other.internal } } fn has(&se...
int
identifier_name
app.rs
use crate::connection; use crate::debug_adapter_protocol as dap; use crate::hsp_ext; use crate::hsprt; use crate::hspsdk; use std; use std::path::PathBuf; use std::sync::mpsc; use std::thread; const MAIN_THREAD_ID: i64 = 1; const MAIN_THREAD_NAME: &'static str = "main"; fn threads() -> Vec<dap::Thread> { vec![dap...
r_ref(r: VarRef) -> Option<Self> { match r { 1 => Some(VarPath::Globals), i if i >= 2 => Some(VarPath::Static((i - 2) as usize)), _ => None, } } } #[derive(Clone, Debug)] pub(crate) struct RuntimeState { file_name: Option<String>, file_path: Option<String...
fn from_va
identifier_name
app.rs
use crate::connection; use crate::debug_adapter_protocol as dap; use crate::hsp_ext; use crate::hsprt; use crate::hspsdk; use std; use std::path::PathBuf; use std::sync::mpsc; use std::thread; const MAIN_THREAD_ID: i64 = 1; const MAIN_THREAD_NAME: &'static str = "main"; fn threads() -> Vec<dap::Thread> { vec![dap...
{ file_path, file_name: Some(file_name), line, stopped: true, }; self.send_pause_event(); } Action::AfterConnected => { self.is_connected = true; self.s...
{ warn!("[app] リクエストではない DAP メッセージを無視"); } Action::AfterStopped(file_name, line) => { let file_path = self.resolve_file_path(&file_name); self.state = RuntimeState
identifier_body
app.rs
use crate::connection; use crate::debug_adapter_protocol as dap; use crate::hsp_ext; use crate::hsprt; use crate::hspsdk; use std; use std::path::PathBuf; use std::sync::mpsc; use std::thread; const MAIN_THREAD_ID: i64 = 1; const MAIN_THREAD_NAME: &'static str = "main"; fn threads() -> Vec<dap::Thread> { vec![dap...
.iter() .map(|name| name.as_str()) .collect::<Vec<&str>>(), ); self.source_map = Some(source_map); } /// ファイル名を絶対パスにする。 /// FIXME: common 以下や 無修飾 include パスに対応する。 fn resolve_file_path(&self, file_name: &String) -> Option<String> { if...
let file_names = debug_info.file_names(); source_map.add_search_path(PathBuf::from(&args.program).parent()); source_map.add_file_names( &file_names
random_line_split
stack.rs
// Copied from: // rust/src/librustrt/stack.rs // git: 70cef9474a3307ec763efc01fe6969e542083823 // stack_exhausted() function deleted, no other changes. // TODO replace with proper runtime-less native threading once Rust gains // support for this. // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // fil...
(limit: uint) { asm!("movl $$0x48+90*4, %eax movl $0, %gs:(%eax)" :: "r"(limit) : "eax" : "volatile") } #[cfg(all(target_arch = "x86", any(target_os = "linux", target_os = "freebsd")))] #[inline(always)] unsafe fn target_record_sp_limit(limit: uint) { asm!("mo...
target_record_sp_limit
identifier_name
stack.rs
// Copied from: // rust/src/librustrt/stack.rs // git: 70cef9474a3307ec763efc01fe6969e542083823 // stack_exhausted() function deleted, no other changes. // TODO replace with proper runtime-less native threading once Rust gains // support for this. // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // fil...
asm!("mov $0, %fs:0x08" :: "r"(stack_lo) :: "volatile"); } #[cfg(all(windows, target_arch = "x86_64"))] #[inline(always)] unsafe fn target_record_stack_bounds(stack_lo: uint, stack_hi: uint) { // stack range is at TIB: %gs:0x08 (top) and %gs:0x10 (bottom) asm!("mov $0, %gs:0x08" :: "...
{ // When the old runtime had segmented stacks, it used a calculation that was // "limit + RED_ZONE + FUDGE". The red zone was for things like dynamic // symbol resolution, llvm function calls, etc. In theory this red zone // value is 0, but it matters far less when we have gigantic stacks because /...
identifier_body
stack.rs
// Copied from: // rust/src/librustrt/stack.rs // git: 70cef9474a3307ec763efc01fe6969e542083823 // stack_exhausted() function deleted, no other changes. // TODO replace with proper runtime-less native threading once Rust gains // support for this. // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // fil...
unsafe fn target_record_sp_limit(limit: uint) { asm!("movl $0, %gs:48" :: "r"(limit) :: "volatile") } #[cfg(all(target_arch = "x86", target_os = "windows"))] #[inline(always)] unsafe fn target_record_sp_limit(_: uint) { } // mips, arm - Some brave soul can port these to inline asm, but ...
movl $0, %gs:(%eax)" :: "r"(limit) : "eax" : "volatile") } #[cfg(all(target_arch = "x86", any(target_os = "linux", target_os = "freebsd")))] #[inline(always)]
random_line_split
lib.rs
//! Crate `ruma_client` is a [Matrix](https://matrix.org/) client library. //! //! # Usage //! //! Begin by creating a `Client` type, usually using the `https` method for a client that supports //! secure connections, and then logging in: //! //! ```no_run //! use futures::Future; //! use ruma_client::Client; //! //! l...
} #[cfg(feature = "tls")] impl Client<HttpsConnector<HttpConnector>> { /// Creates a new client for making HTTPS requests to the given homeserver. pub fn https(homeserver_url: Url, session: Option<Session>) -> Result<Self, NativeTlsError> { let connector = HttpsConnector::new(4)?; Ok(Self(Arc...
{ self.0 .session .lock() .expect("session mutex was poisoned") .clone() }
identifier_body
lib.rs
//! Crate `ruma_client` is a [Matrix](https://matrix.org/) client library. //! //! # Usage //! //! Begin by creating a `Client` type, usually using the `https` method for a client that supports //! secure connections, and then logging in: //! //! ```no_run //! use futures::Future; //! use ruma_client::Client; //! //! l...
set_presence: bool, ) -> impl Stream<Item = api::r0::sync::sync_events::Response, Error = Error> { use crate::api::r0::sync::sync_events; let client = self.clone(); let set_presence = if set_presence { None } else { Some(sync_events::SetPresence::Offl...
since: Option<String>,
random_line_split
lib.rs
//! Crate `ruma_client` is a [Matrix](https://matrix.org/) client library. //! //! # Usage //! //! Begin by creating a `Client` type, usually using the `https` method for a client that supports //! secure connections, and then logging in: //! //! ```no_run //! use futures::Future; //! use ruma_client::Client; //! //! l...
<E>( self, request: <E as Endpoint>::Request, ) -> impl Future<Item = E::Response, Error = Error> where E: Endpoint, { let data1 = self.0.clone(); let data2 = self.0.clone(); let mut url = self.0.homeserver_url.clone(); request .try_into() ...
request
identifier_name
lib.rs
//! Crate `ruma_client` is a [Matrix](https://matrix.org/) client library. //! //! # Usage //! //! Begin by creating a `Client` type, usually using the `https` method for a client that supports //! secure connections, and then logging in: //! //! ```no_run //! use futures::Future; //! use ruma_client::Client; //! //! l...
} Uri::from_str(url.as_ref()) .map(move |uri| (uri, hyper_request)) .map_err(Error::from) }) .and_then(move |(uri, mut hyper_request)| { *hyper_request.uri_mut() = uri; data2.hyper.request(hyp...
{ if let Some(ref session) = *data1.session.lock().unwrap() { url.query_pairs_mut() .append_pair("access_token", &session.access_token); } else { return Err(Error(InnerError::Authentic...
conditional_block
main.rs
// #![feature(alloc_system)] // extern crate alloc_system; extern crate regex; extern crate argparse; use regex::Regex; use std::fs::File; use argparse::{ArgumentParser, Store}; use std::collections::HashSet; use std::collections::BTreeMap; use std::io::{BufReader, BufRead, BufWriter, Write}; // print $seqgene "Gene\...
// now apply input mapping regex if mapping_match_re.is_match(&match_string) { count_matched += 1; match gene_matches.get_mut(al_arr[2].split("_").nth(0).unwrap()) { Some(v) => *v += 1, None => println!("illegal gene id...
{ for pos in mm_positions { // TODO: next line is not compiling match_string.insert_str(pos, "X"); } }
conditional_block
main.rs
// #![feature(alloc_system)] // extern crate alloc_system; extern crate regex; extern crate argparse; use regex::Regex; use std::fs::File; use argparse::{ArgumentParser, Store}; use std::collections::HashSet; use std::collections::BTreeMap; use std::io::{BufReader, BufRead, BufWriter, Write}; // print $seqgene "Gene\...
// alignment section - skip the header starting with @ if next_line.starts_with('@') { continue; } // ----------the basic algorithm starts here --- // now split let al_arr: Vec<&str> = next_line.trim_right().split("\t").collect(); //only count the map...
{ //-> (HashMap<String, i32>, u32) { // our buffer for the sam parser let sam_file = BufReader::new(File::open(sam_file).expect("Problem opening fastq file")) .lines(); let sam_mismatch_re = Regex::new(r"MD:Z:([0-9]+)([A-Z]+)[0-9]+").expect("programmer error in mismatch regex"); let m...
identifier_body
main.rs
// #![feature(alloc_system)] // extern crate alloc_system; extern crate regex; extern crate argparse; use regex::Regex; use std::fs::File; use argparse::{ArgumentParser, Store}; use std::collections::HashSet; use std::collections::BTreeMap; use std::io::{BufReader, BufRead, BufWriter, Write}; // print $seqgene "Gene\...
} } // --------- end of basic algorithm --- } // (mapped_geneids, count_total) (count_total, count_matched) }
Some(v) => *v += 1, None => println!("illegal reference lib id encountered '{}'", &al_arr[2].split("_").nth(0).unwrap()) }
random_line_split
main.rs
// #![feature(alloc_system)] // extern crate alloc_system; extern crate regex; extern crate argparse; use regex::Regex; use std::fs::File; use argparse::{ArgumentParser, Store}; use std::collections::HashSet; use std::collections::BTreeMap; use std::io::{BufReader, BufRead, BufWriter, Write}; // print $seqgene "Gene\...
(fasta_file: &str, fasta_re: &Regex, geneid_pattern : String, gene_matches : &mut BTreeMap<String, u32>, ref_libIds: &mut BTreeMap<String, u32>) { let fasta_file = BufReader::new(File::open(fasta_file).expect("Problem opening fastq file")); for line in fasta_file.lines() { let ln = line.expect("progr...
process_fasta
identifier_name
main.rs
extern crate dotenv; extern crate iron; extern crate handlebars; extern crate handlebars_iron as hbs; #[macro_use] extern crate router; #[cfg(not(feature = "serde_type"))] extern crate rustc_serialize; extern crate mount; extern crate staticfile; extern crate reqwest; extern crate serde_json; extern crate iron_sessions...
let mut resp = Response::new(); resp.set_mut(Template::new("index", data)).set_mut(status::Ok); Ok(Response::with((status::Found, Redirect( Url::parse(redirect_url.as_str()).expect("parse url failed") )))) ...
}) }, None => HashMap::<String, Json>::new(), };
random_line_split
main.rs
extern crate dotenv; extern crate iron; extern crate handlebars; extern crate handlebars_iron as hbs; #[macro_use] extern crate router; #[cfg(not(feature = "serde_type"))] extern crate rustc_serialize; extern crate mount; extern crate staticfile; extern crate reqwest; extern crate serde_json; extern crate iron_sessions...
} } #[derive(Debug)] struct AccessToken(String); impl iron_sessionstorage::Value for AccessToken { fn get_key() -> &'static str { "access_token" } fn into_raw(self) -> String { self.0 } fn from_raw(value: String) -> Option<Self> { Some(AccessToken(value)) } } fn main() { dotenv().ok(...
{ match x { Value::Number(ref x) if x.is_i64() => Json::I64(x.as_i64().unwrap()), Value::Number(ref x) if x.is_u64() => Json::U64(x.as_u64().unwrap()), Value::Number(ref x) if x.is_f64() => Json::F64(x.as_f64().unwrap()), Value::String(x) => Json::String(x), Value::Array(x) =...
identifier_body
main.rs
extern crate dotenv; extern crate iron; extern crate handlebars; extern crate handlebars_iron as hbs; #[macro_use] extern crate router; #[cfg(not(feature = "serde_type"))] extern crate rustc_serialize; extern crate mount; extern crate staticfile; extern crate reqwest; extern crate serde_json; extern crate iron_sessions...
(String); impl iron_sessionstorage::Value for AccessToken { fn get_key() -> &'static str { "access_token" } fn into_raw(self) -> String { self.0 } fn from_raw(value: String) -> Option<Self> { Some(AccessToken(value)) } } fn main() { dotenv().ok(); let port = match env::var("PORT") { ...
AccessToken
identifier_name
endpoint.rs
use std::fmt; use std::fs; use std::io::{ self, Read, Write, }; use std::num::ParseIntError; use std::str; use super::Driver; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SlotFunction(pub u8); impl SlotFunction { pub fn slot(&self) -> u8 { self.0 >> 3 } pub fn function(&self) -> u...
(mut self) -> crate::AResult<()> { if let Some(ep) = self.ep.take() { ep.disable()?; } Ok(()) } } impl Drop for ScopedEnable { fn drop(&mut self) { if let Some(ep) = self.ep.take() { if let Err(e) = ep.disable() { error!("PCI {}: Failed to disable temporarily enabled device: {}", ep, e); } } ...
close
identifier_name
endpoint.rs
use std::fmt; use std::fs; use std::io::{ self, Read, Write, }; use std::num::ParseIntError; use std::str; use super::Driver; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SlotFunction(pub u8); impl SlotFunction { pub fn slot(&self) -> u8 { self.0 >> 3 } pub fn function(&self) -> u...
// short: 0.0, long: 1f.7 let (dev_s, fun_s) = if r.len() == 3 && r[1] == b'.' { (&s[0..1], &s[2..3]) } else if r.len() == 4 && r[2] == b'.' { (&s[0..2], &s[3..4]) } else { bail!("Couldn't find '.' in valid place for PCI device.function: {:?}", s); }; let dev = with_context!(("invalid PCI device:...
fn from_str(s: &str) -> Result<Self, Self::Err> { let r = s.as_bytes(); ensure!(r.len() <= 4, "String too long for PCI device.function: {:?}", s);
random_line_split
common.rs
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclai...
Some(peaks) } /// Calculates the positions of the (parent, sibling) of the node at the provided position. /// Returns an error if the pos provided would result in an underflow or overflow. pub fn family(pos: usize) -> Result<(usize, usize), MerkleMountainRangeError> { let (peak_map, height) = peak_map_height(...
{ // This happens, whenever the MMR is not valid, that is, all nodes are not // fully spawned. For example, in this case // 2 // / \ // 0 1 3 4 // is invalid, as it can be completed to form // 6 // / \ // 2 5 ...
conditional_block
common.rs
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclai...
() { assert_eq!(peak_map_height(0), (0, 0)); assert_eq!(peak_map_height(4), (0b11, 0)); // 6 // 2 5 // 0 1 3 4 7 8 assert_eq!(peak_map_height(9), (0b101, 1)); // 6 // 2 5 9 // 0 1 3 4 7 8 * assert_e...
peak_map_heights
identifier_name
common.rs
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclai...
// A tree with over a million nodes in it find the "family path" back up the tree from a leaf node at 0. // Note: the first two entries in the branch are consistent with a small 7 node tree. // Note: each sibling is on the left branch, this is an example of the largest possible list of peaks ...
assert_eq!(family_branch(3, 6), [(5, 4), (6, 2)]);
random_line_split
common.rs
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclai...
/// Is the node at this pos the "left" sibling of its parent? pub fn is_left_sibling(pos: usize) -> bool { let (peak_map, height) = peak_map_height(pos); let peak = 1 << height; (peak_map & peak) == 0 } pub fn hash_together<D: Digest + DomainDigest>(left: &[u8], right: &[u8]) -> Hash { D::new().chain...
{ if pos == 0 { return (0, 0); } let mut peak_size = ALL_ONES >> pos.leading_zeros(); let mut bitmap = 0; while peak_size != 0 { bitmap <<= 1; if pos >= peak_size { pos -= peak_size; bitmap |= 1; } peak_size >>= 1; } (bitmap, po...
identifier_body
lib.rs
//! # python-config-rs //! //! Just like the `python3-config` script that's installed //! with your Python distribution, `python-config-rs` helps you //! find information about your Python distribution. //! //! ```no_run //! use python_config::PythonConfig; //! //! let cfg = PythonConfig::new(); // Python 3 //! //! // ...
fn is_py3(&self) -> Result<(), Error> { if self.ver!= Version::Three { Err(Error::Python3Only) } else { Ok(()) } } /// Create a `PythonConfig` that uses the interpreter at the path `interpreter`. /// /// This fails if the path cannot be represented ...
{ PythonConfig { cmdr, ver } }
identifier_body
lib.rs
//! # python-config-rs //! //! Just like the `python3-config` script that's installed //! with your Python distribution, `python-config-rs` helps you //! find information about your Python distribution. //! //! ```no_run //! use python_config::PythonConfig; //! //! let cfg = PythonConfig::new(); // Python 3 //! //! // ...
() { let cfg = PythonConfig::new(); let include_str = cfg.includes().unwrap(); assert!(!include_str.is_empty()); let paths: Vec<PathBuf> = include_str .split(" ") .map(|include| { // Drop the '-I' characters before each path PathBuf::...
include_paths_same
identifier_name
lib.rs
//! # python-config-rs //! //! Just like the `python3-config` script that's installed //! with your Python distribution, `python-config-rs` helps you //! find information about your Python distribution. //! //! ```no_run //! use python_config::PythonConfig; //! //! let cfg = PythonConfig::new(); // Python 3 //! //! // ...
/// The result type denotes that this function /// is only available when interfacing a Python 3 /// interpreter. /// /// It's the same as the normal [`PyResult`](type.PyResult.html) /// used throughout this module, but it's just a little /// type hint. pub type Py3Only<T> = Result<T, Error>; #[inline] fn other_err(wh...
/// an [`Error`](enum.Error.html). pub type PyResult<T> = Result<T, Error>;
random_line_split
path.rs
//! This module contains code for abstracting object locations that work //! across different backing implementations and platforms. use itertools::Itertools; use percent_encoding::{percent_decode_str, percent_encode, AsciiSet, CONTROLS}; use std::path::PathBuf; /// Universal interface for handling paths and location...
{} impl FileConverter { /// Creates a filesystem `PathBuf` location by using the standard library's /// `PathBuf` building implementation appropriate for the current /// platform. pub fn convert(object_store_path: &ObjectStorePath) -> PathBuf { object_store_path.parts.iter().map(|p| &p.0).coll...
FileConverter
identifier_name
path.rs
//! This module contains code for abstracting object locations that work //! across different backing implementations and platforms. use itertools::Itertools; use percent_encoding::{percent_decode_str, percent_encode, AsciiSet, CONTROLS}; use std::path::PathBuf; /// Universal interface for handling paths and location...
fn push_encodes() { let mut location = ObjectStorePath::default(); location.push("foo/bar"); location.push("baz%2Ftest"); let converted = CloudConverter::convert(&location); assert_eq!(converted, "foo%2Fbar/baz%252Ftest"); } #[test] fn push_all_encodes() { ...
} #[test]
random_line_split
mod.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! The device layer. pub(crate) mod arp; pub(crate) mod ethernet; pub(crate) mod ndp; use std::fmt::{self, Debug, Display, Formatter}; use log::{debug,...
/// # Panics /// /// Panics if `device` is not initialized. pub fn receive_frame<B: BufferMut, D: BufferDispatcher<B>>( ctx: &mut Context<D>, device: DeviceId, buffer: B, ) { // `device` must be initialized. assert!(is_device_initialized(ctx.state(), device)); match device.protocol { De...
random_line_split
mod.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! The device layer. pub(crate) mod arp; pub(crate) mod ethernet; pub(crate) mod ndp; use std::fmt::{self, Debug, Display, Formatter}; use log::{debug,...
/// Borrow the content which is stored inside. pub(crate) fn inner(&self) -> &T { &self.0 } /// Similar to `Option::map`. pub(crate) fn map<U, F>(self, f: F) -> Tentative<U> where F: FnOnce(T) -> U, { Tentative(f(self.0), self.1) } /// Make the tentative v...
{ if self.is_tentative() { None } else { Some(self.into_inner()) } }
identifier_body
mod.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! The device layer. pub(crate) mod arp; pub(crate) mod ethernet; pub(crate) mod ndp; use std::fmt::{self, Debug, Display, Formatter}; use log::{debug,...
<D: EventDispatcher, A: IpAddress>( ctx: &Context<D>, device: DeviceId, ) -> Option<Tentative<AddrSubnet<A>>> { match device.protocol { DeviceProtocol::Ethernet => { self::ethernet::get_ip_addr_subnet_with_tentative(ctx, device.id) } } } /// Set the IP address and subnet ass...
get_ip_addr_subnet_with_tentative
identifier_name
old_main.rs
let mut app = App::new(opengl, window); while let Some(e) = events.next(&mut app.window) { e.render(|args| { app.render(args); }); e.update(|args| { app.update(args.dt); }); // handle keyboard/button presses e.press(|button| { ...
{ current: Option<FloorNodeId>, last_pointer: Option<Point> } impl PointedRoom { fn new() -> Self { PointedRoom { current: None, last_pointer: None, } } fn forget(&mut self) { self.current = None; self.last_pointer = None; } fn update(...
PointedRoom
identifier_name
old_main.rs
let mut app = App::new(opengl, window); while let Some(e) = events.next(&mut app.window) { e.render(|args| { app.render(args); }); e.update(|args| { app.update(args.dt); }); // handle keyboard/button presses e.press(|button| { ...
// DEBUG: cursor { let [cx, cy] = cursor; let vertical = rectangle::centered([cx, cy, 1.0, 4.0]); let horizontal = rectangle::centered([cx, cy, 4.0, 1.0]); rectangle(CURSOR_COLOR, vertical, c.transform, gl); rectan...
{ let start = Some(player_pos.clone()); let lines = start.iter().chain(nav.waypoints().iter().skip(nav.progress)).sliding(); for (from, to) in lines { line_from_to(PATH_COLOR, 1.0, *from, *to, c.transform, gl); } }
conditional_block
old_main.rs
()); let mut app = App::new(opengl, window); while let Some(e) = events.next(&mut app.window) { e.render(|args| {
e.update(|args| { app.update(args.dt); }); // handle keyboard/button presses e.press(|button| { if let Button::Keyboard(key) = button { if key == Key::Space { app.generate_requested = true; } pri...
app.render(args); });
random_line_split
aarch64.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::fmt::{Displa...
(os error 8)" .to_string() ); init_vcpu(&vcpu.fd, vm.fd()); let state = vcpu.save_state().expect("Cannot save state of vcpu"); assert!(!state.regs.is_empty()); vcpu.restore_state(&state) .expect("Cannot restore state of vcpu"); let ...
"Failed to restore the state of the vcpu: Failed to set register: Exec format error \
random_line_split
aarch64.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::fmt::{Displa...
(index: u8, vm: &Vm) -> Result<Self> { let kvm_vcpu = vm.fd().create_vcpu(index.into()).map_err(Error::CreateFd)?; Ok(KvmVcpu { index, fd: kvm_vcpu, mmio_bus: None, mpidr: 0, }) } /// Gets the MPIDR register value. pub fn get_mpidr(&s...
new
identifier_name
aarch64.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::fmt::{Displa...
/// Initializes an aarch64 specific vcpu for booting Linux. /// /// # Arguments /// /// * `vm_fd` - The kvm `VmFd` for this microvm. pub fn init(&self, vm_fd: &VmFd) -> Result<()> { let mut kvi: kvm_bindings::kvm_vcpu_init = kvm_bindings::kvm_vcpu_init::default(); // This read...
{ arch::aarch64::regs::setup_boot_regs( &self.fd, self.index, kernel_load_addr.raw_value(), guest_mem, ) .map_err(Error::ConfigureRegisters)?; self.mpidr = arch::aarch64::regs::read_mpidr(&self.fd).map_err(Error::ConfigureRegis...
identifier_body
ic7406.rs
// Copyright (c) 2021 Thomas J. Otterson // // This software is released under the MIT License. // https://opensource.org/licenses/MIT // Note that the imports for std::rc::Rc, std::cell::RefCell, and // crate::components::pin::Pin are only necessary because of the demo non-macro constructor // function. /// Pin assi...
assert!(low!(tr[Y6]), "Y6 should be low when A6 is high"); } #[test] fn input_low() { let (_, tr) = before_each(); clear!(tr[A1]); assert!(high!(tr[Y1]), "Y1 should be high when A1 is low"); clear!(tr[A2]); assert!(high!(tr[Y2]), "Y2 should be high when A2 ...
assert!(low!(tr[Y5]), "Y5 should be low when A5 is high"); set!(tr[A6]);
random_line_split
ic7406.rs
// Copyright (c) 2021 Thomas J. Otterson // // This software is released under the MIT License. // https://opensource.org/licenses/MIT // Note that the imports for std::rc::Rc, std::cell::RefCell, and // crate::components::pin::Pin are only necessary because of the demo non-macro constructor // function. /// Pin assi...
} } } #[cfg(test)] mod test { use crate::{components::trace::Trace, test_utils::make_traces}; use super::*; fn before_each() -> (DeviceRef, RefVec<Trace>) { let chip = Ic7406::new(); let tr = make_traces(&chip); (chip, tr) } #[test] fn input_high() { ...
{}
conditional_block
ic7406.rs
// Copyright (c) 2021 Thomas J. Otterson // // This software is released under the MIT License. // https://opensource.org/licenses/MIT // Note that the imports for std::rc::Rc, std::cell::RefCell, and // crate::components::pin::Pin are only necessary because of the demo non-macro constructor // function. /// Pin assi...
fn update(&mut self, event: &LevelChange) { match event { LevelChange(pin) if INPUTS.contains(&number!(pin)) => { let o = output_for(number!(pin)); if high!(pin) { clear!(self.pins[o]); } else { set!(self.p...
{ Vec::new() }
identifier_body
ic7406.rs
// Copyright (c) 2021 Thomas J. Otterson // // This software is released under the MIT License. // https://opensource.org/licenses/MIT // Note that the imports for std::rc::Rc, std::cell::RefCell, and // crate::components::pin::Pin are only necessary because of the demo non-macro constructor // function. /// Pin assi...
() { let (_, tr) = before_each(); set!(tr[A1]); assert!(low!(tr[Y1]), "Y1 should be low when A1 is high"); set!(tr[A2]); assert!(low!(tr[Y2]), "Y2 should be low when A2 is high"); set!(tr[A3]); assert!(low!(tr[Y3]), "Y3 should be low when A3 is high"); ...
input_high
identifier_name
graphics.rs
use std::collections::HashMap; use std::fs; use wgpu::util::DeviceExt; use crate::texture::Texture; pub struct Graphics { pub surface: wgpu::Surface, pub device: wgpu::Device, pub queue: wgpu::Queue, pub swap_chain_descriptor: wgpu::SwapChainDescriptor, pub swap_chain: wgpu::SwapChain, pub size...
pub fn load_shader(shader_name: &str) -> Vec<u8> { let mut shader_dir = std::env::current_dir().unwrap(); shader_dir.push("src\\resources\\shaders"); shader_dir.push(shader_name); match fs::read(&shader_dir) { Ok(v) => v, Err(error) => panic!("Failed to read the file: {:?}. Error: {}"...
{ let texture = Texture::load_texture(texture_name, &device, &queue).unwrap(); device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &texture_bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Te...
identifier_body
graphics.rs
use std::collections::HashMap; use std::fs; use wgpu::util::DeviceExt; use crate::texture::Texture; pub struct Graphics { pub surface: wgpu::Surface, pub device: wgpu::Device, pub queue: wgpu::Queue, pub swap_chain_descriptor: wgpu::SwapChainDescriptor, pub swap_chain: wgpu::SwapChain, pub size...
let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Texture { ...
}; let swap_chain = device.create_swap_chain(&surface, &swap_chain_descriptor);
random_line_split
graphics.rs
use std::collections::HashMap; use std::fs; use wgpu::util::DeviceExt; use crate::texture::Texture; pub struct Graphics { pub surface: wgpu::Surface, pub device: wgpu::Device, pub queue: wgpu::Queue, pub swap_chain_descriptor: wgpu::SwapChainDescriptor, pub swap_chain: wgpu::SwapChain, pub size...
{ pub model_matrix: [[f32; 4]; 4], } fn create_quad() -> Mesh { let mut vertices = Vec::new(); let vertexA = Vertex { position: [-0.5, 0.5, 0.0], normal: [0.0, 0.0, 1.0], tex_coords: [0.0, 0.0], }; let vertexB = Vertex { position: [0.5, 0.5, 0.0], normal: ...
ModelProperties
identifier_name
lib.rs
//! [![docs.rs badge](https://docs.rs/petgraph-graphml/badge.svg)](https://docs.rs/petgraph-graphml/) //! [![crates.io badge](https://img.shields.io/crates/v/petgraph-graphml.svg)](https://crates.io/crates/petgraph-graphml/) //! [![Rust CI](https://github.com/jonasbb/petgraph-graphml/workflows/Rust%20CI/badge.svg)](htt...
.attr("id", &*attr.name) .attr("for", attr.for_.to_str()) .attr("attr.name", &*attr.name) .attr("attr.type", "string"), )?; writer.write(XmlEvent::end_element())?; // end key } Ok(()) } } impl<G> Deb...
XmlEvent::start_element("key")
random_line_split
lib.rs
//! [![docs.rs badge](https://docs.rs/petgraph-graphml/badge.svg)](https://docs.rs/petgraph-graphml/) //! [![crates.io badge](https://img.shields.io/crates/v/petgraph-graphml.svg)](https://crates.io/crates/petgraph-graphml/) //! [![Rust CI](https://github.com/jonasbb/petgraph-graphml/workflows/Rust%20CI/badge.svg)](htt...
else { "undirected" }, ))?; // Emit nodes for node in self.graph.node_references() { writer.write(XmlEvent::start_element("node").attr("id", &*node2str_id(node.id())))?; // Print weights if let Some(ref node_labels) = self.export_...
{ "directed" }
conditional_block
lib.rs
//! [![docs.rs badge](https://docs.rs/petgraph-graphml/badge.svg)](https://docs.rs/petgraph-graphml/) //! [![crates.io badge](https://img.shields.io/crates/v/petgraph-graphml.svg)](https://crates.io/crates/petgraph-graphml/) //! [![Rust CI](https://github.com/jonasbb/petgraph-graphml/workflows/Rust%20CI/badge.svg)](htt...
/// Export the node weights to GraphML. /// /// This uses the [`Display`] implementation of the node weight type. /// The attribute name defaults to "weight". /// /// Once set this option cannot be disabled anymore. /// /// [`Display`]: ::std::fmt::Display pub fn export_node_weight...
{ self.export_edges = Some(edge_weight); self }
identifier_body
lib.rs
//! [![docs.rs badge](https://docs.rs/petgraph-graphml/badge.svg)](https://docs.rs/petgraph-graphml/) //! [![crates.io badge](https://img.shields.io/crates/v/petgraph-graphml.svg)](https://crates.io/crates/petgraph-graphml/) //! [![Rust CI](https://github.com/jonasbb/petgraph-graphml/workflows/Rust%20CI/badge.svg)](htt...
(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("GraphMl") .field("graph", &self.graph) .field("pretty_print", &self.pretty_print) .field("export_edges", &self.export_edges.is_some()) .field("export_nodes", &self.export_nodes.is_some()) ...
fmt
identifier_name
main.rs
#![feature(rustc_private)] extern crate im; extern crate pretty; extern crate rustc_ast; extern crate rustc_driver; extern crate rustc_errors; extern crate rustc_hir; extern crate rustc_interface; extern crate rustc_metadata; extern crate rustc_middle; extern crate rustc_session; extern crate rustc_span; mod ast_to_ru...
.find(|p| p.name == package_name) .expect(&format!( " ⚠️ Can't find the package {} in the Cargo.toml\n\n{}", package_name, APP_USAGE, )) } else { &manifest.packages[0] }; log::trace!("Typechecking '{:?}'...", package); // Take t...
.iter()
random_line_split
main.rs
#![feature(rustc_private)] extern crate im; extern crate pretty; extern crate rustc_ast; extern crate rustc_driver; extern crate rustc_errors; extern crate rustc_hir; extern crate rustc_interface; extern crate rustc_metadata; extern crate rustc_middle; extern crate rustc_session; extern crate rustc_span; mod ast_to_ru...
{ output_file: Option<String>, target_directory: String, } const ERROR_OUTPUT_CONFIG: ErrorOutputType = ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(ColorConfig::Auto)); trait HacspecErrorEmitter { fn span_rustspec_err<S: Into<MultiSpan>>(&self, s: S, msg: &str); fn span_rustsp...
HacspecCallbacks
identifier_name