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
lain/src/buffer.rs
Mrmaxmeier/lain
f4ae991c30abda5860ff7ac3933d91cc62e9c2a1
use crate::traits::*; use crate::types::UnsafeEnum; use byteorder::{ByteOrder, WriteBytesExt}; use paste::paste; use std::io::Write; impl<T> SerializedSize for [T] where T: SerializedSize, { #[inline] default fn serialized_size(&self) -> usize { trace!("using default serialized_size for array"); ...
use crate::traits::*; use crate::types::UnsafeEnum; use byteorder::{ByteOrder, WriteBytesExt}; use paste::paste; use std::io::Write; impl<T> SerializedSize for [T] where T: SerializedSize, { #[inline] default fn serialized_size(&self) -> usize { trace!("using default serialized_size for array"); ...
} impl<T, const N: usize> BinarySerialize for [T; N] where T: BinarySerialize, { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { self.as_ref().binary_serialize::<W, E>(buffer) } } impl<T, I> BinarySerialize for UnsafeEnum<T, I> where T: Bina...
serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { let mut bytes_written = 0; for item in self.iter() { bytes_written += item.binary_serialize::<W, E>(buffer); } bytes_written }
function_block-function_prefixed
[ { "content": "fn bench_serialize_1000(c: &mut Criterion) {\n\n let struct_size = std::mem::size_of::<NestedStruct>();\n\n let function_name = format!(\n\n \"serialize BigEndian with struct of size 0x{:X}\",\n\n struct_size\n\n );\n\n\n\n let nested = TestStruct {\n\n single_byte...
Rust
rust token listener/test/src/bin/test2.rs
everscale-experts/hackathon_new
dafaaea8b7f70cfdb9162a1b6752ac31d6a4a5df
use ureq::json; use std::convert::TryInto; use serde::Serialize; use serde::Serializer; use crypto::blake2b; use crypto::Prefix; use crypto::WithPrefix; use crypto::WithoutPrefix; use crypto::base58check::{FromBase58Check, ToBase58Check}; use crypto::FromBase58CheckError; use crypto::NotMatchingPrefixError; use types::...
use ureq::json; use std::convert::TryInto; use serde::Serialize; use serde::Serializer; use crypto::blake2b; use crypto::Prefix; use crypto::WithPrefix; use crypto::WithoutPrefix; use crypto::base58check::{FromBase58Check, ToBase58Check}; use crypto::FromBase58CheckError; use crypto::NotMatchingPrefixError; use types::...
ializer { serializer.serialize_str( &self.to_base58check() ) } } fn transfer() { let params = json!("{ to: \"KT1MeAHVkJp87r9neejmaxCfaccoUfXAssy1\", amount: 1, parameter: { entrypoint: \"transfer\", value: { prim: \...
not matching prefix")] NotMatchingPrefix, #[error("invalid size")] InvalidSize, } impl From<FromBase58CheckError> for FromPrefixedBase58CheckError { fn from(err: FromBase58CheckError) -> Self { match err { FromBase58CheckError::InvalidBase58 => { Self::InvalidBase58 ...
random
[ { "content": "/// A trait for converting a value to base58 encoded string.\n\npub trait ToBase58Check {\n\n /// Converts a value of `self` to a base58 value, returning the owned string.\n\n fn to_base58check(&self) -> String;\n\n}\n\n\n", "file_path": "rust token listener/crypto/src/base58check.rs", ...
Rust
src/clean.rs
larsluthman/cargo-llvm-cov
0a6842f901fda7d08be5211366e4d632c30782a7
use std::path::Path; use anyhow::Result; use cargo_metadata::PackageId; use regex::Regex; use walkdir::WalkDir; use crate::{ cargo::{self, Workspace}, cli::{CleanOptions, ManifestOptions}, context::Context, env::Env, fs, term, }; pub(crate) fn run(mut options: CleanOptions) -> Result<()> { ...
use std::path::Path; use anyhow::Result; use cargo_metadata::PackageId; use regex::Regex; use walkdir::WalkDir; use crate::{ cargo::{self, Workspace}, cli::{CleanOptions, ManifestOptions}, context::Context, env::Env, fs, term, }; pub(crate) fn run(mut options: CleanOptions) -> Result<()> { ...
pub(crate) fn clean_partial(cx: &Context) -> Result<()> { if cx.no_run || cx.cov.no_report { return Ok(()); } clean_ws_inner(&cx.ws, &cx.workspace_members.included, cx.build.verbose > 1)?; let package_args: Vec<_> = cx .workspace_members .included .iter() .fla...
for dir in &[&ws.target_dir, &ws.output_dir] { rm_rf(dir, options.verbose != 0)?; } return Ok(()); } clean_ws(&ws, &ws.metadata.workspace_members, &options.manifest, options.verbose)?; Ok(()) }
function_block-function_prefix_line
[ { "content": "fn package_root(env: &Env, manifest_path: Option<&Utf8Path>) -> Result<Utf8PathBuf> {\n\n let package_root = if let Some(manifest_path) = manifest_path {\n\n manifest_path.to_owned()\n\n } else {\n\n locate_project(env)?.into()\n\n };\n\n Ok(package_root)\n\n}\n\n\n", ...
Rust
src/full_node/apply_block.rs
NilFoundation/rust-ton
ea970ca3a96f93f2ad48576fd5d8f5503ad2040d
use crate::{ block::BlockStuff, engine_traits::EngineOperations, shard_state::ShardStateStuff }; use std::{ops::Deref, sync::Arc}; use storage::block_handle_db::BlockHandle; use ton_types::{error, fail, Result}; use ton_block::BlockIdExt; pub const MAX_RECURSION_DEPTH: u32 = 16; pub async fn apply_block( hand...
use crate::{ block::BlockStuff, engine_traits::EngineOperations, shard_state::ShardStateStuff }; use std::{ops::Deref, sync::Arc}; use storage::block_handle_db::BlockHandle; use ton_types::{error, fail, Result}; use ton_block::BlockIdExt; pub const MAX_RECURSION_DEPTH: u32 = 16;
async fn check_prev_blocks( prev_ids: &(BlockIdExt, Option<BlockIdExt>), engine: &Arc<dyn EngineOperations>, mc_seq_no: u32, pre_apply: bool, recursion_depth: u32 ) -> Result<()> { match prev_ids { (prev1_id, Some(prev2_id)) => { let mut apply_prev_futures = Vec::with_capac...
pub async fn apply_block( handle: &Arc<BlockHandle>, block: &BlockStuff, mc_seq_no: u32, engine: &Arc<dyn EngineOperations>, pre_apply: bool, recursion_depth: u32 ) -> Result<()> { if handle.id() != block.id() { fail!("Block id mismatch in apply block: {} vs {}", handle.id(), block.i...
function_block-full_function
[]
Rust
src/lexer/mod.rs
rickspencer3/sabre
de0de9f3bc14e85b5443046c7fe21cd4b142e8e5
/** * Copyright 2020 Garrit Franke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
/** * Copyright 2020 Garrit Franke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
fn eat_string(&mut self) { loop { match self.first() { '"' | '\'' => break, '\n' => panic!( "String does not end on same line. At {}:{}", self.pos().line, self.pos().offset ...
fn eat_digits(&mut self) -> bool { let mut has_digits = false; loop { match self.first() { '_' => { self.bump(); } '0'..='9' => { has_digits = true; self.bump(); } ...
function_block-full_function
[ { "content": "pub fn highlight_position_in_file(input: String, position: Position) -> String {\n\n // TODO: Chain without collecting in between\n\n input\n\n .chars()\n\n .skip(position.raw)\n\n .take_while(|c| c != &'\\n')\n\n .collect::<String>()\n\n .chars()\n\n ...
Rust
examples/binance_websockets.rs
vikulikov/binance-rs-async
40c0907e67d629d135dea562f56e5629e5046143
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::RwLock; use futures::stream::StreamExt; use serde_json::from_str; use tokio_tungstenite::tungstenite::Message; use binance::api::*; use binance::userstream::*; use binance::websockets::*; use binance::ws_model::{CombinedStreamEvent, WebsocketEvent, Websock...
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::RwLock; use futures::stream::StreamExt; use serde_json::from_str; use tokio_tungstenite::tungstenite::Message; use binance::api::*; use binance::userstream::*; use binance::websockets::*; use binance::ws_model::{CombinedStreamEvent, WebsocketEvent, Websock...
=> { if msg.is_empty() { continue; } let event: CombinedStreamEvent<WebsocketEventUntag> = from_str(msg.as_str()).unwrap(); eprintln!("event = {:?}", event); } ...
t"); let mut web_socket: WebSockets<'_, WebsocketEventUntag> = WebSockets::new(|events: WebsocketEventUntag| { if let WebsocketEventUntag::BookTicker(tick_event) = events { println!("{:?}", tick_event) } Ok(()) }); web_socket.connect(&book_ticker).await.unwrap(); i...
random
[ { "content": "pub fn kline_stream(symbol: &str, interval: &str) -> String { format!(\"{}@kline_{}\", symbol, interval) }\n\n\n", "file_path": "src/websockets.rs", "rank": 0, "score": 149192.0712904504 }, { "content": "pub fn trade_stream(symbol: &str) -> String { format!(\"{}@trade\", symbol...
Rust
src/adoptopenjdk/mod.rs
wherkamp/adoptopenjdk-installer
d9b94c16d20fbcd4fbd05b15b070a877daa088d2
use reqwest::{StatusCode, Response, Body, Client}; use std::error::Error; use std::fmt::{Formatter, Display}; use crate::adoptopenjdk::response::AvailableReleases; use serde::de::DeserializeOwned; use reqwest::header::{USER_AGENT, HeaderValue, HeaderMap}; use std::path::{Path, PathBuf}; use crate::utils::utils; use st...
use reqwest::{StatusCode, Response, Body, Client}; use std::error::Error; use std::fmt::{Formatter, Display}; use crate::adoptopenjdk::response::AvailableReleases; use serde::de::DeserializeOwned; use reqwest::header::{USER_AGENT, HeaderValue, HeaderMap}; use std::path::{Path, PathBuf}; use crate::utils::utils; use st...
dest: &str) -> String { format!("https://api.adoptium.net/v3/{}", dest) } pub async fn respond<T: DeserializeOwned>( result: Result<Response, reqwest::Error>, ) -> Result<T, AdoptOpenJDKError> { if let Ok(response) = result { let code = response.status(); ...
onse, reqwest::Error> { let string = self.build_url(url); let mut headers = HeaderMap::new(); headers.insert( USER_AGENT, HeaderValue::from_str(&*self.user_agent).unwrap(), ); self.client.get(string).headers(headers).send().await } pub async f...
random
[ { "content": "/// Stolen from Tar depend and modified to fit my needs\n\npub fn unpack(mut archive: Archive<GzDecoder<File>>, dst: &Path) -> Result<String, AdoptOpenJDKError> {\n\n let dst = &dst.canonicalize().unwrap_or(dst.to_path_buf());\n\n let mut first = None;\n\n let mut directories = Vec::new()...
Rust
src/lib.rs
FirelightFlagboy/egui_sdl2_gl
70cde948a769ce841c72360b80da73e16b675c4f
#![warn(clippy::all)] #![allow(clippy::single_match)] pub use egui; pub use gl; pub use sdl2; pub mod painter; #[cfg(feature = "use_epi")] pub use epi; use painter::Painter; #[cfg(feature = "use_epi")] use std::time::Instant; use { egui::*, sdl2::{ event::WindowEvent, keyboard::{Keycode, Mod}, ...
#![warn(clippy::all)] #![allow(clippy::single_match)] pub use egui; pub use gl; pub use sdl2; pub mod painter; #[cfg(feature = "use_epi")] pub use epi; use painter::Painter; #[cfg(feature = "use_epi")] use std::time::Instant; use { egui::*, sdl2::{ event::WindowEvent, keyboard::{Keycode, Mod}, ...
} KeyDown { keycode, keymod, .. } => { let key_code = match keycode { Some(key_code) => key_code, _ => return, }; let key = match translate_virtual_key_code(key_code) { Some(key) => key, ...
}; (painter, _self) } pub fn process_input( &mut self, window: &sdl2::video::Window, event: sdl2::event::Event, painter: &mut Painter, ) { input_to_egui(window, event, painter, self); } pub fn process_output(&mut self, window: &sdl2::video::Win...
random
[ { "content": "#[derive(Default)]\n\nstruct UserTexture {\n\n size: (usize, usize),\n\n\n\n /// Pending upload (will be emptied later).\n\n pixels: Vec<u8>,\n\n\n\n /// Lazily uploaded\n\n texture: Option<GLuint>,\n\n\n\n /// For user textures there is a choice between\n\n /// Linear (defaul...
Rust
test/src/specs/tx_pool/send_large_cycles_tx.rs
chuijiaolianying/ckb
04c8effb7c77f9cb86306090c7f7747dc122ada7
use super::{new_block_assembler_config, type_lock_script_code_hash}; use crate::utils::wait_until; use crate::{Net, Node, Spec, DEFAULT_TX_PROPOSAL_WINDOW}; use ckb_app_config::CKBAppConfig; use ckb_crypto::secp::{Generator, Privkey}; use ckb_hash::{blake2b_256, new_blake2b}; use ckb_types::{ bytes::Bytes, core...
use super::{new_block_assembler_config, type_lock_script_code_hash}; use crate::utils::wait_until; use crate::{Net, Node, Spec, DEFAULT_TX_PROPOSAL_WINDOW}; use ckb_app_config::CKBAppConfig; use ckb_crypto::secp::{Generator, Privkey}; use ckb_hash::{blake2b_256, new_blake2b}; use ckb_types::{ bytes::Bytes, core...
mut Net) { let mut node0 = net.nodes.remove(0); let node1 = &net.nodes[0]; node0.stop(); node0.edit_config_file( Box::new(|_| ()), Box::new(move |config| { config.tx_pool.max_tx_verify_cycles = std::u32::MAX.into(); })...
let block: BlockView = node0.get_tip_block(); assert_eq!(block.transactions()[1], tx); node0.connect(&node1); info!("Wait block relay to node1"); let result = wait_until(60, || { let block2: BlockView = node1.get_tip_block(); block2.hash() == block.hash() ...
random
[ { "content": "pub fn assert_new_block_committed(node: &Node, committed: &[TransactionView]) {\n\n let block = node.new_block(None, None, None);\n\n if committed != &block.transactions()[1..] {\n\n print_proposals_in_window(node);\n\n assert_eq!(committed, &block.transactions()[1..]);\n\n ...
Rust
src/connectivity/bluetooth/core/bt-gap/src/host_device.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
use { fidl::endpoints::ClientEnd, fidl_fuchsia_bluetooth::DeviceClass, fidl_fuchsia_bluetooth::PeerId as FidlPeerId, fidl_fuchsia_bluetooth_control::{ self as control, HostData, InputCapabilityType, OutputCapabilityType, PairingDelegateMarker, PairingOptions, }, fidl_fuchsia_bl...
use { fidl::endpoints::ClientEnd, fidl_fuchsia_bluetooth::DeviceClass, fidl_fuchsia_bluetooth::PeerId as FidlPeerId, fidl_fuchsia_bluetooth_control::{ self as control, HostData, InputCapabilityType, OutputCapabilityType, PairingDelegateMarker, PairingOptions, }, fidl_fuchsia_bl...
; if let Err(e) = listener.on_new_host_bond(data.into()).await { fx_log_err!("Failed to persist bonding data: {:#?}", e); } } }; } Ok(()) } async fn watch_state(host: Arc<RwLock<HostDevice>>) -> types::Result<()> { loop { refre...
match data.try_into() { Err(e) => { fx_log_err!("Invalid bonding data, ignoring: {:#?}", e); continue; } Ok(data) => data, }
if_condition
[]
Rust
examples/bindless/main.rs
peterwmwong/metal-rs
1aaa9033a22b2af7ff8cae2ed412a4733799c3d3
use metal::*; use objc::rc::autoreleasepool; const BINDLESS_TEXTURE_COUNT: NSUInteger = 100_000; fn main() { autoreleasepool(|| { let device = Device::system_default().expect("no device found"); /* MSL struct Textures { texture2d<float> texture; }; ...
use metal::*; use objc::rc::autoreleasepool; const BINDLESS_TEXTURE_COUNT: NSUInteger = 100_000;
fn main() { autoreleasepool(|| { let device = Device::system_default().expect("no device found"); /* MSL struct Textures { texture2d<float> texture; }; struct BindlessTextures { device Textures *textures; }; */ ...
function_block-full_function
[ { "content": "#[allow(non_camel_case_types)]\n\ntype dispatch_block_t = *const Block<(), ()>;\n\n\n\n#[cfg_attr(\n\n any(target_os = \"macos\", target_os = \"ios\"),\n\n link(name = \"System\", kind = \"dylib\")\n\n)]\n\n#[cfg_attr(\n\n not(any(target_os = \"macos\", target_os = \"ios\")),\n\n link(...
Rust
lib/emscripten/build/emtests.rs
cdetrio/wasmer
b68b109b7de1d27a334591fdeeda475c808c812a
use glob::glob; use std::fs; use std::path::Path; use std::path::PathBuf; use std::process::Command; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; static BANNER: &str = "// Rust test file autogenerated with cargo build (build/emtests.rs). // Please do NOT modify it by hand, as it will be reset...
use glob::glob; use std::fs; use std::path::Path; use std::path::PathBuf; use std::process::Command; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; static BANNER: &str = "// Rust test file autogenerated with cargo build (build/emtests.rs). // Please do NOT modify it by hand, as it will be reset...
Vec<String> = Vec::new(); let ignores = read_ignore_list(); for ext in EXTENSIONS.iter() { for entry in glob(&format!("emtests/*.{}", ext)).unwrap() { match entry { Ok(path) => { let test = path.to_str().unwrap(); if !EXCLUDES.it...
&module_path).is_file() { println!("Path not found to test module: {}", module_path); None } else if !Path::new(&test_output_path).is_file() { println!("Path not found to test output: {}", module_path); None } else { let contents = format!( "#[test]{ignore} fn...
random
[ { "content": "pub fn abort_with_message(ctx: &mut Ctx, message: &str) {\n\n debug!(\"emscripten::abort_with_message\");\n\n println!(\"{}\", message);\n\n _abort(ctx);\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 0, "score": 257234.96267437495 }, { "content": "...
Rust
src/cpu/addressing_mode.rs
Erj4/nes-emulator
13f5e1bac138802f1a6bb383227b9d4f92b092ea
use crate::{cpu, memory}; #[derive(Debug)] pub enum ResolvableAddress { ZeroPage(cpu::Int), XIndexedZeroPage(cpu::Int), YIndexedZeroPage(cpu::Int), Absolute(memory::Address), XIndexedAbsolute(memory::Address), YIndexedAbsolute(memory::Address), ...
use crate::{cpu, memory}; #[derive(Debug)] pub enum ResolvableAddress { ZeroPage(cpu::Int), XIndexedZeroPage(cpu::Int), YIndexedZeroPage(cpu::Int), Absolute(memory::Address), XIndexedAbsolute(memory::Address), YIndexedAbsolute(memory::Address), ...
} } } #[derive(Debug)] pub enum Resolvable<V> { Resolved(V), Resolvable(ResolvableAddress), } impl SteppableWithCPU for Resolvable<cpu::Int> { type Output = cpu::Int; fn step(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<Self::Output> { ResolvableAddress::step(resolvable, cpu) ...
match Self::step(resolvable, cpu) { Resolvable::Resolved(resolved) => break resolved, Resolvable::Resolvable(unresolved) => resolvable = unresolved, }
if_condition
[ { "content": "#[derive(Error, Debug)]\n\nenum AddressExprError {\n\n #[error(\n\n \"address {address:#X?} is outside range (expected {:#X?} <= address <= {:#X?})\",\n\n memory::Address::MIN,\n\n memory::Address::MAX\n\n )]\n\n AddressOutOfRange {\n\n address: evalexpr::IntType,\n\n source: st...
Rust
day7/main2.rs
allonsy/advent2017
644dd55ca9cc4319136123126c40330e9ba52de0
mod util; use std::cell::RefCell; use std::collections::HashMap; use std::collections::HashSet; use std::rc::Rc; type Pointer = Rc<RefCell<ProgramTower>>; #[derive(Debug)] struct ProgramTower { name: String, weight: i32, children: HashMap<String, Pointer>, } impl ProgramTower { fn new(name: String, ...
mod util; use std::cell::RefCell; use std::collections::HashMap; use std::collections::HashSet; use std::rc::Rc; type Pointer = Rc<RefCell<ProgramTower>>; #[derive(Debug)] struct ProgramTower { name: String, weight: i32, children: HashMap<String, Pointer>, } impl ProgramTower { fn new(name: String, ...
(bad_child, None); } fn get_bad_weight(children: &HashMap<String, Pointer>) -> Option<(i64, Pointer)> { let mut freq_map: HashMap<i64, (i32, Pointer)> = HashMap::new(); for (_, child) in children { let this_weight = get_tower_weight(child); freq_map.entry(this_weight).or_insert((0, child.clone(...
d_weight { None => { child_weight = Some(actual_child_weight); } Some(wt) => { if wt != actual_child_weight { return false; } } } } return true; } fn analyze_children(children: &HashMap<S...
random
[ { "content": "fn eval_condition(state: &mut HashMap<String, i32>, condition: &Condition) -> bool {\n\n let register_value = get_register_value(state, condition.register.clone());\n\n let operand = condition.operand;\n\n\n\n match condition.relation {\n\n Relation::LT => return register_value < o...
Rust
sdk/data_cosmos/src/operations/get_collection.rs
adeschamps/azure-sdk-for-rust
027f111683f02fd1c43bc041ac6902e87edc69d8
use crate::prelude::*; use crate::headers::from_headers::*; use azure_core::headers::{ content_type_from_headers, etag_from_headers, session_token_from_headers, }; use azure_core::{collect_pinned_stream, Context, Response as HttpResponse}; use chrono::{DateTime, Utc}; #[derive(Debug, Clone)] pub struct GetCollect...
use crate::prelude::*; use crate::headers::from_headers::*; use azure_core::headers::{ content_type_from_headers, etag_from_headers, session_token_from_headers, }; use azure_core::{collect_pinned_stream, Context, Response as HttpResponse}; use chrono::{DateTime, Utc}; #[derive(Debug, Clone)] pub struct GetCollect...
} }
Ok(Self { collection: serde_json::from_slice(&body)?, last_state_change: last_state_change_from_headers(&headers)?, etag: etag_from_headers(&headers)?, collection_partition_index: collection_partition_index_from_headers(&headers)?, collection_service_index: co...
call_expression
[]
Rust
libchordr/src/test_helpers.rs
chorddown/chordr
f28327dfd2d026076d557a926ca8a33063af82fc
use crate::models::meta::BNotation; use crate::models::user::{User, Username}; use crate::parser::{MetaInformation, Node}; use crate::prelude::Password; use crate::tokenizer::{Modifier, Token}; #[cfg(test)] pub fn get_test_parser_input() -> Vec<Token> { vec![ Token::headline(1, "Swing Low Sweet Chariot", M...
use crate::models::meta::BNotation; use crate::models::user::{User, Username}; use crate::parser::{MetaInformation, Node}; use crate::prelude::Password; use crate::tokenizer::{Modifier, Token}; #[cfg(test)] pub fn get_test_parser_input() -> Vec<Token> { vec![ Token::headline(1, "Swing Low Sweet Chariot", M...
pub fn get_test_ast_w_inline_metadata() -> Node { Node::Document(vec![ Node::section( 1, "Swing Low Sweet Chariot", Modifier::None, vec![Node::newline()], ), Node::meta("Artist: The Fantastic Corns").unwrap(), Node::newline(), ...
Modifier::Chorus, vec![ Node::newline(), Node::text("Swing "), Node::chord_text_pair("D", "low, sweet ").unwrap(), Node::chord_text_pair("G", "chari").unwrap(), Node::chord_text_pair("D", "ot.").unwrap(), ], ...
function_block-function_prefix_line
[ { "content": "#[deprecated(note = \"Please use the `Token`s directly\")]\n\npub fn token_lines_to_tokens(token_lines: Vec<Vec<Token>>) -> Vec<Token> {\n\n let mut stream = vec![];\n\n for line in token_lines {\n\n for token in line {\n\n stream.push(token);\n\n }\n\n }\n\n\n\n ...
Rust
vulkano/src/renderer_vulkano.rs
paulpage/rust_ldraw
bed7a738bc95b71b59e5d6d0b3485139a1cfe66d
use cgmath::{Matrix3, Matrix4, Point3, Rad, Vector3}; use vulkano::buffer::cpu_pool::CpuBufferPool; use std::iter; use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer}; use vulkano::command_buffer::{AutoCommandBufferBuilder, DynamicState}; use vulkano::descriptor::descriptor_set::PersistentDescriptorSet; use vulkano...
use cgmath::{Matrix3, Matrix4, Point3, Rad, Vector3}; use vulkano::buffer::cpu_pool::CpuBufferPool; use std::iter; use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer}; use vulkano::command_buffer::{AutoCommandBufferBuilder, DynamicState}; use vulkano::descriptor::descriptor_set::PersistentDescriptorSet; use vulkano...
s .iter() .map(|image| { Arc::new( Framebuffer::start(render_pass.clone()) .add(image.clone()) .unwrap() .add(depth_buffer.clone()) .unwrap() .build() .unwr...
function_block-function_prefixed
[ { "content": "fn unproject(source: Vector3<f32>, view: Matrix4<f32>, proj: Matrix4<f32>) -> Vector3<f32> {\n\n let view_proj = (proj * view).invert().unwrap();\n\n let q = view_proj * Vector4::new(source.x, source.y, source.z, 1.0);\n\n Vector3::new(q.x / q.w, q.y / q.w, q.z / q.w)\n\n}\n\n\n", "fi...
Rust
src/scope.rs
redzic/grass
37c1ada66418fdbb87968ede91efb9be83a80afa
use std::collections::HashMap; use codemap::Spanned; use crate::{ atrule::{Function, Mixin}, builtin::GLOBAL_FUNCTIONS, common::Identifier, error::SassResult, value::Value, }; #[derive(Debug, Clone, Default)] pub(crate) struct Scope { vars: HashMap<Identifier, Spanned<Value>>, mixins: Has...
use std::collections::HashMap; use codemap::Spanned; use crate::{ atrule::{Function, Mixin}, builtin::GLOBAL_FUNCTIONS, common::Identifier, error::SassResult, value::Value, }; #[derive(Debug, Clone, Default)] pub(crate) struct Scope { vars: HashMap<Identifier, Spanned<Value>>, mixins: Has...
pub fn get_fn<T: Into<Identifier>>( &self, name: Spanned<T>, global_scope: &Scope, ) -> SassResult<Function> { let name = name.map_node(Into::into); match self.functions.get(&name.node) { Some(v) => Ok(v.clone()), None => global_scope.get_fn_no_g...
fn get_fn_no_global(&self, name: &Spanned<Identifier>) -> SassResult<Function> { match self.functions.get(&name.node) { Some(v) => Ok(v.clone()), None => Err(("Undefined function.", name.span).into()), } }
function_block-full_function
[ { "content": "pub fn many_variable_redeclarations(c: &mut Criterion) {\n\n c.bench_function(\"many_variable_redeclarations\", |b| {\n\n b.iter(|| {\n\n StyleSheet::new(black_box(\n\n include_str!(\"many_variable_redeclarations.scss\").to_string(),\n\n ))\n\n ...
Rust
src/advisories/diags.rs
svenstaro/cargo-deny
4d7a236d6b4db82fc62052bc67dd808695498426
use crate::{ diag::{Check, Diag, Diagnostic, KrateCoord, Label, Pack, Severity}, Krate, LintLevel, }; use rustsec::advisory::{Id, Informational, Metadata, Versions}; fn get_notes_from_advisory(advisory: &Metadata) -> Vec<String> { let mut n = vec![format!("ID: {}", advisory.id)]; if let Some(url) = adv...
use crate::{ diag::{Check, Diag, Diagnostic, KrateCoord, Label, Pack, Severity}, Krate, LintLevel, }; use rustsec::advisory::{Id, Informational, Metadata, Versions}; fn get_notes_from_advisory(advisory: &Metadata) -> Vec<String> { let mut n = vec![format!("ID: {}", advisory.id)]; if let Some(url) = adv...
) .with_message("detected yanked crate") .with_code("A005") .with_labels(vec![self .krate_spans .label_for_index(krate_index.index(), "yanked version")]), ); pack } pub(crate) fn diag_for_index_failure<D: std::fmt::Display>(&s...
match self.cfg.yanked.value { LintLevel::Allow => Severity::Help, LintLevel::Deny => Severity::Error, LintLevel::Warn => Severity::Warning, }
if_condition
[ { "content": "#[inline]\n\nfn matches<'v>(arr: &'v [cfg::Skrate], details: &Krate) -> Option<Vec<ReqMatch<'v>>> {\n\n let matches: Vec<_> = arr\n\n .iter()\n\n .enumerate()\n\n .filter_map(|(index, req)| {\n\n if req.value.name == details.name\n\n && crate::matc...
Rust
wrflib/examples/example_charts/src/lines_basic.rs
cruise-automation/webviz-rust-framework
09bc1e0f72eb95a3ace45d2284bb4eb4ea5eb3c8
use wrflib::*; use wrflib_components::*; use crate::ChartExample; pub(crate) struct LinesBasic { pub(crate) chart: Chart, pub(crate) datasets: Vec<Vec<f32>>, pub(crate) randomize_btn: Button, pub(crate) add_dataset_btn: Button, pub(crate) add_data_btn: Button, pub(crate) remove_dataset_btn: Bu...
use wrflib::*; use wrflib_components::*; use crate::ChartExample; pub(crate) struct LinesBasic { pub(crate) chart: Chart, pub(crate) datasets: Vec<Vec<f32>>, pub(crate) randomize_btn: Button, pub(crate) add_dataset_btn: Button, pub(crate) add_data_btn: Button, pub(crate) remove_dataset_btn: Bu...
ret.add_dataset(); ret.add_dataset(); ret } } impl LinesBasic { pub(crate) fn with_dark_style() -> Self { Self { style: CHART_STYLE_DARK, ..Self::default() } } pub(crate) fn with_zoom() -> Self { Self { zoom_enabled: true, ..Self::default() } } ...
let mut ret = Self { chart: Chart::default(), datasets: vec![], randomize_btn: Button::default(), add_dataset_btn: Button::default(), add_data_btn: Button::default(), remove_dataset_btn: Button::default(), remove_data_btn: Button::defau...
assignment_statement
[ { "content": "#[derive(Default)]\n\nstruct Tooltip {\n\n value: f32,\n\n path: String,\n\n}\n\n\n\nimpl ChartTooltipRenderer for Tooltip {\n\n fn draw_tooltip(&self, cx: &mut Cx, config: &ChartConfig, pos: Vec2) {\n\n let text_props =\n\n TextInsProps { text_style: TEXT_STYLE_MONO, co...
Rust
age/src/error.rs
str4d/rage
456ce707f6db01f2f953c9e22c058964f3437795
use i18n_embed_fl::fl; use std::fmt; use std::io; use crate::{wfl, wlnfl}; #[cfg(feature = "plugin")] use age_core::format::Stanza; #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] #[derive(Clone, Debug)] pub enum PluginError { Identity { binary_name: String, ...
use i18n_embed_fl::fl; use std::fmt; use std::io; use crate::{wfl, wlnfl}; #[cfg(feature = "plugin")] use age_core::format::Stanza; #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] #[derive(Clone, Debug)] pub enum PluginError { Identity { binary_name: String, ...
e) => e.fmt(f), DecryptError::KeyDecryptionFailed => wfl!(f, "err-key-decryption"), #[cfg(feature = "plugin")] DecryptError::MissingPlugin { binary_name } => { writeln!( f, "{}", fl!( ...
message: String, }, Other { kind: String, metadata: Vec<String>, message: String, }, } #[cfg(feature = "plugin")] impl From<Stanza> for PluginError { fn from(mut s: Stanza) -> Self { assert!(s.tag == "error"); let kind = ...
random
[ { "content": "/// Runs the plugin state machine defined by `state_machine`.\n\n///\n\n/// This should be triggered if the `--age-plugin=state_machine` flag is provided as an\n\n/// argument when starting the plugin.\n\npub fn run_state_machine<R: recipient::RecipientPluginV1, I: identity::IdentityPluginV1>(\n\n...
Rust
src/composable.rs
lostmsu/allocators
fb273782383a1b287bcd0498454cec68c237af46
use super::{Allocator, Error, Block, BlockOwner}; pub struct NullAllocator; unsafe impl Allocator for NullAllocator { unsafe fn allocate_raw(&self, _size: usize, _align: usize) -> Result<Block, Error> { Err(Error::OutOfMemory) } unsafe fn reallocate_raw<'a>(&'a self, block: Block<'a>, _new_size...
use super::{Allocator, Error, Block, BlockOwner}; pub struct NullAllocator; unsafe impl Allocator for NullAllocator { unsafe fn allocate_raw(&self, _size: usize, _align: usize) -> Result<Block, Error> { Err(Error::OutOfMemory) } unsafe fn reallocate_raw<'a>(&'a self, block: Block<'a>, _new_size...
} unsafe impl<M: BlockOwner, F: BlockOwner> Allocator for Fallback<M, F> { unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> { match self.main.allocate_raw(size, align) { Ok(block) => Ok(block), Err(_) => self.fallback.allocate_raw(size, align), ...
pub fn new(main: M, fallback: F) -> Self { Fallback { main: main, fallback: fallback, } }
function_block-full_function
[ { "content": "pub fn make_place<A: ?Sized + Allocator, T>(alloc: &A) -> Result<Place<T, A>, super::Error> {\n\n let (size, align) = (mem::size_of::<T>(), mem::align_of::<T>());\n\n match unsafe { alloc.allocate_raw(size, align) } {\n\n Ok(block) => {\n\n Ok(Place {\n\n all...
Rust
src/bvh.rs
ItsHoff/Rusty
f0418d775442d553b69d8e342a15c597a7786451
use std::ops::{Index, Range}; use cgmath::Point3; use crate::aabb::Aabb; use crate::consts; use crate::float::*; use crate::intersect::{Intersect, Ray}; use crate::stats; use crate::triangle::Triangle; const MAX_LEAF_SIZE: usize = 8; #[allow(dead_code)] #[derive(Clone, Copy, Debug)] pub enum SplitMode { Object,...
use std::ops::{Index, Range}; use cgmath::Point3; use crate::aabb::Aabb; use crate::consts; use crate::float::*; use crate::intersect::{Intersect, Ray}; use crate::stats; use crate::triangle::Triangle; const MAX_LEAF_SIZE: usize = 8; #[allow(dead_code)] #[derive(Clone, Copy, Debug)] pub enum SplitMode { Object,...
right_bbs.push(new_bb); } let mut left_bb = Aabb::empty(); for i in 0..triangles.len() { left_bb.add_aabb(&triangles[i].aabb()); let right_bb = &right_bbs[right_bbs.len() - 1 - i]; let n_left = i.to_float(); let n_right = (triangles.len() ...
function_block-function_prefix_line
[ { "content": "#[allow(dead_code)]\n\npub fn gamma(n: u32) -> Float {\n\n let n = n.to_float();\n\n n * consts::MACHINE_EPSILON / (1.0 - n * consts::MACHINE_EPSILON)\n\n}\n\n\n", "file_path": "src/float.rs", "rank": 3, "score": 211379.58543044538 }, { "content": "#[allow(dead_code)]\n\n...
Rust
core/src/service/file_service.rs
lockbook/lockbook
2aac315bad5989617308311d92e52bf82679d919
use sha2::{Digest, Sha256}; use uuid::Uuid; use crate::model::state::Config; use crate::repo::document_repo; use crate::repo::file_metadata_repo; use crate::repo::{account_repo, local_changes_repo}; use crate::service::file_compression_service; use crate::service::file_encryption_service; use crate::CoreError; use loc...
use sha2::{Digest, Sha256}; use uuid::Uuid; use crate::model::state::Config; use crate::repo::document_repo; use crate::repo::file_metadata_repo; use crate::repo::{account_repo, local_changes_repo}; use crate::service::file_compression_service; use crate::service::file_encryption_service; use crate::CoreError; use loc...
pub fn move_file(config: &Config, id: Uuid, new_parent: Uuid) -> Result<(), CoreError> { let _account = account_repo::get_account(config)?; let mut file = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file.id == file.parent { return Err(CoreError::RootModificat...
nsSlash); } match file_metadata_repo::maybe_get(config, id)? { None => Err(CoreError::FileNonexistent), Some(mut file) => { if file.id == file.parent { return Err(CoreError::RootModificationInvalid); } let siblings = file_metadata_repo::get_c...
function_block-function_prefixed
[ { "content": "pub fn decompress(content: &[u8]) -> SharedResult<Vec<u8>> {\n\n let mut decoder = ZlibDecoder::new(content);\n\n let mut result = Vec::<u8>::new();\n\n decoder\n\n .read_to_end(&mut result)\n\n .map_err(|_| SharedErrorKind::Unexpected(\"unexpected decompression error\"))?;\...
Rust
src/day15.rs
codedstructure/aoc2021
27e151e4c8cbcda78b29fe734df6733818783461
use std::{ collections::{HashMap, HashSet}, fs::File, io::{BufRead, BufReader}, }; pub fn read_list(filename: &str) -> Vec<String> { let f = File::open(filename).expect("Could not read file"); BufReader::new(f).lines().map(|l| l.expect("Err")).collect() } #[derive(Debug)] struct RiskMaze { ris...
use std::{ collections::{HashMap, HashSet}, fs::File, io::{BufRead, BufReader}, }; pub fn read_list(filename: &str) -> Vec<String> { let f = File::open(filename).expect("Could not read file"); BufReader::new(f).lines().map(|l| l.expect("Err")).collect() } #[derive(Debug)] struct RiskMaze { ris...
fn bellman_ford(&self) -> i32 { let start = (0, 0); let target = (self.risk.len() - 1, self.line_width - 1); let mut risk = HashMap::new(); for row in 0..self.risk.len() { for col in 0..self.line_width { risk.insert((row, col), 99999);...
0); boundary.insert((1, 0)); boundary.insert((0, 1)); while risk.get(&target).is_none() { let mut new_boundary = HashSet::new(); for b in &boundary { new_boundary.extend( self.neighbours(*b) .differe...
function_block-function_prefixed
[ { "content": "pub fn read_csv_ints(filename: &str) -> Vec<i32> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n let mut line = String::new();\n\n BufReader::new(f).read_line(&mut line).unwrap();\n\n // parse() breaks on line ending, so need to trim that...\n\n line.retain(|...
Rust
src/day25.rs
marty777/adventofcode2019
b2edc81b6f50ea3d0f64c056d8e9617d3ef6424d
use std::collections::HashMap; #[derive(PartialEq, Copy, Clone)] enum Dir { North, East, South, West, } struct TextNode { north: i64, east: i64, west: i64, south: i64, name: String, explored:bool, dest:bool, } #[derive(Clone)] struct DNode { dist:usize, path:Vec<Dir> } fn dijkstra(nodes: &mut Vec<Text...
use std::collections::HashMap; #[derive(PartialEq, Copy, Clone)] enum Dir { North, East, South, West, } struct TextNode { north: i64, east: i64, west: i64, south: i64, name: String, explored:bool, dest:bool, } #[derive(Clone)] struct DNode { dist:usize, path:Vec<Dir> } fn dijkstra(nodes: &mut Vec<Text...
: i64 = code.parse::<i64>().unwrap(); prog.mem.push(temp); } run_text_adventure(&mut prog); }
et vec = super::utility::util_fread(file_path); let intcodes_str:Vec<&str> = vec[0].split(",").collect(); let mut prog:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0}; prog.mem.reserve(intcodes_str.len()); for code in intcodes_str { let temp
function_block-random_span
[ { "content": "pub fn execute_amp2(intcodes: &mut Vec<i64>, input_signal:i64, phase:i64, input_count:&mut u64, pos: &mut usize, exit:&mut bool) -> i64 {\n\n\tlet mut op_pos: usize = *pos;\n\n\tlet mut output:i64 = 0;\n\n\tlet mut input_signal_used = false;\n\n\tlet mut exit_found = false;\n\n\tloop {\n\n\t\tlet...
Rust
src/ewmh.rs
aniketfuryrocks/worm
bc3793c68258e208cd95eaa13bae7b57b32ab096
extern crate x11rb; use protocol::xproto; use protocol::xproto::ConnectionExt; use x11rb::*; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; pub enum Net { ActiveWindow, Supported, SystemTray, SystemTrayOP, SystemTrayOrientation, SystemTrayOrientationHorz, WMName, ...
extern crate x11rb; use protocol::xproto; use protocol::xproto::ConnectionExt; use x11rb::*; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; pub enum Net { ActiveWindow, Supported, SystemTray, SystemTrayOP, SystemTrayOrientation, SystemTrayOrientationHorz, WMName, ...
pub fn get_ewmh_atoms<C>(conn: &C) -> Result<[xproto::Atom; Net::Last as usize]> where C: connection::Connection, { Ok([ conn.intern_atom(false, b"_NET_ACTIVE_WINDOW")? .reply()? .atom, conn.intern_atom(false, b"_NET_SUPPORTED")?.reply()?.atom, ...
function_block-full_function
[ { "content": "pub fn get_ipc_atoms<C>(conn: &C) -> Result<[xproto::Atom; IPC::Last as usize]>\n\nwhere\n\n C: connection::Connection,\n\n{\n\n // see notes on ewmh.rs, exact same thing here\n\n\n\n Ok([\n\n conn.intern_atom(false, b\"_WORM_CLIENT_MESSAGE\")?\n\n .reply()?\n\n ...
Rust
generative_design/random_and_noise/m_1_3_03.rs
nfletton/nannou
c7c99328a16221a4d0b196c52647f30d75170b14
/** * creates a texture based on noise values * * MOUSE * position x/y : specify noise input range * * KEYS * 1-2 : set noise mode * arrow up : noise falloff + * arrow down : noise falloff - * arrow left : noise octaves - * arrow right : noise oct...
/** * creates a texture based on noise values * * MOUSE * position x/y : specify noise input range * * KEYS * 1-2 : set noise mode * arrow up : noise falloff + * arrow down : noise falloff - * arrow left : noise octaves - * arrow right : noise oct...
model.octaves -= 1; } Key::Right => { model.octaves += 1; } _otherkey => (), } if model.falloff > 1.0 { model.falloff = 1.0; } if model.falloff <= 0.0 { model.falloff = 0.0; } if model.octaves <= 1 { model.octaves = 1; ...
octaves: usize, falloff: f32, noise_mode: u8, noise_random_seed: u32, texture: wgpu::Texture, } fn model(app: &App) -> Model { let _window = app .new_window() .size(512, 512) .view(view) .key_pressed(key_pressed) .key_released(key_released) .build...
random
[]
Rust
systeroid-tui/src/command.rs
orhun/systeroid
ba32367beb5cbe052d2cce6cc98b2babe742df28
use crate::options::{Direction, ScrollArea}; use std::str::FromStr; use termion::event::Key; #[derive(Debug, PartialEq)] pub enum Command { Help, Select, Set(String, String), Scroll(ScrollArea, Direction, u8), MoveCursor(Direction), Search, ProcessInput, ...
use crate::options::{Direction, ScrollArea}; use std::str::FromStr; use termion::event::Key; #[derive(Debug, PartialEq)] pub enum Command { Help, Select, Set(String, String), Scroll(ScrollArea, Direction, u8), MoveCursor(Direction), Search, ProcessInput, ...
} } } } impl Command { pub fn parse(key: Key, input_mode: bool) -> Self { if input_mode { match key { Key::Char('\n') => Command::ProcessInput, Key::Char(c) => Command::UpdateInput(c), Key::Backspace => Command::Clear...
if s.starts_with("set") { let values: Vec<&str> = s .trim_start_matches("set") .trim() .split_whitespace() .collect(); Ok(Command::Set( values.first().ok_or(())...
if_condition
[ { "content": "/// Renders the user interface.\n\npub fn render<B: Backend>(frame: &mut Frame<'_, B>, app: &mut App, colors: &Colors) {\n\n let documentation = app\n\n .parameter_list\n\n .selected()\n\n .and_then(|parameter| parameter.get_documentation());\n\n let rect = frame.size();...
Rust
cli/src/main.rs
asm0dey/cb
b68417ded4f52d8af1541296485bf39b95c0cf6c
#[macro_use] extern crate common; const VERSION: &str = env!("CARGO_PKG_VERSION"); use cli::Handler; use common::constants::SOCKET_PATH; use common::errors::StringErrorResult; use gumdrop::Options; use server; use std::env::current_exe; use std::io::{self, Read}; use std::os::unix::net::UnixStream; use std::process::...
#[macro_use] extern crate common; const VERSION: &str = env!("CARGO_PKG_VERSION"); use cli::Handler; use common::constants::SOCKET_PATH; use common::errors::StringErrorResult; use gumdrop::Options; use server; use std::env::current_exe; use std::io::{self, Read}; use std::os::unix::net::UnixStream; use std::process::...
fn main() { let mut opts = AppOptions::parse_args_default_or_exit(); if opts.server { server::start(); } if opts.help { exit!("{}", AppOptions::usage()); } if opts.version { exit!("{}", VERSION); } let mut handler = Handler::new(match try_connect(true) { ...
fn try_connect(try_run: bool) -> Result<UnixStream, String> { match UnixStream::connect(SOCKET_PATH) { Ok(stream) => Ok(stream), err => { if try_run { let _ = Command::new(current_exe().unwrap()) .arg("-s") .spawn() ...
function_block-full_function
[ { "content": "/// Starts server as a daemon\n\npub fn start() {\n\n env_logger::init();\n\n\n\n let socket_path = Path::new(SOCKET_PATH);\n\n\n\n let (username, group) = match get_user_group() {\n\n Ok(ug) => ug,\n\n Err(e) => {\n\n fatal!(\"{}\", e);\n\n }\n\n };\n\n...
Rust
aer_data/src/metadata/chocolatey.rs
WormieCorp/aer
9eaf1d86c36016cac1afd7125bb60c592bdd960a
#![cfg_attr(docsrs, doc(cfg(feature = "chocolatey")))] use std::collections::HashMap; use std::fmt::Display; use aer_version::Versions; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use url::Url; use crate::prelude::Description; #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "seriali...
#![cfg_attr(docsrs, doc(cfg(feature = "chocolatey")))] use std::collections::HashMap; use std::fmt::Display; use aer_version::Versions; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use url::Url; use crate::prelude::Description; #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "seriali...
on::Text(description.into())); } pub fn set_title(&mut self, title: &str) { if let Some(ref mut self_title) = self.title { self_title.clear(); self_title.push_str(title); } else { self.title = Some(title.into()); } } pub fn set_copyright(&mut...
authors: Vec<String>, pub description: Description, #[cfg_attr( feature = "serialize", serde(default = "crate::defaults::boolean_true") )] pub require_license_acceptance: bool, pub documentation_url: Option<Url>, pub issues_url: Option<Url>, #[cfg_at...
random
[ { "content": "#[cfg(feature = \"chocolatey\")]\n\npub fn boolean_true() -> bool {\n\n true\n\n}\n\n\n", "file_path": "aer_data/src/defaults.rs", "rank": 0, "score": 93514.10413531325 }, { "content": "pub trait FixVersion {\n\n fn is_fix_version(&self) -> bool;\n\n fn add_fix(&mut se...
Rust
src/librustdoc/html/highlight.rs
Kroisse/rust
5716abe3f019ab7d9c8cdde9879332040191cf88
use std::str; use std::io; use syntax::parse; use syntax::parse::lexer; use syntax::codemap::{BytePos, Span}; use html::escape::Escape; use t = syntax::parse::token; pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String { debug!("highlighting: ================\n{}\n==============", src)...
use std::str; use std::io; use syntax::parse; use syntax::parse::lexer; use syntax::codemap::{BytePos, Span}; use html::escape::Escape; use t = syntax::parse::token; pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String { debug!("highlighting: ================\n{}\n==============", src)...
2", t::NOT if is_macro => { is_macro = false; "macro" } t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT | t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW | t::BINOPEQ(..) | t::FAT_ARROW => "op", ...
function_block-function_prefixed
[ { "content": "pub fn main() { loop { int_id(break); } }\n", "file_path": "src/test/run-pass/break-value.rs", "rank": 1, "score": 533837.206130467 }, { "content": "/// Run any tests/code examples in the markdown file `input`.\n\npub fn test(input: &str, libs: HashSet<Path>, mut test_args: Vec...
Rust
dao_vault/lib.rs
RainbowDAO/RainbowDAO-Protocol-Ink-Test-Version-05
b17ecb5c37c868ca99a23e36957ac9e012474c29
#![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; extern crate alloc; pub use self::dao_vault::DaoVault; #[ink::contract] mod dao_vault { use alloc::string::String; use alloc::vec::Vec; use erc20::Erc20; use ink_storage::{ collections::HashMap as StorageHashMap, traits::{P...
#![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; extern crate alloc; pub use self::dao_vault::DaoVault; #[ink::contract] mod dao_vault { use alloc::string::String; use alloc::vec::Vec; use erc20::Erc20; use ink_storage::{ collections::HashMap as StorageHashMap, traits::{P...
#[ink(message)] pub fn withdraw(&mut self,erc_20_address:AccountId,to_address:AccountId,value:u64) -> bool { let from_address = self.vault_contract_address; if self.tokens.contains_key(&erc_20_address) { let mut erc_20 = self.get_erc20_by_address(erc_20_address)...
e(), from_address:from_address, value:value}); true } else{ false } }
function_block-function_prefixed
[ { "content": " }\n\n\n\n /// The ERC-20 error types.\n\n #[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]\n\n #[cfg_attr(feature = \"std\", derive(scale_info::TypeInfo))]\n\n pub enum Error {\n\n /// Returned if not enough balance to fulfill a request is available.\n\n ...
Rust
crates/tm4c129x/src/pwm0/sync.rs
m-labs/ti2svd
30145706b658136c35c90290701de3f02a4b8ef2
#[doc = "Reader of register SYNC"] pub type R = crate::R<u32, super::SYNC>; #[doc = "Writer for register SYNC"] pub type W = crate::W<u32, super::SYNC>; #[doc = "Register SYNC `reset()`'s with value 0"] impl crate::ResetValue for super::SYNC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register SYNC"] pub type R = crate::R<u32, super::SYNC>; #[doc = "Writer for register SYNC"] pub type W = crate::W<u32, super::SYNC>; #[doc = "Register SYNC `reset()`'s with value 0"] impl crate::ResetValue for super::SYNC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
)] pub fn sync1(&mut self) -> SYNC1_W { SYNC1_W { w: self } } #[doc = "Bit 2 - Reset Generator 2 Counter"] #[inline(always)] pub fn sync2(&mut self) -> SYNC2_W { SYNC2_W { w: self } } #[doc = "Bit 3 - Reset Generator 3 Counter"] #[inline(always)] pub fn sync3(&mut sel...
as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `SYNC3`"] pub type SYNC3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNC3`"] pub struct SYNC3_W<'a> { w: &'a mut W, } impl<'a> SYNC3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a ...
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
benches/xml.rs
sahwar/roxmltree
fb3315cee821a370c6f90f33f3e65072dc735848
#![allow(dead_code)] #[macro_use] extern crate bencher; extern crate roxmltree; extern crate xmlparser; extern crate xmltree; extern crate sxd_document; extern crate elementtree; extern crate treexml; extern crate xml; use std::fs; use std::env; use std::io::Read; use bencher::Bencher; fn load_string(path: &str) -...
#![allow(dead_code)] #[macro_use] extern crate bencher; extern crate roxmltree; extern crate xmlparser; extern crate xmltree; extern crate sxd_document; extern crate elementtree; extern crate treexml; extern crate xml; use std::fs; use std::env; use std::io::Read; use bencher::Bencher; fn load_string(path: &str) -...
fn large_xmlrs(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| { for event in xml::EventReader::new(text.as_bytes()) { let _ = event.unwrap(); } }) } fn tiny_roxmltree(bencher: &mut Bencher) { let text = load_string("fonts.conf"); benche...
bencher.iter(|| { for event in xml::EventReader::new(text.as_bytes()) { let _ = event.unwrap(); } }) }
function_block-function_prefixed
[ { "content": "fn load_file(path: &str) -> String {\n\n let mut file = fs::File::open(&path).unwrap();\n\n let mut text = String::new();\n\n file.read_to_string(&mut text).unwrap();\n\n text\n\n}\n", "file_path": "examples/ast.rs", "rank": 1, "score": 190922.63934523566 }, { "cont...
Rust
amethyst_core/src/hide_system.rs
csh/amethyst
68aa4eaadd56c40de6f91d1148affbe3c2381128
use crate::{ ecs::prelude::{ BitSet, ComponentEvent, ReadExpect, ReadStorage, ReaderId, System, SystemData, World, WriteStorage, }, transform::components::{HierarchyEvent, Parent, ParentHierarchy}, SystemDesc, }; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; use log:...
use crate::{ ecs::prelude::{ BitSet, ComponentEvent, ReadExpect, ReadStorage, ReaderId, System, SystemData, World, WriteStorage, }, transform::components::{HierarchyEvent, Parent, ParentHierarchy}, SystemDesc, }; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; use log:...
}
fn run(&mut self, (mut hidden, parents, hierarchy): Self::SystemData) { #[cfg(feature = "profiler")] profile_scope!("hide_hierarchy_system"); self.marked_as_modified.clear(); self.manually_hidden.clear(); let self_hidden_events_id = &mut self.hidden_events_id; ...
function_block-full_function
[ { "content": "fn create_default_mat<B: Backend>(world: &mut World) -> Material {\n\n use crate::mtl::TextureOffset;\n\n\n\n use amethyst_assets::Loader;\n\n\n\n let loader = world.fetch::<Loader>();\n\n\n\n let albedo = load_from_srgba(Srgba::new(0.5, 0.5, 0.5, 1.0));\n\n let emission = load_from...
Rust
src/connectivity/network/testing/netemul/runner/test/netstack_intermediary/src/main.rs
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
#![feature(async_await, await_macro, futures_api)] use { ethernet, failure::{bail, format_err, Error, ResultExt}, fidl_fuchsia_hardware_ethernet::{DeviceMarker, DeviceProxy}, fidl_fuchsia_hardware_ethertap::{ TapControlMarker, TapDeviceEvent, TapDeviceMarker, TapDeviceProxy, }, fidl_f...
#![feature(async_await, await_macro, futures_api)] use { ethernet, failure::{bail, format_err, Error, ResultExt}, fidl_fuchsia_hardware_ethernet::{DeviceMarker, DeviceProxy}, fidl_fuchsia_hardware_ethertap::{ TapControlMarker, TapDeviceEvent, TapDeviceMarker, TapDeviceProxy, }, fidl_f...
o_string.clone().into_bytes().drain(0..))?; println!("To Server: {}", echo_string); let mut tap_events = tap.take_event_stream(); while let Some(event) = await!(tap_events.try_next())? { match event { TapDeviceEvent::OnFrame { data } => { let server_string = str::from_u...
let eth_marker = fidl::endpoints::ClientEnd::new(eth_device.into_channel().unwrap().into_zx_channel()); let netstack = client::connect_to_service::<NetstackMarker>()?; let ip_addr_config = IpAddressConfig::Dhcp(true); let mut cfg = InterfaceConfig { name: "eth-test".to_string(), ...
random
[]
Rust
crate2nix/src/prefetch.rs
alyssais/crate2nix
049897e466ff326945a17303ed4585868cc65b35
use std::io::Write; use std::process::Command; use crate::resolve::{CrateDerivation, CratesIoSource, GitSource, ResolvedSource}; use crate::GenerateConfig; use cargo_metadata::PackageId; use failure::bail; use failure::format_err; use failure::Error; use serde::Deserialize; use std::collections::{BTreeMap, HashMap};...
use std::io::Write; use std::process::Command; use crate::resolve::{CrateDerivation, CratesIoSource, GitSource, ResolvedSource}; use crate::GenerateConfig; use cargo_metadata::PackageId; use failure::bail; use failure::format_err; use failure::Error; use serde::Deserialize; use std::collections::{BTreeMap, HashMap};...
if let Some(r#ref) = self.r#ref.as_ref() { args.extend_from_slice(&["--branch-name", r#ref]); } let json = get_command_output("nix-prefetch-git", &args)?; let prefetch_info: NixPrefetchGitInfo = serde_json::from_str(&json)?; Ok(prefetch_i...
let mut args = vec![ "--url", self.url.as_str(), "--fetch-submodules", "--rev", &self.rev, ];
assignment_statement
[ { "content": "/// Run the command at the given path without arguments and capture the output in the return value.\n\npub fn run_cmd(cmd_path: impl AsRef<Path>) -> Result<String, Error> {\n\n let cmd_path = cmd_path.as_ref().to_string_lossy().to_string();\n\n let output = Command::new(&cmd_path)\n\n ...
Rust
sdk/src/permissions.rs
target/grid
e8efd7f0109dadc89f4b1ab5d57b09aa2d87eb26
use std::error::Error; use std::fmt; cfg_if! { if #[cfg(target_arch = "wasm32")] { use sabre_sdk::WasmSdkError as ContextError; use sabre_sdk::TransactionContext; } else { use sawtooth_sdk::processor::handler::ContextError; use sawtooth_sdk::processor::handler::TransactionCont...
use std::error::Error; use std::fmt; cfg_if! { if #[cfg(target_arch = "wasm32")] { use sabre_sdk::WasmSdkError as ContextError; use sabre_sdk::TransactionContext; } else { use sawtooth_sdk::processor::handler::ContextError; use sawtooth_sdk::processor::handler::TransactionCont...
ntextError), InvalidPublicKey(String), ProtoConversion(ProtoConversionError), } impl fmt::Display for PermissionCheckerError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { PermissionCheckerError::Context(ref e) => e.fmt(f), PermissionChecker...
ate::protocol::pike::state::{Agent, AgentList}; use crate::protos::{FromBytes, ProtoConversionError}; #[derive(Debug)] pub enum PermissionCheckerError { Context(Co
random
[ { "content": "cfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n #[macro_use]\n\n extern crate sabre_sdk;\n\n } else {\n\n #[macro_use]\n\n extern crate clap;\n\n #[macro_use]\n\n extern crate log;\n\n extern crate sawtooth_sdk;\n\n extern crate...
Rust
thavalon-server/src/database/games/db_game.rs
theadd336/ThavalonWeb
cf5e9f80270cdab3d4d2d25fa8bc35748aa18f92
use crate::database::get_database; use crate::utils; use std::collections::{HashMap, HashSet}; use chrono::Utc; use mongodb::{ bson::{self, doc, oid::ObjectId, Document}, Collection, }; use serde::{Deserialize, Serialize}; use thiserror::Error; const GAME_COLLECTION: &str = "thavalon_games"; const FRIEND_CO...
use crate::database::get_database; use crate::utils; use std::collections::{HashMap, HashSet}; use chrono::Utc; use mongodb::{ bson::{self, doc, oid::ObjectId, Document}, Collection, }; use serde::{Deserialize, Serialize}; use thiserror::Error; const GAME_COLLECTION: &str = "thavalon_games"; const FRIEND_CO...
pub async fn end_game(&mut self) -> Result<(), DBGameError> { self.friend_code.clear(); self.end_time = Some(Utc::now().timestamp()); self.status = DBGameStatus::Finished; let update_doc = doc! { "$set": { "frie...
pub async fn start_game(&mut self) -> Result<(), DBGameError> { log::info!("Starting DB game {}.", self._id); self.start_time = Some(Utc::now().timestamp()); self.status = DBGameStatus::InProgress; let update_doc = doc! { "$set": { "start_time": bson...
function_block-full_function
[ { "content": "/// Generate an [`Effect`] that sends an error reply to the player.\n\nfn player_error<S: Into<String>>(message: S) -> Effect {\n\n Effect::Reply(Message::Error(message.into()))\n\n}\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 0, "score": 213652.85552980838 }, ...
Rust
src/mevdb.rs
sambacha/mev-inspect-rs
9d111bf50910f188c3ee66624d5b25b41757c0e1
use crate::types::Evaluation; use ethers::types::{TxHash, U256}; use rust_decimal::prelude::*; use thiserror::Error; use tokio_postgres::{config::Config, Client, NoTls}; pub struct MevDB<'a> { client: Client, table_name: &'a str, overwrite: String, } impl<'a> MevDB<'a> { pub async fn connect(cfg:...
use crate::types::Evaluation; use ethers::types::{TxHash, U256}; use rust_decimal::prelude::*; use thiserror::Error; use tokio_postgres::{config::Config, Client, NoTls}; pub struct MevDB<'a> { client: Client, table_name: &'a str, overwrite: String, } impl<'a> MevDB<'a> { pub async fn connect(cfg:...
pub async fn exists(&mut self, hash: TxHash) -> Result<bool, DbError> { let rows = self .client .query( format!("SELECT hash FROM {} WHERE hash = $1", self.table_name).as_str(), &[&format!("{:?}", hash)], ) .await?; ...
contract, proxy_impl ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) {}", self.table_name, self.overwrite, ) .as_str(), &[ &format!("{:?}", evaluation.inspectio...
function_block-function_prefix_line
[ { "content": "pub fn get_trace(hash: &str) -> Inspection {\n\n let hash = if hash.starts_with(\"0x\") {\n\n &hash[2..]\n\n } else {\n\n hash\n\n };\n\n\n\n TraceWrapper(\n\n TRACES\n\n .iter()\n\n .filter(|t| t.transaction_hash == Some(hash.parse::<TxHash>(...
Rust
src/impls/primitive.rs
JuanPotato/deku
09427b8eb5e39402c4dec49070e9ae0a5ecbe20d
use crate::{ctx::*, DekuError, DekuRead, DekuWrite}; use bitvec::prelude::*; use core::convert::TryInto; #[cfg(feature = "alloc")] use alloc::format; macro_rules! ImplDekuTraits { ($typ:ty) => { impl DekuRead<'_, (Endian, Size)> for $typ { fn read( input: &BitSlice<u8, Msb0>, ...
use crate::{ctx::*, DekuError, DekuRead, DekuWrite}; use bitvec::prelude::*; use core::convert::TryInto; #[cfg(feature = "alloc")] use alloc::format; macro_rules! ImplDekuTraits { ($typ:ty) => { impl DekuRead<'_, (Endian, Size)> for $typ { fn read( input: &BitSlice<u8, Msb0>, ...
3F, 0x01, 0xEF], native_endian!(-0x10FEC0FE_i32) ); TestPrimitive!( test_i64, i64, vec![0x02u8, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF], native_endian!(-0x10FEC0FE10FEC0FE_i64) ); TestPrimitive!( test_i128, i128, vec![ 0x02u8,...
ice.len() == max_type_bits && bit_slice.domain().region().unwrap().1.len() * 8 == max_type_bits { let bytes: &[u8] = bit_slice.domain().region().unwrap().1; if input_is_le { <$...
random
[ { "content": "fn emit_magic_read(input: &DekuData) -> TokenStream {\n\n let crate_ = super::get_crate_name();\n\n if let Some(magic) = &input.magic {\n\n quote! {\n\n let __deku_magic = #magic;\n\n\n\n for __deku_byte in __deku_magic {\n\n let (__deku_new_rest, ...
Rust
src/main.rs
pmalmgren/pongbrickbreaker
708bee1059243ea43af39418dac04eeca8034275
use ncurses::CURSOR_VISIBILITY::CURSOR_INVISIBLE; use ncurses::*; use std::char; use std::process; use std::{thread, time}; use std::cmp; use std::time::{SystemTime, UNIX_EPOCH}; use std::convert::TryFrom; const PADDLE_WIDTH: i32 = 12; const NUM_ROWS: i32 = 4; const BRICKS_PER_ROW: i32 = 6; enum Direction { Left,...
use ncurses::CURSOR_VISIBILITY::CURSOR_INVISIBLE; use ncurses::*; use std::char; use std::process; use std::{thread, time}; use std::cmp; use std::time::{SystemTime, UNIX_EPOCH}; use std::convert::TryFrom; const PADDLE_WIDTH: i32 = 12; const NUM_ROWS: i32 = 4; const BRICKS_PER_ROW: i32 = 6; enum Direction { Left,...
; match y_collision { Some(MoveResult::HitPaddleCenter) => { self.vel.y = -self.vel.y; self.vel.x = 0; }, Some(MoveResult::HitPaddleLeft) => { self.vel.x = -1; self.vel.y = -self.vel.y; }, ...
match self.vel.y { y if y > 0 => self.move1(Direction::Down, screen_bounds, paddle_bounds, brick_bounds), y if y < 0 => self.move1(Direction::Up, screen_bounds, paddle_bounds, brick_bounds), _ => None, }
if_condition
[ { "content": "# Pong Brick Breaker Game\n\n\n\nA console pong brick breaker game written with Rust and ncurses.\n\n\n\n`a` moves the paddle to the left, `d` moves the paddle to the right.\n\n\n\n## Requirements\n\n\n\nYou'll need [Rust](https://www.rust-lang.org/tools/install) and ncurses to play. Once you have...
Rust
host/src/route/chain.rs
manasrivastava/tinychain
e6082f587ac089307ca9264d90d20c3f0991da52
use log::debug; use safecast::TryCastFrom; use tc_error::*; use tc_transact::fs::File; use tc_transact::Transaction; use tc_value::Value; use tcgeneric::{Instance, PathSegment, TCPath}; use crate::chain::{Chain, ChainInstance, ChainType, Subject, SUBJECT}; use super::{DeleteHandler, GetHandler, Handler, PostHandler,...
use log::debug; use safecast::TryCastFrom; use tc_error::*; use tc_transact::fs::File; use tc_transact::Transaction; use tc_value::Value; use tcgeneric::{Instance, PathSegment, TCPath}; use crate::chain::{Chain, ChainInstance, ChainType, Subject, SUBJECT}; use super::{DeleteHandler, GetHandler, Handler, PostHandler,...
> From<&'a Chain> for ChainHandler<'a> { fn from(chain: &'a Chain) -> Self { Self { chain } } } impl<'a> Handler<'a> for ChainHandler<'a> { fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|_txn, key| { Box::pin(async move {...
nc move { debug!("Chain::delete {}", key); self.chain .append_delete(*txn.id(), self.path.to_vec().into(), key.clone()) .await?; delete_handler(txn, key).await }) ...
random
[ { "content": "fn route<'a, T>(tensor: &'a T, path: &'a [PathSegment]) -> Option<Box<dyn Handler<'a> + 'a>>\n\nwhere\n\n T: TensorAccess\n\n + TensorIO<fs::Dir, Txn = Txn>\n\n + TensorCompare<Tensor, Compare = Tensor, Dense = Tensor>\n\n + TensorBoolean<Tensor, Combine = Tensor>\n\n ...
Rust
src/block_ciphers.rs
dkull/cryptopals
8d6b723b2c7f7905755804631a2bdda4c6b2005e
use crate::xor_arrays; use aes::Aes128; use std::collections::VecDeque; #[derive(PartialEq, Clone, Copy, Debug)] pub enum AESBlockMode { ECB, CBC, CTR, } fn ctr_input(nonce: Option<[u8; 8]>, n: usize) -> [u8; 16] { let nonce = if let Some(n) = nonce { n } else { [0u8; 8] }; let counter = &(n as u...
use crate::xor_arrays; use aes::Aes128; use std::collections::VecDeque; #[derive(PartialEq, Clone, Copy, Debug)] pub enum AESBlockMode { ECB, CBC, CTR, } fn ctr_input(nonce: Option<[u8; 8]>, n: usize) -> [u8; 16] { let nonce = if let Some(n) = nonce { n } else { [0u8; 8] }; let counter = &(n as u...
pub fn pkcs7_padding_strip(data: &mut Vec<u8>) -> bool { let padding = data[data.len() - 1]; if padding as usize > data.len() { return false; } if padding == 0 { return false; } let padding_start = data.len() - padding as usize; for p in padding_start..data.len() { ...
fn pkcs7_padding_works() { let mut case1 = (vec![0x00, 0xff, 0x01], vec![0x00, 0xff], 3); pkcs7_padding(&mut case1.1, case1.2); assert_eq!(case1.0, case1.1); let mut case2 = ( vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x02, 0x02], vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01], 8, ...
function_block-full_function
[ { "content": "pub fn xor_arrays(a: &[u8], b: &[u8]) -> Vec<u8> {\n\n assert!(a.len() >= b.len(), format!(\"{} vs {}\", a.len(), b.len()));\n\n a.to_vec()\n\n .iter()\n\n .zip(b.to_vec().iter().cycle())\n\n .map(|(a, b)| a ^ b)\n\n .collect()\n\n}\n\n\n", "file_path": "src/l...
Rust
sigma-tree/src/sigma_protocol.rs
robkorn/sigma-rust
3aa25d62a2b6f6b071b5b89607d0688e5509a9a6
#![allow(dead_code)] #![allow(unused_variables)] #![allow(missing_docs)] pub mod dlog_group; pub mod dlog_protocol; pub mod prover; pub mod verifier; use k256::arithmetic::Scalar; use crate::{big_integer::BigInteger, serialization::op_code::OpCode}; use blake2::digest::{Update, VariableOutput}; use blake2::VarBlak...
#![allow(dead_code)] #![allow(unused_variables)] #![allow(missing_docs)] pub mod dlog_group; pub mod dlog_protocol; pub mod prover; pub mod verifier; use k256::arithmetic::Scalar; use crate::{big_integer::BigInteger, serialization::op_code::OpCode}; use blake2::digest::{Update, VariableOutput}; use blake2::VarBlak...
#[cfg(test)] mod tests { use super::*; use proptest::prelude::*; impl Arbitrary for ProveDlog { type Parameters = (); type Strategy = BoxedStrategy<Self>; fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { (any::<EcPoint>()).prop_map(ProveDlog::new).boxed(...
p(); hasher.update(input); let hash = hasher.finalize_boxed(); FiatShamirHash(hash.try_into().unwrap()) }
function_block-function_prefixed
[ { "content": "/// Creates a random scalar, a big-endian integer in the range [0, n), where n is group order\n\npub fn random_scalar_in_group_range() -> Scalar {\n\n loop {\n\n // Generate a new secret key using the operating system's\n\n // cryptographically secure random number generator\n\n ...
Rust
src/lib.rs
load1n9/neko
addb9c2b2e911e33f2926230677c2d90b3b43de0
extern crate minifb; use std::cell::RefCell; use std::collections::HashMap; use minifb::Key; use minifb::Window; use minifb::WindowOptions; use minifb::MouseMode; use minifb::MouseButton; pub static SUCCESS: u32 = 0; pub static ERR_WINDOW_NOT_FOUND: u32 = 2; pub static ERR_UPDATE_WITH_BUFFER_FAILED: u32 = 3; thread...
extern crate minifb; use std::cell::RefCell; use std::collections::HashMap; use minifb::Key; use minifb::Window; use minifb::WindowOptions; use minifb::MouseMode; use minifb::MouseButton; pub static SUCCESS: u32 = 0; pub static ERR_WINDOW_NOT_FOUND: u32 = 2; pub static ERR_UPDATE_WITH_BUFFER_FAILED: u32 = 3; thread...
#[no_mangle] pub extern "C" fn window_is_active(id: u32) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if let Some(window) = map.get_mut(&id) { if window.is_active() { 1 } else { 0 } } else { ER...
pub extern "C" fn window_is_open(id: u32) -> u32 { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { if window.is_open() { 1 } else { 0 } } else { ERR_WINDOW_NOT_FOUND } ...
function_block-full_function
[ { "content": "const width = 800;\n", "file_path": "examples/test.ts", "rank": 2, "score": 55611.0160243587 }, { "content": "const height = 600;\n", "file_path": "examples/test.ts", "rank": 3, "score": 55611.0160243587 }, { "content": "const H = 300;\n", "file_path": "...
Rust
applications/swap/src/lib.rs
jacob-earle/Theseus
d53038328d1a39c69ffff6e32226394e8c957e33
#![no_std] #![feature(slice_concat_ext)] #[macro_use] extern crate alloc; #[macro_use] extern crate terminal_print; extern crate itertools; extern crate getopts; extern crate memory; extern crate mod_mgmt; extern crate crate_swap; extern crate hpet; extern crate task; extern crate path; extern crate fs_node; use a...
#![no_std] #![feature(slice_concat_ext)] #[macro_use] extern crate alloc; #[macro_use] extern crate terminal_print; extern crate itertools; extern crate getopts; extern crate memory; extern crate mod_mgmt; extern crate crate_swap; extern crate hpet; extern crate task; extern crate path; extern crate fs_node; use a...
ace = task::get_my_current_task().ok_or("Couldn't get current task")?.get_namespace(); let swap_requests = { let mut requests: Vec<SwapRequest> = Vec::with_capacity(tuples.len()); for (old_crate_name, new_crate_str, reexport) in tuples { let (into...
v.push((o, n, reexport_bool)); } _ => return Err("list of crate tuples is formatted incorrectly.".to_string()), } } if v.is_empty() { Err("no crate tuples specified.".to_string()) } else { Ok(v) } } fn do_swap( tuples: Vec<(&str, &str, bool)>...
random
[ { "content": "/// Spawns a new userspace task based on the provided `path`, which must point to an ELF executable file with a defined entry point.\n\n/// Optionally, provide a `name` for the new Task. If none is provided, the name is based on the given `Path`.\n\npub fn spawn_userspace(path: Path, name: Option<...
Rust
src/de/value.rs
Mingun/serde-gff
2bfacbb0b6b361da749082f99edaec474ccc6c7c
use std::collections::HashMap; use std::fmt; use std::marker::PhantomData; use indexmap::IndexMap; use serde::forward_to_deserialize_any; use serde::de::{Deserialize, Deserializer, Error, IntoDeserializer, SeqAccess, MapAccess, Visitor}; use crate::Label; use crate::string::{GffString, StringKey}; use crate::value::...
use std::collections::HashMap; use std::fmt; use std::marker::PhantomData; use indexmap::IndexMap; use serde::forward_to_deserialize_any; use serde::de::{Deserialize, Deserializer, Error, IntoDeserializer, SeqAccess, MapAccess, Visitor}; use crate::Label; use crate::string::{GffString, StringKey}; use crate::value::...
} impl<'de> Deserialize<'de> for Label { #[inline] fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(LabelVisitor) } } #[derive(Debug)] pub struct LabelDeserializer<E> { value: Label, marker: PhantomData<E>, } impl<'de, E...
8]) -> Result<Label, E> where E: Error, { use crate::error::Error::TooLongLabel; match Label::from_bytes(value) { Ok(label) => Ok(label), Err(TooLongLabel(len)) => Err(E::invalid_length(len, &self)), Err(err) => Err(E::custom(err)), } }
function_block-function_prefixed
[ { "content": "/// Десериализатор для чтения идентификаторов полей\n\nstruct Field<'a, R: 'a + Read + Seek>(&'a mut Deserializer<R>);\n\n\n\nimpl<'de, 'a, R: 'a + Read + Seek> de::Deserializer<'de> for Field<'a, R> {\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn is_human_readable(&self) -> bool { false }\n...
Rust
src/intrinsics_orthographic.rs
strawlab/cam-geom
0d160e2510d4f0df7af1123d51cf1518c7a58070
use nalgebra::{ allocator::Allocator, base::storage::{Owned, Storage}, convert, DefaultAllocator, Dim, OMatrix, RealField, U2, U3, }; #[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use crate::{ coordinate_system::CameraFrame, Bundle, IntrinsicParameters, Pixels, Points, RayBu...
use nalgebra::{ allocator::Allocator, base::storage::{Owned, Storage}, convert, DefaultAllocator, Dim, OMatrix, RealField, U2, U3, }; #[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use crate::{ coordinate_system::CameraFrame, Bundle, IntrinsicParameters, Pixels, Points, RayBu...
#[test] #[cfg(feature = "serde-serialize")] fn test_serde() { let params = OrthographicParams { sx: 100.0, sy: 102.0, cx: 321.0, cy: 239.9, }; let expected: IntrinsicParametersOrthographic<_> = params.into(); let buf = serde_...
fn roundtrip() { let params = OrthographicParams { sx: 100.0, sy: 102.0, cx: 321.0, cy: 239.9, }; let cam: IntrinsicParametersOrthographic<_> = params.into(); roundtrip_intrinsics(&cam, 640, 480, 5, 0, nalgebra::convert(1e-10)); l...
function_block-full_function
[ { "content": "#[cfg(test)]\n\npub fn roundtrip_camera<R, I>(\n\n cam: Camera<R, I>,\n\n width: usize,\n\n height: usize,\n\n step: usize,\n\n border: usize,\n\n eps: R,\n\n) where\n\n R: RealField,\n\n I: IntrinsicParameters<R>,\n\n I::BundleType: Bundle<R>,\n\n{\n\n let pixels = c...
Rust
src/handler/description.rs
p0lunin/dptree
cf41f052a864e145ef600faf79a1dff186b5a905
use core::mem; use std::{ collections::{hash_map::RandomState, HashSet}, hash::{BuildHasher, Hash}, }; pub trait HandlerDescription: Sized + Send + Sync + 'static { fn entry() -> Self; fn user_defined() -> Self; fn merge_chain(&self, other: &Self) -> Self; fn merge...
use core::mem; use std::{ collections::{hash_map::RandomState, HashSet}, hash::{BuildHasher, Hash}, }; pub trait HandlerDescription: Sized + Send + Sync + 'static { fn entry() -> Self; fn user_defined() -> Self; fn merge_chain(&self, other: &Self) -> Self; fn merge...
fn merge_branch(&self, other: &Self) -> Self { use EventKind::*; match (self, other) { (Entry, other) | (other, Entry) => other.clone(), (InterestList(l), InterestList(r)) => { let hasher = l....
d::*; match (self, other) { (Entry, other) | (other, Entry) => other.clone(), (InterestList(l), InterestList(r)) => { let hasher = l.hasher().clone(); let mut res = HashSet::with_hasher(hash...
function_block-function_prefixed
[ { "content": "#[must_use]\n\n#[track_caller]\n\npub fn filter_map<'a, Projection, Input, Output, NewType, Args, Descr>(\n\n proj: Projection,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Clone,\n\n Asyncify<Projection>: Injectable<Input, Option<NewType>, Args> + Send + Sync + 'a,\n\n ...
Rust
src/init/init_game_data.rs
Noah2610/LD48
433d248beef1b7a4dd99116d48348bef66bdd301
use crate::resource; use crate::resources::prelude::*; use crate::settings::Settings; use crate::states::aliases::{CustomData, GameDataBuilder}; use amethyst::prelude::Config; use amethyst::window::DisplayConfig; use deathframe::amethyst; pub(super) fn build_game_data<'a, 'b>( settings: &Settings, ) -> amethyst::R...
use crate::resource; use crate::resources::prelude::*; use crate::settings::Settings; use crate::states::aliases::{CustomData, GameDataBuilder}; use amethyst::prelude::Config; use amethyst::window::DisplayConfig; use deathframe::amethyst; pub(super) fn build_game_data<'a, 'b>( settings: &Settings, ) -> amethyst::R...
fn get_display_config() -> amethyst::Result<DisplayConfig> { #[cfg(not(feature = "dev"))] let display_config = DisplayConfig::load(resource("config/display.ron"))?; #[cfg(feature = "dev")] let display_config = { let mut config = DisplayConfig::load(resource("config/display.ron"))?; con...
with( DispatcherId::ZoneSelect, UpdateHighscoreUi::default(), "zone_select_update_highscore_ui_system", &[], )? .with( DispatcherId::GameOver, UpdateRotate::default(), "game_over_update_rotate_system", &[], ...
function_block-function_prefix_line
[ { "content": "/// Merge `Vec` of settings `T` together.\n\n/// Returns `None` if given `Vec` is empty.\n\nfn merge_settings<T>(all_settings: Vec<T>) -> Option<T>\n\nwhere\n\n T: Merge,\n\n{\n\n let mut merged_settings: Option<T> = None;\n\n for settings in all_settings {\n\n if let Some(merged) ...
Rust
src/fixes.rs
utter-step/dotenv-linter
6005dbcb2ea3de0f233f218bf91d8373813b589e
use crate::common::*; mod ending_blank_line; mod key_without_value; mod lowercase_key; mod quote_character; mod space_character; mod trailing_whitespace; trait Fix { fn name(&self) -> &str; fn fix_warnings( &self, warnings: Vec<&mut Warning>, lines: &mut Vec<LineEntry>, ) -> Optio...
use crate::common::*; mod ending_blank_line; mod key_without_value; mod lowercase_key; mod quote_character; mod space_character; mod trailing_whitespace; trait Fix { fn name(&self) -> &str; fn fix_warnings( &self, warnings: Vec<&mut Warning>, lines: &mut Vec<LineEntry>, ) -> Optio...
}
let fixer = TestFixer { name: "fixer" }; fixer.fix_warnings(vec![&mut warning], &mut lines); assert!(!warning.is_fixed) }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn unfixed_warnings() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", \"A=DEF\\nB=BAR \\nf=BAR\\n\\n\");\n\n\n\n let expected_output = String::from(\n\n \"Fixed warnings:\\n\\\n\n .env:2 TrailingWhitespace: Trailing whitesp...
Rust
core/src/util.rs
kruton/SEGIMAP
7e9e68fecd5e2ad22862ec02c5f1a2be9f35269b
use regex::Regex; use std::env::current_dir; use std::fs; use std::path::Path; use std::path::PathBuf; use walkdir::WalkDir; use crate::folder::Folder; #[macro_export] macro_rules! path_filename_to_str( ($p:ident) => ({ use std::ffi::OsStr; $p.file_name().unwrap_or_else(|| OsStr::new("")).to_str...
use regex::Regex; use std::env::current_dir; use std::fs; use std::path::Path; use std::path::PathBuf; use walkdir::WalkDir; use crate::folder::Folder; #[macro_export] macro_rules! path_filename_to_str( ($p:ident) => ({ use std::ffi::OsStr; $p.file_name().unwrap_or_else(|| OsStr::new("")).to_str...
r); let mut flags = match fs::read_dir(&dir.join("cur")) { Err(_) => "\\Noselect".to_string(), _ => { match fs::read_dir(&dir.join("new")) { Err(_) => "\\Noselect".to_string(), ...
select_args: &[&str], examine: bool, tag: &str, ) -> (Option<Folder>, String) { let err_res = (None, "".to_string()); if select_args.len() < 1 { return err_res; } let mbox_name = select_args[0].trim_matches('"').replace("INBOX", "."); let mut maildir_path = PathBuf::new(); maildi...
random
[ { "content": "/// Parse and perform the store operation specified by `store_args`. Returns the\n\n/// response to the client or None if a BAD response should be sent back to\n\n/// the client\n\npub fn store(folder: &mut Folder, store_args: &[&str], seq_uid: bool, tag: &str) -> Option<String> {\n\n if store_...
Rust
dbcrossbarlib/src/config.rs
drusellers/dbcrossbar
c16ed98771a7d18dbef861f88cc8403839c96936
use failure::Fail; use std::{ env, fmt, fs::{create_dir_all, File}, io::{self, Read}, path::{Path, PathBuf}, }; use toml_edit::{Array, Document, Item, Value}; use crate::common::*; #[cfg(not(target_os = "macos"))] fn system_config_dir() -> Option<PathBuf> { dirs::config_dir() } #[cfg(target_os ...
use failure::Fail; use std::{ env, fmt, fs::{create_dir_all, File}, io::{self, Read}, path::{Path, PathBuf}, }; use toml_edit::{Array, Document, Item, Value}; use crate::common::*; #[cfg(not(target_os = "macos"))] fn system_config_dir() -> Option<PathBuf> { dirs::config_dir() } #[cfg(target_os ...
e value types don't match", key) })?; raw_array.fmt(); Ok(()) } pub fn remove_from_string_array( &mut self, key: &Key<'_>, value: &str, ) -> Result<()> { let raw_array = self.raw_string_array_mut(key)?; let mut indices = ve...
if raw_item.as_str() == Some(value) { return Ok(()); } } raw_array.push(value).map_err(|_| { format_err!("cannot append to {} becaus
function_block-random_span
[ { "content": "/// Generate the `COPY ... FROM ...` SQL we'll pass to `copy_in`. `data_format`\n\n/// should be something like `\"CSV HRADER\"` or `\"BINARY\"`.\n\n///\n\n/// We have a separate function for generating this because we'll use it for\n\n/// multiple `COPY` statements.\n\nfn copy_from_sql(table: &Pg...
Rust
src/prns.rs
Chris--B/comms-rs
8b9278e698c4c817a77449f74fa5ffed3f5c5425
use crate::prelude::*; extern crate num; use num::PrimInt; use std::mem::size_of; pub struct PrnGen<T> { poly_mask: T, state: T, } impl<T: PrimInt> PrnGen<T> { pub fn new(poly_mask: T, state: T) -> PrnGen<T> { PrnGen { poly_mask, state } } ...
use crate::prelude::*; extern crate num; use num::PrimInt; use std::mem::size_of; pub struct PrnGen<T> { poly_mask: T, state: T, } impl<T: PrimInt> PrnGen<T> { pub fn new(poly_mask: T, state: T) -> PrnGen<T> { PrnGen { poly_mask, state } } ...
let fb_bit = T::from((self.state & self.poly_mask).count_ones() % 2) .unwrap(); let output = self.state >> (size_of::<T>() * 8 - 1); self.state = self.state << 1; self.state = self.state | fb_bit; ...
if self.statemap.contains_key(&self.state) { println!("\nSize of <T>: {}", size_of::<T>()); println!("\n\nWrapped, size = {}!", self.statemap.len()); assert_eq!(self.statemap.len(), 255); return None; } else { ...
if_condition
[ { "content": "/// Modulates a byte via BPSK into 8 int16 samples\n\npub fn bpsk_byte_mod(byte: u8) -> Vec<Complex<i16>> {\n\n (0..8)\n\n .map(|i| bpsk_bit_mod(((1_u8 << i) & byte).rotate_right(i)).unwrap())\n\n .collect()\n\n}\n\n\n", "file_path": "src/modulation/digital.rs", "rank": 0,...
Rust
buildkit-llb/src/ops/fs/copy.rs
student-coin/dockerfile-plus
559196e0838404d32fa2f1b81151124573a64898
use std::collections::HashMap; use std::fmt::Debug; use std::path::{Path, PathBuf}; use buildkit_proto::pb; use super::path::{LayerPath, UnsetPath}; use super::FileOperation; use crate::serialization::{Context, Result}; use crate::utils::OutputIdx; #[derive(Debug)] pub struct CopyOperation<From: Debug, To: Debug> {...
use std::collections::HashMap; use std::fmt::Debug; use std::path::{Path, PathBuf}; use buildkit_proto::pb; use super::path::{LayerPath, UnsetPath}; use super::FileOperation; use crate::serialization::{Context, Result}; use crate::utils::OutputIdx; #[derive(Debug)] pub struct CopyOperation<From: Debug, To: Debug> {...
ion: self.description, caps: self.caps, } } } impl<'a> OpWithSource<'a> { pub fn to<P>(self, output: OutputIdx, destination: LayerPath<'a, P>) -> OpWithDestination<'a> where P: AsRef<Path>, { CopyOperation { source: self.source, destination: (...
tPath, follow_symlinks: self.follow_symlinks, recursive: self.recursive, create_path: self.create_path, wildcard: self.wildcard, descript
function_block-random_span
[ { "content": "pub fn from_env<T, I>(pairs: I) -> Result<T>\n\nwhere\n\n T: DeserializeOwned,\n\n I: IntoIterator<Item = (String, String)>,\n\n{\n\n let owned_pairs = pairs.into_iter().collect::<Vec<_>>();\n\n let pairs = {\n\n owned_pairs.iter().filter_map(|(name, value)| {\n\n if ...
Rust
src/shared/binary_rate_limiter.rs
rnestler/cobalt-rs
cf8a23791d4c253c75635a6206e8eeeb3f3e1969
use std::cmp; use std::time::{Duration, Instant}; use ::{Config, RateLimiter}; const MIN_GOOD_MODE_TIME_DELAY: u64 = 1000; const MAX_GOOD_MODE_TIME_DELAY: u64 = 60000; #[derive(Debug, PartialEq)] enum Mode { Good, Bad } #[derive(Debug)] pub struct BinaryRateLimiter { tick: u32, max_tick: u32, ...
use std::cmp; use std::time::{Duration, Instant}; use ::{Config, RateLimiter}; const MIN_GOOD_MODE_TIME_DELAY: u64 = 1000; const MAX_GOOD_MODE_TIME_DELAY: u64 = 60000; #[derive(Debug, PartialEq)] enum Mode { Good, Bad } #[derive(Debug)] pub struct BinaryRateLimiter { tick: u32, max_tick: u32, ...
MIN_GOOD_MODE_TIME_DELAY ); } } }, Mode::Bad => { if time_since(&self.last_bad_time) > self.delay_until_good_mode { self.mode = Mode::Good;...
Mode::Good => { if self.good_time_duration >= 10000 { self.good_time_duration -= 10000; self.delay_until_good_mode = cmp::max...
function_block-random_span
[ { "content": "fn create_connection(config: Option<Config>) -> Connection<BinaryRateLimiter, NoopPacketModifier> {\n\n create_connection_with_modifier::<NoopPacketModifier>(config)\n\n}\n\n\n", "file_path": "src/test/connection.rs", "rank": 3, "score": 102625.29645147541 }, { "content": "/...
Rust
pkmnapi-db/src/pic/mod.rs
kevinselwyn/pkmnapi
170e6b6c9a74e85c377137bc086793898c415125
mod bitplane; mod bitstream; mod encoding_method; pub use encoding_method::EncodingMethod as PicEncodingMethod; use crate::error::{self, Result}; use bitplane::*; use bitstream::*; use image::{self, DynamicImage, ImageBuffer, ImageFormat, Luma}; #[derive(Clone, Debug, PartialEq)] pub struct Pic { pub width: u8...
mod bitplane; mod bitstream; mod encoding_method; pub use encoding_method::EncodingMethod as PicEncodingMethod; use crate::error::{self, Result}; use bitplane::*; use bitstream::*; use image::{self, DynamicImage, ImageBuffer, ImageFormat, Luma}; #[derive(Clone, Debug, PartialEq)] pub struct Pic { pub width: u8...
} pub fn from_png(data: Vec<u8>) -> Result<Self> { Pic::from(data, ImageFormat::Png) } pub fn from_jpeg(data: Vec<u8>) -> Result<Self> { Pic::from(data, ImageFormat::Jpeg) } pub fn decode_bitplane(width: u8, height: u8, bitstream: &mut Bitstream) -> Bitplane { let mut...
Ok(Pic { width, height, pixels, bytes: 0, encoding_method, })
call_expression
[ { "content": "pub fn get_data_raw(data: Data) -> Vec<u8> {\n\n let mut raw = Vec::new();\n\n\n\n data.stream_to(&mut raw).unwrap();\n\n\n\n raw\n\n}\n\n\n", "file_path": "pkmnapi-api/src/utils.rs", "rank": 0, "score": 323389.12652447517 }, { "content": "pub fn get_etag(if_match: Res...
Rust
yarte_codegen/src/wasm/client/each.rs
dskleingeld/yarte
f3cd2db21fc4c64f74ef08f988357a282defee96
use std::{collections::HashSet, iter}; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{parse2, Expr, Ident}; use yarte_dom::dom::{Each, ExprId, VarId}; use super::{ component::get_component, state::{InsertPath, Len, Parent, State, Step}, utils::*, BlackBox, WASMCodeGen, }; ...
use std::{collections::HashSet, iter}; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{parse2, Expr, Ident}; use yarte_dom::dom::{Each, ExprId, VarId}; use super::{ component::get_component, state::{InsertPath, Len, Parent, State, Step}, utils::*, BlackBox, WASMCodeGen, }; ...
}
false }); let render = self.render(curr); assert!(!render.is_empty()); if parents { quote! { for (#vdom, #expr) in #table .iter_mut() .zip(#args) { ...
function_block-function_prefix_line
[ { "content": "pub fn resolve_if_block<'a>(expr: &'a Expr, id: usize, builder: &'a mut DOMBuilder) -> Vec<VarId> {\n\n ResolveIf::new(builder, id).resolve(expr)\n\n}\n\n\n", "file_path": "yarte_dom/src/dom/resolve.rs", "rank": 0, "score": 414137.18538381014 }, { "content": "#[inline]\n\npu...
Rust
src/atsame70q21b/usbhs/usbhs_deveptier_intrpt_mode.rs
tstellanova/atsame7x-pac
f7e24c71181651c141d0727379147c388661ce0e
#[doc = "Writer for register USBHS_DEVEPTIER_INTRPT_MODE[%s]"] pub type W = crate::W<u32, super::USBHS_DEVEPTIER_INTRPT_MODE>; #[doc = "Register USBHS_DEVEPTIER_INTRPT_MODE[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::USBHS_DEVEPTIER_INTRPT_MODE { type Type = u32; #[inline(always)] fn re...
#[doc = "Writer for register USBHS_DEVEPTIER_INTRPT_MODE[%s]"] pub type W = crate::W<u32, super::USBHS_DEVEPTIER_INTRPT_MODE>; #[doc = "Register USBHS_DEVEPTIER_INTRPT_MODE[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::USBHS_DEVEPTIER_INTRPT_MODE { type Type = u32; #[inline(always)] fn re...
#[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc ...
2) & 0x01) << 3); self.w } } #[doc = "Write proxy for field `NAKINES`"] pub struct NAKINES_W<'a> { w: &'a mut W, } impl<'a> NAKINES_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"] ...
random
[]
Rust
crate/workspace_tests/src/game_input/system/shared_controller_input_update_system.rs
Lighty0410/autexousious
99d142d8fdbf2076f3fd929f61b8140d47cf6b86
#[cfg(test)] mod tests { use std::any; use amethyst::{ ecs::{Builder, Entity, Join, ReadStorage, WorldExt, WriteStorage}, Error, }; use amethyst_test::AmethystApplication; use game_input_model::{ config::{ControlBindings, ControllerId}, play::{ControllerInput, InputC...
#[cfg(test)] mod tests { use std::any; use amethyst::{ ecs::{Builder, Entity, Join, ReadStorage, WorldExt, WriteStorage}, Error, }; use amethyst_test::AmethystApplication; use game_input_model::{ config::{ControlBindings, ControllerId}, play::{ControllerInput, InputC...
.expect("Failed to delete entity.") }); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( So...
olled::new(controller_id)) .with(ControllerInput::default()) .build() }) .collect::<Vec<Entity>>(); world.insert(controller_entities); let entity = world.create_entity().with(SharedInputContr...
function_block-random_span
[ { "content": "#[test]\n\nfn read_and_exit() -> Result<(), OutputError> {\n\n let command = CargoBuild::new()\n\n .example(\"01_read_and_exit\")\n\n .current_release()\n\n .run()\n\n .expect(\"Failed to create `cargo` command\")\n\n .command();\n\n Command::from_std(comma...
Rust
binding-generator/src/smart_ptr.rs
tanxxjun321/opencv-rust
1cfceeba79eb8fffce3c8ae698c56cdf2d4e5ff5
use std::{ borrow::Cow, fmt, }; use clang::Entity; use maplit::hashmap; use once_cell::sync::Lazy; use crate::{ Constness, CompiledInterpolation, DefaultElement, DefinitionLocation, Element, EntityElement, GeneratedElement, GeneratorEnv, ReturnTypeWrapper, StrExt, type_ref::TemplateArg, TypeRef, }; #[d...
use std::{ borrow::Cow, fmt, }; use clang::Entity; use maplit::hashmap; use once_cell::sync::Lazy; use crate::{ Constness, CompiledInterpolation, DefaultElement, DefinitionLocation, Element, EntityElement, GeneratedElement, GeneratorEnv, ReturnTypeWrapper, StrExt, type_ref::TemplateArg, TypeRef, }; #[d...
ment_safe_id(&self) -> String { format!("{}-{}", self.rust_module(), self.rust_localalias()) } fn gen_rust(&self, _opencv_version: &str) -> String { static TPL: Lazy<CompiledInterpolation> = Lazy::new( || include_str!("../tpl/smart_ptr/rust.tpl.rs").compile_interpolation() ); static TRAIT_CAST_TPL: Lazy<...
artPtr<'tu, '_> { fn entity(&self) -> Entity<'tu> { self.entity } } impl Element for SmartPtr<'_, '_> { fn is_excluded(&self) -> bool { DefaultElement::is_excluded(self) || self.pointee().is_excluded() } fn is_ignored(&self) -> bool { DefaultElement::is_ignored(self) || self.pointee().is_ignored() } fn ...
random
[ { "content": "/// Default face detector\n\n/// This function is mainly utilized by the implementation of a Facemark Algorithm.\n\n/// End users are advised to use function Facemark::getFaces which can be manually defined\n\n/// and circumvented to the algorithm by Facemark::setFaceDetector.\n\n/// \n\n/// ## Pa...
Rust
src/database.rs
chongyi/inspirer-rs
78cf180162e9ba302b16a6873629e56cfb318b4f
use actix::*; use actix_web::*; use diesel; use diesel::prelude::MysqlConnection; use diesel::r2d2::{ Pool, PooledConnection, ConnectionManager }; use diesel::sql_types; use error::Error; pub struct DatabaseExecutor(pub Pool<ConnectionManager<MysqlConnection>>); pub type Conn = PooledConnection<ConnectionManager<Mys...
use actix::*; use actix_web::*; use diesel; use diesel::prelude::MysqlConnection; use diesel::r2d2::{ Pool, PooledConnection, ConnectionManager }; use diesel::sql_types; use error::Error; pub struct DatabaseExecutor(pub Pool<ConnectionManager<MysqlConnection>>); pub type Conn = PooledConnection<ConnectionManager<Mys...
ome(stringify!($table)))) } }; } #[macro_export] macro_rules! update_by_id { ($conn:expr => ($table:ident # = $id:expr; <- $update:expr)) => { update_by_id!($conn => ($table id = $id; <- $update)) }; ($conn:expr => ($table:ident $id_field:ident = $id:expr; <- $update:expr)) => { ...
> { { use $crate::error::database::map_database_error as map_db_err; diesel::delete($table) .filter($id_field.eq($id)) .execute($conn) .map_err(map_db_err(Some(stringify!($table)))) } }; } #[macro_export] macro_rules! find_by_i...
random
[ { "content": "#[derive(Deserialize, Debug, Clone)]\n\nstruct CreateContent {\n\n\n\n}\n\n\n", "file_path": "src/controllers/admin/content.rs", "rank": 0, "score": 48109.37637340417 }, { "content": "pub fn map_database_error(target: Option<&'static str>) -> impl FnOnce(DieselError) -> Error {...
Rust
src/rocksdb_options.rs
susytech/susy-rocksdb
2ca57972fb6661863c72c1bf8549d63122305be6
extern crate libc; use self::libc::{c_int, size_t}; use std::ffi::CString; use std::mem; use rocksdb_ffi; use merge_operator::{self, MergeOperands, MergeOperatorCallback, full_merge_callback, partial_merge_callback}; use comparator::{self, ComparatorCallback, compare_callback}; pub enum IndexTy...
extern crate libc; use self::libc::{c_int, size_t}; use std::ffi::CString; use std::mem; use rocksdb_ffi; use merge_operator::{self, MergeOperands, MergeOperatorCallback, full_merge_callback, partial_merge_callback}; use comparator::{self, ComparatorCallback, compare_callback}; pub enum IndexTy...
pub fn set_block_size(&mut self, size: usize) { unsafe { rocksdb_ffi::rocksdb_block_based_options_set_block_size(self.inner, size); } } pub fn set_index_type(&mut self, index_type: IndexType) { let it ...
pub fn new() -> BlockBasedOptions { let block_opts = unsafe { rocksdb_ffi::rocksdb_block_based_options_create() }; if block_opts.is_null() { panic!("Could not create rocksdb block based options".to_string()); } BlockBasedOptions { inner: block_opts, filter...
function_block-full_function
[ { "content": "pub fn new_cache(capacity: size_t) -> DBCache {\n\n unsafe { rocksdb_cache_create_lru(capacity) }\n\n}\n\n\n\n#[repr(C)]\n\npub enum DBCompressionType {\n\n DBNoCompression = 0,\n\n DBSnappyCompression = 1,\n\n DBZlibCompression = 2,\n\n DBBz2Compression = 3,\n\n DBLz4Compression...
Rust
src/lib.rs
newAM/clap-num
7d23825a4976b41bfd5d6f8ce70bcfa4ca434fc1
#![doc(html_root_url = "https://docs.rs/clap-num/0.2.0")] #![deny(missing_docs)] use core::convert::TryFrom; use core::str::FromStr; use num_traits::identities::Zero; use num_traits::{sign, CheckedAdd, CheckedMul, CheckedSub, Num}; fn check_range<T: Ord + std::fmt::Display>(val: T, min: T, max: T) -> Result<T, Stri...
#![doc(html_root_url = "https://docs.rs/clap-num/0.2.0")] #![deny(missing_docs)] use core::convert::TryFrom; use core::str::FromStr; use num_traits::identities::Zero; use num_traits::{sign, CheckedAdd, CheckedMul, CheckedSub, Num}; fn check_range<T: Ord + std::fmt::Display>(val: T, min: T, max: T) -> Result<T, Stri...
pre.checked_add(&post) .ok_or_else(|| OVERFLOW_MSG.to_string()) } else { pre.checked_sub(&post) .ok_or_else(|| OVERFLOW_MSG.to_string()) } } else { s.parse::<T>().map_err(stringify) } } pub fn si_number_range<T: Ord + Partia...
000_000, 9, Some(i)), 'M' => return (1_000_000, 6, Some(i)), 'k' => return (1_000, 3, Some(i)), _ => continue, }; } (1, 0, None) } fn find_decimal(s: &str) -> Option<usize> { for (i, c) in s.chars().enumerate() { if c == '.' { return Some(i); ...
random
[ { "content": "fn less_than_100(s: &str) -> Result<u8, String> {\n\n number_range(s, 0, 99)\n\n}\n\n\n", "file_path": "examples/change.rs", "rank": 7, "score": 74407.00790011589 }, { "content": "#[test]\n\nfn test_readme_deps() {\n\n version_sync::assert_markdown_deps_updated!(\"README....
Rust
game/src/sandbox/score.rs
jinzhong2/abstreet
e1c5edc76d636af4f3e4593efc25055bdd637dd7
use crate::game::{State, Transition, WizardState}; use crate::sandbox::gameplay::{cmp_count_fewer, cmp_count_more, cmp_duration_shorter}; use crate::ui::UI; use abstutil::prettyprint_usize; use ezgui::{ hotkey, Choice, Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, ModalMenu, Text, VerticalAlignment, ...
use crate::game::{State, Transition, WizardState}; use crate::sandbox::gameplay::{cmp_count_fewer, cmp_count_more, cmp_duration_shorter}; use crate::ui::UI; use abstutil::prettyprint_usize; use ezgui::{ hotkey, Choice, Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, ModalMenu, Text, VerticalAlignment, ...
fn draw(&self, g: &mut GfxCtx, _: &UI) { g.draw_blocking_text( &self.summary, (HorizontalAlignment::Center, VerticalAlignment::Center), ); self.menu.draw(g); } } fn browse_trips(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> { let ...
return Transition::Pop; } if self.menu.action("browse trips") { return Transition::Push(WizardState::new(Box::new(browse_trips))); } Transition::Keep }
function_block-function_prefix_line
[ { "content": "fn pick_color(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let name = wiz\n\n .wrap(ctx)\n\n .choose_string(\"Change which color?\", || ui.cs.color_names())?;\n\n Some(Transition::Replace(Box::new(ColorChanger {\n\n name: name.clone(),\n...
Rust
src/types/float.rs
dholroyd/hls_m3u8
7e6da6224dad326d915d113357e22f6fc0455c92
use core::cmp::Ordering; use core::convert::TryFrom; use core::str::FromStr; use derive_more::{AsRef, Deref, Display}; use crate::Error; #[derive(AsRef, Deref, Default, Debug, Copy, Clone, Display, PartialOrd)] pub struct Float(f32); impl Float { ...
use core::cmp::Ordering; use core::convert::TryFrom; use core::str::FromStr; use derive_more::{AsRef, Deref, Display}; use crate::Error; #[derive(AsRef, Deref, Default, Debug, Copy, Clone, Display, PartialOrd)] pub struct Float(f32); impl Float { ...
#[must_use] pub const fn as_f32(self) -> f32 { self.0 } } impl FromStr for Float { type Err = Error; fn from_str(input: &str) -> Result<Self, Self::Err> { let float = f32::from_str(input).map_err(|e| Error::parse_float(input, e))?; Self::try_fr...
be finite: `{}`", float); } if float.is_nan() { panic!("float must not be `NaN`"); } Self(float) }
function_block-function_prefixed
[ { "content": " pub trait Sealed {}\n\n impl Sealed for crate::MediaSegment {}\n\n impl Sealed for crate::tags::ExtXMap {}\n\n}\n\n\n", "file_path": "src/traits.rs", "rank": 0, "score": 50488.99251107057 }, { "content": "#[doc(hidden)]\n\npub trait RequiredVersion {\n\n /// Return...
Rust
src/app.rs
rsookram/srs-cli
8825fcf6a7f9055d5f13ac8a23cf55f6d959895d
use crate::Srs; use anyhow::anyhow; use anyhow::Result; use dialoguer::theme::Theme; use dialoguer::Confirm; use srs_cli::Card; use srs_cli::DeckStats; use srs_cli::GlobalStats; use std::io; pub struct App<W: io::Write> { srs: Srs, output: W, } impl<W: io::Write> App<W> { pub fn new(srs: Srs, output: W) -...
use crate::Srs; use anyhow::anyhow; use anyhow::Result; use dialoguer::theme::Theme; use dialoguer::Confirm; use srs_cli::Card; use srs_cli::DeckStats; use srs_cli::GlobalStats; use std::io; pub struct App<W: io::Write> { srs: Srs, output: W, } impl<W: io::Write> App<W> { pub fn new(srs: Srs, output: W) -...
pub fn switch(&mut self, card_id: u64, deck_id: u64) -> Result<()> { let front = self.srs.get_card(card_id)?.front; let deck_name = self.srs.get_deck(deck_id)?.name; if Confirm::new() .with_prompt(format!( "Are you sure you want to switch '{front}' to {deck_nam...
fn output_deck(&mut self, stats: &DeckStats) -> Result<()> { let total = stats.active + stats.suspended + (stats.leech as u32); writeln!( self.output, "{}\n {} / {total} active", stats.name, stats.active )?; if stats.leech > 0 { writeln!(...
function_block-full_function
[ { "content": "CREATE INDEX cardDeckId ON Card(deckId);\n\n\n", "file_path": "src/schema.sql", "rank": 1, "score": 80076.39999327567 }, { "content": "CREATE INDEX answerCardId ON Answer(cardId);\n", "file_path": "src/schema.sql", "rank": 2, "score": 80021.74427068235 }, { ...
Rust
src/cluster/src/local.rs
simlay/fluvio
a42283200e667223d3a52b217d266db8927db4eb
use std::path::Path; use std::borrow::Cow; use std::fs::{File, create_dir_all}; use std::process::{Command, Stdio}; use std::time::Duration; use fluvio::{FluvioConfig}; use tracing::{info, warn, debug}; use fluvio::config::{TlsPolicy, TlsConfig, TlsPaths, ConfigFile, Profile, LOCAL_PROFILE}; use fluvio::metadata::spg:...
use std::path::Path; use std::borrow::Cow; use std::fs::{File, create_dir_all}; use std::process::{Command, Stdio}; use std::time::Duration; use fluvio::{FluvioConfig}; use tracing::{info, warn, debug}; use fluvio::config::{TlsPolicy, TlsConfig, TlsPaths, ConfigFile, Profile, LOCAL_PROFILE}; use fluvio::metadata::spg:...
fn set_server_tls( &self, cmd: &mut Command, tls: &TlsConfig, port: u16, ) -> Result<(), ClusterError> { let paths: Cow<TlsPaths> = match tls { TlsConfig::Files(paths) => Cow::Borrowed(paths), TlsConfig::Inline(certs) => Cow::Owned(certs.try_into...
g_dir))?; let errors = outputs.try_clone()?; debug!("starting sc server"); let mut binary = { let mut cmd = Command::new(std::env::current_exe()?); cmd.arg("run"); cmd.arg("sc"); cmd }; if let TlsPolicy::Verified(tls) = &self.config...
function_block-function_prefixed
[ { "content": "/// create new local cluster and profile\n\npub fn set_local_context(local_config: LocalOpt) -> Result<String, CliError> {\n\n let local_addr = local_config.local;\n\n let mut config_file = ConfigFile::load_default_or_new()?;\n\n\n\n let config = config_file.mut_config();\n\n\n\n // ch...
Rust
exe-common/src/network/hermes.rs
nahern/rust-cardano
03fc923641808361273f1645eef221fdf908f5cf
use cardano::{block::{block, Block, BlockHeader, BlockDate, RawBlock, HeaderHash}, tx::{TxAux}}; use cardano::hash::{HASH_SIZE_256}; use storage; use std::io::Write; use std::time::{SystemTime, Duration}; use std::thread; use futures::{Future, Stream}; use hyper::Client; use tokio_core::reactor::Core; use network::{R...
use cardano::{block::{block, Block, BlockHeader, BlockDate, RawBlock, HeaderHash}, tx::{TxAux}}; use cardano::hash::{HASH_SIZE_256}; use storage; use std::io::Write; use std::time::{SystemTime, Duration}; use std::thread; use futures::{Future, Stream}; use hyper::Client; use tokio_core::reactor::Core; use network::{R...
from = BlockRef { hash: hdr.compute_hash(), parent: hdr.get_previous_header(), date: hdr.get_blockdate() }; inclusive = false; } } else { ...
if from.date <= hdr.get_blockdate() { got_block(&hdr.compute_hash(), &block, &block_raw); }
if_condition
[ { "content": "pub fn resolve_date_to_blockhash(storage: &Storage, tip: &BlockHash, date: &BlockDate) -> Result<Option<BlockHash>> {\n\n let epoch = date.get_epochid();\n\n match epoch_open_packref(&storage.config, epoch) {\n\n Ok(mut handle) => {\n\n let slotid = match date {\n\n ...
Rust
argonautica-rs/examples/example_serde.rs
philipahlberg/argonautica
bd9d7cb0f10dcf9a92f8b2e913b7116c1f10099d
extern crate argonautica; extern crate failure; extern crate serde; extern crate serde_json; use argonautica::{Hasher, Verifier}; fn serialize_hasher() -> Result<String, failure::Error> { let additional_data = [1u8, 2, 3, 4]; let salt = [1u8, 2, 3, 4, 5, 6, 7, 8]; let mut hasher = Hasher::default(); h...
extern crate argonautica; extern crate failure; extern crate serde; extern crate serde_json; use argonautica::{Hasher, Verifier}; fn serialize_hasher() -> Result<String, failure::Error> { let additional_data = [1u8, 2, 3, 4]; let salt = [1u8, 2, 3, 4, 5, 6, 7, 8]; let mut hasher = Hasher::default(); h...
fn deserialize_verifier(j: &str) -> Result<argonautica::Verifier, failure::Error> { let verifier: Verifier = serde_json::from_str(&j)?; println!("*** Deserialized Verifier ***"); println!("{:#?}\n", &verifier); ...
fn serialize_verifier() -> Result<String, failure::Error> { let additional_data = [1u8, 2, 3, 4]; let mut verifier = Verifier::default(); verifier .with_additional_data(&additional_data[..]) .with_hash("$argon2id$v=19$m=4096,t=128,p=2$c29tZXNhbHQ$WwD2/wGGTuw7u4BW8sLM0Q") .with_passwo...
function_block-function_prefixed
[ { "content": "fn bench_crates(c: &mut Criterion) {\n\n // argon2rs\n\n let hasher = argon2rs::Argon2::new(\n\n /* passes */ DEFAULT_ITERATIONS,\n\n /* lanes */ default_lanes(),\n\n /* kib */ DEFAULT_MEMORY_SIZE,\n\n /* variant */ argon2rs::Variant::Argon2i,\n\n )\n\n .unw...
Rust
src/procfs.rs
wojciechkepka/rustop
b8ac5b8c36aae9364fb16b64030d3de614e94747
use super::*; pub async fn os_release() -> Result<String> { Ok(fs::read_to_string(SysProperty::OsRelease.path())?.trim_end().to_string()) } pub async fn hostname() -> Result<String> { Ok(fs::read_to_string(SysProperty::Hostname.path())?.trim_end().to_string()) } pub async fn uptime() -> Result<f64> { let...
use super::*; pub async fn os_release() -> Result<String> { Ok(fs::read_to_string(SysProperty::OsRelease.path())?.trim_end().to_string()) } pub async fn hostname() -> Result<String> { Ok(fs::read_to_string(SysProperty::Hostname.path())?.trim_end().to_string()) } pub async fn uptime() -> Result<f64> { let...
} partition.major = handle(storage_dev[1].parse::<u16>()); partition.minor = handle(storage_dev[2].parse::<u16>()); partition.size = handle(storage_dev[3].parse::<u64>()) * 1024; partition.name = partition_name.to_string(); partitions.push(partition); } partition...
if &found_partition[1] == partition_name { partition.mountpoint = found_partition[2].to_string(); partition.filesystem = found_partition[3].to_string(); break; } else { partition.mountpoint = "".to_string(); partition.filesystem...
if_condition
[]
Rust
src/graph.rs
fexolm/max_clique
c181294902c53842fd06450c7a1618daf5bc270b
use std::collections::*; use std::fs::File; use std::io::*; use std::iter::*; use std::sync::Arc; use std::sync::RwLock; use std::u64; use rayon::{Scope}; use regex::Regex; pub struct Graph { adj_list: HashMap<u16, HashSet<u16>>, } pub struct MaxCliqueData { max_clique: Vec<u16>, current_clique: Vec<u16>...
use std::collections::*; use std::fs::File; use std::io::*; use std::iter::*; use std::sync::Arc; use std::sync::RwLock; use std::u64; use rayon::{Scope}; use regex::Regex; pub struct Graph { adj_list: HashMap<u16, HashSet<u16>>, } pub struct MaxCliqueData { max_clique: Vec<u16>, current_clique: Vec<u16>...
fn greedy_coloring(&self, vertexes: &HashSet<u16>) -> HashMap<u16, i16> { let mut res = HashMap::new(); let mut powers = Vec::from_iter( vertexes.iter().copied() .map(|v| (v, Vec::from_iter(self.subgraph_neighbours(vertexes, v)))) ); powers.sort_unstabl...
fn max_clique_heuristic(&self, data: &mut MaxCliqueData) { let mut queue = BinaryHeap::from_iter( self.adj_list.keys().copied().map(|n| (self.degree(n), n))); while let Some((_, node)) = queue.pop() { if self.degree(node) > data.max_clique.len() as u16 { data.cur...
function_block-full_function
[ { "content": "fn print_clique(v: &Vec<u16>) {\n\n for &n in v {\n\n print!(\"{} \", n);\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 3, "score": 38032.75972512833 }, { "content": "fn main() -> Result<()> {\n\n use graph::Graph;\n\n use time::PreciseTime;\n\n\n\n ...
Rust
necsim/impls/std/src/cogs/active_lineage_sampler/gillespie/sampler.rs
fossabot/necsim-rust
996b6a6977bc27a997a123e3e4f5a7b11e1a1aef
use necsim_core::{ cogs::{ ActiveLineageSampler, CoalescenceSampler, DispersalSampler, EmigrationExit, EmptyActiveLineageSamplerError, GloballyCoherentLineageStore, Habitat, ImmigrationEntry, LineageReference, PeekableActiveLineageSampler, RngCore, SpeciationProbability, TurnoverRate...
use necsim_core::{ cogs::{ ActiveLineageSampler, CoalescenceSampler, DispersalSampler, EmigrationExit, EmptyActiveLineageSamplerError, GloballyCoherentLineageStore, Habitat, ImmigrationEntry, LineageReference, PeekableActiveLineageSampler, RngCore, SpeciationProbability, TurnoverRate...
} #[contract_trait] impl< H: Habitat, G: RngCore, R: LineageReference<H>, S: GloballyCoherentLineageStore<H, R>, X: EmigrationExit<H, G, R, S>, D: DispersalSampler<H, G>, C: CoalescenceSampler<H, R, S>, T: TurnoverRate<H>, N: SpeciationProbabilit...
fn insert_new_lineage_to_indexed_location( &mut self, global_reference: GlobalLineageReference, indexed_location: IndexedLocation, time: PositiveF64, simulation: &mut PartialSimulation<H, G, R, S, X, D, C, T, N, E>, rng: &mut G, ) { use necsim_core::cogs::RngS...
function_block-full_function
[ { "content": "#[contract_trait]\n\npub trait EmigrationExit<H: Habitat, G: RngCore, R: LineageReference<H>, S: LineageStore<H, R>>:\n\n crate::cogs::Backup + core::fmt::Debug\n\n{\n\n #[must_use]\n\n #[debug_ensures(match &ret {\n\n Some((\n\n ret_lineage_reference,\n\n ret...
Rust
sos21-gateway/database/src/pending_project_repository.rs
sohosai/sos21-backend
f1883844b0e5c68d6b3f9d159c9268142abc81b4
use crate::project_repository::{ from_project_attributes, from_project_category, to_project_attributes, to_project_category, }; use crate::user_repository::to_user; use anyhow::Result; use futures::lock::Mutex; use ref_cast::RefCast; use sos21_database::{command, model as data, query}; use sos21_domain::context::p...
use crate::project_repository::{ from_project_attributes, from_project_category, to_project_attributes, to_project_category, }; use crate::user_repository::to_user; use anyhow::Result; use futures::lock::Mutex; use ref_cast::RefCast; use sos21_database::{command, model as data, query}; use sos21_domain::context::p...
me: group_name.into_string(), kana_group_name: kana_group_name.into_string(), description: description.into_string(), category: from_project_category(category), attributes: from_project_attributes(&attributes), } } fn to_pending_project_with_owner( pending_project_with_owner: da...
ectKanaGroupName, ProjectKanaName, ProjectName, }, user::UserId, }; use sqlx::{Postgres, Transaction}; #[derive(Debug, RefCast)] #[repr(transparent)] pub struct PendingProjectDatabase(Mutex<Transaction<'static, Postgres>>); #[async_trait::async_trait] impl PendingProjectRepository for PendingProjectDatabase {...
random
[ { "content": "use crate::model::project::{ProjectAttribute, ProjectCategory};\n\n\n\nuse sos21_domain::model::project_query as entity;\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub struct ProjectQueryConjunction {\n\n pub category: Option<ProjectCategory>,\n\n pub attributes: Vec<ProjectAttribute>,...
Rust
examples/bvh_viewer/main.rs
tpltnt/bvh_anim
1f5e37061c6b67c9a0746591dec752adc114a540
#![allow(unused)] mod arcball_camera; use arcball_camera::ArcBall; use bvh_anim::{Bvh, JointData}; use gl::{self, types::*}; use glutin::{ dpi::LogicalSize, ContextBuilder, DeviceEvent, ElementState, Event, EventsLoop, KeyboardInput, MouseButton, Touch, TouchPhase, VirtualKeyCode, WindowBuilder, WindowEvent, ...
#![allow(unused)] mod arcball_camera; use arcball_camera::ArcBall; use bvh_anim::{Bvh, JointData}; use gl::{self, types::*}; use glutin::{ dpi::LogicalSize, ContextBuilder, DeviceEvent, ElementState, Event, EventsLoop, KeyboardInput, MouseButton, Touch, TouchPhase, VirtualKeyCode, WindowBuilder, WindowEvent, ...
ref state, button: MouseButton::Left, .. } => match state { ElementState::Pressed => is_mouse_down = true, ElementState::Released => is_mouse_down = false, }, WindowEvent::Touch(ref t) => { ...
delta: (ref mx, ref my), } if is_mouse_down => { arcball.on_mouse_move(*mx as f32, *my as f32); } _ => {} }, Event::WindowEvent { ref event, .. } => match event { WindowEven...
random
[ { "content": "fn collect_channels(channels: &[ChannelType], num_channels: &mut usize) -> SmallVec<[Channel; 6]> {\n\n let out_channels = channels\n\n .iter()\n\n .enumerate()\n\n .map(|(motion_index, &channel_type)| Channel {\n\n channel_type,\n\n motion_index: moti...
Rust
library/src/canvas.rs
feenkcom/libskia
2a9e95a65acb944fae8167abb93c91443ce71a95
use boxer::array::BoxerArray; use boxer::boxes::{ReferenceBox, ReferenceBoxPointer}; use boxer::{assert_reference_box, function}; use boxer::{ValueBox, ValueBoxPointer}; use float_cmp::ApproxEqUlps; use layer::SaveLayerRecWrapper; use skia_safe::canvas::{PointMode, SaveLayerRec}; use skia_safe::utils::shadow_utils::Sha...
use boxer::array::BoxerArray; use boxer::boxes::{ReferenceBox, ReferenceBoxPointer}; use boxer::{assert_reference_box, function}; use boxer::{ValueBox, ValueBoxPointer}; use float_cmp::ApproxEqUlps; use layer::SaveLayerRecWrapper; use skia_safe::canvas::{PointMode, SaveLayerRec}; use skia_safe::utils::shadow_utils::Sha...
#[no_mangle] pub fn skia_canvas_draw_rrect( canvas_ptr: *mut ReferenceBox<Canvas>, rrect_ptr: *mut ValueBox<RRect>, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { rrect_ptr.with_not_null(|rrect| { paint_pt...
vas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_circle(Point::new(center_x, center_y), radius, paint); }); }); }
function_block-function_prefixed
[ { "content": "#[no_mangle]\n\npub fn skia_paint_set_rgba(paint_ptr: *mut ValueBox<Paint>, r: u8, g: u8, b: u8, a: u8) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_argb(a, r, g, b);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 0, "score": 443120.23559253 }...
Rust
src/strencrypt.rs
JohnAgapeyev/R2D2
bc2ca7143844fe82b4ecc3e221de667a8bb5b3b4
use quote::*; use syn::spanned::Spanned; use syn::visit_mut::*; use syn::*; use crate::crypto::*; use crate::parse::*; #[allow(unused_imports)] use crate as r2d2; struct MemEncCtx { ctx: MemoryEncryptionCtx<XChaCha20Poly1305>, needs_owned_str: bool, } impl ToTokens for MemEncCtx { fn to_tokens(&self, to...
use quote::*; use syn::spanned::Spanned; use syn::visit_mut::*; use syn::*; use crate::crypto::*; use crate::parse::*; #[allow(unused_imports)] use crate as r2d2; struct MemEncCtx { ctx: MemoryEncryptionCtx<XChaCha20Poly1305>, needs_owned_str: bool, } impl ToTokens for MemEncCtx { fn to_tokens(&self, to...
fn visit_expr_mut(&mut self, node: &mut Expr) { /* * Skip function call expressions * This is a case of lifetime scoping problems * Given a function foo("hello"), only a String type would support decryption * If the function takes a &str, the temporary will go out of sc...
fn visit_macro_mut(&mut self, node: &mut Macro) { let macro_path = node .path .get_ident() .map(|ident| ident.to_string()) .unwrap_or_default(); let mut can_encrypt = match macro_path.as_str() { "println" => true, "eprintln" => true...
function_block-full_function
[ { "content": "fn is_shuffle_attr(attr: &str) -> bool {\n\n match attr {\n\n SHUFFLE_ATTR_NAME => true,\n\n _ => false,\n\n }\n\n}\n\n\n", "file_path": "src/shuffle.rs", "rank": 1, "score": 200775.69576019843 }, { "content": "/// Render a sparkline of `data` into `buffer`....
Rust
src/connectivity/network/ping3/src/store.rs
EnderNightLord-ChromeBook/zircon-rpi
b09b1eb3aa7a127c65568229fe10edd251869283
use fuchsia_async as fasync; use fuchsia_zircon as zx; use thiserror::Error; #[derive(Clone)] pub struct SequenceStore { next_seq: u16, last_seq: u16, start_time: zx::Time, } #[derive(Error, Debug)] #[error("No sequence numbers available")] pub struct OutOfSequencesError; #[derive...
use fuchsia_async as fasync; use fuchsia_zircon as zx; use thiserror::Error; #[derive(Clone)] pub struct SequenceStore { next_seq: u16, last_seq: u16, start_time: zx::Time, } #[derive(Error, Debug)] #[error("No sequence numbers available")] pub struct OutOfSequencesError; #[derive...
); let (_, b_time) = s.take().expect("Failed to take"); assert_eq!(b_time - a_time, SHORT_DELAY); } #[test] fn give_latency() { let executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (a, a_tim...
.expect("Failed to take").0, i); } s.take().expect_err("There shouldn't be any more sequence numbers available"); } #[test] fn give_out_of_order() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); ...
random
[]
Rust
src/application/core.rs
mass10/rzip
d9a3cf8dbe3208a382bd5da3d353331a27e59df0
use super::errors::ApplicationError; use crate::configuration; use crate::functions; use std::io::Read; #[allow(unused)] fn matches(pattern: &str, text: &str) -> bool { let reg = regex::Regex::new(pattern); if reg.is_err() { panic!("[ERROR] Fatal error. (reason: {})", reg.err().unwrap()); return false; } let...
use super::errors::ApplicationError; use crate::configuration; use crate::functions; use std::io::Read; #[allow(unused)] fn matches(pattern: &str, text: &str) -> bool { let reg = regex::Regex::new(pattern); if reg.is_err() { pani
pub struct Zipper; impl Zipper { pub fn new() -> Zipper { let instance = Zipper {}; return instance; } fn append_entry(&self, archiver: &mut zip::ZipWriter<std::fs::File>, base_name: &str, path: &str, settings: &configuration::Settings) -> Result<(), Box<dyn std::error::Error>> { use cr...
c!("[ERROR] Fatal error. (reason: {})", reg.err().unwrap()); return false; } let result = reg.unwrap().find(text); if result.is_none() { return false; } return true; }
function_block-function_prefixed
[ { "content": "/// Build a path from `path` and `name`.\n\n///\n\n/// # Arguments\n\n/// * `parent` Parent path.\n\n/// * `name` Name of the file or directory.\n\n///\n\n/// # Returns\n\n/// * Path to the file or directory.\n\npub fn build_path(parent: &str, name: &str) -> String {\n\n\tif parent == \"\" {\n\n\t...
Rust
src/headers/mod.rs
vv9k/mobi-rs
c15606e2842759db9797122c5f8196d36388feba
pub(crate) mod exth; pub(crate) mod header; pub(crate) mod mobih; pub(crate) mod palmdoch; pub use self::{ exth::{ExtHeader, ExthRecord}, header::{Header, HeaderParseError}, mobih::{Language, MobiHeader, MobiType, TextEncoding}, palmdoch::{Compression, Encryption, PalmDocHeader}, }; use crate::record:...
pub(crate) mod exth; pub(crate) mod header; pub(crate) mod mobih; pub(crate) mod palmdoch; pub use self::{ exth::{ExtHeader, ExthRecord}, header::{Header, HeaderParseError}, mobih::{Language, MobiHeader, MobiType, TextEncoding}, palmdoch::{Compression, Encryption, PalmDocHeader}, }; use crate::record:...
; reader.set_position((records.records[0].offset + mobi.name_offset) as usize)?; let name = reader.read_vec_header(mobi.name_length as usize)?; Ok(MobiMetadata { name, header, records, palmdoc, mobi, exth, }) }...
if mobi.has_exth_header() { ExtHeader::parse(reader)? } else { ExtHeader::default() }
if_condition
[ { "content": "pub fn decompress(data: &[u8]) -> Vec<u8> {\n\n let length = data.len();\n\n let mut pos: usize = 0;\n\n let mut text_pos: usize = 0;\n\n let mut text: Vec<u8> = vec![];\n\n\n\n let mut prev = None;\n\n while pos < length {\n\n let byte = data[pos];\n\n pos += 1;\n\...
Rust
src/walker.rs
oxidecomputer/openapi-lint
025fc867b7da62b33474d0a765823653a437f362
use indexmap::IndexMap; use openapiv3::{ Components, MediaType, OpenAPI, Operation, Parameter, ParameterSchemaOrContent, PathItem, ReferenceOr, RequestBody, Response, Schema, }; pub(crate) trait SchemaWalker<'a> { type SchemaIterator: Iterator<Item = (Option<String>, &'a Schema)>; fn walk(&'a self) -...
use indexmap::IndexMap; use openapiv3::{ Components, MediaType, OpenAPI, Operation, Parameter, ParameterSchemaOrContent, PathItem, ReferenceOr, RequestBody, Response, Schema, }; pub(crate) trait SchemaWalker<'a> { type SchemaIterator: Iterator<Item = (Option<String>, &'a Schema)>; fn walk(&'a self) -...
} impl<'a> SchemaWalker<'a> for IndexMap<String, ReferenceOr<Schema>> { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.iter() .flat_map(|(key, value)| { value .walk() ...
fn walk(&'a self) -> Self::SchemaIterator { match self { None => Vec::<(Option<String>, &Schema)>::new().into_iter(), Some(walker) => walker.walk().collect::<Vec<_>>().into_iter(), } }
function_block-full_function
[ { "content": "trait ComponentLookup: Sized {\n\n fn get_components(components: &Components) -> &IndexMap<String, ReferenceOr<Self>>;\n\n}\n\n\n\nimpl<T: ComponentLookup> ReferenceOrExt<T> for openapiv3::ReferenceOr<T> {\n\n fn item<'a>(&'a self, components: &'a Option<Components>) -> Option<&'a T> {\n\n ...
Rust
native-windows-gui/src/controls/notice.rs
gyk/native-windows-gui
163d0fcb5c2af8a859f603ce23a7ec218e9b6813
use super::control_handle::ControlHandle; use crate::win32::{window::build_notice, window_helper as wh}; use crate::NwgError; const NOT_BOUND: &str = "Notice is not yet bound to a winapi object"; const UNUSABLE_NOTICE: &str = "Notice parent window was freed"; const BAD_HANDLE: &str = "INTERNAL ERROR: Notice handle is ...
use super::control_handle::ControlHandle; use crate::win32::{window::build_notice, window_helper as wh}; use crate::NwgError; const NOT_BOUND: &str = "Notice is not yet bound to a winapi object"; const UNUSABLE_NOTICE: &str = "Notice parent window was freed"; const BAD_HANDLE: &str = "INTERNAL ERROR: Notice handle is ...
}
pub fn build(self, out: &mut Notice) -> Result<(), NwgError> { let parent = match self.parent { Some(p) => match p.hwnd() { Some(handle) => Ok(handle), None => Err(NwgError::control_create("Wrong parent type")), }, None => Err(NwgError::no_pare...
function_block-full_function
[ { "content": "pub fn check_hwnd(handle: &ControlHandle, not_bound: &str, bad_handle: &str) -> HWND {\n\n use winapi::um::winuser::IsWindow;\n\n\n\n if handle.blank() {\n\n panic!(\"{}\", not_bound);\n\n }\n\n match handle.hwnd() {\n\n Some(hwnd) => match unsafe { IsWindow(hwnd) } {\n\n...
Rust
src/lib.rs
helium/longfi-device-rs
97ad8f380205a0b0b1c90ff0513e30c576b71e5d
#![cfg_attr(not(test), no_std)] use longfi_sys; pub use longfi_sys::AntPinsMode_t as AntPinsMode; pub use longfi_sys::BoardBindings_t as BoardBindings; pub use longfi_sys::ClientEvent_t as ClientEvent; pub use longfi_sys::LongFiAuthCallbacks as AuthCb; pub use longfi_sys::LongFiAuthMode_t as AuthMode; pub use longfi_s...
#![cfg_attr(not(test), no_std)] use longfi_sys; pub use longfi_sys::AntPinsMode_t as AntPinsMode; pub use longfi_sys::BoardBindings_t as BoardBindings; pub use longfi_sys::ClientEvent_t as ClientEvent; pub use longfi_sys::LongFiAuthCallbacks as AuthCb; pub use longfi_sys::LongFiAuthMode_t as AuthMode; pub use longfi_s...
longfi_sys::longfi_init(&mut longfi_radio.c_handle); Ok(longfi_radio) } else { Err(Error::NoRadioPointer) } } } pub fn set_buffer(&mut self, buffer: &mut [u8]) { unsafe { longfi_sys::longfi_set_buf(&mut self....
let mut longfi_radio = LongFi { c_handle: longfi_sys::longfi_new_handle(bindings, radio_ptr, config, auth_cb), };
assignment_statement
[ { "content": "pub fn initialize_irq(\n\n pin: gpiob::PB4<Uninitialized>,\n\n syscfg: &mut hal::syscfg::SYSCFG,\n\n exti: &mut exti::Exti,\n\n) -> gpiob::PB4<Input<PullUp>> {\n\n let dio0 = pin.into_pull_up_input();\n\n\n\n exti.listen_gpio(\n\n syscfg,\n\n dio0.port(),\n\n Gp...
Rust
src/dft/mod.rs
feos-org/feos-gc-pcsaft
4ce900cab46848a4f6352432d6d23c8f1fda5b6b
use crate::eos::GcPcSaftOptions; use feos_core::MolarWeight; use feos_dft::adsorption::FluidParameters; use feos_dft::fundamental_measure_theory::{FMTContribution, FMTProperties, FMTVersion}; use feos_dft::{FunctionalContribution, HelmholtzEnergyFunctional, MoleculeShape, DFT}; use ndarray::Array1; use num_dual::DualNu...
use crate::eos::GcPcSaftOptions; use feos_core::MolarWeight; use feos_dft::adsorption::FluidParameters; use feos_dft::fundamental_measure_theory::{FMTContribution, FMTProperties, FMTVersion}; use feos_dft::{FunctionalContribution, HelmholtzEnergyFunctional, MoleculeShape, DFT}; use ndarray::Array1; use num_dual::DualNu...
fn compute_max_density(&self, moles: &Array1<f64>) -> f64 { let p = &self.parameters; let moles_segments: Array1<f64> = p.component_index.iter().map(|&i| moles[i]).collect(); self.options.max_eta * moles.sum() / (FRAC_PI_6 * &p.m * p.sigma.mapv(|v| v.powi(3)) * moles_segments)....
fn subset(&self, component_list: &[usize]) -> DFT<Self> { Self::with_options( Rc::new(self.parameters.subset(component_list)), self.fmt_version, self.options, ) }
function_block-full_function
[ { "content": "#[pymodule]\n\npub fn dft(_py: Python<'_>, m: &PyModule) -> PyResult<()> {\n\n m.add_class::<PyGcPcSaftFunctional>()?;\n\n m.add_class::<PyState>()?;\n\n m.add_class::<PyPhaseDiagram>()?;\n\n m.add_class::<PyPhaseEquilibrium>()?;\n\n m.add_class::<PyPlanarInterface>()?;\n\n m.add...
Rust
rust-kernel-rdma/KRdmaKit/src/qp/rc_op.rs
Hf7WCdtO/KRCore
52369924ba175419912a274634d368d478dda501
use rust_kernel_rdma_base::*; use crate::qp::{DoorbellHelper, RC}; use core::option::Option; use linux_kernel_module::bindings::*; use linux_kernel_module::{Error}; use alloc::sync::Arc; #[allow(unused_imports)] pub struct RCOp<'a> { qp: &'a Arc<RC>, } impl<'a> RCOp<'a> { pub fn new(qp: &'a Arc<RC>) -> Self {...
use rust_kernel_rdma_base::*; use crate::qp::{DoorbellHelper, RC}; use core::option::Option; use linux_kernel_module::bindings::*; use linux_kernel_module::{Error}; use alloc::sync::Arc; #[allow(unused_imports)] pub struct RCOp<'a> { qp: &'a Arc<RC>, } impl<'a> RCOp<'a> { pub fn new(qp: &'a Arc<RC>) -> Self {...
WR_RDMA_READ, local_ptr, lkey, sz, remote_addr, rkey, ib_send_flags::IB_SEND_SIGNALED) .and_then(|()| Ok(self.wait_til_comp())) } #[inline] pub fn write(&mut self, local_ptr: u64, lkey: u32, sz: usize, remote_...
None } #[inline] fn post_send( &mut self, mut sge: ib_sge, mut wr: ib_rdma_wr, ) -> linux_kernel_module::KernelResult<()> { wr.wr.sg_list = &mut sge as *mut _; wr.wr.num_sge = 1; let mut bad_wr: *mut ib_send_wr = core::ptr::null_mut(); ...
random
[ { "content": "#[inline]\n\nfn create_ib_qp(config: &Config, pd: *mut ib_pd, qp_type: u32, cq: *mut ib_cq, recv_cq: *mut ib_cq, srq: *mut ib_srq) -> *mut ib_qp {\n\n let mut qp_attr: ib_qp_init_attr = Default::default();\n\n qp_attr.cap.max_send_wr = config.max_send_wr_sz as u32;\n\n qp_attr.cap.max_rec...
Rust
pallet/src/tests.rs
4meta5/deleg8
6bca6d8e1385ea259f7e52eb03dee46d2be112b7
#![cfg(test)] use super::*; use frame_support::{ assert_noop, assert_ok, impl_outer_event, impl_outer_origin, parameter_types, weights::Weight, }; use sp_core::H256; use sp_runtime::{ testing::Header, traits::IdentityLookup, Perbill, }; pub type AccountId = u64; pub type BlockNumbe...
#![cfg(test)] use super::*; use frame_support::{ assert_noop, assert_ok, impl_outer_event, impl_outer_origin, parameter_types, weights::Weight, }; use sp_core::H256; use sp_runtime::{ testing::Header, traits::IdentityLookup, Perbill, }; pub type AccountId = u64; pub type BlockNumbe...
#[test] fn genesis_config_works() { new_test_ext().execute_with(|| { assert!(System::events().is_empty()); }); } #[test] fn create_root_works() { new_test_ext().execute_with(|| { assert_noop!( Delegate::create_root(Origin::signed(21)), DispatchError::Module { ...
unwrap(); pallet_balances::GenesisConfig::<TestRuntime> { balances: vec![ (1, 1000), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100), ], } .assimilate_storage(&mut t) .unwrap(); let mut ext: sp_io::TestExternali...
function_block-function_prefix_line
[ { "content": "pub trait Trait: System {\n\n /// Overarching event type\n\n type Event: From<Event<Self>> + Into<<Self as System>::Event>;\n\n\n\n /// The identifier for trees\n\n type TreeId: Parameter\n\n + Member\n\n + AtLeast32Bit\n\n + Codec\n\n + Default\n\n +...
Rust
src/run_plan.rs
camchenry/lolbench
941ebb099a398ad33cb3658bcd021a98081dfa80
use super::Result; use std::{ fmt::{Display, Formatter, Result as FmtResult}, path::PathBuf, process::Command, }; use ring::digest::{digest, SHA256}; use marky_mark::Benchmark; use cpu_shield::{RenameThisCommandWrapper, ShieldSpec}; use toolchain::Toolchain; use CriterionConfig; #[derive(Clone, Debug, ...
use super::Result; use std::{ fmt::{Display, Formatter, Result as FmtResult}, path::PathBuf, process::Command, }; use ring::digest::{digest, SHA256}; use marky_mark::Benchmark; use cpu_shield::{RenameThisCommandWrapper, ShieldSpec}; use toolchain::Toolchain; use CriterionConfig; #[derive(Clone, Debug, ...
} impl RunPlan { pub fn new( benchmark: Benchmark, bench_config: Option<CriterionConfig>, shield: Option<ShieldSpec>, toolchain: Option<Toolchain>, source_path: PathBuf, ) -> Result<Self> { let binary_name = source_path .file_stem() .unwr...
s!( "{}: {}::{}@{:?}", tcs, self.benchmark.crate_name, self.benchmark.name, self.benchmark.runner, )) }
function_block-function_prefixed
[ { "content": "fn most_covered_toolchains_runtimes(data_dir: impl AsRef<Path>) -> Result<Vec<(R64, String)>> {\n\n info!(\"finding all existing estimates\");\n\n let estimates = GitStore::ensure_initialized(data_dir)?.all_stored_estimates()?;\n\n\n\n info!(\"reorganizing them by toolchain\");\n\n let...
Rust
bin/inx-chronicle/src/api/stardust/v2/routes.rs
iotaledger/inx-chronicle
d7d1643a57f418fec5550ad8c24a63986a2c91a6
use std::str::FromStr; use axum::{ extract::{Extension, Path}, routing::*, Router, }; use chronicle::{ db::MongoDb, types::{ stardust::block::{BlockId, MilestoneId, OutputId, TransactionId}, tangle::MilestoneIndex, }, }; use super::responses::*; use crate::api::{error::ApiErr...
use std::str::FromStr; use axum::{ extract::{Extension, Path}, routing::*, Router, }; use chronicle::{ db::MongoDb, types::{ stardust::block::{BlockId, MilestoneId, OutputId, TransactionId}, tangle::MilestoneIndex, }, }; use super::responses::*; use crate::api::{error::ApiErr...
} async fn transaction_included_block( database: Extension<MongoDb>, Path(transaction_id): Path<String>, ) -> ApiResult<BlockResponse> { let transaction_id_dto = TransactionId::from_str(&transaction_id).map_err(ApiError::bad_parse)?; let block = database .get_block_for_transaction(&transaction...
Ok(OutputMetadataResponse { block_id: metadata.block_id.to_hex(), transaction_id: metadata.transaction_id.to_hex(), output_index: metadata.output_id.index, is_spent: metadata.spent.is_some(), milestone_index_spent: metadata.spent.as_ref().map(|s| s.spent.milestone_index), ...
call_expression
[ { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::payload::milestone as bee;\n\nuse mongodb::bson::{spec::BinarySubtype, Binary, Bson};\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::types::util::bytify...
Rust
src/asm/aarch64/cdef.rs
EwoutH/rav1e
39f35d0c94a0523bc6c26042bb54f7dca28efb37
use crate::cdef::*; use crate::cpu_features::CpuFeatureLevel; use crate::frame::*; use crate::tiling::PlaneRegionMut; use crate::util::*; type CdefPaddingFn = unsafe extern fn( tmp: *mut u16, src: *const u8, src_stride: isize, left: *const [u8; 2], top: *const u8, h: i32, edges: isize, ); type CdefPad...
use crate::cdef::*; use crate::cpu_features::CpuFeatureLevel; use crate::frame::*; use crate::tiling::PlaneRegionMut; use crate::util::*; type CdefPaddingFn = unsafe extern fn( tmp: *mut u16, src: *const u8, src_stride: isize, left: *const [u8; 2], top: *const u8, h: i32, edges: isize, ); type CdefPad...
extern { fn rav1e_cdef_find_dir_8bpc_neon( tmp: *const u8, tmp_stride: isize, var: *mut u32, ) -> i32; } extern { fn rav1e_cdef_find_dir_16bpc_neon( tmp: *const u16, tmp_stride: isize, var: *mut u32, max_bitdepth: i32, ) -> i32; } cpu_function_lookup_table!( CDEF_DIR_LBD_FNS: [Option<CdefDirLBDFn>...
pub(crate) fn cdef_find_dir<T: Pixel>( img: &PlaneSlice<'_, T>, var: &mut u32, coeff_shift: usize, cpu: CpuFeatureLevel, ) -> i32 { let call_rust = |var: &mut u32| rust::cdef_find_dir::<T>(img, var, coeff_shift, cpu); #[cfg(feature = "check_asm")] let (ref_dir, ref_var) = { let mut var: u32 = 0; ...
function_block-full_function
[ { "content": "type CdefDirHBDFn = unsafe extern fn(\n\n tmp: *const u16,\n\n tmp_stride: isize,\n\n var: *mut u32,\n\n bitdepth_max: i32,\n\n) -> i32;\n\n\n\n#[inline(always)]\n\n#[allow(clippy::let_and_return)]\n\npub(crate) fn cdef_find_dir<T: Pixel>(\n\n img: &PlaneSlice<'_, T>, var: &mut u32, coeff_shi...
Rust
pnets_shrink/tests/standard_reduce_tests.rs
nicolasAmat/pnets
482d014001f31afe31bc1c47c08d5c1183bf78a3
use pnets::standard::Net; use pnets_shrink::modifications::{ Agglomeration, InequalityReduction, Modification, Reduction, TransitionElimination, }; use pnets_shrink::reducers::standard::{ IdentityPlaceReducer, IdentityTransitionReducer, ParallelPlaceReducer, ParallelTransitionReducer, SimpleChainReducer, So...
use pnets::standard::Net; use pnets_shrink::modifications::{ Agglomeration, InequalityReduction, Modification, Reduction, TransitionElimination, }; use pnets_shrink::reducers::standard::{ IdentityPlaceReducer, IdentityTransitionReducer, ParallelPlaceReducer, ParallelTransitionReducer, SimpleChainReducer, So...
fn self_loop_transition_elimination() { let parser = pnets_tina::Parser::new(include_str!("self_loop_transition_eliminations.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; IdentityTransitionReducer::reduce(&mut net, &mut modifications); ...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn create_transition_with_used_name() {\n\n let mut net = Net::default();\n\n let tr_1 = net.create_transition();\n\n net.rename_node(NodeId::Transition(tr_1), \"tr_1\").unwrap();\n\n let tr_2 = net.create_transition();\n\n assert_eq!(net.transitions.len(), 2);\n\n ass...
Rust
src/api/data/client.rs
rnag/rust-wistia
91e430ad9ba3665e8b89fb2aa2acef25acf46483
use crate::auth::auth_token; use crate::constants::ENV_VAR_NAME; use crate::https::{get_https_client, tls}; use crate::log::*; use crate::models::*; use crate::status::raise_for_status; use crate::utils::{into_struct_from_slice, stream_reader_from_url}; use crate::RustWistiaError; use std::borrow::Cow; use std::io::Cu...
use crate::auth::auth_token; use crate::constants::ENV_VAR_NAME; use crate::https::{get_https_client, tls}; use crate::log::*; use crate::models::*; use crate::status::raise_for_status; use crate::utils::{into_struct_from_slice, stream_reader_from_url}; use crate::RustWistiaError; use std::borrow::Cow; use std::io::Cu...
; let req = Request::builder() .method(Method::PUT) .uri(url) .header(AUTHORIZATION, token) .body(Body::empty())?; self.make_request(url, req).await } pub async fn put_with_body<B: Serialize, R: DeserializeOwned>( &'a self, ...
if params_len != 0 { uri = String::with_capacity(url.len() + params.len() + 1); uri.push_str(url); uri.push('?'); uri.push_str(&params); uri.as_str() } else { url }
if_condition
[ { "content": "/// Returns the value to set in the `AUTHORIZATION` header for a request.\n\npub fn auth_token(token: &str) -> String {\n\n // \"Bearer \".len() == 7\n\n let mut bearer_token = String::with_capacity(7 + token.len());\n\n bearer_token.push_str(\"Bearer \");\n\n bearer_token.push_str(tok...
Rust
syn-meta-ext/src/lib.rs
YoloDev/evitable
c1284df0c60a99f07caf037e22b7c8ab37b28fca
extern crate ident_case; extern crate proc_macro2; #[cfg_attr(test, macro_use)] extern crate quote; #[cfg_attr(test, macro_use)] extern crate syn; use proc_macro2::TokenStream; use quote::ToTokens; use syn::parse::*; use syn::{parenthesized, parse, token, Attribute, Ident, Lit, LitBool, Path, Token}; pub mod ast; pu...
extern crate ident_case; extern crate proc_macro2; #[cfg_attr(test, macro_use)] extern crate quote; #[cfg_attr(test, macro_use)] extern crate syn; use proc_macro2::TokenStream; use quote::ToTokens; use syn::parse::*; use syn::{parenthesized, parse, token, Attribute, Ident, Lit, LitBool, Path, Token}; pub mod ast; pu...
} else { Ok(Meta::Path(path)) } } fn parse_meta_list_after_path(path: Path, input: ParseStream) -> Result<MetaList> { let content; Ok(MetaList { path: path, paren_token: parenthesized!(content in input), nested: content.parse_terminated(NestedMeta::parse)?, }) } fn parse_meta_name_value_after_...
th, input).map(Meta::List) } else if input.peek(Token![=]) { parse_meta_name_value_after_path(path, input).map(Meta::NameValue)
function_block-random_span
[ { "content": "pub fn assert_trait_impl(ty: &Type, trait_path: &Path, tokens: &mut TokenStream) {\n\n ToTokens::to_tokens(&TraitAssertion { ty, trait_path }, tokens)\n\n}\n", "file_path": "evitable-derive-core/src/trait_assert.rs", "rank": 0, "score": 249387.9298914886 }, { "content": "pub f...
Rust
src/api/routes/namespace_routes_api.rs
proximax-storage/rust-xpx-chain-sdk
55613067328d511dbd9a129be30b9e048ef79175
/* * Copyright 2018 ProximaX Limited. All rights reserved. * Use of this source code is governed by the Apache 2.0 * license that can be found in the LICENSE file. */ use { ::std::{future::Future, pin::Pin, sync::Arc}, reqwest::Method, }; use crate::{ account::{AccountsId, Address}, api::{ ...
/* * Copyright 2018 ProximaX Limited. All rights reserved. * Use of this source code is governed by the Apache 2.0 * license that can be found in the LICENSE file. */ use { ::std::{future::Future, pin::Pin, sync::Arc}, reqwest::Method, }; use crate::{ account::{AccountsId, Address}, api::{ ...
pub async fn get_namespaces_from_accounts( self, accounts_id: Vec<&str>, ns_id: Option<NamespaceId>, page_size: Option<i32>, ) -> Result<Vec<NamespaceInfo>> { valid_vec_len(&accounts_id, ERR_EMPTY_ADDRESSES_IDS)?; let accounts = AccountsId::from(accounts_id); ...
let mut namespace_info: Vec<NamespaceInfo> = vec![]; for namespace_dto in dto.into_iter() { namespace_info.push(namespace_dto.compact(self.__network_type())?); } self.__build_namespaces_hierarchy(&mut namespace_info).await; Ok(namespace_info) }
function_block-function_prefix_line
[ { "content": "fn parse_meta_ws(value_dto: &mut Value) -> Result<()> {\n\n if let Some(v) = value_dto[\"transaction\"][\"transactions\"].as_array_mut() {\n\n let mut meta_value: Vec<Value> = vec![];\n\n\n\n for item in v.iter_mut() {\n\n if item[\"meta\"].is_null() {\n\n ...
Rust
src/config/mod.rs
pc37utn/rocfl
723501625b4b8775901470ffacd856124bfd4713
use std::collections::HashMap; use std::fs; use std::io::Read; use std::path::{Path, PathBuf}; use directories::ProjectDirs; use serde::Deserialize; use crate::ocfl::{DigestAlgorithm, Result, RocflError}; const CONFIG_FILE: &str = "config.toml"; const GLOBAL: &str = "global"; #[derive(Deserialize, Debug)] #[serde(d...
use std::collections::HashMap; use std::fs; use std::io::Read; use std::path::{Path, PathBuf}; use directories::ProjectDirs; use serde::Deserialize; use crate::ocfl::{DigestAlgorithm, Result, RocflError}; const CONFIG_FILE: &str = "config.toml"; const GLOBAL: &str = "global"; #[derive(Deserialize, Debug)] #[serde(d...
fn resolve_field(global_field: Option<String>, repo_field: Option<String>) -> Option<String> { if repo_field.is_some() { repo_field } else { global_field } }
e) => Config::new(), (Some(global), Some(repo)) => { let mut resolved = Config::new(); resolved.author_name = resolve_field(global.author_name, repo.author_name); resolved.author_address = resolve_field(global.author_address, repo.author_address); resolved.root =...
function_block-function_prefixed
[ { "content": "fn default_values(mut config: Config) -> Result<Config> {\n\n if is_s3(&config) {\n\n if config.staging_root.is_none() {\n\n config.staging_root = Some(config::s3_staging_path(&config)?);\n\n }\n\n } else if config.root.is_none() {\n\n config.root = Some(\".\"...
Rust
src/core/mod.rs
yamafaktory/hypergraph
e253ed0f0c34af8e3d07e753323c457644aaa819
pub(crate) mod bi_hash_map; #[doc(hidden)] pub mod errors; #[doc(hidden)] pub mod hyperedges; mod shared; mod utils; #[doc(hidden)] pub mod vertices; use bi_hash_map::BiHashMap; use indexmap::{IndexMap, IndexSet}; use std::{ fmt::{Debug, Display, Formatter, Result}, hash::Hash, }; pub trait SharedTrait: Copy ...
pub(crate) mod bi_hash_map; #[doc(hidden)] pub mod errors; #[doc(hidden)] pub mod hyperedges; mod shared; mod utils; #[doc(hidden)] pub mod vertices; use bi_hash_map::BiHashMap; use indexmap::{IndexMap, IndexSet}; use std::{ fmt::{Debug, Display, Formatter, Result}, hash::Hash, }; pub trait SharedTrait: Copy ...
}
pub fn with_capacity(vertices: usize, hyperedges: usize) -> Self { Hypergraph { hyperedges_count: 0, hyperedges_mapping: BiHashMap::default(), hyperedges: IndexSet::with_capacity(hyperedges), vertices_count: 0, vertices_mapping: BiHashMap::default(), ...
function_block-full_function
[ { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, HyperedgeKey, Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Updates the weight of a hyperedge by index.\n\n pub fn update_hyperedge_weight(\n\n &m...
Rust
src/basic/model.rs
nyari/rtrace
2321a0a50c10940c58a690c678df8f939d5b22fc
use core::{Model, Material, RayIntersection, Ray, RayIntersectionError}; use defs::{Point3, Vector3, FloatType}; use tools::{CompareWithTolerance}; use na; use na::{Unit}; use std; use uuid::{Uuid}; pub struct SolidSphere { material: Material, origo: Point3, radius: FloatType, identifier: Uuid } impl ...
use core::{Model, Material, RayIntersection, Ray, RayIntersectionError}; use defs::{Point3, Vector3, FloatType}; use tools::{CompareWithTolerance}; use na; use na::{Unit}; use std; use uuid::{Uuid}; pub struct SolidSphere { material: Material, origo: Point3, radius: FloatType, identifier: Uuid } impl ...
None); } }
; let c = ray_origo.x.powi(2) + ray_origo.y.powi(2) + ray_origo.z.powi(2) - self.radius.powi(2); let determinant = b.powi(2) - 4.0 * a * c; if determinant.less_eps(&0.0) { None } else { let t1 = (-b + determinant.sqrt()) / (2.0 * a); let t2 = (-b - de...
random
[ { "content": "pub trait Model: Send + Sync {\n\n fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection>;\n\n}\n\n\n\npub struct ModelViewModelWrapper<T: Model> {\n\n wrapped_model: T,\n\n tf_matrix: Matrix4,\n\n inverse_tf_matrix: Matrix4\n\n}\n\n\n\nimpl<T: Model> ModelViewModelWrapper<T>...
Rust
src/error.rs
gadunga/obj-rs
581b76d40d4f5ab33612ee51098ab09d6ee568fc
use std::fmt; use std::io; use std::num::{ParseIntError, ParseFloatError}; use std::convert::From; use std::error::Error; pub type ObjResult<T> = Result<T, ObjError>; #[derive(Debug)] pub enum ObjError { Io(io::Error), ParseInt(ParseIntError), ParseFloat(ParseFloatError), Load(Lo...
use std::fmt; use std::io; use std::num::{ParseIntError, ParseFloatError}; use std::convert::From; use std::error::Error; pub type ObjResult<T> = Result<T, ObjError>; #[derive(Debug)] pub enum ObjError { Io(io::Error), ParseInt(ParseIntError), ParseFloat(ParseFloatError), Load(Lo...
} impl Error for ObjError { fn description(&self) -> &str { match *self { ObjError::Io(ref err) => err.description(), ObjError::ParseInt(ref err) => err.description(), ObjError::ParseFloat(ref err) => err.description(), ObjError::Load(ref err) => err.descrip...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &ObjError::Io(ref e) => e.fmt(f), &ObjError::ParseInt(ref e) => e.fmt(f), &ObjError::ParseFloat(ref e) => e.fmt(f), &ObjError::Load(ref e) => e.fmt(f), } }
function_block-full_function
[ { "content": "/// Parses a wavefront `.obj` format.\n\npub fn parse_obj<T: BufRead>(input: T) -> ObjResult<RawObj> {\n\n let mut name = None;\n\n let mut material_libraries = Vec::new();\n\n\n\n let mut positions = Vec::new();\n\n let mut tex_coords = Vec::new();\n\n let mut normals = Vec::new();...
Rust
shipico/src/old/math/rect.rs
Shipica/Shipica.github.io
d5d451481d013228d99b98c1ccc1c8924f23ed61
use super::point::Point; use super::size::Size; use super::thickness::Thickness; use super::vec2::Vec2; use std::f64::{INFINITY, NEG_INFINITY}; use std::ops::{Add, Sub}; #[derive(Copy, Clone, Debug, Default, PartialEq)] #[repr(C)] pub struct Rect { pub left: f64, pub top: f64, pub right: ...
use super::point::Point; use super::size::Size; use super::thickness::Thickness; use super::vec2::Vec2; use std::f64::{INFINITY, NEG_INFINITY}; use std::ops::{Add, Sub}; #[derive(Copy, Clone, Debug, Default, PartialEq)] #[repr(C)] pub struct Rect { pub left: f64, pub top: f64, pub right: ...
#[inline] pub fn rounded(&self) -> Rect { Rect { left: self.left.round(), top: self.top.round(), right: self.right.round(), bottom: self.bottom.round(), } } #[inline] pub fn size(&self) -> Size { ( ...
pub fn from_center_half_extent( center: impl Into<Point>, half_extents: impl Into<Vec2>, ) -> Rect { let center = center.into(); let half_extents = half_extents.into(); Rect { left: center.x - half_extents.x, top: center.y - half_extents.y, ...
function_block-full_function
[ { "content": "pub fn glWeightfvARB(size: GLint, weights: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 0, "score": 319145.9366847262 }, { "content": "pub fn glWeightusvARB(size: GLint, weights: *const GLushort) {\...