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
old_compiler/toc_ir/src/builder.rs
DropDemBits/turse-rs
80fe09d4b1142e87a0ffd559a3f8e62072ae3b0c
use crate::graph::{BlockIndex, Instruction, InstructionOp, IrGraph, Reference}; use crate::{AddressSpace, ReferenceNode}; use toc_ast::ast::{self, expr, ident, stmt, stmt::BlockKind, types as ty_ast, Visitor}; use toc_ast::scope::UnitScope; use toc_ast::types; use toc_ast::unit::CodeUnit; use toc_ast::value; use toc_c...
use crate::graph::{BlockIndex, Instruction, InstructionOp, IrGraph, Reference}; use crate::{AddressSpace, ReferenceNode}; use toc_ast::ast::{self, expr, ident, stmt, stmt::BlockKind, types as ty_ast, Visitor}; use toc_ast::scope::UnitScope; use toc_ast::types; use toc_ast::unit::CodeUnit; use toc_ast::value; use toc_c...
fn visit_expr(&mut self, expr: &expr::Expr) -> Reference { match &expr.kind { expr::ExprKind::BinaryOp { left, op, right, .. } => { let left_eval = self.visit_expr(&left); let right_eval = self.visit_expr(&right); let ...
fn visit_stmt(&mut self, stmt: &stmt::Stmt) { match &stmt.kind { stmt::StmtKind::VarDecl { idents, value, .. } => { if idents.is_none() { return; } let idents = idents.as_ref().unwrap(); ...
function_block-full_function
[ { "content": "/// Checks if the given `type_ref` is a named reference\n\n/// Requires that `type_ref` is de-aliased (i.e. all aliased references are\n\n/// forwarded to the base type)\n\npub fn is_named(type_ref: &TypeRef) -> bool {\n\n matches!(type_ref, TypeRef::Named(_))\n\n}\n\n\n", "file_path": "old...
Rust
src/day18.rs
tsutton/aoc2020
49c267d75154f1f656659b169224d5dc77a8de3f
#[derive(Debug, PartialEq, Eq, Copy, Clone)] enum Token { LParen, RParen, Plus, Times, Value(i64), } fn tokenize(mut input: &str) -> Vec<Token> { let mut input = &mut input; let mut result = vec![]; while let Some(t) = next_token(&mut input) { result.push(t) } result }...
#[derive(Debug, PartialEq, Eq, Copy, Clone)] enum Token { LParen, RParen, Plus, Times, Value(i64), } fn tokenize(mut input: &str) -> Vec<Token> { let mut input = &mut input; let mut result = vec![]; while let Some(t) = next_token(&mut input) { result.push(t) } result }...
#[cfg(test)] mod test { use super::*; #[test] fn test_next() { let mut s = "1 + (2 * 3) + (4 * (5 + 6))"; let t = s.clone(); assert_eq!(next_token(&mut s), Some(Token::Value(1))); assert_eq!(next_token(&mut s), Some(Token::Plus)); assert_eq!(next_token(&mut s), So...
fn reduce_once(stack: &mut Vec<Token>, peek: Option<Token>) -> bool { let token = stack.pop().unwrap(); if let Token::Value(rhs) = token { let l = stack.len(); if l >= 2 && stack[l - 1] == Token::Plus { if let Token::Value(lhs) = stack[l - 2] { stack.pop(); ...
function_block-full_function
[ { "content": "#[aoc_generator(day5)]\n\npub fn pt1(input: &str) -> Vec<(i64, i64)> {\n\n input.lines().map(one_line).collect()\n\n}\n\n\n", "file_path": "src/day5.rs", "rank": 4, "score": 227605.3283817165 }, { "content": "#[aoc_generator(day10)]\n\npub fn gen(input: &str) -> Vec<i64> {\n...
Rust
bee-message/src/payload/mod.rs
grtlr/bee
cf1c35fdf61e6ac1b2e19dd891a59c6aef223d7b
pub mod milestone; pub mod receipt; pub mod tagged_data; pub mod transaction; pub mod treasury; pub use milestone::MilestonePayload; pub(crate) use milestone::{PublicKeyCount, SignatureCount}; pub use receipt::ReceiptPayload; pub(crate) use receipt::{MigratedFundsAmount, ReceiptFundsCount}; pub use tagged_data::Tagg...
pub mod milestone; pub mod receipt; pub mod tagged_data; pub mod transaction; pub mod treasury; pub use milestone::MilestonePayload; pub(crate) use milestone::{PublicKeyCount, SignatureCount}; pub use receipt::ReceiptPayload; pub(crate) use receipt::{MigratedFundsAmount, ReceiptFundsCount}; pub use tagged_data::Tagg...
} impl From<Option<Payload>> for OptionalPayload { fn from(option: Option<Payload>) -> Self { Self(option) } } #[allow(clippy::from_over_into)] impl Into<Option<Payload>> for OptionalPayload { fn into(self) -> Option<Payload> { self.0 } }
fn unpack<U: Unpacker, const VERIFY: bool>( unpacker: &mut U, ) -> Result<Self, UnpackError<Self::UnpackError, U::Error>> { let len = u32::unpack::<_, VERIFY>(unpacker).infallible()? as usize; if len > 0 { unpacker.ensure_bytes(len)?; let payload = Payload::unpack::...
function_block-function_prefix_line
[ { "content": "fn verify_transaction<const VERIFY: bool>(transaction: &Payload) -> Result<(), Error> {\n\n if !matches!(transaction, Payload::TreasuryTransaction(_)) {\n\n Err(Error::InvalidPayloadKind(transaction.kind()))\n\n } else {\n\n Ok(())\n\n }\n\n}\n", "file_path": "bee-messag...
Rust
mcr/src/main.rs
rafawo/dkreg
91bf677afa0fe0ad011338b0a4de68ea181ad29b
use dkreg::schema::*; use dkreg::*; use structopt::StructOpt; mod layer2guid; #[derive(Debug, StructOpt)] #[structopt(name = "McrCli", about = "Microsoft Container Registry CLI tool")] enum McrCli { #[structopt(name = "catalog")] Catalog { #[structopt(short = "p", long = "pretty")] ...
use dkreg::schema::*; use dkreg::*; use structopt::StructOpt; mod layer2guid; #[derive(Debug, StructOpt)] #[structopt(name = "McrCli", about = "Microsoft Container Registry CLI tool")] enum McrCli { #[structopt(name = "catalog")] Catalog { #[structopt(short = "p", long = "pretty")] ...
async fn main() { env_logger::init(); if let Err(e) = run(&McrCli::from_args()).await { println!("Failure captured running MCR CLI << {} >>", e); std::process::exit(-1); } }
function_block-full_function
[ { "content": "pub fn layer_path_to_guid(path: &str) -> GUID {\n\n const CONTAINER_IMAGE_SEED: GUID = GUID {\n\n Data1: 0x800872c5,\n\n Data2: 0x909c,\n\n Data3: 0x403a,\n\n Data4: [0x89, 0xc9, 0x93, 0x1f, 0xe5, 0xe2, 0xfd, 0x08],\n\n };\n\n let hash_data = std::path::Path::n...
Rust
aoc2020/src/day21.rs
kylewillmon/advent-of-code-rs
f6d37627eabe4b39f87329159b11aedf59362b73
use std::collections::{HashSet, HashMap}; use anyhow::Result; use aoclib::strtools; use itertools::Itertools; pub fn part1(input: String) -> Result<usize> { let recipes: Vec<Recipe<'_>> = input.lines() .map(Recipe::from_line) .collect(); let all_allergens: HashSet<&str> = recipes.iter() ...
use std::collections::{HashSet, HashMap}; use anyhow::Result; use aoclib::strtools; use itertools::Itertools; pub fn part1(input: String) -> Result<usize> { let recipes: Vec<Recipe<'_>> = input.lines() .map(Recipe::from_line) .collect(); let all_allergens: HashSet<&str> = recipes.iter() ...
} pub fn part2(input: String) -> Result<String> { let recipes: Vec<Recipe<'_>> = input.lines() .map(Recipe::from_line) .collect(); let all_allergens: HashSet<&str> = recipes.iter() .flat_map(|r| r.allergens().iter().cloned()) .collect(); let mut ingredients: HashMap<&str,...
Ok(recipes.iter() .flat_map(|r| r.ingredients().iter().cloned()) .filter(|&i| { ingredients.get(i).unwrap().is_empty() }) .count() )
call_expression
[ { "content": "pub fn part1(_: String) -> Result<String> {\n\n part1_answer(\"974618352\")\n\n}\n\n\n", "file_path": "aoc2020/src/day23.rs", "rank": 0, "score": 186857.27289482355 }, { "content": "pub fn part2(_: String) -> Result<u64> {\n\n part2_answer(\"974618352\")\n\n}\n\n\n", ...
Rust
src/hand.rs
cep21/gambling
614b69be5cd58a1dd555aa6c1d00fdbbc1b0df14
use cards::value; use cards::value::Value; use cards::card::Card; use std::fmt; use shoe::shoe::DirectShoe; pub const INDEX_TO_SCORE: [u32;13] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]; pub fn score_for_value(v: &Value) -> u32 { return INDEX_TO_SCORE[v.index()]; } pub struct BJHand { score: u32, ace_...
use cards::value; use cards::value::Value; use cards::card::Card; use std::fmt; use shoe::shoe::DirectShoe; pub const INDEX_TO_SCORE: [u32;13] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]; pub fn score_for_value(v: &Value) -> u32 { return INDEX_TO_SCORE[v.index()]; } pub struct BJHand { score: u32, ace_...
(13, h.score()); assert_eq!(false, h.is_soft()); assert_eq!(3, h.len()); h.add_card(&Card::new(value::KING, suit::SPADE)); assert_eq!(4, h.len()); assert_eq!(23, h.score()); assert_eq!(false, h.is_soft()); assert_eq!(4, h.len()); }
self.splits_to_solve.push(card_to_remove); self.remove_card(&card_to_remove); } pub fn unsplit(&mut self) { assert!(self.splits_to_solve.len() > 0); let c = self.splits_to_solve.pop().unwrap(); assert_eq!(1, self.cards.len()); assert_eq!(c.value(), self.car...
random
[ { "content": "pub fn cards_in_deck<'a>(num_decks: u32) -> Vec<Card> {\n\n let mut ret = Vec::new();\n\n ret.clear();\n\n ret.reserve_exact(52 * num_decks as usize);\n\n for _ in range(0, num_decks) {\n\n for s in suit::SUITS.iter() {\n\n for v in value::VALUES.iter() {\n\n ...
Rust
src/wkb_writer.rs
thomasantony/geos
f79d25c41bf5739c5fb28cb52ea782a7ea832bbd
use enums::{ByteOrder, OutputDimension}; use crate::{ContextHandle, Geometry, GResult, AsRaw, ContextHandling, ContextInteractions}; use context_handle::PtrWrap; use geos_sys::*; use std::sync::Arc; use error::Error; use enums::TryFrom; use c_vec::CVec; pub struct WKBWriter<'a> { ptr: PtrWrap<*mut GEOSWKBWriter>, ...
use enums::{ByteOrder, OutputDimension}; use crate::{ContextHandle, Geometry, GResult, AsRaw, ContextHandling, ContextInteractions}; use context_handle::PtrWrap; use geos_sys::*; use std::sync::Arc; use error::Error; use enums::TryFrom; use c_vec::CVec; pub struct WKBWriter<'a> { ptr: PtrWrap<*mut GEOSWKBWriter>, ...
if ptr.is_null() { Err(Error::NoConstructionFromNullPtr( "WKBWriter::write_wkb failed: GEOSWKBWriter_writeHEX_r returned null pointer".to_owned()) ) } else { Ok(CVec::new(ptr, size as _)) } } } ...
let ptr = GEOSWKBWriter_write_r(self.get_raw_context(), self.as_raw(), geometry.as_raw(), &mut size);
assignment_statement
[ { "content": "pub fn version() -> GResult<String> {\n\n unsafe { unmanaged_string(GEOSversion(), \"version\") }\n\n}\n\n\n\npub(crate) fn check_geos_predicate(val: i32, p: PredicateType) -> GResult<bool> {\n\n match val {\n\n 1 => Ok(true),\n\n 0 => Ok(false),\n\n _ => Err(Error::Geos...
Rust
main/src/request_writer.rs
sfaerber/async-std-http-client
46ac3259b3bb7087e6e5f9627667e60f0d23ebab
use crate::model::*; use async_std::prelude::*; use encoding::EncodingRef; use http::header::{HeaderMap, HeaderName, ACCEPT_ENCODING, CONTENT_LENGTH, HOST}; use smallvec::{smallvec, SmallVec}; use std::collections::HashSet; pub async fn write_request( rw: &mut Connection, req: &Request, config: &ClientConf...
use crate::model::*; use async_std::prelude::*; use encoding::EncodingRef; use http::header::{HeaderMap, HeaderName, ACCEPT_ENCODING, CONTENT_LENGTH, HOST}; use smallvec::{smallvec, SmallVec}; use std::collections::HashSet; pub async fn write_request( rw: &mut Connection, req: &Request, config: &ClientConf...
#[test] fn it_works() { fn test_encode(data: &str, encoding: EncodingRef) -> String { String::from_utf8_lossy(&url_encode(data, encoding, SmallVec::new()).unwrap()).into() } assert_eq!( &test_encode("abc?dfg", encoding::all::ISO_8859_1), "abc%3Fdfg" ); assert_eq!( ...
std::result::Result<Vec<u8>, ()> { use encoding::EncoderTrap; let mut result: Vec<u8> = Vec::new(); for b in data.chars() { match b { 'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => { result.extend(b.to_string().as_bytes()) } ...
function_block-function_prefix_line
[ { "content": "pub trait AsyncReadWriter: 'static + Unpin + Send + Sync + AsyncRead + AsyncWrite {}\n\n\n\nimpl<T> AsyncReadWriter for T where T: 'static + Unpin + Send + Sync + AsyncRead + AsyncWrite {}\n\n\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Debug)]\n\npub struct ConnectionId(pub u64...
Rust
algebra/src/curves/mnt6/g2.rs
osuketh/zexe
1aabda187a1ab39ed766b1eb64b145958e8a5e34
use crate::{ biginteger::BigInteger320, bytes::ToBytes, curves::{ mnt6::{g1::MNT6G1Parameters, G1Affine, MNT6, TWIST_COEFF_A}, models::{ModelParameters, SWModelParameters}, short_weierstrass_projective::{GroupAffine, GroupProjective}, AffineCurve, PairingCurve, PairingEngine,...
use crate::{ biginteger::BigInteger320, bytes::ToBytes, curves::{ mnt6::{g1::MNT6G1Parameters, G1Affine, MNT6, TWIST_COEFF_A}, models::{ModelParameters, SWModelParameters}, short_weierstrass_projective::{GroupAffine, GroupProjective}, AffineCurve, PairingCurve, PairingEngine,...
0x2c28bb71862, ])); pub const G2_GENERATOR_X_C2: Fq = Fq::new(BigInteger320([ 0xf3e5f4eb9631e1f1, 0x657801e80c50778, 0x2d2abb128fee90f3, 0x72e58e4c3aa3598c, 0x100b8026b9d, ])); pub const G2_GENERATOR_Y_C0: Fq = Fq::new(BigInteger320([ 0xb1cddd6c64a67c5f, 0xa01e90d89aa5d2ba, 0x39e9a7...
ith(&self, other: &Self::PairWith) -> Self::PairingResult { MNT6::pairing(*other, *self) } } #[derive(Copy, Clone, Default, PartialEq, Eq)] pub struct MNT6G2Parameters; impl ModelParameters for MNT6G2Parameters { type BaseField = Fq3; type ScalarField = Fr; } pub const MUL_BY_A_C0: Fq = Fq::new(B...
random
[ { "content": "pub fn curve_tests<G: ProjectiveCurve>() {\n\n let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);\n\n\n\n // Negation edge case with zero.\n\n {\n\n let z = -G::zero();\n\n assert!(z.is_zero());\n\n }\n\n\n\n // Doubling edge case w...
Rust
tracing-subscriber/tests/support.rs
mithril-security/tracing-sgx
4853471f5ac23b3d95de1e6468056f83d7ccf060
#![allow(missing_docs, dead_code)] pub use self::support::{event, field, span, subscriber}; #[allow(clippy::module_inception)] #[path = "../../tracing/tests/support/mod.rs"] mod support; use self::{ event::MockEvent, span::{MockSpan, NewSpan}, subscriber::{Expect, MockHandle}, }; use tracing_core::{ s...
#![allow(missing_docs, dead_code)] pub use self::support::{event, field, span, subscriber}; #[allow(clippy::module_inception)] #[path = "../../tracing/tests/support/mod.rs"] mod support; use self::{ event::MockEvent, span::{MockSpan, NewSpan}, subscriber::{Expect, MockHandle}, }; use tracing_core::{ s...
pub fn new_span<I>(mut self, new_span: I) -> Self where I: Into<NewSpan>, { self.expected.push_back(Expect::NewSpan(new_span.into())); self } pub fn run(self) -> ExpectLayer { ExpectLayer { expected: Arc::new(Mutex::new(self.expected)), name...
pub fn record<I>(mut self, span: MockSpan, fields: I) -> Self where I: Into<field::Expect>, { self.expected.push_back(Expect::Visit(span, fields.into())); self }
function_block-full_function
[ { "content": "pub fn msg(message: impl fmt::Display) -> MockEvent {\n\n mock().with_fields(field::msg(message))\n\n}\n\n\n\nimpl MockEvent {\n\n pub fn named<I>(self, name: I) -> Self\n\n where\n\n I: Into<String>,\n\n {\n\n Self {\n\n metadata: metadata::Expect {\n\n ...
Rust
src/output.rs
rohankumardubey/rnr
2339ed2e248498f05849dbadeca8b3e3e83757fc
use ansi_term::Colour::*; use ansi_term::Style; use difference::{Changeset, Difference}; use error::*; use std::path::Path; #[derive(PartialEq)] enum PrinterMode { Silent, NoColor, Color, } pub struct Printer { pub colors: Colors, mode: PrinterMode, } pub struct Colors { pub info: Style, ...
use ansi_term::Colour::*; use ansi_term::Style; use difference::{Changeset, Difference}; use error::*; use std::path::Path; #[derive(PartialEq)] enum PrinterMode { Silent, NoColor, Color, } pub struct Printer { pub colors: Colors, mode: PrinterMode, } pub struct Colors { pub info: Style, ...
pub fn no_color() -> Printer { let colors = Colors { info: Style::default(), warn: Style::default(), error: Style::default(), source: Style::default(), target: Style::default(), highlight: Style::default(), }; Pr...
target: Style::from(Green), highlight: Style::from(Red).bold(), }; Printer { colors, mode: PrinterMode::Color, } }
function_block-function_prefix_line
[ { "content": "/// Check if the paths references the same file. This is useful in case insensitive systems.\n\npub fn is_same_file(source: &Path, target: &Path) -> bool {\n\n // Only perform a more exhaustive check for platform that support case insensitive and case\n\n // preserving file systems by defaul...
Rust
src/system_control/scr/mod.rs
Meptl/mk20d7
c7cd01cf55214b0b53fae7c7672607e739b64663
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::SCR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::SCR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W...
{ #[doc = "o not sleep when returning to Thread mode"] _0, #[doc = "enter sleep, or deep sleep, on return from an ISR"] _1, } impl SLEEPONEXITW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SLEEPONEXITW::_0 => false, ...
r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] ...
random
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
pallets/broker/src/lib.rs
guzzit/broker_pallet
b3e0223cafeef964396b7a5d382009647e43aaed
#![cfg_attr(not(feature = "std"), no_std)] pub use pallet::*; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; mod tests; #[frame_support::pallet] pub mod pallet { use frame_support::{dispatch::DispatchResult, log, pallet_prelude::*}; use frame_system::pallet_prelude::*; use frame_support::{ sp_runtime:...
#![cfg_attr(not(feature = "std"), no_std)] pub use pallet::*; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; mod tests; #[frame_support::pallet] pub mod pallet { use frame_support::{dispatch::DispatchResult, log, pallet_prelude::*}; use frame_system::pallet_prelude::*; use frame_support::{ sp_runtime:...
} #[pallet::call] impl<T: Config> Pallet<T> { #[pallet::weight(100)] pub fn grant_brokerage( origin: OriginFor<T>, broker_id: AccountOf<T>, fixed_block_limit: BalanceOf<T>, ) -> DispatchResult { let client = ensure_signed(origin)?; let brokerage_id = Self::create_brokerage(client.clone(...
fn build(&self) { for (client_id, broker_id, fixed_block_limit) in &self.brokerages { let _ = <Pallet<T>>::create_brokerage(client_id.clone(), broker_id.clone(), fixed_block_limit.clone()); } }
function_block-full_function
[ { "content": "pub fn new_test_ext() -> sp_io::TestExternalities {\n\n\tlet mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();\n\n\tpallet_balances::GenesisConfig::<Test> {\n\n\t\t// Total issuance will be 200 with treasury account initialized at ED.\n\n\t\tbalances: vec![(0, 100), ...
Rust
src/asm.rs
millardjn/mask_opt
2b3ce2ccf3dd8c322269eb4fe543029efd457db4
#![allow(non_snake_case)] use crate::fft::{fft2, fft2_shift_inplace, ifft2, ifft2_shift_inplace, pad_zero_2D}; use image::{open, ImageBuffer, Luma}; use ndarray::{Array2, ShapeBuilder, Zip}; use num_complex::Complex; use std::cmp::max; use std::f64::consts::PI; use std::path::PathBuf; use std::sync::atomic::{AtomicUsi...
#![allow(non_snake_case)] use crate::fft::{fft2, fft2_shift_inplace, ifft2, ifft2_shift_inplace, pad_zero_2D}; use image::{open, ImageBuffer, Luma}; use ndarray::{Array2, ShapeBuilder, Zip}; use num_complex::Complex; use std::cmp::max; use std::f64::consts::PI; use std::path::PathBuf; use std::sync::atomic::{AtomicUsi...
fn asm_type_4( A_xi: &Array2<Complex<f64>>, z: f64, f: f64, pitch: f64, lambda: f64, gamma: f64, ) -> OutputAmplitude { unimplemented!() } fn scaling_czt( mut F_p_minus_m: Array2<Complex<f64>>, M: usize, pitch: f64, lambda: f64, ) -> Array2<Complex<f64>> { assert!(F_p...
fn asm_type_3( A_xi: &Array2<Complex<f64>>, z: f64, f: f64, pitch: f64, lambda: f64, gamma: f64, ) -> OutputAmplitude { unimplemented!() }
function_block-full_function
[ { "content": "pub fn ifft2_shift_inplace(mut input: ArrayViewMut2<Complex<f64>>) {\n\n for row in input.lanes_mut(Axis(1)) {\n\n ifft_shift_inplace(row);\n\n }\n\n for col in input.lanes_mut(Axis(0)) {\n\n ifft_shift_inplace(col);\n\n }\n\n}\n\n\n", "file_path": "src/fft.rs", "...
Rust
forc/src/cli/commands/addr2line.rs
binggh/sway
e75cbd7c975beb8ef1f93f5913abfb8db84e11f9
use anyhow::{anyhow, Result}; use clap::Parser; use std::collections::VecDeque; use std::fs::{self, File}; use std::io::{self, prelude::*, BufReader}; use std::path::{Path, PathBuf}; use annotate_snippets::{ display_list::{DisplayList, FormatOptions}, snippet::{AnnotationType, Slice, Snippet, SourceAnnotation}...
use anyhow::{anyhow, Result}; use clap::Parser; use std::collections::VecDeque; use std::fs::{self, File}; use s
ong)] pub opcode_index: usize, } pub(crate) fn exec(command: Command) -> Result<()> { let contents = fs::read(&command.sourcemap_path) .map_err(|err| anyhow!("{:?}: could not read: {:?}", command.sourcemap_path, err))?; let sm: SourceMap = serde_json::from_slice(&contents).map_err(|err| { ...
td::io::{self, prelude::*, BufReader}; use std::path::{Path, PathBuf}; use annotate_snippets::{ display_list::{DisplayList, FormatOptions}, snippet::{AnnotationType, Slice, Snippet, SourceAnnotation}, }; use sway_core::source_map::{LocationRange, SourceMap}; #[derive(Debug, Parser)] pub(crate) struct Command...
random
[ { "content": "fn format_file(file: &Path, formatted_content: &str) -> Result<()> {\n\n fs::write(file, formatted_content)?;\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::taplo_fmt;\n\n use std::default::Default;\n\n\n\n #[test]\n\n fn test_forc_indentation() {\n\n ...
Rust
src/swapchain.rs
acgaudette/voodoo
968bba208e05eb255e648ba9c4816af52bcca029
use std::sync::Arc; use std::marker::PhantomData; use smallvec::SmallVec; use vks; use ::{VdResult, SurfaceKhr, Device, PhysicalDevice, Image, Handle, Semaphore, Fence}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub struct SwapchainKhrHandle(pub(crate) vks::VkSwapchainKHR); impl SwapchainKhrHandle { ...
use std::sync::Arc; use std::marker::PhantomData; use smallvec::SmallVec; use vks; use ::{VdResult, SurfaceKhr, Device, PhysicalDevice, Image, Handle, Semaphore, Fence}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub struct SwapchainKhrHandle(pub(crate) vks::VkSwapchainKHR); impl SwapchainKhrHandle { ...
pub fn build(&mut self, device: Device) -> VdResult<SwapchainKhr> { let image_format = self.create_info.image_format().clone(); let extent = self.create_info.image_extent().clone(); let handle = unsafe { device.create_swapchain_khr(&self.create_info, None)? }; let images = u...
pub fn old_swapchain<'s, H>(&'s mut self, old_swapchain: H) -> &'s mut SwapchainKhrBuilder<'b> where H: Handle<Target=SwapchainKhrHandle> { self.create_info.set_old_swapchain(old_swapchain); self }
function_block-function_prefix_line
[ { "content": "/// Returns true if `orig_name` specifies a dispatchable or non-dispatchable\n\n/// handle.\n\n///\n\n/// What's a hashmap?\n\nfn struct_is_handle_type(orig_name: &str) -> bool {\n\n match orig_name {\n\n \"VkInstance\" => true,\n\n \"VkPhysicalDevice\" => true,\n\n \"VkDev...
Rust
libindy_vdr/tests/acceptance_mechanism.rs
Patrik-Stas/indy-vdr
d30afea013d37b41237ee04adea9f059e06ae783
#[macro_use] mod utils; inject_dependencies!(); use indy_vdr::common::did::DidValue; use indy_vdr::ledger::constants; use indy_vdr::ledger::requests::author_agreement::AcceptanceMechanisms; use crate::utils::fixtures::*; #[test] fn empty() { } const VERSION: &'static str = "1.0.0"; const CONTEXT: &'static str...
#[macro_use] mod utils; inject_dependencies!(); use indy_vdr::common::did::DidValue; use indy_vdr::ledger::constants; use indy_vdr::ledger::requests::author_agreement::AcceptanceMechanisms; use crate::utils::fixtures::*; #[test] fn empty() { } const VERSION: &'static str = "1.0.0"; const CONTEXT: &'static str...
check_request_operation(&request, expected_operation); } #[rstest] fn test_build_acceptance_mechanisms_request_with_context( request_builder: RequestBuilder, trustee_did: DidValue, ) { let request = request_builder .build...
let expected_operation = json!({ "type": constants::TXN_AUTHR_AGRMT_AML, "aml": aml(), "version": VERSION });
assignment_statement
[ { "content": "#[fixture]\n\npub fn timestamp() -> u64 {\n\n 12345\n\n}\n", "file_path": "libindy_vdr/tests/utils/fixtures.rs", "rank": 0, "score": 302123.1026551401 }, { "content": "fn compare_hash(text: &str, version: &str, hash: &str) -> VdrResult<()> {\n\n let calculated_hash = calc...
Rust
src/packet.rs
exrook/audiopus
f67124ce1964de6ab361b51e362830594c3a1fdc
use crate::{ffi, Bandwidth, Channels, Error, Result, SampleRate, TryFrom, TryInto}; fn packet_len_check(packet_buffer: &[u8]) -> Result<i32> { match packet_buffer { x if x.is_empty() => Err(Error::EmptyPacket), _ if packet_buffer.len() > std::i32::MAX as usize => Err(Error::Packet...
use crate::{ffi, Bandwidth, Channels, Error, Result, SampleRate, TryFrom, TryInto}; fn packet_len_check(packet_buffer: &[u8]) -> Result<i32> {
} pub struct Packet<'a>(&'a [u8]); impl<'a> Packet<'a> { pub fn as_ptr(&self) -> *const u8 { self.0.as_ptr() } pub fn i32_len(&self) -> i32 { self.0.len() as i32 } } impl<'a> TryInto<Packet<'a>> for &'a Vec<u8> { type Error = Error; fn try_into(self) -> Resul...
match packet_buffer { x if x.is_empty() => Err(Error::EmptyPacket), _ if packet_buffer.len() > std::i32::MAX as usize => Err(Error::PacketTooLarge), _ => Ok(packet_buffer.len() as i32), }
if_condition
[ { "content": "/// Checks if the `ffi_return_value` is documented by Opus.\n\n/// Returns `Error` if value is negative.\n\npub fn try_map_opus_error(ffi_return_value: i32) -> Result<i32> {\n\n match ffi_return_value {\n\n v if v < 0 => Err(Error::from(ErrorCode::from(v))),\n\n _ => Ok(ffi_return...
Rust
src/changes.rs
ModProg/emoji_builder
38f117597caa160f28356a76b66113f1e026056d
/* * Copyright 2019 Constantin A. <emoji.builder@c1710.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
/* * Copyright 2019 Constantin A. <emoji.builder@c1710.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
.from_path(path)?; Ok(FileHashes::from_csv_reader(&mut reader)) } pub fn from_reader<R: io::Read>(reader: R) -> Result<FileHashes, Error> { let mut reader = csv::ReaderBuilder::new() .has_headers(false) .from_reader(reader); Ok(FileHashes::...
om_path<P: AsRef<Path>>(path: P) -> Result<FileHashes, Error> { let mut reader = csv::ReaderBuilder::new() .has_headers(false)
function_block-random_span
[ { "content": "/// Saves the already encoded PNG file\n\npub fn write_png(build_path: &Path, emoji: &Emoji, image: Vec<u8>) -> std::io::Result<()> {\n\n let filename = Blobmoji::generate_filename(&emoji);\n\n let path = build_path\n\n .join(PNG_DIR)\n\n .join(&PathBuf::from(filename));\n\n ...
Rust
glommio/benches/proxy.rs
r3v2d0g/glommio
69fd84b347ef5965d7930352a540c875f6431a66
use std::time::Instant; use futures_lite::{ future::{block_on, try_zip}, io::{copy, split}, }; use glommio::{ net::{TcpListener, TcpStream}, prelude::*, }; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, runtime::{Builder, Handle, Runtime}, sync::oneshot, }; #[derive(Copy, Clone)] struct T...
use std::time::Instant; use futures_lite::{ future::{block_on, try_zip}, io::{copy, split}, }; use glommio::{ net::{TcpListener, TcpStream}, prelude::*, }; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, runtime::{Builder, Handle, Runtime}, sync::oneshot, }; #[derive(Copy, Clone)] struct T...
.unwrap(); while let Ok((mut stream, _)) = listener.accept().await { Handle::current().spawn(async move { let (mut read, mut write) = stream.split(); copy(&mut read, &mut write).await.ok(); }); } }); block_on(ready_recv).unwrap(); } fn st...
} runtime.shutdown_background(); } fn start_server(runtime: &Runtime, port: u16) { let (ready_send, ready_recv) = oneshot::channel(); runtime.spawn(async move { use tokio::{io::copy, net::TcpListener}; let listener = TcpListener::bind(("0.0.0.0", port)).await.unwrap(); ready_send....
random
[ { "content": "fn main() {\n\n let project = PathBuf::from(env::var(\"CARGO_MANIFEST_DIR\").unwrap())\n\n .canonicalize()\n\n .unwrap();\n\n\n\n let liburing = match env::var(\"GLOMMIO_LIBURING_DIR\") {\n\n Ok(path) => PathBuf::from(path).canonicalize().unwrap(),\n\n Err(_) => {...
Rust
zebra-chain/src/addresses/sprout.rs
Atul9/zebra
8276bed4004ae0ada837d435349f564ece8ebf87
use std::{fmt, io}; #[cfg(test)] use proptest::{arbitrary::Arbitrary, array, prelude::*}; use crate::{ keys::sprout, serialization::{ReadZcashExt, SerializationError, ZcashDeserialize, ZcashSerialize}, Network, }; mod magics { pub const MAINNET: [u8; 2] = [0x16, 0x9A]; pub const TESTNET: [u8; 2...
use std::{fmt, io}; #[cfg(test)] use proptest::{arbitrary::Arbitrary, array, prelude::*}; use crate::{ keys::sprout, serialization::{ReadZcashExt, SerializationError, ZcashDeserialize, ZcashSerialize}, Network, }; mod magics { pub const MAINNET: [u8; 2] = [0x16, 0x9A]; pub const TESTNET: [u8; 2...
lf.transmission_key.as_bytes() == other.transmission_key.as_bytes() } } impl Eq for SproutShieldedAddress {} impl ZcashSerialize for SproutShieldedAddress { fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> { match self.network { Network::Mainnet => writer.wri...
sion_key", &hex::encode(&self.transmission_key.as_bytes()), ) .finish() } } impl PartialEq for SproutShieldedAddress { fn eq(&self, other: &Self) -> bool { self.network == other.network && self.paying_key.0 == other.paying_key.0 && se
random
[ { "content": "fn write_coinbase_height<W: io::Write>(height: BlockHeight, mut w: W) -> Result<(), io::Error> {\n\n // We can't write this as a match statement on stable until exclusive range\n\n // guards are stabilized.\n\n if let 0 = height.0 {\n\n // Genesis block does not include height.\n\n...
Rust
emulator/src/apu/pulse_channel.rs
DaveTCode/nes-emulator-rust
6a68c01976febfafc160e443a54573964893115f
use apu::envelope::Envelope; use apu::length_counter::LengthCounter; use log::{debug, info}; const EIGHTH_DUTY_CYCLE: [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 1]; const QUARTER_DUTY_CYCLE: [u8; 8] = [0, 0, 0, 0, 0, 0, 1, 1]; const HALF_DUTY_CYCLE: [u8; 8] = [0, 0, 0, 0, 1, 1, 1, 1]; const NEGATIVE_QUARTER_DUTY_CYCLE: [u8; 8] =...
use apu::envelope::Envelope; use apu::length_counter::LengthCounter; use log::{debug, info}; const EIGHTH_DUTY_CYCLE: [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 1]; const QUARTER_DUTY_CYCLE: [u8; 8] = [0, 0, 0, 0, 0, 0, 1, 1]; const HALF_DUTY_CYCLE: [u8; 8] = [0, 0, 0, 0, 1, 1, 1, 1]; const NEGATIVE_QUARTER_DUTY_CYCLE: [u8; 8] =...
self.timer_load = (self.timer_load & 0b1111_1111) | ((value as u16 & 0b111) << 8); info!( "Loaded timer with {}, restarting envelope and duty sequence", self.timer_load ); self.sequence = 0; self.envelope.set_start_flag(); } pub(super) fn lo...
if self.enabled { self.length_counter.set(value); info!( "Loaded length counter for {}: {:02X} -> {:?}", self.name, value, self.length_counter ); }
if_condition
[ { "content": "fn framebuffer_to_ascii_art(fb: [u8; (256 * 240 * 4) as usize]) -> String {\n\n fn lookup(greyscale: f32) -> char {\n\n ASCII_GRAYSCALE_ARRAY[(greyscale * ASCII_GRAYSCALE_ARRAY.len() as f32) as usize]\n\n }\n\n\n\n fb.chunks(4)\n\n .map(|pixel| {\n\n let r = pixel...
Rust
src/prime.rs
phillip-h/reikna
73b12e9ff1f38744755d8b4246dfb161289ba98d
pub fn atkin(max_u64: u64) -> Vec<u64> { assert!(max_u64 < ::std::usize::MAX as u64, "sieve max {} is larger than machine word size!", max_u64); let max = max_u64 as usize; let mut primes: Vec<u64> = Vec::new(); match max { 0 | 1 => (), 2 => primes.extend_from_slice(...
pub fn atkin(max_u64: u64) -> Vec<u64> { assert!(max_u64 < ::std::usize::MAX as u64, "sieve max {} is larger than machine word size!", max_u64); let max = max_u64 as usize; let mut primes: Vec<u64> = Vec::new(); match max { 0 | 1 => (), 2 => primes.extend_from_slice(...
#[test] fn t_next_prime() { assert_eq!(next_prime(0), 2); assert_eq!(next_prime(1), 2); assert_eq!(next_prime(2), 3); assert_eq!(next_prime(3), 5); assert_eq!(next_prime(4), 5); assert_eq!(next_prime(15), 17); assert_eq!(next_prime(39), 41); assert_e...
let vec: Vec<u64> = vec![2, 2, 3]; assert_eq!(factorize(12), vec); let vec: Vec<u64> = vec![2, 2, 5, 5]; assert_eq!(factorize(100), vec); }
function_block-function_prefix_line
[ { "content": "/// Calculate the value of the prime-counting function for each\n\n/// value in `data`, and return a new `Vec<u64>` of the results.\n\n///\n\n/// The resulting vector has the same size as the input vector.\n\n/// \n\n/// This function works in fundamentally the same way as `prime_count()`,\n\n/// ...
Rust
edgelet/edgelet-core/src/authorization.rs
o0rebelious0o/iotedge
8bd573590cdc149c014cf994dba58fc63f1a5c74
use failure::Fail; use futures::future::Either; use futures::{future, Future, Stream}; use error::{Error, ErrorKind}; use module::{Module, ModuleRuntime}; use pid::Pid; pub enum Policy { Anonymous, Caller, Module(&'static str), } pub struct Authorization<M> where M: 'static + ModuleRuntime, { r...
use failure::Fail; use futures::future::Either; use futures::{future, Future, Stream}; use error::{Error, ErrorKind}; use module::{Module, ModuleRuntime}; use pid::Pid; pub enum Policy { Anonymous, Caller, Module(&'static str), } pub struct Authorization<M> where M: 'static + ModuleRuntime, { r...
#[test] fn should_reject_caller_without_name() { let runtime = TestModuleList::new(vec![TestModule::new("abc", 123)]); let auth = Authorization::new(runtime, Policy::Caller); assert_eq!(false, auth.authorize(None, Pid::Value(123)).wait().unwrap()); } #[test] fn should_reje...
tem_caller() { let runtime = TestModuleList::new(vec![ TestModule::new("xyz", 987), TestModule::new("edgeAgent", 123), ]); let auth = Authorization::new(runtime, Policy::Caller); assert_eq!( true, auth.authorize(Some("$edgeAgent".to_string(...
function_block-function_prefixed
[ { "content": "// Stop EdgeAgent\n\nfn stop_runtime<M>(runtime: &M, name: &str) -> impl Future<Item = (), Error = Error>\n\nwhere\n\n M: 'static + ModuleRuntime + Clone,\n\n for<'r> &'r <M as ModuleRuntime>::Error: Into<ModuleRuntimeErrorReason>,\n\n <M::Module as Module>::Config: Clone,\n\n{\n\n inf...
Rust
src/spline/bezier_ease.rs
BrainiumLLC/celerity
752fa37bc327e8c41c8c5f454b051582313beb67
use super::bezier::cubic_bezier_ease; use gee::Point; #[derive(Clone, Debug)] pub struct BezierEase { pub ox: f64, pub oy: f64, pub ix: f64, pub iy: f64, } impl BezierEase { pub const fn new(ox: f64, oy: f64, ix: f64, iy: f64) -> Self { Self { ox, oy, ix, iy } } pub fn as_points(&...
use super::bezier::cubic_bezier_ease; use gee::Point; #[derive(Clone, Debug)] pub struct BezierEase { pub ox: f64, pub oy: f64, pub ix: f64, pub iy: f64, } impl BezierEase { pub const fn new(ox: f64, oy: f64, ix: f64, iy: f64) -> Self { Self { ox, oy, ix, iy } } pub fn as_points(&...
#[test] fn test_vector_linear_path() { let start = Duration::from_secs_f64(10.0); let end = Duration::from_secs_f64(20.0); let from: gee::Point<f64> = gee::Point::new(-4.0, 0.0); let to: gee::Point<f64> = gee::Point::new(4.0, 0.0); let b1: gee::Point<f64> = gee::Point...
fn test_vector_eased() { let start = Duration::from_secs_f64(10.0); let q1 = Duration::from_secs_f64(12.5); let mid = Duration::from_secs_f64(15.0); let q2 = Duration::from_secs_f64(17.5); let end = Duration::from_secs_f64(20.0); let from: gee::Point<f64> = gee::Point::n...
function_block-full_function
[ { "content": "pub fn cubic_bezier_ease(ox: f64, oy: f64, ix: f64, iy: f64, t: f64) -> f64 {\n\n // Uses a cubic 2D bezier curve to map linear interpolation time\n\n // to eased interpolation time.\n\n //\n\n // https://cubic-bezier.com\n\n //\n\n // Bezier control points:\n\n // [0, 0], [ox...
Rust
rsrl/src/control/td/to_sarsa_lambda.rs
tspooner/rsrl
ffe062184dbd2cc322d0412343425900a2175008
use crate::{ Handler, OutputOf, domains::Transition, fa::linear::basis::Basis, params::*, policies::{Policy, EnumerablePolicy}, prediction::{ValuePredictor, ActionValuePredictor}, traces::Trace, }; use ndarray::{Array1, Ix1, linalg::Dot}; use rand::thread_rng; use std::f64; #[derive(Paramet...
use crate::{ Handler, OutputOf, domains::Transition, fa::linear::basis::Basis, params::*, policies::{Policy, EnumerablePolicy}, prediction::{ValuePredictor, ActionValuePredictor}, traces::Trace, }; use ndarray::{Array1, Ix1, linalg::Dot}; use rand::thread_rng; use std::f64; #[derive(Paramet...
pub fn zeros( basis: B, policy: P, alpha: f64, gamma: f64, lambda: f64, ) -> Self where B: spaces::Space, { let n: usize = basis.dim().into(); TOSARSALambda::new( basis, Array1::zeros(n), policy, alpha, gamma, lam...
theta.len()); TOSARSALambda { basis, theta, trace, policy, alpha: alpha.into(), gamma: gamma.into(), lambda: lambda.into(), q_old: 0.0, } }
function_block-function_prefixed
[ { "content": "pub fn argmax_last<I: IntoIterator<Item = f64>>(vals: I) -> (usize, f64) {\n\n vals.into_iter().enumerate().fold(\n\n (0, f64::MIN),\n\n |(i, x), (j, y)| {\n\n if y - x > -1e-7 {\n\n (j, y)\n\n } else {\n\n (i, x)\n\n ...
Rust
pittv3/src/no_std_utils.rs
carl-wallace/rust-pki
d59de7d4a5de480830e2ca8c7a2133d65065b525
#![cfg(any(not(feature = "std"), doc))] use crate::{stats::PathValidationStats, Pittv3Args}; use certval::*; #[cfg(feature = "std_app")] use crate::pitt_log::log_path; pub(crate) fn validate_cert( pe: &PkiEnvironment<'_>, cps: &CertificationPathSettings, cert_filename: &str, target: &[u8], stat...
#![cfg(any(not(feature = "std"), doc))] use crate::{stats::PathValidationStats, Pittv3Args}; use certval::*; #[cfg(feature = "std_app")] use crate::pitt_log::log_path; pub(crate) fn validate_cert( pe: &PkiEnvironment<'_>, cps: &CertificationPathSettings, cert_filename: &str, target: &[u8], stat...
th, &mut cpr); #[cfg(feature = "revocation")] let mut r = pe.validate_path(pe, cps, path, &mut cpr); #[cfg(feature = "revocation")] if let Ok(_valresult) = r { if get_check_revocation_status(cps) { r = check_revocation(pe, cps, path, ...
nd validating path(s) for {}", cert_filename ) .as_str(), ); stats.files_processed += 1; let mut paths: Vec<CertificationPath<'_>> = vec![]; let r = pe.get_paths_for_target(pe, &target_cert, &mut paths, 0, time_of_interest); if let Err(e)...
random
[ { "content": "/// `populate_5280_pki_environment` populates a default [`PkiEnvironment`] instance with a default set of callback\n\n/// functions specified.\n\n///\n\n/// The following callbacks are added:\n\n/// - [`validate_path_rfc5280`]\n\n/// - [`calculate_hash_rust_crypto`]\n\n/// - [`verify_signature_dig...
Rust
impl/shared/src/lib.rs
Project-Sustain/AtlasFS
28e988c06635f5e8b34f37820445ac663d0ddc8f
use glob::{GlobError, PatternError}; use prost::{EncodeError, DecodeError}; use radix::RadixError; use std::fmt::{Display, Formatter}; use std::num::{ParseFloatError, ParseIntError}; pub mod block; pub mod protos { include!(concat!(env!("OUT_DIR"), "/nahfs.rs")); } pub fn geohash_char_to_value(c: char) -> Result...
use glob::{GlobError, PatternError}; use prost::{EncodeError, DecodeError}; use radix::RadixError; use std::fmt::{Display, Formatter}; use std::num::{ParseFloatError, ParseIntError}; pub mod block; pub mod protos { include!(concat!(env!("OUT_DIR"), "/nahfs.rs")); } pub fn geohash_char_to_value(c: char) -> Result...
r) } } impl<'a> From<&'a str> for NahFSError { fn from(err: &'a str) -> NahFSError { NahFSError::Nah(String::from(err)) } } impl From<String> for NahFSError { fn from(err: String) -> NahFSError { NahFSError::Nah(err) } } #[cfg(test)] mod tests { #[test] fn it_works() { ...
97 && x <= 102 => Ok(x - 87), _ => Err(NahFSError::from( format!("invalid geohash character '{}'", c))), } } impl From<NahFSError> for std::io::Error { fn from(err: NahFSError) -> std::io::Error { std::io::Error::new(std::io::ErrorKind::Other, err.to_string()) } } #[derive(Debu...
random
[ { "content": "fn write_block(data: &Vec<u8>, bm_proto: &BlockMetadataProto,\n\n data_directory: &str) -> Result<(), NahFSError> {\n\n let now = SystemTime::now();\n\n\n\n // write block\n\n let file = File::create(format!(\"{}/blk_{}\", \n\n data_directory, bm_proto.block_id))?;\n\n le...
Rust
src/libs/source_codec/test_encoding_builder.rs
devzendo/digimorse
edd0b7f1bb38c33403f2a518be98236a038c1f5c
extern crate hamcrest2; use log::debug; use std::sync::{Arc, RwLock}; use crate::libs::keyer_io::keyer_io::KeyerSpeed; use crate::libs::source_codec::bitvec_source_encoding_builder::BitvecSourceEncodingBuilder; use crate::libs::source_codec::keying_encoder::{DefaultKeyingEncoder, KeyingEncoder}; use crate::libs::sour...
extern crate hamcrest2; use log::debug; use std::sync::{Arc, RwLock}; use crate::libs::keyer_io::keyer_io::KeyerSpeed; use crate::libs::source_codec::bitvec_source_encoding_builder::BitvecSourceEncodingBuilder; use crate::libs::source_codec::keying_encoder::{DefaultKeyingEncoder, KeyingEncoder}; use crate::libs::sour...
#[test] fn encode_delta_dit() { let vec = encoded(20, &[ Frame::KeyingDeltaDit { delta: 1 }, ]); debug!("{}", dump_byte_vec(&vec)); assert_eq!(vec, vec![0b10100000, 0b00100000, 0, 0, 0, 0, 0, 0]); } #[test] fn enco...
fn encode_end() { let vec = encoded(20, &[ Frame::KeyingEnd, ]); assert_eq!(vec, vec![0b10010000, 0, 0, 0, 0, 0, 0, 0]); }
function_block-full_function
[ { "content": "/// Given a number in delta range [-480 .. 480] (see note below), encode it in a given number of\n\n/// bits, returning it in a suitably sized type. This type can have enough of its rightmost bits\n\n/// taken to represent the encoded delta.\n\n/// The output type must be large enough to encode a ...
Rust
src/json/test.rs
lord/crudite
6d697caa871bb823102b807de9c398b3499d8d91
use super::tree::*; use super::value::{self, Value}; #[derive(Clone, PartialEq, Eq, Hash, Debug)] struct MyId(usize); fn vals_to_nums<Id>(vals: Vec<Value<Id>>) -> Vec<i64> { vals.iter() .map(|val| match val { Value::Int(i) => *i, _ => panic!("unexpected type in list"), }) ...
use super::tree::*; use super::value::{self, Value}; #[derive(Clone, PartialEq, Eq, Hash, Debug)] struct MyId(usize); fn vals_to_nums<Id>(vals: Vec<Value<Id>>) -> Vec<i64> { vals.iter() .map(|val| match val { Value::Int(i) => *i, _ => panic!("unexpected type in list"), }) ...
#[test] fn adjacent_string_index() { let mut tree = Tree::new_with_string_root(MyId(0)); for i in 0..5000 { tree.update(&Edit::TextInsert { index: value::StringIndex(MyId(i)), id: value::StringIndex(MyId(i + 10_000)), character: 'b', }) .unwrap(); ...
fn object_assignment_prevents_cycles() { let mut tree = Tree::new_with_object_root(MyId(0)); assert_eq!(Ok(NodeType::Object), tree.get_type(MyId(0))); assert_eq!( Ok(value::Parent::None), value::ObjectRef(MyId(0)).parent(&tree) ); tree.update(&Edit::MapCreate { ...
function_block-full_function
[ { "content": "fn lookup_id_index<Id: Hash + Clone + Eq + Debug>(\n\n tree: &Tree<Id>,\n\n lookup_id: &Id,\n\n) -> Result<(NodeId, usize), TreeError> {\n\n let node_id = tree.id_to_node(&lookup_id)?;\n\n let node = tree\n\n .nodes\n\n .get(&node_id)\n\n .expect(\"node_id listed i...
Rust
fog/test_infra/src/mock_users.rs
cosmicrocks/mobilecoin
d000d4b14752092437495657baeed99caa497864
use mc_common::logger::global_log; use mc_crypto_keys::RistrettoPublic; use mc_fog_types::{ view::{FogTxOut, FogTxOutMetadata, TxOutRecord}, BlockCount, }; use mc_fog_view_protocol::{FogViewConnection, UserPrivate, UserRngSet}; use mc_transaction_core::{fog_hint::FogHint, tx::TxOut, Amount}; use mc_util_from_...
use mc_common::logger::global_log; use mc_crypto_keys::RistrettoPublic; use mc_fog_types::{ view::{FogTxOut, FogTxOutMetadata, TxOutRecord}, BlockCount, }; use mc_fog_view_protocol::{FogViewConnection, UserPrivate, UserRngSet}; use mc_transaction_core::{fog_hint::FogHint, tx::TxOut, Amount}; use mc_util_from_...
); if !errors.is_empty() { global_log::error!("Unexpected errors when polling account server"); for err in errors { global_log::error!("{:?}", err); } panic!("Unexpected errors are fatal!"); } for tx...
s[prev_count..].iter().cloned().collect(), )) } else { None } }) .collect() } pub fn random_test_block<T: RngCore + CryptoRng>( &self, tx_count: usize, acct_server_pubkey: &RistrettoPubl...
random
[ { "content": "pub fn random_tx_row(rng: &mut impl RngCore) -> ETxOutRecord {\n\n let mut result: ETxOutRecord = Default::default();\n\n result.search_key.resize(16, 0);\n\n result.payload.resize(64, 0);\n\n rng.fill_bytes(&mut result.search_key[..]);\n\n rng.fill_bytes(&mut result.payload[..]);\n...
Rust
src/guard.rs
asomers/async-weighted-semaphore
2085026ab5f4a5b9b6bc8a724e7cdca75a212c32
use std::{mem, fmt}; use crate::Semaphore; use std::sync::Arc; use std::thread::panicking; use std::fmt::{Debug, Formatter}; #[must_use] pub struct SemaphoreGuard<'a> { semaphore: &'a Semaphore, amount: usize, panicking: bool, } #[must_use] pub struct SemaphoreGuardArc { semaphore: Option<Arc<Semaphor...
use std::{mem, fmt}; use crate::Semaphore; use std::sync::Arc; use std::thread::panicking; use std::fmt::{Debug, Formatter}; #[must_use] pub struct SemaphoreGuard<'a> { semaphore: &'a Semaphore, amount: usize, panicking: bool, } #[must_use] pub struct SemaphoreGuardArc { semaphore: Option<Arc<Semaphor...
} impl<'a> Debug for SemaphoreGuard<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "SemaphoreGuard({})", self.amount) } } impl Debug for SemaphoreGuardArc { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "SemaphoreGuardArc({})", self.amount) } }...
emaphore) = self.semaphore.take() { if !self.panicking && panicking() { semaphore.poison(); } else { semaphore.release(self.amount); } } }
function_block-function_prefixed
[ { "content": "struct SemMutex(Semaphore, UnsafeCell<usize>);\n\n\n\nunsafe impl Send for SemMutex {}\n\n\n\nunsafe impl Sync for SemMutex {}\n\n\n\nimpl Default for SemMutex {\n\n fn default() -> Self {\n\n SemMutex(Semaphore::new(1), UnsafeCell::new(0))\n\n }\n\n}\n\n\n\nimpl AtomicCounter for Sem...
Rust
src/models/github_user_records.rs
kleary/idevgames.com
8df563138a6685d27d30f36e362825a731c07759
use crate::{ db::DbConn, models::{r_to_opt, ModelError}, }; use super::users::User; #[derive(Debug, Queryable)] pub struct GithubUserRecord { pub id: i64, pub user_id: i32, pub login: String, pub avatar_url: String, pub html_url: String, } impl GithubUser...
use crate::{ db::DbConn, models::{r_to_opt, ModelError}, }; use super::users::User; #[derive(Debug, Queryable)] pub struct GithubUserRecord { pub id: i64, pub user_id: i32, pub login: String, pub avatar_url: String, pub html_url: String, } impl GithubUser...
pub fn get_user(&self, conn: &DbConn) -> Result<User, ModelError> { let u = User::find_by_id(&conn, self.user_id).transpose(); if u.is_none() { Err(ModelError::NotFound) } else { u.unwrap() } } }
f>, ModelError> { use crate::schema::github_user_records::dsl::{github_user_records, user_id}; use diesel::prelude::*; let user_record = github_user_records .filter(user_id.eq(the_user_id)) .limit(1) .first::<Self>(conn); r_to_opt(user_record) }
function_block-function_prefixed
[ { "content": "pub fn env_str(var: &str) -> String {\n\n env::var(var).expect(&format!(\n\n \"Please provide {} as an environment var or in a .env\",\n\n var\n\n ))\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 145891.66256555042 }, { "content": "pub fn env_...
Rust
sdk/cosmos/src/clients/cosmos_client.rs
cschaible/azure-sdk-for-rust
2876e88bae97377b926cacc24e78c186b0b909ee
use super::DatabaseClient; use crate::headers::*; use crate::requests; use crate::{AuthorizationToken, ReadonlyString, ResourceType}; use azure_core::{HttpClient, No}; use http::request::Builder as RequestBuilder; use http::{header, HeaderValue}; use ring::hmac; use url::form_urlencoded; use std::borrow::Cow; use std:...
use super::DatabaseClient; use crate::headers::*; use crate::requests; use crate::{AuthorizationToken, ReadonlyString, ResourceType}; use azure_core::{HttpClient, No}; use http::request::Builder as RequestBuilder; use http::{header, HeaderValue}; use ring::hmac; use url::form_urlencoded; use std::borrow::Cow; use std:...
; assert_eq!( ret, "get dbs dbs/MyDatabase/colls/MyCollection mon, 01 jan 1900 01:00:00 gmt " ); } #[test] fn generate_authorization_00() { let time = chrono::DateTime::parse_from_rfc3339("1900-01-01T01:00:00.000000000+00:00").unwrap(); l...
string_to_sign( &http::Method::GET, ResourceType::Databases, "dbs/MyDatabase/colls/MyCollection", &time, )
call_expression
[ { "content": "pub fn new(account: &str, key: &str) -> KeyClient {\n\n with_access_key(account, key)\n\n}\n\n\n", "file_path": "sdk/storage/src/core/client.rs", "rank": 0, "score": 433172.8974697164 }, { "content": "pub fn from_connection_string(connection_string: &str) -> Result<KeyClient...
Rust
src/fs_monitor.rs
wzjsun/pi_base
4170bfa026b6f8f5ee002a2744ffd76d4aa95a0f
use std::thread; use std::sync::Arc; use std::path::PathBuf; use std::time::Duration; use std::collections::HashMap; use std::sync::mpsc::{Sender, Receiver, channel}; use notify::{Watcher, RecursiveMode, DebouncedEvent, RecommendedWatcher, watcher}; use npnc::{ProduceError, ConsumeError}; use npnc::bounded::s...
use std::thread; use std::sync::Arc; use std::path::PathBuf; use std::time::Duration; use std::collections::HashMap; use std::sync::mpsc::{Sender, Receiver, channel}; use notify::{Watcher, RecursiveMode, DebouncedEvent, RecommendedWatcher, watcher}; use npnc::{ProduceError, ConsumeError}; use npnc::bounded::s...
RecursiveMode::NonRecursive }; match watcher.watch(&path, mode) { Err(e) => Err(format!("add fs monitor failed, path: {:?}, e: {:?}", path, e)), Ok(_) => { watchers.insert(path, watcher); ...
) { if let Err(e) = monitor_path(watchers, &sender, path, is_rec.clone(), time.clone()) { return Err(e); } } else { return Err(format!("monitor dir error, invalid dir, path: {:?}", &path)); ...
random
[ { "content": "//继续写\n\nfn pwrite_continue(len: usize, mut file: SharedFile, options: WriteOptions, pos: u64, bytes: Vec<u8>, vec_pos: u64, callback: Box<FnBox(Arc<<SharedFile as Shared>::T>, Result<usize>)>) {\n\n let func = move || {\n\n #[cfg(any(unix))]\n\n let r = file.inner.write_at(&bytes...
Rust
backend/api/src/service/mail.rs
johnnynotsolucky/ji-cloud
3b2dbded47ef5911c144e8b3b3dcd8db88744a0d
use core::settings::EmailClientSettings; use sendgrid::v3::{Content, Email, Message, Personalization, SGMap, Sender}; use shared::domain::{jig::report::JigReportEmail, session::OAuthProvider}; use tracing::instrument; use crate::error; use super::Service; const SENDER_NAME: &str = "Jigzi"; pub struct Client { c...
use core::settings::EmailClientSettings; use sendgrid::v3::{Content, Email, Message, Personalization, SGMap, Sender}; use shared::domain::{jig::report::JigReportEmail, session::OAuthProvider}; use tracing::instrument; use crate::error; use super::Service; const SENDER_NAME: &str = "Jigzi"; pub struct Client { c...
e) .ok_or(error::ServiceKind::Mail) } pub fn welcome_jigzi_template(&self) -> Result<WelcomeJigziTemplate<'_>, error::ServiceKind> { self.welcome_jigzi_template .as_deref() .map(WelcomeJigziTemplate) .ok_or(error::ServiceKind::Mail) } } impl...
end(&message).await?; Ok(()) } pub async fn send_email_reset( &self, template: EmailResetTemplate<'_>, to: Email, link: String, first_name: String, ) -> anyhow::Result<()> { let mut template_data = SGMap::new(); template_data.insert("url".to_...
random
[ { "content": "pub fn get_card_font_size(value: &str, size: Option<&Size>) -> String {\n\n let size = match size {\n\n None => 40f32, // Return the original font size\n\n Some(size) => {\n\n let size_scale = match size {\n\n Size::Flashcards => 1f32,\n\n ...
Rust
redbpf/src/load/loader.rs
tilpner/redbpf
a8cbba0b2b0bf892068ac4c521f51f43fb2c0874
use bpf_sys; use futures::channel::mpsc; use futures::prelude::*; use std::ffi::CString; use std::fs; use std::io; use std::path::Path; use crate::cpus; use crate::load::map_io::PerfMessageStream; use crate::ProgramKind::*; use crate::{xdp, Error, Module, PerfMap}; #[derive(Debug)] pub enum LoaderError { FileEr...
use bpf_sys; use futures::channel::mpsc; use futures::prelude::*; use std::ffi::CString; use std::fs; use std::io; use std::path::Path; use crate::cpus; use crate::load::map_io::PerfMessageStream; use crate::ProgramKind::*; use crate::{xdp, Error, Module, PerfMap}; #[derive(Debug)] pub enum LoaderError { FileEr...
} } #[derive(Debug, Clone)] pub struct XdpConfig { interface: Option<String>, flags: xdp::Flags, } impl Default for XdpConfig { fn default() -> XdpConfig { XdpConfig { interface: None, flags: xdp::Flags::default(), } } }
if let Some(interface) = &self.xdp.interface { let ciface = CString::new(interface.as_bytes()).unwrap(); let _ = unsafe { bpf_sys::bpf_attach_xdp(ciface.as_ptr(), -1, 0) }; }
if_condition
[ { "content": "pub fn load(program: &PathBuf, interface: Option<&str>) -> Result<(), CommandError> {\n\n let mut runtime = Runtime::new().unwrap();\n\n let _ = runtime.block_on(async {\n\n let mut loader = Loader::new()\n\n .xdp(interface.map(String::from), xdp::Flags::default())\n\n ...
Rust
format/src/wld.rs
jamen/fable_formats
07e2c7746f5a64e1a35545ec0edc10e2f58c6648
use std::io::Read; use crate::Error; use crate::{ Field, IResult, Index, Value, all_consuming, decode_field, decode_field_tagged, many0, many_till, multispace0, }; #[derive(Debug,PartialEq)] pub struct Wld { pub start_initial_quests: Vec<String>, pub map_uid_count: isi...
use std::io::Read; use crate::Error; use crate::{ Field, IResult, Index, Value, all_consuming, decode_field, decode_field_tagged, many0, many_till, multispace0, }; #[derive(Debug,PartialEq)] pub struct Wld { pub start_initial_quests: Vec<String>, pub map_uid_count: isi...
fn decode_thing_manager_uid_count(input: &[u8]) -> IResult<&[u8], isize, Error> { let (input, field) = decode_field_tagged("ThingManagerUIDCount")(input)?; match field.value { Value::Integer(n) => Ok((input, n)), _ => Err(nom::Err::Error(Error::InvalidValue)) } ...
8], isize, Error> { let (input, field) = decode_field_tagged("MapUIDCount")(input)?; match field.value { Value::Integer(n) => Ok((input, n)), _ => Err(nom::Err::Error(Error::InvalidValue)) } }
function_block-function_prefixed
[ { "content": "pub fn decode_field_tagged<'a>(name: &'a str) -> impl Fn(&'a [u8]) -> IResult<&[u8], Field, Error> {\n\n move |input: &[u8]| {\n\n let (input, field) = decode_field(input)?;\n\n\n\n if field.name == name.to_string() {\n\n Ok((input, field))\n\n } else {\n\n ...
Rust
tetris-hard-drop-patcher/src/main.rs
cdubz/mos6502
d88ad4deb8bc55ecba72d833ec05eafb76eb3807
use ines::Ines; use mos6502_assembler::{Addr, Block, LabelRelativeOffset, LabelRelativeOffsetOwned}; use mos6502_model::Address; const HINT_PATTERN_INDEX: u8 = 0xFA; const SHAPE_TABLE: Address = 0x8A9C; const ZP_PIECE_COORD_X: u8 = 0x40; const ZP_PIECE_COORD_Y: u8 = 0x41; const ZP_PIECE_SHAPE: u8 = 0x42; const BOARD_T...
use ines::Ines; use mos6502_assembler::{Addr, Block, LabelRelativeOffset, LabelRelativeOffsetOwned}; use mos6502_model::Address; const HINT_PATTERN_INDEX: u8 = 0xFA; const SHAPE_TABLE: Address = 0x8A9C; const ZP_PIECE_COORD_X: u8 = 0x40; const ZP_PIECE_COORD_Y: u8 = 0x41; const ZP_PIECE_SHAPE: u8 = 0x42; const BOARD_T...
fn program_oam_dma_page_update( b: &mut Block, label: &str, original_function_address: Address, args: &Args, ) { use mos6502_model::addressing_mode::*; use mos6502_model::assembler_instruction::*; b.label(label); b.inst(Jsr(Absolute), original_function_address); if !args.hide_gh...
ller-end")); b.inst(Jsr(Absolute), "compute-hard-drop-distance"); b.inst(Tax, ()); b.inst(Clc, ()); b.inst(Adc(ZeroPage), ZP_PIECE_COORD_Y); b.inst(Sta(ZeroPage), ZP_PIECE_COORD_Y); b.inst(Lda(Immediate), 0x00); b.inst(Sta(ZeroPage), 0x4E); b.inst(Lda(ZeroPage), ...
function_block-function_prefixed
[]
Rust
migration-engine/core/tests/migration_persistence_tests.rs
WellFail/prisma-engine
ae3fd55d36b87de33ecfd34565efbb5a3671fc7d
#![allow(non_snake_case)] #![allow(unused)] mod test_harness; use migration_connector::{steps::CreateEnum, *}; use pretty_assertions::{assert_eq, assert_ne}; use sql_migration_connector::SqlFamily; use test_harness::*; #[test] fn last_should_return_none_if_there_is_no_migration() { test_each_connector(|_, api| { ...
#![allow(non_snake_case)] #![allow(unused)] mod test_harness; use migration_connector::{steps::CreateEnum, *}; use pretty_assertions::{assert_eq, assert_ne}; use sql_migration_connector::SqlFamily; use test_harness::*; #[test] fn last_should_return_none_if_there_is_no_migration() { test_each_connector(|_, api| { ...
#[test] fn create_should_increment_revisions() { test_each_connector(|_, api| { let persistence = api.migration_persistence(); let migration1 = persistence.create(Migration::new("migration_1".to_string())); let migration2 = persistence.create(Migration::new("migration_2".to_string())); ...
fn create_should_allow_to_create_a_new_migration() { test_each_connector(|test_setup, api| { let datamodel = datamodel::parse_datamodel( r#" model Test { id String @id @default(cuid()) } "#, ) .unwrap(); let ...
function_block-full_function
[ { "content": " def test[T](fn: String => T) = internal(None)(fn)\n", "file_path": "query-engine/connector-test-kit/src/test/scala/util/TestDataModelsWrapper.scala", "rank": 0, "score": 265559.46635050385 }, { "content": "fn test_each_backend<MigrationFn, TestFn>(mut mi...
Rust
src/quickjs_utils/json.rs
SreeniIO/quickjs_es_runtime
a765180d98829e73705d66eb5cbe866e30f28948
use crate::quickjs_utils; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::valueref::JSValueRef; use hirofa_utils::js_utils::JsError; use libquickjs_sys as q; use std::ffi::CString; pub fn parse_q(q_ctx: &QuickJsRealmAdapter, input: &str) -> Result<JSValueRef, JsError> { unsafe { parse(q_ctx.conte...
use crate::quickjs_utils; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::valueref::JSValueRef; use hirofa_utils::js_utils::JsError; use libquickjs_sys as q; use std::ffi::CString; pub fn parse_q(q_ctx: &QuickJsRealmAdapter, input: &str) -> Result<JSValueRef, JsError> { unsafe { parse(q_ctx.conte...
.ok() .unwrap(); objects::set_property_q( q_ctx, &obj, "c", &primitives::from_string_q(q_ctx, "abc").ok().unwrap(), ) .ok() .unwrap(); let str_res = json::stringify_q(q_ct...
S_JSONStringify( context, *input.borrow_value(), quickjs_utils::new_null(), *space_ref.borrow_value(), ); let ret = JSValueRef::new(context, val, false, true, "json::stringify result"); if ret.is_exception() { if let Some(ex) = QuickJsRealmAdapter::get_exception(cont...
random
[ { "content": "pub fn from_string_q(q_ctx: &QuickJsRealmAdapter, s: &str) -> Result<JSValueRef, JsError> {\n\n unsafe { from_string(q_ctx.context, s) }\n\n}\n\n/// # Safety\n\n/// When passing a context pointer please make sure the corresponding QuickJsContext is still valid\n\npub unsafe fn from_string(conte...
Rust
src/pass/real.rs
wrnrlr/baryon
18784713d6bf573716fe71329fca3f783361440e
use bc::ContextDetail as _; use fxhash::FxHashMap; use std::mem; use wgpu::util::DeviceExt as _; #[derive(Clone, Copy, Debug)] pub struct Material { pub base_color_map: Option<crate::ImageRef>, pub emissive_color: crate::Color, pub metallic_factor: f32, pub roughness_factor: f32, pub normal_scale: ...
use bc::ContextDetail as _; use fxhash::FxHashMap; use std::mem; use wgpu::util::DeviceExt as _; #[derive(Clone, Copy, Debug)] pub struct Material { pub base_color_map: Option<crate::ImageRef>, pub emissive_color: crate::Color, pub metallic_factor: f32, pub roughness_factor: f32, pub normal_scale: ...
; let mut color_intensity = light.color.into_vec4(); color_intensity[3] = light.intensity; Light { pos, rot: space.rot, color_intensity, } }) .collect::<Vec<_>>(); ...
match light.kind { bc::LightKind::Directional => 0.0, bc::LightKind::Point => 1.0, }
if_condition
[ { "content": "fn load_texture(mut data: gltf::image::Data, context: &mut crate::Context) -> Texture {\n\n let format = match data.format {\n\n gltf::image::Format::R8 => wgpu::TextureFormat::R8Unorm,\n\n gltf::image::Format::R8G8 => wgpu::TextureFormat::Rg8Unorm,\n\n gltf::image::Format:...
Rust
src/types/input_file/media_group.rs
uwinx/tbot
60189fb254e203e275201acc5742041b9c3895ed
use std::slice; use super::{Audio, Document, Photo, Video}; use is_macro::Is; use serde::{ ser::{SerializeSeq, Serializer}, Serialize, }; #[derive(Debug, PartialEq, Eq, Clone, Hash, Is)] #[non_exhaustive] #[must_use] pub enum PhotoOrVideo { Photo(Photo), Video(Video), } #[derive(Debug, Part...
use std::slice; use super::{Audio, Document, Photo, Video}; use is_macro::Is; use serde::{ ser::{SerializeSeq, Serializer}, Serialize, }; #[derive(Debug, PartialEq, Eq, Clone, Hash, Is)] #[non_exhaustive] #[must_use] pub enum PhotoOrVideo { Photo(Photo), Video(Video), } #[derive(Debug, Part...
iter.next().map(AnyGroupMedia::Document) } } } } match self { Self::PhotosAndVideos(album) => Iter::PhotosAndVideos(album.iter()), Self::Audios(audios) => Iter::Audios(audios.iter()), Self::Documents(documents) => I...
n<Self::Item> { match self { Self::PhotosAndVideos(iter) => { iter.next().map(|media| match media { PhotoOrVideo::Photo(photo) => { AnyGroupMedia::Photo(photo) } ...
function_block-random_span
[ { "content": "/// Checks if the document's extension matches one of the given extensions.\n\npub fn match_extension<'a, I, T, C>(\n\n extensions: I,\n\n) -> impl Fn(Arc<C>) -> BoxFuture<'a, bool> + Send + Sync + 'a\n\nwhere\n\n for<'b> &'b I: IntoIterator<Item = &'b T>,\n\n T: Deref<Target = str>,\n\n ...
Rust
puyoai-core/src/field/simulation_tests.rs
mayah/rust-puyoai
4c94087d012e7cfdfb859ad8fddd8fac8918a109
use field::{PuyoPlainField, RealPlainField}; use frame; use rensa_result::RensaResult; #[cfg(all(target_feature = "avx2", target_feature = "bmi2"))] use field::BitField; fn run_puyoplainfield_test(mut pf: PuyoPlainField, expected_result: &RensaResult) { let actual_result = pf.simulate(); assert_eq!(actual_re...
use field::{PuyoPlainField, RealPlainField}; use frame; use rensa_result::RensaResult; #[cfg(all(target_feature = "avx2", target_feature = "bmi2"))] use field::BitField; fn run_puyoplainfield_test(mut pf: PuyoPlainField, expected_result: &RensaResult) { let actual_result = pf.simulate(); assert_eq!(actual_re...
ult); } #[test] fn test_simulate_1rensa_nonquick_case3() { let src = concat!( ".....Y", "....YR", "...RRR"); let expected_result = RensaResult { chain: 1, score: 40, frame: frame::FRAMES_VANISH_ANIMATION + frame::FRAMES_TO_DROP_FAST[2] + frame::FRAMES_GROUNDING,...
lt) { run_puyoplainfield_test(PuyoPlainField::from_str(src), &expected_result); run_realplainfield_test(RealPlainField::from_str(src), &expected_result); } #[test] fn test_simulate_1rensa_quick() { let src = "..RRRR"; let expected_result = RensaResult { chain: 1, score: 40, fra...
random
[ { "content": "fn escape_message(s: &str) -> String {\n\n let mut result = String::new();\n\n for c in s.chars() {\n\n if c == ' ' {\n\n result.push('_');\n\n } else if c == '\\n' {\n\n result.push(',');\n\n } else {\n\n result.push(c);\n\n }\n\n...
Rust
src/decimal.rs
eranfu/fast-float-rust
dfda5f4ddf1662e254d4333d387f2128404d0f5b
use core::fmt::{self, Debug}; use std::cmp::Ordering; use crate::common::{is_8digits, parse_digits, ByteSlice}; #[derive(Clone)] pub struct Decimal { pub num_digits: usize, pub decimal_point: i32, pub negative: bool, pub truncated: bool, pub digits: [u8; Self::MAX_DIGITS], } impl Debug for Decima...
use core::fmt::{self, Debug}; use std::cmp::Ordering; use crate::common::{is_8digits, parse_digits, ByteSlice}; #[derive(Clone)] pub struct Decimal { pub num_digits: usize, pub decimal_point: i32, pub negative: bool, pub truncated: bool, pub digits: [u8; Self::MAX_DIGITS], } impl Debug for Decima...
return num_new_digits - 1; } Ordering::Equal => { continue; } Ordering::Greater => { return num_new_digits; } } } num_new_digits }
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn parse_digits(s: &mut &[u8], mut f: impl FnMut(u8)) {\n\n while !s.is_empty() {\n\n let c = s.get_first().wrapping_sub(b'0');\n\n if c < 10 {\n\n f(c);\n\n *s = s.advance(1);\n\n } else {\n\n break;\n\n }\n\n }\n...
Rust
crates/github_scbot_logic/src/tests/pr_creation.rs
sharingcloud/github-scbot
953ba1ae7f3bb06c37084756458a1ddb53c8fa65
use github_scbot_database::{ models::{DatabaseAdapter, IDatabaseAdapter, RepositoryModel}, tests::using_test_db, Result as DatabaseResult, }; use github_scbot_types::{ common::{GhRepository, GhUser}, pulls::{GhPullRequest, GhPullRequestAction, GhPullRequestEvent}, }; use crate::{pulls::PullRequestL...
use github_scbot_database::{ models::{DatabaseAdapter, IDatabaseAdapter, RepositoryModel}, tests::using_test_db, Result as DatabaseResult, }; use github_scbot_types::{ common::{GhRepository, GhUser}, pulls::{GhPullRequest, GhPullRequestAction, GhPullRequestEvent}, }; use crate::{pulls::PullRequestL...
let repository = RepositoryModel::builder_from_github(&config, &creation_event.repository) .manual_interaction(true) .create_or_update(db_adapter.repository()) .await?; assert!(!PullRequestLogic::should_c...
let creation_event = GhPullRequestEvent { action: GhPullRequestAction::Opened, repository: GhRepository { name: "name".to_string(), owner: GhUser { login: "owner".to_string(), }, full_...
assignment_statement
[ { "content": "/// Establish a connection to a database pool.\n\npub fn establish_pool_connection(config: &Config) -> Result<DbPool> {\n\n ConnectionBuilder::configure(config).build_pool()\n\n}\n\n\n", "file_path": "crates/github_scbot_database/src/lib.rs", "rank": 0, "score": 210176.7009455915 ...
Rust
src/content.rs
k7f/aces
6c7d6a1f08cc826aeeff933155dbc9b2672f1f25
use std::{ ops::{AddAssign, MulAssign}, collections::{BTreeMap, BTreeSet}, path::Path, fmt, error::Error, }; use crate::{DotId, ContextHandle}; pub trait ContentFormat: fmt::Debug { fn expected_extensions(&self) -> &[&str]; fn path_is_acceptable(&self, path: &Path) -> bool { ...
use std::{ ops::{AddAssign, MulAssign}, collections::{BTreeMap, BTreeSet}, path::Path, fmt, error::Error, }; use crate::{DotId, ContextHandle}; pub trait ContentFormat: fmt::Debug { fn expected_extensions(&self) -> &[&str]; fn path_is_acceptable(&self, path: &Path) -> bool { ...
lContent { fn add_assign(&mut self, other: Self) { for (id, poly) in other.causes.content { self.add_to_causes(id, &poly.content); } for (id, poly) in other.effects.content { self.add_to_effects(id, &poly.content); } } } impl MulAssign for PartialContent...
return false } } true } fn script_is_acceptable(&self, script: &str) -> bool; fn script_to_content( &self, cxt: &ContextHandle, script: &str, root_name: Option<&str>, ) -> Result<Box<dyn Content>, Box<dyn Error>>; } #[derive(C...
random
[ { "content": "/// A trait of an identifier convertible into [`DotId`] and into\n\n/// [`sat::Literal`].\n\npub trait Atomic:\n\n From<AtomId> + Into<AtomId> + Contextual + Copy + PartialEq + Eq + PartialOrd + Ord\n\n{\n\n fn into_dot_id(this: InContext<Self>) -> Option<DotId>;\n\n\n\n fn into_dot_id_or...
Rust
src/semck/mod.rs
rodrigo-bruno/dora
3c86c8d5ff7be52846f57fbaf46a047bf9c854b1
use class::TypeParams; use ctxt::{NodeMap, SemContext}; use dora_parser::ast::Type::{TypeBasic, TypeLambda, TypeSelf, TypeTuple}; use dora_parser::ast::{Stmt, Type}; use dora_parser::error::msg::Msg; use mem; use sym::Sym::{SymClass, SymClassTypeParam, SymFctTypeParam, SymStruct, SymTrait}; use ty::BuiltinType; mod ab...
use class::TypeParams; use ctxt::{NodeMap, SemContext}; use dora_parser::ast::Type::{TypeBasic, TypeLambda, TypeSelf, TypeTuple}; use dora_parser::ast::{Stmt, Type}; use dora_parser::error::msg::Msg; use mem; use sym::Sym::{SymClass, SymClassTypeParam, SymFctTypeParam, SymStruct, SymTrait}; use ty::BuiltinType; mod ab...
pub fn err(code: &'static str, pos: Position, msg: Msg) { test::parse_with_errors(code, |ctxt| { let diag = ctxt.diag.borrow(); let errors = diag.errors(); println!("errors = {:?}", errors); assert_eq!(1, errors.len()); assert_eq!(pos, errors[0...
R>(code: &'static str, f: F) -> R where F: FnOnce(&SemContext) -> R, { test::parse_with_errors(code, |ctxt| { let diag = ctxt.diag.borrow(); let errors = diag.errors(); println!("errors = {:?}", errors); for e in errors { println!...
function_block-function_prefixed
[ { "content": "fn internal_fct<'ast>(ctxt: &mut SemContext<'ast>, name: &str, kind: FctKind) {\n\n let name = ctxt.interner.intern(name);\n\n let fctid = ctxt.sym.borrow().get_fct(name);\n\n\n\n if let Some(fctid) = fctid {\n\n let mut fct = ctxt.fcts[fctid].borrow_mut();\n\n\n\n if fct.in...
Rust
src/structureddata.rs
danielzfranklin/lldb.rs
ca0a1b3a9b7d7443a98d9e93d2bb0328014e9718
use super::error::SBError; use super::stream::SBStream; use std::ffi::CString; use std::fmt; use std::ptr; use sys; pub struct SBStructuredData { pub raw: sys::SBStructuredDataRef, } impl SBStructuredData { pub fn wrap(raw: sys::SBStructuredDataRef) -> SBStructuredData { SBStructuredData {...
use super::error::SBError; use super::stream::SBStream; use std::ffi::CString; use std::fmt; use std::ptr; use sys; pub struct SBStructuredData { pub raw: sys::SBStructuredDataRef, } impl SBStructuredData { pub fn wrap(raw: sys::SBStructuredDataRef) -> SBStructuredData { SBStructuredData {...
pub fn item_at_index(&self, idx: usize) -> Option<SBStructuredData> { SBStructuredData::maybe_wrap(unsafe { sys::SBStructuredDataGetItemAtIndex(self.raw, idx) }) } pub fn integer_value(&self) -> Option<u64> { if self.data_type() == sys::StructuredDataType::Integer { ...
pub fn value_for_key(&self, key: &str) -> Option<SBStructuredData> { let key = CString::new(key).unwrap(); SBStructuredData::maybe_wrap(unsafe { sys::SBStructuredDataGetValueForKey(self.raw, key.as_ptr()) }) }
function_block-function_prefix_line
[ { "content": "\n\n /// If this stream is not redirected to a file, this retrieves the\n\n /// length of the locally cached data.\n\n pub fn len(&self) -> usize {\n\n unsafe { sys::SBStreamGetSize(self.raw) as usize }\n\n }\n\n\n\n /// Is this stream empty?\n\n pub fn is_empty(&self) -> ...
Rust
src/lib.rs
ObsidianMinor/lol-html
c33054d922edf4c8ed0499e83a94451bfae87ac9
#[macro_use] mod base; #[macro_use] mod html; #[macro_use] mod rewriter; mod memory; mod parser; mod rewritable_units; mod transform_stream; use cfg_if::cfg_if; pub use self::rewriter::{ rewrite_str, DocumentContentHandlers, ElementContentHandlers, HtmlRewriter, MemorySettings, RewriteStrSettings, Settin...
#[macro_use] mod base; #[macro_use] mod html; #[macro_use] mod rewriter; mod memory; mod parser; mod rewritable_units; mod transform_stream; use cfg_if::cfg_if; pub use self::rewriter::{ rewrite_str, DocumentContentHandlers, ElementContentHandlers, HtmlRewriter, MemorySettings, RewriteStrSettings, Settin...
.0 .into_owned() } } } cfg_if! { if #[cfg(feature = "integration_test")] { pub mod selectors_vm; pub use self::transform_stream::{ StartTagHandlingResult, TransformController, TransformStream, TransformStreamSettings }; ...
ent { pub use super::rewritable_units::{ Attribute, Comment, ContentType, Doctype, DocumentEnd, Element, TextChunk, UserData, }; pub use super::html::TextType; } #[cfg(any(test, feature = "integration_test"))] pub mod test_utils { use encoding_rs::*; pub static ASCII_COMPATIBLE_ENCODINGS:...
random
[ { "content": "/// Rewrites given `html` string with the provided `settings`.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use lol_html::{rewrite_str, element, RewriteStrSettings};\n\n///\n\n/// let output = rewrite_str(\n\n/// r#\"<div><a href=\"http://example.com\"></a></div>\"#,\n\n/// RewriteStrS...
Rust
utils/search-export/src/normalize/accession.rs
RNAcentral/rnacentral-import-pipeline
238e573440c72581a051b16c15f56fcd25bece74
use std::{ collections::HashSet, iter::FromIterator, }; use serde::{ Deserialize, Serialize, }; #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)] pub struct RawAccession { pub id: usize, pub urs_taxid: String, accession: String, common_name: Option<String>, database: S...
use std::{ collections::HashSet, iter::FromIterator, }; use serde::{ Deserialize, Serialize, }; #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)] pub struct RawAccession { pub id: usize, pub urs_taxid: String, accession: String, common_name: Option<String>, database: S...
value.journals.extend(i.journal.into_iter()); value.pub_titles.extend(i.pub_title.into_iter().filter(|t| !t.is_empty())); value.pub_ids.extend(i.pub_id.into_iter()); value.pubmed_ids.extend(i.pubmed_id.into_iter().filter(|t| !t.is_empty())); value.dois.exten...
if i.authors.is_some() { let authors = i.authors.unwrap(); let authors = authors.split(", ").filter(|a| !a.is_empty()).map(|s| s.to_string()); value.authors.extend(authors); }
if_condition
[ { "content": "pub fn group(path: &Path, min: usize, max: usize, output: &Path) -> Result<()> {\n\n grouper::group::<RawAccessionEntry>(grouper::Criteria::AtleastOne, &path, min, max, &output)\n\n}\n", "file_path": "utils/precompute/src/accessions.rs", "rank": 0, "score": 246834.7297733107 }, ...
Rust
kernel/src/arch/x86_64/interrupt/idt.rs
codesforu/rux
4b15340de89d9f3bfdd2a4c27cad6e68bf9f15bb
use arch::segmentation::{self, SegmentSelector}; use super::bit_field::BitField; use super::{HandlerFunc, InterruptVector}; pub struct Idt([Entry; 256]); #[derive(Debug, Clone, Copy)] #[repr(C, packed)] pub struct Entry { pointer_low: u16, gdt_selector: SegmentSelector, options: BitField<u16>, pointer...
use arch::segmentation::{self, SegmentSelector}; use super::bit_field::BitField; use super::{HandlerFunc, InterruptVector}; pub struct Idt([Entry; 256]); #[derive(Debug, Clone, Copy)] #[repr(C, packed)] pub struct Entry { pointer_low: u16, gdt_selector: SegmentSelector, options: BitField<u16>, pointer...
unsafe { lidt(&ptr) }; } } impl Entry { fn new(gdt_selector: SegmentSelector, handler: HandlerFunc) -> Self { let pointer = handler as u64; let mut entry = Entry { gdt_selector: gdt_selector, pointer_low: pointer as u16, pointer_middle: (pointe...
let ptr = DescriptorTablePointer { base: self as *const _ as u64, limit: (size_of::<Self>() - 1) as u16, };
assignment_statement
[ { "content": "/// Decode a code in the PS/2 scan code set 1 (legacy set).\n\n///\n\n/// Difference between set 1 and sets 2 & 3:\n\n/// http://wiki.osdev.org/%228042%22_PS/2_Controller#Translation\n\n///\n\n/// Reference table:\n\n/// http://www.computer-engineering.org/ps2keyboard/scancodes1.html\n\npub fn...
Rust
src/graphql_api/input.rs
Mozilla-GitHub-Standards/3bbbe029a3a84293c012a5a294504e0d1e91aadbcff8904435723496fdb97f28
288e63f3eaa750e27eb009cdd3532e9849facb76
use crate::graphql_api::avatar::upload_picture; use crate::settings::Fossil; use chrono::SecondsFormat; use chrono::Utc; use cis_profile::crypto::Signer; use cis_profile::schema::Display; use cis_profile::schema::KeyValue; use cis_profile::schema::Profile; use cis_profile::schema::PublisherAuthority; use cis_profile::s...
use crate::graphql_api::avatar::upload_picture; use crate::settings::Fossil; use chrono::SecondsFormat; use chrono::Utc; use cis_profile::crypto::Signer; use cis_profile::schema::Display; use cis_profile::schema::KeyValue; use cis_profile::schema::Profile; use cis_profile::schema::PublisherAuthority; use cis_profile::s...
fn update_key_values( s: &Option<KeyValuesWithDisplay>, p: &mut StandardAttributeValues, now: &str, store: &impl Signer, ) -> Result<(), Error> { if let Some(x) = s { let mut sign = false; if let Some(values) = &x.values { let values: BTreeMap<String, Option<String>> = ...
fn update_string( s: &Option<StringWithDisplay>, p: &mut StandardAttributeString, now: &str, store: &impl Signer, ) -> Result<(), Error> { if let Some(x) = s { let mut sign = false; if x.value != p.value { if let Some(value) = &x.value { p.value = Some(val...
function_block-full_function
[ { "content": "fn field_error(msg: &str, e: impl std::fmt::Display) -> FieldError {\n\n let error = format!(\"{}: {}\", msg, e);\n\n FieldError::new(msg, graphql_value!({ \"internal_error\": error }))\n\n}\n\n\n", "file_path": "src/graphql_api/root.rs", "rank": 0, "score": 92731.82819514044 }...
Rust
src/db/update/test.rs
ikrelln/ikrelln
939c33aaaa58c373cfde985f997f7e2adf1a3151
use actix::{Handler, Message, MessageResult}; use chrono; use diesel; use diesel::prelude::*; use serde_json; use uuid; use crate::db::schema::test_item; #[derive(Debug, Insertable, Queryable, Clone, Identifiable)] #[table_name = "test_item"] pub struct TestItemDb { pub id: String, pub parent_id: String, p...
use actix::{Handler, Message, MessageResult}; use chrono; use diesel; use diesel::prelude::*; use serde_json; use uuid; use crate::db::schema::test_item; #[derive(Debug, Insertable, Queryable, Clone, Identifiable)] #[table_name = "test_item"] pub struct TestItemDb { pub id: String, pub parent_id: String, p...
} } impl Into<i32> for ResultCleanupStatus { fn into(self) -> i32 { self.as_i32() } } impl super::DbExecutor { fn find_test_item(&mut self, test_item_db: &TestItemDb) -> Option<TestItemDb> { use super::super::schema::test_item::dsl::*; test_item .filter(name.eq(&te...
match self { ResultCleanupStatus::WithData => 0, ResultCleanupStatus::Important => 1, ResultCleanupStatus::Shell => 2, ResultCleanupStatus::ToKeep => 3, }
if_condition
[ { "content": "pub fn get_environments(\n\n _req: &HttpRequest<AppState>,\n\n) -> Box<dyn Future<Item = HttpResponse, Error = errors::IkError>> {\n\n crate::DB_READ_EXECUTOR_POOL\n\n .send(crate::db::read::test::GetEnvironments)\n\n .from_err()\n\n .and_then(|res| Ok(HttpResponse::Ok()...
Rust
src/developer/ffx/plugins/target/snapshot/src/lib.rs
liexusong/fuchsia
81897680af92a1848a063e3c20ff3a4892ccff07
use { anyhow::{anyhow, bail, Context, Result}, chrono::{Datelike, Timelike, Utc}, ffx_core::ffx_plugin, ffx_snapshot_args::SnapshotCommand, fidl_fuchsia_feedback::{DataProviderProxy, GetSnapshotParameters}, fidl_fuchsia_io::{FileMarker, MAX_BUF}, std::convert::TryFrom, std::fs, std...
use { anyhow::{anyhow, bail, Context, Result}, chrono::{Datelike, Timelike, Utc}, ffx_core::ffx_plugin, ffx_snapshot_args::SnapshotCommand, fidl_fuchsia_feedback::{DataProviderProxy, GetSnapshotParameters}, fidl_fuchsia_io::{FileMarker, MAX_BUF}, std:
shot = data_provider_proxy .get_snapshot(params) .await .map_err(|e| anyhow!("Error: Could not get the snapshot from the target: {:?}", e))?; let data = read_data(&file_proxy).await?; let file_path = output_dir.join("snapshot.zip"); let mut file = fs::File::create(&file_p...
:convert::TryFrom, std::fs, std::io::prelude::*, std::path::{Path, PathBuf}, std::time::Duration, }; pub async fn read_data(file: &fidl_fuchsia_io::FileProxy) -> Result<Vec<u8>> { let mut out = Vec::new(); let (status, attrs) = file .get_attr() .await .context(format!("...
random
[]
Rust
src/control/acio.rs
Hummer12007/synapse
13699112122c6033d3dd027a5e2a08cc37678d93
use std::cell::RefCell; use std::rc::Rc; use std::time; use amy; use {disk, listener, rpc, torrent, tracker}; use CONFIG; use control::cio::{self, ErrorKind, Result, ResultExt}; use util::UHashMap; const POLL_INT_MS: usize = 1000; const PRUNE_GOAL: usize = 50; pub struct ACIO { data: Rc<RefCell<ACIOData>>, } p...
use std::cell::RefCell; use std::rc::Rc; use std::time; use amy; use {disk, listener, rpc, torrent, tracker}; use CONFIG; use control::cio::{self, ErrorKind, Result, ResultExt}; use util::UHashMap; const POLL_INT_MS: usize = 1000; const PRUNE_GOAL: usize = 50; pub struct ACIO { data: Rc<RefCell<ACIOData>>, } p...
self.events.push(cio::Event::Peer { peer: pid, event: Err(ErrorKind::Request.into()), }); } } }
if let Err(e) = self.reg.deregister(p.sock()) { error!("Failed to deregister sock: {:?}", e); }
if_condition
[ { "content": "pub fn peer_rpc_id(torrent: &[u8; 20], peer: u64) -> String {\n\n const PEER_ID: &'static [u8] = b\"PEER\";\n\n let mut idx = [0u8; 8];\n\n (&mut idx[..]).write_u64::<BigEndian>(peer).unwrap();\n\n\n\n let mut ctx = sha::Sha1::new();\n\n ctx.update(torrent);\n\n ctx.update(PEER_I...
Rust
postgrpc/src/transaction.rs
boilerplatter/postgrpc
28be4d12c4359b4d722f98997b6e7d54bec3e943
use crate::{ error_to_status, extensions, proto::transaction::{ transaction_server::Transaction as GrpcService, BeginResponse, CommitRequest, RollbackRequest, TransactionQueryRequest, }, protocol::{json, parameter}, }; use futures_util::{pin_mut, StreamExt, TryStreamExt}; use postgres_ro...
use crate::{ error_to_status, extensions, proto::transaction::{ transaction_server::Transaction as GrpcService, BeginResponse, CommitRequest, RollbackRequest, TransactionQueryRequest, }, protocol::{json, parameter}, }; use futures_util::{pin_mut, StreamExt, TryStreamExt}; use postgres_ro...
let rows = Transaction::query(self, id, role, &statement, &parameters) .await .map_err(transaction_error_to_status)? .map_ok(json::map::to_proto_struct) .map_err(error_to_status); let (transmitter, receiver) = tokio::sync::mpsc::channe...
if parameters.len() < value_count { return Err( Status::invalid_argument( "Invalid parameter values found. Only numbers, strings, boolean, and null values permitted" ) ); }
if_condition
[ { "content": "/// map default pool errors to proper gRPC statuses\n\nfn error_to_status(error: postgres_role_json_pool::Error) -> Status {\n\n let message = error.to_string();\n\n\n\n match error {\n\n postgres_role_json_pool::Error::Params { .. }\n\n | postgres_role_json_pool::Error::Role(....
Rust
src/catalog.rs
AlexKornitzer/consul-rust
8efb4533be579f31fde485609cefd26345582498
use std::collections::HashMap; use std::str::{self, FromStr}; use agent::{AgentCheck, AgentService}; use error::*; use request::{Method, Request}; use response::ResponseHelper; use {BlockingOptions, BlockingResponse, Client}; #[serde(default, rename_all = "PascalCase")] #[derive(Clone, Default, Serialize, Deserialize...
use std::collections::HashMap; use std::str::{self, FromStr}; use agent::{AgentCheck, AgentService}; use error::*; use request::{Method, Request}; use response::ResponseHelper; use {BlockingOptions, BlockingResponse, Client}; #[serde(default, rename_all = "PascalCase")] #[derive(Clone, Default, Serialize, Deserialize...
if let Some(options) = options { if let Some(tag) = &options.tag { params.insert(String::from("tag"), tag.to_string()); } if let Some(near) = &options.near { params.insert(String::from("near"), near.to_string()); } if l...
if let Some(dc) = options .and_then(|o| o.dc.as_ref()) .or_else(|| self.config.datacenter.as_ref()) { params.insert(String::from("dc"), dc.to_string()); }
if_condition
[ { "content": "type CheckWarnOptions = CheckOptions;\n", "file_path": "src/agent.rs", "rank": 2, "score": 71003.51290550447 }, { "content": "type CheckPassOptions = CheckOptions;\n", "file_path": "src/agent.rs", "rank": 3, "score": 71003.51290550447 }, { "content": "pub tr...
Rust
src/rtc0/sr3.rs
Colin-Suckow/ADuCM302x
f0d62f2b527184e1f192d4f2153f5827fd57fe3c
#[doc = "Reader of register SR3"] pub type R = crate::R<u16, super::SR3>; #[doc = "Writer for register SR3"] pub type W = crate::W<u16, super::SR3>; #[doc = "Register SR3 `reset()`'s with value 0"] impl crate::ResetValue for super::SR3 { type Type = u16; #[inline(always)] fn reset_value() -> Self::Type { ...
#[doc = "Reader of register SR3"] pub type R = crate::R<u16, super::SR3>; #[doc = "Writer for register SR3"] pub type W = crate::W<u16, super::SR3>; #[doc = "Register SR3 `reset()`'s with value 0"] impl crate::ResetValue for super::SR3 { type Type = u16; #[inline(always)] fn reset_value() -> Self::Type { ...
ys)] pub fn ic4irq(&mut self) -> IC4IRQ_W { IC4IRQ_W { w: self } } #[doc = "Bit 9 - Sticky Interrupt Source for SensorStrobe Channel 1"] #[inline(always)] pub fn ss1irq(&mut self) -> SS1IRQ_W { SS1IRQ_W { w: self } } }
t 9 - Sticky Interrupt Source for SensorStrobe Channel 1"] #[inline(always)] pub fn ss1irq(&self) -> SS1IRQ_R { SS1IRQ_R::new(((self.bits >> 9) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Sticky Interrupt Source for the RTC Input Capture Channel 0"] #[inline(always)] pub fn ic0irq(&mut s...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/bindings/web/server.rs
aleksanderwlodarczyk/torchbear
b97e699b4895a0626857317408b0c1ab42a08d1e
use std::collections::HashMap; use actix_lua::{LuaMessage}; use actix_web::{ http, AsyncResponder, FutureResponse, HttpResponse, HttpMessage, HttpRequest, }; use futures::Future; use serde_urlencoded; use serde_json; use crate::AppState; fn extract_table_from_request(request: &HttpRequest<AppState>, body: Str...
use std::collections::HashMap; use actix_lua::{LuaMessage}; use actix_web::{ http, AsyncResponder, FutureResponse, HttpResponse, HttpMessage, HttpRequest, }; use futures::Future; use serde_urlencoded; use serde_json; use crate::AppState; fn extract_table_from_request(request: &HttpRequest<AppState>, body: Str...
pub fn handler((request, body): (HttpRequest<AppState>, String)) -> FutureResponse<HttpResponse> { let table = extract_table_from_request(&request, body); let app_state = request.state(); let own_addr = if app_state.lua.is_none() { Some(app_state.create_addr()) } else { None }; let addr =...
function_block-full_function
[ { "content": "pub fn fs_open(_: &Lua, (path, mode): (String, Option<String>)) -> Result<LuaFile, LuaError> {\n\n let mut option = OpenOptions::new();\n\n if let Some(mode) = mode {\n\n match mode.as_ref() {\n\n \"r\" => option.read(true).write(false),\n\n \"w\" => option.creat...
Rust
src/encrypted_file.rs
dmitryvk/rs-credentials-manager
1c5b4a9a2b212c3bb1ee73615c02db247f9d2d79
extern crate crypto; use getrandom::getrandom; use self::crypto::scrypt::{scrypt, ScryptParams}; use self::crypto::aes::KeySize; use self::crypto::aes_gcm::AesGcm; use self::crypto::aead::{AeadEncryptor, AeadDecryptor}; use std::fs::File; use std::path::Path; use std::str; use std::io; use std::io::{Read,Write}; pub ...
extern crate crypto; use getrandom::getrandom; use self::crypto::scrypt::{scrypt, ScryptParams}; use self::crypto::aes::KeySize; use self::crypto::aes_gcm::AesGcm; use self::crypto::aead::{AeadEncryptor, AeadDecryptor}; use std::fs::File; use std::path::Path; use std::str; use std::io; use std::io::{Read,Write}; pub ...
_MAN_MAGIC.len() - 4 - 16 - 12 - 16]; read_bytes(&mut file, &mut magic)?; read_bytes(&mut file, &mut ver_bytes)?; read_bytes(&mut file, &mut salt)?; read_bytes(&mut file, &mut nonce)?; read_bytes(&mut file, &mut tag)?; read_bytes(&mut file, &mut ciphertext)?; if magic != CRED_MAN_MAGIC { ...
32) -> [u8; 4] { let v: [u8; 4] = [((x >> 24) & 0xFF) as u8, ((x >> 16) & 0xFF) as u8, ((x >> 8) & 0xFF) as u8, (x & 0xFF) as u8]; v } pub fn write_to_file<P: AsRef<Path>>(file_name: P, data: &EncryptedFileContent) -> io::Result<()> { let mut file = File::create(file_name)?; file.write_all(CRED_MAN_MA...
random
[ { "content": "#[derive(RustcDecodable, RustcEncodable, Debug)]\n\nstruct DbRecordDTO {\n\n key: String,\n\n timestamp: String,\n\n value: BTreeMap<String, String>,\n\n}\n\n\n\nconst DTO_TIME_FORMAT: &'static str = \"%Y-%m-%dT%H:%M:%S\";\n\n\n\n\n\n#[derive(Clone)]\n\npub enum DbLocation {\n\n DotLoc...
Rust
src/create.rs
nimrodshn/youki
6304a6dee418db6dc0d4eb6424b2d14c15f74e20
use std::fs; use std::path::{Path, PathBuf}; use std::process; use anyhow::{bail, Result}; use clap::Clap; use nix::sched; use nix::unistd; use nix::unistd::{Gid, Uid}; use crate::container::{Container, ContainerStatus}; use crate::namespaces::Namespaces; use crate::notify_socket::NotifyListener; use crate::process:...
use std::fs; use std::path::{Path, PathBuf}; use std::process; use anyhow::{bail, Result}; use clap::Clap; use nix::sched; use nix::unistd; use nix::unistd::{Gid, Uid}; use crate::container::{Container, ContainerStatus}; use crate::namespaces::Namespaces; use crate::notify_socket::NotifyListener; use crate::process:...
let linux = spec.linux.as_ref().unwrap(); let namespaces: Namespaces = linux.namespaces.clone().into(); let rootless = if should_use_rootless() { log::debug!("rootless container should be created"); log::warn!( "resource constraints and multi id mapping is unimplemented f...
, container, command, )?; if let Process::Parent(_) = process { process::exit(0); } Ok(()) } } fn run_container<P: AsRef<Path>>( pid_file: Option<P>, notify_socket: &mut NotifyListener, rootfs: PathBuf, s...
random
[ { "content": "pub fn prepare_rootfs(spec: &Spec, rootfs: &Path, bind_devices: bool) -> Result<()> {\n\n let mut flags = MsFlags::MS_REC;\n\n match spec.linux {\n\n Some(ref linux) => match linux.rootfs_propagation.as_ref() {\n\n \"shared\" => flags |= MsFlags::MS_SHARED,\n\n \...
Rust
rpc/src/endpoint/consensus_state.rs
DaviRain-Su/tendermint-rs
f0b307cb9e94f5a316bcdcdfc827383fc1ac810b
use crate::{Error, Method}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; use std::str::FromStr; use subtle_encoding::hex; use tendermint::block::{Height, Round}; use tendermint::{account, hash, vote, Hash, Time}; const NIL_VOTE_STR: &str = "nil-Vote"; #[derive(Clone, Debug, Default, ...
use crate::{Error, Method}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; use std::str::FromStr; use subtle_encoding::hex; use tendermint::block::{Height, Round}; use tendermint::{account, hash, vote, Hash, Time}; const NIL_VOTE_STR: &str = "nil-Vote"; #[derive(Clone, Debug, Default, ...
EST_VOTE_SUMMARIES: Vec<(String, VoteSummary, String)> = vec![ ( "Vote{0:000001E443FD 1262197/00/1(Prevote) 634ADAF1F402 7BB974E1BA40 @ 2019-08-01T11:52:35.513572509Z}".to_owned(), VoteSummary { validator_index: 0, validator_address_fin...
e, Serialize, Deserialize)] pub struct ValidatorInfo { pub address: account::Id, pub index: i32, } #[cfg(test)] mod test { use super::*; use lazy_static::lazy_static; lazy_static! { static ref T
random
[]
Rust
tab-command/src/service/terminal.rs
lnicola/tab-rs
6c16edad916412a834441e5921bc8d77e97dfd53
use std::{ io::Write, mem::discriminant, sync::atomic::{AtomicBool, Ordering}, }; use crate::state::{fuzzy::FuzzyEscapeState, terminal::TerminalMode}; use crate::bus::MainBus; use crate::prelude::*; use crate::{ bus::TerminalBus, message::terminal::{TerminalInput, TerminalOutput}, }; use echo_mo...
use std::{ io::Write, mem::discriminant, sync::atomic::{AtomicBool, Ordering}, }; use crate::state::{fuzzy::FuzzyEscapeState, terminal::TerminalMode}; use crate::bus::MainBus; use crate::prelude::*; use crate::{ bus::TerminalBus, message::terminal::{TerminalInput, TerminalOutput}, }; use echo_mo...
s = MainBus; type Lifeline = anyhow::Result<Self>; fn spawn(bus: &MainBus) -> Self::Lifeline { let terminal_bus = TerminalBus::default(); terminal_bus.capacity::<TerminalInput>(2048)?; terminal_bus.capacity::<TerminalOutput>(2048)?; let _main_terminal = terminal_bus.carry_from(...
reset commands"); RESET_ENABLED.store(false, Ordering::SeqCst); debug!("terminal state reset"); } } pub struct TerminalService { _main_terminal: MainTerminalCarrier, _terminal_mode: Lifeline, _terminal_event: TerminalEventService, } enum ServiceLifeline { Echo(TerminalEchoServic...
random
[ { "content": "/// Forwards the environment variables required by tab from the current process, to the child\n\n/// See FORWARD_ENV_VARS for a list and explanation of forwarded vars.\n\npub fn forward_env_std(child: &mut std::process::Command) {\n\n for var in crate::env::FORWARD_ENV_VARS.iter().copied() {\n\...
Rust
rust/src/murder_mystery/simulation.rs
corinnaj/mysterious-murder
5d616e53f5c56df6d790fe47ea2f34c206b68b2b
use rand_xorshift::XorShiftRng; use rand::prelude::*; use crate::murder_mystery::eval::*; use crate::murder_mystery::predicate::PredicateSignature; use crate::murder_mystery::mcts; use serde_json::{json, Value}; #[derive(Clone)] pub struct PredicateState<T: PredicateSignature> { pub predicates: Vec<T>, pub s...
use rand_xorshift::XorShiftRng; use rand::prelude::*; use crate::murder_mystery::eval::*; use crate::murder_mystery::predicate::PredicateSignature; use crate::murder_mystery::mcts; use serde_json::{json, Value}; #[derive(Clone)] pub struct PredicateState<T: PredicateSignature> { pub predicates: Vec<T>, pub s...
pub fn take_action(&mut self, evaluator: &Evaluator<T>, actor: usize, rule_instance: &RuleInstance<T>, registry: &mut <T as PredicateSignature>::Registry, rng: &mut impl Rng) { self.take_acti...
pub fn new(predicates: Vec<T>, n_actors: usize) -> PredicateState<T> { PredicateState { predicates: predicates, scores: (0..n_actors).map(|_| ActorState::new()).collect(), } }
function_block-full_function
[ { "content": "pub trait PredicateSignatureRegistry {\n\n fn store(&mut self, name: &String) -> usize;\n\n // FIXME: actually the wrong concrete type, need circular type reference\n\n fn get_name_string(&self, signature: &PredicateSignatureSmall) -> String;\n\n}\n\n\n\npub struct NoopRegistry {\n\n}\n\n...
Rust
benches/sharedring1.rs
diwic/shmem-ipc
c34988e7356c90a92959a3f43ba3baf7e8aaca2f
use std::time::Duration; use criterion::*; use shmem_ipc::sharedring::{Sender, Receiver}; fn setup_one<T: zerocopy::AsBytes + Copy + zerocopy::FromBytes>(chunks: usize) -> (Sender<T>, Receiver<T>) { let s: Sender<T> = Sender::new(chunks).unwrap(); let memfd = s.memfd().as_file().try_clone().unwrap(); let e...
use std::time::Duration; use criterion::*; use shmem_ipc::sharedring::{Sender, Receiver}; fn setup_one<T: zerocopy::AsBytes + Copy + zerocopy::FromBytes>(chunks: usize) -> (Sender<T>, Receiver<T>) { let s: Sender<T> = Sender::new(chunks).unwrap(); let memfd = s.memfd().as_file().try_clone().unwra
= Receiver::open(chunks, memfd, e, f).unwrap(); (s, r) } fn sum(x: &[u64]) -> u64 { let mut r = 0u64; for y in x { r = r.wrapping_add(*y) }; r } fn bench_one<M: measurement::Measurement>(c: &mut BenchmarkGroup<M>, init: &[u64]) { let (mut s, mut r) = setup_one::<u64>(2 * init.len()); let init...
p(); let e = s.empty_signal().try_clone().unwrap(); let f = s.full_signal().try_clone().unwrap(); let r: Receiver<T>
function_block-random_span
[ { "content": "/// Creates a memory map of a memfd. The memfd is sealed to be read only.\n\npub fn read_memfd(memfd: &mfd::Memfd) -> Result<mmap::Mmap, Error> {\n\n // The file can be truncated; no safe memory mapping.\n\n verify_seal(&memfd, mfd::FileSeal::SealShrink)?;\n\n // The file can be written t...
Rust
docs/build.rs
dten/sycamore
ef84e31d68a5ece98569d66f5c3f0115e78c6eff
use std::error::Error; use std::ffi::OsString; use std::fs; use std::path::{Path, PathBuf}; use std::str::FromStr; use pulldown_cmark::html::push_html; use pulldown_cmark::{CowStr, Event, Options, Parser, Tag}; use serde::Serialize; use walkdir::WalkDir; #[derive(Serialize)] struct MarkdownPage { html: String, ...
use std::error::Error; use std::ffi::OsString; use std::fs; use std::path::{Path, PathBuf}; use std::str::FromStr; use pulldown_cmark::html::push_html; use pulldown_cmark::{CowStr, Event, Options, Parser, Tag}; use serde::Serialize; use walkdir::WalkDir; #[derive(Serialize)] struct MarkdownPage { html: String, ...
fn main() -> Result<(), Box<dyn Error>> { println!("cargo:rerun-if-changed=next"); println!("cargo:rerun-if-changed=versioned_docs"); println!("cargo:rerun-if-changed=posts"); build_dir(Path::new("./next"), Path::new("docs"))?; build_dir(Path::new("./versioned_docs"), Path::new("docs"))?; bui...
fn build_dir(base: &Path, output: &Path) -> Result<(), Box<dyn Error>> { let out_dir = Path::new("../website/static"); for entry in WalkDir::new(base) { let entry = entry?; if entry.path().extension() == Some(&OsString::from_str("md").unwrap()) { let page = ...
function_block-function_prefix_line
[ { "content": "/// Abstraction over a rendering backend.\n\n///\n\n/// You would probably use this trait as a trait bound when you want to accept any rendering\n\n/// backend. For example, components are often generic over [`GenericNode`] to be able to render to\n\n/// different backends.\n\n///\n\n/// Note that...
Rust
core/tests/switch_account_tier_test.rs
lockbook/client
af76bea7c3b89850c4224f1aa59f2c4b5e07d942
use lockbook_core::service::api_service; use lockbook_core::service::api_service::ApiError; use lockbook_models::api::*; use lockbook_models::file_metadata::FileType; use rand::RngCore; use test_utils::*; #[test] fn switch_to_premium_and_back() { let core = test_core_with_account(); let account = core.get_acco...
use lockbook_core::service::api_service; use lockbook_core::service::api_service::ApiError; use lockbook_models::api::*; use lockbook_models::file_metadata::FileType; use rand::RngCore; use test_utils::*; #[test] fn switch_to_premium_and_back() { let core = test_core_with_account(); let account = core.get_acco...
ear, maybe_exp_month, maybe_cvc, ), }, ); match result { Err(ApiError::<SwitchAccountTierError>::Endpoint(err)) => { assert_eq!(err, expected_err) } other => panic!("expected {:?}, go...
account_tier: generate_premium_account_tier(test_credit_cards::GOOD, None, None, None), }, ) .unwrap(); api_service::request(&account, SwitchAccountTierRequest { account_tier: AccountTier::Free }) .unwrap(); } #[test] fn new_tier_is_old_tier() { let core = test_core_with_accoun...
random
[ { "content": "pub fn test_core_with_account() -> Core {\n\n let core = test_core();\n\n core.create_account(&random_name(), &url(), false).unwrap();\n\n core\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/lib.rs", "rank": 0, "score": 290124.39950850373 }, { "content": ...
Rust
relm4-examples/examples/components_old.rs
mmstick/Relm4
629a2e8274a6010668138a8b8d4f4a57d9ab8e6f
use gtk::prelude::{BoxExt, ButtonExt, GtkWindowExt, WidgetExt}; use relm4::{ gtk, AppUpdate, ComponentUpdate, Components, Model, RelmApp, RelmComponent, Sender, WidgetPlus, Widgets, }; struct Comp1Widgets { button: gtk::Button, } struct Comp2Widgets { button: gtk::Button, } struct Comp1Model { hi...
use gtk::prelude::{BoxExt, ButtonExt, GtkWindowExt, WidgetExt}; use relm4::{ gtk, AppUpdate, ComponentUpdate, Components, Model, RelmApp, RelmComponent, Sender, WidgetPlus, Widgets, }; struct Comp1Widgets { button: gtk::Button, } struct Comp2Widgets { button: gtk::Button, } struct Comp1Model { hi...
_button.connect_clicked(move |_button| { sender.send(AppMsg::Increment).unwrap(); }); dec_button.connect_clicked(move |_button| { sender2.send(AppMsg::Decrement).unwrap(); }); vbox.append(components.comp1.root_widget()); vbox.append(components.comp2.root...
de => { self.hidden = true; parent_sender.send(AppMsg::ShowComp2).unwrap(); } CompMsg::Show => { self.hidden = false; } } } } impl ComponentUpdate<AppModel> for Comp2Model { fn init_model(_parent_model:...
random
[ { "content": "struct AppModel {\n\n mode: AppMode,\n\n}\n\n\n\nimpl Model for AppModel {\n\n type Msg = AppMsg;\n\n type Widgets = AppWidgets;\n\n type Components = AppComponents;\n\n}\n\n\n\n#[relm4::widget]\n\nimpl Widgets<AppModel, ()> for AppWidgets {\n\n view! {\n\n main_window = gtk:...
Rust
shkdf/src/lib.rs
brycx/sHKDF
28cbb07b0e13436a8136edb62d52468535f60696
#![no_std] extern crate orion; extern crate rand; extern crate sha2; #[cfg(test)] pub mod tests; use orion::hazardous::hmac; use rand::{rngs::OsRng, RngCore}; use sha2::{default_sha512_salted, Sha512_salted}; pub struct HmacSha512 { buffer: [u8; 128], salt: [u8; 128], hasher: Sha512_salted, is_fin...
#![no_std] extern crate orion; extern crate rand; extern crate sha2; #[cfg(test)] pub mod tests; use orion::hazardous::hmac; use rand::{rngs::OsRng, RngCore}; use sha2::{default_sha512_salted, Sha512_salted}; pub struct HmacSha512 { buffer: [u8; 128], salt: [u8; 128], hasher: Sha512_salted, is_fin...
pub fn derive_key(salt: &[u8], ikm: &[u8], info: &[u8], okm_out: &mut [u8], special_salt: &[u8]) { let prk = shkdf_extract(salt, ikm); shkdf_expand(&prk, info, okm_out, special_salt); }
c = init(prk, &special_salt[idx * 128..(idx + 1) * 128]); if prev_switch { hmac.update(&prev_block); } hmac.update(info); hmac.update(&[idx as u8 + 1_u8]); hmac.finalize_with_dst(&mut hlen_block[..block_len]); if block_len < 64 || (block_len * (idx +...
function_block-function_prefixed
[ { "content": "pub fn compress512_with_salt(state: &mut [u64; 8], block: &Block, salt: &[u8]) {\n\n let mut block_u64 = [0u64; BLOCK_LEN];\n\n\n\n assert!(salt.len() == 128);\n\n assert!(block.len() == salt.len());\n\n\n\n let mut salted_block = [0u8; 128];\n\n\n\n for (idx, itm) in salted_block.i...
Rust
src/libos/crates/async-socket/src/io/receiver.rs
ShuochengWang/ngo
d437c98177450efe21f96e0393a71f3c743267fb
use std::mem::ManuallyDrop; #[cfg(feature = "sgx")] use std::prelude::v1::*; use std::ptr::{self, NonNull}; #[cfg(not(feature = "sgx"))] use std::sync::{Arc, Mutex, MutexGuard}; #[cfg(feature = "sgx")] use std::sync::{Arc, SgxMutex as Mutex, SgxMutexGuard as MutexGuard}; use io_uring_callback::{Fd, Handle}; #[cfg(feat...
use std::mem::ManuallyDrop; #[cfg(feature = "sgx")] use std::prelude::v1::*; use std::ptr::{self, NonNull}; #[cfg(not(feature = "sgx"))] use std::sync::{Arc, Mutex, MutexGuard}; #[cfg(feature = "sgx")] use std::sync::{Arc, SgxMutex as Mutex, SgxMutexGuard as MutexGuard}; use io_uring_callback::{Fd, Handle}; #[cfg(feat...
pub fn shutdown(&self) { let inner = self.inner.lock().unwrap(); unsafe { #[cfg(not(feature = "sgx"))] libc::shutdown(self.common.fd(), libc::SHUT_RD); #[cfg(feature = "sgx")] libc::ocall::shutdown(self.common.fd(), libc::SHUT_RD)...
receiver.common.pollee().add(Events::IN); }; let mut iovec_len = 1; let msg_param_ptr = *inner.msg_param; let mut msg_ptr = unsafe { &mut (*msg_param_ptr).msg as *mut libc::msghdr }; unsafe { inner.buf.with_producer_view(|part0, part1| { debu...
function_block-function_prefix_line
[ { "content": "pub fn do_getdents64(fd: FileDesc, buf: &mut [u8]) -> Result<usize> {\n\n getdents_common::<u8>(fd, buf)\n\n}\n\n\n", "file_path": "src/libos/src/fs/file_ops/dirent.rs", "rank": 0, "score": 327336.38622903265 }, { "content": "pub fn do_getdents(fd: FileDesc, buf: &mut [u8]) ...
Rust
src/domain/config.rs
ohke/sqsproxyd
3bd43d52e13dea36bcb71cf4e13a057e5d16085c
use anyhow::{anyhow, Result}; use http::Uri; use structopt::StructOpt; use url::Url; #[derive(Clone, Debug, PartialEq, StructOpt)] #[structopt(name = "sqsproxyd")] pub struct Config { #[structopt(long, env = "AWS_ACCESS_KEY_ID")] pub aws_access_key_id: Option<String>, #[structopt(long, env = "AWS_SECRET_AC...
use anyhow::{anyhow, Result}; use http::Uri; use structopt::StructOpt; use url::Url; #[derive(Clone, Debug, PartialEq, StructOpt)] #[structopt(name = "sqsproxyd")] pub struct Config { #[structopt(long, env = "AWS_ACCESS_KEY_ID")] pub aws_access_key_id: Option<String>, #[structopt(long, env = "AWS_SECRET_AC...
} #[cfg(test)] mod test { use super::*; use std::env; use std::str::FromStr; fn set_env_vars() { env::set_var("AWS_ACCESS_KEY_ID", "AWSACCESSKEY"); env::set_var("AWS_SECRET_ACCESS_KEY", "AWSSECRETACCESSKEY"); env::set_var("AWS_SESSION_TOKEN", "AWSSESSIONTOKEN"); env::s...
pub fn validate(&self) -> Result<()> { if self.aws_endpoint.is_some() && (self.aws_access_key_id.is_none() || self.aws_secret_access_key.is_none()) { return Err(anyhow!("If `--aws-endpoint` is set, `--aws-access-key-id` and `--aws-secret-access-key` should be set.")); } ...
function_block-full_function
[ { "content": "pub fn setup_logger(rust_log: &str) -> Result<()> {\n\n let filter = EnvFilter::from_str(rust_log)?;\n\n let subscriber = tracing_subscriber::fmt().with_env_filter(filter).finish();\n\n tracing::subscriber::set_global_default(subscriber)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/...
Rust
src/parser/parse/tokens.rs
vsaurabh04/nushell
97ef4aeca4831001a92d5b2eed6b6e17a8b00d0b
use crate::parser::Operator; use crate::prelude::*; use crate::Text; use std::fmt; use std::str::FromStr; #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum RawToken { Number(RawNumber), Operator(Operator), String(Span), Variable(Span), ExternalCommand(Span), ExternalW...
use crate::parser::Operator; use crate::prelude::*; use crate::Text; use std::fmt; use std::str::FromStr; #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum RawToken { Number(RawNumber), Operator(Operator), String(Span), Variable(Span), ExternalCommand(Span), ExternalW...
er::Decimal(BigDecimal::from_str(tag.slice(source)).unwrap()) } } } } pub type Token = Spanned<RawToken>; impl Token { pub fn debug<'a>(&self, source: &'a Text) -> DebugToken<'a> { DebugToken { node: *self, source, } } pub fn extract_number(...
anned<RawNumber> { let span = span.into(); RawNumber::Int(span).spanned(span) } pub fn decimal(span: impl Into<Span>) -> Spanned<RawNumber> { let span = span.into(); RawNumber::Decimal(span).spanned(span) } pub(crate) fn to_number(self, source: &Text) -> Number { ...
random
[ { "content": "pub fn per_item_command(command: impl PerItemCommand + 'static) -> Arc<Command> {\n\n Arc::new(Command::PerItem(Arc::new(command)))\n\n}\n", "file_path": "src/commands/command.rs", "rank": 0, "score": 354333.1636720072 }, { "content": "pub fn whole_stream_command(command: im...
Rust
examples/telnet.rs
ethcore/rotor
2a3764a830174aa94405593be550e8fc7ecea25a
extern crate nix; #[macro_use] extern crate rotor; extern crate argparse; extern crate void; use std::io::{Write, stderr, stdout}; use std::os::unix::io::FromRawFd; use void::{Void, unreachable}; use rotor::{EventSet, PollOpt}; use rotor::mio::deprecated::{TryRead, TryWrite}; use rotor::mio::tcp::{TcpStream}; use rot...
extern crate nix; #[macro_use] extern crate rotor; extern crate argparse; extern crate void; use std::io::{Write, stderr, stdout}; use std::os::unix::io::FromRawFd; use void::{Void, unreachable}; use rotor::{EventSet, PollOpt}; use rotor::mio::deprecated::{TryRead, TryWrite}; use rotor::mio::tcp::{TcpStream}; use rot...
let mut loop_creator = rotor::Loop::new(&rotor::Config::new()).unwrap(); let conn = TcpStream::connect( &format!("{}:{}", host, port).parse().unwrap()).unwrap(); let conn2 = conn.try_clone().unwrap(); fcntl(0, FcntlArg::F_SETFL(O_NONBLOCK)).expect("fcntl"); loop_creator.add...
function_block-function_prefix_line
[ { "content": "struct Context;\n\n\n", "file_path": "examples/tcp_echo_server.rs", "rank": 4, "score": 130333.67198800482 }, { "content": "fn main() {\n\n let mut loop_creator = Loop::new(&Config::new()).unwrap();\n\n let lst = TcpListener::bind(&\"127.0.0.1:3000\".parse().unwrap()).unw...
Rust
src/routes/license.rs
White-Green/Portfolio
3e200a147e44d49524235fae52b4c8b428305e67
use std::ops::Deref; use anyhow::Error; use once_cell::sync::OnceCell; use serde::Deserialize; use yew::format::Json; use yew::prelude::*; use yew::services::fetch::*; use yewtil::NeqAssign; use crate::routes::request; #[derive(Debug)] pub(crate) struct License { props: LicenseProperties, link...
use std::ops::Deref; use anyhow::Error; use once_cell::sync::OnceCell; use serde::
ec<LicenseData>), None, } #[derive(Debug, PartialEq, Clone, Deserialize)] pub(crate) struct LicenseData { name: String, version: Option<String>, authors: Option<String>, repository: Option<String>, license: Option<String>, description: Option<String>, } static CELL: OnceCell<...
Deserialize; use yew::format::Json; use yew::prelude::*; use yew::services::fetch::*; use yewtil::NeqAssign; use crate::routes::request; #[derive(Debug)] pub(crate) struct License { props: LicenseProperties, link: ComponentLink<Self>, task: Option<FetchTask>, } #[derive(Debug, Clone, Parti...
random
[ { "content": "use anyhow::Error;\n\nuse serde::Deserialize;\n\nuse yew::format::Json;\n\nuse yew::prelude::*;\n\nuse yew::services::fetch::*;\n\n\n\nuse crate::routes::request;\n\n\n\n#[derive(Clone, Debug)]\n", "file_path": "src/routes/profile.rs", "rank": 0, "score": 5.984814381596527 }, { ...
Rust
examples/admin.rs
async-telegram-bot/async-telegram-bot
ec1d41220c51872cf96e597072c63cdfe77c3521
use std::{error::Error, str::FromStr}; use chrono::Duration; use teloxide::{prelude::*, types::ChatPermissions, utils::command::BotCommands}; #[derive(BotCommands, Clone)] #[command( rename = "lowercase", description = "Use commands in format /%command% %num% %unit%", parse_with = "split" )] enum Command ...
use std::{error::Error, str::FromStr}; use chrono::Duration; use teloxide::{prelude::*, types::ChatPermissions, utils::command::BotCommands}; #[derive(BotCommands, Clone)] #[command( rename = "lowercase", description = "Use commands in format /%command% %num% %unit%", parse_with = "split" )] enum Command ...
fn calc_restrict_time(time: u64, unit: UnitOfTime) -> Duration { match unit { UnitOfTime::Hours => Duration::hours(time as i64), UnitOfTime::Minutes => Duration::minutes(time as i64), UnitOfTime::Seconds => Duration::seconds(time as i64), } }
t?; } None => { bot.send_message(msg.chat.id, "Use this command in a reply to another message!") .await?; } } Ok(()) }
function_block-function_prefixed
[ { "content": "// Calculates time of user restriction.\n\nfn calc_restrict_time(time: u64, unit: UnitOfTime) -> Duration {\n\n // FIXME: actually handle the case of too big integers correctly, instead of\n\n // unwrapping\n\n match unit {\n\n UnitOfTime::Hours => Duration::try_hours(time as i64)....
Rust
src/libproc/pid_rusage.rs
andrewdavidmackenzie/libproc-rs
3bd54d7296b3390e588486b60e287a4eb1e3f4a1
extern crate libc; #[cfg(target_os = "macos")] use crate::libproc::helpers; #[cfg(target_os = "macos")] use self::libc::{c_void, c_int}; #[cfg(target_os = "linux")] use crate::libproc::helpers::{procfile_field, parse_memory_string}; pub trait PIDRUsage: Default { fn flavor() -> PidRUsageFlavor; fn...
extern crate libc; #[cfg(target_os = "macos")] use crate::libproc::helpers; #[cfg(target_os = "macos")] use self::libc::{c_void, c_int}; #[cfg(target_os = "linux")] use crate::libproc::helpers::{procfile_field, parse_memory_string}; pub trait PIDRUsage: Default { fn flavor() -> PidRUsageFlavor; fn...
#[cfg(target_os = "linux")] pub fn pidrusage<T: PIDRUsage>(pid : i32) -> Result<T, String> { let mut pidrusage = T::default(); let vm_size = procfile_field(&format!("/proc/{}/status", pid), "VmSize")?; pidrusage.set_memory_used(parse_memory_string(&vm_size)?); Ok(pidrusage) } #[cfg(test)] mod test ...
2) -> Result<T, String> { let flavor = T::flavor() as i32; let mut pidrusage = T::default(); let buffer_ptr = &mut pidrusage as *mut _ as *mut c_void; let ret: i32; unsafe { ret = proc_pid_rusage(pid, flavor, buffer_ptr); }; if ret < 0 { Err(helpers::get_errno_with_message(...
function_block-function_prefixed
[ { "content": "/// The `PIDInfo` trait is needed for polymorphism on pidinfo types, also abstracting flavor in order to provide\n\n/// type-guaranteed flavor correctness\n\npub trait PIDInfo: Default {\n\n /// Return the `PidInfoFlavor` of the implementing struct\n\n fn flavor() -> PidInfoFlavor;\n\n}\n\n\...
Rust
src/build/dep_tree.rs
shritesh/gleam
6f8bb29f662e9c83bd44983f52531ec513ca5018
use crate::error::GleamExpect; use petgraph::{algo::Cycle, graph::NodeIndex, Direction}; use std::collections::{HashMap, HashSet}; use std::hash::Hash; #[derive(Debug, Default)] pub struct DependencyTree<T> { graph: petgraph::Graph<T, ()>, indexes: HashMap<T, NodeIndex>, values: HashMap<NodeIndex, T>, } p...
use crate::error::GleamExpect; use petgraph::{algo::Cycle, graph::NodeIndex, Direction}; use std::collections::{HashMap, HashSet}; use std::hash::Hash; #[derive(Debug, Default)] pub struct DependencyTree<T> { graph: petgraph::Graph<T, ()>, indexes: HashMap<T, NodeIndex>, values: HashMap<NodeIndex, T>, } p...
; return true; } } false } #[test] fn toposort_deps_test() { assert_eq!( toposort_deps(vec![ ("a".to_string(), vec!["b".to_string()]), ("c".to_string(), vec![]), ("b".to_string(), vec!["c".to_string()]) ]), Ok(vec![ ...
(parent, Direction::Outgoing) { if node == origin { path.push(node); return true; } if seen.contains(&node) { continue; } if find_cycle(origin, node, graph, path, seen) { path.push(node)
function_block-random_span
[ { "content": "pub fn run(stdin: bool, check: bool, files: Vec<String>) -> Result<(), Error> {\n\n let formatted = if stdin {\n\n vec![read_and_format_stdin()?]\n\n } else {\n\n read_and_format_paths(files)?\n\n };\n\n if check {\n\n check_formatting(formatted)\n\n } else {\n\...
Rust
src/storage/stress-tests/blobfs/environment.rs
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
use { crate::{ blob_actor::BlobActor, deletion_actor::DeletionActor, instance_actor::InstanceActor, read_actor::ReadActor, Args, BLOBFS_MOUNT_PATH, }, async_trait::async_trait, fidl_fuchsia_hardware_block_partition::Guid, fidl_fuchsia_io as fio, fs_management::Blobfs, fuchs...
use { crate::{ blob_actor::BlobActor, deletion_actor::DeletionActor, instance_actor::InstanceActor, read_actor::ReadActor, Args, BLOBFS_MOUNT_PATH, }, async_trait::async_trait, fidl_fuchsia_hardware_block_partition::Guid, fidl_fuchsia_io as fio, fs_management::Blobfs, fuchs...
let root_dir = open_blobfs_root(); Arc::new(Mutex::new(BlobActor::new(factory, root_dir))) }; let large_blob_actor = { let rng = SmallRng::from_seed(rng.gen()); let uncompressed_size = UncompressedSize::Exact(2 * disk_size); let compressibility = Compress...
rng = SmallRng::from_seed(rng.gen()); let uncompressed_size = UncompressedSize::InRange(ONE_MIB, FOUR_MIB); let compressibility = Compressibility::Compressible; let factory = FileFactory::new(rng, uncompressed_size, compressibility);
random
[]
Rust
crates/lib3h/src/transport/transport_multiplex/mplex.rs
Connoropolous/lib3h
4ec1578101fdf646eb092f6a414d8955b75a1542
use crate::{ error::{Lib3hError, Lib3hResult}, gateway::protocol::*, transport::{error::*, protocol::*}, }; use detach::prelude::*; use holochain_tracing::Span; use lib3h_ghost_actor::prelude::*; use lib3h_protocol::{data_types::Opaque, types::SpaceHash, uri::Lib3hUri, Address}; use std::collections::HashMa...
use crate::{ error::{Lib3hError, Lib3hResult}, gateway::protocol::*, transport::{error::*, protocol::*}, }; use detach::prelude::*; use holochain_tracing::Span; use lib3h_ghost_actor::prelude::*; use lib3h_protocol::{data_types::Opaque, types::SpaceHash, uri::Lib3hUri, Address}; use std::collections::HashMa...
pub fn remove_agent_space_route( &mut self, space_address: &SpaceHash, local_agent_id: &Address, ) -> Option<TransportActorSelfEndpoint<TransportMultiplex<G>>> { let route_spec = LocalRouteSpec { space_address: space_address.clone(), local_agent_id:...
pub fn create_agent_space_route( &mut self, space_address: &SpaceHash, local_agent_id: &Address, ) -> TransportActorParentEndpoint { let (endpoint_parent, endpoint_self) = create_ghost_channel(); let endpoint_self = endpoint_self .as_context_endpoint_builder() ...
function_block-full_function
[ { "content": "/// Calculate a password hash\n\n///\n\n/// @param {SecBuf} password - the password to hash\n\n///\n\n/// @param {u64} opslimit - operation scaling for hashing algorithm\n\n///\n\n/// @param {usize} memlimit - memory scaling for hashing algorithm\n\n///\n\n/// @param {i8} algorithm - which hashing...
Rust
examples/batch_fem.rs
rodrigo-romano/dos-actors
4ac802701a47617e7e77f9af2d851ef48249effb
use dos_actors::clients::mount::{Mount, MountEncoders, MountTorques}; use dos_actors::{ clients::{ arrow_client::Arrow, windloads, windloads::{WindLoads::*, CS}, }, prelude::*, }; use fem::{ dos::{DiscreteModalSolver, Exponential, ExponentialMatrix}, fem_io::*, FEM, }; us...
use dos_actors::clients::mount::{Mount, MountEncoders, MountTorques}; use dos_actors::{ clients::{ arrow_client::Arrow, windloads, windloads::{WindLoads::*, CS}, }, prelude::*, }; use fem::{ dos::{DiscreteMod
var("FEM_REPO")?; let fem_name = Path::new(&fem_env) .file_name() .and_then(|x| x.to_str()) .unwrap(); for cfd_case in cfd::Baseline::<2021>::default().into_iter() { println!("CFD CASE ({}Hz): {}", cfd_sampling_frequency, cfd_case); let cfd_path = cfd::Baseline::<2021>::...
alSolver, Exponential, ExponentialMatrix}, fem_io::*, FEM, }; use parse_monitors::cfd; use std::{env, fs::create_dir, path::Path}; #[tokio::main] async fn main() -> anyhow::Result<()> { let sim_sampling_frequency = 1000_usize; let sim_duration = 400; const CFD_RATE: usize = 1; let cfd_sampling_...
random
[ { "content": " \"Cring_strL\",\n\n \"Cring_strR\",\n\n \"Cring_strF\",\n\n \"Cring_strB\",\n\n ]\n\n .into_iter()\n\n .map(|x| x.into())\n\n .collect(),\n\n GIR => vec![\"GIR\".into()],\n\n ...
Rust
src/main.rs
AOSC-Dev/systemd-boot-friend-rs
30110ce30f7b3da55e628bb2d8f8b0c4a71d4e5c
use anyhow::{anyhow, bail, Result}; use clap::Parser; use cli::{Opts, SubCommands}; use core::default::Default; use dialoguer::{theme::ColorfulTheme, Select}; use regex::Regex; use serde::{Deserialize, Serialize}; use std::{ fs, path::PathBuf, process::{Command, Stdio}, }; use i18n::I18N_LOADER; use kernel...
use anyhow::{anyhow, bail, Result}; use clap::Parser; use cli::{Opts, SubCommands}; use core::default::Default; use dialoguer::{theme::ColorfulTheme, Select}; use regex::Regex; use serde::{Deserialize, Serialize}; use std::{ fs, path::PathBuf, process::{Command, Stdio}, }; use i18n::I18N_LOADER; use kernel...
} } SubCommands::Install(args) => { let kernel = match args.target { Some(n) => parse_num_or_filename(&config, &n, &kernels)?, None => kernels ...
installed_kernels.push(Kernel::parse(config, version)?); } } } Ok(installed_kernels) } fn choose_kernel(kernels: &[Kernel]) -> Result<Kernel> { if kernels.is_empty() { bail!(fl!("empty_list")); } let n = Select::with_theme(&ColorfulTheme::default()) .item...
random
[ { "content": "pub fn parse_kernel_name(kernel_name: &str) -> Result<(Version, String)> {\n\n if let Some(cap) = KERNEL_REGEX.captures(kernel_name) {\n\n let version = Version {\n\n // These are safe because I'm good\n\n major: cap.name(\"major\").unwrap().as_str().parse()?,\n\n ...
Rust
noodles-bam/src/record/sequence.rs
jianshu93/noodles
4e39a772b2dd907faf85fa3892abba2bd714a05f
mod base; mod bases; pub use self::{base::Base, bases::Bases}; use std::fmt; use noodles_sam as sam; static BASES: &[Base] = &[ Base::Eq, Base::A, Base::C, Base::M, Base::G, Base::R, Base::S, Base::V, Base::T, Base::W, Base::Y, Base::H, Base::K, Base::D, ...
mod base; mod bases; pub use self::{base::Base, bases::Bases}; use std::fmt; use noodles_sam as sam; static BASES: &[Base] = &[ Base::Eq, Base::A, Base::C, Base::M, Base::G, Base::R, Base::S, Base::V, Base::T, Base::W, Base::Y, Base::H, Base::K, Base::D, ...
#[test] fn test_bases() { let sequence = Sequence::new(vec![0x18, 0x42], 4); let mut bases = sequence.bases(); assert_eq!(bases.next(), Some(Base::A)); assert_eq!(bases.next(), Some(Base::T)); assert_eq!(bases.next(), Some(Base::G)); assert_eq!(bases.next(), ...
0), Some(&Base::A)); assert_eq!(sequence.get(1), Some(&Base::T)); assert_eq!(sequence.get(2), Some(&Base::G)); assert_eq!(sequence.get(3), None); assert_eq!(sequence.get(8), None); }
function_block-function_prefixed
[ { "content": "pub fn read_record<R>(reader: &mut R, buf: &mut Vec<u8>, record: &mut Record) -> io::Result<usize>\n\nwhere\n\n R: Read,\n\n{\n\n let l_shared = match reader.read_u32::<LittleEndian>() {\n\n Ok(n) => usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,\n\n ...
Rust
rs/crypto/internal/crypto_lib/threshold_sig/bls12_381/src/types/polynomial/ops/tests.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
use super::*; use crate::types::public_coefficients::tests::uints_to_polynomial; use ic_crypto_internal_bls12381_common::test_utils::uint_to_fr; #[test] fn test_polynomial_sum() { let test_vectors: Vec<(Vec<Vec<u32>>, Vec<u32>, String)> = vec![ ( vec![], vec![], "Summi...
use super::*; use crate::types::public_coefficients::tests::uints_to_polynomial; use ic_crypto_internal_bls12381_common::test_utils::uint_to_fr; #[test] fn test_polynomial_sum() { let test_vectors: Vec<(Vec<Vec<u32>>, Vec<u32>, String)> = vec![ ( vec![], vec![], "Summi...
#[test] fn test_polynomial_add() { for test_vector in addition_test_vectors() { let value = uints_to_polynomial(&test_vector.value) + &uints_to_polynomial(&test_vector.addend); let expected = uints_to_polynomial(&test_vector.sum); assert_eq!(expected, value, "Test vector failed...
5], sum: vec![5, 7, 3], name: "Adding a polynomial of lesser order".to_string(), }, ] }
function_block-function_prefixed
[]
Rust
crates/oauth2-types/src/errors.rs
matrix-org/matrix-authentication-service
0c2950a160e4a831c4d18047412d007df06909ec
use http::status::StatusCode; use serde::ser::{Serialize, SerializeMap}; use url::Url; pub trait OAuth2Error: std::fmt::Debug + Send + Sync { fn error(&self) -> &'static str; fn description(&self) -> Option<String> { None } fn...
use http::status::StatusCode; use serde::ser::{Serialize, SerializeMap}; use url::Url; pub trait OAuth2Error: std::fmt::Debug + Send + Sync { fn error(&self) -> &'static str; fn description(&self) -> Option<String> { None } fn...
de: BAD_REQUEST, "unauthorized_client" => "The client is not authorized to request an access token using this method." } oauth2_error! { UnsupportedGrantType, code: BAD_REQUEST, "unsupported_grant_type" => "The authorization grant type is not supported by the aut...
ise malformed." } oauth2_error! { InvalidClient, code: BAD_REQUEST, "invalid_client" => "Client authentication failed." } oauth2_error! { InvalidGrant, code: BAD_REQUEST, "invalid_grant" } oauth2_error! { UnauthorizedClient, ...
random
[ { "content": "pub trait HtmlError: Debug + Send + Sync + 'static {\n\n fn html_display(&self) -> String;\n\n}\n\n\n", "file_path": "crates/data-model/src/errors.rs", "rank": 0, "score": 395510.23219497415 }, { "content": "#[async_trait::async_trait]\n\npub trait Task: std::fmt::Debug + Se...
Rust
src/auto/enumerator.rs
bilelmoussaoui/gudev-rs
70d2d736e1ee67de3f8fad825510b6df48745a6d
use crate::Client; use crate::Device; use glib::object::IsA; use glib::translate::*; use glib::StaticType; use std::fmt; glib::wrapper! { #[doc(alias = "GUdevEnumerator")] pub struct Enumerator(Object<ffi::GUdevEnumerator, ffi::GUdevEnumeratorClass>); match fn { type_ => || ffi::g_udev_enumerato...
use crate::Client; use crate::Device; use glib::object::IsA; use glib::translate::*; use glib::StaticType; use std::fmt; glib::wrapper! { #[doc(alias = "GUdevEnumerator")] pub struct Enumerator(Object<ffi::GUdevEnumerator, ffi::GUdevEnumeratorClass>); match fn { type_ => || ffi::g_udev_enumerato...
} impl fmt::Display for Enumerator { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("Enumerator") } }
fn client(&self) -> Option<Client> { unsafe { let mut value = glib::Value::from_type(<Client as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"client\0".as_ptr() as *const _, value.to_glib_none_mut().0); ...
function_block-full_function
[]
Rust
src/main.rs
bboreham/vector
92277fbfae7a1873a35ea75a725e9b71e963a0d5
#[macro_use] extern crate tracing; use futures::{future, Future, Stream}; use std::{ cmp::{max, min}, fs::File, net::SocketAddr, path::{Path, PathBuf}, }; use structopt::StructOpt; use tokio_signal::unix::{Signal, SIGHUP, SIGINT, SIGQUIT, SIGTERM}; use trace_metrics::MetricsSubscriber; use tracing::{fi...
#[macro_use] extern crate tracing; use futures::{future, Future, Stream}; use std::{ cmp::{max, min}, fs::File, net::SocketAddr, path::{Path, PathBuf}, }; use structopt::StructOpt; use tokio_signal::unix::{Signal, SIGHUP, SIGINT, SIGQUIT, SIGTERM}; use trace_metrics::MetricsSubscriber; use tracing::{fi...
trace!( message = "Parsing config.", path = field::debug(&opts.config_path) ); let config = vector::topology::Config::load(file); let mut rt = { let mut builder = tokio::runtime::Builder::new(); let threads = opts.threads.unwrap_or(max...
let file = if let Some(file) = open_config(&opts.config_path) { file } else { std::process::exit(1); };
assignment_statement
[ { "content": "// Modified version of Kahn's topological sort algorithm that ignores the actual sorted output and\n\n// only cares if the sort was possible (i.e. whether or not there was a cycle in the input graph).\n\npub fn contains_cycle(config: &Config) -> bool {\n\n let nodes = config\n\n .sources...
Rust
state-fold/tests/access_test.rs
cartesi/state-fold
d58f8a7fec9a942bc1bf872c2ccea5bea33d8923
mod common; use common::*; use ethers::{ contract::Contract, providers::Middleware, types::{Address, H256, U256, U64}, }; use std::sync::Arc; use state_fold::{utils, Access, FoldAccess, SyncAccess}; #[tokio::test] async fn fold_query_test() { let (_handle, provider) = new_geth().await; let genesi...
mod common; use common::*; use ethers::{ contract::Contract, providers::Middleware, types::{Address, H256, U256, U64}, }; use std::sync::Arc; use state_fold::{utils, Access, FoldAccess, SyncAccess}; #[tokio::test] async fn fold_query_test() { let (_handle, provider) = new_geth().await; let genesi...
async fn set_value_get_hash<M: Middleware + Clone>( provider: &Arc<M>, contract: &Contract<M>, value: &str, ) -> H256 { contract .connect(provider.clone()) .method::<_, H256>("setValue", value.to_owned()) .unwrap() .send() .await .unwrap() .await...
contract: &Contract<M>, value: &str, ) -> U64 { contract .connect(provider.clone()) .method::<_, H256>("setValue", value.to_owned()) .unwrap() .send() .await .unwrap() .await .unwrap() .unwrap() .block_number .unwrap() }
function_block-function_prefix_line
[ { "content": "fn sort_logs<M: Middleware>(logs: &mut Vec<Log>) -> Result<(), M> {\n\n for log in logs.iter() {\n\n if !(log.block_number.is_some() && log.log_index.is_some()) {\n\n return LogUnavailable {}.fail();\n\n }\n\n }\n\n\n\n logs.sort_by(|a, b| {\n\n let c = a.b...
Rust
src/context.rs
newAM/rusb
04bcd20b63475abace0978cdda3cde6803ab2823
use libc::{c_int, timeval}; use std::{mem, ptr, sync::Arc, sync::Once, time::Duration}; #[cfg(unix)] use std::os::unix::io::RawFd; use crate::hotplug::{Hotplug, HotplugBuilder, Registration}; use crate::{device_handle::DeviceHandle, device_list::DeviceList, error}; use libusb1_sys::{constants::*, *}; #[cfg(windows)...
use libc::{c_int, timeval}; use std::{mem, ptr, sync::Arc, sync::Once, time::Duration}; #[cfg(unix)] use std::os::unix::io::RawFd; use crate::hotplug::{Hotplug, HotplugBuilder, Registration}; use crate::{device_handle::DeviceHandle, device_list::DeviceList, error}; use libusb1_sys::{constants::*, *}; #[cfg(windows)...
ntextInner { inner: ptr::NonNull::new_unchecked(context.assume_init()), }) }, }) } pub fn with_options(opts: &[crate::UsbOption]) -> crate::Result<Self> { let mut this = Self::new()?; for opt in opts { opt.apply(&mut this...
safe { match timeout { Some(t) => { let tv = timeval { tv_sec: t.as_secs() as Seconds, tv_usec: t.subsec_nanos() as MicroSeconds / 1000, }; libusb_handle_events_timeout_completed(self....
random
[ { "content": "/// When handling a [method@Hotplug::device_arrived] event it is considered safe to call\n\n/// any `rusb` function that takes a [`Device`]. It also safe to open a device and\n\n/// submit **asynchronous** transfers.\n\n/// However, most other functions that take a [`DeviceHandle`] are **not safe*...
Rust
llmalloc-core/src/internals/blocks/block_local.rs
matthieu-m/llmalloc
42b5972bd0568e6c2eeedb0ef61b8e6a0ebc1c06
use core::{ mem, ptr::{self, NonNull}, }; use crate::{PowerOf2, utils}; use super::{AtomicBlockForeign, AtomicBlockForeignList, BlockForeign, BlockForeignList, BlockPtr}; #[repr(C)] #[derive(Default)] pub(crate) struct BlockLocal { next: BlockLocalStack, } impl BlockLocal { ...
use core::{ mem, ptr::{self, NonNull}, }; use crate::{PowerOf2, utils}; use super::{AtomicBlockForeign, AtomicBlockForeignList, BlockForeign, BlockForeignList, BlockPtr}; #[repr(C)] #[derive(Default)] pub(crate) struct BlockLocal { next: BlockLocalStack, } impl BlockLocal { ...
#[test] fn block_local_stack_pop_push() { let array = AlignedArray::<BlockLocal>::default(); let (a, b) = (array.get(1), array.get(2)); let stack = BlockLocalStack::default(); assert_eq!(None, stack.peek()); assert_eq!(None, stack.pop()); stack.push(a); assert_eq!(Some(a), stack.peek())...
fn block_local_stack_peek() { let array = AlignedArray::<BlockLocal>::default(); let block = array.get(1); let stack = BlockLocalStack::new(None); assert_eq!(None, stack.peek()); let stack = BlockLocalStack::new(Some(block)); assert_eq!(Some(block), stack.peek()); }
function_block-full_function
[ { "content": "fn create_list(array: &AlignedArray<BlockForeign>, range: Range<usize>) -> BlockForeignList {\n\n let list = BlockForeignList::default();\n\n\n\n for index in range.rev() {\n\n list.push(array.get(index));\n\n }\n\n\n\n list\n\n}\n\n\n", "file_path": "llmalloc-core/src/inter...
Rust
collector-v2/src/contract.rs
dreamer-zq/wasm-cotranct-example
b00906f9dd1c9c3899a230d128e6da8356e70c9b
use cosmwasm_std::{ entry_point, to_binary, Binary, Deps, DepsMut, Env, HandleResponse, InitResponse, MessageInfo, MigrateResponse, StdResult, }; use crate::error::ContractError; use crate::msg::{ HandleMsg, InitMsg, MigrateMsg, QueryCallersResponse, QueryMsg, QueryVersionResponse, }; use crate::state::{co...
use cosmwasm_std::{ entry_point, to_binary, Binary, Deps, DepsMut, Env, HandleResponse, InitResponse, MessageInfo, MigrateResponse, StdResult, }; use crate::error::ContractError; use crate::msg::{ HandleMsg, InitMsg, MigrateMsg, QueryCallersResponse, QueryMsg, QueryVersionResponse, }; use crate::state::{co...
g(test)] mod tests { use super::*; use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{coins, from_binary}; #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = InitMsg {}; let info = mock_info("creator", ...
} #[entry_point] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::GetCallers {} => to_binary(&query_count(deps)?), QueryMsg::GetVersion {} => to_binary(&query_version()?), } } #[entry_point] pub fn migrate( _deps: DepsMut, _env: Env, _...
random
[ { "content": "pub fn query(deps: Deps, _env: Env, _msg: QueryMsg) -> StdResult<Binary> {\n\n to_binary(&query_count(deps)?)\n\n}\n\n\n", "file_path": "register/src/contract.rs", "rank": 0, "score": 273331.44144313707 }, { "content": "pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> S...
Rust
src/bit_reader.rs
mcuelenaere/quantile-compression
10e3b22c2fcd2b61695783c0bea98b54a6c4204f
use std::fmt::{Debug, Formatter}; use std::fmt; use crate::bits; use crate::bits::{LEFT_MASKS, RIGHT_MASKS}; use crate::constants::{PREFIX_TABLE_SIZE_LOG, BITS_TO_ENCODE_N_ENTRIES}; use crate::errors::{QCompressError, QCompressResult}; use crate::data_types::UnsignedLike; #[derive(Clone)] pub struct BitReader { byt...
use std::fmt::{Debug, Formatter}; use std::fmt; use crate::bits; use crate::bits::{LEFT_MASKS, RIGHT_MASKS}; use crate::constants::{PREFIX_TABLE_SIZE_LOG, BITS_TO_ENCODE_N_ENTRIES}; use crate::errors::{QCompressError, QCompressResult}; use crate::data_types::UnsignedLike; #[derive(Clone)] pub struct BitReader { byt...
as usize; for i in jumpstart..BITS_TO_ENCODE_N_ENTRIES { if self.unchecked_read_one() { if self.unchecked_read_one() { res |= 1 << i } } else { break; } } res } pub(crate) fn drain_empty_byte<F>(&mut self, f: F) -> QCompressResult<()> wher...
for BitReader { fn from(bytes: Vec<u8>) -> BitReader { let total_bits = 8 * bytes.len(); BitReader { bytes, i: 0, j: 0, total_bits, } } } impl BitReader { pub fn aligned_byte_ind(&self) -> QCompressResult<usize> { if self.j == 0 { Ok(self.i) } else if se...
random
[ { "content": "pub fn bit_from_byte(byte: u8, j: usize) -> bool {\n\n (byte & BIT_MASKS[j]) > 0\n\n}\n\n\n", "file_path": "src/bits.rs", "rank": 0, "score": 187142.14800772583 }, { "content": "pub fn bits_to_usize(bits: &[bool]) -> usize {\n\n bits_to_usize_truncated(bits, bits.len())\n\n}\...
Rust
src/model/values.rs
johnstonskj/rust-code_writer
84d7f17d599ca29e34d55be55c88363000b0c134
/*! One-line description. More detailed description, with # Example */ use crate::model::comments::HasDocumentation; use crate::model::identity::{HasName, Identifier}; use crate::model::modules::{HasVisibility, Visibility}; use crate::model::properties::{HasProperties, Property}; use crate::model::Builder; use std:...
/*! One-line description. More detailed description, with # Example */ use crate::model::comments::HasDocumentation; use crate::model::identity::{HasName, Identifier}; use crate::model::modules::{HasVisibility, Visibility}; use crate::model::properties::{HasProperties, Property}; use crate::model::Builder; use std:...
} } impl_has_properties!(NamedValue); impl_has_visibility!(NamedValue); impl_has_name!(NamedValue); impl_has_documentation!(NamedValue); impl_has_type!(NamedValue); impl_has_value!(NamedValue); impl Builder for NamedValue {} impl NamedValue { pub fn new(name: Identifier, value_type: ValueType, value: V...
match self { Value::I8(_) => Some(ValueType::Known(KnownType::I8)), Value::U8(_) => Some(ValueType::Known(KnownType::U8)), Value::I16(_) => Some(ValueType::Known(KnownType::I16)), Value::U16(_) => Some(ValueType::Known(KnownType::U16)), Value::I32(_) => Some(...
if_condition
[ { "content": "fn value_str(value: &Value) -> String {\n\n match value {\n\n Value::I8(v) => v.to_string(),\n\n Value::U8(v) => v.to_string(),\n\n Value::I16(v) => v.to_string(),\n\n Value::U16(v) => v.to_string(),\n\n Value::I32(v) => v.to_string(),\n\n Value::U32(v)...
Rust
playground/src/main.rs
xeuus/rustbite
e62b1a5b3e09991a1f29aecb24e831b0f31041c7
#![allow(non_camel_case_types)] extern crate rustbite; extern crate gl; use rustbite::{vec3, mat4, quat, app, shader, math}; use std::rc::Rc; use std::cell::RefCell; use std::mem; use std::ptr; fn main() { let mut model = Rc::new(RefCell::new(mat4::identify(1.0))); let mut view = Rc::new(RefCell::new(mat4:...
#![allow(non_camel_case_types)] extern crate rustbite; extern crate gl; use rustbite::{vec3, mat4, quat, app, shader, math}; use std::rc::Rc; use std::cell::RefCell; use std::mem; use std::ptr;
/* let nw = time::now().tm_nsec; for i in 0..5000{ let m = mat4::create_trs(vec3::zero(), quat::identify(), vec3::one()); let mut m2= mat4::inverse(m); m2 = m2 * m; m2 = m2 * m; m2 = m2 * m; m2 = m2 * m; m2 = mat4::create_trs(vec3::zero(), quat::id...
fn main() { let mut model = Rc::new(RefCell::new(mat4::identify(1.0))); let mut view = Rc::new(RefCell::new(mat4::create_trs(vec3::zero(), quat::identify(), vec3::one()))); let mut projection = Rc::new(RefCell::new(mat4::ortho_window(1.0, 1.0, -0.1, 200.0))); let mut i = Rc::new(RefCell::new(0.0_...
function_block-full_function
[ { "content": " unsafe {\n\n let vs = gl::CreateShader(gl::VERTEX_SHADER);\n\n gl::ShaderSource(vs, 1, [self.vertex_shader.as_ptr() as *const _].as_ptr(), std::ptr::null());\n\n gl::CompileShader(vs);\n\n\n\n let fs = gl::CreateShader(gl::FRAGMENT_SHADER);\n\n ...
Rust
blobstore/rust/src/generated.rs
wasmCloud/actor-interfaces
0b6fd762f5e8dd40db18401b88dab6908d667f03
extern crate rmp_serde as rmps; use rmps::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use std::io::Cursor; #[cfg(feature = "guest")] extern crate wapc_guest as guest; #[cfg(feature = "guest")] use guest::prelude::*; #[cfg(feature = "guest")] pub struct Host { binding: String, } #[cfg(feature...
extern crate rmp_serde as rmps; use rmps::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use std::io::Cursor; #[cfg(feature = "guest")] extern crate wapc_guest as guest; #[cfg(feature = "guest")] use guest::prelude::*; #[cfg(feature = "guest")] pub struct Host { binding: String, } #[cfg(feature...
) .map(|vec| { let resp = deserialize::<BlobList>(vec.as_ref()).unwrap(); resp }) .map_err(|e| e.into()) } pub fn upload_chunk(&self, chunk: FileChunk) -> HandlerResult<BlobstoreResult> { let input_args = UploadChunkArgs { chunk }; ...
tainer_id: String) -> HandlerResult<BlobList> { let input_args = ListObjectsArgs { container_id }; host_call( &self.binding, "wasmcloud:blobstore", "ListObjects", &serialize(input_args)?,
function_block-random_span
[]
Rust
src/cmd.rs
msiglreith/spirv-tools-rs
a7f201c445dcf8bdce5ab11fadaf6e1837f02b86
use crate::error::Message; use std::process::{Command, Stdio}; pub enum CmdError { BinaryNotFound(std::io::Error), Io(std::io::Error), ToolErrors { exit_code: i32, messages: Vec<Message>, }, } impl From<CmdError> for crate::error::Error { fn from(c...
use crate::error::Message; use std::process::{Command, Stdio}; pub enum CmdError { BinaryNotFound(std::io::Error), Io(std::io::Error), ToolErrors { exit_code: i32, messages: Vec<Message>, }, } impl From<CmdError> for crate::error::Error { fn from(c...
} pub struct CmdOutput { pub binary: Vec<u8>, pub messages: Vec<Message>, } #[derive(PartialEq, Copy, Clone)] pub enum Output { Ignore, Retrieve, } pub fn exec( mut cmd: Command, input: Option<&[u8]>, retrieve_output: Output, ) -> Result<CmdOutput, CmdError> { cmd...
inner: SpirvResult::InternalError, diagnostic: Some(diagnostic), } } } }
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn to_binary(bytes: &[u8]) -> Result<&[u32], crate::Error> {\n\n if bytes.len() % std::mem::size_of::<u32>() != 0 {\n\n return Err(crate::Error {\n\n inner: spirv_tools_sys::shared::SpirvResult::InvalidBinary,\n\n diagnostic: None,\n\n });\n\...
Rust
src/storage/fxfs/src/volume.rs
dahliaOS/fuchsia-pi4
5b534fccefd918b5f03205393c1fe5fddf8031d0
use { crate::{ errors::FxfsError, object_store::{ directory::Directory, filesystem::FxFilesystem, transaction::{LockKey, TransactionHandler}, ObjectDescriptor, ObjectStore, }, }, anyhow::{anyhow, bail, Context, Error}, std::sync::...
use { crate::{ errors::FxfsError, object_store::{ directory::Directory, filesystem::FxFilesystem, transaction::{LockKey, TransactionHandler}, ObjectDescriptor, ObjectStore, }, }, anyhow::{anyhow, bail, Context, Error}, std::sync::...
volume_store } else { self.filesystem.root_store().open_store(object_id).await? }) } pub async fn open_or_create_volume( &self, volume_name: &str, ) -> Result<Arc<ObjectStore>, Error> { match self.volume(volume_name).await { Ok(volume)...
ctStore>, Error> { let object_id = match self.volume_directory.lookup(volume_name).await?.ok_or(FxfsError::NotFound)? { (object_id, ObjectDescriptor::Volume) => object_id, _ => bail!(FxfsError::Inconsistent), }; Ok(if let Some(volume_store) = self....
function_block-random_span
[]
Rust
rbsigner/src/fitsigner.rs
imrank03/rustBoot
c6c2494050dbf5d494722208b14d771392f91d2b
#[cfg(feature = "nistp256")] use p256::ecdsa::{signature::DigestSigner, Signature, SigningKey}; use sha2::Sha256; use signature::Error as SigningError; use as_slice::AsSlice; use rustBoot::dt::{prepare_img_hash, update_dtb_header, Error as ITBError, Reader}; #[derive(Debug)] pub enum CurveType { #[allow(dead_code...
#[cfg(feature = "nistp256")] use p256::ecdsa::{signature::DigestSigner, Signature, SigningKey}; use sha2::Sha256; use signature::Error as SigningError; use as_slice::AsSlice; use rustBoot::dt::{prepare_img_hash, update_dtb_header, Error as ITBError, Reader}; #[derive(Debug)] pub enum CurveType { #[allow(dead_code...
} pub fn sign_fit(curve: CurveType, itb_blob: Vec<u8>, sk_type: SigningKeyType) -> Result<Vec<u8>> { match curve { #[cfg(feature = "secp256k1")] CurveType::Secp256k1 => {} #[cfg(feature = "nistp256")] CurveType::NistP256 => { let (prehashed_digest, _) = prepare_img_hash...
match curve { #[cfg(feature = "secp256k1")] CurveType::Secp256k1 => {} #[cfg(feature = "nistp256")] CurveType::NistP256 => { let sk = SigningKey::from_bytes(bytes).map_err(|v| RbSignerError::KeyError(v))?; Ok(SigningKeyType::NistP256(sk)) } _ => to...
if_condition
[ { "content": "pub fn as_str(bytes: &[u8]) -> Result<Option<&str>> {\n\n let val = core::str::from_utf8(bytes)\n\n .map_err(|val| Error::BadStrEncoding(val))?\n\n .strip_suffix(\"\\u{0}\");\n\n Ok(val)\n\n}\n", "file_path": "rustBoot/src/dt/fit.rs", "rank": 0, "score": 223710.0191...
Rust
rustbus/src/tests.rs
KillingSpark/rustbus
1dfd01d0ef6be915a7a50d501da849703b636f68
use crate::params::Base; use crate::params::Param; use crate::wire::marshal::marshal; use crate::wire::unmarshal::unmarshal_dynamic_header; use crate::wire::unmarshal::unmarshal_header; use crate::wire::unmarshal::unmarshal_next_message; mod dbus_send; mod fdpassing; mod verify_marshalling; mod verify_padding; #[test...
use crate::params::Base; use crate::params::Param; use crate::wire::marshal::marshal; use crate::wire::unmarshal::unmarshal_dynamic_header; use crate::wire::unmarshal::unmarshal_header; use crate::wire::unmarshal::unmarshal_next_message; mod dbus_send; mod fdpassing; mod verify_marshalling; mod verify_padding; #[test...
msg.body.push_old_params(&params).unwrap(); msg.body.push_param(128u8).unwrap(); msg.body.push_param(128u64).unwrap(); msg.body.push_param(128i32).unwrap(); params.push(128u8.into()); params.push(128u64.into()); params.push(128i32.into()); msg.dynheader.serial = Some(1); let...
let mut msg = crate::message_builder::MessageBuilder::new() .signal("io.killing.spark", "TestSignal", "/io/killing/spark") .build();
assignment_statement
[ { "content": "fn marshal_struct(params: &[params::Param], ctx: &mut MarshalContext) -> Result<(), MarshalError> {\n\n ctx.align_to(8);\n\n for p in params {\n\n marshal_param(p, ctx)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "rustbus/src/wire/marshal/param/container.rs", "rank": 0,...
Rust
examples/mtcnn/src/main.rs
sunnyrust/poem-openapi
98c28d67aee280d3877f0946351e79a8b773dde9
use image::{ Pixel, Rgba,ImageFormat}; use imageproc::drawing::draw_hollow_rect_mut; use imageproc::rect::Rect; mod mtcnn; use mtcnn::Mtcnn; use std::collections::HashMap; use poem::{listener::TcpListener, Error, Result}; use poem_openapi::{ payload::{Binary, Json}, types::multipart::Upload, Multipart, Ob...
use image::{ Pixel, Rgba,ImageFormat}; use imageproc::drawing::draw_hollow_rect_mut; use imageproc::rect::Rect; mod mtcnn; use mtcnn::Mtcnn; use std::collections::HashMap; use poem::{listener::TcpListener, Error, Result}; use poem_openapi::{ payload::{Binary, Json}, types::multipart::Upload, Multipart, Ob...
ult::default(), }), }) .title("Upload Files") .ui_path("/ui"), ) .await .unwrap(); }
function_block-function_prefixed
[ { "content": "#[derive(Debug, Response)]\n\nenum GetFileResponse {\n\n #[oai(status = 200)]\n\n Ok(Binary, #[oai(header = \"Content-Disposition\")] String),\n\n /// File not found\n\n #[oai(status = 404)]\n\n NotFound,\n\n}\n\n\n", "file_path": "examples/upload/src/main.rs", "rank": 0, ...