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
src/aes_hash.rs
DSLAM-UMD/aHash
48690455d837c807fd283d1bca689c898ddc981d
use crate::convert::*; #[cfg(feature = "specialize")] use crate::fallback_hash::MULTIPLE; use crate::operations::*; use crate::RandomState; use core::hash::Hasher; use crate::random_state::PI; #[derive(Debug, Clone)] pub struct AHasher { enc: u128, sum: u128, key: u128, } impl AHasher { ...
use crate::convert::*; #[cfg(feature = "specialize")] use crate::fallback_hash::MULTIPLE; use crate::operations::*; use crate::RandomState; use core::hash::Hasher; use crate::random_state::PI; #[derive(Debug, Clone)] pub struct AHasher { enc: u128, sum: u128, key: u128, } impl AHasher { ...
#[inline] fn write_u8(&mut self, _i: u8) {} #[inline] fn write_u16(&mut self, _i: u16) {} #[inline] fn write_u32(&mut self, _i: u32) {} #[inline] fn write_u64(&mut self, _i: u64) {} #[inline] fn write_u128(&mut self, _i: u128) {} #[inline] fn write_usize(&mut self,...
fn write(&mut self, bytes: &[u8]) { if bytes.len() > 8 { self.0.write(bytes); self.0.enc = aesdec(self.0.sum, self.0.enc); self.0.enc = aesenc(aesenc(self.0.enc, self.0.key), self.0.enc); } else { self.0.add_in_length(bytes.len() as u64); let v...
function_block-full_function
[ { "content": "fn test_input_affect_every_byte<T: Hasher>(constructor: impl Fn(u128, u128) -> T) {\n\n let base = hash_with(&0, constructor(0, 0));\n\n for shift in 0..16 {\n\n let mut alternitives = vec![];\n\n for v in 0..256 {\n\n let input = (v as u128) << (shift * 8);\n\n ...
Rust
packages/sycamore/src/template.rs
parker-codes/sycamore
27d90ecb08a020ea9da7e1b3233d6331ac2050ef
use std::cell::RefCell; use std::fmt; use std::rc::Rc; use crate::generic_node::GenericNode; #[derive(Clone)] pub(crate) enum TemplateType<G: GenericNode> { Node(G), Lazy(Rc<RefCell<dyn FnMut() -> Template<G>>>), Fragment(Vec<Template<G>>), } #[derive(Clone)] pub struct Template<G: Gener...
use std::cell::RefCell; use std::fmt; use std::rc::Rc; use crate::generic_node::GenericNode; #[derive(Clone)] pub(crate) enum TemplateType<G: GenericNode> { Node(G), Lazy(Rc<RefCell<dyn FnMut() -> Template<G>>>), Fragment(Vec<Template<G>>), } #[derive(Clone)] pub struct Template<G: Gener...
} impl<G: GenericNode> fmt::Debug for Template<G> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.inner { TemplateType::Node(node) => node.fmt(f), TemplateType::Lazy(lazy) => lazy.as_ref().borrow_mut()().fmt(f), TemplateType::Fragment(fragment) ...
e], TemplateType::Lazy(lazy) => lazy.borrow_mut()().flatten(), TemplateType::Fragment(fragment) => fragment .into_iter() .map(|x| x.flatten()) .flatten() .collect(), } }
function_block-function_prefixed
[ { "content": "#[component(BrowserRouter<G>)]\n\npub fn browser_router<R: Route>(render: impl Fn(R) -> Template<G> + 'static) -> Template<G> {\n\n PATHNAME.with(|pathname| {\n\n assert!(pathname.borrow().is_none());\n\n // Get initial url from window.location.\n\n *pathname.borrow_mut() =...
Rust
libuser/src/crt0/relocation.rs
tiliarou/KFS
48e314360c0a149be280811be56643c954d3793c
#[allow(clippy::missing_docs_in_private_items)] mod module_header { global_asm!(r#" .section .rodata.mod0 .global module_header module_header: .ascii "MOD0" .int _DYNAMIC - module_header .int __bss_start__ - module_header .int __bss_end__ - module_header .int __...
#[allow(clippy::missing_docs_in_private_items)] mod module_header { global_asm!(r#" .section .rodata.mod0 .global module_header module_header: .ascii "MOD0" .int _DYNAMIC - module_header .int __bss_start__ - module_header .int __bss_end__ - module_header .int __...
pub unsafe extern fn relocate_self(aslr_base: *mut u8, module_headr: *const ModuleHeader) -> u32 { let module_header_address = module_headr as *const u8; let module_headr = &(*module_headr); if module_headr.magic != ModuleHeader::MAGIC { return 1; } let mut dynamic = module_header_address....
function_block-full_function
[]
Rust
crates/svm-runtime/src/runtime/macros.rs
Jorropo/svm
d4e77133a428e379e98ae19e596c897421576a63
#[macro_export] macro_rules! include_svm_runtime { ($pages_storage_gen: expr, $page_cache_ctor: expr, $PC: path, $ENV: path, $env_gen: expr) => { mod runtime { use log::{debug, error, info}; use $crate::runtime::{ContractExecError, Receipt}; svm_runtime::...
#[macro_export] macro_rules! include_svm_runtime { ($pages_storage_gen: expr, $page_cache_ctor: expr, $PC: path, $ENV: path, $env_gen: expr) => { mod runtime { use log::{debug, error, info}; use $crate::runtime::{ContractExecError, Receipt}; svm_runtime::...
ontext_mut(); $crate::wasmer_data_storage!(wasmer_ctx.data, $PC) } } }; }
)] fn do_contract_exec( tx: &Transaction, import_object: &wasmer_runtime::ImportObject, ) -> Result<(State, Vec<wasmer_runtime::Value>), ContractExecError> { let mut env = $env_gen(); let contract = contract_load(tx, &mut env)?; ...
random
[ { "content": "#[allow(dead_code)]\n\npub fn parse_transaction(bytes: &[u8]) -> Result<Transaction, TransactionBuildError> {\n\n let mut cursor = Cursor::new(bytes);\n\n\n\n parse_version(&mut cursor)?;\n\n\n\n let contract = parse_address(&mut cursor, Field::Contract)?;\n\n let sender = parse_addres...
Rust
src/golf/lexer/matcher.rs
nilq/golf
aceb3d54cfd3afe1c0ea55d6ec688dd896866931
use super::*; macro_rules! token { ($tokenizer:expr, $token_type:ident, $accum:expr) => {{ token!($tokenizer , TokenType::$token_type, $accum) }}; ($tokenizer:expr, $token_type:expr, $accum:expr) => {{ let tokenizer = $tokenizer as &$crate::golf::lexer::Tokenizer; let token_type =...
use super::*; macro_rules! token { ($tokenizer:expr, $token_type:ident, $accum:expr) => {{ token!($tokenizer , TokenType::$token_type, $accum) }}; ($tokenizer:expr, $token_type:expr, $accum:expr) => {{ let tokenizer = $tokenizer as &$crate::golf::lexer::Tokenizer; let token_type =...
} else { match u64::from_str_radix(accum.as_str(), 10) { Ok(result) => result.to_string(), Err(error) => panic!("unable to parse int: {}", error) } }; token!(tokenizer, IntLiteral, literal) } } } p...
match i64::from_str_radix(accum.as_str(), 10) { Ok(result) => format!("-{}", result), Err(error) => panic!("unable to parse int: {}", error) }
if_condition
[ { "content": "pub fn lexer(data: &mut Chars) -> Lexer {\n\n let tokenizer = Tokenizer::new(data);\n\n let mut lexer = Lexer::new(tokenizer);\n\n\n\n let eol = vec![\"\\n\"].iter().map(|&x| x.to_string()).collect();\n\n\n\n let symbols = vec![\n\n \"(\",\n\n \")\",\n\n \"[\",\n...
Rust
src/experimental/type_graph_builder.rs
Cypher1/Tako
a709df240ce27714fe5474419236049ac979dab5
use crate::ast::{ path_to_string, Abs, Apply, BinOp, HasInfo, Let, Path, Sym, Symbol, UnOp, Visitor, }; use crate::database::DBStorage; use crate::errors::TError; use crate::passes::ast_interpreter::Interpreter; use crate::primitives::{ bit_type, i32_type, string_type, Pack, Prim::{Bool, Str, I32}, Val,...
use crate::ast::{ path_to_string, Abs, Apply, BinOp, HasInfo, Let, Path, Sym, Symbol, UnOp, Visitor, }; use crate::database::DBStorage; use crate::errors::TError; use crate::passes::ast_interpreter::Interpreter; use crate::primitives::{ bit_type, i32_type, string_type, Pack, Prim::{Bool, Str, I32}, Val,...
fn visit_sym(&mut self, _storage: &mut DBStorage, state: &mut State, expr: &Sym) -> Res { debug!( "visiting sym {} {}", path_to_string(&state.path), &expr.name ); Ok(Variable(format!("typeof({})", expr.name))) } fn visit_val(&mut self, ...
odule)?; info!( "Building symbol table & type graph... {}", path_to_string(module) ); let mut state = State { path: module.clone(), graph: TypeGraph::default(), }; let ty = self.visit(storage, &mut state, expr)?; state.graph...
function_block-function_prefixed
[ { "content": "pub fn infer(storage: &mut DBStorage, expr: &Node, env: &Val) -> Result<Val, TError> {\n\n // Infer that expression t has type A, t => A\n\n // See https://ncatlab.org/nlab/show/bidirectional+typechecking\n\n use crate::ast::{Abs, Apply, BinOp, Let, Sym, ToNode, UnOp, Visitor};\n\n mat...
Rust
src/engine/mod.rs
Atul9/rg3d
a4a7ad682a7f4d056863b3bba8c759b49018397c
pub mod resource_manager; pub mod error; use crate::{ core::{ math::vec2::Vec2, visitor::{ Visitor, VisitResult, Visit, }, }, sound::context::Context, engine::{ resource_manager::ResourceManager, error::EngineError, }, ...
pub mod resource_manager; pub mod error; use crate::{ core::{ math::vec2::Vec2, visitor::{ Visitor, VisitResult, Visit, }, }, sound::context::Context, engine::{ resource_manager::ResourceManager, error::EngineError, }, ...
er: Renderer::new(&mut context, client_size.into())?, resource_manager: Arc::new(Mutex::new(ResourceManager::new())), sound_context: Context::new()?, scenes: SceneContainer::new(), user_interface: UserInterface::new(), ui_time: Default::default(), ...
r, Window, }, scene::SceneContainer, PossiblyCurrent, GlRequest, GlProfile, WindowedContext, NotCurrent, Api, event_loop::EventLoop, gui::Control, }; use std::{ sync::{Arc, Mutex}, time, time::Duration, }; pub struct Engine<M: 'static, C: 'static + Control<M,...
random
[ { "content": "pub fn check_gl_error_internal(line: u32, file: &str) {\n\n unsafe {\n\n let error_code = gl::GetError();\n\n if error_code != gl::NO_ERROR {\n\n let code = match error_code {\n\n gl::INVALID_ENUM => \"GL_INVALID_ENUM\",\n\n gl::INVALID_VAL...
Rust
core/bin/zksync_api/src/api_server/rest/v1/mod.rs
huitseeker/zksync
5b936b1855a08033cca7f75d6f87fde106c6e8fd
pub use self::error::{Error, ErrorBody}; use actix_web::{ web::{self, Json}, Scope, }; use serde::{Deserialize, Serialize}; use zksync_config::{ApiServerOptions, ConfigurationOptions}; use zksync_types::BlockNumber; use crate::api_server::tx_sender::TxSender; mod blocks; pub mod client; mod config; mod er...
pub use self::error::{Error, ErrorBody}; use actix_web::{ web::{self, Json}, Scope, }; use serde::{Deserialize, Serialize}; use zksync_config::{ApiServerOptions, ConfigurationOptions}; use zksync_types::BlockNumber; use crate::api_server::tx_sender::TxSender; mod blocks; pub mod client; mod config; mod er...
fn into_query(self, limit: BlockNumber) -> PaginationQuery { match self { Pagination::Before(before) => PaginationQuery { before: Some(before), limit, ..PaginationQuery::default() }, Pagination::After(after) => Pagina...
o")); } Ok(Some(before - 1)) } Pagination::After(after) => Ok(Some(after + limit + 1)), Pagination::Last => Ok(None), } }
function_block-function_prefixed
[ { "content": "/// Takes name of the config, extends it to the constant and volatile config paths,\n\n/// loads them and merged into on object.\n\nfn merge_configs(config: &str) -> serde_json::Value {\n\n let mut constant_config = load_json(&config_path(&format!(\"constant/{}\", config)));\n\n let mut vola...
Rust
day06/day06.rs
CheezeCake/AoC-2019
1426c025f4e6fa1268458fac22776b409e13168a
use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; use std::io; use std::io::prelude::*; type OrbitInfo = HashMap<String, HashSet<String>>; #[derive(Debug, Clone)] struct OrbitCount { direct: usize, indirect: usize, } impl OrbitCount { fn new() -> Self { ...
use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; use std::io; use std::io::prelude::*; type OrbitIn
let mut q = VecDeque::new(); q.push_back((start, 0)); visited.insert(start); let empty = HashSet::new(); while !q.is_empty() { let (obj, n) = q.pop_front().unwrap(); if in_orbit_around .get(target) .unwrap_or(&HashSet::new()) .contains(obj) ...
fo = HashMap<String, HashSet<String>>; #[derive(Debug, Clone)] struct OrbitCount { direct: usize, indirect: usize, } impl OrbitCount { fn new() -> Self { Self { direct: 0, indirect: 0, } } } fn count_orbits(objects_orbiting: &OrbitInfo, in_orbit_around: &OrbitI...
random
[ { "content": "type Position = (i32, i32);\n\n\n", "file_path": "day15/day15.rs", "rank": 0, "score": 53542.84334560843 }, { "content": "type State = Vec<Vec<Tile>>;\n\n\n", "file_path": "day24/day24.rs", "rank": 1, "score": 50393.35288035059 }, { "content": "enum Position...
Rust
chips/nrf5x/src/rtc.rs
jkchien/tock
fa7543b5bdfbd239f5831c01998f0fe27ccbf95d
use core::cell::Cell; use kernel::common::cells::OptionalCell; use kernel::common::registers::{register_bitfields, ReadOnly, ReadWrite, WriteOnly}; use kernel::common::StaticRef; use kernel::hil::time::{self, Alarm, Ticks, Time}; use kernel::ErrorCode; const RTC1_BASE: StaticRef<RtcRegisters> = unsafe { StaticRe...
use core::cell::Cell; use kernel::common::cells::OptionalCell; use kernel::common::registers::{register_bitfields, ReadOnly, ReadWrite, WriteOnly}; use kernel::common::StaticRef; use kernel::hil::time::{self, Alarm, Ticks, Time}; use kernel::ErrorCode; const RTC1_BASE: StaticRef<RtcRegisters> = unsafe { StaticRe...
self.now(); let earliest_possible = now.wrapping_add(Self::Ticks::from(SYNC_TICS)); if !now.within_range(reference, expire) || expire.wrapping_sub(now).into_u32() <= SYNC_TICS { expire = earliest_possible; } regs.cc[0].write(Counter::VALUE.val(expire.into_u32())); ...
:Register>, intenclr: ReadWrite<u32, Inte::Register>, _reserved3: [u8; 52], evten: ReadWrite<u32, Inte::Register>, evtenset: ReadWrite<u32, Inte::Register>, evtenclr: ReadWrite<u32, Inte::Register>, _reserved4: [u8; 440], counter: ReadOnly<u32, Counter::Register>, ...
random
[ { "content": "/// Interface for receiving notification when a particular time\n\n/// (`Counter` value) is reached. Clients use the\n\n/// [`AlarmClient`](trait.AlarmClient.html) trait to signal when the\n\n/// counter has reached a pre-specified value set in\n\n/// [`set_alarm`](#tymethod.set_alarm). Alarms are...
Rust
binrw/src/private.rs
dmgolembiowski/binrw
9779ff3749d0576a46b544373442ce9d9af2914c
use crate::{ error::CustomError, io::{self, Seek, Write}, BinRead, BinResult, Error, ReadOptions, WriteOptions, }; #[cfg(not(feature = "std"))] use alloc::{boxed::Box, string::String}; pub enum AssertErrorFn<M, E> { Message(M), Error(E), } pub fn assert<MsgFn, Msg, ErrorFn, Err>( test: bool, ...
use crate::{ error::CustomError, io::{self, Seek, Write}, BinRead, BinResult, Error, ReadOptions, WriteOptions, }; #[cfg(not(feature = "std"))] use alloc::{boxed::Box, string::String}; pub enum AssertErrorFn<M, E> { Message(M), Error(E), } pub fn assert<MsgFn, Msg, ErrorFn, Err>( test: bool, ...
riter, &WriteOptions, Args) -> BinResult<()>, { x } pub fn write_map_args_type_hint<Input, Output, MapFn, Args>(_: &MapFn, args: Args) -> Args where MapFn: FnOnce(Input) -> Output, Output: crate::BinWrite<Args = Args>, { args } pub fn write_try_map_args_type_hint<Input, Output, MapFn, Args>(_: &MapFn,...
F>(_: F, a: Args) -> Args where R: crate::io::Read + Seek, F: FnOnce(&mut R, &crate::ReadOptions, Args) -> crate::BinResult<Res>, { a } pub fn write_function_args_type_hint<T, W, Args, F>(_: F, a: Args) -> Args where W: Write + Seek, F: FnOnce(&T, &mut W, &crate::WriteOptions, Args) -> crate::BinR...
random
[ { "content": "/// A helper similar to `#[br(count = N)]` which can be used with any collection.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # use binrw::{BinRead, helpers::count, io::Cursor, BinReaderExt};\n\n/// # use std::collections::VecDeque;\n\n/// #[derive(BinRead)]\n\n/// struct CountBytes {\n\n///...
Rust
parser/src/ast_var.rs
patrickf2000/lila
3aad462580fea1f14d9aeb81d192fe1ee3e30e6d
use crate::ast; use crate::ast::*; use crate::lex::{Token, Lex}; use crate::syntax::ErrorManager; use crate::ast_builder::AstBuilder; use crate::ast_utils::*; pub fn build_var_dec(builder : &mut AstBuilder, name : String) -> bool { let mut var_dec = ast::create_stmt(AstStmtType::VarDec, &mut builder.scanner); ...
use crate::ast; use crate::ast::*; use crate::lex::{Token, Lex}; use crate::syntax::ErrorManager; use crate::ast_builder::AstBuilder; use crate::ast_utils::*; pub fn build_var_dec(builder : &mut AstBuilder, name : String) -> bool { let mut var_dec = ast::create_stmt(AstStmtType::VarDec, &mut builder.scanner); ...
pub fn build_var_assign(builder : &mut AstBuilder, name : String, assign_op : Token) -> bool { let mut var_assign = ast::create_stmt(AstStmtType::VarAssign, &mut builder.scanner); var_assign.name = name.clone(); if !build_var_assign_stmt(builder, &mut var_assign, name, assign_op) { return fal...
g); } let num_arg = ast::create_int(1); var_assign.args.push(num_arg); check_end = true; }, Token::AddAssign | Token::SubAssign | Token::MulAssign | Token::DivAssign | Token::ModAssign => { l...
function_block-function_prefixed
[]
Rust
stronghold-wasm/src/wasm_structs/transaction.rs
stronghold-financial/stronghold
7461cbdc6c67459517f10205bd918111ad109100
use wasm_bindgen::prelude::*; use stronghold_rust::sapling_bls12::{ Key, ProposedTransaction, PublicAddress, SimpleTransaction, Transaction, SAPLING, }; use super::errors::*; use super::note::WasmNote; use super::panic_hook; use super::spend_proof::WasmSpendProof; use super::witness::JsWitness; #[wasm_bindgen] p...
use wasm_bindgen::prelude::*; use stronghold_rust::sapling_bls12::{ Key, ProposedTransaction, PublicAddress, SimpleTransaction, Transaction, SAPLING, }; use super::errors::*; use super::note::WasmNote; use super::panic_hook; use super::spend_proof::WasmSpendProof; use super::witness::JsWitness; #[wasm_bindgen] p...
#[wasm_bindgen(getter, js_name = "spendsLength")] pub fn spends_length(&self) -> usize { self.transaction.spends().len() } #[wasm_bindgen(js_name = "getSpend")] pub fn get_spend(&self, index: usize) -> WasmSpendProof { let proof = &self.transaction.spends()[index]; WasmSpe...
let proof = &self.transaction.receipts()[index]; let mut cursor: Vec<u8> = Vec::with_capacity(275); proof .merkle_note() .write(&mut cursor) .map_err(WasmIoError)?; Ok(cursor) }
function_block-function_prefix_line
[ { "content": "#[wasm_bindgen(js_name = \"generateKey\")]\n\npub fn create_key_to_js() -> Key {\n\n let hasher = sapling_bls12::SAPLING.clone();\n\n let sapling_key = sapling_bls12::Key::generate_key(hasher);\n\n\n\n Key {\n\n spending_key: sapling_key.hex_spending_key(),\n\n incoming_view...
Rust
crates/rune/src/compile/expr.rs
shekohex/rune
05fab8da952737e61c8d1141393e3faa6318d4e6
use crate::ast; use crate::compiler::{Compiler, Needs}; use crate::error::CompileResult; use crate::traits::Compile; use crate::worker::Expanded; use crate::CompileError; use runestick::Inst; impl Compile<(&ast::Expr, Needs)> for Compiler<'_> { fn compile(&mut self, (expr, needs): (&ast::Expr, Needs)) -> CompileRe...
use crate::ast; use crate::compiler::{Compiler, Needs}; use crate::error::CompileResult; use crate::traits::Compile; use crate::worker::Expanded; use crate::CompileError; use runestick::Inst; impl Compile<(&ast::Expr, Needs)> for Compiler<'_> { fn compile(&mut self, (expr, needs): (&ast::Expr, Needs)) -> CompileRe...
}
s) => { self.compile((expr_field_access, needs))?; } ast::Expr::ExprClosure(expr_closure) => { self.compile((expr_closure, needs))?; } ast::Expr::LitUnit(lit_unit) => { self.compile((lit_unit, needs))?; } ...
function_block-function_prefixed
[]
Rust
src/main.rs
jyanar/boids_rs
6c03a77ea80c0cf332fce327138ce8f2458a91f9
extern crate piston_window; use rand::Rng; use std::time::{SystemTime,UNIX_EPOCH}; use std::path::Path; use piston_window::*; const WINDOW_SIZE: u32 = 800; const GFX_CONTEXT_OFFSET: f64 = 0.0 as f64; const MILLIS_PER_FRAME: u128 = 10; const BLACK: [f32;4] = [0.0, 0.0, 0.0, 1.0]; const WHITE: [f32;4] = [1.0; 4]; con...
extern crate piston_window; use rand::Rng; use std::time::{SystemTime,UNIX_EPOCH}; use std::path::Path; use piston_window::*; const WINDOW_SIZE: u32 = 800; const GFX_CONTEXT_OFFSET: f64 = 0.0 as f64; const MILLIS_PER_FRAME: u128 = 10; const BLACK: [f32;4] = [0.0, 0.0, 0.0, 1.0]; const WHITE: [f32;4] = [1.0; 4]; con...
fn compute_separation(&self, boids: &[Boid]) -> Vector { let nearby = 0; let mut separation = [0.0 ; 2]; for i in 0 .. boids.len() { if self.location.get_distance(&boids[i].location) < MINSEP && self.id != boids[i].id { ...
fn compute_alignment(&self, boids: &[Boid]) -> Vector { let mut nearby = 0; let mut alignment = [0.0 ; 2]; for i in 0 .. boids.len() { if self.id != boids[i].id && self.location.get_distance(&boids[i].location) < MAXDIST { alignment[0] += boid...
function_block-full_function
[]
Rust
day23.rs
codecow911/adventofcode2018
293cbf4aeda53ed644386dc53a880e762875610e
#![feature(test)] use std::error::Error; use std::fs::File; use std::io::{BufRead, BufReader}; #[macro_use] extern crate scan_fmt; #[derive(Debug)] struct Point { x: i32, y: i32, z: i32, r: u32 } impl Point { pub fn set(&mut self, x: i32, y: i32, z: i32) { self.x = x; self.y = y;...
#![feature(test)] use std::error::Error; use std::fs::File; use std::io::{BufRead, BufReader}; #[macro_use] extern crate scan_fmt; #[derive(Debug)] struct Point { x: i32, y: i32, z: i32, r: u32 } impl Point { pub fn set(&mut self, x: i32, y: i32, z: i32) { self.x = x; self.y = y;...
#[cfg(test)] mod tests { #[test] fn test_part1_ex() { use part1; assert_eq!(part1(r"C:\Users\Igascoigne\advent2018\dec_01_01\test.txt"), 7); } } fn main() { println!("result: {}", part2(r"C:\Users\Igascoigne\advent2018\dec_01_01\input.txt")); }
let mut grid_size = maxx - minx; while grid_size > 0 { let mut max_count = 0; let mut x = minx; while x <= maxx { let mut y = miny; while y <= maxy { let mut z = minz; while z <= maxz { let count = nanobots.iter().f...
function_block-function_prefix_line
[ { "content": "fn part1(path: &str, verbose: bool) -> u32 {\n\n let mut armies = parse(path);\n\n let mut round = 1;\n\n loop {\n\n if verbose {\n\n println!(\"\");\n\n for army in armies.iter_mut() {\n\n army.groups.sort_by_key(|x| x.id);\n\n a...
Rust
src/cli.rs
paulstansifer/odd
456a321c041241c95e147cb1c9c254d02df64a64
#![allow(non_snake_case)] use std::{fs::File, io::Read, path::Path}; use libunseemly::{ ast, ast::Ast, core_forms, expand, grammar, name::{n, Name}, runtime::{core_values, eval, eval::Value}, ty, ty_compare, util::assoc::Assoc, }; use std::{borrow::Cow, cell::RefCell, io::BufRead}; thread...
#![allow(non_snake_case)] use std::{fs::File, io::Read, path::Path}; use libunseemly::{ ast, ast::Ast, core_forms, expand, grammar, name::{n, Name}, runtime::{core_values, eval, eval::Value}, ty, ty_compare, util::assoc::Assoc, }; use std::{borrow::Cow, cell::RefCell, io::BufRead}; thread...
} impl rustyline::completion::Completer for LineHelper { type Candidate = String; fn complete( &self, line: &str, pos: usize, _ctxt: &rustyline::Context, ) -> Result<(usize, Vec<String>), rustyline::error::ReadlineError> { let mut res = vec![]; let (start, ...
LineHelper { highlighter: rustyline::highlight::MatchingBracketHighlighter::new(), validator: rustyline::validate::MatchingBracketValidator::new(), } }
function_block-function_prefix_line
[ { "content": "pub fn eval(expr: &Ast, env: Assoc<Name, Value>) -> Result<Value, ()> {\n\n walk::<Eval>(expr, &LazyWalkReses::new_wrapper(env))\n\n}\n\n\n", "file_path": "src/runtime/eval.rs", "rank": 0, "score": 278618.50121150416 }, { "content": "pub fn eval_top(expr: &Ast) -> Result<Val...
Rust
ast/src/child_iters/recursive_children_iter.rs
Robbepop/stevia
5f0132ef8fa0826a4cadfe07622cd594c31c57e9
use crate::{ AnyExpr, iter::{ Children, ChildrenIter, }, }; use std::iter::Iterator; pub fn children_recursive_with_event(expr: &AnyExpr) -> RecursiveChildrenIter { RecursiveChildrenIter::new(expr) } pub fn children_recursive_entering(expr: &AnyExpr) -> impl Iterator<Item = &AnyExpr> {...
use crate::{ AnyExpr, iter::{ Children, ChildrenIter, }, }; use std::iter::Iterator; pub fn children_recursive_with_event(expr: &AnyExpr) -> RecursiveChildrenIter { RecursiveChildrenIter::new(expr) } pub fn children_recursive_entering(expr: &AnyExpr) -> impl Iterator<Item = &AnyExpr> {...
None } } #[cfg(test)] mod tests { use super::*; use crate::PlainExprTreeBuilder; #[test] fn simple() { fn create_ast() -> AnyExpr { let b = PlainExprTreeBuilder::default(); b.or( b.and(b.bool_const(true), b.bool_const(false)), b.xo...
if let Some(frame) = self.frames.pop() { let guard = frame.guard(); self.next = self.frames .last_mut() .and_then(Iterator::next); return Some(AnyExprAndEvent::leaving(guard)) }
if_condition
[ { "content": "/// A simple marker to mark expression types as such\n\n/// and provide them with an expression kind.\n\npub trait ExprMarker: fmt::Debug + Copy + Clone + PartialEq + Eq {\n\n /// The static kind of the expression.\n\n const EXPR_KIND: ExprKind;\n\n}\n\n\n\npub use self::{\n\n context::{\...
Rust
tokio/src/runtime/task/core.rs
akshay-deepsource/tokio
7ad0461cc1ea9a68804617a785c3bcc4f188cdab
use crate::future::Future; use crate::loom::cell::UnsafeCell; use crate::runtime::task::raw::{self, Vtable}; use crate::runtime::task::state::State; use crate::runtime::task::Schedule; use crate::util::linked_list; use std::pin::Pin; use std::ptr::NonNull; use std::task::{Context, Poll, Waker}; #[repr(C)] pub(super...
use crate::future::Future; use crate::loom::cell::UnsafeCell; use crate::runtime::task::raw::{self, Vtable}; use crate::runtime::task::state::State; use crate::runtime::task::Schedule; use crate::util::linked_list; use std::pin::Pin; use std::ptr::NonNull; use std::task::{Context, Poll, Waker}; #[repr(C)] pub(super...
unsafe fn set_stage(&self, stage: Stage<T>) { self.stage.with_mut(|ptr| *ptr = stage) } } cfg_rt_multi_thread! { impl Header { pub(super) unsafe fn set_next(&self, next: Option<NonNull<Header>>) { self.queue_next.with_mut(|ptr| *ptr = next); } } } impl Header { ...
pub(super) fn take_output(&self) -> super::Result<T::Output> { use std::mem; self.stage.with_mut(|ptr| { match mem::replace(unsafe { &mut *ptr }, Stage::Consumed) { Stage::Finished(output) => output, _ => panic!("JoinHandle polled after completio...
function_block-full_function
[ { "content": "fn model(f: impl Fn() + Send + Sync + 'static) {\n\n #[cfg(loom)]\n\n loom::model(f);\n\n\n\n #[cfg(not(loom))]\n\n f();\n\n}\n\n\n", "file_path": "tokio/src/time/driver/tests/mod.rs", "rank": 0, "score": 405710.77752691077 }, { "content": "/// Poll the future. If t...
Rust
src/main.rs
pacman82/cargo-wheel
d4fd42d2878ff242e103a28efb44fced7d102354
mod header; mod templates; use cargo::{ core::{shell::Shell, Workspace}, util::important_paths, CliResult, Config, }; use std::{ env::current_dir, fs::create_dir_all, path::{Path, PathBuf}, process::Command, }; use structopt::{clap::AppSettings, StructOpt}; use crate::templates::SetupPyVar...
mod header; mod templates; use cargo::{ core::{shell::Shell, Workspace}, util::important_paths, CliResult, Config, }; use std::{ env::current_dir, fs::create_dir_all, path::{Path, PathBuf}, process::Command, }; use structopt::{clap::AppSettings, StructOpt}; use crate::templates::SetupPyVar...
fn real_main(args: Args, config: &mut Config) -> CliResult { let cli_config = []; config.configure( args.verbose, args.quiet, args.color.as_deref(), args.frozen, args.locked, args.offline, &args.target_dir, &args.unstable_flags, &cli_con...
fn main() { env_logger::init(); let mut config = match Config::default() { Ok(cfg) => cfg, Err(e) => { let mut shell = Shell::new(); cargo::exit_with_error(e.into(), &mut shell) } }; let Opts::Wheel(args) = Opts::from_args(); if let Err(err) = real_...
function_block-full_function
[ { "content": "#[derive(Serialize)]\n\nstruct InitPyVars<'a> {\n\n name: &'a str,\n\n}\n\n\n", "file_path": "src/templates.rs", "rank": 3, "score": 38134.878776464204 }, { "content": "pub fn render_init_py(path: &Path, name: &str) {\n\n let template = mustache::compile_str(INIT_PY).unwr...
Rust
src/node.rs
maidsafe/safe_gossip
9c9738072a576fdc654801c68d2b0255fcf5b2a9
use super::gossip::{Content, GossipState, Rumor, Statistics}; use super::messages::{Gossip, Message}; use crate::error::Error; use crate::id::Id; use bincode::serialize; use ed25519::{Keypair, PublicKey}; use rand::seq::SliceRandom; use rand_core::OsRng; use serde::ser::Serialize; use std::fmt::{self, Debug, Formatte...
use super::gossip::{Content, GossipState, Rumor, Statistics}; use super::messages::{Gossip, Message}; use crate::error::Error; use crate::id::Id; use bincode::serialize; use ed25519::{Keypair, PublicKey}; use rand::seq::SliceRandom; use rand_core::OsRng; use serde::ser::Serialize; use std::fmt::{self, Debug, Formatte...
if let Ok((dst_id, Some(push_gossip))) = node.next_round() { processed = true; let _ = gossips_to_push.insert((node.id(), dst_id), push_gossip); } } for ((src_id, dst_id), push_gossip) in gossips_to_push { ...
if !rumors.is_empty() && rng.gen() { let rumor = unwrap!(rumors.pop()); let _ = node.initiate_rumor(&rumor); }
if_condition
[ { "content": "/// This is effectively a container for all the state required to manage a node while the network\n\n/// is running. `Node` implements `Future` and hence each node is run continuously on a single\n\n/// thread from the threadpool. When the future returns, the `Node` has completed processing all\...
Rust
src/bpf/syscall.rs
RG4421/oxidebpf
18d721ac5f03fe291f4e4e88544b5c54937a7108
#[cfg(feature = "log_buf")] use lazy_static::lazy_static; use retry::delay::NoDelay; use retry::{retry_with_index, OperationResult}; use slog::info; use std::ffi::CString; use std::mem::MaybeUninit; use std::os::unix::io::RawFd; use Errno::EAGAIN; use libc::{c_uint, syscall, SYS_bpf}; use nix::errno::{errno, Errno}; ...
#[cfg(feature = "log_buf")] use lazy_static::lazy_static; use retry::delay::NoDelay; use retry::{retry_with_index, OperationResult}; use slog::info; use std::ffi::CString; use std::mem::MaybeUninit; use std::os::unix::io::RawFd; use Errno::EAGAIN; use libc::{c_uint, syscall, SYS_bpf}; use nix::errno::{errno, Errno}; ...
let bpf_attr = SizedBpfAttr { bpf_attr: BpfAttr { map_elem }, size: std::mem::size_of::<MapElem>(), }; unsafe { sys_bpf(BPF_MAP_UPDATE_ELEM, bpf_attr)?; } Ok(()) } pub(crate) unsafe fn bpf_map_create_with_sized_attr( bpf_attr: SizedBpfAttr, ) -> Result<RawFd, OxidebpfEr...
let map_elem = MapElem { map_fd: map_fd as u32, key: &key as *const K as u64, keyval: KeyVal { value: &val as *const V as u64, }, flags: 0, };
assignment_statement
[]
Rust
src/main.rs
Xe/gamebridge
b2e7ba21aa14b556e34d7a99dd02e22f9a1365aa
#[macro_use] extern crate bitflags; pub(crate) mod au; pub(crate) mod controller; pub(crate) mod twitch; use crate::au::Lerper; use anyhow::{anyhow, Result}; use log::{debug, error, info, warn}; use std::{ fs::{File, OpenOptions}, io::{Read, Write}, str::from_utf8, sync::{Arc, RwLock}, thread::sp...
#[macro_use] extern crate bitflags; pub(crate) mod au; pub(crate) mod controller; pub(crate) mod twitch; use crate::au::Lerper; use anyhow::{anyhow, Result}; use log::{debug, error, info, warn}; use std::{ fs::{File, OpenOptions}, io::{Read, Write}, str::from_utf8, sync::{Arc, RwLock}, thread::sp...
:02x}", hi.bits(), lo.bits(), stickx_scalar as u8, sticky_scalar as u8 ); controller[0] = hi.bits() as u8; controller[1] = lo.bits() as u8; controller[2] = stickx_scalar as u8;...
} data.c_right.apply(frame); if data.c_right.pressed(BUTTON_PUSH_THRESHOLD) { lo = lo | LoButtons::C_RIGHT; } debug!( "[ rust] {:02x}{:02x} {:02x}{
random
[ { "content": "fn lerp(start: i64, end: i64, t: f64) -> i64 {\n\n (start as f64 * (1.0 - t) + (end as f64) * t) as i64\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n #[test]\n\n fn lerp_scale() {\n\n for case in [(0.1, 10), (0.5, 31)].iter() {\n\n let t = case.0;\n\n let start =...
Rust
streamer/src/parquet.rs
schradert/podra
e13081e7571ce4427bd70bfaabf47cea6bc51a3e
use std::{ env, fs::File, iter::once, sync::Arc, thread::spawn, time::SystemTime, }; use arrow2::{ array::{Array, Int32Array, Utf8Array}, datatypes::{Field, PhysicalType, Schema}, error::Result, io::parquet::{read, write}, record_batch::RecordBatch, }; use crossbeam_channe...
use std::{ env, fs::File, iter::once, sync::Arc, thread::spawn, time::SystemTime, }; use arrow2::{ array::{Array, Int32Array, Utf8Array}, datatypes::{Field, PhysicalType, Schema}, error::Result, io::parquet::{read, write}, record_batch::RecordBatch, }; use crossbeam_channe...
schema_parquet, options, None, )?; Ok(()) } fn parallel_write_rayon( path: &str, batch: &RecordBatch, ) -> Result<()> { let options = write::WriteOptions { write_statistics: true, compression: write::Compression::Snappy, version: write::Versio...
n(col_num); println!("produce start: {} {}", col_num, row_group_num); let pages = read::get_page_iterator( column_metadata, &mut file, None, vec![], ) .unwrap() ...
random
[ { "content": "fn read_batches(path: &str) -> Result<Vec<RecordBatch>> {\n\n let mut file = File::open(path)?;\n\n let metadata = read::read_file_metadata(&mut file)?;\n\n let reader = read::FileReader::new(&mut file, metadata, None);\n\n\n\n reader.collect()\n\n}\n\n\n", "file_path": "streamer/s...
Rust
server/tests/write_buffer_delete.rs
re-gmbh/influxdb_iox
8717bfa74727bcac0adf762c81878bbdd63435b1
use std::collections::BTreeMap; use std::num::NonZeroU32; use std::sync::Arc; use arrow_util::assert_batches_eq; use data_types::delete_predicate::{DeleteExpr, DeletePredicate, Op, Scalar}; use data_types::router::{ Matcher, MatcherToShard, QuerySinks, Router as RouterConfig, ShardConfig, ShardId, WriteSink, W...
use std::collections::BTreeMap; use std::num::NonZeroU32; use std::sync::Arc; use arrow_util::assert_batches_eq; use data_types::delete_predicate::{DeleteExpr, DeletePredicate, Op, Scalar}; use data_types::router::{ Matcher, MatcherToShard, QuerySinks, Router as RouterConfig, ShardConfig, ShardId, WriteSink, W...
: 20 }, exprs: vec![DeleteExpr { column: "x".to_string(), op: Op::Eq, scalar: Scalar::I64(1), }], }, None, Default::default(), )) .await; fixture.write("bar x=2 ...
(); Self { router, consumer, consumer_db, } } pub async fn wait_for_tables(&self, expected_tables: &[&str]) { wait_for_tables(&self.consumer_db, expected_tables).await } pub async fn write(&self, lp: &str) { self.router ...
random
[ { "content": "pub fn make_server(\n\n server: Arc<RouterServer>,\n\n) -> router_service_server::RouterServiceServer<impl router_service_server::RouterService> {\n\n router_service_server::RouterServiceServer::new(RouterService { server })\n\n}\n", "file_path": "influxdb_iox/src/influxdb_ioxd/server_ty...
Rust
src/database_models/match_models.rs
othello-storm-system/othello_storm_system_backend
5900a404dbbc66b8b5430aed6baba24d81fd42af
use diesel::prelude::*; use diesel::result::Error; use serde_json::{Map, Value}; use crate::errors::ErrorType; use crate::game_match::{GameMatchTransformer, IGameMatch}; use crate::properties::SpecialConditionScore; use super::{RoundDAO, RoundRowModel}; use crate::schema::matches; #[derive(AsChangeset, PartialEq, De...
use diesel::prelude::*; use diesel::result::Error; use serde_json::{Map, Value}; use crate::errors::ErrorType; use crate::game_match::{GameMatchTransformer, IGameMatch}; use crate::properties::SpecialConditionScore; use super::{RoundDAO, RoundRowModel}; use crate::schema::matches; #[derive(AsChangeset, PartialEq, De...
MatchRowModel::insert_to_database(new_match, connection) } fn create_from( game_match: &Box<dyn IGameMatch>, connection: &PgConnection, ) -> Result<Self, ErrorType> { let match_data = GameMatchTransformer::transform_to_match_model_data(game_match); let new_match = ...
let new_match = NewMatchRowModel { round_id, black_player_id, white_player_id, black_score, white_score, meta_data: &meta_data_json, };
assignment_statement
[ { "content": "#[get(\"/<tournament_id>/rounds/<round_id>/standings\")]\n\npub fn get_standings(tournament_id: i32, round_id: i32) -> Json<JsonValue> {\n\n let connection = get_pooled_connection();\n\n response_commands::GetStandingsCommand {\n\n round_id_limit: round_id,\n\n tournament_id,\n...
Rust
src/lib.rs
vinaychandra/embedded-text
71c5e8abbb940deff1fcbab0c06c2c2fced5de10
#![cfg_attr(not(test), no_std)] #![deny(clippy::missing_inline_in_public_items)] #![deny(clippy::cargo)] #![deny(missing_docs)] #![warn(clippy::all)] pub mod alignment; pub mod parser; pub mod rendering; pub mod style; pub mod utils; use alignment::{HorizontalTextAlignment, VerticalTextAlignment}; use embedded_grap...
#![cfg_attr(not(test), no_std)] #![deny(clippy::missing_inline_in_public_items)] #![deny(clippy::cargo)] #![deny(missing_docs)] #![warn(clippy::all)] pub mod alignment; pub mod parser; pub mod rendering; pub mod style; pub mod utils; use alignment::{HorizontalTextAlignment, VerticalTextAlignment}; use embedded_grap...
let y = self.text_box.bounds.top_left.y; let new_y = y.saturating_add(text_height - 1); self.text_box.bounds.bottom_right.y = new_y; self } } impl<'a, C, F, A, V, H> Drawable<C> for &'a StyledTextBox<'a, C, F, A, V, H> where C: PixelColor, F: Font + Copy, A: ...
let text_height = self .style .measure_text_height(self.text_box.text, self.text_box.size().width) .min(max_height) .min(i32::max_value() as u32) as i32;
assignment_statement
[ { "content": "fn str_width<F: Font>(s: &str, ignore_cr: bool) -> u32 {\n\n let mut width = 0;\n\n let mut current_width = 0;\n\n for c in s.chars() {\n\n if !ignore_cr && c == '\\r' {\n\n width = current_width.max(width);\n\n current_width = 0;\n\n } else {\n\n ...
Rust
src/pool.rs
ilammy/dynamic-pool
6237462e096814d2f9aa7977097433d3199018e3
use crossbeam_queue::ArrayQueue; use std::fmt::{Debug, Formatter}; use std::ops::{Deref, DerefMut}; use std::sync::{Arc, Weak}; use crate::DynamicReset; #[derive(Debug)] pub struct DynamicPool<T: DynamicReset> { data: Arc<PoolData<T>>, } impl<T: DynamicReset> DynamicPool<T> { pu...
use crossbeam_queue::ArrayQueue; use std::fmt::{Debug, Formatter}; use std::ops::{Deref, DerefMut}; use std::sync::{Arc, Weak}; use crate::DynamicReset; #[derive(Debug)] pub struct DynamicPool<T: DynamicReset> { data: Arc<PoolData<T>>, } impl<T: DynamicReset> DynamicPool<T> { pu...
}
fn drop(&mut self) { if let Some(mut object) = self.object.take() { object.reset(); if let Some(pool) = self.data.upgrade() { pool.items.push(object).ok(); } } }
function_block-full_function
[ { "content": "pub trait DynamicReset {\n\n fn reset(&mut self);\n\n}\n\n\n\nimpl<T> DynamicReset for Option<T>\n\nwhere\n\n T: DynamicReset,\n\n{\n\n fn reset(&mut self) {\n\n if let Some(x) = self {\n\n x.reset();\n\n }\n\n }\n\n}\n\n\n\nimpl<T1, T2> DynamicReset for (T1, T...
Rust
minidump-processor/src/processor.rs
sigiesec/rust-minidump
aaa0e8cff6d4ec63cbdccd2a1b4df796dec35b24
use breakpad_symbols::{FrameSymbolizer, Symbolizer}; use chrono::{TimeZone, Utc}; use minidump::{self, *}; use process_state::{CallStack, CallStackInfo, ProcessState}; use stackwalker; use std::boxed::Box; use std::ops::Deref; use system_info::SystemInfo; pub trait SymbolProvider { fn fill_symbol(&self, module: ...
use breakpad_symbols::{FrameSymbolizer, Symbolizer}; use chrono::{TimeZone, Utc}; use minidump::{self, *}; use process_state::{CallStack, CallStackInfo, ProcessState}; use stackwalker; use std::boxed::Box; use std::ops::Deref; use system_info::SystemInfo; pub trait SymbolProvider { fn fill_symbol(&self, module: ...
assertion: assertion, requesting_thread: requesting_thread, system_info: system_info, threads: threads, modules: modules, }) }
function_block-function_prefix_line
[ { "content": "pub fn walk_stack<P>(\n\n maybe_context: &Option<&MinidumpContext>,\n\n stack_memory: &Option<MinidumpMemory>,\n\n modules: &MinidumpModuleList,\n\n symbol_provider: &P,\n\n) -> CallStack\n\nwhere\n\n P: SymbolProvider,\n\n{\n\n // Begin with the context frame, and keep getting c...
Rust
tools/lib/cml/macro/src/common.rs
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
extern crate proc_macro; use { proc_macro2::TokenStream as TokenStream2, quote::{quote, TokenStreamExt}, syn, }; pub fn gen_visit_str(ty: Option<TokenStream2>, expected: &syn::LitStr) -> TokenStream2 { let ret = match ty { Some(ty) => quote!(#ty(value)), None => quote!(value), };...
extern crate proc_macro; use { proc_macro2::TokenStream as TokenStream2, quote::{quote, TokenStreamExt}, syn, }; pub fn gen_visit_str(ty: Option<TokenStream2>, expected: &syn::LitStr) -> TokenStream2 { let ret = match ty { Some(ty) => quote!(#ty(value)), None => quote!(value), };...
pub fn extract_unique_items( ast: &syn::DeriveInput, attr: syn::MetaNameValue, unique_items: &mut Option<bool>, ) -> Result<(), syn::Error> { match attr.lit { syn::Lit::Bool(b) => { if unique_items.is_some() { return Err(syn::Error::new_spanned(ast, "duplicate `uniq...
w_spanned(ast, "`min_length` attribute is not base 10") })?; *min_length = Some(l); } _ => { return Err(syn::Error::new_spanned(ast, "`min_length` attribute value must be int")); } } Ok(()) }
function_block-function_prefixed
[]
Rust
07-rust/stm32l0x1/stm32l0x1_pac/src/lpuart1/icr.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Writer for register ICR"] pub type W = crate::W<u32, super::ICR>; #[doc = "Register ICR `reset()`'s with value 0"] impl crate::ResetValue for super::ICR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `WUCF`"] pub struct WUCF_W<...
#[doc = "Writer for register ICR"] pub type W = crate::W<u32, super::ICR>; #[doc = "Register ICR `reset()`'s with value 0"] impl crate::ResetValue for super::ICR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `WUCF`"] pub struct WUCF_W<...
self.bit(true) } #[doc = r"Clears the field bit"] #[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 << 1...
its = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Write proxy for field `TCCF`"] pub struct TCCF_W<'a> { w: &'a mut W, } impl<'a> TCCF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) ...
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
src/mp/integer/integer_ops.rs
selpoG/qboot-rs
ff7bb5bf6486689f4610435121224d6b21bc171d
use super::super::mp; use std::cmp::Ordering; use std::ops::{ Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign, }; use super::super::{Long, ULong}; use super::integer::Integer; fn _add(target: mp::mpz_ptr, op1: mp::mpz_srcptr, op2: mp::mpz_srcptr) { unsafe { mp::__g...
use super::super::mp; use std::cmp::Ordering; use std::ops::{ Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign, }; use super::super::{Long, ULong}; use super::integer::Integer; fn _add(target: mp::mpz_ptr, op1: mp::mpz_srcptr, op2: mp::mpz_srcptr) { unsafe { mp::__g...
fn _ui_sub(target: mp::mpz_ptr, op1: ULong, op2: mp::mpz_srcptr) { unsafe { mp::__gmpz_ui_sub(target, op1, op2); } } fn _si_sub(target: mp::mpz_ptr, op1: Long, op2: mp::mpz_srcptr) { unsafe { _sub_si(target, op2, op1); mp::__gmpz_neg(target, target); } } fn _div(target: mp::mpz...
fn _sub_si(target: mp::mpz_ptr, op1: mp::mpz_srcptr, op2: Long) { unsafe { if op2 >= 0 { mp::__gmpz_sub_ui(target, op1, op2 as ULong); } else { mp::__gmpz_add_ui(target, op1, -op2 as ULong); } } }
function_block-full_function
[ { "content": "fn _mul_si(target: mp::mpfr_ptr, op1: mp::mpfr_srcptr, op2: Long) {\n\n unsafe {\n\n mp::mpfr_mul_si(target, op1, op2, _GLOBAL_RND);\n\n }\n\n}\n", "file_path": "src/mp/real/real_ops.rs", "rank": 0, "score": 149717.46631052246 }, { "content": "fn _add_si(target: mp...
Rust
src/main.rs
JingYenLoh/fluminurs
bc8d6cf0b74f9e0d952caade114cc413d1199349
use std::collections::HashSet; use std::fs; use std::io; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use clap::{App, Arg}; use futures_util::future; use serde::{Deserialize, Serialize}; use tokio; use crate::api::module::{File, Module, OverwriteMode, OverwriteResult}; use crate::api::Api; #[macro_use...
use std::collections::HashSet; use std::fs; use std::io; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use clap::{App, Arg}; use futures_util::future; use serde::{Deserialize, Serialize}; use tokio; use crate::api::module::{File, Module, OverwriteMode, OverwriteResult}; use crate::api::Api; #[macro_use...
} async fn print_announcements(api: &Api, modules: &[Module]) -> Result<()> { let apic = api.clone(); let module_announcements = future::join_all( modules .iter() .map(|module| module.get_announcements(&apic, false)), ) .await; for (module, announcements) in module...
if file.is_directory() { for child in file.children().expect("Children must have been loaded") { print_files(&child, &format!("{}/{}", prefix, file.name())); } } else { println!("{}/{}", prefix, file.name()); }
if_condition
[ { "content": "fn build_auth_form<'a>(username: &'a str, password: &'a str) -> HashMap<&'static str, &'a str> {\n\n let mut map = HashMap::new();\n\n map.insert(\"UserName\", username);\n\n map.insert(\"Password\", password);\n\n map.insert(\"AuthMethod\", \"FormsAuthentication\");\n\n map\n\n}\n\...
Rust
macroquad_macro/src/lib.rs
The-Jon/macroquad
8e80940d611e09cbb360a52c2550a8fed866e9e5
extern crate proc_macro; use proc_macro::{Ident, TokenStream, TokenTree}; use std::iter::Peekable; fn next_group(source: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Option<proc_macro::Group> { if let Some(TokenTree::Group(_)) = source.peek() { let group = match source.next().unwrap() { ...
extern crate proc_macro; use proc_macro::{Ident, TokenStream, TokenTree}; use std::iter::Peekable; fn next_group(source: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Option<proc_macro::Group> { if let Some(TokenTree::Group(_)) = source.peek() { let group = match source.next().unwrap() { ...
#[doc(hidden)] #[proc_macro_derive(CapabilityTrait)] pub fn capability_trait_macro(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let mut source = input.into_iter().peekable(); while let Some(TokenTree::Punct(_)) = source.peek() { let _ = source.next(); let _ = next_group(&mut s...
let _ = source.next().unwrap(); let _group = next_group(&mut source); } if let TokenTree::Ident(ident) = source.next().unwrap() { assert_eq!(format!("{}", ident), "async"); modified.extend(std::iter::once(TokenTree::Ident(ident))); } else { panic!("[macroquad::test] is allo...
function_block-function_prefix_line
[]
Rust
src/lib/storage/ramdevice_client/rust/src/lib.rs
gnoliyil/fuchsia
a98c2d6ae44b7c485c2ee55855d0441da422f4cf
#![deny(missing_docs)] #[allow(bad_style)] mod ramdevice_sys; use { anyhow::Error, fdio, fuchsia_zircon as zx, std::{ ffi, fs, os::unix::io::{AsRawFd, RawFd}, ptr, }, zx::HandleBased, }; enum DevRoot { Provided(fs::File), Isolated, } pub struct VmoRamdiskClientBu...
#![deny(missing_docs)] #[allow(bad_style)] mod ramdevice_sys; use { anyhow::Error, fdio, fuchsia_zircon as zx, std::{ ffi, fs, os::unix::io::{AsRawFd, RawFd}, ptr, }, zx::HandleBased, }; enum DevRoot { Provided(fs::File), Isolated, } pub struct VmoRamdiskClientBu...
; unsafe { ramdevice_sys::ramdisk_create_at( dev_root_fd, block_size, block_count, &mut ramdisk, ) } } ...
match &dev_root { DevRoot::Provided(f) => (f.as_raw_fd(), None), DevRoot::Isolated => { let devmgr = open_isolated_devmgr()?; (devmgr.as_raw_fd(), Some(devmgr)) } }
if_condition
[]
Rust
libtransact/src/families/xo.rs
peterschwarz/transact
a356d456aee65b1aa73a5cf397a72b504b27093e
use crate::error::InvalidStateError; use crate::protocol::batch::BatchBuilder; use crate::protocol::batch::BatchPair; use crate::protocol::transaction::HashMethod; use crate::protocol::transaction::TransactionBuilder; use crate::protocol::transaction::TransactionPair; use crate::workload::BatchWorkload; use crate::work...
use crate::error::InvalidStateError; use crate::protocol::batch::BatchBuilder; use crate::protocol::batch::BatchPair; use crate::protocol::transaction::HashMethod; use crate::protocol::transaction::TransactionBuilder; use crate::protocol::transaction::TransactionPair; use crate::workload::BatchWorkload; use crate::work...
p(|()| self.rng.sample(Alphanumeric)) .map(char::from) .take(NONCE_SIZE) .collect::<String>() .into_bytes(); let payload = Payload::new_as_create_with_random_name(&mut self.rng); Ok(( TransactionBuilder::new() .with_family_nam...
E: usize = 32; pub struct XoTransactionWorkload { rng: StdRng, signer: Box<dyn Signer>, } impl Default for XoTransactionWorkload { fn default() -> Self { Self::new(None, None) } } impl XoTransactionWorkload { pub fn new(seed: Option<u64>, signer: Option<Box<dyn Signer>>) -> Self { ...
random
[ { "content": "fn create_batch(signer: &dyn Signer, game_name: &str, payload: &str) -> BatchPair {\n\n let mut sha = Sha512::default();\n\n sha.update(game_name);\n\n let game_address = \"5b7349\".to_owned() + &hex::encode(&sha.finalize())[..64];\n\n let txn_pair = TransactionBuilder::new()\n\n ...
Rust
tests/trk_write.rs
czotti/trk-io
b90205ccd7a568e4957ea53b7f5b669a775bfac5
mod test; use std::iter::FromIterator; use test::{get_random_trk_path, load_trk}; use trk_io::{Affine4, Point, Reader, Writer}; #[test] fn test_write_dynamic() { let write_to = get_random_trk_path(); let (original_header, original_tractogram) = load_trk("data/simple.trk"); { let mut writer ...
mod test; use std::iter::FromIterator; use test::{get_random_trk_path, load_trk}; use trk_io::{Affine4, Point, Reader, Writer}; #[test] fn test_write_dynamic() { let write_to = get_random_trk_path(); let (original_header, original_tractogram) = load_trk("data/simple.trk"); { let mut writer ...
writer.write(&original_tractogram.streamlines[i]); } } let (header, tractogram) = load_trk(&write_to); assert_eq!(header.nb_streamlines, 10); #[rustfmt::skip] assert_eq!( header.affine4_to_rasmm, Affine4::new( -1.0, 0.0, 0.0, 3.5, 0.0, -1.0, 0.0, ...
ath(); let (original_header, original_tractogram) = load_trk("data/standard.LPS.trk"); { let mut writer = Writer::new(&write_to, Some(original_header.clone())).unwrap(); #[rustfmt::skip] assert_eq!( writer.affine4, Affine4::new( -1.0, 0.0, 0.0, 3....
random
[ { "content": "fn uniform(reader: Reader, header: Header, write_to: &str, r: f32, g: f32, b: f32) {\n\n let mut writer = Writer::new(write_to, Some(header)).unwrap();\n\n for (streamline, mut scalars, properties) in reader.into_iter() {\n\n for _ in 0..streamline.len() {\n\n scalars.push(...
Rust
src/hypergraph/remove.rs
saona-raimundo/ferret_hypergraph
d9c677bdf9e72d491989674ae00cbfccd4ee61c2
use crate::{ elements::{ElementType, ElementValue}, errors, Direction, Hypergraph, }; impl<N, E, H, L, Ty> Hypergraph<N, E, H, L, Ty> { pub fn remove( &mut self, id: impl AsRef<[usize]>, ) -> Result<ElementValue<N, E, H, L>, errors::RemoveError> { let id = id.as_r...
use crate::{ elements::{ElementType, ElementValue}, errors, Direction, Hypergraph, }; impl<N, E, H, L, Ty> Hypergraph<N, E, H, L, Ty> { pub fn remove( &mut self, id: impl AsRef<[usize]>, ) -> Result<ElementValue<N, E, H, L>, errors::RemoveError> { let id = id.as_r...
pub fn remove_node(&mut self, id: impl AsRef<[usize]>) -> Result<N, errors::RemoveError> { let id = id.as_ref(); if !self.contains_node(&id) { Err(errors::NoNode(id.to_vec()))? } let local_id = id.last().unwrap(); for (link_id, _) in self.links_of(id).unwrap()....
d).unwrap(); } } ElementType::Hypergraph => { let raw_hypergraphs = hypergraph.raw_hypergraphs_mut(); let (_, hyperraph_links) = raw_hypergraphs.get_mut(local_id).unwrap(); let link_index = hyperraph_links .ite...
function_block-function_prefixed
[ { "content": "/// A walker is like an iterator, where part of the\n\n/// information is supplied manually at each \"next\" call (named `walk_next`).\n\n///\n\n/// # Remarks\n\n///\n\n/// This allows to visit a Hypergraph without a fixed reference to it.\n\npub trait Walker<'a, N, E, H, L, Ty>: Sized {\n\n ty...
Rust
src/main.rs
danielphan2003/rnix-lsp
c89c8c20700317716cbfbd1bc6731e5056d8e66b
#![warn( missing_copy_implementations, missing_debug_implementations, clippy::cargo_common_metadata, clippy::clone_on_ref_ptr, clippy::dbg_macro, clippy::decimal_literal_representation, clippy::float_cmp_const, clippy::get_unwrap, clippy::integer_arithmetic, clippy::in...
#![warn( missing_copy_implementations, missing_debug_implementations, clippy::cargo_common_metadata, clippy::clone_on_ref_ptr, clippy::dbg_macro, clippy::decimal_literal_representation, clippy::float_cmp_const, clippy::get_unwrap, clippy::integer_arithmetic, clippy::in...
( "textDocument/publishDiagnostics".into(), PublishDiagnosticsParams { uri, diagnostics, version: None, }, )); Ok(()) } }
f.files.get(&params.text_document.uri)?; let offset = utils::lookup_pos(content, params.position)?; let node = ast.node(); let (node, scope, name) = self.scope_for_ident(params.text_document.uri.clone(), &node, offset)?; let (_, content) = self.files.get(&params.te...
random
[ { "content": "pub fn scope_for(file: &Rc<Url>, node: SyntaxNode) -> Option<HashMap<String, Var>> {\n\n let mut scope = HashMap::new();\n\n\n\n let mut current = Some(node);\n\n while let Some(node) = current {\n\n match ParsedType::try_from(node.clone()) {\n\n Ok(ParsedType::LetIn(let...
Rust
src/svi_data_acquirer.rs
Lifars/gargamel
2f220e1fb1e25061f3f29db4860a4ab1df1058a3
use crate::remote::{Connector, Computer, PsExec, PsRemote, Rdp, Wmi, SevenZipCompressCopier, RemoteFileCopier, Compression, Local, RevShareConnector}; use std::path::{Path, PathBuf}; use std::{io, thread}; use std::time::Duration; pub struct SystemVolumeInformationAcquirer<'a> { pub local_store_directory: &'a Path...
use crate::remote::{Connector, Computer, PsExec, PsRemote, Rdp, Wmi, SevenZipCompressCopier, RemoteFileCopier, Compression, Local, RevShareConnector}; use std::path::{Path, PathBuf}; use std::{io, thread}; use std::time::Duration; pub struct SystemVolumeInformationAcquirer<'a> { pub local_store_directory: &'a Path...
pub fn local( username: String, local_store_directory: &'a Path, temp_storage: PathBuf, ) -> SystemVolumeInformationAcquirer<'a> { SystemVolumeInformationAcquirer { local_store_directory, connector: Box::new(Local::new(username, temp_storage)), ...
n psexec32( remote_computer: Computer, local_store_directory: &'a Path, no_7zip: bool, remote_temp_storage: PathBuf, custom_share_folder: Option<String>, reverse: bool, ) -> SystemVolumeInformationAcquirer<'a> { let connector = Box::new(PsExec::psexec32(remote...
function_block-function_prefixed
[ { "content": "pub fn copy_from_local_wildcards<F>(\n\n source: &Path,\n\n target: &Path,\n\n connector: &dyn Connector,\n\n copy_fn: F,\n\n) -> io::Result<()>\n\n where F: Fn(&Path, &Path) -> io::Result<()> {\n\n trace!(\"Copier supports wildcards\");\n\n let dir = source\n\n .compon...
Rust
rulex-lib/src/reference.rs
Aloso/rulex
f56a448003e95283391d1813abe0b9f495cd5dea
use crate::{ compile::{CompileResult, CompileState}, error::{CompileErrorKind, Feature, ParseError}, features::RulexFeatures, options::{CompileOptions, ParseOptions, RegexFlavor}, regex::Regex, span::Span, }; #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) struct Reference<'i> { pub(crate)...
use crate::{ compile::{CompileResult, CompileState}, error::{CompileErrorKind, Feature, ParseError}, features::RulexFeatures, options::{CompileOptions, ParseOptions, RegexFlavor}, regex::Regex, span::Span, }; #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) struct Reference<'i> { pub(crate)...
} i32::MIN..=-1 => offset + (state.next_idx as i32), 1..=i32::MAX => offset + (state.next_idx as i32) - 1, }; if num <= 0 || (num as u32) > state.groups_count { return Err(CompileErrorKind::UnknownReferenceN...
Err( CompileErrorKind::Other("Relative references can't be 0").at(self.span) )
call_expression
[ { "content": "fn get_backslash_help(str: &str) -> Option<String> {\n\n assert!(str.starts_with('\\\\'));\n\n let str = &str[1..];\n\n let mut iter = str.chars();\n\n\n\n Some(match iter.next() {\n\n Some('b') => \"Replace `\\\\b` with `%` to match a word boundary\".into(),\n\n Some('B'...
Rust
src/bin/nydusd/fusedev.rs
changweige/image-service
ba35a388fd12a9c833d20b48a591d029b6af10b5
use std::any::Any; use std::ffi::{CStr, CString}; use std::fs::metadata; use std::io::Result; use std::ops::Deref; use std::os::linux::fs::MetadataExt; use std::os::unix::ffi::OsStrExt; use std::os::unix::net::UnixStream; use std::path::Path; use std::sync::{ atomic::{AtomicI32, AtomicU64, Ordering}, mpsc::{c...
use std::any::Any; use std::ffi::{CStr, CString}; use std::fs::metadata; use std::io::Result; use std::ops::Deref; use std::os::linux::fs::MetadataExt; use std::os::unix::ffi::OsStrExt; use std::os::unix::net::UnixStream; use std::path::Path; use std::sync::{ atomic::{AtomicI32, AtomicU64, Ordering}, mpsc::{c...
; Ok(()) } fn wait(&self) -> DaemonResult<()> { while let Ok(handle) = self.thread_rx.lock().unwrap().recv() { self.running_threads.fetch_sub(1, Ordering::AcqRel); handle .join() .map_err(|e| { DaemonError::WaitDaemon( ...
drop( self.thread_tx .lock() .expect("Not expect poisoned lock") .take() .unwrap(), )
call_expression
[ { "content": "fn register_event(epoll_fd: c_int, fd: RawFd, evt: Events, data: u64) -> io::Result<()> {\n\n let event = Event::new(evt, data);\n\n epoll::ctl(epoll_fd, ControlOptions::EPOLL_CTL_ADD, fd, event)\n\n}\n\n\n\nimpl FuseChannel {\n\n fn new(fd: c_int, evtfd: EventFd, bufsize: usize) -> io::R...
Rust
src/learning/lin_reg.rs
alfaevc/rusty-machine
e7cc57fc5e0f384aeb19169336deb5f66655c76a
use linalg::{Matrix, BaseMatrix}; use linalg::Vector; use learning::{LearningResult, SupModel}; use learning::toolkit::cost_fn::CostFunc; use learning::toolkit::cost_fn::MeanSqError; use learning::optim::grad_desc::GradientDesc; use learning::optim::{OptimAlgorithm, Optimizable}; use learning::error::Error; #[derive...
use linalg::{Matrix, BaseMatrix}; use linalg::Vector; use learning::{LearningResult, SupModel}; use learning::toolkit::cost_fn::CostFunc; use learning::toolkit::cost_fn::MeanSqError; use learning::optim::grad_desc::GradientDesc; use learning::optim::{OptimAlgorithm, Optimizable}; use learning::error::Error; #[derive...
} impl Optimizable for LinRegressor { type Inputs = Matrix<f64>; type Targets = Vector<f64>; fn compute_grad(&self, params: &[f64], inputs: &Matrix<f64>, targets: &Vector<f64>) -> (f64, Vec<f64>) { let beta_vec = Vec...
fn predict(&self, inputs: &Matrix<f64>) -> LearningResult<Vector<f64>> { if let Some(ref v) = self.parameters { let ones = Matrix::<f64>::ones(inputs.rows(), 1); let full_inputs = ones.hcat(inputs); Ok(full_inputs * v) } else { Err(Error::new_untrained()) ...
function_block-full_function
[ { "content": "/// Returns the f1 score for 2 class classification.\n\n///\n\n/// F1-score is calculated with 2 * precision * recall / (precision + recall),\n\n/// see [F1 score](https://en.wikipedia.org/wiki/F1_score) for details.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `outputs` - Iterator of output (predict...
Rust
cmd/replay/src/main.rs
LemonHX/starcoin
d87dbbd8d9b03a93d97075913d35a2c99f216222
use clap::Parser; use sp_utils::stop_watch::start_watch; use starcoin_chain::verifier::Verifier; use starcoin_chain::verifier::{BasicVerifier, ConsensusVerifier, FullVerifier, NoneVerifier}; use starcoin_chain::{BlockChain, ChainReader}; use starcoin_config::RocksdbConfig; use starcoin_config::{BuiltinNetworkID, Chai...
use clap::Parser; use sp_utils::stop_watch::start_watch; use starcoin_chain::verifier::Verifier; use starcoin_chain::verifier::{BasicVerifier, ConsensusVerifier, FullVerifier, NoneVerifier}; use starcoin_chain::{BlockChain, ChainReader}; use starcoin_config::RocksdbConfig; use starcoin_config::{BuiltinNetworkID, Chai...
)) .unwrap(), ); let (chain_info, _) = Genesis::init_and_check_storage(&net, storage.clone(), from_dir.as_ref()) .expect("init storage by genesis fail."); let chain = BlockChain::new(net.time_service(), chain_info.head().id(), storage, None) .expect("create block chain should s...
age::new( from_dir.join("starcoindb/db"), RocksdbConfig::default(), None, ) .unwrap(); let storage = Arc::new( Storage::new(StorageInstance::new_cache_and_db_instance( CacheStorage::new(None), db_storage,
random
[ { "content": "pub fn random_txn(seq_num: u64, net: &ChainNetwork) -> SignedUserTransaction {\n\n let random_public_key = random_public_key();\n\n let addr = account_address::from_public_key(&random_public_key);\n\n peer_to_peer_txn_sent_as_association(\n\n addr,\n\n seq_num,\n\n 10...
Rust
src/lib.rs
tailcats/kvproto
4b2a2d52131a69b007765256956c5957d2d9655b
#[allow(dead_code)] #[allow(unknown_lints)] #[allow(clippy::all)] #[allow(renamed_and_removed_lints)] #[allow(bare_trait_objects)] mod protos { include!(concat!(env!("OUT_DIR"), "/protos/mod.rs")); use raft_proto::eraftpb; } pub use protos::*; #[cfg(feature = "prost-codec")] pub mod prost_adapt { use cra...
#[allow(dead_code)] #[allow(unknown_lints)] #[allow(clippy::all)] #[allow(renamed_and_removed_lints)] #[allow(bare_trait_objects)] mod protos { include!(concat!(env!("OUT_DIR"), "/protos/mod.rs")); use raft_proto::eraftpb; } pub use protos::*; #[cfg(feature = "prost-codec")] pub mod prost_adapt { use cra...
} pub fn take_batch(&mut self) -> WriteBatch { if self.has_batch() { match self.chunk.take() { Some(write_engine_request::Chunk::Batch(v)) => v, _ => unreachable!(), } } else { WriteBatch::de...
match self.chunk { Some(write_engine_request::Chunk::Batch(_)) => true, _ => false, }
if_condition
[ { "content": "\tError *KeyError `protobuf:\"bytes,1,opt,name=error\" json:\"error,omitempty\"`\n", "file_path": "pkg/kvrpcpb/kvrpcpb.pb.go", "rank": 0, "score": 165851.10744556796 }, { "content": "func (*KeyError) ProtoMessage() {}\n", "file_path": "pkg/kvrpcpb/kvrpcpb....
Rust
semantics/src/traversal/contracts.rs
vaporydev/fe
246b23bad148e358ea04b80ca9e4e7a5ce4cec8d
use crate::errors::SemanticError; use crate::namespace::events::Event; use crate::namespace::scopes::{ ContractDef, ContractScope, ModuleScope, Scope, Shared, }; use crate::namespace::types::{ AbiDecodeLocation, FixedSize, Type, }; use crate::traversal::{ functions, types, }; use...
use crate::errors::SemanticError; use crate::namespace::events::Event; use crate::namespace::scopes::{ ContractDef, ContractScope, ModuleScope, Scope, Shared, }; use crate::namespace::types::{ AbiDecodeLocation, FixedSize, Type, }; use crate::traversal::{ functions, types, }; use...
fn event_def( scope: Shared<ContractScope>, stmt: &Spanned<fe::ContractStmt>, ) -> Result<(), SemanticError> { if let fe::ContractStmt::EventDef { name, fields } = &stmt.node { let name = name.node.to_string(); let fields = fields .iter() .map(|field| event_field(Rc...
fn contract_field( scope: Shared<ContractScope>, stmt: &Spanned<fe::ContractStmt>, ) -> Result<(), SemanticError> { if let fe::ContractStmt::ContractField { qual: _, name, typ } = &stmt.node { match types::type_desc(Scope::Contract(Rc::clone(&scope)), typ)? { Type::Map(map) => scope.borr...
function_block-full_function
[ { "content": "/// Maps a type description node to an enum type.\n\npub fn type_desc(scope: Scope, typ: &Spanned<fe::TypeDesc>) -> Result<Type, SemanticError> {\n\n types::type_desc(&scope.module_scope().borrow().defs, &typ.node)\n\n}\n\n\n", "file_path": "semantics/src/traversal/types.rs", "rank": 0,...
Rust
src/image.rs
AlesTsurko/image_uploader
ae6bea76cbbdbc5347924d2ce2ddffc1682f7789
#[cfg(test)] mod tests; mod native_preview_maker; use native_preview_maker::NativePreviewMaker; use bytes::Bytes; use uuid::Uuid; use std::fs::{File, create_dir_all}; use std::io::Write; use crate::{ ImageUploaderResult, IMAGE_NAME, PREVIEW_NAME, }; use failure::Fail; use image::ImageFormat; #[derive(Clone...
#[cfg(test)] mod tests; mod native_preview_maker; use native_preview_maker::NativePreviewMaker; use bytes::Bytes; use uuid::Uuid; use std::fs::{File, create_dir_all}; use std::io::Write; use crate::{ ImageUploaderResult, IMAGE_NAME, PREVIEW_NAME, }; use failure::Fail; use image::ImageFormat; #[derive(Clone...
} impl From<&mime::Mime> for ImageType { fn from(t: &mime::Mime) -> Self { ImageType::from(t.clone()) } } impl From<ImageFormat> for ImageType { fn from(image_format: ImageFormat) -> Self { match image_format { ImageFormat::BMP => ImageType::Bmp, ImageFormat::GIF =...
fn from(t: mime::Mime) -> Self { match t.subtype() { mime::BMP => ImageType::Bmp, mime::GIF => ImageType::Gif, mime::JPEG => ImageType::Jpeg, mime::PNG => ImageType::Png, _ => ImageType::Unknown, } }
function_block-full_function
[ { "content": "#[test]\n\nfn get_preview_file_path() {\n\n let image = init_image();\n\n assert_eq!(format!(\"storage/{}/{}.jpg\", UUID, PREVIEW_NAME), image.get_preview_file_path());\n\n}\n\n\n", "file_path": "src/image/tests.rs", "rank": 0, "score": 112376.14271530061 }, { "content": ...
Rust
src/graphics/render_system.rs
BrassLion/rust-pbr
1b406984d27d7477eb4319ac3acbf2916d7ca755
use super::*; use specs::prelude::*; pub struct RenderSystem; pub struct RenderSystemData { depth_texture: Texture, } impl<'a> System<'a> for RenderSystem { type SystemData = ( WriteExpect<'a, RenderState>, ReadExpect<'a, Camera>, ReadExpect<'a, RenderSystemData>, ReadStorage<...
use super::*; use specs::prelude::*; pub struct RenderSystem; pub struct RenderSystemData { depth_texture: Texture, } impl<'a> System<'a> for RenderSystem { type SystemData = ( WriteExpect<'a, RenderState>, ReadExpect<'a, Camera>, ReadExpect<'a, RenderSystemData>, ReadStorage<...
}
fn run(&mut self, data: Self::SystemData) { let (mut render_state, camera, render_system_data, light, pose, renderable) = data; let frame = render_state .swap_chain .get_next_texture() .expect("Timeout getting texture"); let mut encoder = ...
function_block-full_function
[ { "content": "pub fn build_render_pipeline(\n\n device: &wgpu::Device,\n\n vertex_shader_src: &str,\n\n fragment_shader_src: &str,\n\n bind_group_layouts: &[&wgpu::BindGroupLayout],\n\n vertex_state_desc: wgpu::VertexStateDescriptor,\n\n colour_states: &[wgpu::ColorStateDescriptor],\n\n dep...
Rust
2019/day12/src/main.rs
dcoles/advent-of-code
4d480934daad60fcdb2112ef66f4115d9cb83ac2
use std::path::Path; use std::{fs, ops}; use std::fmt; use std::collections::HashSet; fn main() { let mut s1 = Simulation::new(read_input("sample1.txt")); s1.simulate_n_steps(10); assert_eq!(179, s1.total_energy()); let mut s2 = Simulation::new(read_input("sample2.txt")); s2.simulate_n_steps(...
use std::path::Path; use std::{fs, ops}; use std::fmt; use std::collections::HashSet; fn main() { let mut s1 = Simulation::new(read_input("sample1.txt")); s1.simulate_n_steps(10); assert_eq!(179, s1.total_energy()); let mut s2 = Simulation::new(read_input("sample2.txt")); s2.simulate_n_steps(...
fn read_input<T: AsRef<Path>>(path: T) -> Vec<Moon> { let mut coords = Vec::new(); let contents = fs::read_to_string(path).expect("Failed to read input"); for line in contents.lines() { let line = line.trim_start_matches('<').trim_end_matches('>'); let mut split = line.split(','); ...
let mut sim1 = Simulation::new(read_input("input.txt")); sim1.simulate_n_steps(1000); println!("Part 1: Total energy of system after 1000 steps: {}", sim1.total_energy()); let mut sim2 = Simulation::new(read_input("input.txt")); sim2.simulate_until_repeat(); println!("Part 2: {}", sim2.t); }
function_block-function_prefix_line
[ { "content": "fn reduce(pair: &mut Number) {\n\n loop {\n\n if explode(pair) {\n\n //println!(\"Explode: {:?}\", pair);\n\n continue;\n\n }\n\n\n\n if split(pair) {\n\n //println!(\"Split: {:?}\", pair);\n\n continue;\n\n }\n\n\n\n ...
Rust
compiler-core/src/io.rs
TristanCacqueray/gleam
6b77fbe92b38b7d0a31fd824caaf66d0e1708be5
pub mod memory; use crate::error::{Error, FileIoAction, FileKind, Result}; use async_trait::async_trait; use debug_ignore::DebugIgnore; use flate2::read::GzDecoder; use std::{ fmt::Debug, fs::ReadDir, io, path::{Path, PathBuf}, process::ExitStatus, }; use tar::{Archive, Entry}; pub trait Utf8Write...
pub mod memory; use crate::error::{Error, FileIoAction, FileKind, Result}; use async_trait::async_trait; use debug_ignore::DebugIgnore; use flate2::read::GzDecoder; use std::{ fmt::Debug, fs::ReadDir, io, path::{Path, PathBuf}, process::ExitStatus, }; use tar::{Archive, Entry}; pub trait Utf8Write...
MemoryFile { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { self.contents.borrow_mut().write(buf) } fn flush(&mut self) -> std::io::Result<()> { self.contents.borrow_mut().flush() } } impl std::fmt::Write for InMemoryFile { fn write_...
fn mkdir(&self, _path: &Path) -> Result<(), Error> { panic!("FilesChannel does not support mkdir") } fn copy_dir(&self, _from: &Path, _to: &Path) -> Result<(), Error> { panic!("FilesChannel does not support copy_dir") } } impl FileSystemReader for FilesChann...
random
[ { "content": "pub fn erlang_files(dir: &Path) -> Result<impl Iterator<Item = PathBuf> + '_> {\n\n Ok(read_dir(dir)?\n\n .flat_map(Result::ok)\n\n .map(|e| e.path())\n\n .filter(|path| {\n\n let extension = path\n\n .extension()\n\n .unwrap_or_defa...
Rust
components/pkg-export-container/src/container.rs
Mastercard/habitat-1
de95485cc74b94bcbd2fcd2c1728ea5b575b7844
use crate::{build::BuildRoot, engine::Engine, error::Result, naming::{ImageIdentifiers, Naming}, util}; use failure::SyncFailure; use habitat_common::ui::{Status, UIWriter, UI}; use habitat_core::packa...
use crate::{build::BuildRoot, engine::Engine, error::Result, naming::{ImageIdentifiers, Naming}, util}; use failure::SyncFailure; use habitat_common::ui::{Status, UIWriter, UI}; use habitat_core::packa...
} } pub struct BuildContext(BuildRoot); impl BuildContext { #[cfg(unix)] pub fn from_build_root(build_root: BuildRoot, ui: &mut UI) -> Result<Self> { let context = BuildContext(build_root); context.add_users_and_groups(ui)?; context.create_entrypoint(...
if let Err(e) = std::fs::copy(&current_report, &old_report) { error!("Failed to create '{}' for backwards-compatibility purposes; this may safely \ be ignored: {}", old_report.display(), e); }
if_condition
[]
Rust
crates/core/src/year2021/day05.rs
fornwall/advent-of-code-2019-rs
67bb6a48860f20a773f9e913c7e498c921370eeb
use crate::input::Input; struct Board { claimed_once: [u64; (1000 * 1000) / 64], claimed_multiple: [u64; (1000 * 1000) / 64], } impl Board { const fn new() -> Self { Self { claimed_once: [0; (1000 * 1000) / 64], claimed_multiple: [0; (1000 * 1000) / 64], } ...
use crate::input::Input; struct Board { claimed_once: [u64; (1000 * 1000) / 64], claimed_multiple: [u64; (1000 * 1000) / 64], } impl Board { const fn new() -> Self { Self { claimed_once: [0; (1000 * 1000) / 64], claimed_multiple: [0; (1000 * 1000) / 64], } ...
fn claimed_multiple(&self) -> u32 { self.claimed_multiple.iter().map(|&i| i.count_ones()).sum() } fn add_line(&mut self, from_x: u16, from_y: u16, to_x: u16, to_y: u16) { let mut current_x = i32::from(from_x); let mut current_y = i32::from(from_y); let dx = (i32::from(to_...
if self.claimed_once[array_idx] & local_bit == 0 { self.claimed_once[array_idx] |= local_bit; } else { self.claimed_multiple[array_idx] |= local_bit; } }
function_block-function_prefix_line
[ { "content": "#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]\n\nstruct State<const SIDE_ROOM_SIZE: usize> {\n\n hallways: [Option<Amphipod>; HALLWAY_SPACES],\n\n /// Indexed by amphipod idx\n\n rooms: [[Option<Amphipod>; SIDE_ROOM_SIZE]; 4],\n\n}\n\n\n\nimpl<const SIDE_ROOM_SIZE: usize> S...
Rust
src/encodings/arithmetic_coder/decoder.rs
gcarq/comprs
b23556b78e0813a223bd7dbd09141c94b0a371d1
use std::cmp; use std::io::{Read, Result}; use bitbit::{BitReader, MSB}; use crate::encodings::arithmetic_coder::Symbol; use super::base::ArithmeticCoderBase; use super::FrequencyTable; pub struct ArithmeticDecoder<R: Read> { reader: BitReader<R, MSB>, code: usize, low: usize, high: usiz...
use std::cmp; use std::io::{Read, Result}; use bitbit::{BitReader, MSB}; use crate::encodings::arithmetic_coder::Symbol; use super::base::ArithmeticCoderBase; use super::FrequencyTable; pub struct ArithmeticDecoder<R: Read> { reader: BitReader<R, MSB>, code: usize, low: usize, high: usiz...
} impl<R: Read> ArithmeticDecoder<R> { pub fn new(mut reader: BitReader<R, MSB>, num_bits: usize) -> Result<Self> { let num_state_bits = num_bits; let full_range = 1 << num_state_bits; let half_range = full_range >> 1; let quarte...
fn underflow(&mut self) { let bit = if self.reader.read_bit().unwrap_or(false) { 1 } else { 0 }; self.code = (self.code & self.half_range) | ((self.code << 1) & (self.state_mask >> 1)) | bit; }
function_block-full_function
[ { "content": "pub fn encode_pipeline<R: Read>(reader: R) -> Result<Vec<u8>> {\n\n Ok(bincode::serialize(&TData::encode(reader)?).expect(\"unable to serialize data\"))\n\n}\n\n\n", "file_path": "src/encodings/mod.rs", "rank": 0, "score": 155834.14144813723 }, { "content": "pub fn decode_pi...
Rust
www/src/main.rs
noguxun/rust_web_play
8b8b9a8127687ba347a9c27db40debce384a7e2a
#[macro_use] extern crate derive_more; use bytes::BytesMut; use env_logger::{Builder, Env}; use futures::future; use futures::stream::StreamExt; use futures::FutureExt; use handlebars::Handlebars; use http::header::{HeaderMap, HeaderValue}; use http::status::StatusCode; use http::Uri; use hyper::service::{make_servi...
#[macro_use] extern crate derive_more; use bytes::BytesMut; use env_logger::{Builder, Env}; use futures::future; use futures::stream::StreamExt; use futures::FutureExt; use handlebars::Handlebars; use http::header::{HeaderMap, HeaderValue}; use http::status::StatusCode; use http::Uri; use hyper::service::{make_servi...
; Ok(resp) } fn make_error_response_from_code(status: StatusCode) -> Result<Response<Body>> { make_error_response_from_code_and_headers(status, HeaderMap::new()) } fn make_error_response_from_code_and_headers( status: StatusCode, headers: HeaderMap, ) -> Result<Response<Body>> { let body = render_...
match error.kind() { io::ErrorKind::NotFound => { debug!("{}", error); make_error_response_from_code(StatusCode::NOT_FOUND)? } _ => make_internal_server_error_response(Error::Io(error))?, }
if_condition
[ { "content": "fn make_dir_list_body(root_dir: &Path, paths: &[PathBuf]) -> Result<String> {\n\n let mut buf = String::new();\n\n\n\n writeln!(buf, \"<div>\").map_err(Error::WriteInDirList)?;\n\n\n\n let dot_dot = OsStr::new(\"..\");\n\n\n\n for path in paths {\n\n let full_url = path\n\n ...
Rust
src/cooking_book/recipe.rs
totoMauz/Cooking-Book
d80b051d38e68430ec1d391d6815c44fada08ce1
use crate::cooking_book::ingredient::Ingredient; use crate::file_access::persistency; use std::collections::HashMap; use std::collections::HashSet; #[derive(PartialEq, Eq)] pub struct Recipe { pub name: String, pub ingredients: HashMap<Ingredient, (u16, String)>, pub tags: HashSet<String>, } impl Recipe {...
use crate::cooking_book::ingredient::Ingredient; use crate::file_access::persistency; use std::collections::HashMap; use std::collections::HashSet; #[derive(PartialEq, Eq)] pub struct Recipe { pub name: String, pub ingredients: HashMap<Ingredient, (u16, String)>, pub tags: HashSet<String>, } impl Recipe {...
.insert("Frühstück".to_string()); let waffels = Recipe { name: "Waffeln".to_string(), ingredients: ingredients1, tags: tags1, }; assert_eq!(waffels.to_json(), "{\"name\": \"Waffeln\", \"ingredients\": [{\"name\": \"Ei\", \"amount\": 1, \"unit\": \"Stück\"}]}...
let mut ingredients1: HashMap<Ingredient, (u16, String)> = HashMap::with_capacity(1); let in1 = Ingredient::new_by_name("Ei".to_string()); ingredients1.insert(in1, (1, "Stück".to_string())); let mut tags1: HashSet<String> = HashSet::with_capacity(1); tags1
function_block-random_span
[ { "content": "#[delete(\"/ingredient/<name>\", format = \"application/json\")]\n\nfn delete_ingredient(name: String) -> String {\n\n let ingredients = persistency::load_ingredients();\n\n\n\n let mut shopping_list = persistency::load_shopping_list();\n\n if ingredients.contains_key(&name) {\n\n ...
Rust
foreign-types-macros/src/build.rs
flier/foreign-types
263ab4afdb1268073e1cbbf010768198fae388ec
use proc_macro2::TokenStream; use quote::quote; use syn::{Path, Ident}; use crate::parse::{Input, ForeignType}; fn ref_name(input: &ForeignType) -> Ident { Ident::new(&format!("{}Ref", input.name), input.name.span()) } pub fn build(input: Input) -> TokenStream { let types = input.types.iter().map(|t| build_f...
use proc_macro2::TokenStream; use quote::quote; use syn::{Path, Ident}; use crate::parse::{Input, ForeignType}; fn ref_name(input: &ForeignType) -> Ident { Ident::new(&format!("{}Ref", input.name), input.name.span()) } pub fn build(input: Input) -> TokenStream { let types = input.types.iter().map(|t| build_f...
#[cfg(feature = "std")] fn build_to_owned_impl(crate_: &Path, input: &ForeignType) -> TokenStream { let clone = match &input.clone { Some(clone) => clone, None => return quote!(), }; let name = &input.name; let ref_name = ref_name(input); let (impl_generics, ty_generics, _) = input...
fn build_clone_impl(crate_: &Path, input: &ForeignType) -> TokenStream { let clone = match &input.clone { Some(clone) => clone, None => return quote!(), }; let name = &input.name; let (impl_generics, ty_generics, _) = input.generics.split_for_impl(); quote! { impl #impl_gene...
function_block-full_function
[ { "content": "#[proc_macro]\n\npub fn foreign_type_impl(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as Input);\n\n build::build(input).into()\n\n}\n", "file_path": "foreign-types-macros/src/lib.rs", "rank": 5, "score": 107763.6663491709 }, { "content":...
Rust
batiskaf_derive/tests/sql_result.rs
yakov-bakhmatov/batiskaf
aa5bc46df1e5cab201159a3ef5910fb860a4f301
use rusqlite::types::ToSql; use rusqlite::{Connection, NO_PARAMS}; use batiskaf::SqlResult; use batiskaf_derive::*; #[test] fn test_sql_result() { #[derive(Debug, Eq, PartialEq, SqlResult)] struct Person { pub id: i64, pub name: String, pub age: Option<u32>, } let conn = Connec...
use rusqlite::types::ToSql; use rusqlite::{Connection, NO_PARAMS}; use batiskaf::SqlResult; use batiskaf_derive::*; #[test] fn test_sql_result() { #[derive(Debug, Eq, PartialEq, SqlResult)] struct Person { pub id: i64, pub name: String, pub age: Option<u32>,
(); let mut stmt = conn .prepare("insert into key_value (key, value) values (:key, :value)") .unwrap(); stmt.execute_named(&[(":key", &"name" as &dyn ToSql), (":value", &"Bob")]) .unwrap(); let mut select = conn.prepare("select key, value from key_value").unwrap(); let mut rows =...
} let conn = Connection::open_in_memory().unwrap(); conn.execute( "create table person (id integer primary key, name text not null, age integer)", NO_PARAMS, ) .unwrap(); let mut stmt = conn .prepare("insert into person (name, age) values (:name, :age)") .unwrap()...
random
[ { "content": "#[derive(Debug, Eq, PartialEq)]\n\nstruct Person {\n\n pub id: i64,\n\n pub name: String,\n\n pub age: Option<u32>,\n\n}\n\n\n\nimpl SqlParam for Person {\n\n fn to_named_params(&self, stmt: &Statement) -> Vec<(&str, &dyn ToSql)> {\n\n let mut params = Vec::new();\n\n if ...
Rust
core/src/variant_array.rs
sprucely/godot-rust
bea2eb2ad4e46f76c9e029a8680e224cb2a8701a
use sys; use get_api; use Variant; use ToVariant; pub struct VariantArray(pub(crate) sys::godot_array); impl VariantArray { pub fn new() -> Self { VariantArray::default() } pub fn set(&mut self, idx: i32, val: &Variant) { unsafe { (get_api().godot_array_set)(&mut self.0, idx, &v...
use sys; use get_api; use Variant; use ToVariant; pub struct VariantArray(pub(crate) sys::godot_array); impl VariantArray { pub fn new() -> Self { VariantArray::default() } pub fn set(&mut self, idx: i32, val: &Variant) { unsafe { (get_api().godot_array_set)(&mut self.0, idx, &v...
pub fn get_mut_ref(&mut self, idx: i32) -> &mut Variant { unsafe { Variant::cast_mut_ref((get_api().godot_array_operator_index)(&mut self.0, idx)) } } pub fn count(&mut self, val: &Variant) -> i32 { unsafe { (get_api().godot_array_count)(&mut self.0, &...
x: i32) -> &Variant { unsafe { Variant::cast_ref( (get_api().godot_array_operator_index_const)(&self.0, idx) ) } }
function_block-function_prefixed
[ { "content": "pub fn generate_bindings(\n\n output: &mut File,\n\n crate_type: Crate,\n\n) -> GeneratorResult {\n\n\n\n let api = Api::new(crate_type);\n\n\n\n writeln!(output, \"use std::os::raw::c_char;\")?;\n\n writeln!(output, \"use std::ptr;\")?;\n\n writeln!(output, \"use std::mem;\")?;\...
Rust
pipebuilder/src/cli/commands/list.rs
pipebase/pipebuilder
9e5e08ff9526c1e0917034dc49951939beceac01
use super::Cmd; use crate::ops::{ do_app::list_app_metadata, do_build::{list_build_metadata, list_build_snapshot}, do_catalog_schema::{list_catalog_schema_metadata, list_catalog_schema_snapshot}, do_catalogs::{list_catalogs_metadata, list_catalogs_snapshot}, do_manifest::{list_manifest_metadata, lis...
use super::Cmd; use crate::ops::{ do_app::list_app_metadata, do_build::{list_build_metadata, list_build_snapshot}, do_catalog_schema::{list_catalog_schema_metadata, list_catalog_schema_snapshot}, do_catalogs::{list_catalogs_metadata, list_catalogs_snapshot}, do_manifest::{list_manifest_metadata, lis...
async fn exec_manifest_metadata(client: ApiClient, args: &clap::ArgMatches) -> Result<()> { let namespace = args.value_of("namespace").unwrap(); let id = args.value_of("id"); let id = id.map(|id| id.to_owned()); let response = list_manifest_metadata(&client, namespace.to_owned(), id).await?; print...
async fn exec_manifest_snapshot(client: ApiClient, args: &clap::ArgMatches) -> Result<()> { let namespace = args.value_of("namespace").unwrap(); let response = list_manifest_snapshot(&client, namespace.to_owned()).await?; print_records(response.as_slice()); Ok(()) }
function_block-full_function
[ { "content": "pub fn validate_node_state(state: &NodeState, expected_role: &NodeRole) -> Result<()> {\n\n let actual_role = &state.role;\n\n if actual_role != expected_role {\n\n return Err(invalid_api_request(format!(\n\n \"invalid node state, expect '{}', actual '{}'\",\n\n ...
Rust
src/lib.rs
denbeigh2000/rusty-interaction
ee7abe7d1e57dc3de58ef89ab2441c40108b3aad
#![warn(missing_docs)] #[macro_use] mod macros; #[allow(dead_code)] const BASE_URL: &str = "https://discord.com/api/v9"; #[cfg(feature = "types")] pub mod types; #[cfg(feature = "security")] pub mod security; #[cfg(any(feature = "handler", feature = "extended-handler"))] #[cfg_attr(docsrs, doc(cfg(feature = "hand...
#![warn(missing_docs)] #[macro_use] mod macros; #[allow(dead_code)] const BASE_URL: &str = "https://discord.com/api/v9"; #[cfg(feature = "types")] pub mod types; #[cfg(feature = "security")] pub mod security; #[cfg(any(feature = "handler", feature = "extended-handler"))] #[cfg_attr(docsrs, doc(cfg(feature = "hand...
} else { let a: Result<$struc, serde_json::Error> = serde_json::from_str(&text); match a { Err(e) => { debug!("Failed to decode response: {:#?}", e); debug!("Original response: {:#?}", &text...
or>; } #[macro_export] #[doc(hidden)] macro_rules! expect_successful_api_response { ($response:ident, $succret:expr) => { match $response { Err(e) => { debug!("Discord API request failed: {:#?}", e); Err(HttpError { code: 0, ...
random
[ { "content": "fn handler(\n\n _attr: TokenStream,\n\n item: TokenStream,\n\n defer_return: quote::__private::TokenStream,\n\n) -> TokenStream {\n\n // There is _probably_ a more efficient way to do what I want to do, but hey I am here\n\n // to learn so why not join me on my quest to create this ...
Rust
src/api/schema/components/source.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::cmp; use async_graphql::{Enum, InputObject, Object}; use strum::IntoEnumIterator; use strum_macros::EnumIter; use super::{sink, state, transform, Component}; use crate::{ api::schema::{ filter, metrics::{self, outputs_by_component_key, IntoSourceMetrics, Output}, sort, }, ...
use std::cmp; use async_graphql::{Enum, InputObject, Object}; use strum::IntoEnumIterator; use strum_macros::EnumIter; use super::{sink, state, transform, Component}; use crate::{ api::schema::{ filter, metrics::{self, outputs_by_component_key, IntoSourceMetrics, Output}, sort, }, ...
sort::by_fields(&mut sources, &fields); for (i, component_id) in ["gen3", "gen2", "gen1"].iter().enumerate() { assert_eq!(sources[i].get_component_key().to_string(), *component_id); } } #[test] fn sort_component_type_asc() { let mut sources = vec![ ...
let fields = vec![sort::SortField::<SourcesSortFieldName> { field: SourcesSortFieldName::ComponentKey, direction: sort::Direction::Desc, }];
assignment_statement
[ { "content": "pub fn outputs_by_component_key(component_key: &ComponentKey, outputs: &[String]) -> Vec<Output> {\n\n let metrics = by_component_key(component_key)\n\n .into_iter()\n\n .filter(|m| m.name() == \"component_sent_events_total\")\n\n .collect::<Vec<_>>();\n\n\n\n outputs\n\...
Rust
src/dma/ifc.rs
lucab/efm32hg-pac
ca4230132f7ce087da064f6d7d613e262fef8e62
#[doc = "Writer for register IFC"] pub type W = crate::W<u32, super::IFC>; #[doc = "Register IFC `reset()`'s with value 0"] impl crate::ResetValue for super::IFC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `CH0DONE`"] pub struct CH0D...
#[doc = "Writer for register IFC"] pub type W = crate::W<u32, super::IFC>; #[doc = "Register IFC `reset()`'s with value 0"] impl crate::ResetValue for super::IFC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `CH0DONE`"] pub struct CH0D...
raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Write proxy for field `CH4DONE`"] pub struct CH4DONE_W<'a> { w: &'a mut W, } impl<'a> CH4DONE_W<'a> { ...
e as u32) & 0x01); self.w } } #[doc = "Write proxy for field `CH1DONE`"] pub struct CH1DONE_W<'a> { w: &'a mut W, } impl<'a> CH1DONE_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
[ { "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
src/dispatcher/sink.rs
majacQ/CorTeX
7957f91131f52c9f13b77a890ec2cdcc213c7b8e
use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::io; use std::io::ErrorKind; use std::io::Write; use std::ops::Deref; use std::path::Path; use std::sync::Arc; use std::sync::Mutex; use time; use crate::dispatcher::server; use crate::helpers; use crate::helpers::{TaskProgress, TaskRepo...
use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::io; use std::io::ErrorKind; use std::io::Write; use std::ops::Deref; use std::path::Path; use std::sync::Arc; use std::sync::Mutex; use time; use crate::dispatcher::server; use crate::helpers; use crate::helpers::{TaskProgress, TaskRepo...
}
pub fn start( &self, services_arc: &Arc<Mutex<HashMap<String, Option<Service>>>>, progress_queue_arc: &Arc<Mutex<HashMap<i64, TaskProgress>>>, done_queue_arc: &Arc<Mutex<Vec<TaskReport>>>, job_limit: Option<usize>, ) -> Result<(), Box<dyn Error>> { let context = zmq::Context::new(); l...
function_block-full_function
[ { "content": "/// Utility functions, until they find a better place\n\npub fn utf_truncate(input: &mut String, maxsize: usize) {\n\n let mut utf_maxsize = input.len();\n\n if utf_maxsize >= maxsize {\n\n {\n\n let mut char_iter = input.char_indices();\n\n while utf_maxsize >= maxsize {\n\n ...
Rust
egui_glium/src/backend.rs
katyo/egui
02db9ee5835a522ddf04308f259025388abf0185
use crate::{window_settings::WindowSettings, *}; use egui::Color32; #[cfg(target_os = "windows")] use glium::glutin::platform::windows::WindowBuilderExtWindows; use std::time::Instant; #[cfg(feature = "persistence")] const EGUI_MEMORY_KEY: &str = "egui"; #[cfg(feature = "persistence")] const WINDOW_KEY: &str = "window...
use crate::{window_settings::WindowSettings, *}; use egui::Color32; #[cfg(target_os = "windows")] use glium::glutin::platform::windows::WindowBuilderExtWindows; use std::time::Instant; #[cfg(feature = "persistence")] const EGUI_MEMORY_KEY: &str = "egui"; #[cfg(feature = "persistence")] const WINDOW_KEY: &str = "window...
#[cfg(not(feature = "persistence"))] fn create_storage(_app_name: &str) -> Option<Box<dyn epi::Storage>> { None } #[cfg(feature = "persistence")] fn create_storage(app_name: &str) -> Option<Box<dyn epi::Storage>> { if let Some(proj_dirs) = directories_next::ProjectDirs::from("", "", app_name) { let d...
w() .with_depth_buffer(0) .with_srgb(true) .with_stencil_buffer(0) .with_vsync(true); let display = glium::Display::new(window_builder, context_builder, &event_loop).unwrap(); if let Some(window_settings) = &window_settings { window_settings.restore_positions(&display);...
function_block-function_prefixed
[ { "content": "// A wrapper that allows the more idiomatic usage pattern: `ui.add(toggle(&mut my_bool))`\n\n/// iOS-style toggle switch.\n\n///\n\n/// ## Example:\n\n/// ``` ignore\n\n/// ui.add(toggle(&mut my_bool));\n\n/// ```\n\npub fn toggle(on: &mut bool) -> impl egui::Widget + '_ {\n\n move |ui: &mut eg...
Rust
rust_dev_preview/cross_service/detect_faces/src/main.rs
grjan7/aws-doc-sdk-examples
4a9ce4ee5c9a8808fd6c905dbef25d3674ef1dd5
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use std::error::Error; use std::path::Path; use structopt::StructOpt; #[derive(Debug)] struct Person { from_left: f32, age_range: String, ...
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use std::error::Error; use std::path::Path; use structopt::StructOpt; #[derive(Debug)] struct Person { from_left: f32, age_range: String, ...
.region(s3_region_provider) .load() .await; let s3_client = aws_sdk_s3::Client::new(&s3_shared_config); let rek_shared_config = aws_config::from_env() .region(rek_region_provider) .load() .await; let rek_client = aws_sdk_rekognition::Client::new(&rek_shared_config)...
es(aws_sdk_rekognition::model::Attribute::All) .send() .await?; let mut persons: Vec<Person> = vec![]; for detail in resp.face_details.unwrap_or_default() { if verbose { println!("{:?}", detail); println!(); } let age = detail.age_range.unw...
random
[ { "content": "#[derive(Debug, StructOpt)]\n\nstruct Opt {\n\n /// The AWS Region.\n\n #[structopt(short, long)]\n\n region: Option<String>,\n\n\n\n /// The data to be uploaded to S3.\n\n #[structopt(short, long)]\n\n body: String,\n\n\n\n /// The name of the bucket.\n\n #[structopt(short...
Rust
src/ir/layout.rs
birdbrainswagtrain/combinatorio
89240facff6bc0b341164580c29721ddcaf812d8
use std::collections::HashMap; use rand::Rng; use crate::{common::ConnectType, disjoint_set::DisjointSet}; use super::{IRArg, IRModule, IRNode, WireColor}; #[derive(Debug)] struct WireNet { color: WireColor, connections: Vec<(u32,ConnectType)> } const MAX_DIST: f32 = 9.0; fn square_dist(a: (f32,f32), b: (f...
use std::collections::HashMap; use rand::Rng; use crate::{common::ConnectType, disjoint_set::DisjointSet}; use super::{IRArg, IRModule, IRNode, WireColor}; #[derive(Debug)] struct WireNet { color: WireColor, connections: Vec<(u32,ConnectType)> } const MAX_DIST: f32 = 9.0; fn square_dist(a: (f32,f32), b: (f...
self.shift_chain(module, new_pos, base_pos); } assert_eq!(module.grid.get_id_at(new_pos),None); module.grid.set(new_pos, *id); } } fn shift_chain(&self, module: &mut IRModule, start_pos: (i32,i32), end_pos: (i32,i32)) { ...
pos_b)) { continue; } link_count += 1; subnet_ids.merge(net_id_a, net_id_b); out.push(WireLink{ color: self.color, a: self.connections[id_a].clone(), ...
random
[ { "content": "fn update_color_for_arg(arg: &mut IRArg, forbid_color: WireColor, out_color_counts: &mut Vec<ColorCounts>) -> WireColor {\n\n match arg {\n\n IRArg::Link(parent,color) => {\n\n assert_eq!(*color,WireColor::None);\n\n\n\n let counts = &mut out_color_counts[*parent as...
Rust
summarize/src/main.rs
bugadani/measureme
03a352fca3e9bcf7faeb16218ba5b61345bddd97
#[macro_use] extern crate prettytable; use analyzeme::ProfilingData; use std::error::Error; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::{path::PathBuf, time::Duration}; use prettytable::{Cell, Row, Table}; use serde::Serialize; use structopt::StructOpt; mod aggregate; mod analysis; mod diff; mod...
#[macro_use] extern crate prettytable; use analyzeme::ProfilingData; use std::error::Error; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::{path::PathBuf, time::Duration}; use prettytable::{Cell, Row, Table}; use serde::Serialize; use structopt::StructOpt; mod aggregate; mod analysis; mod diff; mod...
fn aggregate(opt: AggregateOpt) -> Result<(), Box<dyn Error + Send + Sync>> { let profiles = opt .files .into_iter() .map(|file| ProfilingData::new(&file)) .collect::<Result<Vec<_>, _>>()?; aggregate::aggregate_profiles(profiles); Ok(()) } fn diff(opt: DiffOpt) -> R...
fn write_results_json( file: &PathBuf, results: impl Serialize, ) -> Result<(), Box<dyn Error + Send + Sync>> { let file = BufWriter::new(File::create(file.with_extension("json"))?); serde_json::to_writer(file, &results)?; Ok(()) }
function_block-full_function
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {\n\n let opt = Opt::from_args();\n\n\n\n let chrome_file = BufWriter::new(fs::File::create(\"chrome_profiler.json\")?);\n\n let mut serializer = serde_json::Serializer::new(chrome_file);\n\n\n\n let mut seq = serializer...
Rust
src/config.rs
bekicot/cigale
3cf366b02237d43f9a4bf202de93adf8de3d17ba
use crate::events::events::{EventProvider, Result}; use chrono::prelude::*; use gtk::prelude::*; use regex::Regex; use serde_derive::{Deserialize, Serialize}; use std::borrow::Cow; use std::collections::hash_map::*; use std::fs::File; use std::io::{Read, Write}; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use s...
use crate::events::events::{EventProvider, Result}; use chrono::prelude::*; use gtk::prelude::*; use regex::Regex; use serde_derive::{Deserialize, Serialize}; use std::borrow::Cow; use std::collections::hash_map::*; use std::fs::File; use std::io::{Read, Write}; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use s...
pub fn sanitize_for_filename(str: &str) -> Cow<str> { let re = Regex::new(r"[^A-Za-z0-9]").unwrap(); re.replace_all(str, "_") } pub fn get_cached_contents( event_provider: &dyn EventProvider, config_name: &str, date: &DateTime<Local>, ) -> Result<Opti...
ame: &str) -> Result<PathBuf> { let config_folder = Self::config_folder()?; Ok(config_folder.join(format!( "{}_{}.cache", event_provider.name(), Self::sanitize_for_filename(config_name) ))) }
function_block-function_prefixed
[ { "content": "pub fn get_all_events(config: Config, day: Date<Local>) -> Result<Vec<Event>> {\n\n let start = Instant::now();\n\n let eps = get_event_providers();\n\n let configs_to_fetch: Vec<(&Box<dyn EventProvider>, &String)> = eps\n\n .iter()\n\n .flat_map(|ep| {\n\n ep.get...
Rust
src/foreign_key/create.rs
samsamai/sea-query
744a8a859fda2b05b471e88500036ef3b8d92798
use crate::{ backend::SchemaBuilder, prepare::*, types::*, ForeignKeyAction, SchemaStatementBuilder, TableForeignKey, }; #[derive(Debug, Clone)] pub struct ForeignKeyCreateStatement { pub(crate) foreign_key: TableForeignKey, } impl Default for ForeignKeyCreateStatement { fn default() -> Self { ...
use crate::{ backend::SchemaBuilder, prepare::*, types::*, ForeignKeyAction, SchemaStatementBuilder, TableForeignKey, }; #[derive(Debug, Clone)] pub struct ForeignKeyCreateStatement { pub(crate) foreign_key: TableForeignKey, } impl Default for ForeignKeyCreateStatement { fn default() -> Self { ...
] and [`ForeignKeyCreateStatement::to`]" )] pub fn col<T: 'static, R: 'static>(mut self, column: T, ref_column: R) -> Self where T: Iden, R: Iden, { self.foreign_key.from_col(column); self.foreign_key.to_col(ref_column); self } pub fn from<T, C>(mut ...
T: Iden, R: Iden, { self.foreign_key.from_tbl(table); self.foreign_key.to_tbl(ref_table); self } #[deprecated( since = "0.10.2", note = "Please use the [`ForeignKeyCreateStatement::from`
random
[ { "content": "/// Escape a SQL string literal\n\npub fn escape_string(string: &str) -> String {\n\n string\n\n .replace(\"\\\\\", \"\\\\\\\\\")\n\n .replace(\"\\\"\", \"\\\\\\\"\")\n\n .replace(\"'\", \"\\\\'\")\n\n .replace(\"\\0\", \"\\\\0\")\n\n .replace(\"\\x08\", \"\\\...
Rust
flowc/src/lib/model/process.rs
andrewdavidmackenzie/flow
484de720caa19684f0d96e9cbc925254ed4168e3
use serde_derive::{Deserialize, Serialize}; use crate::model::flow::Flow; use crate::model::function::Function; use crate::model::name::{HasName, Name}; use crate::model::route::{HasRoute, Route}; #[derive(Serialize, Deserialize, Debug, Clone)] #[allow(clippy::large_enum_variant)] #[serde(untagged)] pub enum Process ...
use serde_derive::{Deserialize, Serialize}; use crate::model::flow::Flow; use crate::model::function::Function; use crate::model::name::{HasName, Name}; use crate::model::route::{HasRoute, Route}; #[derive(Serialize, Deserialize, Debug, Clone)] #[allow(clippy::large_enum_variant)] #[serde(untagged)] pub enum Process ...
} fn route_mut(&mut self) -> &mut Route { match self { Process::FlowProcess(ref mut flow) => flow.route_mut(), Process::FunctionProcess(ref mut function) => function.route_mut(), } } } #[cfg(test)] mod test { use url::Url; use flowcore::deserializers::dese...
match self { Process::FlowProcess(ref flow) => flow.route(), Process::FunctionProcess(ref function) => function.route(), }
if_condition
[ { "content": "pub fn route_or_route_array<'de, D>(deserializer: D) -> Result<Vec<Route>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n struct StringOrVec(PhantomData<Vec<Route>>);\n\n\n\n impl<'de> de::Visitor<'de> for StringOrVec {\n\n type Value = Vec<Route>;\n\n\n\n fn expectin...
Rust
src/jsonrpc.rs
silvanshade/tower-lsp
4da888ddf92969ff7ba200d20c1080dd83cf0c07
pub use self::error::{Error, ErrorCode}; pub use self::router::{FromParams, IntoResponse, Method}; pub(crate) use self::router::Router; use std::borrow::Cow; use std::fmt::{self, Debug, Display, Formatter}; use lsp_types::NumberOrString; use serde::de::{self, Deserializer}; use serde::ser::Serializer; use serde::{...
pub use self::error::{Error, ErrorCode}; pub use self::router::{FromParams, IntoResponse, Method}; pub(crate) use self::router::Router; use std::borrow::Cow; use std::fmt::{self, Debug, Display, Formatter}; use lsp_types::NumberOrString; use serde::de::{self, Deserializer}; use serde::ser::Serializer; use serde::{...
} impl From<i64> for Id { fn from(n: i64) -> Self { Id::Number(n) } } impl From<&'_ str> for Id { fn from(s: &'_ str) -> Self { Id::String(s.to_string()) } } impl From<String> for Id { fn from(s: String) -> Self { Id::String(s) } } impl From<NumberOrString> for Id { ...
fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Id::Number(id) => Display::fmt(id, f), Id::String(id) => Debug::fmt(id, f), Id::Null => f.write_str("null"), } }
function_block-full_function
[]
Rust
packages/yew-macro/src/hook/mod.rs
WorldSEnder/yew
b580bd4c2f6ec948e7a7fd92a34eb983ea8d0924
use proc_macro2::{Span, TokenStream}; use proc_macro_error::emit_error; use quote::quote; use syn::parse::{Parse, ParseStream}; use syn::{ parse_file, parse_quote, visit_mut, Attribute, Ident, ItemFn, LitStr, ReturnType, Signature, }; mod body; mod lifetime; mod signature; pub use body::BodyRewriter; use signatur...
use proc_macro2::{Span, TokenStream}; use proc_macro_error::emit_error; use quote::quote; use syn::parse::{Parse, ParseStream}; use syn::{ parse_file, parse_quote, visit_mut, Attribute, Ident, ItemFn, LitStr, ReturnType, Signature, }; mod body; mod lifetime; mod signature; pub use body::BodyRewriter; use signatur...
original_fn; let mut block = *block.clone(); let hook_sig = HookSignature::rewrite(sig); let Signature { ref fn_token, ref ident, ref inputs, output: ref hook_return_type, ref generics, .. } = hook_sig.sig; let output_type = &hook_sig.output_type; ...
function_block-function_prefix_line
[ { "content": "/// This hook is used to manually force a function component to re-render.\n\n///\n\n/// Try to use more specialized hooks, such as [`use_state`] and [`use_reducer`].\n\n/// This hook should only be used when your component depends on external state where you\n\n/// can't subscribe to changes, or ...
Rust
crates/cargo-platform/src/lib.rs
moxian/cargo
6e1ca924a67dd1ac89c33f294ef26b5c43b89168
use std::fmt; use std::str::FromStr; mod cfg; mod error; pub use cfg::{Cfg, CfgExpr}; pub use error::{ParseError, ParseErrorKind}; #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Clone, Debug)] pub enum Platform { Name(String), Cfg(CfgExpr), } impl Platform { pub fn matches(&se...
use std::fmt; use std::str::FromStr; mod cfg; mod error; pub use cfg::{Cfg, CfgExpr}; pub use error::{ParseError, ParseErrorKind}; #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Clone, Debug)] pub enum Platform { Name(String), Cfg(CfgExpr), } impl Platform { pub fn matches(&se...
; } Ok(()) } pub fn check_cfg_attributes(&self, warnings: &mut Vec<String>) { fn check_cfg_expr(expr: &CfgExpr, warnings: &mut Vec<String>) { match *expr { CfgExpr::Not(ref e) => check_cfg_expr(e, warnings), CfgExpr::All(ref e) | CfgExpr::Any(...
Err(ParseError::new( name, ParseErrorKind::InvalidTarget(format!( "unexpected character {} in target name", ch )), ))
call_expression
[ { "content": "/// Check the base requirements for a package name.\n\n///\n\n/// This can be used for other things than package names, to enforce some\n\n/// level of sanity. Note that package names have other restrictions\n\n/// elsewhere. `cargo new` has a few restrictions, such as checking for\n\n/// reserved...
Rust
linkerd/proxy/transport/src/tls/accept.rs
olix0r/linkerd2-proxy
2e6357ff040474b5e3e2a19d671c8fcdb4e8daa6
use super::{conditional_accept, Conditional, PeerIdentity, ReasonForNoPeerName}; use crate::io::{BoxedIo, PrefixedIo}; use crate::listen::Addrs; use bytes::BytesMut; use futures::prelude::*; use linkerd2_dns_name as dns; use linkerd2_error::Error; use linkerd2_identity as identity; use linkerd2_stack::{layer, NewServic...
use super::{conditional_accept, Conditional, PeerIdentity, ReasonForNoPeerName}; use crate::io::{BoxedIo, PrefixedIo}; use crate::listen::Addrs; use bytes::BytesMut; use futures::prelude::*; use linkerd2_dns_name as dns; use linkerd2_error::Error; use linkerd2_identity as identity; use linkerd2_stack::{layer, NewServic...
handshake(tls_config.clone(), PrefixedIo::new(buf.freeze(), tcp)).await?; return Ok((peer_id, BoxedIo::new(tls))); } conditional_accept::Match::NotMatched => break, conditional_accept::Match::Incomplete => { if buf.capacity() == 0 { ...
()); } }; let meta = Meta { peer_identity, addrs, }; new_accept .new_service(meta) .oneshot(io) ...
random
[ { "content": "pub fn is_loop(err: &(dyn std::error::Error + 'static)) -> bool {\n\n err.is::<LoopPrevented>() || err.source().map(is_loop).unwrap_or(false)\n\n}\n\n\n\nimpl std::fmt::Display for LoopPrevented {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(\n\n...
Rust
testing/jormungandr-integration-tests/src/jormungandr/mempool/fragments_dump.rs
rmourey26/jormungandr
e5d13409b931a58aee3ea72a5729a99f068b6043
use crate::common::jormungandr::{starter::Role, Starter}; use crate::common::{jormungandr::ConfigurationBuilder, startup}; use assert_fs::fixture::PathChild; use assert_fs::TempDir; use chain_impl_mockchain::chaintypes::ConsensusVersion; use jormungandr_lib::interfaces::InitialUTxO; use jormungandr_lib::interfaces::Per...
use crate::common::jormungandr::{starter::Role, Starter}; use crate::common::{jormungandr::ConfigurationBuilder, startup}; use assert_fs::fixture::PathChild; use assert_fs::TempDir; use chain_impl_mockchain::chaintypes::ConsensusVersion; use jormungandr_lib::interfaces::InitialUTxO; use jormungandr_lib::interfaces::Per...
#[test] pub fn fragment_which_is_not_in_fragment_log_should_be_persisted() { let temp_dir = TempDir::new().unwrap(); let dump_folder = temp_dir.child("dump_folder"); let persistent_log_path = temp_dir.child("persistent_log"); let receiver = startup::create_new_account_address(); let mut sender = s...
path_buf(), }), }), ) .unwrap(); let adversary_sender = AdversaryFragmentSender::new( jormungandr.genesis_block_hash(), jormungandr.fees(), AdversaryFragmentSenderSetup::dump_into(dump_folder.path().to_path_buf(), false), ); adversary_sender ...
function_block-function_prefixed
[ { "content": "pub fn read_persistent_fragment_logs_from_file_path(\n\n entries: impl Iterator<Item = PathBuf>,\n\n) -> io::Result<impl Iterator<Item = Result<PersistentFragmentLog, DeserializeError>>> {\n\n let mut handles = Vec::new();\n\n for entry in entries {\n\n handles.push(FileFragments::...
Rust
src/memtable.rs
g302ge/leveldb-rs
ab3a17a51819f04fcef1b88f00a1c581bb2e6898
use crate::cmp::{Cmp, MemtableKeyCmp}; use crate::key_types::{build_memtable_key, parse_internal_key, parse_memtable_key, ValueType}; use crate::key_types::{LookupKey, UserKey}; use crate::skipmap::{SkipMap, SkipMapIter}; use crate::types::{current_key_val, LdbIterator, SequenceNumber}; use std::rc::Rc; use integer_e...
use crate::cmp::{Cmp, MemtableKeyCmp}; use crate::key_types::{build_memtable_key, parse_internal_key, parse_memtable_key, ValueType}; use crate::key_types::{LookupKey, UserKey}; use crate::skipmap::{SkipMap, SkipMapIter}; use crate::types::{current_key_val, LdbIterator, SequenceNumber}; use std::rc::Rc; use integer_e...
&key[valoff..valoff + vallen], vec![4, 5, 6].as_slice()); } #[test] fn test_memtable_iterator_behavior() { let mut mt = MemTable::new(options::for_test().cmp); let entries = vec![ (115, "abc", "122"), (120, "abd", "123"), (121, "abe", "124"), ...
} #[test] fn test_memtable_iterator_init() { let mt = get_memtable(); let mut iter = mt.iter(); assert!(!iter.valid()); iter.next(); assert!(iter.valid()); assert_eq!( current_key_val(&iter).unwrap().0, vec![97, 98, 99, 1, 120, 0, 0, 0, ...
random
[ { "content": "fn gen_key_val<R: Rng>(gen: &mut R, keylen: usize, vallen: usize) -> (Vec<u8>, Vec<u8>) {\n\n let mut key = Vec::with_capacity(keylen);\n\n let mut val = Vec::with_capacity(vallen);\n\n\n\n for _i in 0..keylen {\n\n key.push(gen.gen_range(b'a', b'z'));\n\n }\n\n for _i in 0.....
Rust
sulis_view/src/item_list_pane.rs
ThyWoof/sulis
e89eda94a1a72228224e1926d307aa4c9228bdcb
use std::any::Any; use std::cell::{Cell, RefCell}; use std::rc::Rc; use sulis_core::ui::{Callback, Widget, WidgetKind}; use sulis_core::widgets::{Button, ScrollDirection, ScrollPane}; use sulis_module::{Item, ItemState, Module}; use sulis_state::{script::ScriptItemKind, EntityState, GameState}; use crate::{item_cal...
use std::any::Any; use std::cell::{Cell, RefCell}; use std::rc::Rc; use sulis_core::ui::{Callback, Widget, WidgetKind}; use sulis_core::widgets::{Button, ScrollDirection, ScrollPane}; use sulis_module::{Item, ItemState, Module}; use sulis_state::{script::ScriptItemKind, EntityState, GameState}; use crate::{item_cal...
} use self::Filter::*; const FILTERS_LIST: [Filter; 5] = [All, Weapon, Armor, Accessory, Usable]; pub struct ItemListPane { entity: Rc<RefCell<EntityState>>, kind: Kind, cur_filter: Rc<Cell<Filter>>, } impl ItemListPane { fn new( entity: &Rc<RefCell<EntityState>>, kind: Kind, ...
fn is_allowed(self, item: &Rc<Item>) -> bool { use self::Filter::*; match self { All => true, Weapon => item.is_weapon(), Armor => item.is_armor(), Accessory => { if item.is_weapon() || item.is_armor() { return false; ...
function_block-full_function
[]
Rust
d13/src/lib.rs
arturhoo/aoc2021
6aaed6d1207be757588ae41e25e6f3ce2ece9061
use std::cmp::max; use std::collections::HashSet; pub mod util; pub fn p1(input: &Vec<String>) -> usize { let (points, folds, edge) = parse_input(input); let (new_points, _new_edge) = perform_fold(points, &folds[0], edge); new_points.len() } pub fn p2(input: &Vec<String>) -> usize { let (mut points, f...
use std::cmp::max; use std::collections::HashSet; pub mod util; pub fn p1(input: &Vec<String>) -> usize { let (points, folds, edge) = parse_input(input); let (new_points, _new_edge) = perform_fold(points, &folds[0], edge); new_points.len() } pub fn p2(input: &Vec<String>) -> usize { let (mut points, f...
fn perform_fold(points: HashSet<Point>, fold: &Fold, edge: Point) -> (HashSet<Point>, Point) { let mut new_points: HashSet<Point> = HashSet::new(); let new_edge; match fold.direction { Direction::Vertical => { for point in points { if point.x > fold.coord { ...
r> = line.split(",").collect(); let point = Point { x: coords[0].parse().unwrap(), y: coords[1].parse().unwrap(), }; max_x = max(max_x, point.x); max_y = max(max_y, point.y); points.insert(point); ...
function_block-function_prefixed
[ { "content": "fn build_lines(input: &Vec<String>) -> (Vec<Line>, usize, usize) {\n\n let (mut max_x, mut max_y) = (0usize, 0usize);\n\n let mut lines: Vec<Line> = vec![];\n\n\n\n for input_line in input {\n\n let coords: Vec<&str> = input_line.split(\"->\").map(|token| token.trim()).collect();\n...
Rust
all-is-cubes-desktop/src/aic_glfw.rs
kpreid/all-is-cubes
81e0fb8fbd5a0557f0f9002085f4160bce37174a
use cgmath::{Point2, Vector2}; use glfw::{Action, Context as _, CursorMode, Window, WindowEvent}; use luminance_glfw::GlfwSurface; use luminance_windowing::{WindowDim, WindowOpt}; use std::error::Error; use std::time::Instant; use all_is_cubes::apps::AllIsCubesAppState; use all_is_cubes::camera::Viewport; use all_is...
use cgmath::{Point2, Vector2}; use glfw::{Action, Context as _, CursorMode, Window, WindowEvent}; use luminance_glfw::GlfwSurface; use luminance_windowing::{WindowDim, WindowOpt}; use std::error::Error; use std::time::Instant; use all_is_cubes::apps::AllIsCubesAppState; use all_is_cubes::camera::Viewport; use all_is...
.get_framebuffer_size()).map(|s| s as u32), } } pub fn map_glfw_button(button: glfw::MouseButton) -> usize { use glfw::MouseButton::*; match button { Button1 => 0, Button2 => 1, Button3 => 2, Button4 => 3, Button5 => 4, Button6 => 5, Button7 => 6, ...
) -> Viewport { Viewport { nominal_size: Vector2::from(window.get_size()).map(|s| s.into()), framebuffer_size: Vector2::from(window
function_block-random_span
[]
Rust
src/async_read.rs
Marwes/rust-partial-io
a308f83766909b5868f15e04928f08cbb8d96902
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::cmp; use std::fmt; use std::io::{self, Read, Write}; use futures::{task, Poll}; use tokio_io::{AsyncRead, AsyncWrite}; u...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::cmp; use std::fmt; use std::io::{self, Read, Write}; use futures::{task, Poll}; use tokio_io::{AsyncRead, AsyncWrite}; u...
s::assert_send; #[test] fn test_sendable() { assert_send::<PartialAsyncRead<File>>(); } }
lush(&mut self) -> io::Result<()> { self.inner.flush() } } impl<R> AsyncWrite for PartialAsyncRead<R> where R: AsyncRead + AsyncWrite, { #[inline] fn shutdown(&mut self) -> Poll<(), io::Error> { self.inner.shutdown() } } impl<R> fmt::Debug for PartialAsyncRead<R> where R: fmt::...
random
[ { "content": "#[inline]\n\nfn make_ops<I>(iter: I) -> Box<dyn Iterator<Item = PartialOp> + Send>\n\nwhere\n\n I: IntoIterator<Item = PartialOp> + 'static,\n\n I::IntoIter: Send,\n\n{\n\n Box::new(iter.into_iter().fuse())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n pub fn assert_send<S: Send>() {}\n\...
Rust
fyrox-ui/src/popup.rs
jackos/Fyrox
4b293733bda8e1a0a774aaf82554ac8930afdd8b
use crate::{ border::BorderBuilder, core::{algebra::Vector2, math::Rect, pool::Handle}, define_constructor, message::{ButtonState, MessageDirection, OsEvent, UiMessage}, widget::{Widget, WidgetBuilder, WidgetMessage}, BuildContext, Control, NodeHandleMapping, RestrictionEntry, Thickness, UiNode,...
use crate::{ border::BorderBuilder, core::{algebra::Vector2, math::Rect, pool::Handle}, define_constructor, message::{ButtonState, MessageDirection, OsEvent, UiMessage}, widget::{Widget, WidgetBuilder, WidgetMessage}, BuildContext, Control, NodeHandleMapping, RestrictionEntry, Thickness, UiNode,...
ui.send_message(WidgetMessage::desired_position( self.handle(), MessageDirection::ToWidget, position, )); if self.smart_placement { ...
let position = match self.placement { Placement::LeftTop(target) => self.left_top_placement(ui, target), Placement::RightTop(target) => self.right_top_placement(ui, target), Placement::Center(target) => self.center_placement...
assignment_statement
[ { "content": "pub fn send_sync_message(ui: &UserInterface, mut msg: UiMessage) {\n\n msg.flags = MSG_SYNC_FLAG;\n\n ui.send_message(msg);\n\n}\n\n\n", "file_path": "editor/src/main.rs", "rank": 0, "score": 447076.9232536799 }, { "content": "/// Trait for all UI controls in library.\n\n...
Rust
noodles-bam/src/async/reader/query.rs
jamestwebber/noodles
4af97d57885821edf53c82a45e3fa81a38481b59
use std::ops::{Bound, RangeBounds}; use futures::{stream, Stream}; use noodles_bgzf as bgzf; use noodles_csi::index::reference_sequence::bin::Chunk; use tokio::io::{self, AsyncRead, AsyncSeek}; use super::Reader; use crate::Record; enum State { Seek, Read(bgzf::VirtualPosition), Done, } struct Context<'...
use std::ops::{Bound, RangeBounds}; use futures::{stream, Stream}; use noodles_bgzf as bgzf; use noodles_csi::index::reference_sequence::bin::Chunk; use tokio::io::{self, AsyncRead, AsyncSeek}; use super::Reader; use crate::Record; enum State { Seek, Read(bgzf::VirtualPosition), Done, } struct Context<'...
Box::pin(stream::unfold(ctx, |mut ctx| async { loop { match ctx.state { State::Seek => { ctx.state = match next_chunk(&ctx.chunks, &mut ctx.i) { Some(chunk) => { if let Err(e) = ctx.reader.seek(chunk.start(...
let ctx = Context { reader, chunks, i: 0, reference_sequence_id, start, end, state: State::Seek, };
assignment_statement
[ { "content": "pub fn read_itf8<R>(reader: &mut R) -> io::Result<i32>\n\nwhere\n\n R: Read,\n\n{\n\n let b0 = read_u8_as_i32(reader)?;\n\n\n\n let value = if b0 & 0x80 == 0 {\n\n b0\n\n } else if b0 & 0x40 == 0 {\n\n let b1 = read_u8_as_i32(reader)?;\n\n (b0 & 0x7f) << 8 | b1\n\n...
Rust
src/spawn/options.rs
storyai/rust-heph
aa6ccf79de85c0abccb6a26f920c7d9d405e80cf
use std::cmp::Ordering; use std::num::NonZeroU8; use std::ops::Mul; use std::time::Duration; #[derive(Clone, Debug)] pub struct ActorOptions { priority: Priority, ready: bool, } impl ActorOptions { pub const fn priority(&self) -> Priority { self.priority } pub const fn with_pr...
use std::cmp::Ordering; use std::num::NonZeroU8; use std::ops::Mul; use std::time::Duration; #[derive(Clone, Debug)] pub struct ActorOptions { priority: Priority, ready: bool, } impl ActorOptions { pub const fn priority(&self) -> Priority { self.priority } pub const fn with_pr...
-> Priority { Priority::NORMAL } } impl Ord for Priority { fn cmp(&self, other: &Self) -> Ordering { other.0.cmp(&self.0) } } impl PartialOrd for Priority { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { other.0.partial_cmp(&self.0) } fn lt(&self, other: &S...
ty::default(), ready: true, } } } #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[repr(transparent)] pub struct Priority(NonZeroU8); impl Priority { pub const LOW: Priority = Priority(NonZeroU8::new(15).unwrap()); pub const NORMAL: Priority = Priority...
random
[ { "content": "#[track_caller]\n\npub fn is_ready<E>(poll: Poll<Result<(), E>>) -> bool\n\nwhere\n\n E: fmt::Display,\n\n{\n\n match poll {\n\n Poll::Ready(Ok(())) => true,\n\n Poll::Ready(Err(err)) => panic!(\"unexpected error: {}\", err),\n\n Poll::Pending => false,\n\n }\n\n}\n\n...
Rust
perf/sawtooth_perf/src/batch_map.rs
sTyL3/sawtooth-core
bcd260ee836e58e85f39d57c39d28dcb9a6d7a0e
/* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agre...
/* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agre...
} #[cfg(test)] mod tests { use super::BatchMap; use rand::Rng; use rand::StdRng; use protobuf::RepeatedField; use sawtooth_sdk::signing; use sawtooth_sdk::messages::batch::Batch; use sawtooth_sdk::messages::batch::BatchList; #[test] fn test_2_cycles_of_retries() { let m...
pub fn add(&mut self, batchlist: BatchList) { batchlist .batches .last() .map(|b| b.header_signature.clone()) .map(|batch_id| { if !self.batches_by_id.contains_key(batch_id.as_str()) { self.batches_by_id.insert(batch_id, batchli...
function_block-full_function
[ { "content": "/// Create the request from the next Target Url and the batchlist.\n\npub fn form_request_from_batchlist(\n\n targets: &mut Cycle<IntoIter<String>>,\n\n batch_list: Result<BatchList, WorkloadError>,\n\n basic_auth: &Option<String>,\n\n) -> Result<(Request, Option<String>), WorkloadError> ...
Rust
actix-web/src/test/test_request.rs
niklasha/actix-web
2f13e5f67579238761aba34e35786026ce4c805c
use std::{borrow::Cow, net::SocketAddr, rc::Rc}; use actix_http::{test::TestRequest as HttpTestRequest, Request}; use serde::Serialize; use crate::{ app_service::AppInitServiceState, config::AppConfig, data::Data, dev::{Extensions, Path, Payload, ResourceDef, Service, Url}, http::header::ContentTy...
use std::{borrow::Cow, net::SocketAddr, rc::Rc}; use actix_http::{test::TestRequest as HttpTestRequest, Request}; use serde::Serialize; use crate::{ app_service::AppInitServiceState, config::AppConfig, data::Data, dev::{Extensions, Path, Payload, ResourceDef, Service, Url}, http::header::ContentTy...
pub fn to_request(mut self) -> Request { let mut req = self.finish(); req.head_mut().peer_addr = self.peer_addr; req } pub fn to_srv_request(mut self) -> ServiceRequest { let (mut head, payload) = self.finish().into_parts(); head.peer_addr = self.peer_add...
fn finish(&mut self) -> Request { #[allow(unused_mut)] let mut req = self.req.finish(); #[cfg(feature = "cookies")] { use actix_http::header::{HeaderValue, COOKIE}; let cookie: String = self .cookies .delta() ...
function_block-full_function
[ { "content": "#[allow(non_snake_case)]\n\npub fn Header(name: &'static str, value: &'static str) -> impl Guard {\n\n HeaderGuard(\n\n header::HeaderName::try_from(name).unwrap(),\n\n header::HeaderValue::from_static(value),\n\n )\n\n}\n\n\n", "file_path": "actix-web/src/guard.rs", "r...
Rust
src/low/v7400/fbx_footer.rs
lo48576/fbxcel
542389fb81582d03def7322dc866b971c0ff1c58
use byteorder::{ByteOrder, LittleEndian}; use log::debug; use crate::{ low::FbxVersion, pull_parser::{ error::DataError, v7400::{FromParser, Parser}, Error as ParserError, ParserSource, SyntacticPosition, Warning, }, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struc...
use byteorder::{ByteOrder, LittleEndian}; use log::debug; use crate::{ low::FbxVersion, pull_parser::{ error::DataError, v7400::{FromParser, Parser}, Error as ParserError, ParserSource, SyntacticPosition, Warning, }, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struc...
}
0, ]; let mut buf = [0u8; 16]; parser.reader().read_exact(&mut buf)?; for (byte, expected) in buf.iter().zip(&EXPECTED) { if (byte & 0xf0) != *expected { let pos = SyntacticPosition { byte_pos: parser.reader().p...
function_block-function_prefixed
[ { "content": "/// Loads a tree from the given reader.\n\n///\n\n/// This works for seekable readers (which implement [`std::io::Seek`]), but\n\n/// [`from_seekable_reader`] should be used for them, because it is more\n\n/// efficent.\n\npub fn from_reader<R: Read>(mut reader: R) -> Result<AnyParser<PlainSource<...
Rust
cargo-wharf-frontend/src/config/builder.rs
RoeeJ/cargo-wharf
48ab920be2e396be534ec12238fa0ca79da6316f
use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use failure::{format_err, Error, ResultExt}; use log::*; use serde::Serialize; use buildkit_frontend::oci; use buildkit_frontend::Bridge; use buildkit_llb::ops::source::ImageSource; use buildkit_llb::prelude::*; use super::base::{BaseBuilderConfig, Cust...
use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use failure::{format_err, Error, ResultExt}; use log::*; use serde::Serialize; use buildkit_frontend::oci; use buildkit_frontend::Bridge; use buildkit_llb::ops::source::ImageSource; use buildkit_llb::prelude::*; use super::base::{BaseBuilderConfig, Cust...
fn image_source(&self) -> Option<&ImageSource> { Some(&self.source) } } fn guess_cargo_home(user: Option<&str>) -> Option<String> { match user { Some("root") => Some("/root/.cargo".into()), Some(user) => Some(format!("/home/{}/.cargo", user)), None => None, } } impl F...
fn populate_env<'a>(&self, mut command: Command<'a>) -> Command<'a> { command = command.env("CARGO_TARGET_DIR", TARGET_PATH); if let Some(user) = self.user() { command = command.user(user); } for (name, value) in self.env() { command = command.env(name, value); ...
function_block-full_function
[]
Rust
examples/reshaping.rs
Clomance/CatEngine
6f14694b6e7f493216b3dc4f01f9458385d55b07
use cat_engine::{ app::{ App, AppAttributes, Window, WindowInner, WindowEvent, WindowProcedure, VirtualKeyCode, quit, }, graphics::{ BlendingFunction, PrimitiveType, TexturedVertex2D, ShapeObject, }, text...
use cat_engine::{ app::{ App, AppAttributes, Window, WindowInner, WindowEvent, WindowProcedure, VirtualKeyCode, quit, }, graphics::{ BlendingFunction, PrimitiveType, TexturedVertex2D, ShapeObject, }, text...
core().blending.set_function( BlendingFunction::SourceAlpha, BlendingFunction::OneMinusSourceAlpha ); let vertices=[ TexturedVertex2D::new( [400f32,0f32], [1f32,1f32], [1.0,0.5,0.5,0.0] ), TexturedVertex2D::new([400f32,400f32],...
WindowHandle; impl WindowProcedure<WindowInner<Option<Texture>>> for WindowHandle{ fn render(window:&Window,window_inner:&mut WindowInner<Option<Texture>>){ window_inner.context().make_current(true).unwrap_or_else(|_|{quit()}); let [width,height]=window.client_size(); unsafe{ wi...
random
[ { "content": "struct WindowStorage{\n\n free_ids:Vec<usize>,\n\n windows:Vec<Option<Window>>,\n\n window_graphics:Vec<Option<WindowGraphics>>,\n\n}\n\n\n\nimpl WindowStorage{\n\n pub fn empty(capacity:usize)->WindowStorage{\n\n let mut free_ids=Vec::with_capacity(capacity);\n\n let mut...
Rust
src/der.rs
str4d/x509-rs
8b0b485254182465c2e089c4766fa85bbe34957f
enum DerType { Explicit(u8), Boolean, Integer, BitString, OctetString, Null, Oid, Utf8String, Sequence, Set, UtcTime, GeneralizedTime, } impl DerType { pub(super) fn parts(&self) -> (u8, u8, u8) { match self { DerType::Explicit...
enum DerType { Explicit(u8), Boolean, Integer, BitString, OctetString, Null, Oid, Utf8String, Sequence, Set, UtcTime, GeneralizedTime, } impl DerType { pub(super) fn parts(&self) -> (u8, u8, u8) { match self { DerType::Explicit...
(), &[0x30] ); } #[test] fn der_lengths() { assert_eq!(gen_simple(der_length(1), vec![]).unwrap(), &[1]); assert_eq!(gen_simple(der_length(127), vec![]).unwrap(), &[127]); assert_eq!( gen_simple(der_length(128), vec...
fn der_integer<'a, W: Write + 'a>(mut num: &'a [u8]) -> impl SerializeFn<W> + 'a { while !num.is_empty() && num[0] == 0 { num = &num[1..]; } der_tlv( DerType::Integer, pair( cond(num.is_empty() || num[0] >= 0x80, sli...
random
[ { "content": "/// A trait for objects which represent ASN.1 `AlgorithmIdentifier`s.\n\npub trait AlgorithmIdentifier {\n\n type AlgorithmOid: der::Oid;\n\n\n\n /// Returns the object identifier for this `AlgorithmIdentifier`.\n\n fn algorithm(&self) -> Self::AlgorithmOid;\n\n\n\n /// Writes the para...
Rust
sdk/src/commitment_config.rs
ZhengYuTay/solana
446c7a53f0d9c9bcd5027de8440363823b1dc1de
#![allow(deprecated)] #![cfg(feature = "full")] use std::str::FromStr; use thiserror::Error; #[derive(Serialize, Deserialize, Default, Clone, Copy, Debug, PartialEq, Eq, Hash)] #[serde(rename_all = "camelCase")] pub struct CommitmentConfig { pub commitment: CommitmentLevel, } impl CommitmentConfig { #[deprec...
#![allow(deprecated)] #![cfg(feature = "full")] use std::str::FromStr; use thiserror::Error; #[derive(Serialize, Deserialize, Default, Clone, Copy, Debug, PartialEq, Eq, Hash)] #[serde(rename_all = "camelCase")] pub struct CommitmentConfig { pub commitment: CommitmentLevel, } impl CommitmentConfig { #[deprec...
} } impl FromStr for CommitmentConfig { type Err = ParseCommitmentLevelError; fn from_str(s: &str) -> Result<Self, Self::Err> { CommitmentLevel::from_str(s).map(|commitment| Self { commitment }) } } #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)] #[serde(rename_all...
match commitment.commitment { CommitmentLevel::Finalized => CommitmentConfig::max(), CommitmentLevel::Confirmed => CommitmentConfig::single_gossip(), CommitmentLevel::Processed => CommitmentConfig::recent(), _ => commitment, }
if_condition
[ { "content": "/// calculate maximum possible prioritization fee, if `use-randomized-compute-unit-price` is\n\n/// enabled, round to nearest lamports.\n\npub fn max_lamports_for_prioritization(use_randomized_compute_unit_price: bool) -> u64 {\n\n if use_randomized_compute_unit_price {\n\n const MICRO_L...
Rust
src/process.rs
zyc801208/rexpect
13d91fff7196ed0bdccf5a03f369cd04153ea0c9
use crate::errors::*; use nix; use nix::fcntl::{open, OFlag}; use nix::libc::{STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO}; use nix::pty::{grantpt, posix_openpt, unlockpt, PtyMaster}; pub use nix::sys::{signal, wait}; use nix::sys::{stat, termios}; use nix::unistd::{dup, dup2, fork, setsid, ForkResult, Pid}; use std; ...
use crate::errors::*; use nix; use nix::fcntl::{open, OFlag}; use nix::libc::{STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO}; use nix::pty::{grantpt, posix_openpt, unlockpt, PtyMaster}; pub use nix::sys::{signal, wait}; use nix::sys::{stat, termios}; use nix::unistd::{dup, dup2, fork, setsid, ForkResult, Pid}; use std; ...
} impl Drop for PtyProcess { fn drop(&mut self) { match self.status() { Some(wait::WaitStatus::StillAlive) => { self.exit().expect("cannot exit"); } _ => {} } } } #[cfg(test)] mod tests { use super::*; use nix::sys::{signal, wait}; ...
pub fn kill(&mut self, sig: signal::Signal) -> Result<wait::WaitStatus> { let start = time::Instant::now(); loop { match signal::kill(self.child_pid, sig) { Ok(_) => {} Err(nix::Error::Sys(nix::errno::Errno::ESRCH)) => { re...
function_block-full_function
[ { "content": "/// See `spawn`\n\npub fn spawn_command(command: Command, timeout_ms: Option<u64>) -> Result<PtySession> {\n\n let commandname = format!(\"{:?}\", &command);\n\n let mut process = PtyProcess::new(command).chain_err(|| \"couldn't start process\")?;\n\n process.set_kill_timeout(timeout_ms);...
Rust
src/lib.rs
ostwilkens/bevy_networking_turbulence
99bd744389ec9cfff5b9027bc8e29b40fa6cc957
use bevy::{ app::{AppBuilder, Events, Plugin}, ecs::prelude::*, tasks::{IoTaskPool, TaskPool}, }; #[cfg(not(target_arch = "wasm32"))] use crossbeam_channel::{unbounded, Receiver, Sender}; #[cfg(not(target_arch = "wasm32"))] use std::sync::RwLock; use std::{ collections::HashMap, error::Error, f...
use bevy::{ app::{AppBuilder, Events, Plugin}, ecs::prelude::*, tasks::{IoTaskPool, TaskPool}, }; #[cfg(not(target_arch = "wasm32"))] use crossbeam_channel::{unbounded, Receiver, Sender}; #[cfg(not(target_arch = "wasm32"))] use std::sync::RwLock; use std::{ collections::HashMap, error::Error, f...
pub fn broadcast_message<M: ChannelMessage + Debug + Clone>(&mut self, message: M) { for (handle, connection) in self.connections.iter_mut() { let channels = connection.channels().unwrap(); let result = channels.send(message.clone()); channels.flush::<M>(); ...
mut self, handle: ConnectionHandle, message: M, ) -> Result<Option<M>, Box<dyn Error + Send>> { match self.connections.get_mut(&handle) { Some(connection) => { let channels = connection.channels().unwrap(); let unsent = channels.send(message); ...
function_block-function_prefix_line
[ { "content": "pub trait Connection: Send + Sync {\n\n fn remote_address(&self) -> Option<SocketAddr>;\n\n\n\n fn send(&mut self, payload: Packet) -> Result<(), Box<dyn Error + Send>>;\n\n\n\n fn receive(&mut self) -> Option<Result<Packet, Box<dyn Error + Send>>>;\n\n\n\n fn build_channels(\n\n ...
Rust
share/elf.rs
RichVillage/SnowFlake
be1c1ce4742de732528382e010b9044542944b10
#![allow(dead_code)] #![allow(non_camel_case_types)] pub type Elf64_Half = u16; pub type Elf64_Addr = u64; pub type Elf64_Off = u64; pub type Elf64_Sword = i32; pub type Elf64_Word = u32; #[repr(C)] #[derive(Copy, Clone, Default)] pub struct ElfHeader { pub e_ident: [u8; 16], pub e_object_type: Elf64_Half, pub e_...
#![allow(dead_code)] #![allow(non_camel_case_types)] pub type Elf64_Half = u16; pub type Elf64_Addr = u64; pub type Elf64_Off = u64; pub type Elf64_Sword = i32; pub type Elf64_Word = u32; #[repr(C)] #[derive(Copy, Clone, Default)] pub struct ElfHeader { pub e_ident: [u8; 16], pub e_object_type: Elf64_Half, pub e_...
} pub fn elf_get_size(file_base: &ElfFile) -> u32 { println!("elf_get_size(file_base={:p})", file_base); file_base.check_header(); let mut max_end = 0; for phent in file_base.phents() { if phent.p_type == 1 { println!("- {:#x}+{:#x} loads +{:#x}+{:#x}", phent.p_paddr, phent.p_memsz, phent.p_offse...
fn next(&mut self) -> Option<ShEnt> { if self.0.len() == 0 { None } else { let rv = self.0[0].clone(); self.0 = &self.0[1..]; Some(rv) } }
function_block-full_function
[ { "content": "pub fn nstr(wstring: *const u16) -> String {\n\n let mut string = String::new();\n\n\n\n let mut i = 0;\n\n loop {\n\n let w = unsafe { *wstring.offset(i) };\n\n i += 1;\n\n if w == 0 {\n\n break;\n\n }\n\n let c = unsafe { char::from_u32_unch...
Rust
src/color.rs
shuhei/colortty
dbb51e29a1f49c9f97174d869a97e63ed9fc0db4
use crate::error::{ErrorKind, Result}; use failure::ResultExt; use regex::Regex; use xml::{Element, Xml}; pub enum ColorSchemeFormat { ITerm, Mintty, Gogh, } impl ColorSchemeFormat { pub fn from_string(s: &str) -> Option<Self> { match s { "iterm" => Some(ColorSchemeFormat::ITerm), ...
use crate::error::{ErrorKind, Result}; use failure::ResultExt; use regex::Regex; use xml::{Element, Xml}; pub enum ColorSchemeFormat { ITerm, Mintty, Gogh, } impl ColorSchemeFormat { pub fn from_string(s: &str) -> Option<Self> { match s { "iterm" => Some(ColorSchemeFormat::ITerm), ...
t_white = color, _ => return Err(ErrorKind::UnknownColorName(name.to_owned()).into()), } } Ok(scheme) } pub fn from_iterm(content: &str) -> Result<Self> { let mut scheme = ColorScheme::default(); let root = content.parse::<Element>().context(Err...
=> scheme.magenta = color, "Cyan" => scheme.cyan = color, "White" => scheme.white = color, "BoldRed" => scheme.bright_red = color, "BoldBlack" => scheme.bright_black = color, "BoldGreen" => scheme.bright_green = color, "Bol...
random
[ { "content": "fn convert(args: Vec<String>) -> Result<()> {\n\n let mut opts = Options::new();\n\n opts.optopt(\n\n \"i\",\n\n \"input-format\",\n\n \"input format: 'iterm'|'mintty'|'gogh'\",\n\n \"INPUT_FORMAT\",\n\n );\n\n let matches = opts.parse(&args[2..]).context(Er...
Rust
experimental/benchmark/src/application/native.rs
DavidKorczynski/oak
fa53908358dd9e9b37f21e4aca17fb41485f5f33
use crate::{ application::ApplicationClient, database::Database, proto::{ trusted_database_client::TrustedDatabaseClient, trusted_database_server::{TrustedDatabase, TrustedDatabaseServer}, GetPointOfInterestRequest, GetPointOfInterestResponse, ListPointsOfInterestRequest, L...
use crate::{ application::ApplicationClient, database::Database, proto::{ trusted_database_client::TrustedDatabaseClient, trusted_database_server::{TrustedDatabase, TrustedDatabaseServer}, GetPointOfInterestRequest, GetPointOfInterestResponse, ListPointsOfInterestRequest, L...
} None => { let err = tonic::Status::new(tonic::Code::NotFound, "ID not found"); warn!("{:?}", err); Err(err) } } } async fn list_points_of_interest( &self, _request: Request<ListPointsOfInterestRequest...
Ok(Response::new(GetPointOfInterestResponse { point_of_interest: Some(point.clone()), }))
call_expression
[ { "content": "/// Return an iterator of all known Cargo Manifest files that define crates.\n\npub fn crate_manifest_files() -> impl Iterator<Item = PathBuf> {\n\n source_files()\n\n .filter(|p| is_cargo_toml_file(p))\n\n .filter(|p| is_cargo_package_file(p))\n\n}\n\n\n", "file_path": "runne...
Rust
types/src/proof/proptest_proof.rs
PragmaTwice/diem
a290b0859a6152a5ffd6f85773a875f17334adac
use crate::proof::{ definition::MAX_ACCUMULATOR_PROOF_DEPTH, AccumulatorConsistencyProof, AccumulatorProof, AccumulatorRangeProof, SparseMerkleLeafNode, SparseMerkleProof, SparseMerkleRangeProof, TransactionAccumulatorSummary, }; use diem_crypto::{ hash::{ CryptoHash, CryptoHasher, ACCUMULATOR...
use crate::proof::{ definition::MAX_ACCUMULATOR_PROOF_DEPTH, AccumulatorConsistencyProof, AccumulatorProof, AccumulatorRangeProof, SparseMerkleLeafNode, SparseMerkleProof, SparseMerkleRangeProof, TransactionAccumulatorSummary, }; use diem_crypto::{ hash::{ CryptoHash, CryptoHasher, ACCUMULATOR...
}) .prop_map(AccumulatorProof::<H>::new) .boxed() } } impl<V> Arbitrary for SparseMerkleProof<V> where V: std::fmt::Debug + CryptoHash, { type Parameters = (); type Strategy = BoxedStrategy<Self>; fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { ...
if len == 0 { Just(vec![]).boxed() } else { ( vec(arb_accumulator_sibling(), len - 1), arb_non_placeholder_accumulator_sibling(), ) .prop_map(|(mut siblings, last_sibling)|...
if_condition
[ { "content": "fn value_strategy<V: Arbitrary + Clone + 'static>(\n\n keep_rate: f64,\n\n) -> impl Strategy<Value = Option<V>> {\n\n let value_strategy = any::<V>();\n\n proptest::option::weighted(keep_rate, value_strategy)\n\n}\n\n\n\nimpl<V: Arbitrary + Debug + Clone> TransactionGen<V> {\n\n pub fn...
Rust
src/query/insert.rs
rex-remind101/sea-query
67a8ffba1351c754aae2559051930d4fe2fe70ae
use crate::{ backend::QueryBuilder, error::*, prepare::*, types::*, value::*, Expr, Query, QueryStatementBuilder, SelectExpr, SelectStatement, SimpleExpr, }; #[derive(Debug, Default, Clone)] pub struct InsertStatement { pub(crate) table: Option<Box<TableRef>>, pub(crate) columns: Vec<DynIden>, pub(...
use crate::{ backend::QueryBuilder, error::*, prepare::*, types::*, value::*, Expr, Query, QueryStatementBuilder, SelectExpr, SelectStatement, SimpleExpr, }; #[derive(Debug, Default, Clone)] pub struct InsertStatement { pub(crate) table: Option<Box<TableRef>>, pub(crate) columns: Vec<DynIden>, pub(...
} impl QueryStatementBuilder for InsertStatement { fn build_collect<T: QueryBuilder>( &self, query_builder: T, collector: &mu...
pub fn returning_col<C>(&mut self, col: C) -> &mut Self where C: IntoIden, { self.returning(Query::select().column(col.into_iden()).take()) }
function_block-full_function
[ { "content": "pub trait IntoTableRef {\n\n fn into_table_ref(self) -> TableRef;\n\n}\n\n\n\n/// Unary operator\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n\npub enum UnOper {\n\n Not,\n\n}\n\n\n\n/// Binary operator\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n\npub enum BinOper {\n\n And,\n\n...
Rust
07-rust/stm32f446/stm32f446_pac/src/otg_hs_device/otg_hs_dctl.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register OTG_HS_DCTL"] pub type R = crate::R<u32, super::OTG_HS_DCTL>; #[doc = "Writer for register OTG_HS_DCTL"] pub type W = crate::W<u32, super::OTG_HS_DCTL>; #[doc = "Register OTG_HS_DCTL `reset()`'s with value 0"] impl crate::ResetValue for super::OTG_HS_DCTL { type Type = u32; #[inline(...
#[doc = "Reader of register OTG_HS_DCTL"] pub type R = crate::R<u32, super::OTG_HS_DCTL>; #[doc = "Writer for register OTG_HS_DCTL"] pub type W = crate::W<u32, super::OTG_HS_DCTL>; #[doc = "Register OTG_HS_DCTL `reset()`'s with value 0"] impl crate::ResetValue for super::OTG_HS_DCTL { type Type = u32; #[inline(...
} #[doc = "Bit 3 - Global OUT NAK status"] #[inline(always)] pub fn gonsts(&self) -> GONSTS_R { GONSTS_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bits 4:6 - Test control"] #[inline(always)] pub fn tctl(&self) -> TCTL_R { TCTL_R::new(((self.bits >> 4) & 0x07) as u8) ...
t(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 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Write proxy for field `SGONAK`"] pub struct SGONAK_W<'a> { w: &'a mu...
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
src/frac.rs
Kate-Painter/BunnyFrac
e7ff387054dc9348adc5b70cb8a0cb94f0979997
use crate::color::*; use std::{process::exit, u8}; use std::fs::create_dir; use std::process::Command; use substring::Substring; pub struct Details { pub frac_type: String, pub imgx: u32, pub imgy: u32, pub scalex: f64, pub scaley: f64, pub centerx: f64, pub centery: f64, pub imax: u32,...
use crate::color::*; use std::{process::exit, u8}; use std::fs::create_dir; use std::process::Command; use substring::Substring; pub struct Details { pub frac_type: String, pub imgx: u32, pub imgy: u32, pub scalex: f64, pub scaley: f64, pub centerx: f64, pub centery: f64, pub imax: u32,...
/** * Finds out whether a provided C value is part of the julia set and returns the escape time as a u32. */ pub fn julia_iter(fractal: &Details, zx: f64, zy: f64) -> u32 { let c = num_complex::Complex::new(-0.8, 0.156); let mut z = num_complex::Complex::new(zx, zy); let mut i: u32 = 0; w...
let mut i: u32 = 0; while i < fractal.imax && z.norm() <= 2.0 { z = z * z + c; i += 1; } return i; }
function_block-function_prefix_line
[]
Rust
demos/in-game/src/ui/components/app.rs
zicklag/raui
bdabe92953c80ea52e67ffd9f8006807d79eb292
use crate::ui::components::{ inventory::inventory, item_cell::{ItemCellProps, ItemCellsProps}, minimap::minimap, new_theme, popup::{popup, PopupProps}, }; use raui_core::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppProps { #[serd...
use crate::ui::components::{ inventory::inventory, item_cell::{ItemCellProps, ItemCellsProps}, minimap::minimap, new_theme, popup::{popup, PopupProps}, }; use raui_core::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppProps { #[serd...
let WidgetContext { id, key, props, state, .. } = context; let shared_props = Props::new(AppSharedProps(id.to_owned())).with(new_theme()); let minimap_props = ContentBoxItemLayout { anchors: Rect { left: 1.0, right: 1.0, to...
function_block-function_prefix_line
[ { "content": "#[pre_hooks(use_nav_text_input)]\n\npub fn use_text_input(context: &mut WidgetContext) {\n\n fn notify<T>(context: &WidgetMountOrChangeContext, data: T)\n\n where\n\n T: 'static + MessageData,\n\n {\n\n if let Ok(notify) = context.props.read::<TextInputNotifyProps>() {\n\n ...