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
runtime/Rust/src/parser_rule_context.rs
3c1u/antlr4
61961d03310dcfcad3ba29a83a11a57942c2fe62
use std::any::{Any, type_name, TypeId}; use std::borrow::{Borrow, BorrowMut}; use std::cell::{Ref, RefCell}; use std::fmt::{Debug, Error, Formatter}; use std::ops::{Deref, DerefMut}; use std::rc::Rc; use crate::common_token_factory::INVALID_TOKEN; use crate::errors::ANTLRError; use crate::interval_set::Interval; use c...
use std::any::{Any, type_name, TypeId}; use std::borrow::{Borrow, BorrowMut}; use std::cell::{Ref, RefCell}; use std::fmt::{Debug, Error, Formatter}; use std::ops::{Deref, DerefMut}; use std::rc::Rc; use crate::common_token_factory::INVALID_TOKEN; use crate::errors::ANTLRError; use crate::interval_set::Interval; use c...
} impl<Ctx: CustomRuleContext> BaseParserRuleContext<Ctx> { pub fn new_parser_ctx(parent_ctx: Option<ParserRuleContextType>, invoking_state: isize, ext: Ctx) -> Self { BaseParserRuleContext { base: BaseRuleContext::new_ctx(parent_ctx, invoking_state, ext), start: RefCell::new((**I...
default fn get_text(&self) -> String { let children = self.get_children(); if children.len() == 0 { return String::new(); } let mut result = String::new(); for child in children.iter() { result += &child.get_text() } result }
function_block-full_function
[ { "content": "pub fn get_node_text(t: &(impl Tree + ?Sized), rule_names: &[&str]) -> String {\n\n t.get_node_text(rule_names)\n\n}\n\n\n\n//pub fn get_children(t: impl Tree) -> Vec<Rc<dyn Tree>> { unimplemented!() }\n\n//\n\n//pub fn get_ancestors(t: impl Tree) -> Vec<Rc<dyn Tree>> { unimplemented!() }\n\n//...
Rust
src/bub/functions/rules.rs
kurotakazuki/Floaout
3f7643e4a5aeb3fdc9c57e7e23165d32a7ee82b4
use crate::bub::functions::BubFnsRules; use crate::bub::functions::{BubFnsVariable, BubFnsVariable::*}; use mpl::rules::{RightRule, Rules}; use mpl::symbols::U8SliceTerminal; type Rule<'a> = RightRule<U8SliceTerminal<'a>, BubFnsVariable>; impl<'a> Rules<U8SliceTerminal<'a>, BubFnsVariable> for BubFnsRules { fn g...
use crate::bub::functions::BubFnsRules; use crate::bub::functions::{BubFnsVariable, BubFnsVariable::*}; use mpl::rules::{RightRule, Rules}; use mpl::symbols::U8SliceTerminal; type Rule<'a> = RightRule<U8SliceTerminal<'a>, BubFnsVariable>; impl<'a> Rules<U8SliceTerminal<'a>, BubFnsVariable> for BubFnsRules {
}
fn get(&self, variable: &BubFnsVariable) -> Option<&Rule<'a>> { Some(match variable { BubFns => &Self::BubFns_RULE, ZeroOrMoreBubFns => &Self::ZeroOrMoreBubFns_RULE, SpaceAndBubFn => &Self::SpaceAndBubFn_RULE, BubFn => &Self::BubFn_RULE...
function_block-full_function
[ { "content": "use crate::BubFnsCoord;\n\nuse mpl::span::StartAndLenSpan;\n\nuse mpl::trees::AST;\n\n\n\npub use self::interpreter::BubFnsInterpreter;\n\npub use self::output::BubFnsOutput;\n\npub use self::parse::parse;\n\npub use self::parse::BubFnsRules;\n\npub use self::parse::BubFnsVariable;\n\n\n\nmod inte...
Rust
cep47/src/data.rs
nguyenminhhieu12041996/casper-nft-cep47
4b104d916b8a1ffe80c40d052228206426aab24b
use std::{collections::BTreeMap, convert::TryInto}; use casper_contract::{ contract_api::{ runtime, storage::{self, new_dictionary}, }, unwrap_or_revert::UnwrapOrRevert, }; use casper_types::{ bytesrepr::{FromBytes, ToBytes}, contracts::NamedKeys, ApiError, CLTyped, ContractPack...
use std::{collections::BTreeMap, convert::TryInto}; use casper_contract::{ contract_api::{ runtime, storage::{self, new_dictionary}, }, unwrap_or_revert::UnwrapOrRevert, }; use casper_types::{ bytesrepr::{FromBytes, ToBytes}, contracts::NamedKeys, ApiError, CLTyped, ContractPack...
Some(key) => { let key_ref = key.try_into().unwrap_or_revert(); storage::write(key_ref, value); } None => { let key = storage::new_uref(value).into(); runtime::put_key(name, key); } } }
function_block-function_prefix_line
[ { "content": "pub fn get_entrypoints(package_hash: Option<ContractPackageHash>) -> EntryPoints {\n\n let secure = if let Some(contract_package_hash) = package_hash {\n\n let deployer_group = storage::create_contract_user_group(\n\n contract_package_hash,\n\n \"deployer\",\n\n ...
Rust
wiz/wizc/src/high_level_ir/type_checker.rs
ChanTsune/wiz
199d0f4698822a177ede8015bf8e04f190f39934
mod error; use crate::high_level_ir::type_checker::error::CheckerError; use crate::high_level_ir::type_resolver::arena::ResolverArena; use crate::high_level_ir::type_resolver::context::StructKind; use wiz_hir::typed_decl::{ TypedDeclKind, TypedExtension, TypedFun, TypedFunBody, TypedProtocol, TypedStruct, TypedVar...
mod error; use crate::high_level_ir::type_checker::error::CheckerError; use crate::high_level_ir::type_resolver::arena::ResolverArena; use crate::high_level_ir::type_resolver::context::StructKind; use wiz_hir::typed_decl::{ TypedDeclKind, TypedExtension, TypedFun, TypedFunBody, TypedProtocol, TypedStruct, TypedVar...
fn assignment_statement(&mut self, typed_assignment: &TypedAssignmentStmt) { match typed_assignment { TypedAssignmentStmt::Assignment(a) => { if a.target.type_() != a.value.type_() { self.session.emit_error(CheckerError::new(format!( ...
TypedStmt::Assignment(a) => self.assignment_statement(a), TypedStmt::Loop(l) => self.loop_statement(l), } }
function_block-function_prefix_line
[ { "content": "/// Creates an iterator that produces tokens from the input string.\n\npub fn tokenize(mut input: &str) -> impl Iterator<Item = Token> + '_ {\n\n std::iter::from_fn(move || {\n\n if input.is_empty() {\n\n return None;\n\n }\n\n let token = first_token(input);\n\n...
Rust
src/function.rs
ifabrisarabellapark/rust101
ea93104e479edb6a090dd2a6a4b88f396d610945
#[allow(dead_code)] #[allow(unused_imports)] #[allow(unused_variables)] #[allow(unused_must_use)] fn printer(num:i32) { println!("{}", num); } fn double(int: &mut i32) { *int *= 2; println!("{}", int); } fn product(x:i32, y:i32) -> i32 { x*y } pub fn funk() { let i:i32 = -2817; printer(i); let mut j = ...
#[allow(dead_code)] #[allow(unused_imports)] #[allow(unused_variables)] #[allow(unused_must_use)] fn p
println!("{} + {} = {}", a, add, plus_add(a)); } let borrow_add = add; println!("{} = {}", borrow_add, add); let plusone = |mut x: i32| x += 1; let mut c = 100; plusone(c); println!("b = {}", c); let plusone = |x:&mut i32| *x += 1; let mut b = 10...
rinter(num:i32) { println!("{}", num); } fn double(int: &mut i32) { *int *= 2; println!("{}", int); } fn product(x:i32, y:i32) -> i32 { x*y } pub fn funk() { let i:i32 = -2817; printer(i); let mut j = 9; double(&mut j); let p = product(6, 7); println!("{}", p); } struct Point {x:f32, y:f32...
random
[ { "content": "// This program executes all that is contained in the main() function, so include your code inside the function pls!\n\nfn main()\n\n{\n\n //variables::variables();\n\n //variables::operators();\n\n //variables::scope_and_shadowing();\n\n //variables::constants();\n\n //variables::stack_and_h...
Rust
scheduler/src/job.rs
LightHero/lightspeed
d18a89e6eea654293b0560315e1316b56ffc6298
use crate::error::SchedulerError; use crate::scheduler::Scheduler; use chrono::{DateTime, Utc}; use chrono_tz::Tz; use futures_util::FutureExt; use log::*; use std::future::Future; use std::panic::AssertUnwindSafe; use std::pin::Pin; use tokio::sync::{Mutex, RwLock}; pub struct JobScheduler { pub job: Job, sch...
use crate::error::SchedulerError; use crate::scheduler::Scheduler; use chrono::{DateTime, Utc}; use chrono_tz::Tz; use futures_util::FutureExt; use log::*; use std::future::Future; use std::panic::AssertUnwindSafe; use std::pin::Pin; use tokio::sync::{Mutex, RwLock}; pub struct JobScheduler { pub job: Job, sch...
Box::pin(async move { println!("job - started"); println!("job - Trying to get the lock"); let mut lock = lock_clone.lock().await; let count = *lock; *lock = count + 1; println!("job - count {}", count); ...
ck = lock.lock().await; let count = *lock; assert_eq!(1, count); } #[tokio::test] async fn job_should_retry_run_if_error() { let lock = Arc::new(Mutex::new(0)); let lock_clone = lock.clone(); let max_retries = 12; let job = Job::new("g", "n", Some(max_retri...
random
[ { "content": "/// Configure a simple global logger that prints to stdout\n\npub fn setup_stdout_logger(logger_filter: &str, use_ansi: bool) -> Result<(), LoggerError> {\n\n let env_filter = Targets::from_str(logger_filter).map_err(|err| LoggerError::LoggerConfigurationError {\n\n message: format!(\"Ca...
Rust
src/config/policy.rs
Patryk27/lxd-snapper
9b096962122988abb3677a69ced244ea7cec2fa2
use lib_lxd::{LxdInstance, LxdInstanceName, LxdInstanceStatus, LxdProject, LxdProjectName}; use serde::Deserialize; use std::collections::HashSet; use std::hash::Hash; #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)] #[serde(deny_unknown_fields)] #[serde(rename_all = "kebab-case")] pub struct Policy { ...
use lib_lxd::{LxdInstance, LxdInstanceName, LxdInstanceStatus, LxdProject, LxdProjectName}; use serde::Deserialize; use std::collections::HashSet; use std::hash::Hash; #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)] #[serde(deny_unknown_fields)] #[serde(rename_all = "kebab-case")] pub struct Policy { ...
{ use super::*; #[test] fn applies_to_all_instances_except_the_ones_belonging_to_given_project() { let policy = Policy { excluded_projects: Some(projects(&["a", "d"])), ..Default::default() }; ...
ze>, pub keep_last: Option<usize>, pub keep_limit: Option<usize>, } impl Policy { pub fn keep_hourly(&self) -> usize { self.keep_hourly.unwrap_or(0) } pub fn keep_daily(&self) -> usize { self.keep_daily.unwrap_or(0) } pub fn keep_weekly(&self) -> usize { self.keep_...
random
[ { "content": "#[derive(Clap, Debug)]\n\nstruct DebugCommand {\n\n #[clap(subcommand)]\n\n cmd: DebugSubcommand,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 77587.35070074443 }, { "content": "#[derive(Clap, Debug)]\n\nstruct Args {\n\n /// Runs application in a simul...
Rust
src/parser.rs
tlverwijst/rustling-ontology
f0cb0c8b60b6f948dbc537d82c5f80077af286f2
use rustling; use rustling_ontology_values::dimension::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Hash, Clone, Eq, PartialEq, Serialize, Deserialize)] pub enum Feat { Rules(Vec<rustling::Sym>), Grains(Vec<usize>), } impl rustling::Feature for Feat {} pub struct FeatureExtractor(); impl rustling...
use rustling; use rustling_ontology_values::dimension::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Hash, Clone, Eq, PartialEq, Serialize, Deserialize)] pub enum Feat { Rules(Vec<rustling::Sym>), Grains(Vec<usize>), } impl rustling::Feature for Feat {} pub struct FeatureExtractor(); impl rustling...
#[cfg(test)] mod tests { use crate::{build_raw_parser, CandidateTagger, Lang, OutputKind}; use rustling::ParserMatch; use rustling::*; use rustling_ontology_values::dimension::*; use rustling_ontology_values::IdentityContext; #[test] fn test_twenty() { let parser = build_raw_parse...
e)) .collect::<Vec<_>>(); let rules_feat = node .children .iter() .map( |child| child.rule_sym ) .collect::<Vec<_>>(); let mut features = vec![Feat::Rules(rules_feat)]; if !grains_feat.is_empty() { features.push(Feat::Grains(grains_feat)); } let chil...
function_block-function_prefixed
[ { "content": "pub fn rule_set() -> ::rustling::RustlingResult<::rustling::RuleSet<rustling_ontology_values::Dimension>> {\n\n let mut b = ::rustling::RuleSetBuilder::new(\n\n ::rustling::BoundariesChecker::detailed(),\n\n ::rustling::BoundariesChecker::separated_alphanum...
Rust
interactive_engine/executor/runtime/src/dataflow/manager/context.rs
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
use maxgraph_store::api::prelude::*; use dataflow::message::subgraph::SubGraph; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::cell::RefCell; use std::rc::Rc; use store::store_delegate::StoreDelegate; use store::remote_store_service::RemoteStoreServiceManager; use store::global_store::Glo...
use maxgraph_store::api::prelude::*; use dataflow::message::subgraph::SubGraph; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::cell::RefCell; use std::rc::Rc; use store::store_delegate::StoreDelegate; use store::remote_store_service::RemoteStoreServiceManager; use store::global_store::Glo...
pub fn get_worker_index(&self) -> u32 { self.index } } pub struct BuilderContext { remote_store_service_manager: Arc<RemoteStoreServiceManager>, task_partition_manager: Arc<TaskPartitionManager>, lambda_service_client: Option<Arc<LambdaServiceClient>>, partition_manager: Arc<GraphPart...
ion(&self, label_id: Option<LabelId>, vid: VertexId, partition_vertex_list: &mut Vec<(PartitionId, Vec<(Option<LabelId>, Vec<VertexId>)>)>) { if let Some(partition_id) = self.get_partition_id(...
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn unary_chain<V, VI, E, EI>(graph: Arc<dyn MVGraph<V=V, VI=VI, E=E, EI=EI>>, partition_ids: Arc<Vec<PartitionId>>, base: &OperatorBase) -> impl Fn(FlowMessage) -> Vec<FlowMessage>\n\n where V: 'static + Vertex, VI: 'static + Iterator<Item=V>, E: 'static + Edge, EI: 'static + I...
Rust
src/httpd/parser.rs
lbrocke/stm32f7-httpd
5084030ac0137fb5412b0a815eef550f73eb762b
use alloc::{ borrow::ToOwned, collections::BTreeMap, string::{String, ToString}, }; use super::request::Request; pub struct HTTPParser { pub source: String, method: Option<String>, path: Option<String>, version: Option<String>, headers: BTreeMap<String, String>, } #[derive(Debug)] pub...
use alloc::{ borrow::ToOwned, collections::BTreeMap, string::{String, ToString}, }; use super::request::Request; pub struct HTTPParser { pub source: String, method: Option<String>, path: Option<String>, version: Option<String>, headers: BTreeMap<String, String>, } #[derive(Debug)] pub...
fn parse_header(&mut self) -> Result<(String, String), ParseError> { let mut maybe_key = None; let mut maybe_value = None; self.read_until(":") .map(|key| maybe_key = Some(key.to_lowercase())) .and_then(|_| self.expect(":")) .and_then(|_| self.read_unti...
fn parse_headers(&mut self) -> Result<(), ParseError> { loop { if self.source.starts_with("\r\n") { return Ok(()); } match self.parse_header() { Ok((key, value)) => { self.headers.insert(key, value); } ...
function_block-full_function
[ { "content": "fn match_path(pattern: &str, path: &str) -> Option<BTreeMap<String, String>> {\n\n let mut pattern_parts = pattern.split(\"/\");\n\n let mut path_parts = path.split(\"/\");\n\n\n\n let mut args = BTreeMap::new();\n\n\n\n loop {\n\n match (pattern_parts.next(), path_parts.next())...
Rust
src/quardle/mod.rs
LeoFVO/quark
6492cf95792fabb85b609c5636b5b242a91a4f08
use std::fs::{File, create_dir_all, remove_dir_all}; use serde::{Deserialize, Serialize}; use serde_json; use std::process::Command; use log::{info, warn}; const QUARK_BUILD_DIR: &str = "/tmp/quark/builds/"; const QUARK_CONFIG_DIR: &str = "/opt/quark/"; const QUARDLE_KERNEL: &str = "vmlinux.bin"; const QUARDLE_KERNEL...
use std::fs::{File, create_dir_all, remove_dir_all}; use serde::{Deserialize, Serialize}; use serde_json; use std::process::Command; use log::{info, warn}; const QUARK_BUILD_DIR: &str = "/tmp/quark/builds/"; const QUARK_CONFIG_DIR: &str = "/opt/quark/"; const QUARDLE_KERNEL: &str = "vmlinux.bin"; const QUARDLE_KERNEL...
uardle.as_ref().unwrap().container_image_url, "container3"); } #[test] fn quardle_add_initramfs() { let quardle = Quardle::new("test4".to_string(), "container4".to_string(), false); quardle.as_ref().unwrap().add_initramfs(); assert_eq!(quardle.as_ref().unwrap().name, "test4"); ...
:new("test3".to_string(), "container3".to_string(), false); quardle.as_ref().unwrap().add_kernel(); assert_eq!(quardle.as_ref().unwrap().name, "test3"); assert_eq!(q
function_block-random_span
[ { "content": "fn main() -> Result<()> {\n\n let cli: Cli = Cli::parse();\n\n\n\n cli.command().handler()?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 1, "score": 38179.442295264686 }, { "content": "pub trait Handler {\n\n fn handler(&self) -> Result<()>;\n\n}\n\n...
Rust
src/lib.rs
MrShiposha/abstrack
61f315645332a2daa2e73f2edbd8509edcff8cf2
mod buf; mod key; mod node; mod interpolator; mod search; #[cfg(test)] mod tests; use { std::{ ops::Index, marker::PhantomData }, buf::Buffer, search::search, }; pub use { key::{ TrackKey, TrackKeyDistance, }, node::TrackNode, interpolator::TrackInterpo...
mod buf; mod key; mod node; mod interpolator; mod search; #[cfg(test)] mod tests; use { std::{ ops::Index, marker::PhantomData }, buf::Buffer, search::search, }; pub use { key::{ TrackKey, TrackKeyDistance, }, node::TrackNode, interpolator::TrackInterpo...
fn force_push(&mut self, node: Node::<I>) -> Result<()> { debug_assert!(!self.ranges.is_empty()); if self.ranges.len() == 1 { self.buf.grow(); self.buf.try_push(node).unwrap(); Ok(()) } else { Err(Error::Overflow) } ...
fn try_push(&mut self, node: Node::<I>) -> Result<()> { if let Err(buf::Error::Overflow(node)) = self.buf.try_push(node) { self.force_push(node)?; } Ok(()) }
function_block-full_function
[ { "content": "type Node = node::TrackNode<Key, Data, DataNA>;\n\n\n\npub struct Interpolator;\n\n\n\nimpl TrackInterpolator for Interpolator {\n\n type Key = Key;\n\n type Data = Data;\n\n type NotAlignedData = DataNA;\n\n type Output = Output;\n\n \n\n fn interpolate(\n\n &mut self, \n...
Rust
src/section/g711_visualization/spectrogram.rs
jpeg-mpeg-visualizer/jpeg-mpeg-visualizer
c38eb21582ce62a03083e0efef313a49271b3aad
use std::cmp::Ordering; use rustfft::{algorithm::Radix4, num_complex::Complex, num_traits::Zero, Fft, FftDirection}; use seed::*; use wasm_bindgen::Clamped; use web_sys::{HtmlCanvasElement, ImageData}; pub struct Spectrogram { pub image_data: Vec<u8>, pub windows_num: usize, pub bins_num: usize, } impl S...
use std::cmp::Ordering; use rustfft::{algorithm::Radix4, num_complex::Complex, num_traits::Zero, Fft, FftDirection}; use seed::*; use wasm_bindgen::Clamped; use web_sys::{HtmlCanvasElement, ImageData}; pub struct Spectrogram { pub image_data: Vec<u8>, pub windows_num: usize, pub bins_num: usize, } impl S...
malized_bin.into()); image_data.extend(color.as_array()); image_data.push(255); } Spectrogram { image_data, windows_num, bins_num, } } pub fn draw_spectrogram(&self, canvas: HtmlCanvasElement) { let image_data = ImageD...
2 + 1; let windows = buffer.windows(WINDOW_SIZE).step_by(HOP_SIZE); let fft = Radix4::<f32>::new(WINDOW_SIZE, FftDirection::Forward); let mut result: Vec<Vec<f32>> = Vec::with_capacity(windows_num); let mut scratch = vec![Complex::zero(); fft.get_inplace_scratch_len()]; for ch...
random
[]
Rust
src/enc/compat.rs
Nemo157/rust-brotli
458f5780a37674c3bae38212e11166b22d3198b1
#![cfg_attr(feature="simd", allow(unused))] use core::ops::{Shr, Add, Sub, AddAssign, Mul, BitAnd}; #[derive(Default, Copy, Clone, Debug)] pub struct Compat16x16([i16;16]); impl Compat16x16 { #[inline(always)] pub fn splat(a: i16) -> Compat16x16 { Compat16x16([a, a, a, a, a, a, a, a, ...
#![cfg_attr(feature="simd", allow(unused))] use core::ops::{Shr, Add, Sub, AddAssign, Mul, BitAnd}; #[derive(Default, Copy, Clone, Debug)] pub struct Compat16x16([i16;16]); impl Compat16x16 { #[inline(always)] pub fn splat(a: i16) -> Compat16x16 { Compat16x16([a, a, a, a, a, a, a, a, ...
} macro_rules! op16 { ($a: expr, $b: expr, $op: expr) => ( Compat16x16::new($op($a[0], $b[0]), $op($a[1], $b[1]), $op($a[2], $b[2]), $op($a[3], $b[3]), $op($a[4], $b[4]), $op($a[5],...
pub fn gt(&self, rhs: Compat16x16) -> Compat16x16 { Self::new(-((self.extract(0) > rhs.extract(0)) as i16), -((self.extract(1) > rhs.extract(1)) as i16), -((self.extract(2) > rhs.extract(2)) as i16), -((self.extract(3) > rhs.extract(3)) as i16), ...
function_block-full_function
[ { "content": "pub fn ctzll(mut x : usize) -> usize {\n\n let mut count : u8 = 0i32 as (u8);\n\n while x & 0usize != 0 {\n\n count = (count as (i32) + 1i32) as (u8);\n\n x = x >> 1i32;\n\n }\n\n count as (usize)\n\n}\n\n\n\nstatic kInvalidMatch : u32 = 0xfffffffu32;\n\n\n\nstatic kCutof...
Rust
src/utils/prp/mod.rs
georgbramm/rust-se
8d38f5a0dec7274d916d26009f09d898bf23f1db
use rulinalg::matrix::Matrix; use rulinalg::matrix::PermutationMatrix; use rulinalg::matrix::BaseMatrix; use rulinalg::matrix::BaseMatrixMut; use crypto::*; use crypto::hmac::Hmac; use crypto::mac::Mac; use crypto::digest::Digest; use crypto::sha3::Sha3; use primitive_types::U256; use std::convert::TryInto; use mongodb...
use rulinalg::matrix::Matrix; use rulinalg::matrix::PermutationMatrix; use rulinalg::matrix::BaseMatrix; use rulinalg::matrix::BaseMatrixMut; use crypto::*; use crypto::hmac::Hmac; use crypto::mac::Mac; use crypto::digest::Digest; use crypto::sha3::Sha3; use primitive_types::U256; use std::convert::TryInto; use mongodb...
} #[cfg(test)] mod tests { use primitive_types::U256; use rulinalg::matrix::Matrix; use std::str::FromStr; use super::*; #[test] fn prp_works() { let key = U256::from_dec_str("12345678909876543210").ok().unwrap(); let vec: Vec<usize> = (0..20).collect(); let prf = PRP...
pub fn g(&self, _data: &Vec<usize>) -> Vec<usize> { let mut _x = self._key.clone(); let _n = _data.len(); let mut _y: Vec<usize> = (1.._n).collect(); for _i in 1usize.._n { let _t = (self._key % _i).as_usize(); _x = _x / _i; _y[_i - 1] = _i - 1; ...
function_block-full_function
[ { "content": "/// Decrypts a buffer with the given key and iv using AES-256/CBC/Pkcs encryption.\n\n///\n\n/// This function is very similar to encrypt(), so, please reference\n\n/// comments in that function. In non-example code, if desired, it is possible to\n\n/// share much of the implementation using closu...
Rust
csql2csv/src/main.rs
stpettersens/db-tools
710232a2a9245040c7126a79810930b120d8be77
/* csql2csv Utility to convert a SQL dump to a CSV file. Copyright 2016 Sam Saint-Pettersen. Licensed under the MIT/X11 License. Rust port of original Python tool (1.0.0). */ extern crate clioptions; extern crate regex; use clioptions::CliOptions; use regex::Regex; use std::io::{BufRead, BufReader, Write}; use std::...
/* csql2csv Utility to convert a SQL dump to a CSV file. Copyright 2016 Sam Saint-Pettersen. Licensed under the MIT/X11 License. Rust port of original Python tool (1.0.0). */ extern crate clioptions; extern crate regex; use clioptions::CliOptions; use regex::Regex; use std::io::{BufRead, BufReader, Write}; use std::...
fn check_extensions(program: &str, input: &str, output: &str) { let mut re = Regex::new(r".sql$").unwrap(); if !re.is_match(&input) { display_error(&program, &format!("Input file '{}' is not SQL", &input)); } re = Regex::new(r".csv$").unwrap(); if !re.is_match(&output) { display_er...
fn convert_sql_to_csv(input: &str, output: &str, separator: &str, tz: bool, verbose: bool) { let mut lines: Vec<String> = Vec::new(); let f = File::open(input).unwrap(); let file = BufReader::new(&f); for line in file.lines() { lines.push(line.unwrap()); } let processed = preprocess_sql...
function_block-full_function
[ { "content": "fn preprocess_sql(lines: Vec<String>) -> Vec<String> {\n\n let mut processed: Vec<String> = Vec::new();\n\n let patterns = vec![\n\n \"VALUES \\\\(\",\n\n \",\",\n\n \"\\\\),\",\n\n \"\\\\(\",\n\n \"\\n\\n\",\n\n ];\n\n\n\n let repls = vec![\n\n ...
Rust
bench-tps/src/main.rs
EwoutH/solana
883fc39c80a3ffe9e04e9d50ded8e88afe840adc
mod bench; mod cli; use solana::client::mk_client; use solana::cluster_info::{ClusterInfo, NodeInfo}; use solana::gossip_service::GossipService; use solana::gen_keys::GenKeys; use solana::service::Service; use solana::thin_client::poll_gossip_for_leader; use solana_metrics; use solana_sdk::signature::KeypairUtil; us...
mod bench; mod cli; use solana::client::mk_client; use solana::cluster_info::{ClusterInfo, NodeInfo}; use solana::gossip_service::GossipService; use solana::gen_keys::GenKeys; use solana::service::Service; use solana::thin_client::poll_gossip_for_leader; use solana_metrics; use solana_sdk::signature::KeypairUtil; us...
duration, tx_count, sustained, reject_extra_nodes, converge_only, } = cfg; println!("Looking for leader at {:?}", network); let leader = poll_gossip_for_leader(network, Some(30)).unwrap_or_else(|err| { println!( "Error: unable to find leader on n...
um_nodes ); } } } sleep(Duration::new(1, 0)); } let leader = spy_ref.read().unwrap().leader_data().cloned(); (v, leader, gossip_service) } fn main() { solana_logger::setup(); solana_metrics::set_panic_hook("bench-tps"); let matche...
random
[ { "content": "fn converge(leader: &NodeInfo, num_nodes: usize) -> Vec<NodeInfo> {\n\n // Let's spy on the network\n\n let (gossip_service, spy_ref, id) = make_spy_node(leader);\n\n trace!(\n\n \"converge spy_node {} looking for at least {} nodes\",\n\n id,\n\n num_nodes\n\n );\n...
Rust
imgui-gfx-examples/examples/support_gfx/mod.rs
aloucks/imgui-rs
b0e37f7a22f91a6c0851cd7e945fcd2367536b90
use gfx::Device; use glutin::{Event, WindowEvent}; use imgui::{Context, FontConfig, FontGlyphRanges, FontSource, Ui}; use imgui_gfx_renderer::{GfxRenderer, Shaders}; use imgui_winit_support::{HiDpiMode, WinitPlatform}; use std::time::Instant; type ColorFormat = gfx::format::Rgba8; type DepthFormat = gfx::format::Depth...
use gfx::Device; use glutin::{Event, WindowEvent}; use imgui::{Context, FontConfig, FontGlyphRanges, FontSource, Ui}; use imgui_gfx_renderer::{GfxRenderer, Shaders
..FontConfig::default() }), }, ]); imgui.io_mut().font_global_scale = (1.0 / hidpi_factor) as f32; let mut renderer = GfxRenderer::init(&mut imgui, &mut factory, shaders) .expect("Failed to initialize renderer"); let mut last_frame = Instant::now(); let mut...
}; use imgui_winit_support::{HiDpiMode, WinitPlatform}; use std::time::Instant; type ColorFormat = gfx::format::Rgba8; type DepthFormat = gfx::format::DepthStencil; #[cfg(feature = "opengl")] pub fn run<F: FnMut(&Ui) -> bool>(title: String, clear_color: [f32; 4], mut run_ui: F) { let mut events_loop = glutin::Eve...
random
[ { "content": "fn example_2(ui: &Ui) {\n\n ui.window(im_str!(\"Example 2: Alpha component\"))\n\n .size([700.0, 320.0], Condition::Appearing)\n\n .position([20.0, 140.0], Condition::Appearing)\n\n .build(|| {\n\n ui.text_wrapped(im_str!(\n\n \"The displayed color...
Rust
crypto-ws-client/src/clients/huobi.rs
CPT-Jack-A-Castle/crypto-crawler-rs
e7b8a2d51989e69779c69e3e7755351fe5fcb3bb
use crate::WSClient; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use log::*; use serde_json::Value; use tungstenite::Message; use super::ws_client_internal::{MiscMessage, WSClientInternal}; use super::{Candlestick, OrderBook, OrderBookSnapshot, Ticker, Trade, BBO}; pub(super) const EXCHANGE_NAME: &st...
use crate::WSClient; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use log::*; use serde_json::Value; use tungstenite::Message; use super::ws_client_internal::{MiscMessage, WSClientInternal}; use super::{Candlestick, OrderBook, OrderBookSnapshot, Ticker, Trade, BBO}; pub(super) const EXCHANGE_NAME: &st...
} else if let Some(op) = obj.get("op") { match op.as_str().unwrap() { "sub" | "unsub" => MiscMessage::Misc, "notify" => MiscMessage::Normal, _ => { warn!("Received {} from {}", msg, EXCHANGE_NAME); ...
match status.as_str().unwrap() { "ok" => info!("Received {} from {}", msg, EXCHANGE_NAME), "error" => { error!("Received {} from {}", msg, EXCHANGE_NAME); let err_msg = obj.get("err-msg").unwrap().as_str().unwrap(); ...
if_condition
[ { "content": "fn channel_to_command(channel: &str, subscribe: bool) -> String {\n\n if channel.starts_with('{') {\n\n return channel.to_string();\n\n }\n\n format!(\n\n r#\"{{\"event\":\"bts:{}\",\"data\":{{\"channel\":\"{}\"}}}}\"#,\n\n if subscribe {\n\n \"subscribe\"\...
Rust
src/core/model.rs
nyari/rtrace
2321a0a50c10940c58a690c678df8f939d5b22fc
use defs::{Matrix4, Vector3, FloatType}; use core::{Ray, RayIntersection}; use na::{Similarity3, Rotation3, Translation3, Unit}; pub trait Model: Send + Sync { fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection>; } pub struct ModelViewModelWrapper<T: Model> { wrapped_model: T, tf_matrix: Matr...
use defs::{Matrix4, Vector3, FloatType}; use core::{Ray, RayIntersection}; use na::{Similarity3, Rotation3, Translation3, Unit}; pub trait Model: Send + Sync { fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection>; } pub struct ModelViewModelWrapper<T: Model> { wrapped_model: T, tf_matrix: Matr...
let transformed_intersection = test_model.get_intersection(&intersector_ray).expect("There was no intersection returned when ModelMock always returns"); assert_relative_eq!(transformed_intersection.get_intersection_point(), &Point3::new(0.0, 1.0, 2.0)); assert_relative_eq!(transformed_intersectio...
nslate(Vector3::new(0.0, 0.0, 1.0)); let intersector_ray = Ray::new_single_shot(Point3::new(0.0, -5.0, 2.0), Vector3::new(0.0, 1.0, 0.0)); let transformed_intersection = test_model.get_intersection(&intersector_ray).expect("There was no intersection returned when ModelMock always returns"); as...
random
[ { "content": "pub trait RayCaster: Send + Sync {\n\n fn cast_ray(&self, ray: &Ray) -> Option<Color>;\n\n fn cast_colored_light_ray(&self, ray: &Ray, intersection: &RayIntersection) -> Option<Color>;\n\n fn cast_model_ray(&self, ray: &Ray) -> Option<RayIntersection>;\n\n}\n\n\n", "file_path": "src/c...
Rust
src/program.rs
attackgoat/screen-13
de1ce897fe96ed25078e32f7aa40e73f356e8185
#[rustfmt::skip] mod default_program_icon { include!(concat!(env!("OUT_DIR"), "/default_program_icon.rs")); } use { super::program_root, serde::{Deserialize, Serialize}, std::{ convert::{AsRef, TryFrom}, io::Error, path::PathBuf, }, winit::window::{BadIcon, Icon as Winit...
#[rustfmt::skip] mod default_program_icon { include!(concat!(env!("OUT_DIR"), "/default_program_icon.rs")); } use { super::program_root, serde::{Deserialize, Serialize}, std::{ convert::{AsRef, TryFrom}, io::Error, path::PathBuf, }, winit::window::{BadIcon, Icon as Winit...
} #[derive(Debug, Deserialize, Serialize)] pub struct Program<'a, 'b> { pub author: &'static str, pub fullscreen: bool, pub icon: Option<Icon<'b>>, pub name: &'static str, pub resizable: bool, pub title: &'a str, } impl Program<'static, '...
else { icon.pixels } .to_owned(); Self::from_rgba(pixels, icon.width, icon.height) }
function_block-function_prefix_line
[ { "content": "/// Reads raw pixel data from an image source file and returns them in the given format.\n\npub fn pixels<P: AsRef<Path>>(filename: P, fmt: BitmapFormat) -> (u32, Vec<u8>) {\n\n let image = match image_open(&filename).unwrap() {\n\n DynamicImage::ImageRgb8(image) => image.convert(),\n\n ...
Rust
src/identities/domain/password_resets.rs
Zeroed-Books/zeroed-books-api
56da67ad9333ad0de5603e7696cb769ff09bf96d
use std::fmt::Debug; use chrono::{DateTime, Duration, Utc}; use rand::{distributions::Alphanumeric, thread_rng, Rng}; use semval::prelude::*; use uuid::Uuid; use super::email::{Email, EmailInvalidity}; #[derive(Debug)] pub struct NewPasswordReset { email: Email, token: String, } const RESET_TOKEN_LENGTH: us...
use std::fmt::Debug; use chrono::{DateTime, Duration, Utc}; use rand::{distributions::Alphanumeric, thread_rng, Rng}; use semval::prelude::*; use uuid::Uuid; use super::email::{Email, EmailInvalidity}; #[derive(Debug)] pub struct NewPasswordReset { email: Email, token: String, } const RESET_TOKEN_LENGTH: us...
}
fn password_reset_token_validate_expired() { let reset = PasswordResetToken { user_id: Uuid::new_v4(), token: "expired-token".to_owned(), created_at: Utc::now() - Duration::seconds(60 * 60 + 1), }; let context = reset.validate().expe...
function_block-full_function
[ { "content": "pub fn routes() -> Vec<Route> {\n\n routes![\n\n create_password_reset,\n\n create_password_reset_request,\n\n create_user,\n\n verify_email\n\n ]\n\n}\n\n\n\n#[derive(Responder)]\n\npub enum ResetPasswordResponse {\n\n #[response(status = 200)]\n\n Ok(()),\...
Rust
core/src/env/call/instantiate.rs
OIEIEIO/ink
c9765ed8ca204585647ff11775490fd0537b137c
use core::marker::PhantomData; use crate::env::{ call::{ CallData, Selector, }, EnvTypes, Result, }; pub mod state { pub use crate::env::call::state::{ Sealed, Unsealed, }; pub enum CodeHashAssigned {} pub enum CodeHashUnassigned {...
use core::marker::PhantomData; use crate::env::{ call::{ CallData, Selector, }, EnvTypes, Result, }; pub mod state { pub use crate::env::call::state::{ Sealed, Unsealed, }; pub enum CodeHashAssigned {} pub enum CodeHashUnassigned {...
InstantiateBuilder<T, C, state::Sealed, CodeHash> { InstantiateBuilder { params: self.params, state: Default::default(), } } } impl<T, C, Seal> InstantiateBuilder<T, C, Seal, state::CodeHashAssigned> where T: EnvTypes, C: FromAccountId<T>, { pub fn instantia...
pub fn using_code( mut self, code_hash: T::Hash, ) -> InstantiateBuilder<T, C, Seal, state::CodeHashAssigned> { self.params.code_hash = code_hash; InstantiateBuilder { params: self.params, state: Default::default(), } } } impl<T, C, CodeHash...
random
[ { "content": "pub fn call(callee: &[u8], gas_limit: u64, value: &[u8], call_data: &[u8]) -> Result<()> {\n\n let ret_code = unsafe {\n\n sys::ext_call(\n\n callee.as_ptr() as u32,\n\n callee.len() as u32,\n\n gas_limit,\n\n value.as_ptr() as u32,\n\n ...
Rust
CodeGen/src/xsd/annotation.rs
Webern/MxOld
822f5ccc92363ddff118e3aa3a048c63be1e857e
#[macro_use] use crate::error::Result; use crate::xsd::constants::{ANNOTATION, APP_INFO, DOCUMENTATION, NAME}; use crate::xsd::id::{Id, Lineage, RootNodeType}; use crate::xsd::Xsd; use std::fmt::{Debug, Formatter}; #[derive(Clone, Debug)] pub struct Annotation { pub id: Id, pub items: Vec<Item>, } #[derive(Cl...
#[macro_use] use crate::error::Result; use crate::xsd::constants::{ANNOTATION, APP_INFO, DOCUMENTATION, NAME}; use crate::xsd::id::{Id, Lineage, RootNodeType}; use crate::xsd::Xsd; use std::fmt::{Debug, Formatter}; #[derive(Clone, Debug)] pub struct Annotation { pub id: Id, pub items: Vec<Item>, } #[derive(Cl...
pub fn from_xml(node: &exile::Element, lineage: Lineage, xsd: &Xsd) -> Result<Self> { check!(ANNOTATION, node, xsd)?; let (id, lineage) = Id::make(lineage, node)?; let mut items = Vec::new(); for inner in node.children() { let t = inner.name.as_str(); if let...
pub fn documentation(&self) -> String { for item in &self.items { if let Item::Documentation(s) = &item { return s.clone(); } } "".to_owned() }
function_block-full_function
[ { "content": "/// Returns a list of enums that I added the word 'Enum' to suffix the name. In some cases this was\n\n/// to prevent a name clash with a complex-type or element by the same name. In other cases this was\n\n/// because I wanted to 'wrap' the enum in a custom class (i.e. when the usage in MusicXML ...
Rust
src/eval/stg/wrap.rs
curvelogic/eucalypt-hs
13b8df25aa2621d257b3c882ad8cba653cf27596
use std::convert::TryInto; use crate::{ common::sourcemap::Smid, eval::{intrinsics, types::IntrinsicType}, }; use super::{ syntax::{ dsl::{ annotated_lambda, app_bif, data, force, let_, local, lref, unbox_num, unbox_str, unbox_sym, unbox_zdt, value, }, Lam...
use std::convert::TryInto; use crate::{ common::sourcemap::Smid, eval::{intrinsics, types::IntrinsicType}, }; use super::{ syntax::{ dsl::{ annotated_lambda, app_bif, data, force, let_, local, lref, unbox_num, unbox_str, unbox_sym, unbox_zdt, value, }, Lam...
yntax)); } Some(IntrinsicType::Symbol) => { syntax = unbox_sym(local(arg_offset + *i), force(local(0), syntax)); } Some(IntrinsicType::ZonedDateTime) => { syntax = unbox_zdt(local(arg_offset + *i), force(local(0), syntax)); } ...
nfo.arity(); if arity == 0 { return value(app_bif(index.try_into().unwrap(), vec![])); } let return_type = info.ty().ret(arity - 1); let mut offset = 0; let mut offsets = vec![0]; for i in info.strict_args() { match info.ty().arg(*i) { ...
random
[ { "content": "/// Construct a property declaration at a specified source location\n\npub fn fn_at(\n\n span: Span,\n\n meta: Option<Expression>,\n\n name: Name,\n\n args: ArgTuple,\n\n body: Expression,\n\n) -> Declaration {\n\n Declaration::FunctionDeclaration(span, meta, name, args, body)\n\...
Rust
crates/shadowsocks/src/relay/tcprelay/proxy_stream/server.rs
Mu-L/shadowsocks-rust
2a5f40b5f778160ddb33b656e84ca54c469382f7
use std::{ io, pin::Pin, task::{self, Poll}, }; #[cfg(feature = "aead-cipher-2022")] use bytes::BytesMut; use futures::ready; use pin_project::pin_project; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use crate::{ context::SharedContext, crypto::CipherKind, relay::{ socks5::Addre...
use std::{ io, pin::Pin, task::{self, Poll}, }; #[cfg(feature = "aead-cipher-2022")] use bytes::BytesMut; use futures::ready; use pin_project::pin_project; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use crate::{ context::SharedContext, crypto::CipherKind, relay::{ socks5::Addre...
} impl<S> AsyncWrite for ProxyServerStream<S> where S: AsyncRead + AsyncWrite + Unpin, { #[inline] fn poll_write(self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &[u8]) -> Poll<Result<usize, io::Error>> { #[allow(unused_mut)] let mut this = self.project(); #[allow(clippy::ne...
s_handshaked { return Err(io::Error::new(io::ErrorKind::Other, "stream is not handshaked yet")).into(); } let this = self.project(); ready!(this.stream.poll_read_decrypted(cx, this.context, buf))?; #[cfg(feature = "aead-cipher-2022")] if let ProxyServerStre...
function_block-function_prefixed
[ { "content": "fn decrypt_message(_context: &Context, method: CipherKind, key: &[u8], packet: &mut [u8]) -> bool {\n\n match method {\n\n CipherKind::AEAD2022_BLAKE3_CHACHA20_POLY1305 => {\n\n // ChaCha20-Poly1305 uses PSK as key, prepended nonce in packet\n\n let nonce_size = Cha...
Rust
all-is-cubes/src/math/matrix.rs
kpreid/all-is-cubes
81e0fb8fbd5a0557f0f9002085f4160bce37174a
use cgmath::{InnerSpace, Matrix4, One, Transform, Vector3, Vector4, Zero as _}; pub use ordered_float::{FloatIsNan, NotNan}; use std::cmp::Ordering; use std::convert::TryFrom as _; use std::ops::Mul; use crate::math::*; #[allow(clippy::exhaustive_structs)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub stru...
use cgmath::{InnerSpace, Matrix4, One, Transform, Vector3, Vector4, Zero as _}; pub use ordered_float::{FloatIsNan, NotNan}; use std::cmp::Ordering; use std::convert::TryFrom as _; use std::ops::Mul; use crate::math::*; #[allow(clippy::exhaustive_structs)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub stru...
} #[cfg(test)] mod tests { use super::*; use rand::{Rng, SeedableRng as _}; use rand_xoshiro::Xoshiro256Plus; fn random_grid_matrix(mut rng: impl Rng) -> GridMatrix { let mut r = || rng.gen_range(-100..=100); GridMatrix::new(r(), r(), r(), r(), r(), r(), r(), r(), r(), r(), r(), r()) ...
e; } if axis == 3 { #[allow(clippy::float_cmp)] if rounded != expected_w { return None; } } else { result[axis] = rounded as GridCoordinate; ...
function_block-function_prefixed
[]
Rust
orchestrator/test_runner/src/happy_path.rs
agoric-labs/peggy
012986df863f4a9a68118073aafa24bfa35b765b
use crate::{utils::*, COSMOS_NODE_GRPC, MINER_ADDRESS, MINER_PRIVATE_KEY, TOTAL_TIMEOUT}; use actix::Arbiter; use clarity::PrivateKey as EthPrivateKey; use clarity::{Address as EthAddress, Uint256}; use contact::client::Contact; use cosmos_peggy::send::send_valset_request; use cosmos_peggy::send::{send_request_batch, s...
use crate::{utils::*, COSMOS_NODE_GRPC, MINER_ADDRESS, MINER_PRIVATE_KEY, TOTAL_TIMEOUT}; use actix::Arbiter; use clarity::PrivateKey as EthPrivateKey; use clarity::{Address as EthAddress, Uint256}; use contact::client::Contact; use cosmos_peggy::send::send_valset_request; use cosmos_peggy::send::{send_request_batch, s...
} else { panic!("Duplicate test failed for unknown reasons!"); } }
if start_coin.amount == end_coin.amount && start_coin.denom == end_coin.denom { info!("Successfully failed to duplicate ERC20!"); } else { panic!("Duplicated ERC20!") }
if_condition
[ { "content": "/// takes the required input data and produces the required signature to confirm a transaction\n\n/// batch on the Peggy Ethereum contract. This value will then be signed before being\n\n/// submitted to Cosmos, verified, and then relayed to Ethereum\n\n/// Note: This is the message, you need to r...
Rust
darknet-config/src/config/common.rs
jerry73204/yolo-dl
35fde79c70d62fc70f045acc8fee7aa85555298b
use super::*; #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(try_from = "RawCommon")] pub struct Common { pub clip: Option<R64>, #[serde( rename = "onlyforward", with = "serde_::zero_one_bool", default = "defaults::bool_false" )] pub only_forward: b...
use super::*; #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(try_from = "RawCommon")] pub struct Common { pub clip: Option<R64>, #[serde( rename = "onlyforward", with = "serde_::zero_one_bool", default = "defaults::bool_false" )] pub only_forward: b...
ing_rate_scale: Option<String>, }
train_only_bn, dont_load, dont_load_scales, learning_rate_scale, } = from; let parse_r64 = |text: &str| -> Result<R64> { R64::try_new(f64::from_str(text)?) .ok_or_else(|| format_err!("'{}' is not a finite number", text)) ...
random
[ { "content": "pub fn interpolate(inter_x: R64, left: impl AsXY<R64, R64>, right: impl AsXY<R64, R64>) -> R64 {\n\n let ldiff = inter_x - left.x();\n\n let rdiff = right.x() - inter_x;\n\n let diff = right.x() - left.x();\n\n\n\n (rdiff * left.y() + ldiff * right.y()) / diff\n\n}\n\n\n", "file_pa...
Rust
src/location/loc.rs
NilsPur/dtn7-plus-rs
7dcb22e3b583dc02aae4207b090c81cfadda8159
use core::convert::TryFrom; use core::fmt; use derive_try_from_primitive::TryFromPrimitive; use serde::de::{SeqAccess, Visitor}; use serde::ser::{SerializeSeq, Serializer}; use serde::{de, Deserialize, Deserializer, Serialize}; #[derive(Debug, Clone, PartialEq, TryFromPrimitive)] #[repr(u8)] enum LocationType { La...
use core::convert::TryFrom; use core::fmt; use derive_try_from_primitive::TryFromPrimitive; use serde::de::{SeqAccess, Visitor}; use serde::ser::{SerializeSeq, Serializer}; use serde::{de, Deserialize, Deserializer, Serialize}; #[derive(Debug, Clone, PartialEq, TryFromPrimitive)] #[repr(u8)] enum LocationType { La...
} #[cfg(test)] mod tests { use crate::location::Location; #[test] fn test_loc_lonlat_roundtrip() { let loc = Location::LatLon((23.0, 42.0)); let buf = serde_cbor::to_vec(&loc).unwrap(); let loc2 = serde_cbor::from_slice(&buf).unwrap(); assert_eq!(loc, loc2); } #[te...
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct LocationVisitor; impl<'de> Visitor<'de> for LocationVisitor { type Value = Location; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { ...
function_block-full_function
[ { "content": "pub fn get_location_data(cblock: &CanonicalBlock) -> Result<LocationBlockData, LocationError> {\n\n if cblock.block_type == LOCATION_BLOCK {\n\n if let CanonicalData::Unknown(data) = cblock.data() {\n\n let loc_data =\n\n serde_cbor::from_slice(data).map_err(|_e...
Rust
src/geoip.rs
jasonish/evebox
ed61cb0cf947c744eb8e9671768ca6a35728508c
use crate::eve::eve::EveJson; use crate::prelude::*; use maxminddb::{geoip2, Reader}; use std::sync::Mutex; use std::time::{Duration, UNIX_EPOCH}; const DAYS_28: i64 = 86400 * 28; const UPDATE_CHECK_TIMEOUT: u64 = 60; struct Inner { reader: Reader<Vec<u8>>, last_modified: u64, last_update_check: std::ti...
use crate::eve::eve::EveJson; use crate::prelude::*; use maxminddb::{geoip2, Reader}; use std::sync::Mutex; use std::time::{Duration, UNIX_EPOCH}; const DAYS_28: i64 = 86400 * 28; const UPDATE_CHECK_TIMEOUT: u64 = 60; struct Inner { reader: Reader<Vec<u8>>, last_modified: u64, last_update_check: std::ti...
fn as_json(&self, city: geoip2::City) -> serde_json::Value { let mut obj = serde_json::json!({}); if let Some(city) = city.city { if let Some(names) = city.names { if let Some(name) = names.get("en") { obj["city_name"] = name.to_string().into(); ...
pub fn add_geoip_to_eve(&self, eve: &mut EveJson) { if let EveJson::String(addr) = &eve["dest_ip"] { if let Ok(city) = self.lookup_city_from_str(addr) { eve["geoip_destination"] = self.as_json(city); } } if let EveJson::String(addr) = &eve["src_ip"] { ...
function_block-full_function
[ { "content": "pub fn get_string(file_path: &str) -> Option<String> {\n\n if let Some(bytes) = get(file_path) {\n\n if let Ok(text) = std::str::from_utf8(&bytes) {\n\n return Some(text.to_string());\n\n }\n\n }\n\n None\n\n}\n", "file_path": "src/resource.rs", "rank": 0,...
Rust
src/mini-scheme/src/builtins.rs
MysteryJump/mini-scheme
63a4d0ca53f37dfed0de6e779025154114958b09
use std::fmt::Display; use uuid::Uuid; use crate::interpreter::{EResult, ExecutionResult, List}; #[derive(Debug, Clone, Copy)] pub enum NumOpKind { Add, Sub, Mul, Div, } impl Display for NumOpKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ...
use std::fmt::Display; use uuid::Uuid; use crate::interpreter::{EResult, ExecutionResult, List}; #[derive(Debug, Clone, Copy)] pub enum NumOpKind { Add, Sub, Mul, Div, } impl Display for NumOpKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ...
}); let first = iter.next().unwrap(); match op_kind { NumCompOpKind::Lt => iter.all(|next| (first < next)), NumCompOpKind::Lte => iter.all(|next| (first <= next)), NumCompOpKind::Gt => iter.all(|next| (first > next)), N...
if let ExecutionResult::Number(x) = x { x } else { panic!() }
if_condition
[ { "content": "fn execute_comp_operation(op_kind: EqCompKind, vals: &[ExecutionResult]) -> EResult {\n\n if vals.len() != 2 {\n\n Err((\"number of arguments needs `2`\").to_string())\n\n } else {\n\n let first = &vals[0];\n\n let second = &vals[1];\n\n match op_kind {\n\n ...
Rust
src/network/ws/server2.rs
wayfair-tremor/uring
483adf33d61a767a2de9a5ed4ed5cc272cc62ac2
use super::*; use async_std::net::TcpListener; use async_std::net::ToSocketAddrs; use async_std::task; use futures::channel::mpsc::{channel, Receiver, Sender}; use futures::io::{AsyncRead, AsyncWrite}; use futures::{select, FutureExt, StreamExt}; use protocol_driver::{ DriverInboundChannelSender, DriverInboundDat...
use super::*; use async_std::net::TcpListener; use async_std::net::ToSocketAddrs; use async_std::task; use futures::channel::mpsc::{channel, Receiver, Sender}; use futures::io::{AsyncRead, AsyncWrite}; use futures::{select, FutureExt, StreamExt}; use protocol_driver::{ DriverInboundChannelSender, DriverInboundDat...
async fn handle_ws_msg(&mut self, msg: Message) { dbg!(&msg); let data = msg.into_data(); let data = if let Ok(data) = serde_json::from_slice(&data) { data } else { DriverInboundData::Message(data) }; dbg!(&data); let msg = DriverInbou...
else { dbg!("snot"); break } } complete => { dbg!("done"); break } }; } }
function_block-function_prefix_line
[ { "content": "pub fn log(logger: &Logger) {\n\n info!(logger, \"uring version: {}\", VERSION);\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn for_coverage_only() {\n\n print();\n\n log(&slog::Logger::root(slog::Discard, o!()));\n\n }\n\n}\n", "fi...
Rust
tests/test_timer.rs
nooberfsh/tokio-timer
ab439926ed316c3bc3edd3811602a3058f8dfefa
extern crate futures; extern crate tokio_timer as timer; mod support; use futures::prelude::*; use futures::channel::{oneshot, mpsc}; use futures::executor::block_on; use timer::*; use std::io; use std::time::*; use std::thread; #[test] fn test_immediate_sleep() { let timer = Timer::default(); let mut t = t...
extern crate futures; extern crate tokio_timer as timer; mod support; use futures::prelude::*; use futures::channel::{oneshot, mpsc}; use futures::executor::block_on; use timer::*; use std::io; use std::time::*; use std::thread; #[test] fn test_immediate_sleep() { let timer = Timer::default(); let mut t = t...
x_timeout(Duration::from_millis(10_000)) .build(); let dur1 = Duration::from_millis(200); let dur2 = Duration::from_millis(1000); let to1 = timer.sleep(dur1); let to2 = timer.sleep(dur2); let e1 = support::time(|| block_on(to1).unwrap()); let e2 = support::time(|| block_on(to2).unwrap...
support::time(|| block_on(to1).unwrap()) }); let t2 = thread::spawn(move || { support::time(|| block_on(to2).unwrap()) }); t1.join().unwrap().assert_is_about(dur1); t2.join().unwrap().assert_is_about(dur2); } #[test] fn test_timer_with_looping_wheel() { let timer = timer::wheel() ...
random
[ { "content": "pub fn time<F: FnOnce()>(f: F) -> Elapsed {\n\n let now = Instant::now();\n\n\n\n f();\n\n\n\n Elapsed { duration: now.elapsed() }\n\n}\n\n\n\nimpl Elapsed {\n\n pub fn assert_is_about(&self, dur: Duration) {\n\n let tolerance = Duration::from_millis(TOLERANCE_MS);\n\n\n\n ...
Rust
src/lib.rs
gregl83/causality
091c17cabe15491e54c56e0c6b1729a72b02463e
use std::error::Error; pub trait Actor<C: Cause, E: Effect, Err: Error> { type Id; type Version; fn handle(&self, cause: C) -> Result<Vec<E>, Err>; fn apply(&mut self, effects: Vec<E>) -> Result<(), Err>; } pub trait Cause { type ActorId; type ActorVersion; ...
use std::error::Error; pub trait Actor<C: Cause, E: Effect, Err: Error> { type Id; type Version; fn handle(&self, cause: C) -> Result<Vec<E>, Err>; fn apply(&mut self, effects: Vec<E>) -> Result<(), Err>; } pub trait Cause { type ActorId; type ActorVersion; ...
}
fn actor_apply_effect_returning_error() { #[allow(dead_code)] struct Aggregate { id: Id, version: Version } impl Actor<Command, Event, SimpleError> for Aggregate { type Id = Id; type Version = Version; fn handle(&self, _command:...
function_block-full_function
[ { "content": "[![Crates.io](https://img.shields.io/crates/v/causality.svg)](https://crates.io/crates/causality)\n\n[![Docs.rs]( https://docs.rs/causality/badge.svg)](https://docs.rs/crate/causality)\n\n[![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/gregl83/causality/blob...
Rust
src/copy/device_copy_processor.rs
kzmi/mtpcopy
012ed0c01f2dcecdf05af0f927cb3d82167bd744
use crate::wpd::device::{ContentObjectInfo, Device}; use super::destination_folder::DestinationFolder; use super::device_file_reader::DeviceFileReader; use super::file_info::FileInfo; use super::copy_processor::{ can_skip_copying, report_copying_end, report_copying_start, report_creating_new_folder, report_de...
use crate::wpd::device::{ContentObjectInfo, Device}; use super::destination_folder::DestinationFolder; use super::device_file_reader::DeviceFileReader; use super::file_info::FileInfo; use super::copy_processor::{ can_skip_copying, report_copying_end, report_copying_start, report_creating_new_folder, report_de...
dest.retain(dest_name); report_copying_end(); return Ok(()); } if target_object_info.is_folder() { let mut new_dest; let new_dest_ref; if dest_is_parent_folder { new_dest = dest.open_or_create_folder(dest_name, |_| {}, report_creating_new_folder)?; ...
function_block-function_prefix_line
[ { "content": "pub fn report_delete_folder(name: &str) {\n\n println!(\"delete folder \\\"{}\\\"\", name);\n\n}\n", "file_path": "src/copy/copy_processor.rs", "rank": 0, "score": 173494.74372066828 }, { "content": "pub fn report_delete_file(name: &str) {\n\n println!(\"delete file \\\"{...
Rust
src/c_api/filter.rs
j2inn/libhaystack
8821d5181f65233a746f7cb27c89d04529fa9b2b
use crate::filter::{Filter, Filtered, ListFiltered}; use crate::val::{Grid, Value}; use std::{ffi::CStr, os::raw::c_char}; use super::err::{new_error, update_last_error}; use super::ResultType; #[no_mangle] pub unsafe extern "C" fn haystack_filter_parse(val: *const c_char) -> Option<Box<Filter>> { ...
use crate::filter::{Filter, Filtered, ListFiltered}; use crate::val::{Grid, Value}; use std::{ffi::CStr, os::raw::c_char}; use super::err::{new_error, update_last_error}; use super::ResultType; #[no_mangle]
#[no_mangle] pub unsafe extern "C" fn haystack_filter_match_dict( filter: *const Filter, dict: *const Value, ) -> ResultType { if filter.is_null() || dict.is_null() { new_error("Invalid null argument(s)"); return ResultType::ERR; } match filter.as_ref() { Som...
pub unsafe extern "C" fn haystack_filter_parse(val: *const c_char) -> Option<Box<Filter>> { if val.is_null() { new_error("Invalid null argument(s)"); return None; } match CStr::from_ptr(val).to_str() { Ok(c_str) => match Filter::try_from(c_str) { Ok(filter) => Some...
function_block-full_function
[ { "content": "fn eval_in_context(filter: &Filter, dict: &Dict) -> bool {\n\n let cx = EvalContext::make(&dict, &NS, dict);\n\n filter.eval(&cx)\n\n}\n\n\n", "file_path": "tests/filter/test_filter_defs.rs", "rank": 0, "score": 90060.59724683489 }, { "content": "#[test]\n\nfn test_dict_m...
Rust
ckb-contracts/lib/eth-recipient-typescript-lib/src/lib.rs
LycrusHamster/force-bridge-eth
a8a65d3ff75cf0e8189d46fcde2a06d3a6c7d80b
#![cfg_attr(not(feature = "std"), no_std)] pub mod actions; pub mod adapter; pub mod debug; pub use adapter::Adapter; cfg_if::cfg_if! { if #[cfg(feature = "std")] { } else { extern crate alloc; } } #[cfg(target_arch = "riscv64")] pub fn verify() -> i8 { let chain = adapter::chain::ChainAdapt...
#![cfg_attr(not(feature = "std"), no_std)] pub mod actions; pub mod adapter; pub mod debug; pub use adapter::Adapter; cfg_if::cfg_if! { if #[cfg(feature = "std")] { } else { extern crate alloc; } } #[cfg(target_arch = "riscv64")] pub fn verify() -> i8 { let chain = adapter::chain::ChainAdapt...
#[test] #[should_panic] fn mock_return_err_when_input_less_than_output() { let data = ETHRecipientDataView { eth_recipient_address: ETHAddress::try_from(vec![0; 20]).unwrap(), eth_token_address: ETHAddress::try_from(vec![0; 20]).unwrap(), token_amount: 100, ...
fn mock_return_ok() { let data = ETHRecipientDataView { eth_recipient_address: ETHAddress::try_from(vec![0; 20]).unwrap(), eth_token_address: ETHAddress::try_from(vec![0; 20]).unwrap(), token_amount: 100, fee: 1, }; let mut mock = MockAdapter::new(...
function_block-full_function
[ { "content": "pub fn verify_burn_token<T: Adapter>(data_loader: T, data: ETHRecipientDataView) {\n\n let eth_contract_address = ETHAddress::try_from(data_loader.load_script_args().to_vec())\n\n .expect(\"eth_contract_address in witness length wrong\");\n\n let eth_bridge_lock_hash =\n\n calc...
Rust
src/kvm/ioctls.rs
Mic92/vmsh
296a09102abece5df0135afb9678261d5a7b6c20
use super::kvm_ioregionfd::kvm_ioregion; use kvm_bindings as kvmb; macro_rules! ioctl_expr { ($dir:expr, $ty:expr, $nr:expr, $size:expr) => { (($dir << _IOC_DIRSHIFT) | ($ty << _IOC_TYPESHIFT) | ($nr << _IOC_NRSHIFT) | ($size << _IOC_SIZESHIFT)) as ::std::os::raw::c_ul...
use super::kvm_ioregionfd::kvm_ioregion; use kvm_bindings as kvmb; macro_rules! ioctl_expr { ($dir:expr, $ty:expr, $nr:expr, $size:expr) => { (($dir << _IOC_DIRSHIFT) | ($ty << _IOC_TYPESHIFT) | ($nr << _IOC_NRSHIFT) | ($size << _IOC_SIZESHIFT)) as ::std::os::raw::c_ul...
_arch = "arm", target_arch = "aarch64")))] ioctl_iow_nr!(KVM_SET_REGS, KVMIO, 0x82, kvmb::kvm_regs); #[cfg(any( target_arch = "x86", target_arch = "x86_64", target_arch = "powerpc", target_arch = "powerpc64" ))] ioctl_ior_nr!(KVM_GET_SREGS, KVMIO, 0x83, kvmb::kvm_sregs); #[cfg(any(target_arch = "x86", ...
$nr, ::std::mem::size_of::<$size>() as u32 ); }; ($name:ident, $ty:expr, $nr:expr, $size:ty, $($v:ident),+) => { ioctl_ioc_nr!( $name, _IOC_READ | _IOC_WRITE, $ty, $nr, ::std::mem::size_of::<$size>() as u32, $($...
random
[ { "content": "pub fn stage_dir(name: &str) -> PathBuf {\n\n let mut dir = env::current_dir().expect(\"cannot get current working directory\");\n\n dir.push(\"src\");\n\n dir.push(name);\n\n dir\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! ok(($expression:expr) => ($expression.unwrap()));\n\n\n\n#[mac...
Rust
layer_core/src/interceptors/session.rs
Sorenon/sorenon_openxr_layer
f32597269ac70ac63b7eb7ec9c6300cd8e6eca64
use std::sync::Arc; use graphics_interop::ImageFormat; use log::info; use openxr::sys as xr; use openxr::Result; use crate::graphics::vulkan_backend::SwapchainBackendVulkan; use crate::wrappers::swapchain::SwapchainBackend; use crate::wrappers::swapchain::SwapchainGraphics; use crate::wrappers::swapchain::SwapchainWr...
use std::sync::Arc; use graphics_interop::ImageFormat; use log::info; use openxr::sys as xr; use openxr::Result; use crate::graphics::vulkan_backend::SwapchainBackendVulkan; use crate::wrappers::swapchain::SwapchainBackend; use crate::wrappers::swapchain::SwapchainGraphics; use crate::wrappers::swapchain::SwapchainWr...
unsafe { (session.inner.core.create_swapchain)(session.handle, &create_info2, swapchain) .result()? }; let interop_info = graphics_interop::ImageCreateInfo { width: create_info.width, height: create_info.height, mip_count: create...
let create_info2 = xr::SwapchainCreateInfo { ty: xr::SwapchainCreateInfo::TYPE, next: std::ptr::null(), create_flags: xr::SwapchainCreateFlags::EMPTY, usage_flags: xr::SwapchainUsageFlags::COLOR_ATTACHMENT, format: format .to_vk() ...
assignment_statement
[ { "content": "type Func<H, T> = unsafe extern \"system\" fn(\n\n handle: H,\n\n format_capacity_input: u32,\n\n format_count_output: *mut u32,\n\n out: *mut T,\n\n) -> xr::Result;\n\n\n\npub unsafe fn call_enumerate<H: Copy, T: Copy>(\n\n handle: H,\n\n f: Func<H, T>,\n\n default: T,\n\n) -...
Rust
meteora-server/src/kv/server.rs
rohitjoshi/meteora
8f25e9311178dc8c7cbc66b19ae1dc343b938d48
use std::collections::HashMap; use std::sync::mpsc::{self, Receiver, Sender}; use std::sync::Arc; use std::thread; use std::time::Duration; use futures::Future; use grpcio::{RpcContext, UnarySink}; use log::*; use raft::storage::MemStorage; use rocksdb::DB; use serde::{Deserialize, Serialize}; use meteora_proto::prot...
use std::collections::HashMap; use std::sync::mpsc::{self, Receiver, Sender}; use std::sync::Arc; use std::thread; use std::time::Duration; use futures::Future; use grpcio::{RpcContext, UnarySink}; use log::*; use raft::storage::MemStorage; use rocksdb::DB; use serde::{Deserialize, Serialize}; use meteora_proto::prot...
("Failed to reply set: {:?}", err)); ctx.spawn(f); } fn delete(&mut self, ctx: RpcContext, req: DeleteReq, sink: UnarySink<DeleteReply>) { let (s1, r1) = mpsc::channel(); let sender = self.sender.clone(); let op = Op::Delete { key: String::from(req.get_key()), ...
: Arc<DB>, sender: Sender<config::Msg>, seq: u64, } #[derive(Serialize, Deserialize, Clone)] pub enum Op { Put { key: String, val: String }, Get { key: String }, Delete { key: String }, } impl KVServer { pub fn new( db_path: String, raft_storage: MemStorage, server_id: ...
random
[ { "content": "pub fn set_logger() {\n\n match env::var(\"RUST_LOG\") {\n\n Ok(val) => {\n\n let log_level: &str = &val;\n\n match log_level {\n\n \"error\" => { /* noop */ }\n\n \"warn\" => { /* noop */ }\n\n \"info\" => { /* noop */ }...
Rust
src/day14.rs
Aidiakapi/advent_of_code_2019
e387ea9764cf3ca0ee1c2ffb010d0b0b2c0b8d5b
use crate::graph::dfs; use crate::HashMap; use std::cmp::Ordering; use std::collections::hash_map::Entry; module!(pt1: parse, pt2: parse); fn calculate_ore_cost<'s>( transformations: &Transformations<'s>, fuel_goal: u64, spare: &mut HashMap<&'s str, u64>, ) -> u64 { spare.clear(); let...
use crate::graph::dfs; use crate::HashMap; use std::cmp::Ordering; use std::collections::hash_map::Entry; module!(pt1: parse, pt2: parse); fn calculate_ore_cost<'s>( transformations: &Transformations<'s>, fuel_goal: u64, spare: &mut HashMap<&'s str, u64>, ) -> u64 { spare.clear(); let...
(s) } let from = separated_list1(tag(", "), molecule); let transformation = map( pair(terminated(from, tag(" => ")), molecule), |(from, into)| Transformation { from, into }, ); fn create_transformations(list: Vec<Transformation>) -> Result<Transformations> { let mut t...
map( pair(terminated(u64_str, char(' ')), alpha1), |(count, name)| Molecule(count, name), )
call_expression
[ { "content": "struct ParentIter<'h, 's: 'h>(&'h HashMap<&'s str, Body<'s>>, Option<&'s str>);\n\nimpl<'h, 's: 'h> Iterator for ParentIter<'h, 's> {\n\n type Item = &'h Body<'s>;\n\n fn next(&mut self) -> Option<&'h Body<'s>> {\n\n if let Some(body) = self.0.get(&self.1?) {\n\n self.1 = b...
Rust
examples/examples/heartbeat_entry.rs
theWebalyst/polyfuse-test
89911c83e45a4ae33d368a48d4a81ce96e603cb3
#![allow(clippy::unnecessary_mut_passed)] #![deny(clippy::unimplemented)] use chrono::Local; use futures::lock::Mutex; use polyfuse::{ io::{Reader, Writer}, reply::{ReplyAttr, ReplyEntry}, Context, DirEntry, FileAttr, Filesystem, Operation, }; use polyfuse_tokio::Server; use std::{io, mem, os::unix::prelud...
#![allow(clippy::unnecessary_mut_passed)] #![deny(clippy::unimplemented)] use chrono::Local; use futures::lock::Mutex; use polyfuse::{ io::{Reader, Writer}, reply::{ReplyAttr, ReplyEntry}, Context, DirEntry, FileAttr, Filesystem, Operation, }; use polyfuse_tokio::Server; use std::{io, mem, os::unix::prelud...
} #[polyfuse::async_trait] impl Filesystem for Heartbeat { #[allow(clippy::cognitive_complexity)] async fn call<'a, 'cx, T: ?Sized>( &'a self, cx: &'a mut Context<'cx, T>, op: Operation<'cx>, ) -> io::Result<()> where T: Reader + Writer + Unpin + Send, { mat...
async fn rename_file(&self, server: Option<&mut Server>) -> io::Result<()> { let mut current = self.current.lock().await; let old_filename = mem::replace(&mut current.filename, generate_filename()); match (server, current.nlookup) { (Some(server), n) if n > 0 => { tr...
function_block-function_prefix_line
[ { "content": "fn run_impl(cmd: &mut Command, timeout: Option<Duration>) -> anyhow::Result<()> {\n\n eprintln!(\"[cargo-xtask] run {:?}\", cmd);\n\n\n\n let mut child = cmd.spawn().context(\"failed to spawn the subprocess\")?;\n\n\n\n let st = match timeout {\n\n Some(timeout) => match child.wait...
Rust
src/app/view.rs
RottenFishbone/wpm
8f5668fef0bff4be15ad19606ce68b728823dbaa
use std::{collections::VecDeque, iter::FromIterator}; use super::{Model, RoundState}; use tui::{ Frame, backend::Backend, layout::{Constraint, Layout, Direction, Corner, Rect, Alignment}, style::{Modifier, Style, Color}, text::{Spans, Span}, widgets::{Block, List, ListItem, Borders, Paragr...
use std::{collections::VecDeque, iter::FromIterator}; use super::{Model, RoundState}; use tui::{ Frame, backend::Backend, layout::{Constraint, Layout, Direction, Corner, Rect, Alignment}, style::{Modifier, Style, Color}, text::{Spans, Span}, widgets::{Block, List, ListItem, Borders, Paragr...
fn draw_current_word<B: Backend>(f: &mut Frame<B>, area: Rect, model: &Model){ let padding_chunks = Layout::default() .direction(Direction::Horizontal) .constraints([Constraint::Min(30), Constraint::Percentage(66)]) .split(area); let block = Block::default() ...
fn draw_words_list<B: Backend>(f: &mut Frame<B>, area: Rect, model: &Model){ let mut next_words = model.word_queue.iter().take(10); let mut words: Vec<Span> = Vec::new(); while let Some(word) = next_words.next() { if words.is_empty() { let mut green_chars = Vec::<char>::new(); ...
function_block-full_function
[ { "content": "/// Spawn a thread that hooks into user events as well as emits a tick event\n\n/// at a given interval. In the event that the Reciever is dropped, the thread\n\n/// will close itself, effectively acting as a kill command.\n\nfn spawn_event_loop(event_tx: Sender<UIEvent>, tick_rate: u64) -> Result...
Rust
src/spdx/details.rs
ShigureLab/lic
2804bcacc8357fc8230fbd5a3abfe14dcd8edffa
use serde::Deserialize; #[derive(Deserialize, PartialEq, Debug)] #[serde(rename_all = "camelCase")] pub struct LicenseDetails { pub is_deprecated_license_id: bool, pub license_text: String, standard_license_header_template: Option<String>, standard_license_template: String, name: String, licens...
use serde::Deserialize; #[derive(Deserialize, PartialEq, Debug)] #[serde(rename_all = "camelCase")] pub struct LicenseDetails { pub is_deprecated_license_id: bool, pub license_text: String, standard_license_header_template: Option<String>, standard_license_template: String, name: String, licens...
#[tokio::test] async fn test_get_details() { let url = "https://spdx.org/licenses/MIT.json".into(); assert!(get_details(url).await.is_ok()); } }
fn test_cross_ref_mit() { let data = r#" { "match": "false", "url": "https://opensource.org/licenses/MIT", "isValid": true, "isLive": true, "timestamp": "2022-02-06T22:01:14Z", "isWayBackLink": false, "order": 0...
function_block-full_function
[ { "content": "pub trait Manifest {\n\n fn license(self) -> String;\n\n fn filename() -> String;\n\n fn from_str(text: &str) -> Self;\n\n fn read() -> Option<String> {\n\n // TODO: 自动向上层寻找\n\n match fs::read_to_string(Self::filename()) {\n\n Ok(text) => Some(text),\n\n ...
Rust
src/error.rs
sgpthomas/sexpy
4d4cbad90714a5013a7b87c3a0ca2e0a0c145161
use nom::{ error::{ErrorKind, ParseError}, Err, IResult, }; use std::iter::repeat; #[derive(Debug)] pub struct SexpyError<Input> { pub errors: Vec<(Input, SexpyErrorKind)>, } #[derive(Clone, Debug, PartialEq)] pub enum SexpyErrorKind { Context(&'static str), Char(char), Word(St...
use nom::{ error::{ErrorKind, ParseError}, Err, IResult, }; use std::iter::repeat; #[derive(Debug)] pub struct SexpyError<Input> { pub errors: Vec<(Input, SexpyErrorKind)>, } #[derive(Clone, Debug, PartialEq)] pub enum SexpyErrorKind { Context(&'static str), Char(char), Word(St...
} pub fn context<I: Clone, E: ParseError<I>, F, O>( context: &'static str, f: F, ) -> impl Fn(I) -> IResult<I, O, E> where F: Fn(I) -> IResult<I, O, E>, { move |i: I| match f(i.clone()) { Ok(o) => Ok(o), Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)), Err(Err::Error(e)) => ...
let mut result = String::new(); for (i, error) in self.errors.iter().enumerate() { result += &format_error(input, i, error); } result }
function_block-function_prefix_line
[ { "content": "/// Takes in a `word` and returns `()` if the first word matches, otherwise\n\n/// returns an Error\n\npub fn word<'a>(\n\n word: &'a str,\n\n) -> impl Fn(&'a str) -> IResult<&'a str, (), SexpyError<&'a str>> {\n\n move |i: &'a str| {\n\n let chars = \" ()[]{}\\n\\t\\r;\";\n\n ...
Rust
kapp_platforms/src/macos/application_mac.rs
kettle11/kettlewin
36109e9ab506b9bce55da6e1cdee0d10e64e6dc4
use super::apple::*; use super::window_mac::WindowState; use kapp_platform_common::*; use std::cell::RefCell; use std::ffi::c_void; thread_local!(pub(crate) static APPLICATION_DATA: RefCell<Box<ApplicationData>> = RefCell::new(Box::new(ApplicationData::new()))); pub(crate) struct ApplicationData { ns_application...
use super::apple::*; use super::window_mac::WindowState; use kapp_platform_common::*; use std::cell::RefCell; use std::ffi::c_void; thread_local!(pub(crate) static APPLICATION_DATA: RefCell<Box<ApplicationData>> = RefCell::new(Box::new(ApplicationData::new()))); pub(crate) struct ApplicationData { ns_application...
let () = unsafe { msg(cursor, Sels::set, ()) }; } fn hide_cursor(&mut self) { let ns_cursor = unsafe { &*NSCursorClass }; unsafe { let () = msg(ns_cursor, Sels::unhide, ()); let () = msg(ns_cursor, Sels::hide, ()); } } ...
let cursor: *mut Object = unsafe { match cursor { Cursor::Arrow => msg(ns_cursor, Sels::arrowCursor, ()), Cursor::IBeam => msg(ns_cursor, Sels::IBeamCursor, ()), Cursor::PointingHand => msg(ns_cursor, Sels::pointingHandCursor, ()), Cursor::Open...
assignment_statement
[ { "content": "fn get_mouse_position(_this: &Object, event: *mut Object) -> (f64, f64) {\n\n unsafe {\n\n let window: *const Object = msg(event, Sels::window, ());\n\n\n\n // Are these coordinates correct or do they not correctly account for the titlebar?\n\n let backing_scale = get_backi...
Rust
src/mbox.rs
petabi/eventio
75e89139f75bcf317209215bed94d438b68e11aa
use crate::{BareEvent, Error}; use nom::{bytes::complete::tag, IResult}; use std::io::{self, BufRead, BufReader, Read}; pub type Event = BareEvent; pub struct Input<T: Read> { data_channel: Option<crossbeam_channel::Sender<Event>>, ack_channel: crossbeam_channel::Receiver<u64>, buf: BufReader<T>, } imp...
use crate::{BareEvent, Error}; use nom::{bytes::complete::tag, IResult}; use std::io::{self, BufRead, BufReader, Read}; pub type Event = BareEvent; pub struct Input<T: Read> { data_channel: Option<crossbeam_channel::Sender<Event>>, ack_channel: crossbeam_channel::Receiver<u64>, buf: BufReader<T>, } imp...
, } } fn read_email<T: Read>(reader: &mut BufReader<T>) -> Result<Option<Vec<u8>>, Error> { let mut buf = vec![]; let mut cur = 0; loop { let bytes = reader .read_until(b'\n', &mut buf) .map_err(|e| Error::CannotFetch(Box::new(e)))?; if bytes == 0 { i...
Err(Error::InvalidMessage(Box::new(io::Error::new( io::ErrorKind::Other, "wrong format", ))))
call_expression
[ { "content": "/// A trait for a single event from any type of data source.\n\npub trait Event {\n\n type Ack;\n\n\n\n fn raw(&self) -> &[u8];\n\n fn time(&self) -> u64;\n\n fn ack(&self) -> Self::Ack;\n\n}\n\n\n\n/// A raw event as a byte sequence.\n\n#[derive(Debug)]\n\npub struct BareEvent {\n\n ...
Rust
src/lib.rs
kbknapp/mkey_map-rs
188f16455658ed162727dd3236e5ef44d75ce859
#![feature(nll)] extern crate clap; use std::collections::hash_map; use std::collections::hash_map::DefaultHasher; use std::collections::{HashMap, HashSet}; use std::ffi::OsStr; use std::hash::{Hash, Hasher}; use std::slice; #[derive(Default, PartialEq, Debug)] pub struct MKeyMap<'a, 'b> where 'a: 'b, { keys:...
#![feature(nll)] extern crate clap; use std::collections::hash_map; use std::collections::hash_map::DefaultHasher; use std::collections::{HashMap, HashSet}; use std::ffi::OsStr; use std::hash::{Hash, Hasher}; use std::slice; #[derive(Default, PartialEq, Debug)] pub struct MKeyMap<'a, 'b> where 'a: 'b, { keys:...
self.keys.insert(key, index); index } pub fn insert_key(&mut self, key: KeyType<'a>, index: usize) { if index >= self.values.len() { panic!("Index out of bounds"); } self.keys.insert(key, index); } pub fn insert_key_by_name(&mut self, k...
if let Some((idx, _)) = self.values.get(&hash).and_then(|ids| { ids.iter() .map(|&x| (x, &self.value_index[x])) .find(|(_i, x)| x == &&value) }) { index = idx; } else { self.value_index.push(value); index = self.value_index....
if_condition
[ { "content": "#[bench]\n\nfn insert10(b: &mut Bencher) {\n\n b.iter(|| {\n\n let mut map = MKeyMap::new();\n\n for i in 0..10 {\n\n map.insert(\n\n Long(&OsStr::new(concat!(\"One\", stringify!(i)))),\n\n Arg::with_name(concat!(\"Value\", stringify!(i))),...
Rust
markov/src/main.rs
jsdw/pudzu-rust
11d07b8d893cc8399fba7b157ce28603cf80a37f
use itertools::Itertools; use std::collections::HashMap; use std::fs::File; use std::path::PathBuf; use std::io::{self, prelude::*, BufReader}; use std::iter::Iterator; use structopt::StructOpt; #[derive(StructOpt)] #[structopt(about = "Thingy for markov whatsits")] struct Opts { #[structopt(name = "FILE", pa...
use itertools::Itertools; use std::collections::HashMap; use std::fs::File; use std::path::PathBuf; use std::io::{self, prelude::*, BufReader}; use std::iter::Iterator; use structopt::StructOpt; #[derive(StructOpt)] #[structopt(about = "Thingy for markov whatsits")] struct Opts { #[structopt(name = "FILE", pa...
} trait NGrams<'a, T: std::clone::Clone>: Iterator<Item = T> { fn tee_n(self, n: u8) -> Vec<Box<dyn Iterator<Item = T> + 'a>>; fn ngrams(self, n: u8) -> ZipVec<T, Box<dyn Iterator<Item = T> + 'a>>; } impl<'a, T: std::clone::Clone + 'a, I: Iterator<Item = T> + 'a> NGrams<'a, T> for I { fn tee_n(self, n: u...
lf::Item> { if self.0.is_empty() { None } else { self.0.iter_mut().map(Iterator::next).collect() } }
function_block-function_prefixed
[ { "content": "import argparse\n\nimport bisect\n\nimport functools\n\nimport itertools\n\nimport json\n\nimport operator as op\n\nimport pickle\n\nimport random\n\nimport string\n\nimport sys\n\nimport unicodedata\n\nfrom collections import Counter\n\nfrom numbers import Integral\n\n\n\n# Simple Markov n-gram b...
Rust
src/runtimefacade_utils/promises.rs
SreeniIO/quickjs_es_runtime
a765180d98829e73705d66eb5cbe866e30f28948
use crate::facades::QuickJsRuntimeFacade; use crate::quickjs_utils::primitives; use crate::quickjs_utils::promises::new_promise_q; use crate::quickjs_utils::promises::PromiseRef; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use crate::valueref::JSValueRef...
use crate::facades::QuickJsRuntimeFacade; use crate::quickjs_utils::primitives; use crate::quickjs_utils::promises::new_promise_q; use crate::quickjs_utils::promises::PromiseRef; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use crate::valueref::JSValueRef...
#[test] fn test_simple_prom() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_context(); q_ctx.eval(Script::new( "test_simple_prom.es", "this.test = function(){return new Promi...
fn test_resolving_prom() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(move |q_js_rt| { let q_ctx = q_js_rt.get_main_context(); let func_ref = functions::new_function_q( q_ctx, "asyncTest", move |q_ctx, _this...
function_block-full_function
[ { "content": "pub fn traverse_properties_q_mut<V, R>(\n\n q_ctx: &QuickJsRealmAdapter,\n\n obj_ref: &JSValueRef,\n\n visitor: V,\n\n) -> Result<(), JsError>\n\nwhere\n\n V: FnMut(&str, &JSValueRef) -> Result<R, JsError>,\n\n{\n\n unsafe { traverse_properties_mut(q_ctx.context, obj_ref, visitor) }...
Rust
cli/src/protocol/enums.rs
DmitryAstafyev/fiber
82b4c585ea811769a0b228445dc40bab9a4f875f
use super::{stop, PrimitiveTypes, Store}; #[derive(Debug, Clone)] pub struct EnumItem { pub name: String, pub types: Option<PrimitiveTypes::ETypes>, pub ref_type_id: Option<usize>, pub ref_type_path: Vec<usize>, pub repeated: bool, pub type_path: Vec<String>, } impl EnumItem { pub fn accep...
use super::{stop, PrimitiveTypes, Store}; #[derive(Debug, Clone)] pub struct EnumItem { pub name: String, pub types: Option<PrimitiveTypes::ETypes>, pub ref_type_id: Option<usize>, pub ref_type_path: Vec<usize>, pub repeated: bool, pub type_path: Vec<String>, } impl EnumItem { pub fn accep...
} }
, ref_type_id: None, name: String::new(), ref_type_path: vec![], repeated: false, type_path: vec![], }); } if let Some(current) = self.current.as_mut() { current.add_type_path(type_str); } els...
random
[ { "content": "pub fn get_cleaner() -> impl Fn(Vec<String>) -> Vec<String> {\n\n move |mut args: Vec<String>| {\n\n if let Some(index) = args.iter().position(|arg| arg == keys::EMBEDDED || arg == keys::EM || arg == keys::E) {\n\n args.remove(index);\n\n }\n\n args\n\n }\n\n}...
Rust
packages/fluid_codegen/src/expression.rs
fluid-lang/fluid
0e169b7dafeec39f4b9bfbb57e25f7a5873308de
use fluid_mangle::mangle_function_name; use fluid_parser::{BinaryOp, Expression, Literal, Type, UnaryOp}; use llvm::core::*; use crate::{cstring, utils::FluidValueRef, CodeGen}; impl CodeGen { pub(crate) unsafe fn gen_expression(&mut self, expression: &Expression) -> FluidValueRef { match expression...
use fluid_mangle::mangle_function_name; use fluid_parser::{BinaryOp, Expression, Literal, Type, UnaryOp}; use llvm::core::*; use crate::{cstring, utils::FluidValueRef, CodeGen}; impl CodeGen { pub(crate) unsafe fn gen_expression(&mut self, expression: &Expression) -> FluidValueRef { match expression...
pub(crate) unsafe fn gen_binary(&mut self, lhs: &Expression, op: &BinaryOp, rhs: &Expression) -> FluidValueRef { let lhs = self.gen_expression(lhs); let rhs = self.gen_expression(rhs); let res = match op { BinaryOp::Add => { if lhs.kind == Type::Number { ...
pub(crate) unsafe fn gen_unary(&mut self, op: &UnaryOp, rhs: &Expression) -> FluidValueRef { let rhs = self.gen_expression(rhs); match op { UnaryOp::Neg => FluidValueRef::new(rhs.kind, LLVMBuildNeg(self.builder, rhs.value, cstring!("nottmp").as_ptr())), UnaryOp::Not => { ...
function_block-full_function
[ { "content": "/// Mangle a function name.\n\npub fn mangle_function_name(name: String, _params: Vec<Type>) -> String {\n\n name\n\n}\n", "file_path": "packages/fluid_mangle/src/lib.rs", "rank": 0, "score": 85191.37062426023 }, { "content": "/// The scope's unique id.\n\ntype ScopeId = usi...
Rust
src/openassets/marker_output.rs
Yamaguchi/openassets-rust
9e3334e284f9623f45aa23d6eee90177a89930f1
use std::fmt; use bitcoin::blockdata::script::Instruction; use bitcoin::consensus::encode::Error; use bitcoin::consensus::{deserialize, Decodable, Decoder, Encodable, Encoder}; use bitcoin::{TxOut, VarInt}; pub const MARKER: u16 = 0x4f41; pub const VERSION: u16 = 0x0100; #[derive(PartialEq, Eq, Debug, Clone)] pub st...
use std::fmt; use bitcoin::blockdata::script::Instruction; use bitcoin::consensus::encode::Error; use bitcoin::consensus::{deserialize, Decodable, Decoder, Encodable, Encoder}; use bitcoin::{TxOut, VarInt}; pub const MARKER: u16 = 0x4f41; pub const VERSION: u16 = 0x0100; #[derive(PartialEq, Eq, Debug, Clone)] pub st...
rker()); } #[test] fn test_get_oa_payload() { let marker_output = TxOut { value: 0, script_pubkey: Builder::from( hex_decode( "6a244f4101000364007b1b753d68747470733a2f2f6370722e736d2f35596753553150672d71", ) ...
if (b as u64) & 0x80 == 0 { break; } offset += 7; } quantities.push(value); } let payload = Payload { quantities, metadata: Decodable::consensus_decode(d)?, }; return Ok(payload); }...
random
[ { "content": "pub trait OAAddressConverter {\n\n fn to_oa_address(&self) -> Result<Address, encode::Error>;\n\n}\n\n\n\nimpl OAAddressConverter for bitcoin::Address {\n\n fn to_oa_address(&self) -> Result<Address, encode::Error> {\n\n Address::new(self.payload.clone(), self.network)\n\n }\n\n}\n...
Rust
feel/src/scope.rs
dmntk/dmntk.rs
3b8a2bd4bec8aec7b2efe020c543b95710bdf1cd
/* * DMNTK - Decision Model and Notation Toolkit * * MIT license * * Copyright (c) 2018-2022 Dariusz Depta Engos Software * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE ...
/* * DMNTK - Decision Model and Notation Toolkit * * MIT license * * Copyright (c) 2018-2022 Dariusz Depta Engos Software * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE ...
name_a, value_number!(125, 2)); assert_eq!("[]", scope.to_string()); scope.set_entry(&name_b, value_number!(175, 2)); assert_eq!("[]", scope.to_string()); scope.pop(); assert_eq!("[]", scope.to_string()); } }
st] fn test_scope_multiple_empty_contexts() { let scope = Scope::new(); scope.push(FeelContext::default()); scope.push(FeelContext::default()); scope.push(FeelContext::default()); assert_eq!("[{}, {}, {}]", scope.to_string()); let scope = Scope::default(); scope.push(FeelContext::default()...
random
[ { "content": "pub fn bring_knowledge_requirements_into_context(def_definitions: &DefDefinitions, knowledge_requirements: &[DefKnowledgeRequirement], ctx: &mut FeelContext) -> Result<()> {\n\n for knowledge_requirement in knowledge_requirements {\n\n let def_href = knowledge_requirement.required_knowledge();...
Rust
derky/src/d3d11/buffer.rs
kb10uy/derky
87f7fbb344c52e5a9430eaf4c6928e849994c5d5
use crate::{ comptrize, d3d11::{ com_support::{ComPtr, HresultErrorExt}, context::{Context, Device}, vertex::D3d11Vertex, }, null, }; use std::{ ffi::c_void, marker::PhantomData, mem::{size_of, zeroed}, ptr::copy_nonoverlapping, slice::from_ref, }; use any...
use crate::{ comptrize, d3d11::{ com_support::{ComPtr, HresultErrorExt}, context::{Context, Device}, vertex::D3d11Vertex, }, null, }; use std::{ ffi::c_void, marker::PhantomData, mem::{size_of, zeroed}, ptr::copy_nonoverlapping, slice::from_ref, }; use any...
pub fn new_immutable(device: &Device, initial: &T) -> Result<ConstantBuffer<T>> { let buffer = create_buffer( device, from_ref(initial), d3d11::D3D11_USAGE_IMMUTABLE, d3d11::D3D11_BIND_CONSTANT_BUFFER, 0, 0, "Constant...
T, d3d11::D3D11_BIND_CONSTANT_BUFFER, 0, 0, "Constant", )?; Ok(ConstantBuffer { buffer, modifiable: true, inner_type: Default::default(), }) }
function_block-function_prefixed
[ { "content": "/// バッファを生成する。\n\npub fn initialize_buffers(display: &Display) -> Result<Buffers> {\n\n let out_albedo = Texture2d::empty_with_format(\n\n display,\n\n UncompressedFloatFormat::F32F32F32F32,\n\n MipmapsOption::NoMipmap,\n\n 1280,\n\n 720,\n\n )?;\n\n let...
Rust
mqtt-packets/src/v_3_1_1/connect/connect_flags.rs
telemq/telemq
adfae0c90c0e28e554f80172507a769cdd58279a
use crate::v_3_1_1::QoS; use bytes::{BufMut, BytesMut}; #[derive(Debug, PartialEq, Clone)] pub struct ConnectFlags(u8); impl ConnectFlags { const RESERVED_MASK: u8 = 0b00000001; const CLEAN_SESSION_MASK: u8 = 0b00000010; const WILL_FLAG_MASK: u8 = 0b00000100; const QOS_MASK: u8 = 0b00011000; cons...
use crate::v_3_1_1::QoS; use bytes::{BufMut, BytesMut}; #[derive(Debug, PartialEq, Clone)] pub struct ConnectFlags(u8); impl ConnectFlags { const RESERVED_MASK: u8 = 0b00000001; const CLEAN_SESSION_MASK: u8 = 0b00000010; const WILL_FLAG_MASK: u8 = 0b00000100; const QOS_MASK: u8 = 0b00011000; cons...
}
uf) .expect("Should decode connection flag without errors"); assert_eq!(flags_opt.unwrap(), ConnectFlags(0b00010100)); }
function_block-function_prefixed
[ { "content": "/// Function that returns `Ok(QoS)` for a flag.\n\npub fn get_qos_level_from_flag(flag: &Flag) -> std::io::Result<QoS> {\n\n // masked bits rotated right in order to remove a leading zero\n\n let rotated_bits = (flag.bits & QOS_MASK).rotate_right(1);\n\n QoS::try_from(rotated_bits)\n\n}\n...
Rust
packages/hurl_core/src/parser/query.rs
youhavethewrong/hurl
91cc14882a5f1ef7fa86be09a9f5581cef680559
/* * hurl (https://hurl.dev) * Copyright (C) 2020 Orange * * 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 ...
/* * hurl (https://hurl.dev) * Copyright (C) 2020 Orange * * 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 ...
; Ok(Query { source_info: SourceInfo { start, end }, value, subquery: optional_subquery, }) } fn query_value(reader: &mut Reader) -> ParseResult<'static, QueryValue> { choice( vec![ status_query, header_query, cookie_query, bod...
if space.value.is_empty() { reader.state = save; None } else { match subquery(reader) { Ok(q) => Some((space, q)), Err(e) => { if e.recoverable { reader.state = save; None } else { ...
if_condition
[]
Rust
src/macos/win_id.rs
Jamyw7g/wingif
f21a5dc9d7baf2a74b7c60b8274d0bda1992c36f
use crate::macos::core_foundation_sys_patches::{ kCFNumberSInt32Type as I32, kCFNumberSInt64Type as I64, CFBooleanGetValue, CFNumberGetType, }; use anyhow::{anyhow, Result}; use core_foundation::base::{CFGetTypeID, CFTypeID, ToVoid}; use core_foundation::string::{kCFStringEncodingUTF8, CFString, CFStringGetCString...
use crate::macos::core_foundation_sys_patches::{ kCFNumberSInt32Type as I32, kCFNumberSInt64Type as I64, CFBooleanGetValue, CFNumberGetType, }; use anyhow::{anyhow, Result}; use core_foundation::base::{CFGetTypeID, CFTypeID, ToVoid}; use core_foundation::string::{kCFStringEncodingUTF8, CFString, CFStringGetCString...
t = String::from(c_result.to_str().unwrap()); DictEntryValue::_String(result) } else { use objc_foundation::{INSString, NSString}; use objc_id::Id; let nss: Id<NSString> = unsafe { Id::from_ptr(value as *mut NS...
tTypeID() } { let value = value as CFNumberRef; match unsafe { CFNumberGetType(value) } { I64 => { let mut value_i64 = 0_i64; let out_value: *mut i64 = &mut value_i64; let converted = unsafe { CFNumberGetValue(value, I64...
function_block-random_span
[ { "content": "pub fn capture_by_id(win_id: u32) -> Result<ImgVec<RGBA8>> {\n\n let screenshot = unsafe {\n\n CGDisplay::screenshot(\n\n CGRectNull,\n\n kCGWindowListOptionIncludingWindow | kCGWindowListExcludeDesktopElements,\n\n win_id,\n\n kCGWindowImageNo...
Rust
src/series_paint.rs
pwil3058/rs_epaint
abde42728f65fc166df6416df8b3c3067faf51ed
use std::path::Path; use std::rc::Rc; use pw_gix::{ gdk_pixbuf::Pixbuf, gtk::{self, prelude::*}, gtkx::window::*, wrapper::*, }; use crate::basic_paint::*; use crate::colln_paint::binder::*; use crate::colln_paint::collection::*; pub use crate::colln_paint::display::*; use crate::colln_paint::editor...
use std::path::Path; use std::rc::Rc; use pw_gix::{ gdk_pixbuf::Pixbuf, gtk::{self, prelude::*}, gtkx::window::*, wrapper::*, }; use crate::basic_paint::*; use crate::colln_paint::binder::*; use crate::colln_paint::collection::*; pub use crate::colln_paint::display::*; use crate::colln_paint::editor...
fn tool_button(&self) -> gtk::ToolButton { let tool_button = gtk::ToolButton::new(Some(&series_paint_image(24)), Some("Series Paint Manager")); tool_button.set_tooltip_text(Some(TOOLTIP_TEXT)); let spm_c = self.clone(); tool_button.connect_clicked(move |_| spm_c.window....
w(); button.set_tooltip_text(Some(TOOLTIP_TEXT)); button.set_image(Some(&series_paint_image(24))); let spm_c = self.clone(); button.connect_clicked(move |_| spm_c.window.present()); button }
function_block-function_prefixed
[ { "content": "pub trait BasicPaintInterface<C>: Clone + PartialEq + Ord + Debug + ColouredItemInterface\n\nwhere\n\n C: CharacteristicsInterface,\n\n{\n\n fn name(&self) -> String;\n\n fn notes(&self) -> String;\n\n fn tooltip_text(&self) -> String;\n\n fn characteristics(&self) -> C;\n\n\n\n ...
Rust
planner/bootstrap.rs
zeedb/ZeeDB
892ba026d893299b2717eb2401c818f9e9d8520f
use zetasql::{function_enums::*, *}; use defaults::{builtin_function_options, builtin_named_types}; pub fn bootstrap_metadata_catalog() -> SimpleCatalogProto { let mut count = 0; let mut table = |name: &str, columns: Vec<SimpleColumnProto>| -> SimpleTableProto { let serialization_id = count; c...
use zetasql::{function_enums::*, *}; use defaults::{builtin_function_options, builtin_named_types}; pub fn bootstrap_metadata_catalog() -> SimpleCatalogProto { let mut count = 0; let mut table = |name: &str, columns: Vec<SimpleColumnProto>| -> SimpleTableProto { let serialization_id = count; c...
SimpleCatalogProto { name: Some("metadata".to_string()), table: vec![ table( "catalog", vec![ column("parent_catalog_id", TypeKind::TypeInt64), column("catalog_id", TypeKind::TypeInt64), column("...
let column = |name: &str, kind: TypeKind| -> SimpleColumnProto { SimpleColumnProto { name: Some(String::from(name)), r#type: Some(TypeProto { type_kind: Some(kind as i32), ..Default::default() }), ..Default::default() } ...
assignment_statement
[ { "content": "#[log::trace]\n\npub fn column_statistics(table_id: i64, column_name: &str) -> Option<ColumnStatistics> {\n\n CACHE\n\n .get_or_init(Default::default)\n\n .lock()\n\n .unwrap()\n\n .entry(table_id)\n\n .or_insert_with(|| populate_cache(table_id))\n\n .c...
Rust
src/lib.rs
awh6al/uuid-rs
3f4341be58e1034d68488fd0e764563709ef2458
#![doc(html_root_url = "https://docs.rs/uuid-rs")] mod name; mod rand; mod time; use core::fmt; use core::sync::atomic; use std::time::SystemTime; pub const UTC_EPOCH: u64 = 0x1B21_DD21_3814_000; #[derive(Debug)] pub struct Layout { pub field_low: u32, pub field_mid: u16, pub field_high...
#![doc(html_root_url = "https://docs.rs/uuid-rs")] mod name; mod rand; mod time; use core::fmt; use core::sync::atomic; use std::time::SystemTime; pub const UTC_EPOCH: u64 = 0x1B21_DD21_3814_000; #[derive(Debug)] pub struct Layout { pub field_low: u32, pub field_mid: u16, pub field_high...
#[test] fn test_node_format() { let node = Node([00, 42, 53, 13, 19, 128]); assert_eq!(format!("{}", node), "00-2a-35-0d-13-80"); assert_eq!(format!("{}", node).to_uppercase(), "00-2A-35-0D-13-80") } #[test] fn test_is_valid_uuid() { let uuid = [ v1!()...
fn is_valid(s: &str) -> bool { let regex = Regex::new( r"^(?i)(urn:uuid:)?[0-9a-f]{8}\-[0-9a-f]{4}\-[0-5]{1}[0-9a-f]{3}\-[0-9a-f]{4}\-[0-9a-f]{12}$", ); regex.unwrap().is_match(s) }
function_block-full_function
[ { "content": "#[bench]\n\nfn bench_from_mac(b: &mut Bencher) {\n\n b.iter(|| UUID::from_mac(Version::TIME, [0x03, 0x2a, 0x35, 0x0d, 0x13, 0x80]));\n\n}\n\n\n", "file_path": "benches/bench.rs", "rank": 0, "score": 50885.21069634547 }, { "content": "#[bench]\n\nfn bench_v1(b: &mut Bencher) ...
Rust
gml/meta/src/lib.rs
gm-archive/dejavu
1751e25fb3db15573bfa5767472ec8f1d5079cc5
extern crate proc_macro; use std::iter; use std::collections::HashMap; use proc_macro::TokenStream; use proc_macro2; use syn::{ self, parse_quote, parenthesized, punctuated, ItemImpl, ImplItemMethod, Attribute, Signature, FnArg, PatType, Type, TypeReference, Path, Ident }; use syn::parse::{Parse, ParseStre...
extern crate proc_macro; use std::iter; use std::collections::HashMap; use proc_macro::TokenStream; use proc_macro2; use syn::{ self, parse_quote, parenthesized, punctuated, ItemImpl, ImplItemMethod, Attribute, Signature, FnArg, PatType, Type, TypeReference, Path, Ident }; use syn::parse::{Parse, ParseStre...
#[proc_macro_attribute] pub fn bind(_attr: TokenStream, input: TokenStream) -> TokenStream { let mut input: ItemImpl = syn::parse_macro_input!(input); let bindings = match ItemBindings::parse(&mut input) { Ok(bindings) => bindings, Err(errors) => { let errors: proc_macro2::To...
am { FnArg::Typed(PatType { ref ty, .. }) => match **ty { Type::Reference(TypeReference { ref elem, .. }) => match **elem { Type::Path(_) => Some(&**elem), _ => None, } _ => None, } _ => None, } }
function_block-function_prefixed
[ { "content": "pub trait Project<'r, R> { fn fields(&'r mut self) -> R; }\n\n\n\nimpl<W> Project<'_, ()> for W { fn fields(&mut self) -> () { () } }\n\nimpl<'r, W> Project<'r, (&'r mut W,)> for W { fn fields(&'r mut self) -> (&'r mut W,) { (self,) } }\n\n\n", "file_path": "gml/src/vm/bind.rs", "rank": 2,...
Rust
src/search.rs
dlee13/peep
3c5c4f3a114cb3659030b423934ee53cf4d0712f
use regex::{self, Regex}; use std::io; #[derive(Clone, Debug, PartialEq)] pub struct Match { start: usize, end: usize, } impl Match { #[inline] pub fn start(&self) -> usize { self.start } #[inline] pub fn end(&self) -> usize { self.end } fn new(start: usize, end: us...
use regex::{self, Regex}; use std::io; #[derive(Clone, Debug, PartialEq)] pub struct Match { start: usize, end: usize, } impl Match { #[inline] pub fn start(&self) -> usize { self.start } #[inline] pub fn end(&self) -> usize { self.end } fn new(start: usize, end: us...
, _ => Err(io::Error::new(io::ErrorKind::Other, "Unknown regex error")), }; } self.pat = a.unwrap(); Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_plane() { let pat = "abc"; let text = "xabcabcwowabc"; let...
Err(io::Error::new( io::ErrorKind::InvalidInput, "Compiled too big", ))
call_expression
[ { "content": "#[cfg(not(debug_assertions))]\n\npub fn log(_: &str) {}\n", "file_path": "src/logger.rs", "rank": 1, "score": 97346.62308184855 }, { "content": "#[cfg(debug_assertions)]\n\npub fn log(msg: &str) {\n\n const LOG_PATH: &str = \"./peep.log\";\n\n use std::fs::OpenOptions;\n\...
Rust
src/client.rs
Arthamys/pay-engine
33a482810fa5bf18c61a4b675dcdba5be1083e67
use crate::error::{Error, Result}; use serde::ser::{Serialize, SerializeStruct, Serializer}; use std::collections::HashMap; #[derive(Debug)] pub struct Client { id: u16, available_balance: f64, held_balance: f64, total_balance: f64, locked: bool, } impl Serialize for Client { fn serialize<S>...
use crate::error::{Error, Result}; use serde::ser::{Serialize, SerializeStruct, Serializer}; use std::collections::HashMap; #[derive(Debug)] pub struct Client { id: u16, available_balance: f64, held_balance: f64, total_balance: f64, locked: bool, } impl Serialize for Client { fn serialize<S>...
pub fn id(&self) -> u16 { self.id } pub fn lock(&mut self) { self.locked = true; } #[cfg(test)] pub fn available_balance(&self) -> f64 { self.available_balance } #[cfg(test)] pub fn held_balance(&self) -> f64 { self.held_balance } ...
pub fn confiscate(&mut self, amount: f64) -> Result<()> { if self.held_balance < amount { return Err(Error::InssuficientFunds); } self.held_balance -= amount; self.total_balance -= amount; Ok(()) }
function_block-full_function
[ { "content": "/// Credit the client's account of `amount` funds.\n\nfn deposit(client: &mut Client, amount: f64) -> bool {\n\n client.credit(amount);\n\n log::trace!(\"deposited {} to client {}'s balance\", amount, client.id());\n\n true\n\n}\n\n\n", "file_path": "src/engine.rs", "rank": 0, ...
Rust
services/src/pro/contexts/in_memory.rs
glombiewski/geoengine
d84520756198ce5759fa83cba211f38fe523ed61
use crate::contexts::{ExecutionContextImpl, QueryContextImpl}; use crate::error; use crate::layers::add_from_directory::{ add_layer_collections_from_directory, add_layers_from_directory, }; use crate::layers::storage::HashMapLayerDb; use crate::pro::contexts::{Context, ProContext}; use crate::pro::datasets::{add_da...
use crate::contexts::{ExecutionContextImpl, QueryContextImpl}; use crate::error; use crate::layers::add_from_directory::{ add_layer_collections_from_directory, add_layers_from_directory, }; use crate::layers::storage::HashMapLayerDb; use crate::pro::contexts::{Context, ProContext}; use crate::pro::datasets::{add_da...
} #[async_trait] impl ProContext for ProInMemoryContext { type UserDB = HashMapUserDb; fn user_db(&self) -> Arc<Self::UserDB> { self.user_db.clone() } fn user_db_ref(&self) -> &Self::UserDB { &self.user_db } } #[async_trait] impl Context for ProInMemoryContext { type Session ...
pub fn new_with_context_spec( exe_ctx_tiling_spec: TilingSpecification, query_ctx_chunk_size: ChunkByteSize, ) -> Self { ProInMemoryContext { user_db: Default::default(), project_db: Default::default(), workflow_registry: Default::default(), da...
function_block-full_function
[]
Rust
src/game/shooting.rs
PapugaPower/bevyjam
c484cfecfbfcbf3261d4e3e4dd464d756c24fd47
use crate::game::crosshair::Crosshair; use crate::game::damage::{DamageAreaShape, DamageEvent, DamageSource, Pulsing, PulsingBundle}; use crate::game::enemies::Enemy; use crate::game::phys_layers::PhysLayer; use crate::game::player::{Player, PlayerShootState, PlayerState}; use crate::game::{GameAssets, GameAudioChannel...
use crate::game::crosshair::Crosshair; use crate::game::damage::{DamageAreaShape, DamageEvent, DamageSource, Pulsing, PulsingBundle}; use crate::game::enemies::Enemy; use crate::game::phys_layers::PhysLayer; use crate::game::player::{Player, PlayerShootState, PlayerState}; use crate::game::{GameAssets, GameAudioChannel...
; damage_event.send(DamageEvent { entity: collision.entity, source: DamageSource::Weapon, damage: projectile.damage, }); commands.entity(entity).despawn(); impact_event.send(BulletImpactEvent { position: col...
if collision.entity == player_entity { ImpactSurface::Player } else if (collision.collision_point - transform.translation).length() <= bullet_travel && query_enemy.get(collision.entity).is_ok() { ImpactSurface::Monster } else { ...
if_condition
[ { "content": "pub fn print_player_position(q: Query<&Transform, With<Player>>, keys: Res<Input<KeyCode>>) {\n\n if keys.just_pressed(KeyCode::P) {\n\n let t = q.single();\n\n println!(\"Current player position: {:?}\", t.translation);\n\n }\n\n}\n\n\n", "file_path": "src/game/player.rs",...
Rust
src/main.rs
Emberwalker/drakonid-rs
8240482b93eacdbfd5fb4f252f23e5f66f092363
extern crate chrono; #[macro_use] extern crate clap; extern crate fern; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate regex; extern crate drakonid; use clap::{App, Arg}; use regex::Regex; use std::hash::{Hash, Hasher}; use std::{cmp, thread}; static CONF_LOC_ENV: &'static str = "...
extern crate chrono; #[macro_use] extern crate clap; extern crate fern; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate regex; extern crate drakonid; use clap::{App, Arg}; use regex::Regex; use std::hash::{Hash, Hasher}; use std::{cmp, thread}; static CONF_LOC_ENV: &'static str = "...
info!(target: "main", "Logger configured; using log level {}", log_lvl); drakonid::run(conf_loc, matches.occurrences_of("is_wrapped") != 0); } struct DummyHasher(pub u64); impl Hasher for DummyHasher { fn write_u64(&mut self, i: u64) { self.0 = i; } fn write(&mut self, _: &[u8]) {} ...
.global(true) .takes_value(true), ) .arg( Arg::with_name("v") .short("v") .multiple(true) .help("Sets verbosity. May be specified up to 3 times.") .global(true), ) .arg( A...
random
[ { "content": "#[inline]\n\npub fn run_on_worker<T: 'static + FnOnce() -> () + Send>(thunk: T) {\n\n THREAD_POOL_INST.with(move |pool| {\n\n pool.execute(thunk);\n\n });\n\n}\n", "file_path": "src/workers.rs", "rank": 3, "score": 59587.63158654327 }, { "content": "fn shutdown_bot...
Rust
main/src/class/messages/view.rs
lovelace-edu/lovelace
d1511560682852612b4247da33401b37d2997b7b
use diesel::prelude::*; use malvolio::prelude::*; use portia::levels::Level; use rocket::serde::json::Json; use thiserror::Error as ThisError; use super::super::get_user_role_in_class; use crate::{ auth::AuthCookie, db::Database, utils::{default_head, error_messages::database_error}, }; use crate::{ mo...
use diesel::prelude::*; use malvolio::prelude::*; use portia::levels::Level; use rocket::serde::json::Json; use thiserror::Error as ThisError; use super::super::get_user_role_in_class; use crate::{ auth::AuthCookie, db::Database, utils::{default_head, error_messages::database_error}, }; use crate::{ mo...
} #[get("/<class_id>/message/<message_id>/view")] pub async fn view_message( class_id: i32, message_id: i32, auth: AuthCookie, conn: Database, ) -> Html { match view_message_base(class_id, message_id, auth, conn).await { Ok((_message, replies)) => { Html::default() ...
match conn .run(move |c| { ClassMessageReply::belonging_to(&message_clone) .inner_join(crate::schema::users::table) .select(( crate::schema::class_message_reply::all_columns, users::username, )) ....
if_condition
[]
Rust
influxdb_iox/tests/end_to_end_cases/database_migration.rs
Marwes/influxdb_iox
b3b2d9b6232a3341ff15506df1f02bef4dc81d6b
use std::{ path::{Path, PathBuf}, time::Duration, }; use arrow_util::assert_batches_eq; use assert_cmd::Command; use data_types::chunk_metadata::ChunkStorage; use predicates::prelude::*; use tempfile::TempDir; use test_helpers::assert_contains; use uuid::Uuid; use crate::{ common::server_fixture::{Serve...
use std::{ path::{Path, PathBuf}, time::Duration, }; use arrow_util::assert_batches_eq; use assert_cmd::Command; use data_types::chunk_metadata::ChunkStorage; use predicates::prelude::*; use tempfile::TempDir; use test_helpers::assert_contains; use uuid::Uuid; use crate::{ common::server_fixture::{Serve...
#[tokio::test] async fn migrate_all_database_files_from_one_server_to_another() { let (db_name, db_uuid, tmp_dir) = create_copied_database().await; let fixture = ServerFixture::create_shared(ServerType::Database).await; let addr = fixture.grpc_base(); let mut source_dir: PathBuf = tmp...
async fn create_copied_database() -> (String, Uuid, TempDir) { let fixture = ServerFixture::create_single_use(ServerType::Database).await; let addr = fixture.grpc_base(); Command::cargo_bin("influxdb_iox") .unwrap() .arg("server") .arg("set") .arg("3113") .arg("--hos...
function_block-full_function
[ { "content": "/// Return the path that the database stores data for all databases:\n\n/// `<server_path>/dbs`\n\npub fn data_dir(server_path: impl AsRef<Path>) -> PathBuf {\n\n // Assume data layout is <dir>/dbs/<uuid>\n\n let mut data_dir: PathBuf = server_path.as_ref().into();\n\n data_dir.push(\"dbs...
Rust
src/cli/transaction.rs
paddymills/430-project
d90a816bc9f58dfc3aa242bd402af79ededd1a95
use chrono::{ naive::NaiveDate, prelude::* }; use requestty::{ DefaultSeparator, prompt, prompt_one, Question, Answer }; use tabled::{Table, Style}; use crate::{ cli::{AnswerValue, MENU_SEP}, db, schema::TransactionOps }; const DATE_FMT: &str = "%m/%d/%Y"; pub fn menu() { loop { ...
use chrono::{ naive::NaiveDate, prelude::* }; use requestty::{ DefaultSeparator, prompt, prompt_one, Question, Answer }; use tabled::{Table, Style}; use crate::{ cli::{AnswerValue, MENU_SEP}, db, schema::TransactionOps }; const DATE_FMT: &str = "%m/%d/%Y"; pub fn menu() { loop { ...
fn edit() { let questions = vec![ Question::int("tid").message("Transaction ID:").build(), Question::input("dt").message("Transaction Date (month/day/year):") .default(Local::today().format(DATE_FMT).to_string()) .validate(|name, _| match NaiveDate::parse_from_str(name, DAT...
match prompt(questions) { Ok(answers) => { let cid = &answers.get_int("lid"); let lid = &answers.get_int("cid"); let dt = NaiveDate::parse_from_str(&answers.get_str("dt"), DATE_FMT).unwrap(); let amt = &answers.get_float("amt"); match db::get...
function_block-function_prefix_line
[ { "content": "pub fn menu() {\n\n loop {\n\n let select = Question::select(\"main\")\n\n .message(\"Main Menu\")\n\n .choices(vec![\n\n \"Customer Menu\".into(),\n\n \"Transaction Menu\".into(),\n\n \"Loan Menu\".into(),\n\n ...
Rust
src/parsing/grammar.rs
Verdex/ash
0d6b44001301c0d7447abd5fc64b67c986381d5e
use super::parser::{Parser, bind, unit, exact, any, peek, the}; use super::ast::Ast; use monad::compute; macro_rules! trim { ($p : expr) => { compute!{ bind, unit => _junk_1 <- junk().zero_or_more(); t <- $p; _junk_2 <- junk().zero_or_more(); unit t....
use super::parser::{Parser, bind, unit, exact, any, peek, the}; use super::ast::Ast; use monad::compute; macro_rules! trim { ($p : expr) => { compute!{ bind, unit => _junk_1 <- junk().zero_or_more(); t <- $p; _junk_2 <- junk().zero_or_more(); unit t....
/* private Parser<Expr> StrParser() { static Parser<char> EscapeParser() => (from slash in Expect("\\") from other in Expect("t") .Or(Expect("n")) .Or(Expect("r")) .Or(E...
e!{ bind, unit => v <- exact("true").or(exact("false")); _i <- not_sym_char(); unit v }; p.map(|b| Ast::Bool(b.parse::<bool>().expect("Parsed bool fails parse::<bool>()"))) }
function_block-function_prefixed
[ { "content": "pub fn peek() -> Parser<char> {\n\n Parser::Parse(Box::new(move |input| {\n\n match input.peek() {\n\n Ok((index, value)) => Output::Success(value, index, index),\n\n Err(index) => Output::Failure(index),\n\n }\n\n }))\n\n}\n\n\n\nimpl<T : 'static + Clone>...
Rust
src/cli/snapshot/resample/regular_grid.rs
lars-frogner/bifrost-rust
ae1b4e7adde92ec1c611259796ef593243f82a8d
use super::{ direct_sampling::create_direct_sampling_subcommand, weighted_cell_averaging::create_weighted_cell_averaging_subcommand, weighted_sample_averaging::create_weighted_sample_averaging_subcommand, }; use crate::{ add_subcommand_combinations, cli::{ snapshot::{ derive::c...
use super::{ direct_sampling::create_direct_sampling_subcommand, weighted_cell_averaging::create_weighted_cell_averaging_subcommand, weighted_sample_averaging::create_weighted_sample_averaging_subcommand, }; use crate::{ add_subcommand_combinations, cli::{ snapshot::{ derive::c...
pub fn run_resampling_for_regular_grid<G, P, I>( root_arguments: &ArgMatches, arguments: &ArgMatches, provider: P, snap_num_in_range: &Option<SnapNumInRange>, resampled_locations: &In3D<ResampledCoordLocation>, resampling_method: ResamplingMethod, continue_on_warnings: bool, verbose: Ver...
function_block-full_function
[ { "content": "/// Builds a representation of the `snapshot-resample-direct_sampling` command line subcommand.\n\npub fn create_direct_sampling_subcommand(_parent_command_name: &'static str) -> Command<'static> {\n\n let command_name = \"direct_sampling\";\n\n\n\n update_command_graph!(_parent_command_name...
Rust
src/lib/types/src/net/protocol.rs
workanator/wrustlr
0e38becaae2bd2af6059616ebe2b13bf50933ef1
use std::str::FromStr; use ::Error; const PROTOCOL_TCP: &'static str = "TCP"; const PROTOCOL_UDP: &'static str = "UDP"; const PROTOCOL_UNIX: &'static str = "UNIX"; #[derive(Debug, Clone)] pub enum Protocol<TcpData = (), UdpData = (), UnixData = ()> { Tcp(TcpData), Udp(UdpData), Unix(UnixData), } impl<TcpDat...
use std::str::FromStr; use ::Error; const PROTOCOL_TCP: &'static str = "TCP"; const PROTOCOL_UDP: &'static str = "UDP"; const PROTOCOL_UNIX: &'static str = "UNIX"; #[derive(Debug, Clone)] pub enum Protocol<TcpData = (), UdpData = (), UnixData = ()> { Tcp(TcpData), Udp(UdpData), Unix(UnixData), } impl<TcpDat...
pub fn is_unix(&self) -> bool { match *self { Protocol::Unix(_) => true, _ => false, } } pub fn unix(self) -> Option<UnixData> { match self { Protocol::Unix(data) => Some(data), _ => None, } } pub fn unix_ref(&self) -> Option<&UnixData> { match *self { Protocol::Unix(ref data) =>...
pub fn udp_and_then_mut<Func>(&mut self, mut func: Func) -> &mut Self where Func : FnMut(&mut UdpData) { if let Protocol::Udp(ref mut data) = *self { func(data); } self }
function_block-full_function
[]
Rust
src/bxdf/bsdf.rs
joeftiger/rust-v2
42676758f0845488fc81aa3fb57ffca00a83616f
use crate::bxdf::{same_hemisphere, world_to_bxdf, BxDF, BxDFFlag, BxDFSample, BxDFSamplePacket}; use crate::sampler::Sample; use crate::{Float, Spectrum, Vec3, PACKET_SIZE}; use serde::{Deserialize, Serialize}; #[derive(Default, Serialize, Deserialize)] pub struct BSDF { #[serde(default)] bxdfs: Vec<Box<dyn Bx...
use crate::bxdf::{same_hemisphere, world_to_bxdf, BxDF, BxDFFlag, BxDFSample, BxDFSamplePacket}; use crate::sampler::Sample; use crate::{Float, Spectrum, Vec3, PACKET_SIZE}; use serde::{Deserialize, Serialize}; #[derive(Default, Serialize, Deserialize)] pub struct BSDF { #[serde(default)] bxdfs: Vec<Box<dyn Bx...
}
flags: BxDFFlag, index: usize, ) -> Option<BxDFSample<Float>> { let rotation = world_to_bxdf(normal); let outgoing = rotation.rotate_vector(outgoing_world); let bxdf = self.random_matching_bxdf(flags, sample.float)?; bxdf.sample_lambda(outgoing, sample.vec2, index) ...
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn same_hemisphere(a: Vec3, b: Vec3) -> bool {\n\n a.y * b.y > 0.0\n\n}\n\n\n", "file_path": "src/bxdf/mod.rs", "rank": 0, "score": 243608.33743803727 }, { "content": "#[inline]\n\npub fn cos_d_phi(a: Vec3, b: Vec3) -> Float {\n\n let abxz = a.x * b.x + a...
Rust
src/bus.rs
fry/n2k
bdbd50fad67cabcc51caf0cabcbf88515195dfaa
use core::{convert::TryFrom, fmt::Debug}; use crate::hal_can::{self, Receiver, Transmitter}; use crate::CanFrame; use crate::{Id, IdError, Message, GLOBAL_ADDRESS}; const CB_TP_BAM: u8 = 0x40; const PGN_TP_CM: u32 = 0x00ec00; const PGN_TP_DT: u32 = 0x00eb00; #[derive(Copy, Clone, Debug, PartialEq)] pub enum BusE...
use core::{convert::TryFrom, fmt::Debug}; use crate::hal_can::{self, Receiver, Transmitter}; use crate::CanFrame; use crate::{Id, IdError, Message, GLOBAL_ADDRESS}; const CB_TP_BAM: u8 = 0x40; const PGN_TP_CM: u32 = 0x00ec00; const PGN_TP_DT: u32 = 0x00eb00; #[derive(Copy, Clone, Debug, PartialEq)] pub enum BusE...
for i in &test_cases { let can = MockCan::new(); let mut bus = Bus::new(can); bus.send(&i.message).unwrap(); let data = i.message.data(); if data.len() <= 8 { } else { for b in 0..data.le...
let test_cases = [ TestCase { message: Message::new( Id::new(Priority::Priority0, 12345, 123, GLOBAL_ADDRESS).unwrap(), Box::new([1, 2, 3, 4, 5, 6, 7]), ) .unwrap(), }, TestCase { ...
assignment_statement
[ { "content": "fn validate_id(id: &u32) -> Result<()> {\n\n if id & 0xe0000000 > 0 {\n\n return Err(IdError::InvalidId);\n\n }\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{Id, Priority, GLOBAL_ADDRESS};\n\n use core::convert::TryFrom;\n\n\n\n #[test]\n\n fn id_ne...
Rust
src/testdrive/action/sql.rs
cuongdo/materialize
5e32da2ef02ce32a5b2cfec7f861c40b698402d0
use std::env; use std::error::Error as _; use std::fmt::Write as _; use std::io::{self, Write}; use std::thread; use std::time::Duration; use postgres::error::DbError; use postgres::row::Row; use postgres::types::{Json, Type}; use serde_json::Value; use sql_parser::ast::Statement; use sql_parser::parser::Parser as S...
use std::env; use std::error::Error as _; use std::fmt::Write as _; use std::io::{self, Write}; use std::thread; use std::time::Duration; use postgres::error::DbError; use postgres::row::Row; use postgres::types::{Json, Type}; use serde_json::Value; use sql_parser::ast::Statement; use sql_parser::parser::Parser as S...
Ok(_) => Ok(()), } } fn try_redo(&self, pgclient: &mut postgres::Client, query: &str) -> Result<(), String> { let mut actual: Vec<_> = pgclient .query(query, &[]) .map_err(|e| format!("query failed: {}", e))? .into_iter() .map(decode_row) ...
), Statement::CreateSchema { name, .. } => self.try_drop( &mut state.pgclient, &format!("DROP SCHEMA IF EXISTS {} CASCADE", name.to_string()), ), Statement::CreateSource { name, .. } => self.try_drop( &mut state.pgclient, ...
random
[ { "content": "pub fn build_write(mut cmd: BuiltinCommand) -> Result<WriteAction, String> {\n\n let path = cmd.args.string(\"path\")?;\n\n let contents = cmd.input.join(\"\\n\");\n\n cmd.args.done()?;\n\n if path.contains(path::MAIN_SEPARATOR) {\n\n // The goal isn't security, but preventing m...
Rust
src/provider/marc21.rs
wrenger/schiller-lib
fd1e45797f602db7ec037a6892b6d1bff26d287f
use crate::api; use crate::provider::BookData; use unicode_normalization::UnicodeNormalization; const ISBN_COSTS_TAG: &str = "020"; const ISBN_CODE: &str = "a"; const COSTS_CODE: &str = "c"; const EAN_TAG: &str = "024"; const EAN_CODE: &str = "a"; const TITLE_TAG: &str = "245"; const TITLE_CODE: &str = "a"; const SUB...
use crate::api; use crate::provider::BookData; use unicode_normalization::UnicodeNormalization; const ISBN_COSTS_TAG: &str = "020"; const ISBN_CODE: &str = "a"; const COSTS_CODE: &str = "c"; const EAN_TAG: &str = "024"; const EAN_CODE: &str = "a"; const TITLE_TAG: &str = "245"; const TITLE_CODE: &str = "a"; const SUB...
#[test] fn parse_costs() { fn approx_eq(a: f64, b: f64) -> bool { (a - b).abs() < 8.0 * f64::EPSILON } macro_rules! assert_approx_eq { ($left:expr, $right:expr $(,)?) => { assert!( approx_eq($left, $right), ...
o() ], publisher: "Cornelsen".into(), costs: 12.5, } ) }
function_block-function_prefixed
[ { "content": "/// Parses the isbn and removing invalid characters.\n\n///\n\n/// If the checksum is invalid the stripped invalid isbn is returned.\n\npub fn parse(input: &str) -> Result<String, String> {\n\n // Collect numeric values\n\n let isbn: Vec<u8> = input\n\n .chars()\n\n .flat_map(|...
Rust
src/routes/user.rs
afnan007a/Backpack
4100435272f4557bae815d1a4d943ff76410e24f
use actix_web::{get, http::StatusCode, patch, post, put, web, HttpResponse, Responder, Scope}; use argon2::{self, Argon2, PasswordHash, PasswordVerifier}; use lettre::AsyncTransport; use sea_orm::{ActiveModelTrait, ColumnTrait, DbErr, EntityTrait, ModelTrait, QueryFilter, Set}; use crate::{ database::entity::{user...
use actix_web::{get, http::StatusCode, patch, post, put, web, HttpResponse, Responder, Scope}; use argon2::{self, Argon2, PasswordHash, PasswordVerifier}; use lettre::AsyncTransport; use sea_orm::{ActiveModelTrait, ColumnTrait, DbErr, EntityTrait, ModelTrait, QueryFilter, Set}; use crate::{ database::entity::{user...
), ..Default::default() } .insert(&state.database) .await?; if let Some(smtp) = &state.smtp_client { let random_code = random_string(72); let success = verifications::ActiveModel { user_id: Set(user_data.id.to_owned()), code: Set(random_code.to_owned()),...
match new_password(&form.password)? { Ok(password_hashed) => password_hashed, Err(err) => return Ok(err), }
if_condition
[]
Rust
src/router/table.rs
Sasasu/placeholder
0c5973dff13c92ccbb2d1f59ff734b43c17f8b46
use log::*; use radix_trie::Trie; use radix_trie::TrieCommon; use std::net::{IpAddr, SocketAddr}; use super::peer::Host; use super::peer::Peer; #[derive(Debug)] pub struct Table { table: Trie<Vec<u8>, Peer>, } pub trait LikeRouter { fn find(&self, addr: IpAddr) -> Option<&Peer>; fn insert( &mut s...
use log::*; use radix_trie::Trie; use radix_trie::TrieCommon; use std::net::{IpAddr, SocketAddr}; use super::peer::Host; use super::peer::Peer; #[derive(Debug)] pub struct Table { table: Trie<Vec<u8>, Peer>, } pub trait LikeRouter { fn find(&self, addr: IpAddr) -> Option<&Peer>; fn insert( &mut s...
} #[test] pub fn get_by_name() { let mut table = Table::new(); table .insert( "128.66.1.0".parse().unwrap(), 24, "test1".to_string(), Host::Localhost, ) .unwrap(); table ....
let ans2 = table.find("128.66.2.1".parse().unwrap()); assert!(ans2.is_none()); table.delete("128.66.1.0".parse().unwrap(), 24).unwrap(); assert!(table.find("128.66.1.1".parse().unwrap()).is_none()); assert!(table.find("128.66.1.0".parse().unwrap()).is_none());
function_block-random_span
[ { "content": "fn parse_ip(v: IpAddr) -> Vec<u8> {\n\n match v {\n\n IpAddr::V4(v4) => v4.octets().to_vec(),\n\n IpAddr::V6(v6) => v6.octets().to_vec(),\n\n }\n\n}\n", "file_path": "src/router/mod.rs", "rank": 0, "score": 181946.492487 }, { "content": "fn read_ip(v: &[u8])...
Rust
kurobako_core/src/epi/solver/external_program.rs
hvy/kurobako
35b24596cea73148a9fa942c283e88238a313ef4
use crate::epi::channel::{MessageReceiver, MessageSender}; use crate::epi::solver::SolverMessage; use crate::problem::ProblemSpec; use crate::registry::FactoryRegistry; use crate::rng::{ArcRng, Rng as _}; use crate::solver::{Solver, SolverFactory, SolverRecipe, SolverSpec}; use crate::trial::{EvaluatedTrial, IdGen, Nex...
use crate::epi::channel::{MessageReceiver, MessageSender}; use crate::epi::solver::SolverMessage; use crate::problem::ProblemSpec; use crate::registry::FactoryRegistry; use crate::rng::{ArcRng, Rng as _}; use crate::solver::{Solver, SolverFactory, SolverRecipe, SolverSpec}; use crate::trial::{EvaluatedTrial, IdGen, Nex...
) } fn cache_key(&self) -> Vec<u8> { let mut hasher = Sha256::new(); hasher.update(&*self.path.to_string_lossy()); for arg in &self.args { hasher.update(arg.as_bytes()); } hasher.finalize().to_vec() } } impl SolverRecipe for ExternalProgramSolverRecipe { ...
ExternalProgramSolverFactory(Arc::new( ExternalProgramSolverFactoryInner { spec, child, tx: Arc::new(Mutex::new(tx)), rx: Arc::new(Mutex::new(rx)), next_solver_id: AtomicU64::new(0), }, ))
call_expression
[ { "content": "/// Recipe of a solver.\n\npub trait SolverRecipe: Clone + Send + StructOpt + Serialize + for<'a> Deserialize<'a> {\n\n /// The type of he factory creating solver instances from this recipe.\n\n type Factory: SolverFactory;\n\n\n\n /// Creates a solver factory.\n\n fn create_factory(&s...
Rust
flamelines/src/lib.rs
nongiach/flamelines
26e594e2f09aad31da2f1b3fc8301453a5c48eec
use proc_macro::TokenStream; use quote::ToTokens; use syn::{parse_quote, Stmt}; use syn::visit_mut; use syn::visit_mut::VisitMut; use syn::{File, ImplItemMethod, ItemFn}; extern crate proc_macro; type LineCallback = fn(&mut Stmt, &str); fn wrap_line_with_instrumentation(_original_line: &mut Stmt, _function_name: &s...
use proc_macro::TokenStream; use quote::ToTokens; use syn::{parse_quote, Stmt}; use syn::visit_mut; use syn::visit_mut::VisitMut; use syn::{File, ImplItemMethod, ItemFn}; extern crate proc_macro; type LineCallback = fn(&mut Stmt, &str); fn wrap_line_with_instrumentation(_original_line: &mut Stmt, _function_name: &s...
sit_mut::visit_item_fn_mut(self, node); let function_name = node.sig.ident.to_string(); self.patch_block( &mut node.block.stmts, wrap_line_with_instrumentation, &function_name, ); } fn visit_impl_item_method_mut(&mut self, node: &mut ImplItemMethod) { ...
_hook_callback: LineCallback, function_name: &str, ) { let before_line: Vec<Stmt> = parse_quote!( let __flametime_before_execution = __flamelines_before_hook(); ); fn after_line( function_name: &str, _original_line: &Stmt, origina...
random
[ { "content": "struct ImplDemo {\n\n name: String,\n\n}\n\n\n\n/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n/// example on a impl, it hooks all methods\n\n/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n\n#[flamelines::time_lines]\n\nimpl ImplDemo {\n\n fn new() -> Se...
Rust
src/traits/structure.rs
combustion-engine/nalgebra
0f9b1b1e1e06dc0f860be833a41fff4ca5e845da
use std::{f32, f64, i8, i16, i32, i64, u8, u16, u32, u64, isize, usize}; use std::slice::{Iter, IterMut}; use std::ops::{Add, Sub, Mul, Div, Rem, AddAssign, SubAssign, MulAssign, DivAssign, RemAssign, Index, IndexMut, Neg}; use num::{Float, Zero, One}; use traits::operations::{Axpy, Tran...
use std::{f32, f64, i8, i16, i32, i64, u8, u16, u32, u64, isize, usize}; use std::slice::{Iter, IterMut}; use std::ops::{Add, Sub, Mul, Div, Rem, AddAssign, SubAssign, MulAssign, DivAssign, RemAssign, Index, IndexMut, Neg}; use num::{Float, Zero, One}; use traits::operations::{Axpy, Tran...
fn canonical_basis<F: FnMut(Self) -> bool>(F); fn orthonormal_subspace_basis<F: FnMut(Self) -> bool>(&Self, F); fn canonical_basis_element(i: usize) -> Option<Self>; } pub trait Row<R> { fn nrows(&self) -> usize; fn row(&self, i: usize) -> R; fn set_row(&mut self, i: us...
Row<R> + Column<C> + Mul<R, Output = C> + Index<(usize, usize), Output = N> { } impl<N, M, R, C> Matrix<N, R, C> for M where M: Row<R> + Column<C> + Mul<R, Output = C> + Index<(usize, usize), Output = N>, C: Mul<M, Output = R>, { } pub...
random
[ { "content": "/// Traits of objects having an euclidian norm.\n\npub trait Norm: Sized {\n\n /// The scalar type for the norm (i.e. the undelying field).\n\n type NormType : BaseFloat;\n\n\n\n /// Computes the norm of `self`.\n\n #[inline]\n\n fn norm(&self) -> Self::NormType {\n\n self.no...
Rust
src/main.rs
andor0/polkahub-deployer
2dc7643e836d1528583966252ac040b73a65c54f
use actix_web::{middleware, web, App, HttpResponse, HttpServer, Responder}; use askama::Template; use reqwest::{header, Certificate, Client}; use serde_derive::Deserialize; use serde_json::json; use tokio::{fs::File, io::AsyncReadExt}; use std::env; use std::fmt::Debug; use std::path::Path; use std::sync::Arc; #[deri...
use actix_web::{middleware, web, App, HttpResponse, HttpServer, Responder}; use askama::Template; use reqwest::{header, Certificate, Client}; use serde_derive::Deserialize; use serde_json::json; use tokio::{fs::File, io::AsyncReadExt}; use std::env; use std::fmt::Debug; use std::path::Path; use std::sync::Arc; #[deri...
ait } #[actix_rt::main] async fn main() -> std::io::Result<()> { env_logger::init(); let (ip, port, workers, api_url, config_path, secret_path) = read_env(); let registry_url = read_file(&config_path, "registry") .await? .trim() .to_string(); let crt = read_file(&secret_path, ...
deploy_project_request: web::Json<DeployProjectRequest>, ) -> impl Responder { handle_deploy_project(data, deploy_project_request).aw
function_block-random_span
[ { "content": "![alt text](https://github.com/akropolisio/polkahub-deployer/blob/master/img/web3%20foundation_grants_badge_black.png \"Project supported by web3 foundation grants program\")\n\n\n\n# Polkahub Deployer\n\n\n\nThis is Polkahub Deployer.\n\n\n\n# Status\n\n\n\nPOC. Active development.\n\n\n\n# Build...
Rust
src/keyboard.rs
0xSiO/ps2-rs
e5cbb647fb961d2e40282dac58d22892beb8f02b
use crate::{ controller::Controller, error::{ControllerError, KeyboardError}, flags::KeyboardLedFlags, COMMAND_ACKNOWLEDGED, RESEND, SELF_TEST_FAILED, SELF_TEST_PASSED, }; pub use self::keyboard_type::KeyboardType; mod keyboard_type; const BUFFER_OVERRUN: u8 = 0x00; const ECHO: u8 = 0xee; const KEY_D...
use crate::{ controller::Controller, error::{ControllerError, KeyboardError}, flags::KeyboardLedFlags, COMMAND_ACKNOWLEDGED, RESEND, SELF_TEST_FAILED, SELF_TEST_PASSED, }; pub use self::keyboard_type::KeyboardType; mod keyboard_type; const BUFFER_OVERRUN: u8 = 0x00; const ECHO: u8 = 0xee; const KEY_D...
} }
match self.controller.read_data()? { SELF_TEST_PASSED => Ok(()), SELF_TEST_FAILED => Err(KeyboardError::SelfTestFailed), RESEND => Err(KeyboardError::Resend), other => Err(KeyboardError::InvalidResponse(other)), }
if_condition
[ { "content": "type Result<T> = core::result::Result<T, ControllerError>;\n\n\n\n#[repr(u8)]\n\npub(crate) enum Command {\n\n ReadInternalRam = 0x20,\n\n WriteInternalRam = 0x60,\n\n DisableMouse = 0xa7,\n\n EnableMouse = 0xa8,\n\n TestMouse = 0xa9,\n\n TestController = 0xaa,\n\n TestKeyboar...
Rust
src/node/src/node.rs
suhaibaffan/database
1ff9d8b770d893ffa53d8fdd0f004518e91763c1
use crate::query_listener::SmolQueryListener; use protocol::{listener::Secure, messages::Message, ColumnMetadata, Command, QueryListener}; use smol::Task; use sql_engine::{Handler, QueryError, QueryEvent, QueryResult}; use sql_types::SqlType; use std::sync::{ atomic::{AtomicU8, Ordering}, Arc, Mutex, }; cons...
use crate::query_listener::SmolQueryListener; use protocol::{listener::Secure, messages::Message, ColumnMetadata, Command, QueryListener}; use smol::Task; use sql_engine::{Handler, QueryError, QueryEvent, QueryResult}; use sql_types::SqlType; use std::sync::{ atomic::{AtomicU8, Ordering}, Arc, Mutex, }; cons...
mn_name_2".to_owned(), SqlType::SmallInt), ], vec![ vec!["1".to_owned(), "2".to_owned()], vec!["3".to_owned(), "4".to_owned()], ], ); assert_eq!( QueryResultMapper::map(Ok(QueryEvent::RecordsSelected(projection))), ...
SqlType::BigInt => 20, SqlType::SmallInt => 21, SqlType::Integer => 23, SqlType::Real => 700, SqlType::DoublePrecision => 701, SqlType::VarChar(_) => 1043, SqlType::Date => 1082, Sql...
random
[ { "content": "fn create_schema<P: backend::BackendStorage>(storage: &mut FrontendStorage<P>, schema_name: &str) {\n\n storage\n\n .create_schema(schema_name)\n\n .expect(\"no system errors\")\n\n .expect(\"schema is created\");\n\n}\n\n\n", "file_path": "src/storage/src/frontend/test...
Rust
generator/src/main.rs
Teaonly/Teaonly.github.io
7321778f8424b190f25d460a401552bbd1a6e1ed
extern crate tera; extern crate yaml_rust; extern crate chrono; extern crate pulldown_cmark; mod help; mod cli; mod blog; use std::fs; use std::collections::HashSet; use std::path::PathBuf; use chrono::{NaiveDate}; use glob::glob; use tera::Tera; fn create_blog_index(tera: Tera, target_dir: &PathBuf, blogs: &mut Ve...
extern crate tera; extern crate yaml_rust; extern crate chrono; extern crate pulldown_cmark; mod help; mod cli; mod blog; use std::fs; use std::collections::HashSet; use std::path::PathBuf; use chrono::{NaiveDate}; use glob::glob; use tera::Tera; fn create_blog_index(tera: Tera, target_dir: &PathBuf, blogs: &mut Ve...
fn main() { let command = cli::build_cli().get_matches(); /* ====== step.1 preparing tera engine */ let root_value = PathBuf::from(command.value_of("root").unwrap()); let root_path = fs::canonicalize(&root_value).unwrap(); let root_dir = root_path.to_str().unwrap(); let target_dir = PathB...
function_block-full_function
[ { "content": "pub fn render(tera: &mut tera::Tera, htdoc: &str, blog: &Blog) -> Result<String, String> {\n\n let mut context = Context::new();\n\n\n\n context.insert(\"title\", &blog.title);\n\n context.insert(\"desc\", &blog.desc);\n\n context.insert(\"published_date\", &blog.date);\n\n context....
Rust
compiler/src/yul/mappers/functions.rs
satyamakgec/fe
b0d8ccd25ddea624d1e3b7e56caa269211f37a0f
use crate::yul::mappers::{ assignments, declarations, expressions, }; use crate::yul::names; use crate::yul::operations::data as data_operations; use fe_analyzer::namespace::types::{ FeSized, Type, }; use fe_analyzer::{ Context, ExpressionAttributes, }; use fe_parser::ast as fe; use fe_parse...
use crate::yul::mappers::{ assignments, declarations, expressions, }; use crate::yul::names; use crate::yul::operations::data as data_operations; use fe_analyzer::namespace::types::{ FeSized, Type, }; use fe_analyzer::{ Context, ExpressionAttributes, }; use fe_parser::ast as fe; use fe_parse...
let test = expressions::expr(context, test); let yul_body = multiple_func_stmt(context, body); return block_statement! { (for {} ([test]) {} { [yul_body...] }) }; } unreachable!() }
function_block-function_prefix_line
[ { "content": "/// Builds a Yul statement from a Fe assignment.\n\npub fn assign(context: &Context, stmt: &Node<fe::FuncStmt>) -> yul::Statement {\n\n if let fe::FuncStmt::Assign { targets, value } = &stmt.kind {\n\n if targets.len() > 1 {\n\n unimplemented!(\"multiple assignment targets\")\...
Rust
rustpad-client/src/client.rs
komonad/rustpad
039d5e368058147b410c73cb50cfd372379bdb6b
use rustpad_server::rustpad::{ServerMsg, UserOperation, UserInfo, CursorData, ClientMsg}; use std::mem::swap; use operational_transform::{OperationSeq, Operation}; use std::collections::HashMap; use futures_channel::mpsc::UnboundedSender; use tokio_tungstenite::tungstenite::Message; use std::sync::Arc; use parking_lot:...
use rustpad_server::rustpad::{ServerMsg, UserOperation, UserInfo, CursorData, ClientMsg}; use std::mem::swap; use operational_transform::{OperationSeq, Operation}; use std::collections::HashMap; use futures_channel::mpsc::UnboundedSender; use tokio_tungstenite::tungstenite::Message; use std::sync::Arc; use parking_lot:...
} trace!("trying to transform cursor by {:?}", operation); self.transform_cursor(&operation); trace!("transformed cursor by {:?}", operation); } fn update_cursors(&mut self) { self.event_sink.as_ref().unwrap().submit_command( USER_CURSOR_UPDATE_SELECTOR, ...
\"operation\": {} }} }}", self.revision, serde_json::to_string(operation).unwrap() ) )).ok() } pub fn update_and_send_cursor_data(&mut self, selection: (u32, u32)) -> Option<()> { self.cursor_data = CursorData { cursors: vec![selection.0]...
random
[ { "content": "#[allow(clippy::trivially_copy_pass_by_ref)]\n\npub fn offset_for_delete_backwards(region: &Selection, text: &impl EditableText) -> usize {\n\n if !region.is_caret() {\n\n region.min()\n\n } else {\n\n backspace_offset(text, region.active)\n\n }\n\n}\n", "file_path": "ru...
Rust
src/app.rs
yukimemi/dot
57a0227b609884427e5073426567268ceaf24ca2
use std::borrow::Borrow; use std::env; use std::path::Path; use crate::dotfiles::Dotfiles; use crate::util; use crate::errors::Result; use url::Url; use regex::Regex; use dirs; #[cfg(windows)] use crate::windows; pub struct App { dotfiles: Dotfiles, dry_run: bool, verbose: bool, } impl App { pub fn n...
use std::borrow::Borrow; use std::env; use std::path::Path; use crate::dotfiles::Dotfiles; use crate::util; use crate::errors::Result; use url::Url; use regex::Regex; use dirs; #[cfg(windows)] use crate::windows; pub struct App { dotfiles: Dotfiles, dry_run: bool, verbose: bool, } impl App { pub fn n...
pub fn command_clone(&self, query: &str) -> Result<i32> { let url = resolve_url(query)?; let dotdir = self.dotfiles.root_dir().to_string_lossy(); util::wait_exec("git", &["clone", url.as_str(), dotdir.borrow()], None, ...
let dotdir = init_envs()?; let dotfiles = Dotfiles::new(Path::new(&dotdir).to_path_buf()); Ok(App { dotfiles: dotfiles, dry_run: dry_run, verbose: verbose, }) }
function_block-function_prefix_line
[ { "content": "pub fn is_elevated() -> Result<bool, &'static str> {\n\n let token = open_process_token(winnt::TOKEN_QUERY)?;\n\n\n\n let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 };\n\n let mut cb_size: u32 = mem::size_of_val(&elevation) as u32;\n\n let ret = unsafe {\n\n GetTokenIn...
Rust
examples/read_metadata.rs
oebb-digirail/parquet2
37748686c90956a8aeebc11e4cd7c583880ae91a
use parquet2::bloom_filter; use parquet2::error::Result; use parquet2::encoding::Encoding; use parquet2::page::{split_buffer, DataPage}; use parquet2::schema::types::PhysicalType; fn deserialize(page: &DataPage) { let (_rep_levels, _def_levels, _values_buffer) = split_buffer(page); match ( ...
use parquet2::bloom_filter; use parquet2::error::Result; use parquet2::encoding::Encoding; use parquet2::page::{split_buffer, DataPage}; use parquet2::schema::types::PhysicalType; fn deserialize(page: &DataPage) { let (_rep_levels, _def_levels, _values_buffer) = split_buffer(page); match ( ...
unwrap(); let _min: i32 = stats.min_value.unwrap(); let _max: i32 = stats.max_value.unwrap(); let _null_count: i64 = stats.null_count.unwrap(); } PhysicalType::Int64 => { let stats = stats .as_any() ...
function_block-function_prefix_line
[ { "content": "pub fn write_column_index<W: Write>(writer: &mut W, pages: &[PageWriteSpec]) -> Result<u64> {\n\n let index = serialize_column_index(pages)?;\n\n let mut protocol = TCompactOutputProtocol::new(writer);\n\n Ok(index.write_to_out_protocol(&mut protocol)? as u64)\n\n}\n\n\n", "file_path"...
Rust
src/error.rs
peterschwarz/sawtooth-pbft
f9b5372fc028d5c47ad4f2a7c6947cbc77272a50
/* * Copyright 2018 Bitwise IO, Inc. * * 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 agree...
/* * Copyright 2018 Bitwise IO, Inc. * * 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 agree...
} impl fmt::Display for PbftError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: ", self.description())?; match self { PbftError::SerializationError(pb_err) => pb_err.fmt(f), PbftError::WrongNumMessages(t, exp, got) => write!( f, ...
WrongNumMessages(_, _, _) => "WrongNumMessages", BlockMismatch(_, _) => "BlockMismatch", MessageMismatch(_) => "MessageMismatch", ViewMismatch(_, _) => "ViewMismatch", InvalidSequenceNumber(_, _, _) => "InvalidSequenceNumber", InternalError(_) => "InternalErro...
function_block-function_prefix_line
[ { "content": "/// Verifies that the SHA-512 hash of the given content matches the given hash\n\npub fn verify_sha512(content: &[u8], content_hash: &[u8]) -> Result<(), PbftError> {\n\n let computed_sha512 = hash_sha512(&content);\n\n\n\n if computed_sha512 != content_hash {\n\n Err(PbftError::Inter...
Rust
src/lib.rs
bob-yamaguchi/tex_shooter
88f5afdf22635f046e7ce14e1d2c2dcf97e33755
use std::collections::HashMap; use std::path::{/*Path, */PathBuf}; use serde::{Deserialize, Serialize}; mod config; use config::{ProjectSettings}; mod camera; use edsdk::wrap; #[derive(Serialize, Deserialize, Debug)] struct RecieveInfo{ id: i32, name: String, value: String, info: HashMap<...
use std::collections::HashMap; use std::path::{/*Path, */PathBuf}; use serde::{Deserialize, Serialize}; mod config; use config::{ProjectSettings}; mod camera; use edsdk::wrap; #[derive(Serialize, Deserialize, Debug)] struct RecieveInfo{ id: i32, name: String, value: String, info: HashMap<...
pub fn send_image<T>(&self, webview: &mut web_view::WebView<T>, image_name: &str, func_name: &str) { let mut path = std::env::current_exe().unwrap(); path.pop(); path.push(image_name); let jpg = std::fs::read(&path).unwrap(); let _ = webview.eval(&format!("{}...
t current_path = std::env::current_exe().unwrap(); current_path.pop(); let result = web_view::DialogBuilder::new(webview).choose_directory("select a project root directory", current_path); if result.is_ok(){ let path = result.unwrap(); if path.is_some(){ ...
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn convert_av(av_str: &str)->types::ApertureValue{\n\n match av_str{\n\n \"1.0\"=>{types::ApertureValue::Av1_0}\n\n \"1.1\"=>{types::ApertureValue::Av1_1}\n\n \"1.2\"=>{types::ApertureValue::Av1_2}\n\n \"1.4\"=>{types::ApertureValue::Av1_4}...
Rust
rld2hack/src/plugins/plugin2.rs
rlabrecque/rl-diablo-2-hack
7a2a424e0052990e1782b12a4fbec800e6858b36
use crate::plugincore::{plugin::Plugin, plugin_info::PluginInfo}; pub fn get_info() -> PluginInfo { PluginInfo { name: "Plugin2".into(), description: "Second plugin!".into(), author: "Riley Labrecque".into(), version: "1.0.1".into(), plugin: Box::new(Plugin2 {}), } } st...
use crate::plugincore::{plugin::Plugin, plugin_info::PluginInfo}; pub fn get_info() -> PluginInfo { PluginInfo { name: "Plugin2".into(), description: "Second plugin!".into(), author: "Riley Labrecque".into(), version: "1.0.1".into(), plugin: Box::new(Plugin2 {}), } } st...
}
e.game)); println!("Chat Message: {}", d2::variables::get_chat_message(&d2core.game)); println!("Orfice Id: {}", d2::variables::get_orifice_id(&d2core.game)); println!( "Cursor Item Mode: {}", d2::variables::get_cursor_item_mode(&d2core.game) ); println!(...
function_block-function_prefixed
[ { "content": "pub fn get_info() -> PluginInfo {\n\n PluginInfo {\n\n name: \"Playground\".into(),\n\n description: \"First plugin!\".into(),\n\n author: \"Riley Labrecque\".into(),\n\n version: \"1.0.0\".into(),\n\n plugin: Box::new(Playground {}),\n\n }\n\n}\n\n\n\npub ...
Rust
src/lib.rs
sklopi/winit
a630aba5e283e7745040a9e162e9dd4fa4b553d2
#[macro_use] extern crate lazy_static; #[macro_use] extern crate shared_library; extern crate libc; #[cfg(target_os = "windows")] extern crate winapi; #[cfg(target_os = "windows")] extern crate kernel32; #[cfg(target_os = "windows")] extern crate shell32; #[cfg(target_os = "windows")] extern crate gdi32; #[cfg(tar...
#[macro_use] extern crate lazy_static; #[macro_use] extern crate shared_library; extern crate libc; #[cfg(target_os = "windows")] extern crate winapi; #[cfg(target_os = "windows")] extern crate kernel32; #[cfg(target_os = "windows")] extern crate shell32; #[cfg(target_os = "windows")] extern crate gdi32; #[cfg(tar...
pub fn new() -> EventsLoop { EventsLoop { events_loop: Arc::new(platform::EventsLoop::new()), } } #[inline] pub fn poll_events<F>(&self, callback: F) where F: FnMut(Event) { self.events_loop.poll_events(callback) } #[inline] pub f...
target_os = "openbsd"))] extern crate x11_dl; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))] #[macro_use(wayland_env,declare_handler)] extern crate wayland_client; use std::sync::Arc; pub use events::*; pub use window::{AvailableMonitorsIter, MonitorId, get_ava...
random
[ { "content": "// Convert the `cocoa::base::id` associated with a window to a usize to use as a unique identifier\n\n// for the window.\n\npub fn get_window_id(window_cocoa_id: cocoa::base::id) -> Id {\n\n Id(window_cocoa_id as *const objc::runtime::Object as usize)\n\n}\n\n\n\nunsafe fn nswindow_set_min_dime...
Rust
terra/contracts/cw20-wrapped/src/contract.rs
cryptorites-scotti/wormhole
2e220a6f76a1ec03364fa2fac2e571b9824744f8
use cosmwasm_std::{ to_binary, Binary, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, Uint128, WasmMsg, }; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cw2::set_contract_version; use cw20_legacy::{ allowances::{ ...
use cosmwasm_std::{ to_binary, Binary, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, Uint128, WasmMsg, }; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cw2::set_contract_version; use cw20_legacy::{ allowances::{ ...
} pub fn query_wrapped_asset_info(deps: Deps) -> StdResult<WrappedAssetInfoResponse> { let info = wrapped_asset_info_read(deps.storage).load()?; Ok(WrappedAssetInfoResponse { asset_chain: info.asset_chain, asset_address: info.asset_address, bridge: deps.api.addr_humanize(&info.bridge)?...
Ok(TokenInfoResponse { name: info.name + " (Wormhole)", symbol: info.symbol, decimals: info.decimals, total_supply: info.total_supply, })
call_expression
[ { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> {\n\n match msg {\n\n ExecuteMsg::RegisterAssetHook { asset_id } => {\n\n handle_register_asset(deps, env, info, &asset_id...
Rust
src/twi0.rs
blueluna/nrf51
7ce3ab44d3a99a90f779bda07e1642e581e87a9a
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Start 2-Wire master receive sequence."] pub tasks_startrx: TASKS_STARTRX, _reserved0: [u8; 4usize], #[doc = "0x08 - Start 2-Wire master transmit sequence."] pub tasks_starttx: TASKS_STARTTX, _reserved1: [u8; 8usize...
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Start 2-Wire master receive sequence."] pub tasks_startrx: TASKS_STARTRX,
NCY { register: ::vcell::VolatileCell<u32>, } #[doc = "Two-wire frequency."] pub mod frequency; #[doc = "Address used in the two-wire transfer."] pub struct ADDRESS { register: ::vcell::VolatileCell<u32>, } #[doc = "Address used in the two-wire transfer."] pub mod address; #[doc = "Peripheral power control."] p...
_reserved0: [u8; 4usize], #[doc = "0x08 - Start 2-Wire master transmit sequence."] pub tasks_starttx: TASKS_STARTTX, _reserved1: [u8; 8usize], #[doc = "0x14 - Stop 2-Wire transaction."] pub tasks_stop: TASKS_STOP, _reserved2: [u8; 4usize], #[doc = "0x1c - Suspend 2-Wire transaction."] ...
random
[ { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\" Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::EVENTS_STARTED {\n\n #[doc = r\" Modifies the contents of the register\"]\n\n #[inline]\n\n pub fn ...
Rust
src/day_15/cave_map.rs
DirtGrubDylan/adventofcode2021
e52a9f14904504f47b611ca0af2ca98f9976bff9
use crate::util::location::Location; use crate::util::point_2d::Point2d; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap, HashSet}; const RELATIVE_NEIGHBOR_POINTS: [Point2d<i32>; 4] = [ Point2d { x: 0, y: 1 }, Point2d { x: 1, y: 0 }, Point2d { x: 0, y: -1 }, Point2d { x: -1,...
use crate::util::location::Location; use crate::util::point_2d::Point2d; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap, HashSet}; const RELATIVE_NEIGHBOR_POINTS: [Point2d<i32>; 4] = [ Point2d { x: 0, y: 1 }, Point2d { x: 1, y: 0 }, Point2d { x: 0, y: -1 }, Point2d { x: -1,...
}
let expected = Some(315); let result = cave_map.get_lowest_total_risk_level_to_exit(); assert_eq!(result, expected); }
function_block-function_prefix_line
[ { "content": "pub fn str_slice_to_string_vector(input: &[&str]) -> Vec<String> {\n\n input.iter().map(|s| s.to_string()).collect()\n\n}\n", "file_path": "src/util/test_tools.rs", "rank": 0, "score": 317461.1015523975 }, { "content": "pub fn to_string_vector(file_name: &str) -> Result<Vec<...
Rust
src/refine/process/mod.rs
Eonm/refine-io
04447b82fa6f77fdd59273426b4894e97923eda8
use crate::RefineProject; use std::error::Error; use crate::consts; use crate::utils; use std::thread; use std::time; pub enum ProcessMod { Sync, Async } pub trait Process { fn process(&mut self, process_mod: ProcessMod) -> Result<RefineProject, Box<dyn Error>>; fn apply_operations(&mut self) -> Resul...
use crate::RefineProject; use std::error::Error; use crate::consts; use crate::utils; use std::thread; use std::time; pub enum ProcessMod { Sync, Async } pub trait Process { fn process(&mut self, process_mod: ProcessMod) -> Result<RefineProject, Box<dyn Error>>; fn apply_operations(&mut self) -> Resul...
let data = project.print("tsv".into()).expect("Failed to get remote data"); assert_eq!(data, "_ - subjectFR - subjectFR\techo-1\n1\t1\n"); project.delete().expect("Failed to delete project"); } #[test] fn test_get_async_process() { let mut project = RefineInit::...
= RefineInit::from_string("_ - subjectFR - subjectFR\n1", "tsv", None, None).expect("Failed to create project"); project.refine_script = Some("./playground/async_processes.json".into()); project.process(ProcessMod::Sync).expect("Failed to apply operations");
function_block-random_span
[ { "content": "fn download_data(project_id: &str, format: &str) -> Result<reqwest::Response, Box<dyn Error>> {\n\n info!(\"downloading data\");\n\n let mut request_params = HashMap::new();\n\n request_params.insert(\"project\",project_id);\n\n request_params.insert(\"engine\", r#\"'{\"facets\": [], \...
Rust
src/runtime/src/operators.rs
cleanbaja/Mercenary
ea21c1307ace10b626bebfd3cc81c3d705c535b5
pub mod ternary { use std::{borrow::Cow, cell::RefCell}; use crate::{ runtime::Runtime, value::{NativeFunction, Value}, }; pub const INDEX_SET: NativeFunction = NativeFunction { name: Cow::Borrowed("==[]"), arity: 3, fun_ptr: index_set, }; fn index_set(...
pub mod ternary { use std::{borrow::Cow, cell::RefCell}; use crate::{ runtime::Runtime, value::{NativeFunction, Value}, }; pub const INDEX_SET: NativeFunction = NativeFunction { name: Cow::Borrowed("==[]"), arity: 3, fun_ptr: index_set, }; fn index_set(...
runtime.push_value_to_stack(Boolean(a.truthy() && b.truthy())) } fn or(runtime: &mut Runtime) { let b = runtime.pop_value_from_stack(); let a = runtime.pop_value_from_stack(); runtime.push_value_to_stack(Boolean(a.truthy() || b.truthy())) } fn add(runtime: &mut Runtime) { ...
tion { name: Cow::Borrowed("~&&"), arity: 2, fun_ptr: and, }; pub const OR: NativeFunction = NativeFunction { name: Cow::Borrowed("~||"), arity: 2, fun_ptr: or, }; pub const ADD: NativeFunction = NativeFunction { name: Cow::Borrowed("~+"), ...
random
[]