lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
gen/src/builtin.rs
capickett/cxx
8e2faa4991c75704b33e998cd332eb45346d5336
use crate::gen::block::Block; use crate::gen::ifndef; use crate::gen::out::{Content, OutFile}; #[derive(Default, PartialEq)] pub struct Builtins<'a> { pub panic: bool, pub rust_string: bool, pub rust_str: bool, pub rust_slice: bool, pub rust_box: bool, pub rust_vec: bool, pub rust_fn: bool,...
use crate::gen::block::Block; use crate::gen::ifndef; use crate::gen::out::{Content, OutFile}; #[derive(Default, PartialEq)] pub struct Builtins<'a> { pub panic: bool, pub rust_string: bool, pub rust_str: bool, pub rust_slice: bool, pub rust_box: bool, pub rust_vec: bool, pub rust_fn: bool,...
if builtin.rust_box { include.new = true; include.type_traits = true; include.utility = true; } if builtin.rust_fn { include.utility = true; } if builtin.rust_error { include.exception = true; builtin.friend_impl = true; } if builtin.rust_...
if builtin.rust_slice { include.array = true; include.cstddef = true; include.cstdint = true; include.iterator = true; include.type_traits = true; builtin.friend_impl = true; builtin.layout = true; builtin.panic = true; }
if_condition
[ { "content": "pub fn expand_struct(strct: &Struct, actual_derives: &mut Option<TokenStream>) -> TokenStream {\n\n let mut expanded = TokenStream::new();\n\n let mut traits = Vec::new();\n\n\n\n for derive in &strct.derives {\n\n let span = derive.span;\n\n match derive.what {\n\n ...
Rust
tests/test.rs
zharkomi/vector-merkle-tree
62385c81e5fcc2a0f419b073816f4a26cab70bea
extern crate ring; extern crate vmt; macro_rules! test_tree { ($constructor:ident) => { use ring::digest::{Algorithm, Context, Digest, SHA512}; use vmt::MerkleTree; static ALGO: &'static Algorithm = &SHA512; #[test] fn test_tree_0() { let values: Vec<&str> = v...
extern crate ring; extern crate vmt; macro_rules! test_tree { ($constructor:ident) => { use ring::digest::{Algorithm, Context, Digest, SHA512}; use vmt::MerkleTree; static ALGO: &'static Algorithm = &SHA512; #[test] f
assert_eq!(true, proof.is_some()); let vec = proof.unwrap(); assert_eq!(3, vec.len()); tree.validate(&vec); } let absent = vec!["qqq", "www", "eee", "rrr"]; for v in absent { let proof = tree.build_proof(&v); ...
n test_tree_0() { let values: Vec<&str> = vec![]; let tree = MerkleTree::$constructor(&values, ALGO); assert_eq!(true, tree.is_empty()); assert_eq!(0, tree.height()); assert_eq!(0, tree.nodes_count()); assert_eq!(0, tree.data_size()); ...
random
[ { "content": "pub fn get_hash(x: &[u8], algo: &'static Algorithm) -> Digest {\n\n let mut ctx = Context::new(algo);\n\n ctx.update(x);\n\n ctx.finish()\n\n}", "file_path": "src/lib.rs", "rank": 0, "score": 65870.31932308526 }, { "content": "pub fn get_pair_hash(x: &[u8], y: &[u8], a...
Rust
exonum/src/encoding/protobuf/mod.rs
fedir-molchan/exonum
3501abba0f4574d21da64e5991434412234e813e
#![allow(bare_trait_objects)] #![allow(renamed_and_removed_lints)] pub use self::blockchain::{Block, ConfigReference, TxLocation}; pub use self::helpers::{BitVec, Hash, PublicKey}; pub use self::protocol::{ BlockRequest, BlockResponse, Connect, PeersRequest, Precommit, Prevote, PrevotesRequest, Propose, Prop...
#![allow(bare_trait_objects)] #![allow(renamed_and_removed_lints)] pub use self::blockchain::{Block, ConfigReference, TxLocation}; pub use self::helpers::{BitVec, Hash, PublicKey}; pub use self::protocol::{ BlockRequest, BlockResponse, Connect, PeersRequest, Precommit, Prevote, PrevotesRequest, Propose, Prop...
= u32; fn to_pb(&self) -> Self::ProtoStruct { self.0 } fn from_pb(pb: Self::ProtoStruct) -> Result<Self, ()> { Ok(Round(pb)) } } impl ProtobufConvert for ValidatorId { type ProtoStruct = u32; fn to_pb(&self) -> Self::ProtoStruct { u32::from(self.0) } fn from_pb(p...
chain; mod helpers; mod protocol; pub trait ProtobufConvert: Sized { type ProtoStruct; fn to_pb(&self) -> Self::ProtoStruct; fn from_pb(pb: Self::ProtoStruct) -> Result<Self, ()>; } impl<T> BinaryForm for T where T: ProtobufConvert, <T as ProtobufConvert>::ProtoStruct: Message, { ...
random
[ { "content": "/// Calculates hash of a bytes slice.\n\npub fn hash(data: &[u8]) -> Hash {\n\n sha256::hash(data)\n\n}\n", "file_path": "crypto/src/crypto_lib/sodiumoxide/mod.rs", "rank": 0, "score": 275758.0190634015 }, { "content": "/// Calculates a hash of a bytes slice.\n\n///\n\n/// T...
Rust
consensus/service/src/api/grpc_error.rs
isis-mc/mobilecoin
aa5c65c042c78840ade32bf198538646ea2020ee
use crate::tx_manager::TxManagerError; use displaydoc::Display; use grpcio::{RpcStatus, RpcStatusCode}; use mc_common::logger::global_log; use mc_consensus_api::consensus_common::{ProposeTxResponse, ProposeTxResult}; use mc_consensus_enclave::Error as EnclaveError; use mc_ledger_db::Error as LedgerError; use mc_trans...
use crate::tx_manager::TxManagerError; use displaydoc::Display; use grpcio::{RpcStatus, RpcStatusCode}; use mc_common::logger::global_log; use mc_consensus_api::consensus_common::{Pr
n(err) => { let mut resp = ProposeTxResponse::new(); resp.set_result(ProposeTxResult::from(err)); Ok(resp) } _ => Err(RpcStatus::from(self)), } } }
oposeTxResponse, ProposeTxResult}; use mc_consensus_enclave::Error as EnclaveError; use mc_ledger_db::Error as LedgerError; use mc_transaction_core::validation::TransactionValidationError; #[derive(Debug, Display)] pub enum ConsensusGrpcError { RpcStatus(RpcStatus), Ledger(LedgerError), Ov...
random
[ { "content": "## Prohibited Uses and Transfers of MobileCoins and Uses of MobileCoin Wallets\n\n\n\nYou may not:\n\n- use or transfer MobileCoins or access or use a MobileCoin Wallet in order to disguise the origin or nature of illicit proceeds of, or to further, any breach of applicable laws, or to transact or...
Rust
http/src/request/channel/message/create_message.rs
dlee13/dawn
3a1443e88bee0abc543b9cc92ed2e5665e685b84
use super::allowed_mentions::{AllowedMentions, AllowedMentionsBuilder, Unspecified}; use crate::request::prelude::*; use reqwest::{ multipart::{Form, Part}, Body, }; use std::{ collections::HashMap, error::Error, fmt::{Display, Formatter, Result as FmtResult}, }; use twilight_model::{ channel::{...
use super::allowed_mentions::{AllowedMentions, AllowedMentionsBuilder, Unspecified}; use crate::request::prelude::*; use reqwest::{ multipart::{Form, Part}, Body, }; use std::{ collections::HashMap, error::Error, fmt::{Display, Formatter, Result as FmtResult}, }; use twilight_model::{ channel::{...
self.fields.embed.replace(embed); Ok(self) } pub fn allowed_mentions( self, ) -> AllowedMentionsBuilder<'a, Unspecified, Unspecified, Unspecified> { AllowedMentionsBuilder::for_builder(self) } pub fn attachment(mut self, name: impl I...
if let Err(source) = validate::embed(&embed) { return Err(CreateMessageError::EmbedTooLarge { embed: Box::new(embed), source, }); }
if_condition
[ { "content": "pub fn embed(embed: &Embed) -> Result<(), EmbedValidationError> {\n\n let mut total = 0;\n\n\n\n if embed.fields.len() > EmbedValidationError::FIELD_COUNT {\n\n return Err(EmbedValidationError::TooManyFields {\n\n amount: embed.fields.len(),\n\n });\n\n }\n\n\n\n ...
Rust
megenginelite-rs/src/api.rs
MegEngine/megenginelite-rs
8d88645bfe4e1eaee144aa73433b359c69d09b98
use crate::types::*; use megenginelite_sys::MgeLiteDynLib; use std::ffi::CStr; use std::sync::{Mutex, Once}; #[doc(hidden)] pub trait IntoLiteRst { fn into_rst(self) -> LiteResult<()>; } impl IntoLiteRst for i32 { fn into_rst(self) -> LiteResult<()> { match self { 0 => Ok(()), ...
use crate::types::*; use megenginelite_sys::MgeLiteDynLib; use std::ffi::CStr; use std::sync::{Mutex, Once}; #[doc(hidden)] pub trait IntoLiteRst { fn into_rst(self) -> LiteResult<()>; } impl IntoLiteRst for i32 { fn into_rst(self) -> LiteResult<()> { match self { 0 => Ok(()), ...
fn version(major: i32, minor: i32, patch: i32) -> i32 { const UNIT: i32 = 10000; major * UNIT * UNIT + minor * UNIT + patch }
fn check_version() -> LiteResult<()> { let mut major = 0i32; let mut minor = 0i32; let mut patch = 0i32; unsafe { let api = API .as_ref() .expect("dynamic library [megenginelite] is not found"); api.LITE_get_version(&mut major, &mut minor, &mut patch) }; ...
function_block-full_function
[ { "content": "/// Dump the algo policy cache to file, if the network is set to profile\n\n///\n\n/// when forward, though this the algo policy will dump to file\n\n/// `cache_path` is the file path which store the cache\n\npub fn dump_persistent_cache(path: impl AsRef<Path>) {\n\n let path = utils::path_to_c...
Rust
benches/bench.rs
sdroege/byteorder
f8e7685b3a81c52f5448fd77fb4e0535bc92f880
#![cfg_attr(feature = "i128", feature(i128))] #![feature(test)] extern crate byteorder; extern crate test; macro_rules! bench_num { ($name:ident, $read:ident, $bytes:expr, $data:expr) => ( mod $name { use byteorder::{ByteOrder, BigEndian, NativeEndian, LittleEndian}; use super::tes...
#![cfg_attr(feature = "i128", feature(i128))] #![feature(test)] extern crate byteorder; extern crate test; macro_rules! bench_num { ($name:ident, $read:ident, $bytes:expr, $data:expr) => ( mod $name { use byteorder::{ByteOrder, BigEndian, NativeEndian, LittleEndian}; use super::tes...
0, 11]); #[cfg(feature = "i128")] bench_num!(int128_12, read_int128, 12, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); #[cfg(feature = "i128")] bench_num!(int128_13, read_int128, 13, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]); #[cfg(feature = "i128")] bench_num!(int128_14, read_int128, 14, [1, 2, 3, 4, 5, 6, ...
f32, MAX, read_f32, write_f32, 4, [1, 2, 3, 4]); bench_num!(f64, MAX, read_f64, write_f64, 8, [1, 2, 3, 4, 5, 6, 7, 8]); bench_num!(uint_1, read_uint, 1, [1]); bench_num!(uint_2, read_uint, 2, [1, 2]); bench_num!(uint_3, read_uint, 3, [1, 2, 3]); bench_num!(uint_4, read_uint, 4, [1, 2, 3, 4]); bench_num!(ui...
random
[ { "content": "#[cfg(feature = \"i128\")]\n\n#[inline]\n\nfn unextend_sign128(val: i128, nbytes: usize) -> u128 {\n\n let shift = (16 - nbytes) * 8;\n\n (val << shift) as u128 >> shift\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 48565.358119323115 }, { "content": "#[cfg(...
Rust
src/llvm/global_variables.rs
mrLSD/iLang
3202a32d7401460cab90b15768e42088c2de3bcb
use super::{ addrspace::AddrSpace, align::Alignment, comdat::ComDat, dll_storage_classes::DllStorageClasses, linkage_types::LinkageTypes, runtime_preemption::RuntimePreemptionSpecifier, section::Section, thread_local_storage::ThreadLocalStorage, types::Type, visibility_styles::...
use super::{ addrspace::AddrSpace, align::Alignment, comdat::ComDat, dll_storage_classes::DllStorageClasses, linkage_types::LinkageTypes, runtime_preemption::RuntimePreemptionSpecifier, section::Section, thread_local_storage::ThreadLocalStorage, types::Type, visibility_styles::...
} impl InstructionSet for GlobalVariable { fn set_context(&mut self, ctx: u64) { self.ctx = Some(ctx); } fn is_assignment(&self) -> bool { true } fn is_global(&self) -> bool { true } fn get_type(&self) -> Option<Type> { Some(self.value_type.clone()) } ...
pub fn get_value_name(&self) -> Option<String> { if let Some(ctx) = self.ctx { Some(format!("@{:?}", ctx)) } else { Some(format!("@{}", self.name)) } }
function_block-full_function
[ { "content": "type LetValueName = String;\n\n\n\n/// Value and their type representation\n\n#[derive(Debug, Clone)]\n\npub struct ValueType {\n\n pub value: LetValueName,\n\n pub value_type: Option<BuildInTypes>,\n\n}\n\n\n\nimpl<'a> Codegen<'a> {\n\n #[allow(clippy::ptr_arg)]\n\n fn new(ast: &'a Ma...
Rust
src/mint.rs
Rational-As-Fuck/metaboss
89ee1b6123ca0b743d72d220f27fcffa7e728d16
use anyhow::{anyhow, Result}; use glob::glob; use log::{error, info}; use metaplex_token_metadata::instruction::{ create_master_edition, create_metadata_accounts, update_metadata_accounts, }; use rayon::prelude::*; use reqwest; use retry::{delay::Exponential, retry}; use serde_json::Value; use solana_client::rpc_cl...
use anyhow::{anyhow, Result}; use glob::glob; use log::{error, info}; use metaplex_token_metadata::instruction::{ create_master_edition, create_metadata_accounts, update_metadata_accounts, }; use rayon::prelude::*; use reqwest; use retry::{delay::Exponential, retry}; use serde_json::Value; use solana_client::rpc_cl...
{ Ok(_) => (), Err(e) => error!("Failed to mint {:?}: {}", &path, e), } }); if !errors.is_empty() { error!("Failed to read some of the files with the following errors:"); for error in errors { error!("{}", error); } } Ok(()) } ...
mint_one( client, &keypair, &receiver, Some(path), None, immutable, primary_sale_happened, )
call_expression
[ { "content": "pub fn sign_one(client: &RpcClient, keypair: String, account: String) -> Result<()> {\n\n let creator = parse_keypair(&keypair)?;\n\n let account_pubkey = Pubkey::from_str(&account)?;\n\n\n\n let metadata_pubkey = get_metadata_pda(account_pubkey);\n\n\n\n info!(\n\n \"Signing me...
Rust
starknet-core/src/types/block.rs
xJonathanLEI/starknet-rs
23f3b072e85ebd44437addc86449a3ba805dc2c7
use super::{ super::serde::unsigned_field_element::{UfeHex, UfeHexOption}, ConfirmedTransactionReceipt, FieldElement, TransactionType, }; use serde::Deserialize; use serde_with::serde_as; pub enum BlockId { Hash(FieldElement), Number(u64), Pending, Latest, } #[derive(Debug, Deserialize, Parti...
use super::{ super::serde::unsigned_field_element::{UfeHex, UfeHexOption}, ConfirmedTransactionReceipt, FieldElement, TransactionType, }; use serde::Deserialize; use serde_with::serde_as; pub enum BlockId { Hash(FieldElement), Number(u64), Pending, Latest, } #[derive(Debug, Deserialize, Parti...
#[test] #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] fn test_block_deser_with_declare_tx() { let raw = include_str!("../../test-data/raw_gateway_responses/get_block/7_with_declare_tx.txt"); let block: Block = serde_json::from_str(raw).unwrap(); ...
unwrap(); assert!(new_block.sequencer_address.is_some()); let old_block: Block = serde_json::from_str(include_str!( "../../test-data/raw_gateway_responses/get_block/2_with_messages.txt" )) .unwrap(); assert!(old_block.sequencer_address.is_none()); }
function_block-function_prefix_line
[ { "content": "#[serde_as]\n\n#[derive(Serialize, Deserialize)]\n\nstruct Felt(#[serde_as(as = \"UfeHex\")] pub FieldElement);\n\n\n", "file_path": "starknet-providers/src/jsonrpc/mod.rs", "rank": 0, "score": 146793.51411672964 }, { "content": "pub fn mul_mod_floor(\n\n multiplicand: &Fiel...
Rust
common/functions/src/scalars/logics/logic.rs
youngsofun/databend
82689b1f3eb9da9e4243045090815ff1124a0a38
use std::sync::Arc; use common_datavalues2::BooleanType; use common_datavalues2::ColumnBuilder; use common_datavalues2::ColumnRef; use common_datavalues2::ColumnViewer; use common_datavalues2::ColumnsWithField; use common_datavalues2::DataTypePtr; use common_datavalues2::NullableColumnBuilder; use common_datavalues2...
use std::sync::Arc; use common_datavalues2::BooleanType; use common_datavalues2::ColumnBuilder; use common_datavalues2::ColumnRef; use common_datavalues2::ColumnViewer; use common_datavalues2::ColumnsWithField; use common_datavalues2::DataTypePtr; use common_datavalues2::NullableColumnBuilder; use common_datavalues2...
fn eval(&self, columns: &ColumnsWithField, input_rows: usize) -> Result<ColumnRef> { match self.op { LogicOperator::Not => self.eval_not(columns, input_rows), _ => self.eval_and_not_or(columns, input_rows), } } fn passthrough_null(&self) -> bool { !matches!...
fn return_type(&self, args: &[&DataTypePtr]) -> Result<DataTypePtr> { match self.op { LogicOperator::Not => { if args[0].is_nullable() { Ok(Arc::new(NullableType::create(BooleanType::arc()))) } else { Ok(BooleanType::arc()) ...
function_block-full_function
[ { "content": "pub fn col(name: &str) -> Expression {\n\n Expression::Column(name.to_string())\n\n}\n", "file_path": "common/planners/src/plan_expression_column.rs", "rank": 0, "score": 377708.0555833581 }, { "content": "pub fn match_text(text: &'static str) -> impl FnMut(Input) -> IResult...
Rust
src/spi.rs
jonas-schievink/stm32f0xx-hal
a7daf77cf0e9707e0d9b8f441ffbe82d80654fb5
use core::marker::PhantomData; use core::{ops::Deref, ptr}; pub use embedded_hal::spi::{Mode, Phase, Polarity}; use crate::pac::SPI1; #[cfg(any( feature = "stm32f030x8", feature = "stm32f030xc", feature = "stm32f042", feature = "stm32f048", feature = "stm32f051", feature = "stm32f058", f...
use core::marker::PhantomData; use core::{ops::Deref, ptr}; pub use embedded_hal::spi::{Mode, Phase, Polarity}; use crate::pac::SPI1; #[cfg(any( feature = "stm32f030x8", feature = "stm32f030xc", feature = "stm32f042", feature = "stm32f048", feature = "stm32f051", feature = "stm32f058", f...
} fn read_u8(&mut self) -> u8 { unsafe { ptr::read_volatile(&self.spi.dr as *const _ as *const u8) } } fn send_u8(&mut self, byte: u8) { unsafe { ptr::write_volatile(&self.spi.dr as *const _ as *mut u8, byte) } } fn read_u16(&mut self) -> u16 { ...
Err(if sr.ovr().bit_is_set() { nb::Error::Other(Error::Overrun) } else if sr.modf().bit_is_set() { nb::Error::Other(Error::ModeFault) } else if sr.crcerr().bit_is_set() { nb::Error::Other(Error::Crc) } else if sr.txe().bit_is_set() { return Ok(());...
call_expression
[]
Rust
core/http/src/uri/absolute.rs
benjaminch/Rocket
7f1731089849987052a1a545464188dace2b0d0c
use std::borrow::Cow; use std::fmt::{self, Display}; use crate::ext::IntoOwned; use crate::parse::{Extent, IndexedStr}; use crate::uri::{Authority, Origin, Error, as_utf8_unchecked}; #[derive(Debug, Clone)] pub struct Absolute<'a> { source: Option<Cow<'a, str>>, scheme: IndexedStr<'a>, authority: Option<A...
use std::borrow::Cow; use std::fmt::{self, Display}; use crate::ext::IntoOwned; use crate::parse::{Extent, IndexedStr}; use crate::uri::{Authority, Origin, Error, as_utf8_unchecked}; #[derive(Debug, Clone)] pub struct Absolute<'a> { source: Option<Cow<'a, str>>, scheme: IndexedStr<'a>, authority: Option<A...
}
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.scheme())?; match self.authority { Some(ref authority) => write!(f, "://{}", authority)?, None => write!(f, ":")? } if let Some(ref origin) = self.origin { write!(f, "{}",...
function_block-full_function
[ { "content": "#[inline]\n\npub fn origin_from_str(s: &str) -> Result<Origin<'_>, Error<'_>> {\n\n Ok(parse!(origin: RawInput::new(s.as_bytes()))?)\n\n}\n\n\n", "file_path": "core/http/src/parse/uri/mod.rs", "rank": 0, "score": 387481.30215801205 }, { "content": "#[inline]\n\npub fn author...
Rust
2018/01/src/main.rs
RadicalZephyr/advent-of-rust
34207a74305adbf1aae4e317c14f8cad8cb7811d
use std::collections::HashSet; use std::env; use std::fs::File; use std::io::BufReader; use std::io::{self, BufRead}; use std::num; #[derive(Debug)] enum Error { ArgumentError, EmptyInput, IoError(io::Error), ParseError(num::ParseIntError), } impl From<io::Error> for Error { fn from(error: io::Err...
use std::collections::HashSet; use std::env; use std::fs::File; use std::io::BufReader; use std::io::{self, BufRead}; use std::num; #[derive(Debug)] enum Error { ArgumentError, EmptyInput, IoError(io::Error), ParseError(num::ParseIntError), } impl From<io::Error> for Error {
.map(|c| c.as_ref().parse()) .collect::<Result<Vec<isize>, num::ParseIntError>>() } fn frequency<'a>(changes: impl Iterator<Item = &'a isize>) -> isize { changes.sum() } fn first_repeat<'a>(changes: impl Iterator<Item = &'a isize> + Clone) -> Option<isize> { let mut frequency = 0; let mut ...
fn from(error: io::Error) -> Self { Error::IoError(error) } } impl From<num::ParseIntError> for Error { fn from(error: num::ParseIntError) -> Self { Error::ParseError(error) } } fn parse<'a>( changes: impl Iterator<Item = &'a (impl AsRef<str> + 'a)>, ) -> Result<Vec<isize>, num::P...
random
[ { "content": "#[derive(Debug)]\n\nenum Error {\n\n ArgumentError,\n\n IoError(io::Error),\n\n}\n\n\n\nimpl From<io::Error> for Error {\n\n fn from(error: io::Error) -> Self {\n\n Error::IoError(error)\n\n }\n\n}\n\n\n", "file_path": "2018/02/src/main.rs", "rank": 1, "score": 86601...
Rust
query/src/sql/planner/binder/ddl/table.rs
DatafuseDev/fusequery
70de90ad5b05f0c2159921c7e9866da73d7bb217
use std::collections::BTreeMap; use common_ast::ast::*; use common_datavalues::DataField; use common_datavalues::DataSchemaRef; use common_datavalues::DataSchemaRefExt; use common_datavalues::NullableType; use common_datavalues::TypeFactory; use common_exception::ErrorCode; use common_exception::Result; use common_m...
use std::collections::BTreeMap; use common_ast::ast::*; use common_datavalues::DataField; use common_datavalues::DataSchemaRef; use common_datavalues::DataSchemaRefExt; use common_datavalues::NullableType; use common_datavalues::TypeFactory; use common_exception::ErrorCode; use common_exception::Result; use common_m...
.unwrap_or_else(|| self.ctx.get_current_catalog()); let database = database .as_ref() .map(|ident| ident.name.to_lowercase()) .unwrap_or_else(|| self.ctx.get_current_database()); let table = table.name.to_lowercase(); let mut engine = Engin...
aRefExt::create(fields)) } CreateTableSource::Like { catalog, database, table, } => { let catalog = catalog .as_ref() .map(|catalog| catalog.name.to_lowercase()) ...
random
[ { "content": "pub fn col(name: &str) -> Expression {\n\n Expression::Column(name.to_string())\n\n}\n", "file_path": "common/planners/src/plan_expression_column.rs", "rank": 0, "score": 242307.14682482358 }, { "content": "fn run_lexer(file: &mut File, source: &str) {\n\n let tokens = To...
Rust
gee/src/auto/queue.rs
jeandudey/granite-rs
a06d131240dbcf2935eb8d9659d8e65ab0d38df4
use crate::Collection; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct Queue(Interface<ffi::GeeQueue>) @requires Collection; ...
use crate::Collection; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct Queue(Interface<ffi::GeeQueue>) @requires Collection; ...
x_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::is-full\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(notify_is_full_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } } impl fmt::Display for Queue { fn fmt(&self, f: &mut...
#[doc(alias = "gee_queue_drain")] fn drain<P: IsA<Collection>>(recipient: &P, amount: i32) -> i32; #[doc(alias = "gee_queue_get_capacity")] fn get_capacity() -> i32; #[doc(alias = "gee_queue_get_remaining_capacity")] fn get_remaining_capacity() -> i32; #[doc(alias...
random
[ { "content": "pub trait CollectionExt: 'static {\n\n //#[doc(alias = \"gee_collection_contains\")]\n\n //fn contains(item: /*Unimplemented*/Fundamental: Pointer) -> bool;\n\n\n\n //#[doc(alias = \"gee_collection_add\")]\n\n //fn add(item: /*Unimplemented*/Fundamental: Pointer) -> bool;\n\n\n\n //...
Rust
bootloader-efi/src/arch/aarch64/mod.rs
hyperswine/Redox2
b090d53c3270d6eabf7d2fce5077d1bb0c78052a
use core::{mem, ptr}; use orbclient::{Color, Renderer}; use std::fs::find; use std::proto::Protocol; use uefi::guid::Guid; use uefi::status::{Error, Result}; use crate::display::{Display, ScaledDisplay, Output}; use crate::image::{self, Image}; use crate::key::{key, Key}; use crate::redoxfs; use crate::text::TextDispl...
use core::{mem, ptr}; use orbclient::{Color, Renderer}; use std::fs::find; use std::proto::Protocol; use uefi::guid::Guid; use uefi::status::{Error, Result}; use crate::display::{Display, ScaledDisplay, Output}; use crate::image::{self, Image}; use crate::key::{key, Key}; use crate::redoxfs; use crate::text::TextDispl...
if count == 0 { break; } kernel.extend(&buf[.. count]); } println!(""); (kernel, String::new()) }; println!("Copying Kernel..."); unsafe { KERNEL_SIZE = kernel.len() as u64; ...
atic mut KERNEL_ENTRY: u64 = 0; static mut DTB_PHYSICAL: u64 = 0; #[no_mangle] pub extern "C" fn __chkstk() { } unsafe fn exit_boot_services(key: usize) { let handle = std::handle(); let uefi = std::system_table(); let _ = (uefi.BootServices.ExitBootServices)(handle, key); } unsafe fn enter() -> !...
random
[]
Rust
contrib/rust/src/softmax_builder.rs
verycumbersome/dynet
b477636c62e22efdaa024acf497080fc6a6dae1f
use std::ptr::{self, NonNull}; use dynet_sys; use super::{ ApiResult, ComputationGraph, Expression, Parameter, ParameterCollection, Result, Wrap, }; pub trait SoftmaxBuilder: Wrap<dynet_sys::dynetSoftmaxBuilder_t> { fn new_graph(&mut self, cg: &mut ComputationGraph, update: bool) { unsafe { ...
use std::ptr::{self, NonNull}; use dynet_sys; use super::{ ApiResult, ComputationGraph, Expression, Parameter, ParameterCollection, Result, Wrap, }; pub trait SoftmaxBuilder: Wrap<dynet_sys::dynetSoftmaxBuilder_t> { fn new_graph(&mut self, cg: &mut ComputationGraph, update: bool) { unsafe { ...
pression { unsafe { let mut expr_ptr: *mut dynet_sys::dynetExpression_t = ptr::null_mut(); check_api_status!(dynet_sys::dynetGetSoftmaxBuilderFullLogDistribution( self.as_mut_ptr(), rep.as_ref().as_ptr(), &mut expr_ptr, )); ...
ression { unsafe { let mut expr_ptr: *mut dynet_sys::dynetExpression_t = ptr::null_mut(); check_api_status!(dynet_sys::dynetApplySoftmaxBuilderNegLogSoftmaxOne( self.as_mut_ptr(), rep.as_ref().as_ptr(), classidx, &mut expr_p...
random
[ { "content": "/// Computes moment along a specific dimension.\n\n///\n\n/// # Arguments\n\n///\n\n/// * x - Input mini-batched expression.\n\n/// * dims - Dimensions along which to reduce.\n\n/// * r - Order of the moment.\n\n/// * b - Whether to include batch dimension.\n\n/// * n - If > 0, overwrite the `n` i...
Rust
src/main.rs
frol/cargo-hack
2befd3982c39aef6f446827346b365aee6b2ce67
#![forbid(unsafe_code)] #![warn(future_incompatible, rust_2018_idioms, single_use_lifetimes, unreachable_pub)] #![warn(clippy::default_trait_access, clippy::wildcard_imports)] #[macro_use] mod term; #[macro_use] mod process; mod cargo; mod cli; mod context; mod features; mod fs; mod manifest; mod metadata; mod remov...
#![forbid(unsafe_code)] #![warn(future_incompatible, rust_2018_idioms, single_use_lifetimes, unreachable_pub)] #![warn(clippy::default_trait_access, clippy::wildcard_imports)] #[macro_use] mod term; #[macro_use] mod process; mod cargo; mod cli; mod context; mod features; mod fs; mod manifest; mod metadata; mod remov...
fn exec_cargo_with_features( cx: &Context<'_>, id: &PackageId, line: &ProcessBuilder<'_>, progress: &mut Progress, features: impl IntoIterator<Item = impl AsRef<str>>, ) -> Result<()> { let mut line = line.clone(); line.append_features(features); exec_cargo(cx, id, &mut line, progress)...
fn exec_actual( cx: &Context<'_>, id: &PackageId, kind: &Kind<'_>, line: &mut ProcessBuilder<'_>, progress: &mut Progress, ) -> Result<()> { match kind { Kind::NoSubcommand => return Ok(()), Kind::SkipAsPrivate => unreachable!(), Kind::Normal => { ...
function_block-full_function
[ { "content": "fn powerset<T: Copy>(iter: impl IntoIterator<Item = T>, depth: Option<usize>) -> Vec<Vec<T>> {\n\n iter.into_iter().fold(vec![vec![]], |mut acc, elem| {\n\n let ext = acc.clone().into_iter().map(|mut curr| {\n\n curr.push(elem);\n\n curr\n\n });\n\n if...
Rust
src/main.rs
phase/pokerus
27742d188930d62e76a2c7125692f32090acfbaf
extern crate bitbit; extern crate logos; extern crate png; use std::borrow::Cow; use std::env::args; use std::error::Error; use std::fs; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::process::exit; use crate::tileset::{parse_metatile_config, Tile, TileStorage}; mod rom; mod tileset; const VE...
extern crate bitbit; extern crate logos; extern crate png; use std::borrow::Cow; use std::env::args; use std::error::Error; use std::fs; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::process::exit; use crate::tileset::{parse_metatile_config, Tile, TileStorage}; mod rom; mod tileset; const VE...
}.clone(); if args.len() < 5 { return Err("missing input tilesets".to_string()); } let inputs = &args[4..]; let mut storage = TileStorage::new(output_path.clone(), primary); for tileset in...
let file = File::open(arg).expect("no such file"); let buf = BufReader::new(file); let lines: Vec<String> = buf.lines() .map(|l| l.expect("Could not parse line")) .collect(); parse_metatile_c...
random
[ { "content": "pub fn parse_metatile_config(lines: Vec<String>) -> Vec<(String, usize)> {\n\n let mut file_map: HashMap<String, String> = HashMap::new();\n\n let mut metatile_refs: Vec<(String, usize)> = Vec::new();\n\n for line in lines {\n\n if line.len() < 3 || line.starts_with('#') {\n\n ...
Rust
api/src/auth.rs
anjaamrein/ngm
a039de268ed856d93a098b0d04c1ce76266d49ca
use anyhow::Context; use axum::{ async_trait, extract::{FromRequest, RequestParts, TypedHeader}, headers::{authorization::Bearer, Authorization}, }; use jsonwebtoken::jwk::{AlgorithmParameters, JwkSet}; use jsonwebtoken::{DecodingKey, Validation}; use once_cell::sync::OnceCell; use serde::{Deserialize, Seri...
use anyhow::Context; use axum::{ async_trait, extract::{FromRequest, RequestParts, TypedHeader}, headers::{authorization::Bearer, Authorization}, }; use jsonwebtoken::jwk::{AlgorithmParameters, JwkSet}; use jsonwebtoken::{DecodingKey, Validation}; use once_cell::sync::OnceCell; use serde::{Deserialize, Seri...
Error::Jwt("Failed to decode token") }, )?; return Ok(decoded_token.claims); } _ => return Err(Error::Jwt("Unreachable!")), } } }
WKS` not initialized")? .find(&kid) .ok_or(Error::Jwt("No matching key found in keyset"))?; match jwk.algorithm { AlgorithmParameters::RSA(ref rsa) => { let decoding_key = DecodingKey::from_rsa_components(&rsa.n, &rsa.e) .map_err(|_| Error...
random
[ { "content": " static getAccessToken(): string | null {\n\n return localStorage.getItem(cognitoAccessToken);\n", "file_path": "ui/src/auth.ts", "rank": 0, "score": 146769.28736785732 }, { "content": "const header = `\n\n/* eslint-disable */\n\n// DO NOT EDIT: this is file is automaticall...
Rust
src/middleware/identity.rs
DenisKolodin/actix-web
a1958deaae7910f901d2ce4e6ecd8636869dbe15
use std::rc::Rc; use cookie::{Cookie, CookieJar, Key}; use futures::future::{err as FutErr, ok as FutOk, FutureResult}; use futures::Future; use time::Duration; use error::{Error, Result}; use http::header::{self, HeaderValue}; use httprequest::HttpRequest; use httpresponse::HttpResponse; use middleware::{Middlewar...
use std::rc::Rc; use cookie::{Cookie, CookieJar, Key}; use futures::future::{err as FutErr, ok as FutOk, FutureResult}; use futures::Future; use time::Duration; use error::{Error, Result}; use http::header::{self, HeaderValue}; use httprequest::HttpRequest; use httpresponse::HttpResponse; use middleware::{Middlewar...
} #[doc(hidden)] pub struct CookieIdentity { changed: bool, identity: Option<String>, inner: Rc<CookieIdentityInner>, } impl Identity for CookieIdentity { fn identity(&self) -> Option<&str> { self.identity.as_ref().map(|s| s.as_ref()) } fn remember(&mut self, value: String) { ...
self, req: &mut HttpRequest<S>, resp: HttpResponse, ) -> Result<Response> { if let Some(mut id) = req.extensions_mut().remove::<IdentityBox>() { id.0.write(resp) } else { Ok(Response::Done(resp)) } }
function_block-function_prefix_line
[ { "content": "/// Do websocket handshake and start actor\n\npub fn start<A, S>(req: HttpRequest<S>, actor: A) -> Result<HttpResponse, Error>\n\nwhere\n\n A: Actor<Context = WebsocketContext<A, S>> + StreamHandler<Message, ProtocolError>,\n\n S: 'static,\n\n{\n\n let mut resp = handshake(&req)?;\n\n ...
Rust
util/fee-estimator/src/estimator.rs
brson/ckb
b9bf40024b8a5acd9b8871dba669c89f38be297d
use crate::tx_confirm_stat::TxConfirmStat; use crate::FeeRate; use ckb_logger::debug; use ckb_types::packed::Byte32; use std::collections::HashMap; pub const MAX_CONFIRM_BLOCKS: usize = 1000; const MIN_BUCKET_FEERATE: f64 = 1000f64; const MAX_BUCKET_FEERATE: f64 = 1e7; const FEE_SPACING: f64 = 1.05f64; const MIN_ESTIM...
use crate::tx_confirm_stat::TxConfirmStat; use crate::FeeRate; use ckb_logger::debug; use ckb_types::packed::Byte32; use std::collections::HashMap; pub const MAX_CONFIRM_BLOCKS: usize = 1000; const MIN_BUCKET_FEERATE: f64 = 1000f64; const MAX_BUCKET_FEERATE: f64 = 1e7; const FEE_SPACING: f64 = 1.05f64; const MIN_ESTIM...
_tx(&mut self, tx_hash: Byte32, fee_rate: FeeRate, height: u64) { if self.tracked_txs.contains_key(&tx_hash) { return; } if height != self.best_height { return; } if let Some(bucket_index) = self.tx_confirm_stat.add_unconfirmed_tx...
filter(|tx| self.process_block_tx(height, tx)).count(); if self.start_height == 0 && processed_txs > 0 { self.start_height = self.best_height; debug!("Fee estimator start recording at {}", self.start_height); } } pub fn track
random
[]
Rust
clap-utils/src/input_parsers.rs
kevzettler/solana
ce4304cc9a087f1f3defa29aac16e5751f9657bf
use crate::keypair::{ keypair_from_seed_phrase, pubkey_from_path, resolve_signer_from_path, signer_from_path, ASK_KEYWORD, SKIP_SEED_PHRASE_VALIDATION_ARG, }; use chrono::DateTime; use clap::ArgMatches; use solana_remote_wallet::remote_wallet::RemoteWalletManager; use solana_sdk::{ clock::UnixTimestamp, ...
use crate::keypair::{ keypair_from_seed_phrase, pubkey_from_path, resolve_signer_from_path, signer_from_path, ASK_KEYWORD, SKIP_SEED_PHRASE_VALIDATION_ARG, }; use chrono::DateTime; use clap::ArgMatches; use solana_remote_wallet::remote_wallet::RemoteWalletManager; use solana_sdk::{ clock::UnixTimestamp, ...
pub fn keypair_of(matches: &ArgMatches<'_>, name: &str) -> Option<Keypair> { if let Some(value) = matches.value_of(name) { if value == ASK_KEYWORD { let skip_validation = matches.is_present(SKIP_SEED_PHRASE_VALIDATION_ARG.name); keypair_from_seed_phrase(name, skip_validation, true)...
pub fn unix_timestamp_from_rfc3339_datetime( matches: &ArgMatches<'_>, name: &str, ) -> Option<UnixTimestamp> { matches.value_of(name).and_then(|value| { DateTime::parse_from_rfc3339(value) .ok() .map(|date_time| date_time.timestamp()) }) }
function_block-full_function
[ { "content": "// Pretty print a \"name value\"\n\npub fn println_name_value(name: &str, value: &str) {\n\n let styled_value = if value == \"\" {\n\n style(\"(not set)\").italic()\n\n } else {\n\n style(value)\n\n };\n\n println!(\"{} {}\", style(name).bold(), styled_value);\n\n}\n\n\n"...
Rust
src/material.rs
PicoJr/rray
b1cb3c30a1d31a3b4fe96316266bf2f2bf7350d3
use crate::color::RRgb; use crate::ray::{random_in_unit_sphere, Ray, RayHit, RT}; use nalgebra::Vector3; use rand::distributions::Uniform; use rand::prelude::ThreadRng; use rand::Rng; #[derive(Clone)] pub(crate) enum Material { Dieletric(Dieletric), Lambertian(Lambertian), Metal(Metal), Light(Light), }...
use crate::color::RRgb; use crate::ray::{random_in_unit_sphere, Ray, RayHit, RT}; use nalgebra::Vector3; use rand::distributions::Uniform; use rand::prelude::ThreadRng; use rand::Rng; #[derive(Clone)] pub(crate) enum Material { Dieletric(Dieletric), Lambertian(Lambertian), Metal(Metal), Light(Light), }...
} impl Emitter for Material { fn emit(&self) -> RRgb { match self { Material::Dieletric(_) => RRgb::new(0., 0., 0.), Material::Lambertian(_) => RRgb::new(0., 0., 0.), Material::Metal(_) => RRgb::new(0., 0., 0.), Material::Light(light) => light.emit(), ...
ray_hit: &RayHit, thread_rng: &mut ThreadRng, ) -> Option<(RRgb, Ray<f32>)> { match self { Material::Dieletric(dieletric) => dieletric.scatter(ray, ray_hit, thread_rng), Material::Lambertian(lambertian) => lambertian.scatter(ray, ray_hit, thread_rng), Material::Me...
function_block-function_prefix_line
[ { "content": "fn bvh_direction(v: Vector3<RT>) -> bvh::nalgebra::Vector3<RT> {\n\n bvh::nalgebra::Vector3::new(v.x, v.y, v.z)\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub(crate) struct Ray<T: Scalar> {\n\n origin: Point3<T>,\n\n direction: Vector3<T>,\n\n}\n\n\n\nimpl Ray<RT> {\n\n pub(crate) fn new(o...
Rust
serialization-tests/tests/serialization.rs
saona-raimundo/petgraph
9ff688872b467d3e1b5adef19f5c52f519d3279c
extern crate petgraph; #[macro_use] extern crate quickcheck; extern crate bincode; extern crate itertools; extern crate serde_json; #[macro_use] extern crate defmac; use std::collections::HashSet; use std::fmt::Debug; use std::iter::FromIterator; use itertools::assert_equal; use itertools::{repeat_n, Itertools}; use...
extern crate petgraph; #[macro_use] extern crate quickcheck; extern crate bincode; extern crate itertools; extern crate serde_json; #[macro_use] extern crate defmac; use std::collections::HashSet; use std::fmt::Debug; use std::iter::FromIterator; use itertools::assert_equal; use itertools::{repeat_n, Itertools}; use...
#[test] fn bincode_stablegraph_added3_removed2() { let mut g1 = StableGraph::<i32, i32>::new(); let x = 1729; let a = g1.add_node(x); let b = g1.add_node(x + 1); let _c = g1.add_node(x + 2); g1.remove_node(a); g1.remove_node(b); let g2: StableGraph<i32, i32> = recod...
fn bincode_stablegraph_added2_removed2() { let mut g1 = StableGraph::<i32, i32>::new(); let x = 1729; let a = g1.add_node(x); let b = g1.add_node(x + 1); g1.remove_node(a); g1.remove_node(b); let g2: StableGraph<i32, i32> = recode!(&g1); assert_stable_graph_eq(&g1, &...
function_block-function_prefix_line
[ { "content": "fn mst_graph<N, E, Ty, Ix>(g: &Graph<N, E, Ty, Ix>) -> Graph<N, E, Undirected, Ix>\n\nwhere\n\n Ty: EdgeType,\n\n Ix: IndexType,\n\n N: Clone,\n\n E: Clone + PartialOrd,\n\n{\n\n Graph::from_elements(min_spanning_tree(&g))\n\n}\n\n\n\nuse std::fmt;\n\n\n\nquickcheck! {\n\n fn mst...
Rust
src/header/ethernet.rs
ajguerrer/tygress
6c05e4a27dfe825a6cc3b89ec4f80905c8ef51a2
use core::fmt; use super::as_header; use crate::error::{Error, Result}; #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone)] #[repr(C)] pub struct EthernetII { dst: EtherAddr, src: EtherAddr, ty: EtherTypeRepr, } impl EthernetII { #[inline] pub fn split_header(bytes: &[u8]) -...
use core::fmt; use super::as_header; use crate::error::{Error, Result}; #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone)] #[repr(C)] pub struct EthernetII { dst: EtherAddr, src: EtherAddr, ty: EtherTypeRepr, } impl EthernetII { #[inline] pub fn split_header(bytes: &[u8]) -...
} #[non_exhaustive] #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] #[repr(u16)] pub enum EtherType { Ipv4 = 0x0800, Arp = 0x0806, Ipv6 = 0x86DD, } impl From<EtherType> for u16 { #[inline] fn from(val: EtherType) -> Self { val as u16 } } impl TryFrom<u16> for Ethe...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let bytes = self.0; write!( f, "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5] ) }
function_block-full_function
[ { "content": "#[inline]\n\npub fn verify_checksum(bytes: &[u8]) -> Result<()> {\n\n let sum: u32 = bytes\n\n .chunks_exact(2)\n\n // chunks_exact(2) always maps to arrays of 2 bytes as a slice so the conversion should\n\n // never fail.\n\n .map(|bytes| u32::from(u16::from_be_byte...
Rust
crates/holochain/src/core/workflow/call_zome_workflow.rs
guillemcordoba/holochain
fa4acd2067176757327328446368b1e09bfa2a34
use super::app_validation_workflow; use super::app_validation_workflow::AppValidationError; use super::app_validation_workflow::Outcome; use super::error::WorkflowResult; use super::sys_validation_workflow::sys_validate_element; use crate::conductor::api::CellConductorApi; use crate::conductor::api::CellConductorApiT; ...
use super::app_validation_workflow; use super::app_validation_workflow::AppValidationError; use super::app_validation_workflow::Outcome; use super::error::WorkflowResult; use super::sys_validation_workflow::sys_validate_element; use crate::conductor::api::CellConductorApi; use crate::conductor::api::CellConductorApiT; ...
} } validation_result?; Ok(result) } pub async fn call_zome_function_authorized<R>( ribosome: R, host_access: ZomeCallHostAccess, invocation: ZomeCallInvocation, ) -> WorkflowResult<(R, RibosomeResult<ZomeCallResponse>)> where R: RibosomeT + 'static, { if invocation.is_authoriz...
if !lock.is_empty() && workspace .source_chain() .is_chain_locked(Vec::with_capacity(0)) .await? && !workspace.source_chain().is_chain_locked(lock).await? { if let Err(error) = workspace.source_chain(...
if_condition
[ { "content": "/// Helper function for the common case of returning this boxed future type.\n\npub fn ok_fut<E1, R: Send + 'static>(result: R) -> Result<MustBoxFuture<'static, R>, E1> {\n\n use futures::FutureExt;\n\n Ok(async move { result }.boxed().into())\n\n}\n\n\n", "file_path": "crates/kitsune_p2...
Rust
src/watchpoints.rs
mewbak/haybale
d22f0eb7ae09bbbca75da6b409dfb8036ecc3fe2
use crate::backend::{Backend, BV}; use crate::error::Result; use crate::state::State; use log::info; use std::collections::HashMap; use std::fmt; #[derive(Eq, PartialEq, Clone, Debug, Hash)] pub struct Watchpoint { low: u64, high: u64, } impl Watchpoint { pub fn new(addr: u64, bytes:...
use crate::backend::{Backend, BV}; use crate::error::Result; use crate::state::State; use log::info; use std::collections::HashMap; use std::fmt; #[derive(Eq, PartialEq, Clone, Debug, Hash)] pub struct Watchpoint { low: u64, high: u64, } impl Watchpoint { pub fn new(addr: u64, bytes:...
pub(crate) fn is_watchpoint_triggered<B: Backend>( &self, state: &State<B>, watchpoint: &Watchpoint, interval_lower: &B::BV, interval_upper: &B::BV, ) -> Result<bool> { let width = interval_lower.get_width(); assert_eq!(width, interval_upper.get_wid...
bits: u32, is_write: bool, ) -> Result<bool> { let mut retval = false; if !self.0.is_empty() { let addr_width = addr.get_width(); let op_lower = addr; let bytes = if bits < 8 { 1 } else { bits / 8 }; let op_upper = addr.add(&state.bv_from_u32(b...
function_block-function_prefix_line
[ { "content": "/// Reallocate the given `addr` to be at least the number of bytes given by the `Operand`.\n\n///\n\n/// Returns the address of the allocation, which may or may not be the same\n\n/// address which was passed in.\n\npub fn realloc<B: Backend>(state: &mut State<B>, addr: &Operand, num_bytes: &Opera...
Rust
src/kv_manager/kv.rs
axelarnetwork/tofnd
ec8b9a00a652ae47da6b2102284f8dd979dbbae5
use crate::encrypted_sled::{self, Password}; use super::{ error::{KvError::*, KvResult}, sled_bindings::{handle_delete, handle_exists, handle_get, handle_put, handle_reserve}, types::{ Command::{self, *}, KeyReservation, DEFAULT_KV_NAME, DEFAULT_KV_PATH, }, }; use serde::{de::Deserial...
use crate::encrypted_sled::{self, Password}; use super::{ error::{KvError::*, KvResult}, sled_bindings::{handle_delete, handle_exists, handle_get, handle_put, handle_reserve}, types::{ Command::{self, *}, KeyReservation, DEFAULT_KV_NAME, DEFAULT_KV_PATH, }, }; use serde::{de::Deserial...
pub async fn exists(&self, key: &str) -> KvResult<bool> { let (resp_tx, resp_rx) = oneshot::channel(); self.sender .send(Exists { key: key.to_string(), resp: resp_tx, }) .map_err(|e| SendErr(e.to_string()))?; res...
pub async fn delete(&self, key: &str) -> KvResult<()> { let (resp_tx, resp_rx) = oneshot::channel(); self.sender .send(Delete { key: key.to_string(), resp: resp_tx, }) .map_err(|e| SendErr(e.to_string()))?; resp_rx.await?.map_er...
function_block-full_function
[ { "content": "// Provided by the requester and used by the manager task to send the command response back to the requester.\n\ntype Responder<T> = tokio::sync::oneshot::Sender<super::error::InnerKvResult<T>>;\n\n\n\n#[derive(Debug)]\n\npub(super) enum Command<V> {\n\n ReserveKey {\n\n key: String,\n\n...
Rust
src/desktop/request.rs
jtojnar/ashpd
7cd1792916b9e169cd015f975f4f453fe5c2207c
use std::{ collections::HashMap, convert::TryFrom, fmt::{self, Debug}, marker::PhantomData, }; use serde::{ de::{self, Error as SeError, Visitor}, Deserialize, Deserializer, Serialize, }; use serde_repr::{Deserialize_repr, Serialize_repr}; use zvariant::OwnedValue; use zvariant_derive::Type; u...
use std::{ collections::HashMap, convert::TryFrom, fmt::{self, Debug}, marker::PhantomData, }; use serde::{ de::{self, Error as SeError, Visitor}, Deserialize, Deserializer, Serialize, }; use serde_repr::{Deserialize_repr, Serialize_repr}; use zvariant::OwnedValue; use zvariant_derive::Type; u...
Ok(Self(proxy)) } pub async fn from_unique_name( connection: &zbus::Connection, handle_token: &HandleToken, ) -> Result<RequestProxy<'a>, Error> { let unique_name = connection.unique_name().unwrap(); let unique_identifier = unique_name.trim_start_matches(':').replac...
let proxy = zbus::ProxyBuilder::new_bare(connection) .interface("org.freedesktop.portal.Request")? .path(path)? .destination(DESTINATION)? .build() .await?;
assignment_statement
[ { "content": "#[cfg(feature = \"feature_pipewire\")]\n\nfn pipewire_node_id_inner<F: FnOnce(u32) + Clone + 'static>(\n\n fd: RawFd,\n\n callback: F,\n\n) -> Result<(), pw::Error> {\n\n use pw::prelude::*;\n\n let mainloop = pw::MainLoop::new()?;\n\n let context = pw::Context::new(&mainloop)?;\n\n...
Rust
language/move-prover/src/prover_task_runner.rs
CVeniamin/diem
6fad0d397f683bdc9a80e4c6dbe74f5370ac45b4
use crate::cli::Options; use async_trait::async_trait; use futures::{future::FutureExt, pin_mut, select}; use log::debug; use rand::Rng; use regex::Regex; use std::{ process::Output, sync::{ mpsc::{channel, Sender}, Arc, }, }; use tokio::{ process::Command, sync::{broadcast, broadc...
use crate::cli::Options; use async_trait::async_trait; use futures::{future::FutureExt, pin_mut, select}; use log::debug; use rand::Rng; use regex::Regex; use std::{ process::Output, sync::{ mpsc::{channel, Sender}, Arc, }, }; use tokio::{ process::Command, sync::{broadcast, broadc...
}
x::new(r"(?m)^.*\((?P<line>\d+),(?P<col>\d+)\).*Verification.*(inconclusive|out of resource|timed out).*$") .unwrap(); regex.is_match(output) }
function_block-function_prefixed
[ { "content": "pub trait RetryStrategy: std::fmt::Debug + Send + Sync {\n\n fn max_retries(&self, err: &Error) -> u32;\n\n fn delay(&self, err: &Error, retries: u32) -> Duration;\n\n fn is_retriable(&self, err: &Error) -> bool;\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Retry {\n\n pub max_retries: u...
Rust
cube3x3x3/src/main.rs
lePerdu/twisted
6f3330fbb594beb9f06d8bfeb307cb60ca8035b9
extern crate pretty_env_logger; extern crate twisted; use std::io::{self, Write}; use twisted::coord::Coord; use twisted::cube::cube3::{ coord::{ CornerOrientCoord, CornerPosCoord, EEdgePosCoord, ESliceAndEOCoord, ESliceEdgePosCoord, EdgeOrientCoord, Phase1Coord, Phase2Coord, Phase2MinusECoord, U...
extern crate pretty_env_logger; extern crate twisted; use std::io::{self, Write}; use twisted::coord::Coord; use twisted::cube::cube3::{ coord::{ CornerOrientCoord, CornerPosCoord, EEdgePosCoord, ESliceAndEOCoord, ESliceEdgePosCoord, EdgeOrientCoord, Phase1Coord, Phase2Coord, Phase2MinusECoord, U...
Ok(notation) => do_solve( &phase1_move_table, &phase1_prune_table, &phase2_move_table, &phase2_prune_table, notation, ), Err(_) => { ...
rd != Phase1Coord::default() { println!("Error, invalid solution (Coord = {:?})", solved_coord); } (sol, solved) } None => { println!("No phase 1 solution found"); return; } }; let (phase2_solution, solved_perm) = match do...
random
[ { "content": "pub fn apply_coord<C, T, P>(coord: C, items_in_order: impl Iterator<Item = T>, items: &mut [P])\n\nwhere\n\n C: PrimInt,\n\n T: Copy + Eq,\n\n P: Copy,\n\n{\n\n let mut coord = coord;\n\n\n\n for (index, _) in items_in_order.enumerate().skip(1) {\n\n let base = C::from(index)...
Rust
src/tui/vterm/vterm.rs
CodeSteak/hs_app
4ec5359ed393fe4a9cbe84254426da9c25b04828
use super::*; use unicode_segmentation::UnicodeSegmentation; pub struct VTerm { width: isize, lines: Vec<Vec<VChar>>, pub tab_size: isize, pub tab_char: VChar, } impl Widget for VTerm { fn size(&mut self) -> (isize, isize) { let w = self.width; let h = self.lines.len(); ...
use super::*; use unicode_segmentation::UnicodeSegmentation; pub struct VTerm { width: isize, lines: Vec<Vec<VChar>>, pub tab_size: isize, pub tab_char: VChar, } impl Widget for VTerm { fn size(&mut self) -> (isize, isize) { let w = self.width; let h = self.lines.len(); ...
for _ in 0..indent { let tc = self.tab_char; self.write_char_color(tc.char, tc.foreground); } return; } '\x00'..='\x19' => { return; } _ => (), }; i...
if cursor_pos + indent >= self.width { self.write_char_color('\n', color); indent = self.tab_size; }
if_condition
[ { "content": "pub trait WithBackground<W: Widget> {\n\n fn with_background(self, c : Color) -> Background<W>;\n\n}\n\n\n\nimpl<W : Widget+Sized> WithBackground<W> for W {\n\n fn with_background(self, c : Color) -> Background<W> {\n\n Background(c, self)\n\n }\n\n}", "file_path": "src/tui/vte...
Rust
storage/src/context.rs
fafk/tezedge
a42d44b30f938a976731367c857a58633386a668
use failure::Fail; use crypto::hash::{BlockHash, ContextHash, HashType}; use crate::{BlockStorage, BlockStorageReader, StorageError}; use crate::persistent::{ContextList, ContextMap}; use crate::skip_list::{Bucket, SkipListError}; #[derive(Debug, Fail)] pub enum ContextError { #[fail(display = "Failed to save ...
use failure::Fail; use crypto::hash::{BlockHash, ContextHash, HashType}; use crate::{BlockStorage, BlockStorageReader, StorageError}; use crate::persistent::{ContextList, ContextMap}; use crate::skip_list::{Bucket, SkipListError}; #[derive(Debug, Fail)] pub enum ContextError { #[fail(display = "Failed to save ...
fn delete_to_diff(&self, context_hash: &Option<ContextHash>, key_prefix_to_delete: &Vec<String>, context_diff: &mut ContextDiff) -> Result<(), ContextError> { ensure_eq_context_hash!(context_hash, &context_diff); self.remove_recursively_to_diff(context_hash, key_prefix_to_delete, context_diff) ...
ext_diff); let mut writer = self.storage.write().expect("lock poisoning"); writer.push(&context_diff.diff)?; self.block_storage .assign_to_context(block_hash, new_context_hash) .map_err(|e| ContextError::ContextHashAssignError { ...
function_block-function_prefixed
[ { "content": "#[test]\n\npub fn list_get_values_by_prefix() -> Result<(), failure::Error> {\n\n let tmp_storage = TmpStorage::create(\"__skip_list:list_get_values_by_prefix\").expect(\"Storage error\");\n\n let mut list: Box<dyn TypedSkipList<String, i32>> = Box::new(DatabaseBackedSkipList::new(9, tmp_sto...
Rust
src/oid.rs
Clockwork757/github-types
914a78eba90b2035d071723804d149c379b7bf0f
use std::fmt; use std::ops; use hex::{FromHex, FromHexError, ToHex}; use serde::de::{self, Deserialize, Deserializer, Visitor}; use serde::ser::{self, Serialize, Serializer}; #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Default)] pub struct Oid([u8; 20]); impl Oid { pub fn from_hex(s: &str) -> R...
use std::fmt; use std::ops; use hex::{FromHex, FromHexError, ToHex}; use serde::de::{self, Deserialize, Deserializer, Visitor}; use serde::ser::{self, Serialize, Serializer}; #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Default)] pub struct Oid([u8; 20]); impl Oid { pub fn from_hex(s: &str) -> R...
}
FromHexError::InvalidHexCharacter { c, .. } => { E::invalid_value( de::Unexpected::Char(c), &"string with only hexadecimal characters", ) } FromHexError::InvalidStringLength =>...
function_block-function_prefixed
[ { "content": "pub trait AppEvent {\n\n /// Returns the installation ID for the event.\n\n fn installation(&self) -> Option<u64> {\n\n None\n\n }\n\n}\n\n\n\n#[derive(\n\n Deserialize, Serialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash,\n\n)]\n\n#[serde(rename_all = \"snake_ca...
Rust
vrp-pragmatic/src/checker/assignment.rs
dooley/vrp
0007543128fcf6d261c1e08be4a006aaa90a331f
#[cfg(test)] #[path = "../../tests/unit/checker/assignment_test.rs"] mod assignment_test; use super::*; use crate::format::solution::activity_matcher::try_match_job; use crate::format::{get_coord_index, get_job_index}; use std::collections::HashSet; pub fn check_assignment(ctx: &CheckerContext) -> Result<(), String> ...
#[cfg(test)] #[path = "../../tests/unit/checker/assignment_test.rs"] mod assignment_test; use super::*; use crate::format::solution::activity_matcher::try_match_job; use crate::format::{get_coord_index, get_job_index}; use std::collections::HashSet; pub fn check_assignment(ctx: &CheckerContext) -> Result<(), String> ...
fn check_jobs_match(ctx: &CheckerContext) -> Result<(), String> { let job_ids = ctx .solution .tours .iter() .flat_map(move |tour| { tour.stops.iter().flat_map(move |stop| { stop.activities .iter() .filter(move |ac...
fn check_jobs_presence(ctx: &CheckerContext) -> Result<(), String> { struct JobAssignment { pub tour_info: (String, usize), pub pickups: Vec<usize>, pub deliveries: Vec<usize>, pub replacements: Vec<usize>, pub services: Vec<usize>, } let new_assignment = |tour_info: ...
function_block-full_function
[ { "content": "/// Checks that vehicle load is assigned correctly. The following rules are checked:\n\n/// * max vehicle's capacity is not violated\n\n/// * load change is correct\n\npub fn check_vehicle_load(context: &CheckerContext) -> Result<(), String> {\n\n context.solution.tours.iter().try_for_each(|tou...
Rust
src/handlers/users/mod.rs
jsvana/uwiki
d00c93d75b8803814e104cf20ad98976f272c0f1
use std::convert::TryInto; use std::iter; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{anyhow, Result}; use bcrypt::{hash, verify, DEFAULT_COST}; use handlebars::Handlebars; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use serde_json::json; use sqlx::{Pool, Postgres}; use warp::http::{S...
use std::convert::TryInto; use std::iter; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{anyhow, Result}; use bcrypt::{hash, verify, DEFAULT_COST}; use handlebars::Handlebars; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use serde_json::json; use sqlx::{Pool, Postgres}; use warp::http::{S...
pub async fn approve( user_id: i32, db: Pool<Postgres>, templates: Handlebars<'_>, session_with_store: SessionWithStore<MemoryStore>, ) -> Result<HandlerReturn, warp::Rejection> { set_user_state( user_id, UserState::Active, db, templates, session_with_store,...
db: Pool<Postgres>, templates: Handlebars<'_>, session_with_store: SessionWithStore<MemoryStore>, ) -> Result<HandlerReturn, warp::Rejection> { let mut tx = value_or_error_html!( db.begin().await, "Error communicating with database", StatusCode::INTERNAL_SERVER_ERROR, &templa...
function_block-function_prefix_line
[ { "content": "pub fn error_html(\n\n message: &str,\n\n status_code: StatusCode,\n\n templates: &Handlebars,\n\n session_with_store: SessionWithStore<MemoryStore>,\n\n) -> HandlerReturn {\n\n let (flash, session_with_store) = get_and_clear_flash(session_with_store);\n\n\n\n let text = match te...
Rust
core/lib/storage/src/chain/mempool/mod.rs
huitseeker/zksync
5b936b1855a08033cca7f75d6f87fde106c6e8fd
use std::{collections::VecDeque, convert::TryFrom, time::Instant}; use itertools::Itertools; use zksync_types::{ mempool::SignedTxVariant, tx::{TxEthSignature, TxHash}, SignedZkSyncTx, }; use self::records::MempoolTx; use crate::{QueryResult, StorageProcessor}; pub mod records; #[derive(Debug)] pub st...
use std::{collections::VecDeque, convert::TryFrom, time::Instant}; use itertools::Itertools; use zksync_types::{ mempool::SignedTxVariant, tx::{TxEthSignature, TxHash}, SignedZkSyncTx, }; use self::records::MempoolTx; use crate::{QueryResult, StorageProcessor}; pub mod records; #[derive(Debug)] pub st...
let row = sqlx::query!( "SELECT count(*) from mempool_txs WHERE tx_hash = $1", &tx_hash ) .fetch_one(self.0.conn()) .await? .count; let contains = row.filter(|&counter| counter > 0).is_some(); metrics::histogram!("sql.chain", star...
Processor<'c>); impl<'a, 'c> MempoolSchema<'a, 'c> { pub async fn load_txs(&mut self) -> QueryResult<VecDeque<SignedTxVariant>> { let start = Instant::now(); let txs: Vec<MempoolTx> = sqlx::query_as!( MempoolTx, "SELECT * FROM mempool_txs ORDER BY c...
random
[ { "content": "pub fn bench_signatures(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Signature verify\");\n\n group.throughput(Throughput::Elements(1));\n\n group.bench_function(\n\n \"bench_signature_verify_zksync_musig\",\n\n bench_signature_zksync_musig_verify,\n\n );\...
Rust
datafusion/src/physical_plan/expressions/average.rs
andts/arrow-datafusion
1c39f5ce865e3e1225b4895196073be560a93e82
use std::any::Any; use std::convert::TryFrom; use std::sync::Arc; use crate::error::{DataFusionError, Result}; use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr}; use crate::scalar::{ ScalarValue, MAX_PRECISION_FOR_DECIMAL128, MAX_SCALE_FOR_DECIMAL128, }; use arrow::compute; use arrow::datatype...
use std::any::Any; use std::convert::TryFrom; use std::sync::Arc; use crate::error::{DataFusionError, Result}; use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr}; use crate::scalar::{ ScalarValue, MAX_PRECISION_FOR_DECIMAL128, MAX_SCALE_FOR_DECIMAL128, }; use arrow::compute; use arrow::datatype...
-> Result<()> { let a: ArrayRef = Arc::new(Int32Array::from(vec![None, None])); generic_test_op!( a, DataType::Int32, Avg, ScalarValue::Float64(None), DataType::Float64 ) } #[test] fn avg_u32() -> Result<()> { let a...
&self) -> Result<Vec<ScalarValue>> { Ok(vec![ScalarValue::from(self.count), self.sum.clone()]) } fn update(&mut self, _values: &[ScalarValue]) -> Result<()> { unimplemented!("update_batch is implemented instead"); } fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> { ...
random
[]
Rust
src/libfourcc/lib.rs
pfalabella/rust
3deb2c1aa6bb255ebe62b294be5e3c580e19bb9b
/*! Syntax extension to generate FourCCs. Once loaded, fourcc!() is called with a single 4-character string, and an optional ident that is either `big`, `little`, or `target`. The ident represents endianness, and specifies in which direction the characters should be read. If the ident is omitted, it is assumed to be...
/*! Syntax extension to generate FourCCs. Once loaded, fourcc!() is called with a single 4-character string, and an optional ident that is either `big`, `little`, or `target`. The ident represents endianness, and specifies in which direction the characters should be read. If the ident is omitted, it is assumed to be...
}; let s = match expr.node { ast::ExprLit(ref lit) => match lit.node { ast::LitStr(ref s, _) => { if s.get().char_len() != 4 { cx.span_err(expr.span, "string literal with len != 4 in fourcc!"); } s ...
match token::get_ident(ident).get() { "little" => true, "big" => false, "target" => target_endian_little(cx, sp), _ => { cx.span_err(span, "invalid endian directive in fourcc!"); target_endian_little(cx, sp) } }
if_condition
[ { "content": "pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])\n\n -> Box<base::MacResult> {\n\n let mut res_str = String::new();\n\n for (i, e) in tts.iter().enumerate() {\n\n if i & 1 == 1 {\n\n match *e {\n\n ast::TTTo...
Rust
src/svg.rs
sleibrock/wad2map
1f1095e1ebadae26ded818e7fa7dbe57ac9a9b33
use std::fs::File; use std::io::Write; use std::error::Error; pub enum Color { Red, Blue, Green, Yellow, Black, White, Grey, None } pub fn color_to_string(c: &Color) -> String { match *c { Color::Red => "red".to_owned(), Color::None => "none".to_owned(), Color::Blue => "blue"....
use std::fs::File; use std::io::Write; use std::error::Error; pub enum Color { Red, Blue, Green, Yellow, Black, White, Grey, None } pub fn color_to_string(c: &Color) -> String { match *c { Color::Red => "red".to_owned(), Color::None => "none".to_owned(), Color::Blue => "blue"....
{ format!("{},{}", self.x, self.y) } } impl SVGPoly { pub fn new(c: Color, stroke: u64) -> SVGPoly { let v: Vec<SVGVertex> = Vec::new(); SVGPoly{color: c, stroke: stroke, vertices: v} } pub fn addv(&mut self, x: u64, y: u64) { self.vertices.push(SVGVertex::new(x, y)); ...
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{}\" />", self.x1, self.y1, self.x2, self.y2, color_to_string(&self.color), self.stroke, ) } } impl SVGRect { pub fn new(x: u64, y: u64, w: u64, h: u64, fill: Color) -> SVGRect { SVGRect{x: x,...
random
[ { "content": "// flip a value in a certain axis\n\n// if the axis is set to zero, just return the initial value\n\nfn flatten(v: u64, m: u64) -> u64 {\n\n match m == 0 {\n\n true => v,\n\n _ => m - v,\n\n }\n\n}\n\n\n\n\n", "file_path": "src/mapmaker.rs", "rank": 2, "score": 7...
Rust
src/libterm/lib.rs
Ryman/rust
11571cd9c1cde63c3b46ca65e608b84647785ac8
#![crate_id = "term#0.11-pre"] #![comment = "Simple ANSI color library"] #![license = "MIT/ASL2"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_ur...
#![crate_id = "term#0.11-pre"] #![comment = "Simple ANSI color library"] #![license = "MIT/ASL2"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_ur...
pub fn fg(&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(&("setaf"...
se)); 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) } else { 0 }; return Ok(Terminal {out: out, ti: inf, num_colors: nc}); }
function_block-function_prefixed
[ { "content": "enum Color { cyan, magenta, yellow, black }\n\n\n\nimpl Equal for Color {\n\n fn isEq(a: Color, b: Color) -> bool {\n\n match (a, b) {\n\n (cyan, cyan) => { true }\n\n (magenta, magenta) => { true }\n\n (yellow, yellow) => { true }\n\n (blac...
Rust
src/error.rs
ygf11/bincode
f33abb21b45ff20b63be2a5ab134fce0d6d86d59
#[non_exhaustive] #[derive(Debug)] pub enum EncodeError { UnexpectedEnd, RefCellAlreadyBorrowed { inner: core::cell::BorrowError, type_name: &'static str, }, Other(&'static str), #[cfg(feature = "alloc")] OtherString(alloc::string::Strin...
#[non_exhaustive] #[derive(Debug)] pub enum EncodeError { UnexpectedEnd, RefCellAlreadyBorrowed { inner: core::cell::BorrowError, type_name: &'static str, }, Other(&'static str), #[cfg(feature = "alloc")] OtherString(alloc::string::Strin...
=> Self::Isize, other => other, } } }
Self::I16, Self::U32 => Self::I32, Self::U64 => Self::I64, Self::U128 => Self::I128, Self::Usize
function_block-random_span
[ { "content": "/// Encode a `serde` `Serialize` type into a given byte slice with the bincode algorithm\n\npub fn encode_to_slice<T, C>(t: T, slice: &mut [u8], config: C) -> Result<usize, EncodeError>\n\nwhere\n\n T: Serialize,\n\n C: Config,\n\n{\n\n let mut encoder =\n\n crate::enc::EncoderImpl...
Rust
server/src/realtime/mod.rs
kalgynirae/sudoku
e32241a732a53fdfff08a7a5298e2281ecee5af6
pub mod protocol; pub mod tasks; use futures::prelude::*; use futures::stream::{SplitSink, SplitStream}; use log::{debug, error, warn}; use std::sync::Arc; use tokio::sync::Mutex; use warp::filters::BoxedFilter; use warp::reject::Reject; use warp::ws::{Message, WebSocket}; use warp::{Filter, Reply}; use crate::cursor...
pub mod protocol; pub mod tasks; use futures::prelude::*; use futures::stream::{SplitSink, SplitStream}; use log::{debug, error, warn}; use std::sync::Arc; use tokio::sync::Mutex; use warp::filters::BoxedFilter; use warp::reject::Reject; use warp::ws::{Message, WebSocket}; use warp::{Filter, Reply}; use crate
room_state: room_state.clone(), ws_tx: ws_tx.clone(), ws_rx: ws_rx.clone(), session_id, last_received_sync_id: last_received_sync_id.clone(), cursor_tx, } .run(); let diff_broadcast_receiver = DiffBroadcastReceiver { room_state: room_state.clone(), ...
::cursors::SessionCursor; use crate::global_state::GlobalState; use crate::realtime::protocol::{ serialize_response, write_to_socket, ResponseMessage, SocketWriteError, }; use crate::realtime::tasks::error::ApiTaskError; use crate::realtime::tasks::{CursorNotifyReceiver, DiffBroadcastReceiver, RequestReceiver}; use...
random
[ { "content": "pub fn serialize_response(msg: ResponseMessage) -> Result<Message, SocketWriteError> {\n\n let text = serde_json::to_string(&msg)?;\n\n Ok(Message::text(text))\n\n}\n\n\n\npub async fn write_to_socket(\n\n ws_tx: &Mutex<SplitSink<WebSocket, Message>>,\n\n msg: Message,\n\n) -> Result<(...
Rust
src/auto/exception.rs
gtk-rs/javascriptcore-rs
313a15205b5b3d1daa6983faa3948a6d02af42cb
use crate::Context; use glib::{object::IsA, translate::*}; use std::fmt; glib::wrapper! { #[doc(alias = "JSCException")] pub struct Exception(Object<ffi::JSCException, ffi::JSCExceptionClass>); match fn { type_ => || ffi::jsc_exception_get_type(), } } impl Exception { #[doc(alias = "jsc_e...
use crate::Context; use glib::{object::IsA, translate::*}; use std::fmt; glib::wrapper! { #[doc(alias = "JSCException")] pub struct Exception(Object<ffi::JSCException, ffi::JSCExceptionClass>); match fn { type_ => || ffi::jsc_exception_get_type(), } } impl Exception { #[doc(alias = "jsc_e...
} } } impl fmt::Display for Exception { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&ExceptionExt::to_str(self)) } } pub const NONE_EXCEPTION: Option<&Exception> = None; pub trait ExceptionExt: 'static { #[doc(alias = "jsc_exception_...
from_glib_full(ffi::jsc_exception_new_with_name( context.as_ref().to_glib_none().0, name.to_glib_none().0, message.to_glib_none().0, ))
call_expression
[ { "content": "fn get_var(name: &str, default: &str) -> Result<Vec<String>, Box<dyn Error>> {\n\n match env::var(name) {\n\n Ok(value) => Ok(shell_words::split(&value)?),\n\n Err(env::VarError::NotPresent) => Ok(shell_words::split(default)?),\n\n Err(err) => Err(format!(\"{} {}\", name, err).into()),\n...
Rust
algebra-core/src/serialize/mod.rs
AleoHQ/zexe
d190054f587791da790d372be62867809e251f12
mod error; mod flags; pub use crate::io::{Read, Write}; pub use error::*; pub use flags::*; #[cfg(feature = "derive")] #[doc(hidden)] pub use algebra_core_derive::*; use crate::Vec; pub trait CanonicalSerializeWithFlags: CanonicalSerialize { fn serialize_with_flags<W: Write, F: Flags>( &self, ...
mod error; mod flags; pub use crate::io::{Read, Write}; pub use error::*; pub use flags::*; #[cfg(feature = "derive")] #[doc(hidden)] pub use algebra_core_derive::*; use crate::Vec; pub trait CanonicalSerializeWithFlags: CanonicalSerialize { fn serialize_with_flags<W: Write, F: Flags>( &self, ...
; Ok(Self::read(&masked_bytes[..])?) } } }; } macro_rules! impl_sw_curve_serializer { ($params: ident) => { impl<P: $params> CanonicalSerialize for GroupAffine<P> { #[allow(unused_qualifications)] #[inline] fn serialize<W: crate::...
n_bits()); if F::len() > (output_bit_size - P::MODULUS_BITS as usize) { return Err(crate::serialize::SerializationError::NotEnoughSpace); } let mut masked_bytes = [0; BYTE_SIZE]; reader.read_exact(&mut masked_bytes[..output_byte_size])...
random
[ { "content": "pub fn batch_inversion<F: Field>(v: &mut [F]) {\n\n // Montgomery’s Trick and Fast Implementation of Masked AES\n\n // Genelle, Prouff and Quisquater\n\n // Section 3.2\n\n\n\n // First pass: compute [a, ab, abc, ...]\n\n let mut prod = Vec::with_capacity(v.len());\n\n let mut tm...
Rust
arci-ros/src/ros_robot_client.rs
mertcookimg/openrr
4bdb49d483383e912b37907c6f651b52f2b7a742
use std::sync::Arc; use arci::*; use parking_lot::Mutex; use crate::msg; #[derive(Clone)] pub struct RosRobotClient(Arc<RosRobotClientInner>); struct RosRobotClientInner { joint_names: Vec<String>, trajectory_publisher: Option<rosrust::Publisher<msg::trajectory_msgs::JointTrajectory>>, _joint_state_subs...
use std::sync::Arc; use arci::*; use parking_lot::Mutex; use crate::msg; #[derive(Clone)] pub struct RosRobotClient(Arc<RosRobotClientInner>); struct RosRobotClientInner { joint_names: Vec<String>, trajectory_publisher: Option<rosrust::Publisher<msg::trajectory_msgs::JointTrajectory>>, _joint_state_subs...
complete_condition.lock().clone(); complete_condition .wait( &this, &trajectory.last().unwrap().positions, trajectory.last().unwrap().time_from_start.as_secs_f64(), ) .awai...
})) } } impl JointTrajectoryClient for RosRobotClient { fn joint_names(&self) -> Vec<String> { self.0.joint_names.clone() } fn current_joint_positions(&self) -> Result<Vec<f64>, Error> { let message = self.0.joint_state_message.lock(); Ok(message.position.clone()) } ...
random
[ { "content": "/// # To copy joint name and position between `from` and `to`\n\n///\n\n/// Copy position of same joint name.\n\n/// This function returns Ok() or Err().\n\n///\n\n/// # When this function through Error?\n\n///\n\n/// length of joint names and positions is difference.\n\n///\n\n/// # Sample code\n...
Rust
plonky2/src/gates/exponentiation.rs
mfaulk/plonky2
2cedd1b02a718d19115560647ba1f741eab83260
use std::marker::PhantomData; use plonky2_field::extension_field::Extendable; use plonky2_field::field_types::Field; use plonky2_field::ops::Square; use plonky2_field::packed_field::PackedField; use crate::gates::gate::Gate; use crate::gates::packed_util::PackedEvaluableBase; use crate::gates::util::StridedConstraint...
use std::marker::PhantomData; use plonky2_field::extension_field::Extendable; use plonky2_field::field_types::Field; use plonky2_field::ops::Square; use plonky2_field::packed_field::PackedField; use crate::gates::gate::Gate; use crate::gates::packed_util::PackedEvaluableBase; use crate::gates::util::StridedConstraint...
let output_value = intermediate_values[num_power_bits - 1]; v.push(output_value); v.extend(intermediate_values); v.iter().map(|&x| x.into()).collect::<Vec<_>>() } let mut rng = rand::thread_rng(); let base = F::TWO; let power = rng.gen::<usize>(...
rent_intermediate_value = F::ONE; for i in 0..num_power_bits { if power_bits[num_power_bits - i - 1] == 1 { current_intermediate_value *= base; } intermediate_values.push(current_intermediate_value); current_intermediate_val...
function_block-random_span
[ { "content": "/// Tests that the constraints imposed by the given gate are low-degree by applying them to random\n\n/// low-degree witness polynomials.\n\npub fn test_low_degree<F: RichField + Extendable<D>, G: Gate<F, D>, const D: usize>(gate: G) {\n\n let rate_bits = log2_ceil(gate.degree() + 1);\n\n\n\n ...
Rust
src/parser.rs
Popog/dtml-rs
43224bba007b951d348061fa05856092e68b66dc
use std::error; use std::iter::{Iterator, once}; use token::{ContentType, Token, NonText, TokenWithComments, TextAccumulator, is_whitespace}; use tokenizer; use tuple::{LazyTuple, parent_element, LazyTupleContainer}; type TokenWithCommentsResult<S, E> = Result<TokenWithComments<S>, tokenizer::Error<E>>; type TokenResu...
use std::error; use std::iter::{Iterator, once}; use token::{ContentType, Token, NonText, TokenWithComments, TextAccumulator, is_whitespace}; use tokenizer; use tuple::{LazyTuple, parent_element, LazyTupleContainer}; type TokenWithCommentsResult<S, E> = Result<TokenWithComments<S>, tokenizer::Error<E>>; type TokenResu...
=> return Err(Error::UnexpectedToken(Token::Null)), (_, Some(NonText::Null)) => { let t = try!(map_error(i.skip_while(is_whitespace).next())); if let Some(t) = t { Err(Error::UnexpectedToken(t)) } else { Ok(LazyTuple::Null) } }, } } fn parse_helper<...
me(t) = t { Err(Error::UnexpectedToken(t)) } else { Ok(tuple) } }, } }, (_, Some(NonText::Close)) => return Err(Error::UnexpectedToken(Token::Close)), (_, Some(NonText::Divider)) => return Err(Error::UnexpectedToken(Token::Divider)), (Co...
function_block-random_span
[ { "content": "fn map_error<C, E: error::Error>(r: Option<Result<C, E>>) -> Result<C, Error<E>> {\n\n match r {\n\n None => return Err(Error::UnexpectedEOF),\n\n Some(Err(e)) => return Err(From::from(e)),\n\n Some(Ok(t)) => Ok(t),\n\n }\n\n}\n\n\n\n/*\n\n .o88b. db db .d8b. d8888b....
Rust
geom/src/segment.rs
HalfVoxel/lyon
5e42176d5a7ad78a23c735c2946caed15955ac82
use crate::generic_math::{Point, Rect, Vector}; use crate::scalar::{One, Scalar}; use crate::{CubicBezierSegment, LineSegment, QuadraticBezierSegment}; use std::ops::Range; pub trait Segment: Copy + Sized { type Scalar: Scalar; fn from(&self) -> Point<Self::Scalar>; fn to(&self) -> Point<Self:...
use crate::generic_math::{Point, Rect, Vector}; use crate::scalar::{One, Scalar}; use crate::{CubicBezierSegment, LineSegment, QuadraticBezierSegment}; use std::ops::Range; pub trait Segment: Copy + Sized { type Scalar: Scalar; fn from(&self) -> Point<Self::Scalar>; fn to(&self) -> Point<Self:...
} impl<S> From<LineSegment<S>> for BezierSegment<S> { fn from(s: LineSegment<S>) -> Self { BezierSegment::Linear(s) } } impl<S> From<QuadraticBezierSegment<S>> for BezierSegment<S> { fn from(s: QuadraticBezierSegment<S>) -> Self { BezierSegment::Quadratic(s) } } impl<S> From<CubicBez...
t::Quadratic(segment) => { let (a, b) = segment.split(t); (BezierSegment::Quadratic(a), BezierSegment::Quadratic(b)) } BezierSegment::Cubic(segment) => { let (a, b) = segment.split(t); (BezierSegment::Cubic(a), BezierSegment::Cubic(...
function_block-function_prefixed
[ { "content": "pub fn flatten_cubic_bezier_with_t<S: Scalar, F>(curve: &CubicBezierSegment<S>, tolerance: S, callback: &mut F)\n\nwhere\n\n F: FnMut(Point<S>, S),\n\n{\n\n debug_assert!(tolerance >= S::EPSILON);\n\n let quadratics_tolerance = tolerance * S::value(0.2);\n\n let flattening_tolerance = ...
Rust
src/mouse.rs
gifnksm/sabios
a0729dbdaafbbc318c6bc13636a3a17a842c782b
use crate::{ graphics::{Color, Draw, Offset, Point, ScreenInfo}, layer, prelude::*, sync::{mpsc, OnceCell}, window::Window, }; use core::future::Future; use enumflags2::{bitflags, BitFlags}; const TRANSPARENT_COLOR: Color = Color::RED; const MOUSE_CURSOR_WIDTH: usize = 15; const MOUSE_CURSOR_HEIGHT...
use crate::{ graphics::{Color, Draw, Offset, Point, ScreenInfo}, layer, prelude::*, sync::{mpsc, OnceCell}, window::Window, }; use core::future::Future; use enumflags2::{bitflags, BitFlags}; const TRANSPARENT_COLOR: Color = Color::RED; const MOUSE_CURSOR_WIDTH: usize
_pos).await?; } tx.mouse_event( cursor_layer_id, MouseEvent { down, up, pos: cursor_pos, pos_diff, }, ) .await?; } Ok(()) }...
= 15; const MOUSE_CURSOR_HEIGHT: usize = 24; const MOUSE_CURSOR_SIZE: Point<i32> = Point::new(MOUSE_CURSOR_WIDTH as i32, MOUSE_CURSOR_HEIGHT as i32); const MOUSE_CURSOR_SHAPE: [[u8; MOUSE_CURSOR_WIDTH]; MOUSE_CURSOR_HEIGHT] = [ *b"@ ", *b"@@ ", *b"@.@ ", *b"@..@ ...
random
[ { "content": "fn draw(drawer: &mut dyn Draw, size: Size<i32>) {\n\n drawer.fill_rect(\n\n Rectangle::new(Point::new(0, 0), Size::new(size.x, size.y - 50)),\n\n BG_COLOR,\n\n );\n\n drawer.fill_rect(\n\n Rectangle::new(Point::new(0, size.y - 50), Size::new(size.x, 50)),\n\n C...
Rust
piet-gpu/bin/winit.rs
linebender/piet-gpu
086e547aef2edbdb595f73b10770a0b5f0853058
use piet::kurbo::Point; use piet::{RenderContext, Text, TextAttribute, TextLayoutBuilder}; use piet_gpu_hal::{Error, ImageLayout, Instance, Session, SubmittedCmdBuf}; use piet_gpu::{test_scenes, PietGpuRenderContext, Renderer}; use clap::{App, Arg}; use winit::{ event::{Event, WindowEvent}, event_loop::{Cont...
use piet::kurbo::Point; use piet::{RenderContext, Text, TextAttribute, TextLayoutBuilder}; use piet_gpu_hal::{Error, ImageLayout, Instance, Session, SubmittedCmdBuf}; use piet_gpu::{test_scenes, PietGpuRenderContext, Renderer}; use clap::{App, Arg}; use winit::{ event::{Event, WindowEvent}, event_loop::{Cont...
+= 1; } Event::LoopDestroyed => { for cmd_buf in &mut submitted { if let Some(cmd_buf) = cmd_buf.take() { cmd_buf.wait().unwrap(); } ...
&swap_image, ImageLayout::Undefined, ImageLayout::BlitDst, ); cmd_buf.blit_image(&renderer.image_dev, &swap_image); cmd_buf.image_barrier(&swap_image, ImageLayout::BlitDst, ImageLayout::Present...
random
[ { "content": "pub fn render_svg(rc: &mut impl RenderContext, filename: &str, scale: f64) {\n\n let xml_str = std::fs::read_to_string(filename).unwrap();\n\n let start = std::time::Instant::now();\n\n let svg = PicoSvg::load(&xml_str, scale).unwrap();\n\n println!(\"parsing time: {:?}\", start.elapse...
Rust
shell/tests/common/test_data.rs
tizoc/tezedge
f44cbd00ab73e443593cb8c089cae2732acbfa81
use std::collections::HashMap; use std::convert::TryInto; use anyhow::format_err; use crypto::hash::{BlockHash, ContextHash, OperationHash}; use tezos_api::environment::TezosEnvironment; use tezos_api::ffi::ApplyBlockRequest; use tezos_messages::p2p::binary_message::MessageHash; use tezos_messages::p2p::encoding::b...
use std::collections::HashMap; use std::convert::TryInto; use anyhow::format_err; use crypto::hash::{BlockHash, ContextHash, OperationHash}; use tezos_api::environment::TezosEnvironment; use tezos_api::ffi::ApplyBlockRequest; use tezos_messages::p2p::binary_message::MessageHash; use tezos_messages::p2p::encoding::b...
message hash"), level, ); } } } Db { tezos_env, requests, headers, operations, operation_hashes, } } pub fn get(&self, block_hash: &BlockHash) -> Result<O...
in requests.iter().enumerate() { let level = to_level(idx); let request = crate::common::samples::from_captured_bytes(request) .expect("Failed to parse request"); let block = request .block_header .message_typed_hash() ...
random
[ { "content": "pub fn log_level() -> Level {\n\n env::var(\"LOG_LEVEL\")\n\n .unwrap_or_else(|_| \"info\".to_string())\n\n .parse::<Level>()\n\n .unwrap()\n\n}\n\n\n", "file_path": "shell/tests/common/mod.rs", "rank": 0, "score": 253031.1164835876 }, { "content": "pub ...
Rust
programs/vest/src/vest_instruction.rs
garious/silk
947a339714752dfa6ecc06d03da65696bee512d6
use crate::{id, vest_state::VestState}; use bincode::serialized_size; use chrono::prelude::{Date, DateTime, Utc}; use num_derive::FromPrimitive; use serde_derive::{Deserialize, Serialize}; use solana_sdk::{ instruction::{AccountMeta, Instruction, InstructionError}, program_utils::DecodeError, pubkey::Pubkey...
use crate::{id, vest_state::VestState}; use bincode::serialized_size; use chrono::prelude::{Date, DateTime, Utc}; use num_derive::FromPrimitive; use serde_derive::{Deserialize, Serialize}; use solana_sdk::{ instruction::{AccountMeta, Instruction, InstructionError}, program_utils::DecodeError, pubkey::Pubkey...
Instruction { let account_metas = vec![ AccountMeta::new(*contract, false), AccountMeta::new(*from, true), ]; Instruction::new(id(), &VestInstruction::VestAll, account_metas) }
d(), &VestInstruction::SetPayee(*new_pubkey), account_metas) } pub fn redeem_tokens(contract: &Pubkey, date_pubkey: &Pubkey, to: &Pubkey) -> Instruction { let account_metas = vec![ AccountMeta::new(*contract, false), AccountMeta::new_readonly(*date_pubkey, false), AccountMeta::new(*to, fals...
random
[ { "content": "/// Create and sign new SystemInstruction::Transfer transaction to many destinations\n\npub fn transfer_many(from_pubkey: &Pubkey, to_lamports: &[(Pubkey, u64)]) -> Vec<Instruction> {\n\n to_lamports\n\n .iter()\n\n .map(|(to_pubkey, lamports)| transfer(from_pubkey, to_pubkey, *la...
Rust
src/parser/hir/syntax_shape/expression/number.rs
thegedge/nushell
2716bb020f537470511f1036b1ef95c029a455d7
use crate::parser::hir::syntax_shape::{ expand_atom, parse_single_node, ExpandContext, ExpandExpression, ExpansionRule, FallibleColorSyntax, FlatShape, }; use crate::parser::{ hir, hir::{RawNumber, TokensIterator}, RawToken, }; use crate::prelude::*; #[derive(Debug, Copy, Clone)] pub struct NumberS...
use crate::parser::hir::syntax_shape::{ expand_atom, parse_single_node, ExpandContext, ExpandExpression, ExpansionRule, FallibleColorSyntax, FlatShape, }; use crate::parser::{ hir, hir::{RawNumber, TokensIterator}, RawToken, }; use crate::prelude::*; #[derive(Debug, Copy, Clone)] pub struct NumberS...
) => hir::Expression::string(span, token_span), }) }) } } impl FallibleColorSyntax for IntShape { type Info = (); type Input = (); fn color_syntax<'a, 'b>( &self, _input: &(), token_nodes: &'b mut TokensIterator<'a>, context: &ExpandContext, ...
context.source), token_span) } RawToken::Number(_) => return Err(err.error()), RawToken::Bare => hir::Expression::bare(token_span), RawToken::String(span
function_block-random_span
[]
Rust
src/writable.rs
engiwengi/speedy
1489137636c850461529e4b34c56b07818eebab7
use std::io::{ self, Write }; use std::fs::File; use std::path::Path; use crate::writer::Writer; use crate::context::{Context, DefaultContext}; use crate::endianness::Endianness; use crate::Error; use crate::error::{ error_end_of_output_buffer, error_output_buffer_is_too_small }; struct BufferCollec...
use std::io::{ self, Write }; use std::fs::File; use std::path::Path; use crate::writer::Writer; use crate::context::{Context, DefaultContext}; use crate::endianness::Endianness; use crate::Error; use crate::error::{ error_end_of_output_buffer, error_output_buffer_is_too_small }; struct BufferCollec...
()?; let mut vec = Vec::with_capacity( capacity ); unsafe { vec.set_len( capacity ); } let mut writer = BufferCollector { context, buffer: vec.as_mut_slice(), position: 0 }; self.write_to( &mut writer )?; let posi...
sition..self.position + size ).is_some() ) } } struct WritingCollector< C: Context, T: Write > { context: C, writer: T } impl< C: Context, T: Write > Writer< C > for WritingCollector< C, T > { #[inline] fn write_bytes( &mut self, slice: &[u8] ) -> Result< (), C::Error > { self.writer.write...
random
[ { "content": "#[inline]\n\npub fn write_length_u8< C, W >( length: usize, writer: &mut W ) -> Result< (), C::Error >\n\n where C: Context,\n\n W: ?Sized + Writer< C >\n\n{\n\n if length as u64 > std::u8::MAX as u64 {\n\n return Err( error_out_of_range_length() );\n\n }\n\n\n\n write...
Rust
src/diagnostic.rs
DanSnow/clang-rs
55bb2aa91de51d691cd04571c9c5368f64e5639e
use std::fmt; use std::mem; use std::cmp::{self, Ordering}; use clang_sys::*; use utility; use super::{TranslationUnit}; use super::source::{SourceLocation, SourceRange}; #[derive(Clone, Debug, PartialEq, Eq)] pub enum FixIt<'tu> { Deletion(SourceRange<'tu>), Insertion(SourceLocation<'tu>, String...
use std::fmt; use std::mem; use std::cmp::{self, Ordering}; use clang_sys::*; use utility; use super::{TranslationUnit}; use super::source::{SourceLocation, SourceRange}; #[derive(Clone, Debug, PartialEq, Eq)] pub enum FixIt<'tu> { Deletion(SourceRange<'tu>), Insertion(SourceLocation<'tu>, String...
pub fn get_fix_its(&self) -> Vec<FixIt<'tu>> { unsafe { (0..clang_getDiagnosticNumFixIts(self.ptr)).map(|i| { let mut range = mem::uninitialized(); let fixit = clang_getDiagnosticFixIt(self.ptr, i, &mut range); let string = utility::to_strin...
c<SourceRange<'tu>> { iter!( clang_getDiagnosticNumRanges(self.ptr), clang_getDiagnosticRange(self.ptr), ).map(|r| SourceRange::from_raw(r, self.tu)).collect() }
function_block-function_prefixed
[ { "content": "pub fn to_string(clang: CXString) -> String {\n\n unsafe {\n\n let c = CStr::from_ptr(clang_getCString(clang));\n\n let rust = c.to_str().expect(\"invalid Rust string\").into();\n\n clang_disposeString(clang);\n\n rust\n\n }\n\n}\n\n\n", "file_path": "src/util...
Rust
dev-utils/src/commands/test_vector_command.rs
crypto-raymond/chain-1
f0b612fc5cadf42308d3377f364f5751cca893a6
use parity_scale_codec::Encode; use serde::Serialize; use chain_core::common::Proof; use chain_core::init::address::{CroAddress, RedeemAddress}; use chain_core::init::coin::Coin; use chain_core::init::network::Network; use chain_core::state::account::{ CouncilNodeMeta, DepositBondTx, NodeMetadata, StakedStateAddre...
use parity_scale_codec::Encode; use serde::Serialize; use chain_core::common::Proof; use chain_core::init::address::{CroAddress, RedeemAddress}; use chain_core::init::coin::Coin; use chain_core::init::network::Network; use chain_core::state::account::{ CouncilNodeMeta, DepositBondTx, NodeMetadata, StakedStateAddre...
} #[cfg(test)] mod tests { use super::*; #[test] fn test_vectors() { let seed = hex::decode("9ee5468093cf78ce008ace0b676b606d94548f8eac79e727e3cb0500ae739facca7bb5ee1f3dd698bc6fcd044117905d42d90fadf324c6187e1faba7e662410f").unwrap(); println!("seed: {:?}", hex::encode(seed.clone())); ...
pub fn create_test_vectors(&mut self) -> Result<()> { self.test_vectors.wallet_view_key = Some(hex::encode(self.wallet.view_key.0.serialize())); let tx_id = self.create_withdraw_unbonded_tx().unwrap(); self.create_transfer_tx(tx_id)?; self.create_deposit_stake_tx(tx_id)?; self.cr...
function_block-full_function
[ { "content": "pub fn store_tx_witness(db: &mut impl StoreKV, txid: &TxId, witness_payload: &[u8]) {\n\n insert_item(db, LookupItem::TxWitness, *txid, witness_payload.to_vec());\n\n}\n\n\n", "file_path": "chain-storage/src/api.rs", "rank": 0, "score": 481254.94713891984 }, { "content": "#[...
Rust
spectrum_primitives/src/prg/group.rs
znewman01/spectrum-impl
389b463afa6463bc4a5de6884157730e9cf0b59e
use super::*; use crate::util::Sampleable; use crate::{ algebra::{Group, Monoid, SpecialExponentMonoid}, Bytes, }; use itertools::Itertools; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; use std::fmt::Debug; use std::hash::Hash; use std::iter::repeat; use std::ops::{Add, BitXor, BitXorAssig...
use super::*; use crate::util::Sampleable; use crate::{ algebra::{Group, Monoid, SpecialExponentMonoid}, Bytes, }; use itertools::Itertools; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; use std::fmt::Debug; use std::hash::Hash; use std::iter::repeat; use std::ops::{Add, BitXor, BitXorAssig...
element2)| element1 + element2) .collect(), ) } } impl<G> From<ElementVector<G>> for Vec<u8> where G: Group + Into<Vec<u8>>, { fn from(value: ElementVector<G>) -> Vec<u8> { let chunk_size = 32; let mut all_bytes = Vec::with_capacity(chunk_size * va...
ange, prelude::*}; #[cfg(any(test, feature = "testing"))] use proptest_derive::Arbitrary; #[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)] pub struct ElementVector<G>(pub Vec<G>); impl<G: Group> ElementVector<G> { pub fn new(inner: Vec<G>) -> Self { ElementVector(inner) } pub ...
random
[ { "content": "/// A monoid with custom exponentiation for a particular exponent type.\n\npub trait SpecialExponentMonoid: Monoid {\n\n type Exponent: Monoid;\n\n\n\n /// Raise `self` to the `exp`th power.\n\n fn pow(&self, exp: Self::Exponent) -> Self;\n\n}\n\n\n\n#[cfg(test)]\n\nmacro_rules! check_mon...
Rust
solana/pyth2wormhole/program/src/types/mod.rs
dendisuhubdy/wormhole
29cd5a3934aaf489a1b7aa45495414c5cb974c82
pub mod pyth_extensions; use std::{ convert::{ TryFrom, TryInto, }, io::Read, mem, }; use borsh::BorshSerialize; use pyth_client::{ AccountType, CorpAction, Ema, Price, PriceStatus, PriceType, }; use solana_program::{ clock::UnixTimestamp, program_error:...
pub mod pyth_extensions; use std::{ convert::{ TryFrom, TryInto, }, io::Read, mem, }; use borsh::BorshSerialize; use pyth_client::{ AccountType, CorpAction, Ema, Price, PriceStatus, PriceType, }; use solana_program::{ clock::UnixTimestamp, program_error:...
}
3, status: P2WPriceStatus::Trading, confidence_interval: 101, corp_act: P2WCorpAction::NoCorpAct, timestamp: 123456789i64, }; println!("Regular: {:#?}", &attestation); println!("Hex: {:#02X?}", &attestation); let bytes = attestation.serialize(); ...
function_block-function_prefixed
[ { "content": "#[wasm_bindgen]\n\npub fn parse_attestation(bytes: Vec<u8>) -> JsValue {\n\n let a = PriceAttestation::deserialize(bytes.as_slice()).unwrap();\n\n \n\n JsValue::from_serde(&a).unwrap()\n\n}\n", "file_path": "solana/pyth2wormhole/program/src/wasm.rs", "rank": 0, "score": 363306...
Rust
src/testing/sl4f/src/bluetooth/avrcp_facade.rs
EnderNightLord-ChromeBook/zircon-rpi
b09b1eb3aa7a127c65568229fe10edd251869283
use super::types::{CustomAvcPanelCommand, CustomPlayStatus}; use crate::common_utils::common::macros::{fx_err_and_bail, with_line}; use anyhow::Error; use fidl::endpoints::create_endpoints; use fidl_fuchsia_bluetooth_avrcp::{ ControllerMarker, ControllerProxy, PeerManagerMarker, PeerManagerProxy, }; use fuchsia_c...
use super::types::{CustomAvcPanelCommand, CustomPlayStatus}; use crate::common_utils::common::macros::{fx_err_and_bail, with_line}; use anyhow::Error; use fidl::endpoints::create_endpoints; use fidl_fuchsia_bluetooth_avrcp::{ ControllerMarker, ControllerProxy, PeerManagerMarker, PeerManagerProxy, }; use fuchsia_c...
} pub async fn send_command(&self, command: CustomAvcPanelCommand) -> Result<(), Error> { let tag = "AvrcpFacade::send_command"; let result = match self.inner.read().controller_proxy.clone() { Some(proxy) => proxy.send_command(command.into()).await?, ...
match self.inner.read().controller_proxy.clone() { Some(proxy) => match proxy.get_play_status().await? { Ok(play_status) => Ok(CustomPlayStatus::new(&play_status)), Err(e) => fx_err_and_bail!( &with_line!(tag), format!("Error fetching p...
if_condition
[]
Rust
azure-functions/src/rpc/client.rs
rylev/azure-functions-rs
7bc1e1d977da8bca669e7d802d401c689448e852
use crate::logger; use crate::registry::Registry; use azure_functions_shared::rpc::protocol; use futures::future::{lazy, ok}; use futures::sync::mpsc; use futures::{Future, Sink, Stream}; use grpcio::{ChannelBuilder, ClientDuplexReceiver, EnvBuilder, WriteFlags}; use log::{self, error}; use std::cell::RefCell; use std:...
use crate::logger; use crate::registry::Registry; use azure_functions_shared::rpc::protocol; use futures::future::{lazy, ok}; use futures::sync::mpsc; use futures::{Future, Sink, Stream}; use grpcio::{ChannelBuilder, ClientDuplexReceiver, EnvBuilder, WriteFlags}; use log::{self, error}; use std::cell::RefCell; use std:...
pub fn read( mut self, ) -> impl Future<Item = (Client, Option<protocol::StreamingMessage>), Error = ()> { self.receiver .take() .unwrap() .into_future() .map_err(|(err, _)| panic!("failed to receive message: {:?}.", err)) .and_then(m...
take() .unwrap() .send(message) .map_err(|err| panic!("failed to send message: {:?}.", err)) .and_then(move |sender| { self.sender = Some(sender); ok(self) }) }
function_block-function_prefix_line
[ { "content": "pub fn read_crate_name(path: &str) -> Result<String, String> {\n\n let mut _file =\n\n File::open(path).map_err(|e| format!(\"Failed to open {}: {}\", \"Cargo.toml\".cyan(), e))?;\n\n\n\n let mut contents = String::new();\n\n _file\n\n .read_to_string(&mut contents)\n\n ...
Rust
src/adc0/verid.rs
conorpp/lpc55-pac
eb30d633de05113362de01095123d70c54e63ef4
#[doc = "Reader of register VERID"] pub type R = crate::R<u32, super::VERID>; #[doc = "Resolution\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RES_A { #[doc = "0: Up to 13-bit differential/12-bit single ended resolution supported."] RES_0 = 0, #[doc = "1: Up to 16-bit differentia...
#[doc = "Reader of register VERID"] pub type R = crate::R<u32, super::VERID>; #[doc = "Resolution\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RES_A { #[doc = "0: Up to 13-bit differential/12-bit single ended resolution supported."] RES_0 = 0, #[doc = "1: Up to 16-bit differentia...
VR1RNGI_0 = 0, #[doc = "1: Range control required. CFG\\[VREF1RNG\\] is implemented."] VR1RNGI_1 = 1, } impl From<VR1RNGI_A> for bool { #[inline(always)] fn from(variant: VR1RNGI_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `VR1RNGI`"] pub type VR1RNGI_R = crate::R<bool, VR...
derive(Clone, Copy, Debug, PartialEq)] pub enum DIFFEN_A { #[doc = "0: Differential operation not supported."] DIFFEN_0 = 0, #[doc = "1: Differential operation supported. CMDLa\\[CTYPE\\] controls fields implemented."] DIFFEN_1 = 1, } impl From<DIFFEN_A> for bool { #[inline(always)] fn from(vari...
random
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
ark-bcs/src/ldt/mod.rs
arkworks-rs/bcs
baf903d87c0ee98d82e931610439b3d0e03a982f
use ark_std::marker::PhantomData; use ark_crypto_primitives::merkle_tree::Config as MTConfig; use ark_ff::PrimeField; use ark_ldt::domain::Radix2CosetDomain; use ark_sponge::{Absorb, CryptographicSponge}; use crate::{ bcs::{simulation_transcript::SimulationTranscript, transcript::Transcript}, iop::{ b...
use ark_std::marker::PhantomData; use ark_crypto_primitives::merkle_tree::Config as MTConfig; use ark_ff::PrimeField; use ark_ldt::domain::Radix2CosetDomain; use ark_sponge::{Absorb, CryptographicSponge}; use crate::{ bcs::{simulation_transcript::SimulationTranscript, transcript::Transcript}, iop::{ b...
} impl<F: PrimeField + Absorb> LDT<F> for NoLDT<F> { type LDTParameters = Option<(Radix2CosetDomain<F>, usize)>; fn prove<MT: MTConfig<Leaf = [F]>, S: CryptographicSponge>( _namespace: NameSpace, _param: &Self::LDTParameters, _transcript: &mut Transcript<MT, S, F>, ...
pub fn parameter( evaluation_domain: Radix2CosetDomain<F>, localization_parameter: usize, ) -> (Radix2CosetDomain<F>, usize) { (evaluation_domain, localization_parameter) }
function_block-full_function
[ { "content": "/// The verifier for public coin IOP has two phases. This is intended to be\n\n/// used as an endpoint protocol. Any subprotocol does not need to implement\n\n/// this trait. Any implementation of this trait can be transformed to SNARG by\n\n/// BCS.\n\n/// * **Commit Phase**: Verifier send messa...
Rust
src/flash/fcfg_b0_ssize0.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register FCFG_B0_SSIZE0"] pub type R = crate::R<u32, super::FCFG_B0_SSIZE0>; #[doc = "Writer for register FCFG_B0_SSIZE0"] pub type W = crate::W<u32, super::FCFG_B0_SSIZE0>; #[doc = "Register FCFG_B0_SSIZE0 `reset()`'s with value 0x002c_0008"] impl crate::ResetValue for super::FCFG_B0_SSIZE0 { ty...
#[doc = "Reader of register FCFG_B0_SSIZE0"] pub type R = crate::R<u32, super::FCFG_B0_SSIZE0>; #[doc = "Writer for register FCFG_B0_SSIZE0"] pub type W = crate::W<u32, super::FCFG_B0_SSIZE0>; #[doc = "Register FCFG_B0_SSIZE0 `reset()`'s with value 0x002c_0008"] impl crate::ResetValue for super::FCFG_B0_SSIZE0 { ty...
gh TI provided API."] #[inline(always)] pub fn b0_num_sectors(&mut self) -> B0_NUM_SECTORS_W { B0_NUM_SECTORS_W { w: self } } #[doc = "Bits 4:15 - 15:4\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn reserved4(&mut self) -> RESERVED4_W { RESERVED4...
ct B0_SECT_SIZE_W<'a> { w: &'a mut W, } impl<'a> B0_SECT_SIZE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } impl R { #[doc = "Bits 28:...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
chain-impl-mockchain/src/stake/role.rs
Emurgo/rust-cardano
31b508cbabcee2ef4ff9596abe2b04aede34e1a0
use crate::key::{deserialize_public_key, serialize_public_key, Hash}; use crate::leadership::genesis::GenesisPraosLeader; use chain_core::mempack::{ReadBuf, ReadError, Readable}; use chain_core::property; use chain_crypto::{Ed25519, PublicKey}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct StakeKeyInfo { pub(c...
use crate::key::{deserialize_public_key, serialize_public_key, Hash}; use crate::leadership::genesis::GenesisPraosLeader; use chain_core::mempack::{ReadBuf, ReadError, Readable}; use chain_core::property; use chain_crypto::{Ed25519, PublicKey}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct StakeKeyInfo { pub(c...
} impl property::Serialize for StakePoolInfo { type Error = std::io::Error; fn serialize<W: std::io::Write>(&self, writer: W) -> Result<(), Self::Error> { assert!(self.owners.len() < 256); use chain_core::packer::Codec; let mut codec = Codec::new(writer); codec.put_u128(self....
let vrf_public_key = deserialize_public_key(reader)?; Ok(GenesisPraosLeader { vrf_public_key, kes_public_key, }) }
function_block-function_prefix_line
[ { "content": "/// Trait identifying the block identifier type.\n\npub trait BlockId: Eq + Ord + Clone + Debug + Hash + Serialize + Deserialize {\n\n /// A special ID used to denote a non-existent block (e.g. the\n\n /// parent of the first block).\n\n fn zero() -> Self;\n\n}\n\n\n", "file_path": "c...
Rust
sdk/cosmos/src/clients/database_client.rs
duysqubix/azure-sdk-for-rust
fe07e29f11e95acbf830289499eb373b4efa0006
use super::*; use crate::authorization_policy::CosmosContext; use crate::operations::*; use crate::resources::ResourceType; use crate::{requests, ReadonlyString}; use azure_core::pipeline::Pipeline; use azure_core::prelude::Continuation; use azure_core::{AddAsHeader, Context, HttpClient, PipelineContext}; use futures::...
use super::*; use crate::authorization_policy::CosmosContext; use crate::operations::*; use crate::resources::ResourceType; use crate::{requests, ReadonlyString}; use azure_core::pipeline::Pipeline; use azure_core::prelude::Continuation; use azure_core::{AddAsHeader, Context, HttpClient, PipelineContext}; use futures::...
} pub fn into_collection_client<S: Into<ReadonlyString>>( self, collection_name: S, ) -> CollectionClient { CollectionClient::new(self, collection_name) } pub fn into_user_client<S: Into<ReadonlyString>>(self, user_name: S) -> UserClient { UserClient::new...
unfold(State::Init, move |state: State| { let this = self.clone(); let ctx = ctx.clone(); let options = options.clone(); async move { let response = match state { State::Init => { let mut request = this.cosmos_cl...
call_expression
[]
Rust
src/process/intermediate.rs
Ian-Yy/youki
d209d75512631d676ca0409a19b893d4314f3830
use crate::{namespaces::Namespaces, process::channel, process::fork}; use anyhow::{Context, Error, Result}; use cgroups::common::CgroupManager; use nix::unistd::{Gid, Pid, Uid}; use oci_spec::runtime::{LinuxNamespaceType, LinuxResources}; use procfs::process::Process; use std::convert::From; use super::args::Container...
use crate::{namespaces::Namespaces, process::channel, process::fork}; use anyhow::{Context, Error, Result}; use cgroups::common::CgroupManager; use nix::unistd::{Gid, Pid, Uid}; use oci_spec::runtime::{LinuxNamespaceType, LinuxResources}; use procfs::process::Process; use std::convert::From; use super::args::Container...
#[test] fn apply_cgroup_no_resources() -> Result<()> { let cmanager = TestManager::default(); apply_cgroups(&cmanager, None, true)?; assert_eq!( cmanager.get_add_task_args()[0], Pid::from_raw(Process::myself()?.pid()) ); ...
let resources = LinuxResources::default(); apply_cgroups(&cmanager, Some(&resources), false)?; assert_eq!( cmanager.get_add_task_args()[0], Pid::from_raw(Process::myself()?.pid()) ); assert!(!cmanager.apply_called()); Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn init_to_intermediate() -> Result<(SenderInitToIntermediate, ReceiverFromInit)> {\n\n let (sender, receiver) = new_pipe()?;\n\n Ok((\n\n SenderInitToIntermediate { sender },\n\n ReceiverFromInit { receiver },\n\n ))\n\n}\n\n\n\npub struct SenderInitToIntermediate {\n\n...
Rust
examples/test.rs
AntonHermann/synth
74c53d72ee1a690cd055417e48e2c114b0e1061d
extern crate pitch_calc as pitch; extern crate portaudio; extern crate sample; extern crate synth; use portaudio as pa; use pitch::{Letter, LetterOctave}; use synth::Synth; pub type AudioSample = f32; pub type Input = AudioSample; pub type Output = AudioSample; const CHANNELS: i32 = 2; const FRAMES: u32 = 64; cons...
extern crate pitch_calc as pitch; extern crate portaudio; extern crate sample; extern crate synth; use portaudio as pa; use pitch::{Letter, LetterOctave}; use synth::Synth; pub type AudioSample = f32; pub type Input = AudioSample; pub type Output = AudioSample; const CHANNELS: i32 = 2; const FRAMES: u32 = 64; cons...
pa::Continue } else { pa::Complete } }; let pa = try!(pa::PortAudio::new()); let settings = try!(pa.default_output_stream_settings::<f32>(CHANNELS, SAMPLE_HZ, FRAMES)); let mut stream = try!(pa.open_non_blocking_stream(settings, callback)); try!(stream....
if timer > note_duration { if !is_note_off { synth.note_off(note); is_note_off = true; } }
if_condition
[ { "content": "#[test]\n\nfn test_dynamic_synth() {\n\n use dynamic::Synth;\n\n\n\n extern crate serde_json;\n\n\n\n let synth = Synth::dynamic_retrigger();\n\n let serialized = serde_json::to_string(&synth).unwrap();\n\n\n\n println!(\"{}\", serialized);\n\n \n\n let deserialized: Synth = s...
Rust
src/schema/text_options.rs
elbow-jason/tantivy
45e62d43293ed8c66ef027104a35cf25afe2e995
use schema::IndexRecordOption; use std::borrow::Cow; use std::ops::BitOr; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct TextOptions { indexing: Option<TextFieldIndexing>, stored: bool, } impl TextOptions { pub fn get_indexing_options(&self) -> Option<&TextFieldIndexing> { ...
use schema::IndexRecordOption; use std::borrow::Cow; use std::ops::BitOr; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct TextOptions { indexing: Option<TextFieldIndexing>, stored: bool, } impl TextOptions { pub fn get_indexing_options(&self) -> Option<&TextFieldIndexing> { ...
} } #[test] fn test_cmp_index_record_option() { assert!(IndexRecordOption::WithFreqsAndPositions > IndexRecordOption::WithFreqs); assert!(IndexRecordOption::WithFreqs > IndexRecordOption::Basic); } }
match field_entry.field_type() { &FieldType::Str(ref text_options) => { assert!(text_options.get_indexing_options().is_some()); assert_eq!( text_options.get_indexing_options().unwrap().tokenizer(), "default" ...
if_condition
[ { "content": "// writes a lowercased version of text into output.\n\nfn to_lowercase_unicode(text: &mut String, output: &mut String) {\n\n output.clear();\n\n for c in text.chars() {\n\n // Contrary to the std, we do not take care of sigma special case.\n\n // This will have an normalization...
Rust
tests/route_middleware.rs
chrisdickinson/tide
f884167f29e36993afd31f477ce77138bd915b7c
use http_types::headers::HeaderName; use std::convert::TryInto; use tide::http::{self, url::Url, Method}; use tide::Middleware; use test_utils::BoxFuture; mod test_utils; #[derive(Debug)] struct TestMiddleware(HeaderName, &'static str); impl TestMiddleware { fn with_header_name(name: &'static str, value: &'stat...
use http_types::headers::HeaderName; use std::convert::TryInto; use tide::http::{self, url::Url, Method}; use tide::Middleware; use test_utils::BoxFuture; mod test_utils; #[derive(Debug)] struct TestMiddleware(HeaderName, &'static str); impl TestMiddleware { fn with_header_name(name: &'static str, value: &'stat...
#[async_std::test] async fn nested_app_with_route_middleware() { let mut inner = tide::new(); inner.middleware(TestMiddleware::with_header_name("X-Inner", "inner")); inner .at("/baz") .middleware(TestMiddleware::with_header_name("X-Baz", "baz")) .get(echo_path); let mut app = ...
async fn app_and_route_middleware() { let mut app = tide::new(); app.middleware(TestMiddleware::with_header_name("X-Root", "root")); app.at("/foo") .middleware(TestMiddleware::with_header_name("X-Foo", "foo")) .get(echo_path); app.at("/bar") .middleware(TestMiddleware::with_heade...
function_block-full_function
[ { "content": "/// An HTTP request handler.\n\n///\n\n/// This trait is automatically implemented for `Fn` types, and so is rarely implemented\n\n/// directly by Tide users.\n\n///\n\n/// In practice, endpoints are functions that take a `Request<State>` as an argument and\n\n/// return a type `T` that implements...
Rust
account/src/account.rs
WormholeStudio/starcoin
9f7025537cccb613834f1659649cd753e0becdd7
use crate::account_manager::gen_private_key; use crate::account_storage::AccountStorage; use anyhow::{format_err, Result}; use starcoin_account_api::error::AccountError; use starcoin_account_api::{ AccountInfo, AccountPrivateKey, AccountPublicKey, AccountResult, Setting, }; use starcoin_crypto::PrivateKey; use st...
use crate::account_manager::gen_private_key; use crate::account_storage::AccountStorage; use anyhow::{format_err, Result}; use starcoin_account_api::error::AccountError; use starcoin_account_api::{ AccountInfo, AccountPrivateKey, AccountPublicKey, AccountResult, Setting, }; use starcoin_crypto::PrivateKey; use st...
pub fn create_readonly( address: AccountAddress, public_key: AccountPublicKey, storage: AccountStorage, ) -> AccountResult<Self> { storage.update_public_key(address, public_key.clone())?; let setting = Setting::readonly(); storage.update_setting(address, setting...
n create( address: AccountAddress, private_key: AccountPrivateKey, password: String, storage: AccountStorage, ) -> AccountResult<Self> { storage.update_key(address, &private_key, password.as_str())?; let setting = Setting::default(); storage.update_setting(add...
function_block-function_prefixed
[ { "content": "#[test]\n\npub fn test_readonly_account() -> Result<()> {\n\n let tempdir = tempfile::tempdir()?;\n\n let storage = AccountStorage::create_from_path(tempdir.path(), RocksdbConfig::default())?;\n\n let manager = AccountManager::new(storage.clone(), ChainId::test())?;\n\n let mut key_gen...
Rust
src/style/styles/styledobject.rs
tkaden4/crossterm
dd01de870beed9717de1afc6d12e145be4e931bc
use std::io::Write; use std::{self, fmt}; #[cfg(unix)] use super::super::Attribute; use style::{Color, ObjectStyle}; pub struct StyledObject<D> { pub object_style: ObjectStyle, pub content: D, } impl<D> StyledObject<D> { ...
use std::io::Write; use std::{self, fmt}; #[cfg(unix)] use super::super::Attribute; use style::{Color, ObjectStyle}; pub struct StyledObject<D> { pub object_style: ObjectStyle, pub content: D, } impl<D> StyledObject<D> { ...
for attr in self.object_style.attrs.iter() { write!(f, csi!("{}m"), *attr as i16); reset = true; } fmt::$name::fmt(&self.content, f)?; std::io::stdout().flush().expect("Flush stdout failed"); if reset { ...
olor { colored_terminal.set_fg(fg); reset = true; } #[cfg(unix)]
random
[ { "content": "/// Get an TerminalColor implementation whereon color related actions can be performed.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust\n\n/// extern crate crossterm;\n\n///\n\n/// use self::crossterm::style::{color, Color};\n\n///\n\n/// // Get colored terminal instance\n\n/// let mut colored_termi...
Rust
tools/publisher/src/sort.rs
Jacco/smithy-rs
8a5b48062bb76138844c6c912f355076c3ad75ba
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use crate::package::{Package, PackageHandle}; use anyhow::Result; use std::collections::{BTreeMap, BTreeSet}; pub fn dependency_order(packages: Vec<Package>) -> Result<Vec<Package>> { let mut order...
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use crate::package::{Package, PackageHandle}; use anyhow::Result; use std::collections::{BTreeMap, BTreeSet}; pub fn dependency_order(packages: Vec<Package>) -> Result<Vec<Package>> { let mut order...
#[test] pub fn test_dependency_order() { let packages = vec![ package("E", &["B", "C", "A"]), package("B", &[]), package("F", &["E", "D"]), package("C", &["A"]), package("A", &[]), package("D", &["C"]), ]; let res...
fn package(name: &str, dependencies: &[&str]) -> Package { Package::new( PackageHandle::new(name, Version::parse("1.0.0").unwrap()), format!("{}/Cargo.toml", name), dependencies .iter() .map(|d| PackageHandle::new(*d, Version::parse("1.0.0").un...
function_block-full_function
[ { "content": "/// Writes the given `headers` to a `buffer`.\n\npub fn write_headers_to<B: BufMut>(headers: &[Header], mut buffer: B) -> Result<(), Error> {\n\n for header in headers {\n\n header.write_to(&mut buffer)?;\n\n }\n\n Ok(())\n\n}\n\n\n\n/// Event Stream message.\n\n#[non_exhaustive]\n...
Rust
src/sdif/ctype.rs
geky/lpc55s6x-pac
766a1eec50a670a5872aa1a8c7637a9d5b9d6478
#[doc = "Reader of register CTYPE"] pub type R = crate::R<u32, super::CTYPE>; #[doc = "Writer for register CTYPE"] pub type W = crate::W<u32, super::CTYPE>; #[doc = "Register CTYPE `reset()`'s with value 0"] impl crate::ResetValue for super::CTYPE { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
#[doc = "Reader of register CTYPE"] pub type R = crate::R<u32, super::CTYPE>; #[doc = "Writer for register CTYPE"] pub type W = crate::W<u32, super::CTYPE>; #[doc = "Register CTYPE `reset()`'s with value 0"] impl crate::ResetValue for super::CTYPE { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
pub fn card1_width0(&mut self) -> CARD1_WIDTH0_W { CARD1_WIDTH0_W { w: self } } #[doc = "Bit 16 - Indicates if card 0 is 8-bit: 0 - Non 8-bit mode 1 - 8-bit mode."] #[inline(always)] pub fn card0_width1(&mut self) -> CARD0_WIDTH1_W { CARD0_WIDTH1_W { w: self } } #[doc = "Bit...
it: 0 - Non 8-bit mode 1 - 8-bit mode."] #[inline(always)] pub fn card1_width1(&self) -> CARD1_WIDTH1_R { CARD1_WIDTH1_R::new(((self.bits >> 17) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Indicates if card 0 is 1-bit or 4-bit: 0 - 1-bit mode 1 - 4-bit mode 1 and 4-bit modes only work when 8-bit...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
sway-core/src/semantic_analysis/ast_node/expression/match_expression/analysis/patstack.rs
FuelLabs/sway
0190b5dac4735fd2a34528e48cc2e0c9606b5ce8
use std::{cmp::Ordering, fmt, slice::Iter, vec::IntoIter}; use itertools::Itertools; use sway_types::Span; use crate::{ error::{err, ok}, CompileError, CompileResult, }; use super::pattern::Pattern; #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct PatStack { pats: Vec<Pattern>, } impl PatStack ...
use std::{cmp::Ordering, fmt, slice::Iter, vec::IntoIter}; use itertools::Itertools; use sway_types::Span; use crate::{ error::{err, ok}, CompileError, CompileResult, }; use super::pattern::Pattern; #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct PatStack { pats: Vec<Pattern>, } impl PatStack ...
for (i, pat) in top.clone().into_iter().enumerate() { if let Pattern::Or(elems) = pat { for elem in elems.into_iter() { let mut top = top.clone(); let r = check!( top.get_mut(i, span),...
pub(crate) fn serialize_multi_patterns(self, span: &Span) -> CompileResult<Vec<PatStack>> { let mut warnings = vec![]; let mut...
random
[ { "content": "/// Given a `PatStack` *pⁱ* from `Matrix` *P*, compute the resulting row of the\n\n/// default `Matrix` *D(P)*.\n\n///\n\n/// A row in the default `Matrix` \"shrinks itself\" or \"eliminates itself\"\n\n/// depending on if its possible to make general claims the first element of the\n\n/// row *pⁱ...
Rust
tests/std.rs
passcod/async-process
bc9719e64a5d82d7b122b7e1a59dfb5db79148a5
use std::env; use std::io; use std::str; use async_process::{Command, Output, Stdio}; use futures_lite::{future, prelude::*}; #[test] fn smoke() { future::block_on(async { let p = if cfg!(target_os = "windows") { Command::new("cmd").args(&["/C", "exit 0"]).spawn() } else { ...
use std::env; use std::io; use std::str; use async_process::{Command, Output, Stdio}; use futures_lite::{future, prelude::*}; #[test] fn smoke() { future::block_on(async { let p = if cfg!(target_os = "windows") { Command::new("cmd").args(&["/C", "exit 0"]).spawn() } else { ...
#[test] fn exit_reported_right() { future::block_on(async { let p = if cfg!(target_os = "windows") { Command::new("cmd").args(&["/C", "exit 1"]).spawn() } else { Command::new("false").spawn() }; assert!(p.is_ok()); let mut p = p.unwrap(); ass...
match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() { Ok(..) => panic!(), Err(..) => {} } }
function_block-function_prefix_line
[ { "content": "//! Windows-specific extensions.\n\n\n\nuse std::os::windows::process::CommandExt as _;\n\n\n\nuse crate::Command;\n\n\n\n/// Windows-specific extensions to the [`Command`] builder.\n", "file_path": "src/windows.rs", "rank": 19, "score": 23251.021665620086 }, { "content": "/// ...
Rust
src/main.rs
AldanTanneo/lotr-mod-discord-bot
624ae132fefa5bb4b1f5762629f24c9f398e9891
pub mod announcement; pub mod api; pub mod check; pub mod commands; pub mod constants; pub mod database; pub mod event_handler; pub mod qa_answers; pub mod role_cache; pub mod utils; use mysql_async::OptsBuilder; use serenity::client::bridge::gateway::GatewayIntents; use serenity::client::ClientBuilder; use serenity...
pub mod announcement; pub mod api; pub mod check; pub mod commands; pub mod constants; pub mod database; pub mod event_handler; pub mod qa_answers; pub mod role_cache; pub mod utils; use mysql_async::OptsBuilder; use serenity::client::bridge::gateway::GatewayIntents; use serenity::client::ClientBuilder; use serenity...
}
if let Err(why) = client.start().await { println!("An error occurred while running the client: {:?}", why); }
if_condition
[ { "content": "pub fn to_json_safe_string(s: impl ToString) -> String {\n\n // serialize as string to get string escapes\n\n let s = serde_json::ser::to_string(&serde_json::Value::String(s.to_string())).unwrap();\n\n // remove the surrounding quotes\n\n s[1..s.len() - 1].to_string()\n\n}\n\n\n\n#[cfg...
Rust
nj-core/src/buffer.rs
sehz/node-bindgen
6450525dbd3202310b1e153adb1314062842477c
use std::ptr; use std::ops::Deref; use log::trace; use crate::TryIntoJs; use crate::JSValue; use crate::sys::{napi_value, napi_ref, napi_env}; use crate::val::JsEnv; use crate::NjError; pub struct ArrayBuffer { data: Vec<u8>, } use std::fmt; use std::fmt::Debug; impl Debug for ArrayBuffer { fn fmt(&self, f...
use std::ptr; use std::ops::Deref; use log::trace; use crate::TryIntoJs; use crate::JSValue; use crate::sys::{napi_value, napi_ref, napi_env}; use crate::val::JsEnv; use crate::NjError; pub struct ArrayBuffer { data: Vec<u8>, } use std::fmt; use std::fmt::Debug; impl Debug for ArrayBuffer { fn fmt(&self, f...
; } let buffer = env.get_buffer_info(js_value)?; Ok(buffer) } } pub struct JSArrayBuffer { env: JsEnv, napi_ref: napi_ref, buffer: &'static [u8], } unsafe impl Send for JSArrayBuffer {} impl JSArrayBuffer { pub fn as_bytes(&self) -> &[u8] { &self.buffer } } ...
Err(NjError::InvalidType( "Buffer".to_owned(), env.value_type_string(js_value)?.to_owned(), ))
call_expression
[ { "content": "#[node_bindgen]\n\nfn test3(data: JSArrayBuffer) -> Result<String, NjError> {\n\n let message = String::from_utf8(data.to_vec())?;\n\n Ok(format!(\"reply {}\", message))\n\n}\n\n\n", "file_path": "examples/buffer/src/lib.rs", "rank": 0, "score": 210644.66397764176 }, { "c...
Rust
network/src/peer_store/peer_store_impl.rs
brson/ckb
b9bf40024b8a5acd9b8871dba669c89f38be297d
use crate::{ errors::{PeerStoreError, Result}, network_group::{Group, NetworkGroup}, peer_store::{ addr_manager::AddrManager, ban_list::BanList, types::{ip_to_network, AddrInfo, BannedAddr, MultiaddrExt, PeerInfo}, Behaviour, Multiaddr, PeerScoreConfig, ReportResult, Status, ...
use crate::{ errors::{PeerStoreError, Result}, network_group::{Group, NetworkGroup}, peer_store::{ addr_manager::AddrManager, ban_list::BanList, types::{ip_to_network, AddrInfo, BannedAddr, MultiaddrExt, PeerInfo}, Behaviour, Multiaddr, PeerScoreConfig, ReportResult, Status, ...
let score = self.score_config.default_score; if session_type.is_outbound() { self.addr_manager.add(AddrInfo::new( peer_id, addr.extract_ip_addr()?, addr.exclude_p2p(), now_ms, score, )); } ...
match self.peers.get_mut().entry(peer_id.to_owned()) { Entry::Occupied(mut entry) => { let mut peer = entry.get_mut(); peer.connected_addr = addr.clone(); peer.last_connected_at_ms = now_ms; peer.session_type = session_type; } ...
if_condition
[]
Rust
derive/src/lib.rs
znly/async-graphql
16d38c521f5855914d9a830076731ef515b8d4d3
#![allow(clippy::cognitive_complexity)] #![forbid(unsafe_code)] extern crate proc_macro; mod args; mod r#enum; mod input_object; mod interface; mod merged_object; mod merged_subscription; mod object; mod output_type; mod scalar; mod simple_object; mod subscription; mod union; mod utils; use crate::utils::{add_contai...
#![allow(clippy::cognitive_complexity)] #![forbid(unsafe_code)] extern crate proc_macro; mod args; mod r#enum; mod input_object; mod interface; mod merged_object; mod merged_subscription; mod object; mod output_type; mod scalar; mod simple_object; mod subscription; mod union; mod utils; use crate::utils::{add_contai...
#[proc_macro_attribute] #[allow(non_snake_case)] pub fn Enum(args: TokenStream, input: TokenStream) -> TokenStream { add_container_attrs( quote!(GQLEnum, Copy, Clone, Eq, PartialEq), parse_macro_input!(args as AttributeArgs), input.into(), ) .unwrap_or_else(|err| err.to_compile_err...
t) = match parse_derive(input.into()) { Ok(r) => r, Err(err) => return err.to_compile_error().into(), }; let object_args = match args::Object::parse(parse_macro_input!(args as AttributeArgs)) { Ok(object_args) => object_args, Err(err) => return err.to_compile_error().into(), ...
function_block-function_prefixed
[]
Rust
examples/noise_handshake.rs
niklaslong/pea2pea
4ff273bd6f0e9703d8347f5fccddd21a37a33f0d
mod common; use bytes::Bytes; use parking_lot::{Mutex, RwLock}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, time::sleep, }; use tracing::*; use tracing_subscriber::filter::LevelFilter; use pea2pea::{ protocols::{Handshaking, Reading, Writing}, Connection, ConnectionSide, Node, NodeConfig, Pea2Pea,...
mod common; use bytes::Bytes; use parking_lot::{Mutex, RwLock}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, time::sleep, }; use tracing::*; use tracing_subscriber::filter::LevelFilter; use pea2pea::{ protocols::{Handshaking, Reading, Writing}, Connection, ConnectionSide, Node, NodeConfig, Pea2Pea,...
async fn process_message(&self, source: SocketAddr, message: Self::Message) -> io::Result<()> { info!(parent: self.node().span(), "decrypted a message from {}: \"{}\"", source, message); Ok(()) } } impl Writing for SecureNode { fn write_message( &self, target: SocketAddr,...
fn read_message( &self, source: SocketAddr, buffer: &[u8], ) -> io::Result<Option<(Self::Message, usize)>> { let bytes = read_message(buffer)?; if let Some(bytes) = bytes { let noise = Arc::clone(self.noise_states.read().get(&source).unwrap()); let No...
function_block-full_function
[ { "content": "pub fn read_len_prefixed_message(len_size: usize, buffer: &[u8]) -> io::Result<Option<&[u8]>> {\n\n if buffer.len() >= len_size {\n\n let payload_len = match len_size {\n\n 2 => u16::from_le_bytes(buffer[..len_size].try_into().unwrap()) as usize,\n\n 4 => u32::from_...
Rust
src/shade.rs
ucarion/gfx
0701f16155ec5af4a2abff4e2b8740523861d1a4
use std::error::Error; use std::fmt; pub use gfx_device_gl::Version as GlslVersion; #[cfg(target_os = "windows")] pub use gfx_device_dx11::ShaderModel as DxShaderModel; #[cfg(feature = "metal")] pub use gfx_device_metal::ShaderModel as MetalShaderModel; #[derive(Copy, Clone, Debug, PartialEq)] pub enum Backend { ...
use std::error::Error; use std::fmt; pub use gfx_device_gl::Version as GlslVersion; #[cfg(target_os = "windows")] pub use gfx_device_dx11::ShaderModel as DxShaderModel; #[cfg(feature = "metal")] pub use gfx_device_metal::ShaderModel as MetalShaderModel; #[derive(Copy, Clone, Debug, PartialEq)] pub enum Backend { ...
}
pub fn select(&self, backend: Backend) -> Result<&'a [u8], SelectError> { Ok(match backend { Backend::Glsl(version) => { let v = version.major * 100 + version.minor; match *self { Source { glsl_430: s, .. } if s != EMPTY && v >= 430 => s, ...
function_block-full_function
[ { "content": "// texture loading boilerplate\n\npub fn load_texture<R, F>(factory: &mut F, data: &[u8])\n\n -> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String>\n\n where R: gfx::Resources, F: gfx::Factory<R>\n\n{\n\n use gfx::format::Rgba8;\n\n use gfx::texture as t;\...
Rust
pac/atsam3x8h/src/uotghs/devicr.rs
compenguy/atsam3x8e
79168e405c0c8ce9005866c85df5dcc77e235f5e
#[doc = "Writer for register DEVICR"] pub type W = crate::W<u32, super::DEVICR>; #[doc = "Write proxy for field `SUSPC`"] pub struct SUSPC_W<'a> { w: &'a mut W, } impl<'a> SUSPC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } ...
#[doc = "Writer for register DEVICR"] pub type W = crate::W<u32, super::DEVICR>; #[doc = "Write proxy for field `SUSPC`"] pub struct SUSPC_W<'a> { w: &'a mut W, } impl<'a> SUSPC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } ...
} #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Write proxy for field `EORSMC`"] pub struct EORSMC_W<'a> { w: &'a mut W, } i...
_W<'a> { w: &'a mut W, } impl<'a> EORSTC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc ...
random
[]
Rust
src/custom_fd.rs
nsforth/actorio
b15dacfadfb93b201d54f2b3758fd1a84a044e0a
use crate::{AsSocketId, MaybeSocketOwner, ActorioContext, SocketHolder, SocketId}; use mio::event::Source; use mio::unix::SourceFd; use mio::{Interest, Registry, Token}; use std::io::Error; use std::os::unix::io::RawFd; type CustomFdEventHandler<'a, A> = Box<dyn FnMut(&mut A, &mut ActorioContext<'a, A>, &CustomFdI...
use crate::{AsSocketId, MaybeSocketOwner, ActorioContext, SocketHolder, SocketId}; use mio::event::Source; use mio::unix::SourceFd; use mio::{Interest, Registry, Token}; use std::io::Error; use std::os::unix::io::RawFd; type CustomFdEventHandler<'a, A> = Box<dyn FnMut(&mut A, &mut ActorioContext<'a, A>, &CustomFdI...
pub(crate) fn has_read_handler(&self) -> bool { self.on_readable.is_some() } pub(crate) fn has_write_handler(&self) -> bool { self.on_writeable.is_some() } } impl<'a, A> Source for CustomFd<'a, A> { fn register( &mut self, registry: &Registry, token: Token...
ocess_write( act_ctx: &mut ActorioContext<'a, A>, application: &mut A, custom_fd_id: CustomFdId, ) { if let Some(custom_fd) = act_ctx.try_get_socket(&custom_fd_id) { let mut on_writeable = custom_fd.on_writeable.take().unwrap(); on_writeable(appli...
function_block-function_prefixed
[ { "content": "type TCPEventHandler<'a, A> = Box<dyn FnMut(&mut A, &mut ActorioContext<'a, A>, &TCPConnId) + 'a>;\n\n\n\n#[derive(Hash, PartialEq, Eq, Debug)]\n\npub struct TCPConnId(SocketId);\n\n\n\nimpl AsSocketId for TCPConnId {\n\n fn as_socket_id(&self) -> &SocketId {\n\n &self.0\n\n }\n\n}\n\...
Rust
src/lib.rs
dvdplm/rsmq-rust
20fe18287247a81c803b8b539ea1027c9de54736
use failure::{Error, format_err}; use bb8::Pool; use bb8_redis::RedisConnectionManager; use std::{default::Default, ops::DerefMut}; use redis::{from_redis_value, RedisError, RedisResult, Value, ErrorKind as RedisErrorKind}; #[derive(Clone, Debug)] pub struct Queue { pub qname: String, pub vt: u64, pub delay: u64, ...
use failure::{Error, format_err}; use bb8::Pool; use bb8_redis::RedisConnectionManager; use std::{default::Default, ops::DerefMut}; use redis::{from_redis_value, RedisError, RedisResult, Value, ErrorKind as RedisErrorKind}; #[derive(Clone, Debug)] pub struct Queue { pub qname: String, pub vt: u64, pub delay: u64, ...
} impl Default for Queue { fn default() -> Queue { Queue { qname: "".into(), vt: 30, delay: 0, maxsize: 65536, totalrecv: 0, totalsent: 0, created: 0, modified: 0, msgs: 0, hiddenmsgs: 0, } } } #[derive(Clone, Debug)] pub struct Message { pub id: String, pub message: String, pu...
e { ..Default::default() }; q.qname = qname.into(); q.vt = vt.unwrap_or(30); q.delay = delay.unwrap_or(0); q.maxsize = maxsize.unwrap_or(65536); q }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn criterion_benchmark() {\n\n\tlet rsmq = block_on(Rsmq::new(\"redis://127.0.0.1/\", \"rsmq\"))\n\n\t\t.expect(\"Can't instantiate RSMQ\");\n\n\tlet q = Queue::new(\"bench-queue\", Some(60), Some(0), Some(1200));\n\n\tblock_on(rsmq.create_queue(q))\n\n\t\t.expect(\"queue creation faile...
Rust
day3/src/main.rs
thomas9911/aoc-2021
a226244802b69cef33ebed33a44a7537805d0d64
use std::collections::VecDeque; use std::convert::TryFrom; use std::fs::read_to_string; use std::path::Path; fn fetch_file_path() -> &'static str { if Path::new("src/input.txt").exists() { "src/input.txt" } else { "day3/src/input.txt" } } fn parse_input(path: &str) -> Option<Vec<VecDeque<u...
use std::collections::VecDeque; use std::convert::TryFrom; use std::fs::read_to_string; use std::path::Path; fn fetch_file_path() -> &'static str { if Path::new("src/input.txt").exists() { "src/input.txt" } else { "day3/src/input.txt" } } fn parse_input(path: &str) -> Option<Vec<VecDeque<u...
fn part_one(input_file: &str) -> Result<i64, Box<dyn std::error::Error>> { let input = parse_input(input_file).ok_or(String::from("invalid input"))?; let input = transpose_input(input); let most_common_bits = most_common_bits(&input); let gamma = binary_to_number(&most_common_bits); let least_comm...
fn main() -> Result<(), Box<dyn std::error::Error>> { let input_file = fetch_file_path(); println!("part one: {:?}", part_one(input_file)?); println!("part two: {:?}", part_two(input_file)?); Ok(()) }
function_block-full_function
[ { "content": "fn parse_i64(input: &str) -> Result<i64, String> {\n\n input.parse::<i64>().map_err(|x| x.to_string())\n\n}\n\n\n\nimpl FromStr for Direction {\n\n type Err = String;\n\n\n\n fn from_str(input: &str) -> Result<Direction, Self::Err> {\n\n use Direction::*;\n\n\n\n let directi...
Rust
enroll/src/main.rs
galenguyer/gatekeeper-utils
46462104c62327eec80439f1e0e3c308b2cd8a59
extern crate serde; extern crate serde_json; extern crate libgatekeeper_sys; extern crate reqwest; use std::env; use clap::{App, Arg}; use libgatekeeper_sys::{Nfc, Realm}; use serde_json::json; use std::time::Duration; use std::thread; use std::io; use std::fmt; use serde::{Serialize, Deserialize}; use reqwest::Statu...
extern crate serde; extern crate serde_json; extern crate libgatekeeper_sys; extern crate reqwest; use std::env; use clap::{App, Arg}; use libgatekeeper_sys::{Nfc, Realm}; use serde_json::json; use std::time::Duration; use std::thread; use std::io; use std::fmt; use serde::{Serialize, Deserialize}; use reqwest::Statu...
return match res.status() { StatusCode::OK => match res.json::<UserLookup>() { Ok(user) => Ok(user), Err(_) => Err(Box::new(GatekeeperError::Unknown)), }, StatusCode::NOT_FOUND => { println!("User {} doesn't exist!", username); Err(Box::new(Ga...
let res = client.get( prefix + "/users/uuid-by-uid/" + &username.to_string() ).header(AUTHORIZATION, token).send()?;
assignment_statement
[ { "content": "# Gatekeeper Utilities\n\n\n\nGatekeeper powers access to the doors to [Computer Science House](https://csh.rit.edu/)'s special rooms.\n\n\n\nThis repository contains tools for enrolling and manipulating tags.\n\n\n\n# Building\n\n\n\nTo download and build this project on a development machine, ru...
Rust
src/client.rs
jo/wcb-rs
263fc1af02874fab770c5d192294d3d37efd96fa
use crate::cli; use webcryptobox::*; use std::io::{Error, Read, Write}; use std::path::PathBuf; use std::{fs, io}; fn read_file(filename: &PathBuf) -> Vec<u8> { fs::read(&filename).unwrap() } fn read_hex(key: &String) -> Vec<u8> { hex::decode(key).unwrap() } fn read_file_or_stdin(filename: &Option<PathBuf>...
use crate::cli; use webcryptobox::*; use std::io::{Error, Read, Write}; use std::path::PathBuf; use std::{fs, io}; fn read_file(filename: &PathBuf) -> Vec<u8> { fs::read(&filename).unwrap() } fn read_hex(key: &String) -> Vec<u8> { hex::decode(key).unwrap() } fn read_file_or_stdin(filename: &Option<PathBuf>...
.unwrap(); let pem = export_private_key_pem(private_key).unwrap(); write_file_or_stdout(&output_filename, &pem); } cli::Commands::EncryptPrivateKeyTo { filename, private_key_filename, public_key_f...
import_encrypted_private_key_pem( &encrypted_private_key_pem, passphrase.as_bytes(), )
call_expression
[ { "content": "fn main() -> Result<(), Error> {\n\n let outdir = match env::var_os(\"OUT_DIR\") {\n\n None => return Ok(()),\n\n Some(outdir) => outdir,\n\n };\n\n\n\n let mut app = Args::command();\n\n let path = generate_to(Bash, &mut app, \"wcb\", outdir)?;\n\n\n\n println!(\"carg...
Rust
src/fib/stream_ring.rs
rmja/drone-core
01f463ba1fd42655ed8edae79d5ba9dcb308b51b
use crate::{ fib::{self, Fiber}, sync::spsc::ring::{channel, Receiver, SendError, SendErrorKind}, thr::prelude::*, }; use core::{ convert::identity, pin::Pin, task::{Context, Poll}, }; use futures::Stream; #[must_use = "streams do nothing unless you `.await` or poll them"] pub struct FiberStrea...
use crate::{ fib::{self, Fiber}, sync::spsc::ring::{channel, Receiver, SendError, SendErrorKind}, thr::prelude::*, }; use core::{ convert::identity, pin::Pin, task::{Context, Poll}, }; use futures::Stream; #[must_use = "streams do nothing unless you `.await` or poll them"] pub struct FiberStrea...
drop(tx.send_err(err)); break; } }, }, }, fib::Complete(value) => { match convert(value) { Ok(None) => {} ...
, capacity, |_| Ok(()), fib, Ok) } } #[inline] fn add_overwriting_stream<F, T>(self, capacity: usize, fib: F) -> FiberStreamRing<T> where F: Fiber<Input = (), Yield = Option<T>, Return = Option<T>>, F: Send + 'static, T: Send + 'static, { Fib...
random
[ { "content": "#[marker]\n\npub trait YieldNone: Send + 'static {}\n\n\n\nimpl YieldNone for () {}\n\nimpl YieldNone for ! {}\n\n\n\nimpl<T> FiberFuture<T> {\n\n /// Gracefully close this future.\n\n ///\n\n /// The fiber will be removed on a next thread invocation without resuming.\n\n #[inline]\n\n...
Rust
src/lib.rs
neithernut/transiter
e73ad3cdd5aaa154933a061e20e7c96b348f2149
use std::iter::FromIterator; #[derive(Clone, Debug)] pub struct TransIter<F: FnMut(&T) -> I, I: IntoIterator<Item = T>, T> { get_next: F, queue: std::collections::VecDeque<T>, mode: Mode, } impl<F: FnMut(&T) -> I, I: IntoIterator<Item = T>, T> TransIter<F, I, T> { pub fn new...
use std::iter::FromIterator; #[derive(Clone, Debug)] pub struct TransIter<F: FnMut(&T) -> I, I: IntoIterator<Item = T>, T> { get_next: F, queue: std::collections::VecDeque<T>, mode: Mode, } impl<F: FnMut(&T) -> I, I: IntoIterator<Item = T>, T> TransIter<F, I, T> { pub fn new...
} #[derive(Copy, Clone, Debug)] enum Mode { BreadthFirst, DepthFirst, DepthFirstUnordered, } impl Default for Mode { fn default() -> Self { Self::BreadthFirst } } #[derive(Clone, Debug)] pub struct TransPrioQueue<F: FnMut(&T) -> I, I: IntoIterator<Item = T>, T: Ord> { get_next: F, ...
tch self.mode { Mode::BreadthFirst => self.queue.extend(items), Mode::DepthFirst => { let mut items = Vec::from_iter(items); self.queue.reserve(items.len()); while let Some(i) = items.pop() { self.queue.push_...
function_block-function_prefixed
[ { "content": "#[quickcheck]\n\nfn node_count_prio_queue(node: Node) -> bool {\n\n let count = node.count();\n\n node.trans_prio_queue().count() == count\n\n}\n\n\n", "file_path": "src/tests.rs", "rank": 2, "score": 37565.85385757161 }, { "content": "#[derive(Clone, Debug, PartialEq, Eq...
Rust
src/correct/mod.rs
natir/br
8d83017bb1ad1ec7153fa177c1d0c5127aeed6ed
/* Copyright (c) 2020 Pierre Marijon <pmarijon@mmci.uni-saarland.de> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
/* Copyright (c) 2020 Pierre Marijon <pmarijon@mmci.uni-saarland.de> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
} pub(crate) fn add_nuc_to_end(kmer: u64, nuc: u64, k: u8) -> u64 { ((kmer << 2) & mask(k)) ^ nuc } pub(crate) fn alt_nucs(valid_kmer: &set::BoxKmerSet, ori: u64) -> Vec<u64> { next_nucs(valid_kmer, ori >> 2) } pub(crate) fn next_nucs(valid_kmer: &set::BoxKmerSet, kmer: u64) -> Vec<u64> { let mut correc...
fn correct(&self, seq: &[u8]) -> Vec<u8> { let mut correct: Vec<u8> = Vec::with_capacity(seq.len()); if seq.len() < self.k() as usize { return seq.to_vec(); } let mut i = self.k() as usize; let mut kmer = cocktail::kmer::seq2bit(&seq[0..i]); for n in &seq[0...
function_block-full_function
[ { "content": "pub trait KmerSet: Sync {\n\n fn get(&self, kmer: u64) -> bool;\n\n\n\n fn k(&self) -> u8;\n\n}\n\n\n\npub type BoxKmerSet<'a> = Box<dyn KmerSet + 'a>;\n", "file_path": "src/set/mod.rs", "rank": 1, "score": 77363.71832479363 }, { "content": "/// Set the number of threads ...
Rust
zcash_proofs/src/circuit/pedersen_hash.rs
murisi/masp
502f61121b6acac85a61b4ca594a4110e2d0d643
use super::ecc::{EdwardsPoint, MontgomeryPoint}; use bellman::gadgets::boolean::Boolean; use bellman::gadgets::lookup::*; use bellman::{ConstraintSystem, SynthesisError}; pub use zcash_primitives::pedersen_hash::Personalization; use crate::constants::PEDERSEN_CIRCUIT_GENERATORS; fn get_constant_bools(person: &Perso...
use super::ecc::{EdwardsPoint, MontgomeryPoint}; use bellman::gadgets::boolean::Boolean; use bellman::gadgets::lookup::*; use bellman::{ConstraintSystem, SynthesisError}; pub use zcash_primitives::pedersen_hash::Personalization; use crate::constants::PEDERSEN_CIRCUIT_GENERATORS; fn get_constant_bools(person: &Perso...
segment_windows = &segment_windows[1..]; if segment_windows.is_empty() { break; } window_i += 1; } let segment_result = segment_result.expect( "bits is not exhausted due to while condition; thus there mu...
match segment_result { None => { segment_result = Some(tmp); } Some(ref mut segment_result) => { *segment_result = tmp.add( cs.namespace(|| { format!("addition of segment {}, windo...
if_condition
[ { "content": "pub fn prf_a_pk<Scalar, CS>(cs: CS, a_sk: &[Boolean]) -> Result<Vec<Boolean>, SynthesisError>\n\nwhere\n\n Scalar: PrimeField,\n\n CS: ConstraintSystem<Scalar>,\n\n{\n\n prf(\n\n cs,\n\n true,\n\n true,\n\n false,\n\n false,\n\n a_sk,\n\n &...
Rust
src/stat/fsext.rs
LuoZijun/coreutils
9b6f0b02e82b05cbe94d9b4c036e18bdb87b8042
pub use super::uucore::libc; extern crate time; use self::time::Timespec; pub use libc::{c_int, mode_t, strerror, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, S_IFREG, S_IFSOCK, S_IRGRP, S_IROTH, S_IRUSR, S_ISGID, S_ISUID, S_ISVTX, S_IWGRP, S_IWOTH, S_IWUSR, S_IXGRP, S_IXOTH, S_...
pub use super::uucore::libc; extern crate time; use self::time::Timespec; pub use libc::{c_int, mode_t, strerror, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, S_IFREG, S_IFSOCK, S_IRGRP, S_IROTH, S_IRUSR, S_ISGID, S_ISUID, S_ISVTX, S_IWGRP, S_IWOTH, S_IWUSR, S_IXGRP, S_IXOTH, S_...
use std::mem::{self, transmute}; use std::path::Path; use std::borrow::Cow; use std::ffi::CString; use std::convert::{AsRef, From}; use std::error::Error; use std::io::Error as IOError; #[cfg(any(target_os = "linux", target_os = "macos", target_os = "android"))] use libc::statfs as Sstatfs; #[cfg(any(target_os = "l...
e { 'T' } } else if has!(mode, S_IXOTH) { 'x' } else { '-' }); result }
function_block-function_prefixed
[ { "content": "pub fn parse_numeric(fperm: u32, mut mode: &str) -> Result<u32, String> {\n\n let (op, pos) = parse_op(mode, Some('='))?;\n\n mode = mode[pos..].trim_left_matches('0');\n\n if mode.len() > 4 {\n\n Err(format!(\"mode is too large ({} > 7777)\", mode))\n\n } else {\n\n matc...
Rust
src/io/ui.rs
casey/paper
2ad01386f7f05c71860127b2367cba4dfc0003ac
mod error; pub use error::{CreateTerminalError, DisplayCmdFailure, UserActionFailure}; use { core::{ cell::{RefCell, RefMut}, convert::{TryFrom, TryInto}, ops::Deref, time::Duration, }, crossterm::{ cursor::{Hide, MoveTo}, event::{self, Event, KeyCode, Key...
mod error; pub use error::{CreateTerminalError, DisplayCmdFailure, UserActionFailure}; use { core::{ cell::{RefCell, RefMut}, convert::{TryFrom, TryInto}, ops::Deref, time::Duration, }, crossterm::{ cursor::{Hide, MoveTo}, event::{self, Event, KeyCode, Key...
} impl From<KeyEvent> for UserAction { #[inline] fn from(value: KeyEvent) -> Self { Self::Key { code: value.code, modifiers: value.modifiers, } } } #[derive(Debug, ParseDisplay)] #[display("DisplayCmd")] pub(crate) enum DisplayCmd { Rows { ...
fn from(value: Event) -> Self { match value { Event::Resize(columns, rows) => Self::Resize { dimensions: Dimensions { height: rows.saturating_sub(1).into(), width: columns.into(), }, }, ...
function_block-full_function
[ { "content": "#[throws(Failure)]\n\nfn main() {\n\n // Forces compiler to rebuild when Cargo.toml file is changed, needed for app_from_crate.\n\n let _ = include_str!(\"../Cargo.toml\");\n\n\n\n Paper::new(\n\n &(&app_from_crate!()\n\n .arg(\n\n Arg::with_name(\"log\")\...
Rust
common/functions/src/aggregates/aggregate_stddev_pop.rs
mrhamburg/databend
9e4c5ae43de9a77d47cd39cc98ef0aa7a5e29337
use std::alloc::Layout; use std::fmt; use std::marker::PhantomData; use std::sync::Arc; use common_datavalues::prelude::*; use common_datavalues::with_match_primitive_type_id; use common_exception::ErrorCode; use common_exception::Result; use common_io::prelude::*; use num::cast::AsPrimitive; use serde::Deserialize;...
use std::alloc::Layout; use std::fmt; use std::marker::PhantomData; use std::sync::Arc; use common_datavalues::prelude::*; use common_datavalues::with_match_primitive_type_id; use common_exception::ErrorCode; use common_exception::Result; use common_io::prelude::*; use num::cast::AsPrimitive; use serde::Deserialize;...
fn serialize(&self, place: StateAddr, writer: &mut BytesMut) -> Result<()> { let state = place.get::<AggregateStddevPopState>(); serialize_into_buf(writer, state) } fn deserialize(&self, place: StateAddr, reader: &mut &[u8]) -> Result<()> { let state = place.get::<AggregateStddevP...
fn accumulate_row(&self, place: StateAddr, columns: &[ColumnRef], row: usize) -> Result<()> { let column: &PrimitiveColumn<T> = unsafe { Series::static_cast(&columns[0]) }; let state = place.get::<AggregateStddevPopState>(); let v: f64 = unsafe { column.value_unchecked(row).as_() }; sta...
function_block-full_function
[]
Rust
src/oauth/google/mod.rs
saturn-xiv/peony
2161b89624b12bcea77c639a18569f38b8736187
pub mod openid; pub mod photo; pub mod youtube; use std::collections::HashMap; use std::fmt; use std::str::FromStr; use actix_web::http::StatusCode; use rand::Rng; use serde::de::DeserializeOwned; use url::{form_urlencoded, Url}; use super::super::{ errors::{Error, Result}, request::https_client, }; #[deriv...
pub mod openid; pub mod photo; pub mod youtube; use std::collections::HashMap; use std::fmt; use std::str::FromStr; use actix_web::http::StatusCode; use rand::Rng; use serde::de::DeserializeOwned; use url::{form_urlencoded, Url}; use super::super::{ errors::{Error, Result}, request::https_client, }; #[deriv...
pub async fn get<Q: DeserializeOwned>(&self, action: &str, token: &str) -> Result<Q> { let mut res = https_client()? .bearer_auth(token) .finish() .get(action) .send() .await?; if res.status().is_success() { return Ok(res.json...
pub fn oauth2(&self, scope: Vec<Scope>, redirect_uri: &str) -> (String, String, String) { let mut rng = rand::thread_rng(); let nonce = rng.gen::<u32>().to_string(); let state = rng.gen::<u32>().to_string(); let url = form_urlencoded::Serializer::new( "https://accounts.googl...
function_block-full_function
[ { "content": "pub fn hostname() -> Result<String> {\n\n let mut buf = [0u8; 64];\n\n let it = nix::unistd::gethostname(&mut buf)?.to_str()?;\n\n Ok(it.to_string())\n\n}\n\n\n", "file_path": "src/sys/mod.rs", "rank": 0, "score": 276874.06456342764 }, { "content": "// https://en.grava...
Rust
examples/scaling/lib.rs
lykhouzov/rust-wasm-webgl
cfebda351f3c9fa3c3813c317fb40ad59e598a20
extern crate js_sys; extern crate wasm_bindgen; extern crate web_sys; use js_sys::{Float32Array, Uint16Array, WebAssembly}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::WebGlRenderingContext; #[allow(dead_code)] mod utils; use utils::{compile_shader, link_program, set_panic_hook}; #[allow(non_...
extern crate js_sys; extern crate wasm_bindgen; extern crate web_sys; use js_sys::{Float32Array, Uint16Array, WebAssembly}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::WebGlRenderingContext; #[allow(dead_code)] mod utils; use utils::{compile_shader, link_program, set_panic_hook}; #[allow(non_...
ates; attribute vec3 color; varying vec3 vColor; uniform mat4 u_xformMatrix; void main(void) { gl_Position = u_xformMatrix * vec4(coordinates, 1.0); vColor = color; } "#; let vertShader = compile_shader(&gl, WebGlRenderingContext::VERTEX_SHADER, vertCode)?; let fragCode = r#"precision mediump f...
c_hook(); /*============ Creating a canvas =================*/ let document = web_sys::window().unwrap().document().unwrap(); let canvas = document.get_element_by_id("canvas").unwrap(); let canvas: web_sys::HtmlCanvasElement = canvas.dyn_into::<web_sys::HtmlCanvasElement>()?; let gl = canvas ...
random
[ { "content": "#[allow(non_snake_case)]\n\n#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n set_panic_hook();\n\n /*============ Creating a canvas =================*/\n\n let document = web_sys::window().unwrap().document().unwrap();\n\n let canvas = document.get_element_by_id(\"...
Rust
src/utils.rs
nrot/image-png
0069402d348bf3bf7696163b5ec88b85147b35d5
use std::iter::{repeat, StepBy}; use std::ops::Range; #[inline(always)] pub fn unpack_bits<F>(buf: &mut [u8], channels: usize, bit_depth: u8, func: F) where F: Fn(u8, &mut [u8]), { if buf.len() < channels { return; } let bits = buf.len() / channels * bit_depth as usize; let extra_bit...
use std::iter::{repeat, StepBy}; use std::ops::Range; #[inline(always)] pub fn unpack_bits<F>(buf: &mut [u8], channels: usize, bit_depth: u8, func: F) where F: Fn(u8, &mut [u8]), { if buf.len() < channels { return; } let bits = buf.len() / channels * bit_depth as usize; let extra_bit...
#[derive(Clone)] pub(crate) struct Adam7Iterator { line: u32, lines: u32, line_width: u32, current_pass: u8, width: u32, height: u32, } impl Adam7Iterator { pub fn new(width: u32, height: u32) -> Adam7Iterator { let mut this = Adam7Iterator { line: 0, lines...
pub fn expand_trns_line16(buf: &mut [u8], trns: &[u8], channels: usize) { let c2 = 2 * channels; if buf.len() < (c2 + 2) { return; } let i = (0..=buf.len() / (c2 + 2) * c2 - c2).rev().step_by(c2); let j = (0..=buf.len() - (c2 + 2)).rev().step_by(c2 + 2); for (i, j) in i.zip(j) { ...
function_block-full_function
[ { "content": "fn expand_gray_u8(buffer: &mut [u8], info: &Info) {\n\n let rescale = true;\n\n let scaling_factor = if rescale {\n\n (255) / ((1u16 << info.bit_depth as u8) - 1) as u8\n\n } else {\n\n 1\n\n };\n\n if let Some(ref trns) = info.trns {\n\n utils::unpack_bits(buff...