lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/window/event.rs
Arandur/rust-sfml
cb62603ae36f0589b5d68b3cf09cf76c192211c0
/* * Rust-SFML - Copyright (c) 2013 Letang Jeremy. * * The original software, SFML library, is provided by Laurent Gomila. * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission...
/* * Rust-SFML - Copyright (c) 2013 Letang Jeremy. * * The original software, SFML library, is provided by Laurent Gomila. * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission...
ouseMoved { x: i32, y: i32 }, MouseEntered, MouseLeft, JoystickButtonPressed { joystickid: u32, button: u32 }, JoystickButtonReleased { joystickid: u32, button: u32 }, ...
g commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim * that you wrote the original software. If you use this software in a product, * an acknowledgment in the product docume...
random
[ { "content": "pub fn get_wrapped_event(event: &mut ::csfml_window_sys::sfEvent) -> Option<Event> {\n\n let type_ = unsafe { *type_(event) };\n\n\n\n Some(match type_ {\n\n sfEventType::sfEvtClosed => Event::Closed,\n\n sfEventType::sfEvtResized => size(event),\n\n sfEventType::sfEvtLo...
Rust
src/lib.rs
ogoodman/tiny-nix-ipc
39d06f77517095309b2ad9f134dd272ac6149198
extern crate nix; #[macro_use] extern crate error_chain; #[cfg(any(feature = "ser_cbor", feature = "ser_json", feature = "ser_bincode"))] extern crate serde; #[cfg(feature = "ser_cbor")] extern crate serde_cbor; #[cfg(feature = "ser_json")] extern crate serde_json; #[cfg(feature = "ser_bincode")] extern crate bincode; ...
extern crate nix; #[macro_use] extern crate error_chain; #[cfg(any(feature = "ser_cbor", feature = "ser_json", feature = "ser_bincode"))] extern crate serde; #[cfg(feature = "ser_cbor")] extern crate serde_cbor; #[cfg(feature = "ser_json")] extern crate serde_json; #[cfg(feature = "ser_bincode")] extern crate bincode; ...
f, data: &[u8], fds: Option<&[RawFd]>) -> Result<usize> { let len = data.len() as u64; let iov = [IoVec::from_slice(unsafe { slice::from_raw_parts((&len as *const u64) as *const u8, mem::size_of::<u64>()) }), IoVec::from_slice(data)]; self.send_iovec(&iov[..], fds) } ...
with_len(buf_size)?; if bytes != len as usize + mem::size_of::<u64>() { bail!(ErrorKind::WrongRecvLength); } Ok((bincode::deserialize(&buf[..])?, rfds)) } pub fn send_iovec(&mut self, iov: &[IoVec<&[u8]>], fds: Option<&[RawFd]>) -> Result<usize> { if l...
random
[ { "content": "[![unlicense](https://img.shields.io/badge/un-license-green.svg?style=flat)](http://unlicense.org)\n\n[![crates.io](https://img.shields.io/crates/v/tiny-nix-ipc.svg)](https://crates.io/crates/tiny-nix-ipc)\n\n\n\n# tiny-nix-ipc\n\n\n\nA small and convenient Rust library for using (UNIX domain) soc...
Rust
mongodb-redis/src/errors.rs
rkudryashov/exploring-rust-ecosystem
56f17d089d7383313981dbd8208527158bd3bb65
use actix_web::error::ResponseError; use actix_web::http::header::ContentType; use actix_web::http::StatusCode; use actix_web::{HttpResponse, HttpResponseBuilder}; use derive_more::{Display, Error}; use log::error; use redis::RedisError; use serde::Serialize; #[derive(Debug, Display, Error)] pub enum CustomError { ...
use actix_web::error::ResponseError; use actix_web::http::header::ContentType; use actix_web::http::StatusCode; use actix_web::{HttpResponse, HttpResponseBuilder}; use derive_more::{Display, Error}; use log::error; use redis::RedisError; use serde::Serialize; #[derive(Debug, Display, Error)] pub enum CustomError { ...
String::from(name) } } impl ResponseError for CustomError { fn status_code(&self) -> StatusCode { match *self { CustomError::MongoDbError { message: _ } => StatusCode::INTERNAL_SERVER_ERROR, CustomError::RedisError { message: _ } => StatusCode::INTERNAL_SERVER_ERROR, ...
let name = match self { Self::MongoDbError { message: _ } => "MongoDB error", Self::RedisError { message: _ } => "Redis error", Self::NotFound { message: _ } => "Resource not found", Self::InternalError => "Internal error", Self::TooManyRequests { ...
assignment_statement
[ { "content": "fn get_ip_addr(req: &HttpRequest) -> Result<String, CustomError> {\n\n Ok(req\n\n .peer_addr()\n\n .ok_or(CustomError::InternalError)?\n\n .ip()\n\n .to_string())\n\n}\n", "file_path": "mongodb-redis/src/handlers.rs", "rank": 0, "score": 119936.6152894974...
Rust
src/adapt.rs
kcking/oddio
1e2f392365714d549de453d623914d2a10e94af5
use core::cell::Cell; use crate::{math::Float, Filter, Frame, Signal}; pub struct Adapt<T: ?Sized> { options: AdaptOptions, avg_squared: Cell<f32>, inner: T, } impl<T> Adapt<T> { pub fn new(signal: T, initial_rms: f32, options: AdaptOptions) -> Self { Self { op...
use core::cell::Cell; use crate::{math::Float, Filter, Frame, Signal}; pub struct Adapt<T: ?Sized> { options: AdaptOptions, avg_squared: Cell<f32>, inner: T, } impl<T> Adapt<T> { pub fn new(signal: T, initial_rms: f32, options: AdaptOptions) -> Self { Self { op...
fn remaining(&self) -> f32 { self.inner.remaining() } } impl<T> Filter for Adapt<T> { type Inner = T; fn inner(&self) -> &T { &self.inner } } #[cfg(test)] mod tests { use super::*; use crate::Constant; #[test] fn smoke() { const LOW: f32 = 0.1; co...
fn sample(&self, interval: f32, out: &mut [T::Frame]) { let alpha = 1.0 - (-interval / self.options.tau).exp(); self.inner.sample(interval, out); for x in out { let sample = x.channels().iter().sum::<f32>(); self.avg_squared .set(sample * sample * alpha + ...
function_block-full_function
[ { "content": "/// Populate `out` with frames from `signal` at `sample_rate`\n\n///\n\n/// Convenience wrapper for [`Signal::sample`].\n\npub fn run<S: Signal + ?Sized>(signal: &S, sample_rate: u32, out: &mut [S::Frame]) {\n\n let interval = 1.0 / sample_rate as f32;\n\n signal.sample(interval, out);\n\n}\...
Rust
tunshell-client/src/stream/crypto/web_sys.rs
cooltvapp/tunshell
e3196bf543ddffd9ff9125fcfd21360e594d2d56
use super::super::EncryptedMessage; use anyhow::{Error, Result}; use futures::Future; use js_sys::{Array, JsString, Uint8Array}; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen_futures::JsFuture; use web_sys::{AesDerivedKeyParams, AesGcmParams, Crypto, CryptoKey, Pbkdf2Params}; #[derive(Clone)] pub struct Key(Cr...
use super::super::EncryptedMessage; use anyhow::{Error, Result}; use futures::Future; use js_sys::{Array, JsString, Uint8Array}; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen_futures::JsFuture; use web_sys::{AesDerivedKeyParams, AesGcmParams, Crypto, CryptoKey, Pbkdf2Params}; #[derive(Clone)] pub struct Key(Cr...
async fn import_key(key: &[u8]) -> Result<CryptoKey> { let key_material = { let promise = crypto()? .subtle() .import_key_with_str( "raw", &Uint8Array::from(key), "PBKDF2", false, &Array::of2(&JsString:...
fn crypto() -> Result<Crypto> { Ok(web_sys::window() .ok_or_else(|| Error::msg("could not get 'window' reference"))? .crypto() .map_err(|_| Error::msg("could not get 'window.crypto' reference"))?) }
function_block-full_function
[ { "content": "fn send_sync<T>(tx: &mut Sender<T>, value: T) -> Result<()>\n\nwhere\n\n T: Sized + Sync + Send + std::fmt::Debug + 'static,\n\n{\n\n match tx.try_send(value) {\n\n Ok(_) => {}\n\n Err(err) => match err {\n\n TrySendError::Closed(_) => return Err(Error::msg(\"channel...
Rust
src/sse.rs
pthariensflame/highway-rs
796831cae0bbfae410766c1131a1038b87548d1a
use crate::internal::unordered_load3; use crate::internal::{Filled, HashPacket, PACKET_SIZE}; use crate::key::Key; use crate::traits::HighwayHash; use crate::v2x64u::V2x64U; use core::arch::x86_64::*; #[derive(Debug, Default, Clone)] pub struct SseHash { key: Key, buffer: HashPacket, v0L: V2x64U, v0H: ...
use crate::internal::unordered_load3; use crate::internal::{Filled, HashPacket, PACKET_SIZE}; use crate::key::Key; use crate::traits::HighwayHash; use crate::v2x64u::V2x64U; use core::arch::x86_64::*; #[derive(Debug, Default, Clone)] pub struct SseHash { key: Key, buffer: HashPacket, v0L: V2x64U, v0H: ...
#[target_feature(enable = "sse4.1")] unsafe fn rotate_32_by(&mut self, count: i64) { let vL = &mut self.v1L; let vH = &mut self.v1H; let count_left = _mm_cvtsi64_si128(count); let count_right = _mm_cvtsi64_si128(32 - count); let shifted_leftL = V2x64U::from(_mm_sll_epi3...
let size = self.buffer.len(); let vsize_mod32 = _mm_set1_epi32(size as i32); self.v0L += V2x64U::from(vsize_mod32); self.v0H += V2x64U::from(vsize_mod32); self.rotate_32_by(size as i64); let (packetH, packetL) = SseHash::remainder(self.buffer.as_slice()); self.update(pack...
function_block-function_prefix_line
[ { "content": "fn hash<H>() -> std::io::Result<u64>\n\nwhere\n\n H: std::hash::Hasher,\n\n H: std::io::Write,\n\n H: Default,\n\n{\n\n let mut reader = \"foobar\".as_bytes();\n\n let mut hasher = H::default();\n\n std::io::copy(&mut reader, &mut hasher)?;\n\n Ok(std::hash::Hasher::finish(&ha...
Rust
src/sinks/aws_kinesis_firehose.rs
alakahakai/vector
c8654461f930d8f1318ab1dc81f12337ebeef2c9
use crate::{ dns::Resolver, event::{self, Event}, region::RegionOrEndpoint, sinks::util::{ encoding::{EncodingConfig, EncodingConfiguration}, retries2::RetryLogic, rusoto, service2::TowerRequestConfig, sink::Response, BatchConfig, BatchSettings, Compressio...
use crate::{ dns::Resolver, event::{self, Event}, region::RegionOrEndpoint, sinks::util::{ encoding::{EncodingConfig, EncodingConfiguration}, retries2::RetryLogic, rusoto, service2::TowerRequestConfig, sink::Response, BatchConfig, BatchSettings, Compressio...
on: RegionOrEndpoint::with_endpoint("http://localhost:4573".into()), encoding: EncodingConfig::from(Encoding::Json), compression: Compression::None, batch: BatchConfig { max_events: Some(2), ..Default::default() }, request: Tow...
fn input_type(&self) -> DataType { DataType::Log } fn sink_type(&self) -> &'static str { "aws_kinesis_firehose" } } impl KinesisFirehoseSinkConfig { async fn healthcheck(self, client: KinesisFirehoseClient) -> crate::Result<()> { let stream_name = self.stream_name; ...
random
[ { "content": "pub fn client(resolver: Resolver) -> crate::Result<Client> {\n\n let settings = MaybeTlsSettings::enable_client()?;\n\n let client = util::http::HttpClient::new(resolver, settings)?;\n\n Ok(HttpClient { client })\n\n}\n\n\n", "file_path": "src/sinks/util/rusoto.rs", "rank": 0, ...
Rust
src/generators/slice_generator.rs
AndWass/pushgen
148fcc196cae2b98372c638f7c2096faf568389b
use crate::{Generator, GeneratorResult, ReverseGenerator, ValueResult}; use core::num::NonZeroUsize; #[derive(Clone)] pub struct SliceGenerator<'a, T> { slice: &'a [T], begin: usize, end: usize, } impl<'a, T> SliceGenerator<'a, T> { #[in...
use crate::{Generator, GeneratorResult, ReverseGenerator, ValueResult}; use core::num::NonZeroUsize; #[derive(Clone)] pub struct SliceGenerator<'a, T> { slice: &'a [T], begin: usize, end: usize, } impl<'a, T> SliceGenerator<'a, T> { #[in...
#[inline] fn try_advance_back(&mut self, n: NonZeroUsize) -> (usize, GeneratorResult) { let n = n.get(); let available = self.end - self.begin; if n > available { self.end = self.begin; (available, GeneratorResult::Complete) } else { self.end...
let end_back = self.begin; while self.end > end_back { if output(unsafe { self.slice.get_unchecked(self.end - 1) }) == ValueResult::Stop { self.end -= 1; return GeneratorResult::Stopped; } self.end -= 1; } ...
function_block-function_prefix_line
[ { "content": "#[inline(always)]\n\npub fn set_some<T>(option: &mut Option<T>, value: T) -> &mut T {\n\n *option = Some(value);\n\n unsafe { unwrap_unchecked(option.as_mut()) }\n\n}\n", "file_path": "src/structs/utility.rs", "rank": 0, "score": 149367.99481494504 }, { "content": "pub fn...
Rust
src/main.rs
getreu/stringsext
1d7efab7414290a89c62c0b0ecc5d6df31343599
extern crate encoding_rs; mod finding; mod finding_collection; mod help; mod helper; mod input; mod mission; mod options; mod scanner; use crate::finding::OUTPUT_LINE_METADATA_LEN; use crate::finding_collection::FindingCollection; use crate::help::help; use crate::input::Slicer; use crate::mission::MISSIONS; use cr...
extern crate encoding_rs; mod finding; mod finding_collection; mod help; mod helper; mod input; mod mission; mod options; mod scanner; use crate::finding::OUTPUT_LINE_METADATA_LEN; use crate::finding_collection::FindingCollection; use crate::help::help; use crate::input::Slicer; use crate::mission::MISSIONS; use cr...
}
let f = iter.next().unwrap(); assert_eq!(f.s, "qrstuvw"); assert_eq!(f.position, 5000); assert_eq!(f.position_precision, Precision::After); assert_eq!(f.mission.mission_id, 0); let f = iter.next().unwrap(); assert_eq!(f.s, "abcdefgÜhijklmn"); assert_eq!(f.positio...
function_block-function_prefix_line
[ { "content": "pub fn help() {\n\n if ARGS.version {\n\n println!(\"Version {}, {}\", VERSION.unwrap_or(\"unknown\"), AUTHOR);\n\n process::exit(0);\n\n };\n\n\n\n if ARGS.debug_option {\n\n println!(\"GIVEN COMMANDLINE-ARGUMENTS\\n\");\n\n println!(\"Input files\\n----------...
Rust
openmls/src/group/mls_group/processing.rs
pulkitkothari/openmls
f1b83735315c517bbdd8c7db432c6a08e924b3b0
use std::mem; use core_group::{ create_commit_params::CreateCommitParams, proposals::QueuedProposal, staged_commit::StagedCommit, }; use super::*; impl MlsGroup { pub fn parse_message( &mut self, message: MlsMessageIn, backend: &impl OpenMlsCryptoProvider,...
use std::mem; use core_group::{ create_commit_params::CreateCommitParams, proposals::QueuedProposal, staged_commit::StagedCommit, }; use super::*; impl MlsGroup { pub fn parse_message( &mut self, message: MlsMessageIn, backend: &impl OpenMlsCryptoProvider,...
pub fn merge_pending_commit(&mut self) -> Result<(), MlsGroupError> { match &self.group_state { MlsGroupState::PendingCommit(_) => { let old_state = mem::replace(&mut self.group_state, MlsGroupState::Operational); if let MlsGroupState::PendingCommit(pe...
mmit( &mut self, staged_commit: StagedCommit, ) -> Result<(), MlsGroupError> { if staged_commit.self_removed() { self.group_state = MlsGroupState::Inactive; } self.flag_state_change(); self.group .merge_staged_commi...
function_block-function_prefixed
[ { "content": "pub fn backends(backend: &impl OpenMlsCryptoProvider) {}\n\n\n\n// === Ciphersuites ===\n\n\n\n// For now we support all ciphersuites, regardless of the backend\n\n\n\n#[allow(non_snake_case)]\n\n#[template]\n\n#[rstest(ciphersuite,\n\n case::MLS10_128_DHKEMX25519_AES128GCM_SHA256_Ed25519(Confi...
Rust
src/result/error.rs
msorvig/windows-rs
bf5efbf4933e3e44ff9322735065fa88d64d281c
use crate::*; #[derive(Clone, PartialEq)] pub struct Error { code: ErrorCode, info: Option<IRestrictedErrorInfo>, } impl Error { pub fn new(code: ErrorCode, message: &str) -> Self { let message: HString = message.into(); unsafe { let _ = Ro...
use crate::*; #[derive(Clone, PartialEq)] pub struct Error { code: ErrorCode, info: Option<IRestrictedErrorInfo>, } impl Error { pub fn new(code: ErrorCode, message: &str) -> Self { let message: HString = message.into(); unsafe { let _ = Ro...
return Self { code, info: Some(info), }; } if let Ok(info) = IErrorInfo::from_thread() { Self::new(code, &info.description()) } else { Self::new(code, "") } } } impl std::fmt::Debug for Error { fn...
if let Ok(capture) = info.cast::<ILanguageExceptionErrorInfo2>() { capture.capture_propagation_context(); }
if_condition
[ { "content": "/// Change a CamelCase name to snake case.\n\npub fn to_snake(camel: &str) -> String {\n\n debug_assert!(!camel.is_empty());\n\n let snake = String::with_capacity(camel.len());\n\n append_to_snake(snake, camel)\n\n}\n\n\n", "file_path": "crates/gen/src/to_snake.rs", "rank": 0, ...
Rust
libzeropool-rs/src/client/state.rs
zkBob/libzeropool-rs
68f7b60a6883bd1ca6b6071318bf06fd3a05f246
use std::{convert::TryInto, marker::PhantomData}; use kvdb::KeyValueDB; use kvdb_memorydb::InMemory as MemoryDatabase; #[cfg(feature = "web")] use kvdb_web::Database as WebDatabase; use libzeropool::{ constants, fawkes_crypto::{ff_uint::Num, ff_uint::PrimeField, BorshDeserialize, BorshSerialize}, native::{...
use std::{convert::TryInto, marker::PhantomData}; use kvdb::KeyValueDB; use kvdb_memorydb::InMemory as MemoryDatabase; #[cfg(feature = "web")] use kvdb_web::Database as WebDatabase; use libzeropool::{ constants, fawkes_crypto::{ff_uint::Num, ff_uint::PrimeField, BorshDeserialize, BorshSerialize}, native::{...
index..=self.latest_note_index) { if let Transaction::Note(note) = tx { note_balance += note.b.to_num(); } } note_balance } }
let tree = MerkleTree::new_test(params.clone()); let txs = TxStorage::new_test(); Self::new(tree, txs) } } impl<D, P> State<D, P> where D: KeyValueDB, P: PoolParams, P::Fr: 'static, { pub fn new(tree: MerkleTree<D, P>, txs: TxStorage<D, P::Fr>) -> Self { let ...
random
[ { "content": "pub fn zero_proof<Fr: PrimeField>() -> MerkleProof<Fr, { constants::HEIGHT }> {\n\n MerkleProof {\n\n sibling: (0..constants::HEIGHT).map(|_| Num::ZERO).collect(),\n\n path: (0..constants::HEIGHT).map(|_| false).collect(),\n\n }\n\n}\n", "file_path": "libzeropool-rs/src/uti...
Rust
core/lib/prover_utils/src/lib.rs
AlmavivA/zksync
3af534ce40ed064bcd558af325e34133501b0848
use lazy_static::lazy_static; use std::collections::HashMap; use std::fs::File; use std::sync::{Arc, Mutex}; use std::time::Instant; use zksync_crypto::bellman::kate_commitment::{Crs, CrsForMonomialForm}; use zksync_crypto::bellman::plonk::better_cs::{ adaptor::TranspilationVariant, cs::PlonkCsWidth4WithNextStepPar...
use lazy_static::lazy_static; use std::collections::HashMap; use std::fs::File; use std::sync::{Arc, Mutex}; use std::time::Instant; use zksync_crypto::bellman::kate_commitment::{Crs, CrsForMonomialForm}; use zksync_crypto::bellman::plonk::better_cs::{ adaptor::TranspilationVariant, cs::PlonkCsWidth4WithNextStepPar...
vlog::info!("Proof for circuit successful"); Ok(proof.into()) } pub fn get_universal_setup_monomial_form( power_of_two: u32, download_from_network: bool, ) -> Result<Crs<Engine, CrsForMonomialForm>, anyhow::Error> { if let Some(cached_setup) = UNIVERSAL_SETUP_CACHE.take_setup_struct(power_of_two) { ...
let size_log2 = std::cmp::max(size_log2, SETUP_MIN_POW2); let key_monomial_form = get_universal_setup_monomial_form(size_log2, false)?; let proof = prove_by_steps::<_, _, RollingKeccakTranscript<Fr>>( circuit, &hints, &setup, None, &key_monomial_form, None,...
random
[ { "content": "/// Measures the time to `drop` a tree with calculated cache.\n\nfn smt_drop(b: &mut Bencher<'_>, size: u32) {\n\n let depth = zksync_crypto::params::account_tree_depth();\n\n\n\n // Create a tree and fill it with some accounts.\n\n let mut tree = RealSMT::new(depth);\n\n for (id, acco...
Rust
pijama_parser/src/lexer/mod.rs
christianpoveda/pijama
458e5777c94894b4ad371cef21e8820bdb8feb62
use logos::{Logos, SpannedIter}; use std::{ convert::TryFrom, fmt::{Display, Formatter, Result as FmtResult}, }; use pijama_common::location::{Located, Location}; mod raw; use raw::RawToken; #[derive(Debug, Clone)] pub enum LexError { Internal, Custom(&'static str), } pub struct Lexer<'a> { i...
use logos::{Logos, SpannedIter}; use std::{ convert::TryFrom, fmt::{Display, Formatter, Result as FmtResult}, }; use pijama_common::location::{Located, Location}; mod raw; use raw::RawToken; #[derive(Debug, Clone)] pub enum LexError { Internal, Custom(&'static str), } pub struct Lexer<'a> { i...
} #[derive(Debug, Clone)] pub enum Keyword { Fn, If, Do, End, Else, Elif, True, False, Unit, IntTy, BoolTy, UnitTy, Print, } impl Display for Keyword { fn fmt(&self, f: &mut Formatter) -> FmtResult { match self { Keyword::Fn => write!(f, "fn...
fn try_from(raw: RawToken<'a>) -> Result<Self, Self::Error> { match raw { RawToken::Newline => Ok(Token::Newline), RawToken::Int(int) => Ok(Token::Int(int)), RawToken::Ident(ident) => Ok(Token::Ident(ident)), RawToken::Fn => Ok(Token::Kword(Keyword::Fn)), ...
function_block-full_function
[ { "content": "pub fn display_error(input: &str, path: &str, error: &LangError) {\n\n let writer = StandardStream::stderr(ColorChoice::Always);\n\n let config = codespan_reporting::term::Config::default();\n\n let mut files = SimpleFiles::new();\n\n\n\n let file_id = files.add(path, input);\n\n\n\n ...
Rust
boa/src/syntax/ast/node/declaration/let_decl_list/mod.rs
54k1/boa
ceca316ca5a3a1f8d907d57d076fba183cc93ee6
use crate::{ environment::lexical_environment::VariableScope, exec::Executable, gc::{Finalize, Trace}, syntax::ast::node::{join_nodes, Identifier, Node}, Context, Result, Value, }; use std::fmt; #[cfg(feature = "deser")] use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "deser", derive(Ser...
use crate::{ environment::lexical_environment::VariableScope, exec::Executable, gc::{Finalize, Trace}, syntax::ast::node::{join_nodes, Identifier, Node}, Context, Result, Value, }; use std::fmt; #[cfg(feature = "deser")] use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "deser", derive(Ser...
} impl LetDecl { pub(in crate::syntax) fn new<N, I>(name: N, init: I) -> Self where N: Into<Identifier>, I: Into<Option<Node>>, { Self { name: name.into(), init: init.into(), } } pub fn name(&self) -> &str { self.name.as_re...
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.name, f)?; if let Some(ref init) = self.init { write!(f, " = {}", init)?; } Ok(()) }
function_block-function_prefix_line
[]
Rust
src/reactor/segment_selector.rs
claudiofahey/pravega-client-rust
efaccc1ba896588ffb125cd72378b07f714609e5
use ahash::RandomState; use std::collections::{BTreeMap, HashMap}; use pravega_client_channel::ChannelSender; use tracing::{debug, warn}; use pravega_client_shared::*; use crate::client_factory::ClientFactory; use crate::get_random_f64; use crate::reactor::event::Incoming; use crate::reactor::segment_writer::{Appe...
use ahash::RandomState; use std::collections::{BTreeMap, HashMap}; use pravega_client_channel::ChannelSender; use tracing::{debug, warn}; use pravega_client_shared::*; use crate::client_factory::ClientFactory; use crate::get_random_f64; use crate::reactor::event::Incoming; use crate::reactor::segment_writer::{Appe...
.unwrap(); factory .get_controller_client() .create_stream(&StreamConfiguration { scoped_stream: stream.clone(), scaling: Scaling { scale_type: ScaleType::FixedNumSegments, target_rate: 1, ...
.connection_type(ConnectionType::Mock(mock)) .controller_uri(PravegaNodeUri::from("127.0.0.1:9091".to_string())) .mock(true) .build() .unwrap(); let factory = ClientFactory::new(config); factory .get_controller_client() .c...
function_block-random_span
[ { "content": "fn test_seal(writer: &mut ByteStreamWriter, reader: &mut ByteStreamReader, rt: &mut Runtime) {\n\n info!(\"test byte stream seal\");\n\n // seal\n\n rt.block_on(writer.seal()).expect(\"seal\");\n\n\n\n // read sealed segment\n\n reader.seek(SeekFrom::Start(4)).expect(\"seek to start...
Rust
Ch14/07.tanimate/tanimate-rs/src/main.rs
SteveLauC/Understanding-Unix-Linux-Programming
67facc5a99d0bcc5a8c614fc4bb4f6fe85b67b31
/* * Only the last string will appear on the screen(Actually it is the first one cuz I used `swap_remove`) * * And the main thread will do nothing to the keyboard event * * :( */ use crossbeam::scope; use curses_sys::{ addch, addstr, cbreak, clear, endwin, getch, initscr, move_, noecho, refresh, COLS, LINES, ...
/* * Only the last string will appear on the screen(Actually it is the first one cuz I used `swap_remove`) * * And the main thread will do nothing to the keyboard event * * :( */ use crossbeam::scope; use curses_sys::{ addch, addstr, cbreak, clear, endwin, getch, initscr, move_, noecho, refresh, COLS, LINES, ...
clear(); } num_msg as i32 } fn animate(arg: &mut PropSet, lock: &Arc<Mutex<()>>) { let len: usize = unsafe { strlen(arg.str.as_ptr()) } + 2; let mut col: i32 = rand::random::<i32>() % (unsafe { COLS } - len as i32 - 3); loop { sleep(Duration::from_micros(arg.delay * TUNIT)); ...
in(); } } fn setup(n_strings: usize, strings: Vec<String>, props: &mut [PropSet; MAXMSG]) -> i32 { let num_msg = if n_strings > MAXMSG { MAXMSG } else { n_strings }; let mut rng: ThreadRng = rand::thread_rng(); for idx in 0..num_msg { props[idx].str = CString::new(strin...
random
[ { "content": "fn count_words(file_name: String, counter: Arc<Mutex<usize>>) {\n\n let mut buf: Vec<u8> = Vec::with_capacity(500);\n\n let mut reader: BufReader<File> = BufReader::new(File::open(file_name).unwrap());\n\n\n\n reader.read_to_end(&mut buf).unwrap();\n\n\n\n let mut prev: char = '\\0';\n...
Rust
src/rfid_buffer.rs
rosie-home-automation/garage_rfid
343067c27f093a23cb8126c79aa98f8a657ab538
use diesel; use slog; use std::sync::{ mpsc, Arc, Mutex }; use std::time::{ Duration, Instant }; use bouncer::{ Bouncer, Variety }; use database::Database; use garage_door::GarageDoor; use key_mapper::KeyMapper; use slacker::Slacker; #[derive(Debug)] pub struct RfidBuffer<'a> { rx: mpsc::Receiver<u8>, bit_buffer:...
use diesel; use slog; use std::sync::{ mpsc, Arc, Mutex }; use std::time::{ Duration, Instant }; use bouncer::{ Bouncer, Variety }; use database::Database; use garage_door::GarageDoor; use key_mapper::KeyMapper; use slacker::Slacker; #[derive(Debug)] pub struct RfidBuffer<'a> { rx: mpsc::Receiver<u8>, bit_buffer:...
fn read_data(&mut self) { 'read_data_loop: loop { match self.rx.recv_timeout(self.read_timeout) { Ok(bit) => self.add_bit(bit), Err(mpsc::RecvTimeoutError::Timeout) => { self.process_bit_buffer(); break 'read_data_loop; }, Err(err) => { error!(...
fn wait_for_data(&mut self) { match self.rx.recv_timeout(self.wait_timeout) { Ok(bit) => { self.add_bit(bit); self.read_data(); }, Err(mpsc::RecvTimeoutError::Timeout) => { if self.pin_key_buffer_is_stale() { self.clear_pin_key_buffer() } },...
function_block-full_function
[ { "content": "fn setup_slog() -> slog::Logger {\n\n let decorator = slog_term::TermDecorator::new().build();\n\n let stdout_drain = slog_term::CompactFormat::new(decorator).build().fuse();\n\n let stdout_drain = slog_async::Async::new(stdout_drain).build().fuse();\n\n slog::Logger::root(stdout_drain, o!(\"...
Rust
iota-streams-core/src/tbits/convert.rs
JakeSCahill/streams
ef7fcacf8aec5ab88610f0c9951e09fdee9d549b
use super::{ slice::{ TbitSlice, TbitSliceMut, }, word::BasicTbitWord, }; pub trait ConvertInto<IntoW>: Sized { fn cvt_into(from: TbitSlice<Self>, into: &mut TbitSliceMut<IntoW>); } pub trait IConvertInto<FromW>: Sized { fn icvt_into(from: TbitSlice<FromW>, into: &mut TbitSliceMut<...
use super::{ slice::{ TbitSlice, TbitSliceMut, }, word::BasicTbi
Mut<TW>) { let n = onto.size(); assert!(n <= from.size()); from.take(n).copy(&onto.advance(n)); } } pub trait ConvertIso<IsoW>: Sized where Self: ConvertInto<IsoW>, IsoW: ConvertOnto<Self>, { fn cvt_from(from: TbitSlice<IsoW>, onto: &mut TbitSliceMut<Self>) { <IsoW as Co...
tWord, }; pub trait ConvertInto<IntoW>: Sized { fn cvt_into(from: TbitSlice<Self>, into: &mut TbitSliceMut<IntoW>); } pub trait IConvertInto<FromW>: Sized { fn icvt_into(from: TbitSlice<FromW>, into: &mut TbitSliceMut<Self>); } impl<IntoW, FromW> IConvertInto<FromW> for IntoW where FromW: ConvertInto<Int...
random
[ { "content": "pub trait RngTbitWord: BasicTbitWord + super::convert::IConvertOnto<super::binary::Byte> {}\n", "file_path": "iota-streams-core/src/tbits/word.rs", "rank": 0, "score": 82523.8557091098 }, { "content": "fn encrypt_with_fo_transform<TW, FO>(h: &Poly, r: TbitSliceMut<TW>, y: TbitS...
Rust
src/render.rs
zmwangx/debian-metadata
a219ab2cb77f1dff6caf866f8a1ba24bc861602b
use handlebars::{self, Handlebars}; use serde::Serialize; use media_file::MediaFileMetadata; use stream::{self, StreamMetadata}; pub trait Render: Serialize { fn render(&self, template: &str) -> Result<String, handlebars::TemplateRenderError> { Handlebars::new().render_template(template, &self) } ...
use handlebars::{self, Handlebars}; use serde::Serialize; use media_file::MediaFileMetadata; use stream::{self, StreamMetadata}; pub trait Render: Serialize { fn render(&self, template: &str) -> Result<String, handlebars::TemplateRenderError> { Handlebars::new().render_template(template, &self) } ...
, {{{bit_rate}}}\ {{/if}}\ " .to_string() } } impl Render for stream::SubtitleMetadata { fn default_template() -> String { "#{{{index}}}: Subtitle \ ({{#if language}}{{{language}}}{{else}}und{{/if}})\ , {{{codec_desc}}}\ " .to_string() ...
y kv.0}}{{{kv.1}}}\n{{/each}}\ {{/if}}\ {{#each streams_filtered_tags as |s|}}\ {{#if s.tags}} #{{{s.index}}}\n\ {{#each s.tags as |kv|}} {{padkey kv.0}}{{{kv.1}}}\n{{/each}}\ {{/if}}\ {{/each}}\ {{/if}}{{/if}}\ " ...
random
[ { "content": "// An unknown field order, AV_FIELD_UNKNOWN, is treated as a sign of being\n\n// progressive, unless decode_frames is true, in which case the first 30 frames\n\n// are decoded to look for interlaced frames.\n\npub fn get_scan_type(input: &mut Input, decode_frames: bool) -> io::Result<Option<ScanTy...
Rust
base/src/input.rs
Houjuu-Nue/Vulkan
a69c01a6da7bf4eb7154146081e89e317ba4c5a6
use smallvec::SmallVec; use crate::utils::frame::FrameAction; use crate::utils::fps::FpsCounter; const SIMULTANEOUS_KEY_COUNT: usize = 12; pub struct EventController { pub key: KeyHeap, pub cursor: CursorMotion, pub fps_counter: FpsCounter, action: FrameAction, is_toggle_key: bool, is_toggl...
use smallvec::SmallVec; use crate::utils::frame::FrameAction; use crate::utils::fps::FpsCounter; const SIMULTANEOUS_KEY_COUNT: usize = 12; pub struct EventController { pub key: KeyHeap, pub cursor: CursorMotion, pub fps_counter: FpsCounter, action: FrameAction, is_toggle_key: bool, is_toggl...
pub(crate) fn current_action(&self) -> FrameAction { self.action } } pub struct KeyHeap { keys: SmallVec<[winit::VirtualKeyCode; SIMULTANEOUS_KEY_COUNT]>, } impl Default for KeyHeap { fn default() -> KeyHeap { KeyHeap { keys: SmallVec::new(), } } } impl KeyHeap { fn key_p...
k_frame(&mut self) { self.fps_counter.tick_frame(); self.is_toggle_key = false; self.is_toggle_cursor = false; self.action = FrameAction::Rendering; }
function_block-function_prefixed
[ { "content": "pub fn input_descriptions() -> VertexInputSCI {\n\n\n\n VertexInputSCI::new()\n\n .add_binding(vk::VertexInputBindingDescription {\n\n binding: 0,\n\n stride : ::std::mem::size_of::<CharacterVertex>() as _,\n\n input_rate: vk::VertexInputRate::VERTEX,\n\n...
Rust
aoc_2019/src/day22.rs
ckuenzi/AoC
3dd243ec02b7f2dff42aa7c67e2dcddefb0fef64
use itertools::Itertools; #[aoc_generator(day22)] fn get_shuffles(input: &str) -> Vec<Operation> { let mut out = vec![]; for line in input.lines() { let words = line.split(' ').collect_vec(); match words[1] { "into" => out.push(Operation { shuffle: Shuffle::...
use itertools::Itertools; #[aoc_generator(day22)] fn get_shuffles(input: &str) -> Vec<Operation> { let mut out = vec![]; for line in input.lines() { let words = line.split(' ').collect_vec(); match words[1] { "into" => out.push(Operation { shuffle: Shuffle::...
deck.clear(); deck.append(&mut new_deck); } fn reverse(deck: &mut Vec<i128>) { deck.reverse(); } #[aoc(day22, part2)] fn part2(shuffles: &Vec<Operation>) -> i128 { const D: i128 = 119315717514047; const N: i128 = 101741582076661; let mut a = 1; let mut b = 0; for shuf...
if shuffle.amount > 0 { for i in shuffle.amount as usize..deck.len() { new_deck.push(deck[i]); } for i in 0..shuffle.amount as usize { new_deck.push(deck[i]); } } else { for i in (deck.len() as i128 + shuffle.amount) as usize..deck.len() { ...
if_condition
[ { "content": "#[aoc(day13, part1)]\n\nfn part1(input: &str) -> usize {\n\n Computer::new_from_text(input)\n\n .run()\n\n .get_outputs()\n\n .iter()\n\n .skip(2)\n\n .step_by(3)\n\n .filter(|&&t| t == 2)\n\n .count()\n\n}\n\n\n", "file_path": "aoc_2019/src/...
Rust
core/src/api/ping.rs
Szetty/seven_wonders
77f6f4ff015a8fc481c7edfc87e3cd77b61bc79b
#![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![rustfmt::skip] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_imports)] #![allow(...
#![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![rustfmt::skip] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_imports)] #![allow(...
fn default_instance() -> &'static PingRequest { static instance: ::protobuf::rt::LazyV2<PingRequest> = ::protobuf::rt::LazyV2::INIT; instance.get(PingRequest::new) } } impl ::protobuf::Clear for PingRequest { fn clear(&mut self) { self.name.clear(); self.unknown_fields.cle...
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::refle...
function_block-full_function
[ { "content": "pub fn default_game_state() -> GameState {\n\n let player_names = vec![\"a\".to_string(), \"b\".to_string(), \"c\".to_string()];\n\n GameState {\n\n neighbours: Neighbours::new(player_names),\n\n player_states: hashmap! {\n\n \"a\".to_string() => PlayerState {\n\n ...
Rust
src/optimizers/nelder_mead.rs
sile/yamakan
e125f30ca05806be5f148730b1eb5d52489d34c9
use crate::domains::ContinuousDomain; use crate::{ErrorKind, IdGen, Obs, ObsId, Optimizer, Result}; use rand::distributions::Distribution; use rand::Rng; use std::f64::EPSILON; #[derive(Debug)] pub struct NelderMeadOptimizer<V> { params_domain: Vec<ContinuousDomain>, simplex: Vec<Obs<Vec<f64>, V>>, alpha...
use crate::domains::ContinuousDomain; use crate::{ErrorKind, IdGen, Obs, ObsId, Optimizer, Result}; use rand::distributions::Distribution; use rand::Rng; use std::f64::EPSILON; #[derive(Debug)] pub struct NelderMeadOptimizer<V> { params_domain: Vec<ContinuousDomain>, simplex: Vec<Obs<Vec<f64>, V>>, alpha...
pub fn with_initial_simplex( params_domain: Vec<ContinuousDomain>, initial_simplex: Vec<Vec<f64>>, ) -> Result<Self> { track_assert!( params_domain.len() >= 2, ErrorKind::InvalidInput, "Too few dimensions: {}", params_domain.len() ...
pub fn with_initial_point(params_domain: Vec<ContinuousDomain>, point: &[f64]) -> Result<Self> { let mut initial_simplex = vec![point.to_vec()]; for i in 0..params_domain.len() { let tau = if point[i] == 0.0 { 0.00025 } else { 0.05 }; let x = point .iter() ...
function_block-full_function
[ { "content": "fn dominates<P>(a: &Obs<P, Vec<f64>>, b: &Obs<P, Vec<f64>>) -> Result<bool> {\n\n track_assert_eq!(a.value.len(), b.value.len(), ErrorKind::InvalidInput);\n\n if a.value.iter().zip(b.value.iter()).any(|(a, b)| a > b) {\n\n Ok(false)\n\n } else {\n\n Ok(a.value.iter().zip(b.v...
Rust
src/main/rust/src/motionevent.rs
wartman4404/everybody-draw
ceb80a74aa49d260233b08b20ddbee230b832974
use core::prelude::*; use collections::vec_map::VecMap; use android::input::*; use point::{PaintPoint, Coordinate, PointEntry, PointProducer, PointInfo}; use activestate; use activestate::ActiveState; static AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT: usize = 8; type PointerState = VecMap<ActiveState>; pub struct D...
use core::prelude::*; use collections::vec_map::VecMap; use android::input::*; use point::{PaintPoint, Coordinate, PointEntry, PointProducer, PointInfo}; use activestate; use activestate::ActiveState; static AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT: usize = 8; type PointerState = VecMap<ActiveState>; pub struct D...
fn push_historical_point(queue: &mut PointProducer, evt: *const AInputEvent, id: i32, ptr: size_t, hist: size_t) { let _ = queue.send(PointEntry { index: id, entry: PointInfo::Point(PaintPoint { pos: Coordinate { x: unsafe { AMotionEvent_getHistoricalX(evt, ptr, hist) }, y: unsaf...
t updated = active.get(&(id as usize)).unwrap_or(&activestate::INACTIVE).push(newstate); active.insert(id as usize, updated); if updated == activestate::STOPPING { let _ = queue.send(PointEntry { index: id, entry: PointInfo::Stop }); } }
function_block-function_prefixed
[ { "content": "//FIXME: needs meaningful name\n\npub fn jni_append_motion_event(s: &mut MotionEventProducer, evt: *const AInputEvent) {\n\n append_motion_event(&mut s.pointer_data, evt, &mut s.producer);\n\n}\n\n\n", "file_path": "src/main/rust/src/glpoint.rs", "rank": 7, "score": 319187.587549801...
Rust
async_fuse/src/main.rs
pymongo/datenlord
697cddceb317895fb80bc7995c7fe6a6127e4cdf
#![deny( anonymous_parameters, bare_trait_objects, elided_lifetimes_in_paths, missing_copy_implementations, missing_debug_implementations, missing_docs, single_use_lifetimes, trivial_casts, trivial_numeric_casts, unstable_features, unused_extern...
#![deny( anonymous_parameters, bare_trait_objects, elided_lifetimes_in_paths, missing_copy_implementations, missing_debug_implementations, missing_docs, single_use_lifetimes, trivial_casts, trivial_numeric_casts, unstable_features, unused_extern...
}
fn test_async_iter() -> io::Result<()> { smol::block_on(async move { let dir = smol::unblock(|| fs::read_dir(".")).await?; let mut dir = smol::stream::iter(dir); while let Some(entry) = dir.next().await { let path = entry?.path(); if path.is_fi...
function_block-function_prefix_line
[ { "content": "/// Get ip address of node\n\npub fn get_ip_of_node(node_id: &str) -> IpAddr {\n\n let hostname = format!(\"{}:{}\", node_id, 0);\n\n let sockets = hostname.to_socket_addrs();\n\n let addrs: Vec<_> = sockets\n\n .unwrap_or_else(|_| panic!(\"Failed to resolve node ID={}\", node_id))...
Rust
Snippets/Rust/gtk-rs-more/src/main.rs
fredmorcos/attic
0da3b94aa525df59ddc977c32cb71c243ffd0dbd
#![feature(tool_lints)] #![warn(clippy::all)] extern crate glib; extern crate gdk; extern crate gdk_pixbuf; extern crate gtk; use gdk_pixbuf::PixbufExt; use gtk::prelude::*; use std::error::Error; use std::fmt::Debug; use std::fmt::Display; use std::rc::Rc; use std::cell::RefCell; enum AppError { GtkInit(&'stati...
#![feature(tool_lints)] #![warn(clippy::all)] extern crate glib; extern crate gdk; extern crate gdk_pixbuf; extern crate gtk; use gdk_pixbuf::PixbufExt; use gtk::prelude::*; use std::error::Error; use std::fmt::Debug; use std::fmt::Display; use std::rc::Rc; use std::cell::RefCell; enum AppError { GtkInit(&'stati...
} impl Debug for AppError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { AppError::GtkInit(msg) => f.write_str(msg), AppError::IconTheme => f.write_str("Cannot get Gtk+ icon theme"), AppError::FolderIcon(err) => f.write_str(&err.to_string()), AppError::No...
fn cause(&self) -> Option<&Error> { if let AppError::FolderIcon(err) = self { Some(err) } else { None } }
function_block-full_function
[ { "content": "fn parse(data: &str) -> impl Iterator<Item = Result<Entry, Error>> {\n\n data.lines()\n\n .enumerate()\n\n .filter(|(_, line)| {\n\n let line = line.trim();\n\n !line.is_empty() && !line.starts_with('#')\n\n })\n\n .map(|(num, line)| Entry::pars...
Rust
src/p00xx/p55.rs
Houjuu-Nue/leetcode-rs
9c54af5f3cf810745796cf9bd4075117070a1b3d
pub type Input = Vec<i32>; pub type Output = bool; pub trait Solution { fn can_jump(&self, nums: Vec<i32>) -> bool; } pub struct Solution0; impl Solution for Solution0 { fn can_jump(&self, nums: Vec<i32>) -> bool { let mut last_pos = nums.len() - 1; for i in (0..nums.len()).rev() { ...
pub type Input = Vec<i32>; pub type Output = bool; pub trait Solution { fn can_jump(&self, nums: Vec<i32>) -> bool; } pub struct Solution0; impl Solution for Solution0 { fn can_jump(&self, nums: Vec<i32>) -> bool { let mut last_pos = nums.len() - 1; for i in (0..nums.len()).rev() { ...
} fn dyn_topdown_can_jum_from(nums: &[i32], status: &mut [LocStatus]) -> bool { match status[0] { | LocStatus::Good => true, | LocStatus::Bad => false, | LocStatus::Unknown => { let jump_boundary = nums.len().min(nums[0] as usize + 1); let ans = (1..jump_boundar...
fn can_jump(&self, nums: Vec<i32>) -> bool { let mut status = vec![LocStatus::Unknown; nums.len()]; (*status.last_mut().unwrap()) = LocStatus::Good; dyn_topdown_can_jum_from(&nums, &mut status) }
function_block-full_function
[ { "content": "fn dfs(nums: &mut Vec<i32>, candidate: &[i32], used: &mut [bool], result: &mut Vec<Vec<i32>>) {\n\n\n\n if nums.len() == candidate.len() {\n\n result.push(nums.clone());\n\n return\n\n }\n\n\n\n use std::collections::HashSet;\n\n let mut set = HashSet::new();\n\n\n\n f...
Rust
core/src/lib.rs
daviddrysdale/tink-rust
f27759c07b2b331f3702c52e1c31b1eaedd45b4f
#![cfg_attr(docsrs, feature(doc_cfg))] #![deny(broken_intra_doc_links)] pub mod cryptofmt; pub mod keyset; pub mod primitiveset; pub mod registry; pub mod subtle; pub mod utils; pub use utils::TinkError; pub const UPSTREAM_VERSION: &str = "1.6.0"; pub type KeyId = u32; mod aead; pub use aead::*; mod deterministic...
#![cfg_attr(docsrs, feature(doc_cfg))] #![deny(broken_intra_doc_links)] pub mod cryptofmt; pub mod keyset; pub mod primitiveset; pub mod registry; pub mod subtle; pub mod utils; pub use utils::TinkError; pub const UPSTREAM_VERSION: &str = "1.6.0"; pub type KeyId = u32; mod aead; pub use aead::*; mod deterministic...
amingAead> { match p { Primitive::StreamingAead(p) => p, _ => panic!("attempt to convert wrong primitive type"), } } } impl From<Primitive> for Box<dyn Verifier> { fn from(p: Primitive) -> Box<dyn Verifier> { match p { Primitive::Verifier(p) => p, ...
:Signer(p) => Primitive::Signer(p.box_clone()), Primitive::StreamingAead(p) => Primitive::StreamingAead(p.box_clone()), Primitive::Verifier(p) => Primitive::Verifier(p.box_clone()), } } } impl From<Primitive> for Box<dyn Aead> { fn from(p: Primitive) -> Box<dyn Aead> { m...
random
[ { "content": "/// Convert different forms of a hash name to the hash type that Tink recognizes.\n\npub fn convert_hash_name(name: &str) -> HashType {\n\n match name {\n\n \"SHA-256\" => HashType::Sha256,\n\n \"SHA-384\" => HashType::Sha384,\n\n \"SHA-512\" => HashType::Sha512,\n\n ...
Rust
src/dsc/circular_prime_sieve.rs
CmdrMoozy/euler
ae30dcaeb86b8442b5e7f95565f72175e6abeeb4
use crate::math::exp::log10; use crate::math::prime::PrimeSieve; use crate::math::sieve::Sieve; use crate::structs::bit_array::*; use std::collections::VecDeque; use std::iter::FilterMap; use std::option::Option; #[derive(Debug)] struct DigitalRotationIterator { index: usize, digits: VecDeque<char>, } impl ...
use crate::math::exp::log10; use crate::math::prime::PrimeSieve; use crate::math::sieve::Sieve; use crate::structs::bit_array::*; use std::collections::VecDeque; use std::iter::FilterMap; use std::option::Option; #[derive(Debug)] struct DigitalRotationIterator { index: usize, digits: VecDeque<char>, } impl ...
} else { None }; self.index += 1; let last_digit = self.digits.pop_back().unwrap(); self.digits.push_front(last_digit); if item.is_some() { return item; } } } } pub struct Cir...
Some( self.digits .iter() .cloned() .collect::<String>() .parse::<u64>() .unwrap(), )
call_expression
[ { "content": "/// Returns the average of the given list of unsigned integers. If the average\n\n/// is too large to fit in a u64, None is returned instead. If the given list\n\n/// is empty, 0 is returned.\n\npub fn iaverage<I, V>(iter: I) -> Option<u64>\n\nwhere\n\n I: Iterator<Item = V>,\n\n V: Into<u64...
Rust
implementations/rust/transport/src/tcp.rs
mkaszubowski/ockam
fddfdbee03f2adae4d2f4a586edd2a06db1510d8
use futures::io::Error; use ockam::message::MAX_MESSAGE_SIZE; #[allow(unused)] use ockam::message::*; use ockam::system::commands::RouterCommand::ReceiveMessage; use ockam::system::commands::{OckamCommand, RouterCommand, TransportCommand}; use std::collections::HashMap; use std::io; use std::io::{Read, Write}; use std:...
use futures::io::Error; use ockam::message::MAX_MESSAGE_SIZE; #[allow(unused)] use ockam::message::*; use ockam::system::commands::RouterCommand::ReceiveMessage; use ockam::system::commands::{OckamCommand, RouterCommand, TransportCommand}; use std::collections::HashMap; use std::io; use std::io::{Read, Write}; use std:...
g = false; break; } _ => { println!("unrecognized command"); } } } for a in &self.addresses { let mut l = 0; match self.conne...
println!("send_message failed: {}", e); keep_going = false; } _ => {} } } else { println!("can't find connection {}", addr...
random
[ { "content": "pub fn ockam_error_is_none(error: &ockam_error_t) -> bool {\n\n error.code == 0\n\n}\n\n\n", "file_path": "implementations/rust/c/bindings/src/helpers.rs", "rank": 0, "score": 308078.6532158383 }, { "content": "pub fn ockam_error_has_error(error: &ockam_error_t) -> bool {\n\...
Rust
libursa/bin/test_aesgcm.rs
HarshMultani/ursa
c08d98774f286785914310d39604bc5f661220a8
extern crate openssl; extern crate ursa; use openssl::symm::{ decrypt_aead as openssl_decrypt, encrypt_aead as openssl_encrypt, Cipher as OpenSslCipher, }; use ursa::encryption::random_vec; use ursa::encryption::symm::prelude::*; use std::io; use std::io::Write; use std::time::Instant; fn main() { let aad =...
extern crate openssl; extern crate ursa; use openssl::symm::{ decrypt_aead as openssl_decrypt, encrypt_aead as openssl_encrypt, Cipher as OpenSslCipher, }; use ursa::encryption::random_vec; use ursa::encryption::symm::prelude::*; use std::io; use std::io::Write; use std::time::Instant; fn main() { let aad =...
macro_rules! aes_gcm_impl { ($encrypt:ident, $decrypt:ident, $cipherid:ident) => { fn $encrypt(key: &[u8], aad: &[u8], msg: &[u8]) -> Vec<u8> { let mut nonce = random_vec(12).unwrap(); let mut tag = vec![0u8; 16]; let ciphertext = openssl_encrypt( OpenS...
println!("{}.{:03}", elapsed.as_secs(), elapsed.subsec_millis()); print!("openssl based aes-256-gcm - "); io::stdout().flush().unwrap(); let key = random_vec(32).unwrap(); now = Instant::now(); for _ in 0..trials { let ciphertext = aes_256_gcm_encrypt(key.as_slice(), &aad[..], &msg[..]); ...
function_block-function_prefix_line
[ { "content": "fn get_keysize(cipher: EncryptorType) -> usize {\n\n match cipher {\n\n EncryptorType::Aes128CbcHmac256 => {\n\n <<Aes128CbcHmac256 as NewAead>::KeySize as Unsigned>::to_usize()\n\n }\n\n EncryptorType::Aes256CbcHmac512 => {\n\n <<Aes256CbcHmac512 as N...
Rust
src/native.rs
moonshadow565/lolmetadumper2
e2cbcc56c559ed156f37f401c30770266a1ac03f
use pelite::pe::{Pe, PeView}; use winapi::um::consoleapi::AllocConsole; use winapi::um::handleapi::CloseHandle; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::memoryapi::ReadProcessMemory; use winapi::um::processthreadsapi::ExitProcess; use winapi::um::processthreadsapi::GetCurrentProcess; use winapi:...
use pelite::pe::{Pe, PeView}; use winapi::um::consoleapi::AllocConsole; use winapi::um::handleapi::CloseHandle; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::memoryapi::ReadProcessMemory; use winapi::um::processthreadsapi::ExitProcess; use winapi::um::processthreadsapi::GetCurrentProcess; use winapi:...
n % 0x1000 != 0 { remain % 0x1000 } else { 0x1000 }; remain -= page_size; unsafe { let offset = (self.base + remain) as *const _; if IsBadReadPtr(offset, page_size) != 0 { last_page_size =...
me(lang) = version_info.translation().get(0) { if let Some(product_version) = version_info.value(*lang, "ProductVersion") { version = product_version.replace("\0", "").to_string(); } } } Self { base, ...
random
[ { "content": "pub fn dump_class(base: usize, class: &Class) -> Value {\n\n json!({\n\n \"base\": class.base_class.map(|c| dump_hex(c.hash)),\n\n \"secondary_bases\": dump_class_secondary(class.secondary_bases.slice()),\n\n \"secondary_children\": dump_class_secondary(class.secondary_chil...
Rust
src/server.rs
gsou/ricsctl
933684b72d4caccfbfc221c7a7c86a2ad55577aa
use std::io::{Read, Write}; use std::collections::HashMap; use protobuf::{Message, CodedInputStream}; #[cfg(target_family="unix")] use std::os::unix::net::{UnixStream}; use std::net::TcpStream; use std::time::Duration; use std::sync::mpsc::{channel, Receiver}; use super::rics; #[cfg(target_family="windows")] type Un...
use std::io::{Read, Write}; use std::collections::HashMap; use protobuf::{Message, CodedInputStream}; #[cfg(target_family="unix")] use std::os::unix::net::{UnixStream}; use std::net::TcpStream; use std::time::Duration; use std::sync::mpsc::{channel, Receiver}; use super::rics; #[cfg(target_family="windows")] type Un...
}, ConnectTo::Tcp(path) => { let socket = TcpStream::connect(path).expect("Failed to connect to server"); socket.set_read_timeout(Some(Duration::new(1,0))).expect("Can't change socket param"); socket.set_write_timeout(Some(Duration::new(1,0))).exp...
if cfg!(target_family="unix") { let socket = UnixStream::connect(path).expect("Failed to connect to server"); socket.set_read_timeout(Some(Duration::new(1,0))).expect("Can't change socket param"); socket.set_write_timeout(Some(Duration::new(1,0))).expect("Can'...
if_condition
[ { "content": "/// Arbitrary client connection manager\n\nfn run_client<T>(server_state: Arc<RwLock<ServerState>>, socket: T, input_stream: &mut CodedInputStream) where T: 'static+Read+Write+Sync+Send {\n\n debug!(\"New client connection accepted\");\n\n // Initialize node if needed\n\n let socket_arc =...
Rust
src/git.rs
arusahni/git-req
6e044b8a3ca1dcae602dcbef9efc501971845bd4
use anyhow::{anyhow, Result}; use logchop::OptionLogger; use std::path::Path; use std::str; use std::{collections::HashSet, convert::TryInto}; use duct::cmd; use git2::{Config, Repository}; use log::{debug, trace, warn}; fn migrate_legacy(field_name: &str, remote_name: &str) { let repo = Repository::open_from_env...
use anyhow::{anyhow, Result}; use logchop::OptionLogger; use std::path::Path; use std::str; use std::{collections::HashSet, convert::TryInto}; use duct::cmd; use git2::{Config, Repository}; use log::{debug, trace, warn}; fn migrate_legacy(field_name: &str, remote_name: &str) { let repo = Repository::open_from_env...
} } }
match cmd("git", checkout_args).run() { Ok(_) => Ok(CheckoutResult::BranchChanged), Err(err) => Err(anyhow!("Could not check out local branch: {}", err)), }
if_condition
[ { "content": "/// Get a remote struct from an origin URL\n\npub fn get_remote(remote_name: &str, origin: &str, skip_api_key: bool) -> Result<Box<dyn Remote>> {\n\n let domain = get_domain(origin)?;\n\n Ok(match domain {\n\n \"github.com\" => {\n\n let name = github::get_github_project_na...
Rust
src/main.rs
periklis/rust-microservice-example
a4059aa536017074a7a67f3fbe87e2e690dca5c3
#![deny(warnings)] extern crate chrono; extern crate futures; extern crate hyper; extern crate pretty_env_logger; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; use chrono::{DateTime, Utc}; use futures::{Async, Future, IntoFuture, Poll}; use futures::future::{FutureRe...
#![deny(warnings)] extern crate chrono; extern crate futures; extern crate hyper; extern crate pretty_env_logger; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; use chrono::{DateTime, Utc}; use futures::{Async, Future, IntoFuture, Poll}; use futures::future::{FutureRe...
} #[derive(Debug)] struct App<'a> { repository: RegionRepository<'a> } impl<'a> Service for App<'a> { type ReqBody = Body; type ResBody = Body; type Error = hyperError; type Future = Box<Future<Item = Response<Self::ResBody>, Error = Self::Error> + 'a + Send>; fn call(&mut self, req: Requ...
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let entity = json!(Region { id: 1234, name: "Crete".to_string(), description: "Biggest greek Island".to_string(), created: Utc::now() }); Ok(Async::Ready(entity.to_string())) }
function_block-full_function
[ { "content": "# rust-microservice-example\n\nSecond evaluation of Rust web ecosystem - Simple Microservice with Hyper, Serde, Futures\n\n\n\n## Motivation\n\n\n\nSince my last evaluation of the Rust web ecosystem in Summer 2017 and post Futures 0.2 release, this repository is another evaluation sample of the cu...
Rust
Day16/src/main.rs
dclamage/aoc2021-rust
999a99d3afb12b5e4d1a47fafc14020b5caec57d
use bitvec::prelude::*; use std::fs; use std::time; type BS = BitSlice<Msb0, u8>; fn part1(packet_data: &BS) -> usize { let mut reader = DataReader::new(packet_data); let packet = Packet::new(&mut reader); packet.total_version() } fn part2(packet_data: &BS) -> usize { let mut reader = DataReader::new...
use bitvec::prelude::*; use std::fs; use std::time; type BS = BitSlice<Msb0, u8>; fn part1(packet_data: &BS) -> usize { let mut reader = DataReader::new(packet_data); let packet = Packet::new(&mut reader); packet.total_version() } fn part2(packet_data: &BS) -> usize { let mut reader = DataReader::new...
fn main() { let read_time_start = time::Instant::now(); let input = fs::read_to_string("input.txt").expect("Unable to read file"); let input: Vec<u8> = hex::decode(input.trim()).expect("Unable to decode hex"); let input_bits = input.view_bits::<Msb0>(); let read_time = read_time_start.ela...
function_block-full_function
[ { "content": "fn part2(input: &[u8], width: usize, height: usize) -> u64 {\n\n let mut input = input.to_vec();\n\n let mut step_num = 0;\n\n loop {\n\n for i in 0..input.len() {\n\n input[i] += 1;\n\n }\n\n\n\n let mut flashed = vec![false; input.len()];\n\n let m...
Rust
tests/stream_tests.rs
xdm67x/sdk-rust
5416d901f8f0106faca506bcecad88d47f9f7597
mod identity; use futures::io::ErrorKind; use futures::{AsyncRead, AsyncReadExt}; use identity::TestApp; use std::cmp::min; use std::pin::Pin; use std::task::{Context, Poll}; use tankersdk::{Error, ErrorCode}; #[tokio::test(flavor = "multi_thread")] async fn encrypt_stream_and_decrypt() -> Result<(), Error> { let...
mod identity; use futures::io::ErrorKind; use futures::{AsyncRead, AsyncReadExt}; use identity::TestApp; use std::cmp::min; use std::pin::Pin; use std::task::{Context, Poll}; use tankersdk::{Error, ErrorCode}; #[tokio::test(flavor = "multi_thread")] async fn encrypt_stream_and_decrypt() -> Result<(), Error> { let...
ce()).await?; let mut decrypted = Vec::new(); decrypted_stream.read_to_end(&mut decrypted).await.unwrap(); tanker.stop().await?; assert_eq!(decrypted, plaintext); Ok(()) } #[tokio::test(flavor = "multi_thread")] async fn encrypt_stream_and_decrypt_stream() -> Result<(), futures::io::Error> { l...
s(&app.create_identity(None)).await?; let plaintext = b"Chocolate"; let encrypted = tanker.encrypt(plaintext, &Default::default()).await?; let mut decrypted_stream = tanker.decrypt_stream(encrypted.as_sli
function_block-random_span
[ { "content": "pub fn generate_app_id(app_secret: &[u8]) -> Vec<u8> {\n\n let mut hasher = VarBlake2b::new(BLOCK_HASH_SIZE).unwrap();\n\n hasher.update(&[APP_CREATION_NATURE]);\n\n hasher.update(&[0u8; AUTHOR_SIZE]);\n\n hasher.update(&app_secret[app_secret.len() - APP_PUBLIC_KEY_SIZE..]);\n\n has...
Rust
src/problem.rs
masonium/exact-cover-rs
eb6276d3163da8ca1b974a0087fe67ee2e1f35e8
use node::{WeakNode, OwnedNode, Node, Row}; use iter::{iter_row}; use node::{prepend_left, prepend_up}; use std::hash::Hash; use std::collections::{HashMap}; use std::rc::{Rc}; use cover::{cover_column}; pub trait Constraint : Clone + Hash + Eq {} impl<T: Clone + Hash + Eq> Constraint for T {} pub trait Action : Copy...
use node::{WeakNode, OwnedNode, Node, Row}; use iter::{iter_row}; use node::{prepend_left, prepend_up}; use std::hash::Hash; use std::collections::{HashMap}; use std::rc::{Rc}; use cover::{cover_column}; pub trait Constraint : Clone + Hash + Eq {} impl<T: Clone + Hash + Eq> Constraint for T {} pub trait Action : Copy...
pub fn add_action(&mut self, a: A, clist: &[C]) { if clist.is_empty() { return } if self.action_map.contains_key(&a) { return } for x in clist { self.add_constraint(x); } le...
end_left(&mut self.root, &Rc::downgrade(&c)); self.constraints.push(c); self.constraint_map.insert(constraint.clone(), curr_size); } }
function_block-function_prefixed
[ { "content": "/// Prepend node above root.\n\npub fn prepend_up(root: &OwnedNode, node: &WeakNode) {\n\n let u = (*node).upgrade().unwrap();\n\n\n\n {\n\n\tlet mut n = u.borrow_mut();\n\n\tn.down = Rc::downgrade(&root);\n\n\tn.up = root.borrow_mut().up.clone();\n\n }\n\n {\n\n\tlet mut head = root.b...
Rust
src/plugins/forum/graphql/topics.rs
cinnabaris/Arche
980cdf77dc6285d8b2ee24d09f2505837faa1305
use std::ops::Deref; use chrono::{DateTime, NaiveDateTime, Utc}; use diesel::{delete, insert_into, prelude::*, update}; use rocket::http::Status; use validator::Validate; use super::super::super::super::{ errors::{Error, Result}, graphql::{context::Context, H}, orm::schema::{forum_posts, forum_tags, forum...
use std::ops::Deref; use chrono::{DateTime, NaiveDateTime, Utc}; use diesel::{delete, insert_into, prelude::*, update}; use rocket::http::Status; use validator::Validate; use super::super::super::super::{ errors::{Error, Result}, graphql::{context::Context, H}, orm::schema::{forum_posts, forum_tags, forum...
} pub fn list(ctx: &Context) -> Result<Vec<Topic>> { let user = ctx.current_user()?; let db = ctx.db.deref(); let is_manager = dao::is_manager(db, user.id); let items = forum_topics::dsl::forum_topics .select(( forum_topics::dsl::id, forum_topics::dsl::user_id, ...
pub fn call(&self, ctx: &Context) -> Result<H> { self.validate()?; let id: i64 = self.id.parse()?; let user = ctx.current_user()?; let db = ctx.db.deref(); if !dao::is_manager(db, user.id) && user.id != id { return Err(Status::Forbidden.reason.into()); } ...
function_block-full_function
[ { "content": "pub fn lock(db: &Db, id: &i64, un: bool) -> Result<()> {\n\n let now = Utc::now().naive_utc();\n\n let it = users::dsl::users.filter(users::dsl::id.eq(id));\n\n update(it)\n\n .set((\n\n users::dsl::locked_at.eq(&if un { None } else { Some(now) }),\n\n users::...
Rust
src/bvh.rs
jgrazian/webgpu-raytracer
1168d3c27b664313871d3f427458ae03070ccb5e
use crate::aabb::{Bounded, AABB}; use crate::geometry::Sphere; use crate::traits::AsBytes; use glam::Vec3; #[repr(C)] #[derive(Debug, Clone, Copy)] pub enum Leaf { S(Sphere), } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct Node { bb_min: Vec3, node_type: u32, bb_max: Vec3, esc_index: u32, } ...
use crate::aabb::{Bounded, AABB}; use crate::geometry::Sphere; use crate::traits::AsBytes; use glam::Vec3; #[repr(C)] #[derive(Debug, Clone, Copy)] pub enum Leaf { S(Sphere), } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct Node { bb_min: Vec3, node_type: u32, bb_max: Vec3, esc_index: u32, } ...
impl Bounded for Leaf { fn get_bounds(&self) -> AABB { match self { Leaf::S(s) => s.get_bounds(), } } } impl Bounded for BVHElement { fn get_bounds(&self) -> AABB { return match self { BVHElement::Node(n) => AABB { min: n.bb_min, ...
fn axis_size(v: Vec3, axis: Vec3) -> f32 { let d = v * axis; match (d.x() != 0.0, d.y() != 0.0, d.z() != 0.0) { (true, false, false) => return d.x(), (false, true, false) => return d.y(), (false, false, true) => return d.z(), _ => return 0.0, } }
function_block-full_function
[ { "content": "fn sphereflake(pos: Vec3, axis: Vec3, r: f32, depth: u32) -> Vec<geometry::Sphere> {\n\n const MAX_DEPTH: u32 = 3;\n\n\n\n let mat = match depth % 2 {\n\n 0 => 1,\n\n _ => 2,\n\n };\n\n let mut s = vec![geometry::Sphere::new(pos, r, mat)];\n\n\n\n if depth == MAX_DEPTH...
Rust
manufacturing-server/src/handlers/diun.rs
say-paul/fido-device-onboard-rs
61145c33f1e58be9bf07ee59812c077bd0647b55
use crate::{ ManufacturingServiceUD, ManufacturingServiceUDT, DEVICE_KEY_FROM_DIUN_SES_KEY, PERFORMED_DIUN_SES_KEY, }; use fdo_data_formats::{ constants::{ErrorCode, HeaderKeys}, messages::{self, ClientMessage, Message}, types::{COSEHeaderMap, COSESign, KeyDeriveSide, KeyExchange}, }; use fdo_http...
use crate::{ ManufacturingServiceUD, ManufacturingServiceUDT, DEVICE_KEY_FROM_DIUN_SES_KEY, PERFORMED_DIUN_SES_KEY, }; use fdo_data_formats::{ constants::{ErrorCode, HeaderKeys}, messages::{self, ClientMessage, Message}, types::{COSEHeaderMap, COSESign, KeyDeriveSide, KeyExchange}, }; use fdo_http...
pub(crate) async fn provide_key( user_data: ManufacturingServiceUDT, mut ses_with_store: RequestInformation, msg: messages::v11::diun::ProvideKey, ) -> Result<(messages::v11::diun::Done, RequestInformation), warp::Rejection> { fail_if_no_diun::<messages::v11::diun::ProvideKey>(&user_data)?; let mut...
function_block-full_function
[ { "content": "fn load_private_key(path: &str) -> Result<PKey<Private>, Error> {\n\n let contents = fs::read(path)?;\n\n Ok(PKey::private_key_from_der(&contents)?)\n\n}\n\n\n", "file_path": "owner-tool/src/main.rs", "rank": 0, "score": 263499.5333560065 }, { "content": "fn install_ssh_k...
Rust
kernel/src/mm/heap/slab_allocator/slab.rs
tstree-oscomp2021/hecto-os
285141beba9d946bfdd1c15135e0f41d12eadc7f
use core::{ alloc::{GlobalAlloc, Layout}, cmp::{max, min}, mem::size_of, ptr::null_mut, }; use super::{linked_list::forward_list::*, page::*}; use crate::VA; #[derive(Copy, Clone)] pub struct SlabAllocator; struct SlabChunk; type SlabChunkList = ForwardList<SlabChunk>; type SlabChunkNode = ForwardLis...
use core::{ alloc::{GlobalAlloc, Layout}, cmp::{max, min}, mem::size_of, ptr::null_mut, }; use super::{linked_list::forward_list::*, page::*}; use crate::VA; #[derive(Copy, Clone)] pub struct SlabAllocator; struct SlabChunk; type SlabChunkList = ForwardList<SlabChunk>; type SlabChunkNode = ForwardLis...
unsafe fn malloc(mut size: usize) -> *mut SlabChunkNode { let chunk: *mut SlabChunkNode; let kup: *mut PageUsage; let mut zn: *mut SlabZoneNode; let zi: usize; if size == 0 { return null_mut(); } if size > CHUNK_LIMIT { ...
7, 0usize.leading_zeros() as usize - n.leading_zeros() as usize, ) - 1 - 3; n = round_up!(n, 1 << i); *bytes = n; return (n >> i) + 8 * (i - 3) - 1; }
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn get_sched_cx() -> &'static mut *const TaskContextImpl {\n\n unsafe { transmute(&mut (&mut *SCHEDULE_THREAD).task_cx) }\n\n}\n", "file_path": "kernel/src/process/schedule.rs", "rank": 0, "score": 296754.9463868729 }, { "content": "/// 获取当前线程的 TrapFrame 的可变...
Rust
src/runner.rs
hhandika/fastp-runner
ddfe0eddc3793a9b2a69710983f8c5103980d248
use std::fs; use std::str; use std::io::{self, Result, BufWriter, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; #[cfg(target_family="unix")] use std::os::unix; use spinners::{Spinner, Spinners}; use crate::parser::RawSeq; use crate::utils; pub fn check_fastp() { let out = Command:...
use std::fs; use std::str; use std::io::{self, Result, BufWriter, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; #[cfg(target_family="unix")] use std::os::unix; use spinners::{Spinner, Spinners}; use crate::parser::RawSeq; use crate::utils; pub fn check_fastp() { let out = Command:...
#[cfg(target_family="unix")] fn create_symlink(&self) -> Result<()> { let symdir = self.clean_dir.join("raw_read_symlinks"); fs::create_dir_all(&symdir)?; let abs_r1 = self.reads.read_1.canonicalize().unwrap(); let abs_r2 = self.reads.read_2.canonicalize().unwrap()...
e_symlink().unwrap(); } else { println!("Skip creating symlink in dir {} for {} and {}. \ Operating system is not supported.", &self.clean_dir.to_string_lossy(), &self.reads.read_1.to_string_lossy(), &self.reads.read_2.to_string_loss...
function_block-function_prefixed
[ { "content": "pub fn dry_run(input: &PathBuf, is_id: bool, is_rename: bool) {\n\n display_fastp_status();\n\n let reads: Vec<RawSeq> = parser::parse_csv(input, is_id, is_rename);\n\n let stdout = io::stdout();\n\n let mut handle = io::BufWriter::new(stdout);\n\n\n\n writeln!(handle).unwrap();\n\n...
Rust
src/deb.rs
coderstephen/deb
eae9caef86540a2dff6f7de05dbb0795701d6918
use ar; use flate2::Compression; use flate2::write::GzEncoder; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use tar; use time; #[cfg(unix)] use std::os::unix::fs::MetadataExt; pub enum Arch { X86, X64, All, } impl ToString for Arch { fn to_string(...
use ar; use flate2::Compression; use flate2::write::GzEncoder; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use tar; use time; #[cfg(unix)] use std::os::unix::fs::MetadataExt; pub enum Arch { X86, X64, All, } impl ToString for Arch { fn to_string(...
} pub struct Package { pub name: String, pub files: Vec<(PathBuf, PathBuf)>, pub priority: Priority, pub section: String, pub depends: Vec<(String, String)>, pub maintainer: String, pub arch: Arch, pub version: String, pub homepage: Option<String>, pub short_desc: String, p...
fn to_string(&self) -> String { match *self { Priority::Essential => "essential", Priority::Extra => "extra", Priority::Important => "important", Priority::Optional => "optional", Priority::Required => "required", Priority::Standard => "sta...
function_block-full_function
[ { "content": "fn tar(environment: Environment) -> ScriptResult {\n\n let path = environment.state().check_string(1).to_string();\n\n environment.state().check_type(2, lua::Type::Table);\n\n\n\n let file = File::create(path).unwrap();\n\n let archive = Archive::new(file);\n\n\n\n for mut item in e...
Rust
chain-tx-enclave-next/mls/src/keypackage.rs
Itchibon777/chain
48ddd62c467795757620a5bda011fe0a287b887d
#[cfg(target_env = "sgx")] use std::convert::TryInto; use std::time::{Duration, UNIX_EPOCH}; use ra_client::{AttestedCertVerifier, CertVerifyResult, EnclaveCertVerifierError}; #[cfg(target_env = "sgx")] use ra_enclave::{Certificate, EnclaveRaContext, EnclaveRaContextError}; use rustls::internal::msgs::codec::{self, C...
#[cfg(target_env = "sgx")] use std::convert::TryInto; use std::time::{Duration, UNIX_EPOCH}; use ra_client::{AttestedCertVerifier, CertVerifyResult, EnclaveCertVerifierError}; #[cfg(target_env = "sgx")] use ra_enclave::{Certificate, EnclaveRaContext, EnclaveRaContextError}; use rustls::internal::msgs::codec::{self, C...
let Certificate { certificate, private_key, .. } = ra_ctx.get_certificate()?; let (_, cert) = parse_x509_der(&certificate.0).expect("invalid cert"); let x509::Validity { not_before, not_after, } = &cert.tbs_certificate.valid...
x509_parser::{parse_x509_der, x509}; use crate::credential::Credential; use crate::extensions::{self as ext, MLSExtension}; use crate::key::{HPKEPrivateKey, HPKEPublicKey, IdentityPrivateKey, IdentityPublicKey}; use crate::utils; use core::cmp::Ordering; pub type ProtocolVersion = u8; pub type Timespec = u64; pub ty...
random
[ { "content": "#[allow(clippy::option_option)]\n\npub fn decode_option<T: Codec>(r: &mut Reader) -> Option<Option<T>> {\n\n let present = u8::read(r)?;\n\n match present {\n\n 0 => Some(None),\n\n 1 => {\n\n let v = T::read(r)?;\n\n Some(Some(v))\n\n }\n\n ...
Rust
src/writer/file_rotation.rs
cspinetta/jon-listen
89134524b67443d7620b11bb840dfb9dfe04d0f8
use std::thread::{self, JoinHandle}; use std::path::Path; use std::path::PathBuf; use std::io; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use chrono::prelude::*; use regex::Regex; use glob::glob; use glob::PatternError; use glob::GlobError; use std::sync::mpsc::SyncSender; use writer::file_writer::FileWrit...
use std::thread::{self, JoinHandle}; use std::path::Path; use std::path::PathBuf; use std::io; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use chrono::prelude::*; use regex::Regex; use glob::glob; use glob::PatternError; use glob::GlobError; use std::sync::mpsc::SyncSender; use writer::file_writer::FileWrit...
fn search_files(path: PathBuf) -> Result<Vec<PathBuf>, RotateError> { let files_query = path.to_str().ok_or(RotateError::OtherError(format!("Impossible get file path from {:?}", &path)))?; let files_query = format!("{}.*", files_query); let mut files: Vec<PathBuf> = vec![]; for r...
fn request_rotate(&self) -> Result<PathBuf, RotateError> { let files: Vec<PathBuf> = Self::search_files(self.file_path.clone())?; let new_path = if files.len() >= self.max_files as usize { self.oldest_file(&files)? } else { self.next_path(&files)? }; se...
function_block-full_function
[ { "content": "fn extract_command_arg(args: &mut Vec<String>, names: Vec<String>) -> bool {\n\n match args.iter().position(|a| names.contains(a)) {\n\n Some(i) => {\n\n args.remove(i);\n\n true\n\n }\n\n None => false,\n\n }\n\n}\n\n\n\nmod tcp {\n\n use std::i...
Rust
diesel_tests/tests/expressions/date_and_time.rs
wadsager/diesel
2296d23abdd439bc18c4c90bfd9fab364baf1599
use schema::{connection, TestConnection}; use diesel::*; use diesel::data_types::*; use diesel::expression::dsl::*; table! { has_timestamps { id -> Integer, created_at -> Timestamp, updated_at -> Timestamp, } } operator_allowed!(has_timestamps::created_at, Add, add); table! { has_t...
use schema::{connection, TestConnection}; use diesel::*; use diesel::data_types::*; use diesel::expression::dsl::*; table! { has_timestamps { id -> Integer, created_at -> Timestamp, updated_at -> Timestamp, } } operator_allowed!(has_timestamps::created_at, Add, add); table! { has_t...
res")] fn time_is_deserialized_properly() { use self::has_time::dsl::*; let connection = connection(); setup_test_table(&connection); connection.execute("INSERT INTO has_time (\"time\") VALUES ('00:00:01'), ('00:02:00'), ('03:00:00') ").unwrap(); let on...
.load::<i32>(&connection); let after_today = has_timestamps.select(id) .filter(created_at.gt(now)) .load::<i32>(&connection); assert_eq!(Ok(vec![1]), before_today); assert_eq!(Ok(vec![2]), after_today); } #[test] #[cfg(not(feature="mysql"))] fn date_uses_sql_function_date() { ...
random
[]
Rust
src/tag.rs
335g/tiff
f5aee5976c4eb284fcec5e965b8845b125755d26
use std::fmt::{ self, Display, }; use std::io::{ Read, Seek, }; use error::{ DecodeResult, DecodeError, DecodeErrorKind, }; use ifd::DataType; use byte::{ Endian, EndianReadExt, SeekExt, }; pub trait TagType: Clone + Copy { type Value; fn id(&self) -> u16; fn defau...
use std::fmt::{ self, Display, }; use std::io::{ Read, Seek, }; use error::{ DecodeResult, DecodeError, DecodeErrorKind, }; use ifd::DataType; use byte::{ Endian, EndianReadExt, SeekExt, }; pub trait TagType: Clone + Copy { type Value; fn id(&self) -> u16; fn defau...
u8], endian: Endian, datatype: DataType, count: usize) -> DecodeResult<Self::Value> { match datatype { DataType::Short if count == 1 => Ok(offset.read_u16(endian)? as u32), DataType::Long if count == 1 => Ok(offset.read_u32(endian)?), _ => Err(...
pub struct $name; impl Display for $name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", $name) } })* #[derive(Debug, Fail)] pub enum AnyTag { $($name,)* Unknown(u16), } ...
random
[ { "content": "pub trait EndianReadExt: Read {\n\n fn read_u8(&mut self) -> io::Result<u8> {\n\n <Self as ReadBytesExt>::read_u8(self)\n\n }\n\n\n\n fn read_u16(&mut self, byte_order: Endian) -> io::Result<u16> {\n\n match byte_order {\n\n Endian::Big => <Self as ReadBytesExt>::...
Rust
src/blob.rs
jimblandy/harfbuzz_rs
163cefe006b463f6330d28cf14dfb56e3626cc87
use hb; use libc::c_void; use std; use std::marker::PhantomData; use std::path::Path; use std::fs::File; use std::io::Read; use std::fmt; use common::{HarfbuzzObject, Owned, Shared}; #[repr(C)] pub struct Blob<'a> { _raw: hb::hb_blob_t, _marker: PhantomData<&'a mut [u8]>, } impl<'a> Blob<'a> { pub ...
use hb; use libc::c_void; use std; use std::marker::PhantomData; use std::path::Path; use std::fs::File; use std::io::Read; use std::fmt; use common::{HarfbuzzObject, Owned, Shared}; #[repr(C)] pub struct Blob<'a> { _raw: hb::hb_blob_t, _marker: PhantomData<&'a mut [u8]>, } impl<'a> Blob<'a> { pub ...
} } } } impl<'a> fmt::Debug for Blob<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Blob") .field("data", &self.get_data()) .finish() } } impl<'a> HarfbuzzObject for Blob<'a> { type Raw = hb::hb_blob_t; unsafe fn r...
Some(std::slice::from_raw_parts_mut( data_ptr as *mut u8, length as usize, ))
call_expression
[ { "content": "// Execute this file from the root directory of this repository.\n\n//\n\n// The output should look like the following:\n\n// gid09=00@ 634,0+0\n\n// gid32=01@ 478,0+0\n\n// gid39=02@ 230,0+0\n\n// gid39=03@ 230,0+0\n\n// gid42=04@ 520,0+0\n\n// gid01=05@ 200,0+0\n\n// gid24=06@ 764,0+0\n\n// gid4...
Rust
serde-generate/src/generate.rs
zefchain/serde-reflection
3bc9fa7422a2e725960ae8a1166f6929961f6128
use serde_generate::{ cpp, csharp, dart, golang, java, ocaml, python3, rust, swift, typescript, CodeGeneratorConfig, Encoding, SourceInstaller, }; use serde_reflection::Registry; use std::path::PathBuf; use structopt::{clap::arg_enum, StructOpt}; arg_enum! { #[derive(Debug, StructOpt)] enum Language { Py...
use serde_generate::{ cpp, csharp, dart, golang, java, ocaml, python3, rust, swift, typescript, CodeGeneratorConfig, Encoding, SourceInstaller, }; use serde_reflection::Registry; use std::path::PathBuf; use structopt::{clap::arg_enum, StructOpt}; arg_enum! { #[derive(Debug, StructOpt)] enum Language { Py...
all_dir)), }; if let Some((registry, name)) = named_registry_opt { let config = get_codegen_config(name, &runtimes, options.use_c_style_enums); installer.install_module(&config, &registry).unwrap(); } for runtime in runtimes { ...
std::collections::BTreeSet<_> = options.with_runtimes.into_iter().collect(); match options.target_source_dir { None => { if let Some((registry, name)) = named_registry_opt { let config = get_codegen_config(name, &runtimes, options.use_c_style_enums); let stdout ...
random
[ { "content": "fn main() {{\n\n for encoding in vec![{}] {{\n\n let value = {}::<SerdeData>(&encoding).unwrap();\n\n let s = {}(&value).unwrap();\n\n assert_eq!(s, encoding);\n\n }}\n\n}}\n\n\"#,\n\n encodings.join(\", \"),\n\n runtime.quote_deserialize(),\n\n runt...
Rust
beacon_node/http_api/src/proposer_duties.rs
buchhlz2/lighthouse
fff01b24ddedcd54486e374460855ca20d3dd232
use crate::state_id::StateId; use beacon_chain::{ BeaconChain, BeaconChainError, BeaconChainTypes, MAXIMUM_GOSSIP_CLOCK_DISPARITY, }; use eth2::types::{self as api_types}; use slog::{debug, Logger}; use slot_clock::SlotClock; use state_processing::state_advance::partial_state_advance; use std::cmp::Ordering; use ...
use crate::state_id::StateId; use beacon_chain::{ BeaconChain, BeaconChainError, BeaconChainTypes, MAXIMUM_GOSSIP_CLOCK_DISPARITY, }; use eth2::types::{self as api_types}; use slog::{debug, Logger}; use slot_clock::SlotClock; use state_processing::state_advance::partial_state_advance; use std::cmp::Ordering; use ...
rror(format!( "state epoch {} not equal to request epoch {}", state.current_epoch(), epoch ))); } let indices = state .get_beacon_proposer_indices(&chain.spec) .map_err(BeaconChainError::from) .map_err(warp_utils::reject::beacon_chain_error)?;...
Ordering::Greater => { return Err(warp_utils::reject::custom_server_error(format!( "head epoch {} is later than request epoch {}", head_epoch, request_epoch ))) } }; chain .beacon_proposer_cache .lock() .get_epoch::<T::Eth...
random
[ { "content": "fn eth1_logging<T: BeaconChainTypes>(beacon_chain: &BeaconChain<T>, log: &Logger) {\n\n let current_slot_opt = beacon_chain.slot().ok();\n\n\n\n if let Ok(head_info) = beacon_chain.head_info() {\n\n // Perform some logging about the eth1 chain\n\n if let Some(eth1_chain) = beac...
Rust
src/hashgraph/graph.rs
DrStiev/rs-handlegraph2
c1f9cf6249739d73f3fce75e52847d18ffcf28ea
use fnv::FnvHashMap; use gfa2::{ gfa1::{Link, Segment as Segment1, GFA}, gfa2::{orientation::Orientation, Edge, GroupO, GroupU, Segment, GFA2}, tag::OptFields, }; use crate::{ handle::{Edge as GraphEdge, Handle, NodeId}, handlegraph::*, mutablehandlegraph::*, pathgraph::PathHandleGraph, };...
use fnv::FnvHashMap; use gfa2::{ gfa1::{Link, Segment as Segment1, GFA}, gfa2::{orientation::Orientation, Edge, GroupO, GroupU, Segment, GFA2}, tag::OptFields, }; use crate::{ handle::{Edge as GraphEdge, Handle, NodeId}, handlegraph::*, mutablehandlegraph::*, pathgraph::PathHandleGraph, };...
} pub fn print_path(&self, path_id: &PathId) { let path = self.paths.get(&path_id).unwrap(); println!("Path\t{}", path_id); for (ix, handle) in path.nodes.iter().enumer...
let pb_path = ProgressBar::new(1000); pb_path.set_style(ProgressStyle::default_bar().template( "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] [{pos}/{pos}]", )); */ let mut graph = Self::new(); gfa.segments .iter() /*.progress_wit...
function_block-random_span
[ { "content": "/// Function that takes a HashGraph object as input and return a GFA object\n\n/// This function is still ```Work In Progress``` so it's not perfect.\\\n\n/// Sometimes can leads to unexpected bugs.\n\n/// # Example\n\n/// ```ignore\n\n/// let parser = GFAParser::new();\n\n/// let gfa_in: GFA<BStr...
Rust
src/ai.rs
armin-afd/Legions-AI
3b28c71adbf0125aba90e386a4a7653b25a849d5
use std::{ cmp::{max, min}, io::{stdout, Write}, sync::mpsc::channel, thread, }; use crate::card::*; use crate::utility::*; fn available_moves( board: &[[Option<Card>; 5]; 4], bombs: &mut [[u8; 5]; 4], deck: &Vec<Card>, player: u8, ) -> Vec<(usize, usize, usize, [Option<(usize, usize)>...
use std::{ cmp::{max, min}, io::{stdout, Write}, sync::mpsc::channel, thread, }; use crate::card::*; use crate::utility::*; fn available_moves( board: &[[Option<Card>; 5]; 4], bombs: &mut [[u8; 5]; 4], deck: &Vec<Card>, player: u8, ) -> Vec<(usize, usize, usize, [Option<(usize, usize)>...
t mov = moves[m]; let temp_board: [[Option<Card>; 5]; 4] = copy_board(&board); let temp_card = { if player == 1 { Card::copy(&deck1[mov.0]) } else { Card::copy(&deck2[mov.0]) } }; let temp_b...
( board: &mut [[Option<Card>; 5]; 4], deck1: &mut Vec<Card>, deck2: &mut Vec<Card>, bombs: &mut [[u8; 5]; 4], player: u8, mut alpha: i8, mut beta: i8, depth: (u8, u8), ) -> i8 { if deck2.is_empty() { let (p1_score, p2_score) = calc_scores(&board); if p1_score > p...
random
[ { "content": "// calculates score for each player\n\npub fn calc_scores(board: &[[Option<Card>; 5]; 4]) -> (i8, i8) {\n\n let mut p1: i8 = 1;\n\n let mut p2: i8 = 0;\n\n\n\n for i in 0..4 {\n\n for j in 0..5 {\n\n let card = board[i][j].as_ref();\n\n match card {\n\n ...
Rust
builder/src/lib.rs
jstarry/proc-macro-workshop
fb8339ac9cd34b5f8eb923711fed7547f0e5242a
extern crate proc_macro; extern crate quote; extern crate syn; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::{quote, ToTokens}; use std::error::Error; use syn::parse_macro_input; use syn::spanned::Spanned; use syn::{ punctuated, AngleBracketedGenericArguments, DeriveInput, Field, GenericA...
extern crate proc_macro; extern crate quote; extern crate syn; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::{quote, ToTokens};
t { ident, arguments: PathArguments::AngleBracketed(AngleBracketedGenericArguments { args, .. }), }) => Some((ident, args)), _ => None, }?; let wrapped_ty = match type_args.first()? { punctuated::Pair::End(GenericArgument::Type(ref ty)) => Some(ty), _ => ...
use std::error::Error; use syn::parse_macro_input; use syn::spanned::Spanned; use syn::{ punctuated, AngleBracketedGenericArguments, DeriveInput, Field, GenericArgument, Lit, Meta, NestedMeta, Path, PathArguments, PathSegment, Type, TypePath, }; struct VecInfo<'a> { ty: &'a Type, ident: Option<Ident>,...
random
[ { "content": "// The procedural macro API uses a type called Span to attach source location\n\n// and hygiene information to every token. In order for compiler errors to\n\n// appear underlining the right places, procedural macros are responsible for\n\n// propagating and manipulating these spans correctly.\n\n...
Rust
src/day22/day22.rs
bwestlin/advent-of-code-2018-rs
480b67b7eb5efbc6c6661661ec82a8ffb351831c
extern crate utils; use std::collections::HashSet; use std::collections::HashMap; use std::str::FromStr; use std::error::Error; use std::num::ParseIntError; use std::io::{self, BufReader}; use std::io::prelude::*; use std::fs::File; use utils::*; #[derive(PartialEq, Eq, Hash, Clone, Copy)] struct Pos { x: usize, ...
extern crate utils; use std::collections::HashSet; use std::collections::HashMap; use std::str::FromStr; use std::error::Error; use std::num::ParseIntError; use std::io::{self, BufReader}; use std::io::prelude::*; use std::fs::File; use utils::*; #[derive(PartialEq, Eq, Hash, Clone, Copy)] struct Pos { x: usize, ...
sited.insert((start_pos, Torch), 0); to_eval.insert((start_pos, Torch, 0)); let tool_valid = |rt: &RegionType, t: &Tool| { match (rt, t) { (Rocky, Neither) => false, (Wet, Torch) => false, (Narrow, Gear) => false, _ => true ...
0 => RegionType::Rocky, 1 => RegionType::Wet, 2 => RegionType::Narrow, _ => unreachable!() } } } } #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] enum Tool { Torch, Gear, Neither } struct CaveSystem { target: Pos, r...
random
[ { "content": "fn part2(polymer: &str) -> i32 {\n\n let units = polymer.chars()\n\n .fold(BTreeMap::new(), |mut units: BTreeMap<char, BTreeSet<char>>, c| {\n\n units.entry(c.to_ascii_uppercase()).or_insert(BTreeSet::new()).insert(c);\n\n units\n\n });\n\n\n\n units.iter(...
Rust
src/application.rs
matheuslessarodrigues/verco
6084a2dfb2ec7cbf2bc53c073dccf8a49efcc625
use std::{ io, sync::{mpsc, Arc}, thread, time::Duration, }; use crate::{ backend::Backend, mode::{self, ModeContext, ModeKind, ModeResponse}, platform::{Key, Platform, PlatformEventReader}, ui::Drawer, }; enum Event { Key(Key), Resize(u16, u16), Response(ModeResponse), ...
use std::{ io, sync::{mpsc, Arc}, thread, time::Duration, }; use crate::{ backend::Backend, mode::{self, ModeContext, ModeKind, ModeResponse}, platform::{Key, Platform, PlatformEventReader}, ui::Drawer, }; enum Event { Key(Key), Resize(u16, u16), Response(ModeResponse), ...
} fn terminal_event_loop(mut event_reader: PlatformEventReader, sender: mpsc::SyncSender<Event>) { event_reader.init(); let mut keys = Vec::new(); loop { keys.clear(); let mut resize = None; event_reader.read_terminal_events(&mut keys, &mut resize); for &key in &keys { ...
pub fn draw_body(&self, drawer: &mut Drawer) { match &self.current_mode { ModeKind::Status => self.status_mode.draw(drawer), ModeKind::Log => self.log_mode.draw(drawer), ModeKind::RevisionDetails(_) => { self.revision_details_mode.draw(drawer); } ...
function_block-full_function
[ { "content": "pub fn fuzzy_matches(text: &str, pattern: &str) -> bool {\n\n let mut pattern_chars = pattern.chars();\n\n let mut pattern_char = match pattern_chars.next() {\n\n Some(c) => c,\n\n None => return true,\n\n };\n\n\n\n let mut previous_matched_index = 0;\n\n let mut was_...
Rust
src/view/canvas.rs
andycking/pixwiz-rust
6a986a5ca16356e63f59aacfda017a40f20b1809
use druid::widget::prelude::*; use crate::common::commands; use crate::model::app::AppState; use crate::model::types::*; use crate::util::shapes; use crate::view::theme; pub struct Canvas { long_dash: [druid::piet::StrokeStyle; 2], short_dash: [druid::piet::StrokeStyle; 2], } impl Canvas { pub fn ...
use druid::widget::prelude::*; use crate::common::commands; use crate::model::app::AppState; use crate::model::types::*; use crate::util::shapes; use crate::view::theme; pub struct Canvas { long_dash: [druid::piet::StrokeStyle; 2], short_dash: [druid::piet::StrokeStyle; 2], } impl Canvas { pub fn ...
fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, _env: &Env) { self.paint_border(ctx, data); self.paint_pixels(ctx, data); self.paint_grid(ctx, data); self.paint_selection(ctx, data); } } pub struct CanvasController; impl<W: Widget<AppState>> druid::widget::Controller...
fn layout( &mut self, _layout_ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &AppState, _env: &Env, ) -> Size { let rect = Self::screen_rect(theme::CANVAS_DIMS, theme::CANVAS_DIMS); let size = Size::new(rect.x1 + 1.0, rect.y1 + 1.0); bc.constrain(siz...
function_block-full_function
[ { "content": "fn dismiss(ctx: &mut EventCtx, data: &mut AppState, _env: &Env) {\n\n data.reset_window_state();\n\n ctx.submit_command(druid::commands::CLOSE_WINDOW);\n\n}\n\n\n", "file_path": "src/view/alert.rs", "rank": 0, "score": 339131.8765219884 }, { "content": "pub fn new(ctx: &m...
Rust
controller/src/util/shared_test_utils.rs
bfjelds/akri-1
55daf105284c2643a4b9eb5b0beb6edd37036b1a
#[cfg(test)] pub mod config_for_tests { use akri_shared::{ akri::{ configuration::KubeAkriConfig, instance::{Instance, KubeAkriInstance, KubeAkriInstanceList}, }, k8s::MockKubeInterface, os::file, }; use k8s_openapi::api::core::v1::{PodSpec, PodStatus,...
#[cfg(test)] pub mod config_for_tests { use akri_shared::{ akri::{ configuration::KubeAkriConfig, instance::{Instance, KubeAkriInstance, KubeAkriInstanceList}, }, k8s::MockKubeInterface, os::file, }; use k8s_openapi::api::core::v1::{PodSpec, PodStatus,...
}); } pub fn configure_find_pods( mock: &mut MockKubeInterface, pod_selector: &'static str, result_file: &'static str, result_error: bool, ) { trace!( "mock.expect_find_pods_with_label pod_selector:{}", pod_selector ); ...
if result_error { Err(None.ok_or("failure")?) } else { Ok(()) }
if_condition
[ { "content": "/// This tests whether an item should be included according to the `FilterList`\n\npub fn should_include(filter_list: Option<&FilterList>, item: &str) -> bool {\n\n if filter_list.is_none() {\n\n return true;\n\n }\n\n let item_contained = filter_list.unwrap().items.contains(&item....
Rust
crates/eg-renderer-core/src/renderer/renderer.rs
likr/eg-renderer
2b80a931f94a08ada396c4643c470523db382c10
use super::meshes::{ GroupMesh, LabelMesh, LayoutData, LinkCircleMarkerMesh, LinkMesh, LinkTriangleMarkerMesh, LinkType, Mesh, MeshGeometry, NodeMesh, ShapeType, }; use cgmatrix::{identity, matmul, orthogonal_matrix, scale, translate, viewing_matrix, Matrix44}; use std::collections::HashMap; use wasm_bindgen::p...
use super::meshes::{ GroupMesh, LabelMesh, LayoutData, LinkCircleMarkerMesh, LinkMesh, LinkTriangleMarkerMesh, LinkType, Mesh, MeshGeometry, NodeMesh, ShapeType, }; use cgmatrix::{identity, matmul, orthogonal_matrix, scale, translate, viewing_matrix, Matrix44}; use std::collections::HashMap; use wasm_bindgen::p...
}
let near = -10.; let far = 10.; self.context.p_matrix = orthogonal_matrix(left, right, top, bottom, near, far); Ok(()) }
function_block-function_prefix_line
[ { "content": "fn create_instance_data(layout: &LayoutData) -> Vec<f32> {\n\n let mut data = vec![];\n\n for edge in &layout.enter.links {\n\n if edge.source_marker_shape == \"triangle\" {\n\n add_source_marker(&mut data, edge, edge, 0.0, 1.0);\n\n }\n\n if edge.target_marke...
Rust
server/src/webserver/users.rs
khonsulabs/khonsubase
12980659694be1b791ba53de991e2c4e138c63af
use rocket::{ http::{ContentType, Status}, response::content::Content, }; use rocket_contrib::templates::Template; use serde::{Deserialize, Serialize}; use database::schema::accounts::{AccountError, User}; use crate::webserver::{ auth::SessionId, localization::UserLanguage, Failure, FullPathAndQuery, Requ...
use rocket::{ http::{ContentType, Status}, response::content::Content, }; use rocket_contrib::templates::Template; use serde::{Deserialize, Serialize}; use database::schema::accounts::{AccountError, User}; use crate::webserver::{ auth::SessionId, localization::UserLanguage, Failure, FullPathAndQuery, Requ...
#[derive(Serialize, Deserialize)] struct EditUserContext { request: RequestData, user: User, error_message: Option<String>, } #[get("/user/<user_id>/edit")] pub async fn edit_user( user_id: i64, language: UserLanguage, session: Option<SessionId>, path: FullPathAndQuery, ) -> Result<Templa...
await .map_err(|_| Status::NotFound)?; let identicon = identicon_rs::new(user.username).size(8).unwrap(); let identicon = match size { 512 => identicon.scale(384).unwrap().border(64), 256 => identicon.scale(192).unwrap().border(32), 128 => identicon.scale(96).unwrap().border(1...
function_block-function_prefix_line
[ { "content": "pub fn can_edit_issue<I: AuthoredBy>(request: &RequestData, _issue: &I) -> bool {\n\n request.session.is_some()\n\n}\n\n\n\n#[get(\"/issues\")]\n\npub async fn list_issues(\n\n language: UserLanguage,\n\n path: FullPathAndQuery,\n\n session: Option<SessionId>,\n\n) -> Result<Template, ...
Rust
src/lib.rs
jramapuram/parallel_image_crop
3e58847ee249a590048cdceb10991c8520cbe451
extern crate libc; extern crate image; extern crate rayon; extern crate vips_sys; #[macro_use] extern crate itertools; #[macro_use] extern crate lazy_static; use std::ptr; use std::fs::File; use std::path::Path; use std::ffi::{CStr, OsStr, CString}; use std::{slice, str, mem}; use rayon::prelude::*; use libc::{size_t...
extern crate libc; extern crate image; extern crate rayon; extern crate vips_sys; #[macro_use] extern crate itertools; #[macro_use] extern crate lazy_static; use std::ptr; use std::fs::File; use std::path::Path; use std::ffi::{CStr, OsStr, CString}; use std::{slice, str, mem}; use rayon::prelude::*; use libc::{size_t...
#[no_mangle] pub extern "C" fn destroy(crop_manager_ptr: *mut c_void) { println!("into destroy"); let cm: Box<Box<CropManager>> = unsafe { Box::from_raw(crop_manager_ptr as *mut Box<CropManager>) }; } pub struct Job { image_paths_ptr: *const *const c_char, return_p...
pub extern "C" fn initialize(num_threads: u64, use_vips: bool) -> *mut c_void { let cm = Box::new(Box::new(CropManager { threadpool: rayon::ThreadPoolBuilder::new().num_threads(num_threads as usize).build().unwrap(), num_threads: num_threads as usize, use_vips: use_vips, vips_in...
function_block-full_function
[ { "content": "pub fn vips_crop_and_resize(path: &str, scale: f32, x_crop: f32, y_crop: f32,\n\n max_img_percent: f32, resize_width: u32, resize_height: u32) -> Vec<u8>\n\n{\n\n assert!(x_crop >= 0f32 && x_crop <= 1f32, \"x of crop not bounded in [0, 1]\");\n\n assert!(y_crop >= ...
Rust
day8/src/main.rs
jgosmann/aoc2020
da97eb0534eff3cb91c8d42fa8a4f952c7b22541
use std::collections::{HashSet, VecDeque}; use std::fmt::Display; use std::io::{self, BufRead}; #[derive(Clone, Debug, PartialEq)] struct State { accumulator: i32, instruction_pointer: usize, } impl State { fn new() -> Self { Self { accumulator: 0, instruction_pointer: 0, ...
use std::collections::{HashSet, VecDeque}; use std::fmt::Display; use std::io::{self, BufRead}; #[derive(Clone, Debug, PartialEq)] struct State { accumulator: i32, instruction_pointer: usize, } impl State { fn new() -> Self { Self { accumulator: 0, instruction_pointer: 0, ...
fn construct_reverse_flow_graph(program: &[OpCode]) -> Vec<Vec<usize>> { let mut graph = vec![vec![]; program.len() + 1]; for (i, operation) in program.iter().enumerate() { let new_state = reduce( State { accumulator: 0, instruction_pointer: i, ...
fn reduce(state: State, operation: &OpCode) -> State { match operation { OpCode::Acc(value) => State { accumulator: state.accumulator + value, instruction_pointer: state.instruction_pointer + 1, }, OpCode::Jmp(value) => State { accumulator: state.accumulat...
function_block-full_function
[ { "content": "fn process(tokens: impl Iterator<Item = Token>) -> Result<ValueType, ()> {\n\n let mut stack = vec![];\n\n for token in tokens {\n\n stack.push(token);\n\n loop {\n\n if stack.len() < 3 {\n\n break;\n\n }\n\n match (\n\n ...
Rust
src/gap/oob_block.rs
gpace1/bo-tie
911bdd99d6e165747b19f9eeab19ce4e823d7d06
use crate::gap::assigned::IntoRaw; const MIN_LEN: usize = 8; pub struct OobDataBlockBuilder { address: crate::BluetoothDeviceAddress, } impl OobDataBlockBuilder { pub fn new(address: crate::BluetoothDeviceAddress) -> Self { OobDataBlockBuilder { address } } ...
use crate::gap::assigned::IntoRaw; const MIN_LEN: usize = 8; pub struct OobDataBlockBuilder { address: crate::BluetoothDeviceAddress, } impl OobDataBlockBuilder { pub fn new(address: crate::BluetoothDeviceAddress) -> Self { OobDataBlockBuilder { address } } ...
} pub struct OobDataBlockIter { address: crate::BluetoothDeviceAddress, raw: alloc::vec::Vec<u8>, } impl OobDataBlockIter { pub fn new(mut raw: alloc::vec::Vec<u8>) -> Self { let mut len_arr = [0; 2]; len_arr.copy_from_slice(&raw[..2]); let len: usize = <u16>::fro...
data.extend(raw_ad); } data[0..2].copy_from_slice(&<u16>::to_le_bytes(len as u16)); data }
function_block-function_prefix_line
[ { "content": "/// Create service data for 16-bit UUID's\n\npub fn new_16<Data>(uuid: u16, data: Data) -> ServiceData<u16, Data> {\n\n ServiceData::new(uuid, data)\n\n}\n\n\n", "file_path": "src/gap/assigned/service_data.rs", "rank": 0, "score": 186430.96462141295 }, { "content": "/// Crea...
Rust
rust/examples/test-drive/participant.rs
Robert-Steiner/xaynet
63ea2ac8b2793ada3b2f16cddecab808a2d77369
use std::{sync::Arc, time::Duration}; use async_trait::async_trait; use tokio::{sync::mpsc, time::delay_for}; use tracing::{info, warn}; use xaynet_core::mask::Model; use xaynet_sdk::{ client::Client, settings::PetSettings, ModelStore, Notify, StateMachine, TransitionOutcome, XaynetClient,...
use std::{sync::Arc, time::Duration}; use async_trait::async_trait; use tokio::{sync::mpsc, time::delay_for}; use tracing::{info, warn}; use xaynet_core::mask::Model; use xaynet_sdk::{ client::Client, settings::PetSettings, ModelStore, Notify, StateMachine, TransitionOutcome, XaynetClient,...
} impl Participant { pub fn new( settings: PetSettings, xaynet_client: Client<reqwest::Client>, model: Arc<Model>, ) -> (Self, Agent) { let (tx, rx) = mpsc::channel::<Event>(10); let notifier = Notifier(tx); let agent = Agent::new(settings, xaynet_client.clone()...
pub async fn run(mut self, tick: Duration) { loop { self = match self.0.transition().await { TransitionOutcome::Pending(state_machine) => { delay_for(tick).await; Self(state_machine) } TransitionOutcome::Complete...
function_block-full_function
[ { "content": "/// Construct a [`Fetcher`] service\n\npub fn fetcher(event_subscriber: &EventSubscriber) -> impl Fetcher + Sync + Send + Clone + 'static {\n\n let round_params = ServiceBuilder::new()\n\n .buffer(100)\n\n .concurrency_limit(100)\n\n .layer(FetcherLayer)\n\n .service...
Rust
src/cargo/sources/registry/hook.rs
msrv-rs/rargo
91a880b9188ded9fd9e7c5862b6c6dc47cfff061
use crate::core::package_id::PackageId; use crate::util::errors::CargoResult; use crate::util::config::Config; use libloading::Library; use rental::rental; use self::rent_libloading::RentSymbols; use std::process::{Command, Child}; use std::io::{BufRead, BufReader, Write}; use std::process::Stdio; use std::ffi::c_void;...
use crate::core::package_id::PackageId; use crate::util::errors::CargoResult; use crate::util::config::Config; use libloading::Library; use rental::rental; use self::rent_libloading::RentSymbols; use std::process::{Command, Child}; use std::io::{BufRead, BufReader, Write}; use std::process::Stdio; use std::ffi::c_void;...
} impl Drop for HookPlugin { fn drop(&mut self) { self.syms.rent(|syms| (syms.sym_delete)(self.plugin_ctx)); } } struct HookProcess { chld: Child, stdout: Box<dyn BufRead + Send>, } impl HookProcess { fn new(path: &str) -> CargoResult<Self> { let mut chld = Command::new(path) ...
fn hook(&mut self, id: PackageId) -> CargoResult<bool> { let req = serde_json::to_string(&id)?; let f = format!("{}\n", req); match self.query(&f) { 1 => Ok(true), 0 => Ok(false), v => anyhow::bail!("wrong code {}", v), } }
function_block-full_function
[ { "content": "pub fn write_config_at(path: impl AsRef<Path>, contents: &str) {\n\n let path = paths::root().join(path.as_ref());\n\n fs::create_dir_all(path.parent().unwrap()).unwrap();\n\n fs::write(path, contents).unwrap();\n\n}\n\n\n", "file_path": "tests/testsuite/config.rs", "rank": 0, ...
Rust
src/vertex.rs
omni-viral/gfx-mesh
2b11aea90be3675f3b29074314490e97b9543535
use std::borrow::Cow; use std::fmt::Debug; use hal::format::{AsFormat, Format}; use hal::memory::Pod; use hal::pso::{ElemStride, Element}; pub trait Attribute: AsFormat + Debug + PartialEq + Pod + Send + Sync { const NAME: &'static str; const SIZE: ElemStride; } #[repr(C)] #[derive(Clo...
use std::borrow::Cow; use std::fmt::Debug; use hal::format::{AsFormat, Format}; use hal::memory::Pod; use hal::pso::{ElemStride, Element}; pub trait Attribute: AsFormat + Debug + PartialEq + Pod + Send + Sync { const NAME: &'static str; const SIZE: ElemStride; } #[repr(C)] #[derive(Clo...
} impl<T> AsVertexFormat for T where T: Attribute, { const VERTEX_FORMAT: VertexFormat<'static> = VertexFormat { attributes: Cow::Borrowed(&[Element { format: T::SELF, offset: 0, }]), stride: T::SIZE, }; } pub trait WithAttribute<F: Attribute>: AsVertexForm...
fn attribute<F>() -> Element<Format> where F: Attribute, Self: WithAttribute<F>, { <Self as WithAttribute<F>>::ELEMENT }
function_block-full_function
[ { "content": "pub fn is_slice_sorted<T: Ord>(slice: &[T]) -> bool {\n\n is_slice_sorted_by_key(slice, |i| i)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 4, "score": 70731.54894922783 }, { "content": "pub fn is_slice_sorted_by_key<'a, T, K: Ord, F: Fn(&'a T) -> K>(slice: &'a [T], f: ...
Rust
nash-protocol/src/protocol/place_order/request.rs
acatinon/nash-rust
f2350bbd99a3193cadf95ef62d7e62aca9145ec2
use crate::errors::{ProtocolError, Result}; use crate::graphql; use crate::graphql::place_limit_order; use crate::types::neo::PublicKey as NeoPublicKey; use crate::types::PublicKey; use crate::types::{ Asset, AssetAmount, Blockchain, BuyOrSell, Nonce, OrderCancellationPolicy, OrderRate, Rate }; use crate::utils::pa...
use crate::errors::{ProtocolError, Result}; use crate::graphql; use crate::graphql::place_limit_order; use crate::types::neo::PublicKey as NeoPublicKey; use crate::types::PublicKey; use crate::types::{ Asset, AssetAmount, Blockchain, BuyOrSell, Nonce, OrderCancellationPolicy, OrderRate, Rate }; use crate::utils::pa...
fee_rate, nonces.order_nonce, ); Ok(FillOrder::NEO(neo_order)) } } } pub fn blockchain_signatures( &self, signer: &mut Signer, nonces: &[PayloadNonces], ) -> Result<BlockchainSignatures> { ...
let neo_order = neo::FillOrder::new( neo_pub_key, self.source.asset.into(), self.destination.into(), map_crosschain(nonces.nonce_from, chain, self.source.asset.into()), map_crosschain(nonces.nonce_to, chain, self.dest...
function_block-random_span
[ { "content": "pub fn chain_path(chain: Blockchain) -> &'static str {\n\n match chain {\n\n Blockchain::NEO => \"m/44'/888'/0'/0/0\",\n\n Blockchain::Ethereum => \"m/44'/60'/0'/0/0\",\n\n Blockchain::Bitcoin => \"m/44'/0'/0'/0/0\",\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Signe...
Rust
src/scan/path_aa.rs
RazrFalcon/tiny-skia
96fbfcb691a21848772986c57ee9ce228b105f8a
use core::convert::TryFrom; use crate::{Path, IntRect, FillRule, LengthU32, Rect}; use crate::alpha_runs::AlphaRuns; use crate::blitter::Blitter; use crate::color::AlphaU8; use crate::geom::ScreenIntRect; use crate::math::left_shift; #[cfg(all(not(feature = "std"), feature = "libm"))] use crate::scalar::FloatExt; ...
use core::convert::TryFrom; use crate::{Path, IntRect, FillRule, LengthU32, Rect}; use crate::alpha_runs::AlphaRuns; use crate::blitter::Blitter; use crate::color::AlphaU8; use crate::geom::ScreenIntRect; use crate::math::left_shift; #[cfg(all(not(feature = "std"), feature = "libm"))] use crate::scalar::FloatExt; ...
} impl Drop for SuperBlitter<'_> { fn drop(&mut self) { self.flush(); } } impl Blitter for SuperBlitter<'_> { fn blit_h(&mut self, mut x: u32, y: u32, mut width: LengthU32) { let iy = (y >> SHIFT) as i32; debug_assert!(iy >= self.base.curr_iy); match x....
fn flush(&mut self) { if self.base.curr_iy >= self.base.top { if !self.runs.is_empty() { self.base.real_blitter.blit_anti_h( self.base.left, u32::try_from(self.base.curr_iy).unwrap(), &mut self.runs.alpha, ...
function_block-full_function
[ { "content": "pub fn left_shift(value: i32, shift: i32) -> i32 {\n\n ((value as u32) << shift) as i32\n\n}\n\n\n", "file_path": "src/math.rs", "rank": 0, "score": 393906.2631946779 }, { "content": "fn fill_fixed_rect(rect: &FixedRect, blitter: &mut dyn Blitter) {\n\n fill_dot8(\n\n ...
Rust
redpwn/2020/tetanus/tetanus.rs
Xelentra1/CTFium
d254237035a49099d8721e6e70d65b688afe355c
#![feature(alloc_system)] #![allow(while_true)] extern crate alloc_system; use std::collections::VecDeque; use std::io; use std::process; use std::io::Write; use std::ptr; fn menu() { println!("1. Create a list"); println!("2. Delete a list"); println!("3. Edit a list"); println!("4. Prepend to list...
#![feature(alloc_system)] #![allow(while_true)] extern crate alloc_system; use std::collections::VecDeque; use std::io; use std::process; use std::io::Write; use std::ptr; fn menu() { println!("1. Create a list"); println!("2. Delete a list"); println!("3. Edit a list"); println!("4. Prepend to list...
fn prepend(lists: &mut Vec<VecDeque<i64>>) { println!("Which list do you want to prepend to?"); let mut list_i = String::new(); prompt(); io::stdin() .read_line(&mut list_i) .expect("failed to read input."); let list_i: usize = list_i.trim().parse().expect("invalid input"); le...
alid input"); let vec_deque: &mut VecDeque<i64> = lists.get_mut(list_i).unwrap(); println!("Okay, which element do you want to edit?"); let mut list_i = String::new(); prompt(); io::stdin() .read_line(&mut list_i) .expect("failed to read input."); let list_i: usize = list_i.tri...
function_block-function_prefixed
[ { "content": "fn prepend(lists: &mut Vec<VecDeque<i64>>) {\n\n println!(\"Which list do you want to prepend to?\");\n\n let mut list_i = String::new();\n\n prompt();\n\n io::stdin()\n\n .read_line(&mut list_i)\n\n .expect(\"failed to read input.\");\n\n let list_i: usize = list_i.tr...
Rust
src/utils.rs
exoego/ouch
49a9740e422bc3ce0fcf206eaa8701a5ea4cd058
use std::{ cmp, env, ffi::OsStr, fs::{self, ReadDir}, path::Component, path::{Path, PathBuf}, }; use crate::{dialogs::Confirmation, info, oof}; pub fn dir_is_empty(dir_path: &Path) -> bool { let is_empty = |mut rd: ReadDir| rd.next().is_none(); dir_path.read_dir().map(is_empty).unwrap_or_...
use std::{ cmp, env, ffi::OsStr, fs::{self, ReadDir}, path::Component, path::{Path, PathBuf}, }; use crate::{dialogs::Confirmation, info, oof}; pub fn dir_is_empty(dir_path: &Path) -> bool { let is_empty = |mut rd: ReadDir| rd.next().is_none(); dir_path.read_dir().map(is_empty).unwrap_or_...
}
fn test_pretty_bytes_formatting() { fn format_bytes(bytes: u64) -> String { format!("{}", Bytes::new(bytes)) } let b = 1; let kb = b * 1000; let mb = kb * 1000; let gb = mb * 1000; assert_eq!("0 B", format_bytes(0)); assert_eq!("1.00 B", form...
function_block-full_function
[ { "content": "pub fn compress_files(at: &Path, paths_to_compress: &[PathBuf], format: &str) -> PathBuf {\n\n let archive_path = String::from(\"archive.\") + format;\n\n let archive_path = at.join(archive_path);\n\n\n\n let command = Command::Compress { files: paths_to_compress.to_vec(), output_path: ar...
Rust
src/persistence.rs
piropaolo/cleora
7846461f785b8dfdb6e77f60d38e1e0ae0988666
pub mod entity { use rustc_hash::FxHashMap; use std::sync::RwLock; pub trait EntityMappingPersistor { fn get_entity(&self, hash: u64) -> Option<String>; fn put_data(&self, hash: u64, entity: String); fn contains(&self, hash: u64) -> bool; } #[derive(Debug, Default)] pub...
pub mod entity { use rustc_hash::FxHashMap; use std::sync::RwLock; pub trait EntityMappingPersistor { fn get_entity(&self, hash: u64) -> Option<String>; fn put_data(&self, hash: u64, entity: String); fn contains(&self, hash: u64) -> bool; } #[derive(Debug, Default)] pub...
} }
r, format!("Could not save embedding array: {}", other), ), })?; if let Some(occurences_buf) = self.occurences_buf.as_mut() { let occur = ndarray::ArrayView1::from(&self.occurences); occur.write_npy(occurences_buf).map_err(|e| ...
function_block-function_prefixed
[ { "content": "/// Extract columns config based on raw strings.\n\npub fn extract_fields(cols: Vec<&str>) -> Result<Vec<Column>, String> {\n\n let mut columns: Vec<Column> = Vec::new();\n\n\n\n for col in cols {\n\n let parts: Vec<&str> = col.split(\"::\").collect();\n\n\n\n let column_name: ...
Rust
src/sync/subscription.rs
keroro520/testground-sdk-rust-public
a88d19fdbe42c703044f3f78a4940ef1c9eb244c
use crate::sync::client::REDIS_PAYLOAD_KEY; use crate::sync::types::{Payload, Subscription}; use crossbeam_channel::{bounded, select, Receiver, Sender}; use log::{debug, error, info, warn}; use redis::{Client as RedisClient, Commands, Connection, FromRedisValue, Value}; use std::collections::{HashMap, HashSet}; use std...
use crate::sync::client::REDIS_PAYLOAD_KEY; use crate::sync::types::{Payload, Subscription}; use crossbeam_channel::{bounded, select, Receiver, Sender}; use log::{debug, error, info, warn}; use redis::{Client as RedisClient, Commands, Connection, FromRedisValue, Value}; use std::collections::{HashMap, HashSet}; use std...
fn consume_subscriptions( redis_client: &mut RedisClient, actives: &mut HashMap<String, Subscription>, ) { let mut cmd = redis::cmd("XREAD"); cmd.arg("COUNT").arg(10); cmd.arg("BLOCK").arg(0); cmd.arg("STREAMS"); for sub in actives.values() { cmd.arg(sub.redis_key()).arg(sub.last...
p<String, Subscription>, add_sub_receiver: &Receiver<Subscription>, ) { loop { select! { recv(add_sub_receiver) -> msg => { if let Ok(subscription) = msg { let key = subscription.redis_key(); if actives.contains_key(&key) { ...
function_block-function_prefixed
[ { "content": "fn run_barrier_handler(mut redis_client: RedisClient, receiver: Receiver<Barrier>) {\n\n let mut pending: Vec<Barrier> = Vec::new();\n\n let mut ticker = never();\n\n loop {\n\n select! {\n\n recv(receiver) -> msg => {\n\n if let Ok(barrier) = msg {\n\n ...
Rust
algorithm/src/lib.rs
b401/nidhogg
69df3f047d0259093d3ccf352f7255e14324444c
use serde::{Deserialize, Serialize}; #[macro_use] extern crate enum_derive; #[macro_use] extern crate custom_derive; use chrono; use config; use lettre::smtp::{authentication, SmtpClient}; use lettre::Transport; use lettre_email::EmailBuilder; use scanner; use splunk; use std::thread; custom_derive! { #[derive(Enu...
use serde::{Deserialize, Serialize}; #[macro_use] extern crate enum_derive; #[macro_use] extern crate custom_derive; use chrono; use config; use lettre::smtp::{authentication, SmtpClient}; use lettre::Transport; use lettre_email::EmailBuilder; use scanner; use splunk; use std::thread; custom_derive! { #[derive(Enu...
pub fn send_mail( mail: std::sync::Arc<config::Mail>, msg: &String, subject: &String, ) -> Result<(), lettre::smtp::error::Error> { let mail = mail.clone(); let authentication = authentication::Credentials::new(mail.username.clone(), mail.password.clone()); let email = EmailBuilde...
format!("{}: {}", info.host, info.sensor), ) .unwrap(); } Sensor::Unknown => { println!( "[Unknown] Host: {} , Sensor: {}, State: {}", info.host, info.state, info.sensor ); } }; }
function_block-function_prefix_line
[ { "content": "pub fn current_time() -> String {\n\n use chrono::{DateTime, Utc};\n\n let now: DateTime<Utc> = Utc::now();\n\n format!(\"[{}]\", now.format(\"%b %e %T\"))\n\n}\n\n\n", "file_path": "arp_det/src/lib.rs", "rank": 6, "score": 110570.35801066423 }, { "content": "pub fn ru...
Rust
src/api/reply/player.rs
GrizzlT/hypixel-api-rust
cb870d224053a0ac002a9532af2cc28da5b78b5e
use chrono::{DateTime, Local, TimeZone}; use serde::Deserialize; use serde_json::Value; use std::collections::HashMap; use serde::de::DeserializeOwned; use uuid::Uuid; use crate::api::{ColorCodes, MonthlyPackageRank, PackageRank, StaffLevel}; use crate::error::HypixelApiError; use crate::util::leveling; #[derive(Debug...
use chrono::{DateTime, Local, TimeZone}; use serde::Deserialize; use serde_json::Value; use std::collections::HashMap; use serde::de::DeserializeOwned; use uuid::Uuid; use crate::api::{ColorCodes, MonthlyPackageRank, PackageRank, StaffLevel}; use crate::error::HypixelApiError; use crate::util::leveling; #[derive(Debug...
pub fn network_xp(&self) -> u64 { (self.network_exp + leveling::network::total_xp_to_full_level(self.network_lvl + 1.0)) as u64 } pub fn network_level(&self) -> f64 { let xp = self.network_exp + leveling::network::total_xp_to_full_level(self.network_lvl + 1.0)...
pub fn name(&self) -> Option<&str> { if self.display_name.is_some() { return self.display_name.as_deref(); } if let Some(aliases) = &self.known_aliases { if aliases.len() > 0 { return Some(&aliases[aliases.len() - 1]); } } if se...
function_block-full_function
[ { "content": "/// This function returns the level of a player calculated by the\n\n/// current experience gathered. Unlike [`exact_level`], this function returns\n\n/// the largest integer smaller than the exact level (= floored).\n\n///\n\n/// The result cannot be smaller than `1.0` and negative experience res...
Rust
src/rpc/client.rs
01intelligence/hulk
29e4c98f686042e9290d3ad9e25df9e2e8c6f587
use std::convert::TryFrom; use std::future::Future; use std::pin::Pin; use std::str::FromStr; use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; use http::{HeaderValue, Request, Response}; use lazy_static::lazy_static; use tonic::body::BoxBody; use to...
use std::convert::TryFrom; use std::future::Future; use std::pin::Pin; use std::str::FromStr; use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; use http::{HeaderValue, Request, Response}; use lazy_static::lazy_static; use tonic::body::BoxBody; use to...
pub fn new_auth_token() -> String { let active_cred = GLOBALS.active_cred.guard(); crate::http::authenticate_node(active_cred.access_key.clone(), &active_cred.secret_key).unwrap() } pub struct WrappedChannel { channel: Channel, inner: Arc<WrappedChannelInner>, tx: Arc<tokio::sync::Notify>, } str...
pub fn set_inter_node_client_builder(ca_certs: Option<&[u8]>) -> anyhow::Result<()> { let mut tls_config = tonic::transport::ClientTlsConfig::new(); if let Some(ca_certs) = ca_certs { tls_config = tls_config.ca_certificate(tonic::transport::Certificate::from_pem(ca_certs)); } let builder = Inte...
function_block-full_function
[ { "content": "pub fn get_url_scheme() -> &'static str {\n\n if GLOBALS.is_tls.get() {\n\n \"https\"\n\n } else {\n\n \"http\"\n\n }\n\n}\n", "file_path": "src/globals/vars.rs", "rank": 0, "score": 258926.6077331472 }, { "content": "pub fn readdir(p: impl AsRef<Path>) -...
Rust
src/printer.rs
itgonzo/Cursive
fd09b5f806b103154d693ca829ac4b35d09ce66e
use backend::Backend; use enumset::EnumSet; use std::cell::Cell; use std::cmp::min; use std::rc::Rc; use theme::{BorderStyle, ColorStyle, Effect, PaletteColor, Style, Theme}; use unicode_segmentation::UnicodeSegmentation; use utils::lines::simple::prefix; use vec::Vec2; pub struct Printer<'a> { pub offset: ...
use backend::Backend; use enumset::EnumSet; use std::cell::Cell; use std::cmp::min; use std::rc::Rc; use theme::{BorderStyle, ColorStyle, Effect, PaletteColor, Style, Theme}; use unicode_segmentation::UnicodeSegmentation; use utils::lines::simple::prefix; use vec::Vec2; pub struct Printer<'a> { pub offset: ...
let size = size.into(); if size.x < 2 || size.y < 2 { return; } let size = size - (1, 1); self.with_high_border(invert, |s| { s.print(start, "┌"); s.print(start + size.keep_y(), "└"); s.print_hline(start + (1, 0), size.x - 1, "─"); ...
pub fn print_box<T: Into<Vec2>, S: Into<Vec2>>( &self, start: T, size: S, invert: bool ) { self.new.set(false); let start = start.into();
random
[ { "content": "fn with_color<F, R>(clr: &theme::Color, f: F) -> R\n\nwhere\n\n F: FnOnce(&tcolor::Color) -> R,\n\n{\n\n match *clr {\n\n theme::Color::TerminalDefault => f(&tcolor::Reset),\n\n theme::Color::Dark(theme::BaseColor::Black) => f(&tcolor::Black),\n\n theme::Color::Dark(them...
Rust
examples/iced.rs
StT191/rust-wgx
0b4948ae85ac8d9a9d43610cba20ed39c89632c8
#![allow(unused)] use futures::executor::block_on; use iced_wgpu::Settings; use iced_winit::winit; use self::winit::{ dpi::{PhysicalSize}, event_loop::{ControlFlow, EventLoop}, window::{Window, Icon}, event::*, }; use wgx::{*, /*cgmath::**/}; use iced_wgpu::Renderer; use iced_winit::{ Alignment, Comma...
#![allow(unused)] use futures::executor::block_on; use iced_wgpu::Settings; use iced_winit::winit; use self::winit::{ dpi::{PhysicalSize}, event_loop::{ControlFlow, EventLoop}, window::{Window, Icon}, event::*, }; use wgx::{*, /*cgmath::**/}; use iced_wgpu::Renderer; use iced_winit::{ Alignment, Comma...
const DEPTH_TESTING:bool = false; const ALPHA_BLENDING:bool = false; const MSAA:u32 = 1; let img = image::open("img/logo_red_96.png").expect("failed loading image").into_rgba8(); let event_loop = EventLoop::new(); let (width, height) = (1200, 800); let window = Window::new(&event_...
xt(String), } pub struct Controls { pub color: Color, text: String, text_input: text_input::State, sliders: [slider::State; 3], } impl Controls { pub fn new() -> Controls { Controls { color: Color::from([0.46, 0.60, 0.46]), text: "".to_string(), text_inp...
random
[ { "content": "// device methods\n\npub trait WgxDevice {\n\n\n\n fn device(&self) -> &wgpu::Device;\n\n\n\n // texture, sampler\n\n\n\n fn texture(&self, descriptor:&TexDsc) -> wgpu::Texture {\n\n self.device().create_texture(&descriptor.into())\n\n }\n\n\n\n fn sampler(&self, descriptor: ...
Rust
src/client_server/message.rs
nekrondev/conduit_rockdb
f47d89eca32dd1237ddc4c460abd3d240a8ebb3c
use crate::{database::DatabaseGuard, pdu::PduBuilder, utils, ConduitResult, Error, Ruma}; use ruma::{ api::client::{ error::ErrorKind, r0::message::{get_message_events, send_message_event}, }, events::EventType, EventId, }; use std::{ collections::BTreeMap, convert::{TryFrom, Try...
use crate::{database::DatabaseGuard, pdu::PduBuilder, utils, ConduitResult, Error, Ruma}; use ruma::{ api::client::{ error::ErrorKind, r0::message::{get_message_events, send_message_event}, }, events::EventType, EventId, }; use std::{ collections::BTreeMap, convert::{TryFrom, Try...
r = body.sender_user.as_ref().expect("user is authenticated"); if !db.rooms.is_joined(sender_user, &body.room_id)? { return Err(Error::BadRequest( ErrorKind::Forbidden, "You don't have permission to view this room.", )); } let from = body .from .clon...
function_block-function_prefixed
[ { "content": "#[tracing::instrument(skip(bytes))]\n\npub fn u64_from_bytes(bytes: &[u8]) -> Result<u64, std::array::TryFromSliceError> {\n\n let array: [u8; 8] = bytes.try_into()?;\n\n Ok(u64::from_be_bytes(array))\n\n}\n\n\n\n/// Parses the bytes into a string.\n", "file_path": "src/utils.rs", "r...
Rust
chain-abci/tests/punishment.rs
SchoolOfFreelancing/chain
c5f806393fbcffbdaa27d9f4843b6933ebac56b1
use abci::*; use parity_scale_codec::Encode; use protobuf::well_known_types::Timestamp; use chain_core::init::coin::Coin; use test_common::chain_env::{get_account, ChainEnv}; #[test] fn end_block_should_update_liveness_tracker() { let (env, storage) = ChainEnv::new_with_customizer(Coin::max(), Coin::...
use abci::*; use parity_scale_codec::Encode; use protobuf::well_known_types::Timestamp; use chain_core::init::coin::Coin; use test_common::chain_env::{get_account, ChainEnv}; #[test] fn end_block_should_update_liveness_tracker() { let (env, storage) = ChainEnv::new_with_customizer(Coin::max(), Coin::...
#[test] fn begin_block_should_slash_non_live_validators() { let (env, storage) = ChainEnv::new(Coin::max(), Coin::zero(), 1); let mut app = env.chain_node(storage); let _rsp_init_chain = app.init_chain(&env.req_init_chain()); app.begin_block(&RequestBeginBlock { last_commit_info: So...
eq_begin_block(1, 0) }); let account = get_account(&env.accounts[0].staking_address(), &app); assert!(account.is_jailed()); let slash_amount = Coin::new((u64::from(env.dist_coin) / 10) * 2).unwrap(); assert_eq!(account.last_slash.unwrap().amount, slash_amount); assert_eq!( slash_amount,...
function_block-function_prefixed
[ { "content": "fn block_commit(app: &mut ChainNodeApp<MockClient>, tx: TxAux, block_height: i64) {\n\n let mut creq = RequestCheckTx::default();\n\n creq.set_tx(tx.encode());\n\n println!(\"checktx: {:?}\", app.check_tx(&creq));\n\n println!(\"beginblock: {:?}\", begin_block(app));\n\n let mut dre...
Rust
core/src/node_group_tests.rs
caesarchad/morgan
b77b19601d6cc3deb3ff22d4f988ffb57675c9a9
use crate::block_buffer_pool::BlockBufferPool; use crate::node_group_info::FULLNODE_PORT_RANGE; use crate::connection_info::ContactInfo; use crate::entry_info::{Entry, EntrySlice}; use crate::gossip_service::find_node_group_host; use crate::fork_selection::VOTE_THRESHOLD_DEPTH; use morgan_client::thin_client::create_c...
use crate::block_buffer_pool::BlockBufferPool; use crate::node_group_info::FULLNODE_PORT_RANGE; use crate::connection_info::ContactInfo; use crate::entry_info::{Entry, EntrySlice}; use crate::gossip_service::find_node_group_host; use crate::fork_selection::VOTE_THRESHOLD_DEPTH; use morgan_client::thin_client::create_c...
ng_addr(), FULLNODE_PORT_RANGE); assert!(client.fullnode_exit().unwrap()); } sleep(Duration::from_millis(DEFAULT_SLOT_MILLIS)); for node in &node_group_hosts { let client = create_client(node.client_facing_addr(), FULLNODE_PORT_RANGE); assert!(client.fullnode_exit().is_err()); } ...
&ContactInfo, nodes: usize) { let (node_group_hosts, _) = find_node_group_host(&entry_point_info.gossip, nodes).unwrap(); assert!(node_group_hosts.len() >= nodes); for node in &node_group_hosts { let client = create_client(node.client_faci
function_block-random_span
[ { "content": "/// fund the dests keys by spending all of the genesis keys into MAX_SPENDS_PER_TX\n\n/// on every iteration. This allows us to replay the transfers because the genesis is either empty,\n\n/// or full\n\npub fn fund_keys<T: Client>(client: &T, genesis: &Keypair, dests: &[Keypair], difs: u64) {\n\...
Rust
src/gconf.rs
VladimirMarkelov/solkit
e58cb22b12f846276a702f412726984577eed94a
use crate::card::{Card, Face, Suit}; use crate::err::SolError; #[derive(Clone, Copy, PartialEq)] pub enum FaceOrder { Asc, Desc, Any, } pub fn str_to_face_order(s: &str) -> Result<FaceOrder, SolError> { match s { "asc" | "ascending" | "inc" | "increasing" => Ok(FaceOrder::Asc), "desc" ...
use crate::card::{Card, Face, Suit}; use crate::err::SolError; #[derive(Clone, Copy, PartialEq)] pub enum FaceOrder { Asc, Desc, Any, } pub fn str_to_face_order(s: &str) -> Result<FaceOrder, SolError> { match s { "asc" | "ascending" | "inc" | "increasing" => Ok(FaceOrder::Asc), "desc" ...
} impl Conf { pub fn new() -> Self { Default::default() } pub fn validate(&self) -> Result<(), SolError> { if self.deck_count == 0 || self.deck_count > 2 { return Err(SolError::InvalidDeckNumber(self.deck_count)); } if let Some(ref cfg) = self.temp { ...
f { name: String::new(), chance: None, deck_count: 1, playable: Playable::Top, pile: None, fnd: Vec::new(), temp: None, cols: Vec::new(), col_forder: FaceOrder::Desc, col_sorder: SuitOrder::SameSuit, ...
function_block-function_prefixed
[ { "content": "pub fn str_to_suit(s: &str) -> Result<Suit, SolError> {\n\n match s {\n\n \"spade\" | \"spades\" => Ok(Suit::Spade),\n\n \"club\" | \"clubs\" => Ok(Suit::Club),\n\n \"diamond\" | \"diamonds\" => Ok(Suit::Diamond),\n\n \"heart\" | \"hearts\" => Ok(Suit::Heart),\n\n ...
Rust
alacritty/src/renderer/grid.rs
w23/alacritty
3d4260bf7e0db0700078222b25dd350533ea5e12
use std::ptr; use log::*; use alacritty_terminal::grid::Dimensions as _; use alacritty_terminal::term::{color::Rgb, SizeInfo}; use crate::display::content::RenderableCell; use crate::gl; use crate::gl::types::*; use crate::renderer::atlas::{AtlasInsertError, GridAtlas}; use crate::renderer::glyph::{GridAtlasGlyph, R...
use std::ptr; use log::*; use alacritty_terminal::grid::Dimensions as _; use alacritty_terminal::term::{color::Rgb, SizeInfo}; use crate::display::content::RenderableCell; use crate::gl; use crate::gl::types::*; use crate::renderer::atlas::{AtlasInsertError, GridAtlas}; use crate::renderer::glyph::{GridAtlasGlyph, R...
ize, lines: usize) { let cells = columns * lines; self.glyphs.resize(cells, EMPTY_GLYPH_REF); } fn clear(&mut self) { self.glyphs.iter_mut().for_each(|x| *x = EMPTY_GLYPH_REF); self.dirty = false; } }
ell.point.column.0 < self.columns { self.screen_colors_bg[cell_index + 1] = [cell.bg.r, cell.bg.g, cell.bg.b, bg_alpha]; } } pub fn update_cell(&mut self, cell: &RenderableCell, glyph: &GridAtlasGlyph) { let cell_index = cell.point.line * self.columns + cell.point.column.0; ...
random
[ { "content": "/// Parse colors in `rgb:r(rrr)/g(ggg)/b(bbb)` format.\n\nfn parse_rgb_color(color: &[u8]) -> Option<Rgb> {\n\n let colors = str::from_utf8(color).ok()?.split('/').collect::<Vec<_>>();\n\n\n\n if colors.len() != 3 {\n\n return None;\n\n }\n\n\n\n // Scale values instead of filli...
Rust
src/computer.rs
Yey007/mc-computer-emulator
fad0f7f97aa6a7cc4096c36858318f8e7f63e36e
mod alu; mod memory; mod port; mod register; use crate::computer::alu::ArithmeticLogicUnit; use crate::computer::memory::readonly::ReadOnlyMemory; use crate::computer::memory::readwrite::ReadWriteMemory; use crate::computer::port::Port; use crate::computer::register::Register; use crate::instruction::{decode_instructi...
mod alu; mod memory; mod port; mod register; use crate::computer::alu::ArithmeticLogicUnit; use crate::computer::memory::readonly::ReadOnlyMemory; use crate::computer::memory::readwrite::ReadWriteMemory; use crate::computer::port::Port; use crate::computer::register::Register; use crate::instruction::{decode_instructi...
} fn get_port(&self, id: PortIndexType) -> &Port<WorkingType> { let id_u8: u8 = id.into(); self.ports[id_u8 as usize].borrow() } fn get_register_mut(&mut self, id: RegisterIndexType) -> &mut Register<WorkingType> { let id_u8: u8 = id.into(); match id_u8 { 0...
match id_u8 { 0 => self.alu.accumulator(), 1 => self.x_register.borrow(), 2 => self.y_register.borrow(), 3 => self.z_register.borrow(), _ => panic!("Max value of u2 exceeded."), }
if_condition
[ { "content": "#[bitmatch]\n\npub fn decode_instruction(binary: InstructionBitType) -> Instruction {\n\n #[bitmatch]\n\n match binary {\n\n \"000001rr\" => Instruction::STR {\n\n register_id: RegisterIndexType::new(r),\n\n },\n\n \"000010rr\" => Instruction::LOD {\n\n ...
Rust
src/lib/util/mod.rs
andrevidela/elba
8428563d9edc60466cb0c42f860e49a5bd1f6c39
pub mod config; pub mod errors; pub mod git; pub mod graph; pub mod lock; pub mod read2; pub mod shell; pub use crate::util::read2::read2; use crate::util::errors::{Error, Res}; use failure::{bail, format_err, ResultExt}; use itertools::Itertools; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; u...
pub mod config; pub mod errors; pub mod git; pub mod graph; pub mod lock; pub mod read2; pub mod shell; pub use crate::util::read2::read2; use crate::util::errors::{Error, Res}; use failure::{bail, format_err, ResultExt}; use itertools::Itertools; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; u...
pub fn fmt_output(c: &Output) -> String { let mut res = String::new(); if !c.stderr.is_empty() { if !c.stdout.is_empty() { res.push_str("--- stdout\n"); } res.push_str(format!("{}\n", String::from_utf8_lossy(&c.stderr)).as_ref()); res.push_str(format!("--- stderr\n{}\...
function_block-full_function
[ { "content": "pub fn init(path: &Path) -> Res<()> {\n\n git2::Repository::init(path)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/lib/util/git.rs", "rank": 6, "score": 173463.23920484996 }, { "content": "pub fn shell() -> Shell {\n\n Shell::default()\n\n}\n\n\n", "file_path": "te...
Rust
plots/examples/174/main.rs
gre/shaderday.com
702ca2d395b6ec327b7b115add15251aea474f21
use clap::Clap; use gre::*; use noise::*; use svg::node::element::path::Data; use svg::node::element::*; #[derive(Clap)] #[clap()] struct Opts { } pub fn fill<F: FnMut((f64, f64)) -> f64>( data: Data, bounds: (f64, f64, f64, f64), increment: (f64,f64), mut f: F, threshold: f64, threshold_dir: ...
use clap::Clap; use gre::*; use noise::*; use svg::node::element::path::Data; use svg::node::element::*; #[derive(Clap)] #[clap()] struct Opts { } pub fn fill<F: FnMut((f64, f64)) -> f64>( data: Data, bounds: (f64, f64, f64, f64), increment: (f64,f64), mut f: F, threshold: f64, threshold_dir: ...
fn main() { let opts: Opts = Opts::parse(); let groups = art(&opts); let mut document = base_24x30_landscape("white"); for g in groups { document = document.add(g); } svg::save("image.svg", &document).unwrap(); }
Users/grenaudeau/Desktop/avatars/3/2.jpeg", "/Users/grenaudeau/Desktop/avatars/3/3.png", ].iter().enumerate().map(|(i, path)| { let x = i as f64 * 120.0 + 40.; let y = 70.; Group::new().set("transform", format!("translate({},{})", x, y)).add(shape(path, true, i)) }).collect() }
function_block-function_prefix_line
[]
Rust
daemon/src/setup_taker.rs
comit-network/hermes
74e939c4c9784a07c3bf6d9d4e1ed69ef4cf3831
use crate::command; use crate::connection; use crate::model::cfd::Dlc; use crate::model::cfd::OrderId; use crate::model::cfd::Role; use crate::model::cfd::SetupCompleted; use crate::model::Usd; use crate::oracle::Announcement; use crate::process_manager; use crate::setup_contract; use crate::wallet; use crate::wire; us...
use crate::command; use crate::connection; use crate::model::cfd::Dlc; use crate::model::cfd::OrderId; use crate::model::cfd::Role; use crate::model::cfd::SetupCompleted; use crate::model::Usd; use crate::oracle::Announcement; use crate::process_manager; use crate::setup_contract; use crate::wallet; use crate::wire; us...
} #[async_trait] impl xtra::Actor for Actor { async fn started(&mut self, ctx: &mut xtra::Context<Self>) { let address = ctx .address() .expect("actor to be able to give address to itself"); let res = self .maker .send(connection::TakeOrder { ...
r .execute(self.order_id, |cfd| { cfd.setup_contract(SetupCompleted::Failed { order_id: msg.order_id, error: msg.error, }) }) .await { tracing::warn!("{:#}", e); } ctx.stop();...
function_block-function_prefixed
[ { "content": "pub fn dummy_new_order() -> maker_cfd::NewOrder {\n\n maker_cfd::NewOrder {\n\n price: dummy_price(),\n\n min_quantity: Usd::new(dec!(5)),\n\n max_quantity: Usd::new(dec!(100)),\n\n tx_fee_rate: 1,\n\n funding_rate: FundingRate::default(),\n\n }\n\n}\n\n\n"...
Rust
services/src/datasets/add_from_directory.rs
glombiewski/geoengine
d84520756198ce5759fa83cba211f38fe523ed61
use std::ffi::OsStr; use std::{ fs::{self, DirEntry, File}, io::BufReader, path::PathBuf, }; use crate::datasets::storage::MetaDataDefinition; use crate::layers::layer::{AddLayer, AddLayerCollection, LayerCollectionId}; use crate::layers::storage::LayerDb; use crate::util::user_input::UserInput; use crate:...
use std::ffi::OsStr; use std::{ fs::{self, DirEntry, File}, io::BufReader, path::PathBuf, }; use crate::datasets::storage::MetaDataDefinition; use c
et layer = layer_db.add_layer(layer).await?; layer_db .add_layer_to_collection(layer, DATASET_LAYER_COLLECTION_ID) .await?; Ok(()) } pub async fn add_datasets_from_directory< S: MockableSession, D: DatasetDb<S>, L: LayerDb, W: WorkflowRegistry, >( dataset_db: &mut D, la...
rate::layers::layer::{AddLayer, AddLayerCollection, LayerCollectionId}; use crate::layers::storage::LayerDb; use crate::util::user_input::UserInput; use crate::workflows::registry::WorkflowRegistry; use crate::workflows::workflow::Workflow; use crate::{contexts::MockableSession, datasets::storage::DatasetDb}; use crate...
random
[]
Rust
src/components/combat.rs
a5huynh/evoli
442515894674296a1bba6956824b92130da18b8a
use amethyst::{ assets::{PrefabData, PrefabLoader, ProgressCounter, RonFormat}, core::Named, derive::PrefabData, ecs::{Component, DenseVecStorage, Entity, HashMapStorage, Read, Write, WriteStorage}, prelude::*, Error, }; use log::error; use serde::{Deserialize, Serialize}; use std::collections:...
use amethyst::{ assets::{PrefabData, PrefabLoader, ProgressCounter, RonFormat}, core::Named, derive::PrefabData, ecs::{Component, DenseVecStorage, Entity, HashMapStorage, Read, Write, WriteStorage}, prelude::*, Error, }; use log::error; use serde::{Deserialize, Serialize}; use std::collections:...
.insert(name.name.to_string(), entity); } self.name .add_to_entity(entity, named, entities, children) .expect("unreachable"); self.faction_preys .add_to_entity(entity, faction_preys, entities, children) .expect("unreachable"); Ok(()) } ...
_: &[Entity], ) -> Result<Self::Result, Error> { let faction = (system_data.1).0.get(&self.faction); if let Some(f) = faction { system_data .0 .insert(entity, HasFaction { faction: *f }) .expect("Unreachable: we are inserting now."...
random
[ { "content": "// delete the specified root entity and all of its descendents as specified\n\n// by the Parent component and maintained by the ParentHierarchy resource\n\npub fn delete_hierarchy(root: Entity, world: &mut World) -> Result<(), WrongGeneration> {\n\n let entities = {\n\n iter::once(root)\...
Rust
src/lib.rs
tetcoin/x509-signature
4b86e65cfae0a024f96872b0e862deecc5c6e4ca
#![no_std] #![deny( exceeding_bitshifts, invalid_type_param_default, missing_fragment_specifier, no_mangle_const_items, overflowing_literals, patterns_in_fns_without_body, pub_use_of_private_extern_crate, unknown_crate_types, const_err, order_dependent_trait_objects, illega...
#![no_std] #![deny( exceeding_bitshifts, invalid_type_param_default, missing_fragment_specifier, no_mangle_const_items, overflowing_literals, patterns_in_fns_without_body, pub_use_of_private_extern_crate, unknown_crate_types, const_err, order_dependent_trait_objects, illega...
#[cfg(test)] mod tests { use super::*; #[test] fn parses_openssl_generated_cert() { let signature = include_bytes!("../testing.sig"); let invalid_signature = include_bytes!("../testing.bad-sig"); let forged_message = include_bytes!("../forged-message.txt"); let message = in...
pub fn parse_certificate<'a>(certificate: &'a [u8]) -> Result<X509Certificate<'a>, Error> { use core::convert::TryFrom as _; let das = DataAlgorithmSignature::try_from(certificate)?; untrusted::Input::from(&*das.inner()).read_all(Error::BadDER, |input| { const CONTEXT_SPECIFIC_PRIMITIVE_1: u8 = der:...
function_block-full_function
[ { "content": "fn seconds_from_hms(hour: u8, minute: u8, second: u8) -> Result<u32, Error> {\n\n if hour > 23 || minute > 59 || second > 59 {\n\n Err(Error::BadDERTime)\n\n } else {\n\n Ok((u32::from(hour) * 60 + u32::from(minute)) * 60 + u32::from(second))\n\n }\n\n}\n\n\n", "file_pat...
Rust
src/gravity.rs
gendx/gravity-rs
9dbd9fdbf934f29d9fedac572af452abcf88a977
use address; use config::*; use hash; use hash::Hash; use merkle; use pors; use prng; use subtree; pub struct SecKey { seed: Hash, salt: Hash, cache: merkle::MerkleTree, } pub struct PubKey { pub h: Hash, } #[derive(Default)] pub struct Signature { pors_sign: pors::Signature, subtrees: [subtree...
use address; use config::*; use hash; use hash::Hash; use merkle; use pors; use prng; use subtree; pub struct SecKey { seed: Hash, salt: Hash, cache: merkle::MerkleTree, } pub struct PubKey { pub h: Hash, } #[derive(Default)] pub struct Signature { pors_sign: pors::Signature, subtrees: [subtree...
bb\ \xc4\x4d\xd7\xb6\x94\x07\x94\x2a" } ConfigType::M => { *b"\x33\xbd\x9a\x33\x3d\x5f\x88\xc6\ \x0a\xca\x08\x42\x3e\xe3\xbc\xcf\ \x02\xe1\xc7\xd2\x74\xa8\xec\xf4\ \xd7\x4e\xfe\x34\x05\xb9\x24\x04" ...
4] = [0u8; 64]; let pkh: [u8; 32] = match get_config_type() { ConfigType::S => { *b"\x57\x03\x58\x87\x1a\x7a\x2c\xfe\ \x1e\xab\xf1\x3b\x4c\x11\x3a\x81\ \xce\x08\x9a\x2c\x02\x04\xa3\x
function_block-random_span
[ { "content": "pub fn sign(prng: &prng::Prng, salt: &Hash, msg: &Hash) -> (address::Address, Hash, Signature) {\n\n let pepper = hash::hash_2n_to_n_ret(&salt, &msg);\n\n let (address, subset) = obtain_address_subset(&pepper, &msg);\n\n\n\n let sk = SecKey::new(&prng, &address);\n\n let (root, sign) =...
Rust
src/project.rs
STBoyden/ocean
d0a5a86b5568029dfe7173f8bfb383ad3f06991e
use crate::{compiler::*, language::*, platform::*}; use serde_derive::*; use std::{collections::hash_map::Values, collections::HashMap, env, path::PathBuf}; #[derive(Deserialize, Serialize)] pub struct DirectoryHashMap(HashMap<String, String>); #[derive(Deserialize, Serialize, Clone, Debug)] pub struct Binary { p...
use crate::{compiler::*, language::*, platform::*}; use serde_derive::*; use std::{collections::hash_map::Values, collections::HashMap, env, path::PathBuf}; #[derive(Deserialize, Serialize)] pub struct DirectoryHashMap(HashMap<String, String>); #[derive(Deserialize, Serialize, Clone, Debug)] pub struct Binary { p...
{ return bins; } Vec::new() } } impl Default for Project { fn default() -> Self { Self { project: Inner::default(), directories: DirectoryHashMap::new(), compiler: Compiler::default(), platforms: None, bins: None,...
mand(language, compiler_command); } pub fn set_current_compiler(&mut self, compiler_command: String) { println!( "Set compiler command for {} to '{}'", self.project.language.as_string(), compiler_command ); let language = self.project.language; ...
random
[ { "content": "fn parse_args(mut args: Vec<String>) -> Result<(), StrRet> {\n\n let platforms = [\"linux\", \"osx\", \"windows\"];\n\n\n\n if args[1..].is_empty() {\n\n Commands::help(None);\n\n return Err(\"No arguments were specified\".into());\n\n } else {\n\n args = args[1..].to...
Rust
src/main.rs
MindFlavor/pusheventhub
a86bbbb3306e33fb356a2d40d7ed865a404020d9
#[macro_use] extern crate hyper; extern crate url; extern crate chrono; extern crate time; extern crate crypto; extern crate rustc_serialize as serialize; #[macro_use] extern crate log; extern crate env_logger; extern crate clap; use clap::{Arg, App}; mod azure_error; use azure_error::AzureError; use azure_error::Une...
#[macro_use] extern crate hyper; extern crate url; extern crate chrono; extern crate time; extern crate crypto; extern crate rustc_serialize as serialize; #[macro_use] extern crate log; extern crate env_logger; extern crate clap; use clap::{Arg, App}; mod azure_error; use azure_error::AzureError; use azure_error::Une...
fn main() { env_logger::init().unwrap(); let matches = App::new("pusheventhub") .version("0.1.0") .author("Francesco Cogno <francesco.cogno@outlook.com>") .about("sends standard input to event hub") .arg(Arg::with_name("NA...
let str_to_sign = format!("{}\n{}", url_encoded, expiry); debug!("str_to_sign == {:?}", str_to_sign); let mut v_hmac_key: Vec<u8> = Vec::new(); v_hmac_key.extend(hmac_key.as_bytes()); let mut hmac = Hmac::new(Sha256::new(), &v_hmac_key); hmac.input(str_to_sign.as_bytes()); let sig = hmac.result...
function_block-function_prefix_line
[ { "content": "use std::convert::From;\n\n\n\nuse url::ParseError;\n\nuse std::io::Error as IOError;\n\nuse hyper::error::Error as HyperError;\n\nuse hyper::status::StatusCode;\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub struct UnexpectedHTTPResult {\n\n expected: StatusCode,\n\n received: StatusCode,...
Rust
src/test.rs
dacut/acme-client
220ae3b82603c2aa1972906edbdfbb62efd5ead1
use std::{ fs::File, thread::sleep, time::Duration, }; use async_trait::async_trait; use ctor::ctor; use env_logger; use lazy_static::lazy_static; use log::{debug, warn}; use openssl::{ ec::EcKey, rsa::Rsa, }; use rand::random; use rusoto_core::{ Region, request::HttpClient, }; use rusoto_cr...
use std::{ fs::File, thread::sleep, time::Duration, }; use async_trait::async_trait; use ctor::ctor; use env_logger; use lazy_static::lazy_static; use log::{debug, warn}; use openssl::{ ec::EcKey, rsa::Rsa, }; use rand::random; use rusoto_core::{ Region, request::HttpClient, }; use rusoto_cr...
async fn dns_test_core(keyalg: KeyAlg, email: &str) { let dir = AcmeDirectory::from_url(LETSENCRYPT_STAGING_DIRECTORY_URL, keyalg.clone()).await.unwrap(); let req = AcmeAccountRequest{ contact: Some(vec![format!("mailto:{}", email)]), terms_of_service_agreed: Some(true), external_accoun...
function_block-full_function
[ { "content": "/// Return the JWK `alg` and `crv` values for a given elliptic curve.\n\nfn get_ec_alg_crv(curve_name: Option<Nid>) -> Result<(&'static str, &'static str)> {\n\n match curve_name {\n\n None => return Err(Error::invalid_ec_key(\"EC key does not have an associated named curve\")),\n\n ...
Rust
src/wordvectors.rs
jayay/word2vec
27a73ef00717823e3e81cf1a807fb69d0528bdcc
use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use std::cmp::Ordering; use utils; use errors::Word2VecError; use vectorreader::WordVectorReader; pub struct WordVector { vocabulary: Vec<(String, Vec<f32>)>, vector_size: usize, } impl WordVector { pub fn load_from_b...
use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use std::cmp::Ordering; use utils; use errors::Word2VecError; use vectorreader::WordVectorReader; pub struct WordVector { vocabulary: Vec<(String, Vec<f32>)>, vector_size: usize, } impl WordVector { pub fn load_from_b...
>)>, index: usize, } impl<'a> Words<'a> { fn new(x: &'a Vec<(String, Vec<f32>)>) -> Words<'a> { Words { words: x, index: 0, } } } impl<'a> Iterator for Words<'a> { type Item = String; fn next(&mut self) -> Option<Self::Item> { if self.index >= self....
rtial_cmp(&a.1).unwrap_or(Ordering::Equal)); Some(metrics[1..n+1].iter().map(|&(idx, dist)| (self.vocabulary[idx].clone().0, dist)).collect()) } None => None, } } pub fn analogy(&self, pos: Vec<&str>, neg: Vec<&str>, n: usize) -> Option<...
random
[ { "content": "#[cfg(not(feature = \"simd\"))]\n\npub fn vector_norm(vector: &mut Vec<f32>) {\n\n let sum = 1.0 / vector.iter().fold(0f32, |sum, &x| sum + (x * x)).sqrt();\n\n for x in vector.iter_mut() {\n\n (*x) *= sum;\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 0, "sco...
Rust
libbit/src/rev/revwalk.rs
andyyu2004/bit
4041637b56445b3857a256c8f552a79cdac307d2
use super::Revspec; use crate::error::{BitGenericError, BitResult}; use crate::obj::{BitObject, Commit, Oid}; use crate::peel::Peel; use crate::repo::BitRepo; use bitflags::bitflags; use fallible_iterator::FallibleIterator; use rustc_hash::FxHashMap; use smallvec::{smallvec, SmallVec}; use std::cmp::Ordering; use std::...
use super::Revspec; use crate::error::{BitGenericError, BitResult}; use crate::obj::{BitObject, Commit, Oid}; use crate::peel::Peel; use crate::repo::BitRepo; use bitflags::bitflags; use fallible_iterator::FallibleIterator; use rustc_hash::FxHashMap; use smallvec::{smallvec, SmallVec}; use std::cmp::Ordering; use std::...
} #[derive(Debug, Clone)] pub struct RevWalk<'rcx> { repo: BitRepo<'rcx>, flags: FxHashMap<Oid, CommitNodeFlags>, pqueue: BinaryHeap<CommitNode<'rcx>>, index: usize, } impl<'rcx> RevWalk<'rcx> { pub fn new(roots: SmallVec<[&'rcx Commit<'rcx>; 2]>) -> Self { debug_assert!(!roots....
efault::default(), pqueue: Default::default(), index: 0, }; self.exclude.into_iter().for_each(|commit| { this.enqueue_commit_with_flags(commit, CommitNodeFlags::UNINTERESTING) }); self.roots.into_iter().for_each(|commit| this.enqueue_commit(commit)); ...
function_block-function_prefixed
[ { "content": "pub fn crc_of(bytes: impl AsRef<[u8]>) -> u32 {\n\n let mut crc = flate2::Crc::new();\n\n crc.update(bytes.as_ref());\n\n crc.sum()\n\n}\n\n\n", "file_path": "libbit/src/hash.rs", "rank": 0, "score": 284820.9788807088 }, { "content": "pub fn hash_bytes(bytes: impl AsRe...
Rust
openmls/src/treesync/hashes.rs
pulkitkothari/openmls
f1b83735315c517bbdd8c7db432c6a08e924b3b0
use openmls_traits::{types::CryptoError, OpenMlsCryptoProvider}; use tls_codec::{ Error as TlsCodecError, Serialize, TlsSerialize, TlsSize, TlsSliceU32, TlsSliceU8, }; use crate::{ binary_tree::LeafIndex, ciphersuite::{Ciphersuite, HpkePublicKey}, }; use super::node::parent_node::ParentNode; use crate::...
use openmls_traits::{types::CryptoError, OpenMlsCryptoProvider}; use tls_codec::{ Error as TlsCodecError, Serialize, TlsSerialize, TlsSize, TlsSliceU32, TlsSliceU8, }; use crate::{ binary_tree::LeafIndex, ciphersuite::{Ciphersuite, HpkePublicKey}, }; use super::node::parent_node::ParentNode; use crate::...
pub(super) fn hash( &self, ciphersuite: &Ciphersuite, backend: &impl OpenMlsCryptoProvider, ) -> Result<Vec<u8>, ParentHashError> { let payload = self.tls_serialize_detached()?; ciphersuite .hash(backend, &payload) .map_err(ParentHashError::...
pub(super) fn new(leaf_index: &'a LeafIndex, key_package: Option<&'a KeyPackage>) -> Self { Self { leaf_index, key_package, } }
function_block-full_function
[ { "content": "pub fn ciphersuites_and_backends(ciphersuite: &Ciphersuite, backend: &impl OpenMlsCryptoProvider) {}\n", "file_path": "openmls/src/test_utils/mod.rs", "rank": 0, "score": 317547.7023449105 }, { "content": "#[apply(ciphersuites_and_backends)]\n\nfn test_parent_hash(ciphersuite: ...
Rust
day-24/src/main.rs
kecors/aoc20
3fcafa85aac2d6769ffe89f17a2c467fa9d59f15
extern crate pest; #[macro_use] extern crate pest_derive; use pest::Parser; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::io::{stdin, Read}; #[derive(Parser)] #[grammar = "step.pest"] struct StepParser; #[derive(Debug)] enum Direction { East, Southeast, Southwest, Wes...
extern crate pest; #[macro_use] extern crate pest_derive; use pest::Parser; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::io::{stdin, Read}; #[derive(Parser)] #[grammar = "step.pest"] struct StepParser; #[derive(Debug)] enum Direction { East, Southeast, Southwest, Wes...
{ nesw: self.nesw, senw: self.senw + 1, }); neighbors.push(Location { nesw: self.nesw - 1, senw: self.senw, }); neighbors.push(Location { nesw: self.nesw - 1, senw: self.senw - 1, }); neighbors.push(L...
w(directions: Vec<Direction>) -> Location { let mut nesw: i16 = 0; let mut senw: i16 = 0; for direction in directions.iter() { match direction { Direction::East => { senw += 1; nesw += 1; } Direc...
random
[ { "content": "fn validate_passport_part_1(passport: &HashMap<&str, &str>) -> bool {\n\n passport.contains_key(\"byr\")\n\n && passport.contains_key(\"iyr\")\n\n && passport.contains_key(\"eyr\")\n\n && passport.contains_key(\"hgt\")\n\n && passport.contains_key(\"hcl\")\n\n ...
Rust
src/lib.rs
KyleMayes/queuecheck
e851acb6d287bb684e7d972a526c6fea0b6609c8
#![warn(missing_copy_implementations, missing_debug_implementations, missing_docs)] use std::ops::{Range}; use std::time::{Duration}; #[macro_export] macro_rules! queuecheck_bench_latency { ($pairs:expr, $producers:expr, $consumers:expr, $produce:expr, $consume:expr) => ({ use std::thread; use s...
#![warn(missing_copy_implementations, missing_debug_implementations, missing_docs)] use std::ops::{Range}; use std::time::{Duration}; #[macro_export] macro_rules! queuecheck_bench_latency { ($pairs:expr, $producers:expr, $consumers:expr, $produce:expr, $consume:expr) => ({ use std::thread; use s...
pub fn partition(threads: usize, operations: usize) -> Vec<Range<i32>> { let factor = operations / threads; (0..threads).map(|t| { let end = if t + 1 == threads { operations } else { factor * (t + 1) }; ((factor * t) as i32)..(end as i32) }).collect() }
function_block-full_function
[ { "content": "#### Throughput\n\n\n\nThe below benchmarks the throughput of the unbounded MPMC queue from the standard library by producing 100,000 items using two producer threads which are then consumed by one consumer thread.\n\n\n\n```rust\n\nuse std::sync::mpsc::{self, Receiver, Sender};\n\n\n\nlet (produc...
Rust
src/interpreter/object.rs
sigmaSd/jlox
89187887fa36b067fc51a4251bd14c1953a12e94
use std::{ fmt, ops::Deref, sync::{Arc, RwLock}, }; use crate::uuid::Uuid; use self::{class::LoxClass, instance::LoxInstance, lox_callable::LoxCallable}; pub mod class; pub mod function; mod instance; pub mod lox_callable; #[derive(Clone)] pub enum ObjectInner { Number(f64), String(String), ...
use std::{ fmt, ops::Deref, sync::{Arc, RwLock}, }; use crate::uuid::Uuid; use self::{class::LoxClass, instance::LoxInstance, lox_callable::LoxCallable}; pub mod class; pub mod function; mod instance; pub mod lox_callable; #[derive(Clone)] pub enum ObjectInner { Number(f64), String(String), ...
1.hash(state) } } impl fmt::Debug for Object { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let this: &ObjectInner = self; match this { ObjectInner::Number(arg0) => f.debug_tuple("Number").field(arg0).finish(), ObjectInner::String(arg0) => f.debug_tuple("Str...
jectInner; fn deref(&self) -> &Self::Target { &self.0 } } impl PartialEq for Object { fn eq(&self, other: &Self) -> bool { let this: &ObjectInner = self; let other: &ObjectInner = other; match (this, other) { (ObjectInner::Instance(i1), ObjectInner::Instance(i2...
random
[ { "content": "#[derive(Clone, Copy)]\n\nenum ClassType {\n\n None,\n\n Class,\n\n SubClass,\n\n}\n\n\n\nimpl stmt::Visit<()> for Resolver {\n\n fn visit_block_stmt(&mut self, stmt: &stmt::Block) {\n\n self.begin_scope();\n\n self.resolve_stmts(&stmt.statements);\n\n self.end_sco...