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
apps/baker/src/services/key.rs
simplestaking/tezos-rs
d859dff0a8db4f5adb4885e4885217d5284f7861
use std::{convert::TryFrom, fs::File, io, path::Path, str::FromStr}; use derive_more::From; use reqwest::{blocking::Client, Url}; use serde::Deserialize; use thiserror::Error; use crypto::{ base58::FromBase58CheckError, hash::{ ChainId, ContractTz1Hash, Ed25519Signature, SecretKeyEd25519, SeedEd2551...
use std::{convert::TryFrom, fs::File, io, path::Path, str::FromStr}; use derive_more::From; use reqwest::{blocking::Client, Url}; use serde::Deserialize; use thiserror::Error; use crypto::{ base58::FromBase58CheckError, hash::{ ChainId, ContractTz1Hash, Ed25519Signature, SecretKeyEd25519, SeedEd2551...
} "http" | "https" => { let url = Url::parse(s)?; let pkh_str = url .path_segments() .ok_or(SignerParseError::MissingPkhPathSegment)? .last() .ok_or(SignerParseError::MissingPkhPathSe...
Ok(Signer { backend: SignerBackend::LiteralSecretKey(secret_key), pkh: ContractTz1Hash::try_from(public_key)?, })
call_expression
[ { "content": "pub fn string(data: impl AsRef<str>, out: &mut Vec<u8>) -> BinResult {\n\n put_size(data.as_ref().len(), out)?;\n\n put_bytes(data.as_ref().as_bytes(), out);\n\n Ok(())\n\n}\n\n\n", "file_path": "tezos/encoding/src/enc.rs", "rank": 0, "score": 499328.670751536 }, { "co...
Rust
src/rr/rdata/mod.rs
matttpt/quandary
6ecd1837020baa08814a7239d12ddb0280524e49
use std::borrow::Cow; use std::fmt::{self, Write}; use std::ops::Deref; use super::Type; use crate::name; use crate::util::nibble_to_ascii_hex_digit; mod helpers; mod ipv6; mod opt; mod srv; mod std13; pub use ipv6::*; pub use opt::*; pub use srv::*; pub use std13::*; #[derive(Eq, PartialEq)] #[repr(transparent)]...
use std::borrow::Cow; use std::fmt::{self, Write}; use std::ops::Deref; use super::Type; use crate::name; use crate::util::nibble_to_ascii_hex_digit; mod helpers; mod ipv6; mod opt; mod srv; mod std13; pub use ipv6::*; pub use opt::*; pub use srv::*; pub use std13::*; #[derive(Eq, PartialEq)] #[repr(transparent)]...
} impl<'a, const N: usize> TryFrom<&'a [u8; N]> for &'a Rdata { type Error = RdataTooLongError; fn try_from(octets: &'a [u8; N]) -> Result<Self, Self::Error> { octets[..].try_into() } } impl Deref for Rdata { type Target = [u8]; fn deref(&self) -> &Self::Target { &self.octets ...
if octets.len() > (u16::MAX as usize) { Err(RdataTooLongError) } else { Ok(Rdata::from_unchecked(octets)) } }
function_block-function_prefix_line
[ { "content": "/// Validates and decompresses RDATA consisting of a single domain name.\n\n/// This is for the implementation of [`Rdata::read`].\n\npub fn read_name_rdata(buf: &[u8], cursor: usize) -> Result<Box<Rdata>, ReadRdataError> {\n\n let (name, len) = Name::try_from_compressed(buf, cursor)?;\n\n i...
Rust
src/policy.rs
cloudflare/dmarc
438945db5f1685c5bfaeefa3de1644fa317d85f8
use rand::distributions::Bernoulli; use rand::distributions::Distribution; use slog::debug; use std::default::Default; use crate::{dns, DMARCResult, PolicyContext, SPFResult}; #[derive(Debug, PartialEq, Clone)] pub enum Alignement { Relaxed, Strict, } impl Default for Alignement { fn default() -> Self { ...
use rand::distributions::Bernoulli; use rand::distributions::Distribution; use slog::debug; use std::default::Default; use crate::{dns, DMARCResult, PolicyContext, SPFResult}; #[derive(Debug, PartialEq, Clone)] pub enum Alignement { Relaxed, Strict, } impl Default for Alignement { fn default() -> Self { ...
assert_eq!(policy.check_spf_alignment(from_domain, &spf_result), false); } #[test] fn test_check_alignement_spf_relaxed() { let mut policy = Policy::new(ReceiverAction::Reject); policy.aspf = Alignement::Relaxed; let from_domain = "a.com"; let spf_result = SPFResu...
let spf_result = SPFResult { domain_used: "cc.com".to_string(), value: "-".to_string(), };
assignment_statement
[ { "content": "/// Parse a DMARC policy\n\n///\n\n/// If the policy wasn't found at the current domain but was found at the root\n\n/// domain `is_root` must be true. And if the `sp` tag was provided it will be\n\n/// set to the policy's action, otherwise the `p` tag will be used.\n\n///\n\n/// For non-root doma...
Rust
src/input.rs
HeikoRibberink/piston2d_abstraction
2c26eec068380864bc62ba2ae36312f384284f77
#![allow(unused_variables)] use piston_window as pw; use std::collections::HashSet; pub use piston2d_abstraction_proc_macros::derive_input_consumer; macro_rules! create_consumer_trait { ($consumer_name:ident consumes $($arg_name:ident: $arg_ty:ty),*; $(fn $fn_name:ident($($fn_arg_name:ident: $fn_arg_ty:ty),*) $(-...
#![allow(unused_variables)] use piston_window as pw; use std::collections::HashSet; pub use piston2d_abstraction_proc_macros::derive_input_consumer; macro_rules! create_consumer_trait { ($consumer_name:ident consumes $($arg_name:ident: $arg_ty:ty),*; $(fn $fn_name:ident($($fn_arg_name:ident: $fn_arg_ty:ty),*) $(-...
er_trait!(CursorMotionConsumer consumes change: [f64; 2];); create_consumer_trait!(ScrollConsumer consumes change: [f64; 2];);
ler { pub pressed_buttons: HashSet<pw::Button>, } impl InputHandler { pub fn new() -> Self { Self { pressed_buttons: HashSet::new(), } } pub fn consume(&mut self, event: pw::Input, consumers: &mut [&mut dyn InputConsumer]) { use pw::Input::*; for con in cons...
random
[ { "content": "pub fn render(\n\n c: Context,\n\n g: &mut impl Graphics<Texture = G2dTexture>,\n\n settings: &RenderSettings,\n\n rs: &[&dyn Renderable],\n\n) {\n\n let [width, height] = c.get_view_size();\n\n let mut m = Matrix2d::identity();\n\n m *= match settings.scaling {\n\n Sca...
Rust
fountain/src/parse.rs
adamchalmers/fountain-rs
4568a41e4ff2e2aff994a84bac85773fd48cb2ed
use super::data::*; use nom::{ branch::alt, bytes::complete::{is_not, tag, take_while1}, character::complete::{char, line_ending, multispace1, not_line_ending}, combinator::{cut, map, opt, verify}, error::{context, ContextError, ParseError}, multi::{many0, separated_list0}, sequence::{delimi...
use super::data::*; use nom::{ branch::alt, bytes::complete::{is_not, tag, take_while1}, character::complete::{char, line_ending, multispace1, not_line_ending}, combinator::{cut, map, opt, verify}, error::{context, ContextError, ParseError}, multi::{many0, separated_list0}, sequence::{delimi...
#[test] fn test_forced_transition() { let input_text = "> Burn to white.\n"; let output = transition_forced::<(&str, ErrorKind)>(input_text); let expected = Ok(("", Line::Transition("Burn to white.".to_owned()))); assert_eq!(output, expected); } #[test] fn test_int...
fn test_transition() { let input_text = "FADE TO:\n"; let output = transition_to::<VerboseError<&str>>(input_text); let expected = Ok(("", Line::Transition("FADE TO:".to_owned()))); assert_eq!(output, expected); }
function_block-full_function
[ { "content": "#[wasm_bindgen]\n\npub fn parse(screenplay: &str) -> String {\n\n println!(\"Parsing the following Fountain doc:\\n{}\", screenplay);\n\n\n\n // Write to String buffer.\n\n match fountain::parse_document::<(&str, _)>(&screenplay) {\n\n Err(e) => format!(\n\n \"\\\n\n<h1 ...
Rust
src/solution/y2020/d21pt2.rs
benaryorg/adventofcode
79855c500ab2b89895978cf0f1d7bb1b90e3fe1d
use crate::error::*; pub struct Solution { input: String, } impl Solution { pub fn new(input: String) -> Self { Self { input, } } } use nom:: { character::complete::*, bytes::complete::tag, sequence::*, multi::*, IResult, }; #[derive(Clone,Debug)] struct Recipe { allergenes: Vec<String>, ingredients: V...
use crate::error::*; pub struct Solution { input: String, } impl Solution { pub fn new(input: String) -> Self { Self { input, } } } use nom:: { character::complete::*, bytes::complete::tag, sequence::*, multi::*, IResult, }; #[derive(Clone,Debug)] struct Recipe { allergenes: Vec<String>, ingredients: V...
} fn recipe(input: &str) -> IResult<&str,Recipe> { let (input,ingredients) = ingredients(input)?; let (input,_) = char(' ')(input)?; let (input,allergenes) = allergenes(input)?; Ok((input,Recipe { allergenes, ingredients, })) } fn ingredients(input: &str) -> IResult<&str,Vec<String>> { let (input,vec) = ...
fn from_str(input: &str) -> std::result::Result<Self, Error> { let result = recipe(input) .map_err(|err| anyhow!("{}", err)) .context(Error::AocParsing)? .1; Ok(result) }
function_block-full_function
[ { "content": "fn input(input: &str) -> IResult<&str, Set<(isize, isize)>, nom::error::VerboseError<&str>>\n\n{\n\n\tlet (input, bitlines) = many1(terminated(many1(map(one_of(\"#.\"), |ch| ch == '#')), newline))(input)?;\n\n\n\n\tlet set = bitlines.into_iter()\n\n\t\t.enumerate()\n\n\t\t.flat_map(|(y, v)|\n\n\t\...
Rust
src/parser/types.rs
al3xfischer/wasm-ast
1b4c42685bb33d4edee0ae958dccbca1f8106e09
use crate::parser::values::{match_byte, parse_u32, parse_vector}; use crate::{ FloatType, FunctionType, GlobalType, IntegerType, Limit, MemoryType, Mutability, NumberType, ReferenceType, ResultType, TableType, ValueType, }; use nom::branch::alt; use nom::combinator::map; use nom::sequence::{preceded, tuple}; ...
use crate::parser::values::{match_byte, parse_u32, parse_vector}; use crate::{ FloatType, FunctionType, GlobalType, IntegerType, Limit, MemoryType, Mutability, NumberType, ReferenceType, ResultType, TableType, ValueType, }; use nom::branch::alt; use nom::combinator::map; use nom::sequence::{preceded, tuple}; ...
alt(( map(match_byte(0x00), |_| Mutability::Immutable), map(match_byte(0x01), |_| Mutability::Mutable), )), )), |(kind, mutability)| GlobalType::new(kind, mutability), )(input) } #[cfg(test)] mod tests { use super::*; #[test] fn parse_result...
FunctionType> { map( preceded( match_byte(0x60), tuple((parse_result_type, parse_result_type)), ), |(parameters, results)| FunctionType::new(parameters, results), )(input) } pub fn parse_limit(input: &[u8]) -> IResult<&[u8], Limit> { alt(( map(preced...
random
[ { "content": "/// Parses an unsigned 32-bit integer using LEB128 (Little-Endian Base 128) encoding.\n\n///\n\n/// See <https://webassembly.github.io/spec/core/binary/values.html#integers>\n\npub fn parse_u32(input: &[u8]) -> IResult<&[u8], u32> {\n\n nomify(input, parse_unsigned::<u32>(input))\n\n}\n\n\n", ...
Rust
src/lib.rs
bytwise/mitte_amd64
7d56d7efe2280d6340c10a207e53c1fa64f7a190
extern crate byteorder; use std::io::{Write, Cursor}; use byteorder::{WriteBytesExt, LittleEndian}; use amd64::*; mod buffer; mod ptr; mod common; #[macro_use] mod macros; mod encode; pub mod reg; pub mod operand; pub mod error; pub mod fixup; pub mod label; pub mod amd64; pub use ptr::{Mem, Byte, Word, DWord, QWo...
extern crate byteorder; use std::io::{Write, Cursor}; use byteorder::{WriteBytesExt, LittleEndian}; use amd64::*; mod buffer; mod ptr; mod common; #[macro_use] mod macros; mod encode; pub mod reg; pub mod operand; pub mod error; pub mod fixup; pub mod label; pub mod amd64; pub use ptr::{Mem, Byte, Word, DWord, QWo...
jnp(arg: T) -> R => Jnp; emit_jns(arg: T) -> R => Jns; emit_jnz(arg: T) -> R => Jnz; emit_jo(arg: T) -> R => Jo; emit_jp(arg: T) -> R => Jp; emit_jpe(arg: T) -> R => Jpe; emit_jpo(arg: T) -> R => Jpo; emit_js(arg: T) -> R => Js; emit_jz(arg: T) -> R => Jz;...
_cmovnle(dst: D, src: S) => Cmovnle; emit_cmovno(dst: D, src: S) => Cmovno; emit_cmovnp(dst: D, src: S) => Cmovnp; emit_cmovns(dst: D, src: S) => Cmovns; emit_cmovnz(dst: D, src: S) => Cmovnz; emit_cmovo(dst: D, src: S) => Cmovo; emit_cmovp(dst: D, src: S) => Cmovp; ...
random
[ { "content": "#[inline]\n\npub fn write_reg_disp(buffer: &mut Buffer, reg: u8, disp: i32) -> Result<(), Error<NoError>> {\n\n buffer.write_u8(modrm(0, reg, 4));\n\n buffer.write_u8(sib(0, 4, 5));\n\n buffer.write_u32(disp as u32);\n\n Ok(())\n\n}\n\n\n", "file_path": "src/common.rs", "rank":...
Rust
rclrust-msg-gen/src/types/primitives.rs
HarukiUchito/rclrust
a00c65daa837ff72e437f17516705725c807a8c3
use std::fmt; use proc_macro2::{Ident, Literal, Span}; use quote::{format_ident, quote, ToTokens}; macro_rules! define_enum_from { ($into_t:ty, $from_t:ty, $path:path) => { impl From<$from_t> for $into_t { fn from(t: $from_t) -> Self { $path(t) } } }; } ...
use std::fmt; use proc_macro2::{Ident, Literal, Span}; use quote::{format_ident, quote, ToTokens}; macro_rules! define_enum_from { ($into_t:ty, $from_t:ty, $path:path) => { impl From<$from_t> for $into_t { fn from(t: $from_t) -> Self { $path(t) } } }; } ...
fn value_literal(self, value: &str) -> Option<Literal> { Some(match self { Self::I8 => Literal::i8_suffixed(value.parse().unwrap()), Self::I16 => Literal::i16_suffixed(value.parse().unwrap()), Self::I32 => Literal::i32_suffixed(value.parse().unwrap()), Self:...
f::U32 => quote! { u32 }, Self::U64 => quote! { u64 }, Self::F32 => quote! { f32 }, Self::F64 => quote! { f64 }, Self::Bool => quote! { bool }, } }
function_block-function_prefixed
[ { "content": "fn bool_literal(s: &str) -> IResult<&str, bool> {\n\n alt((\n\n value(true, alt((tag(\"true\"), tag(\"1\")))),\n\n value(false, alt((tag(\"false\"), tag(\"0\")))),\n\n ))(s)\n\n}\n\n\n", "file_path": "rclrust-msg-gen/src/parser/literal.rs", "rank": 0, "score": 22727...
Rust
src/data.rs
yellow-pitaya/scpi-client
31d9483a3051a20a42f6d72a7fa3de1536d720c4
use crate::socket::Socket; #[derive(Copy, Clone, Debug, PartialEq)] pub enum Unit { RAW, VOLTS, } impl std::convert::From<Unit> for String { fn from(unit: Unit) -> Self { let s = match unit { Unit::RAW => "RAW", Unit::VOLTS => "VOLTS", }; String::from(s) ...
use crate::socket::Socket; #[derive(Copy, Clone, Debug, PartialEq)] pub enum Unit { RAW, VOLTS, } impl std::convert::From<Unit> for String { fn from(unit: Unit) -> Self { let s = match unit { Unit::RAW => "RAW", Unit::VOLTS => "VOLTS", }; String::from(s) ...
} #[derive(Copy, Clone, Debug, PartialEq)] pub enum Format { ASCII, BIN, } impl std::convert::From<Format> for String { fn from(format: Format) -> Self { let s = match format { Format::ASCII => "ASCII", Format::BIN => "BIN", }; String::from(s) } } #[d...
fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "RAW" => Ok(Unit::RAW), "VOLTS" => Ok(Unit::VOLTS), unit => Err(format!("Unknow unit '{}'", unit)), } }
function_block-full_function
[ { "content": "pub trait Pin: std::convert::Into<String> {}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq)]\n\npub enum Gpio {\n\n DIO0_N,\n\n DIO0_P,\n\n DIO1_N,\n\n DIO1_P,\n\n DIO2_N,\n\n DIO2_P,\n\n DIO3_N,\n\n DIO3_P,\n\n DIO4_N,\n\n DIO4_P,\n\n DIO5_N,\n\n DIO5_P,\n\n ...
Rust
sources/rust/font/src/math/mod.rs
xunilrj/sandbox
f92c12f83433cac01a885585e41c02bb5826a01f
pub fn dist2_line_line( l0_p0_x: f32, l0_p0_y: f32, l0_p1_x: f32, l0_p1_y: f32, l1_p0_x: f32, l1_p0_y: f32, l1_p1_x: f32, l1_p1_y: f32, ) -> f32 { let x0: f32 = l0_p0_x * l1_p1_x; let x1: f32 = l0_p0_y * l1_p1_y; let x2: f32 = l0_p1_x * l1_p0_x; let x3: f32 = l0_p1_y * l...
pub fn dist2_line_line( l0_p0_x: f32, l0_p0_y: f32, l0_p1_x: f32, l0_p1_y: f32, l1_p0_x: f32, l1_p0_y: f32, l1_p1_x: f32, l1_p1_y: f32, ) -> f32 { let x0: f32 = l0_p0_x * l1_p1_x; let x1: f32 = l0_p0_y * l1_p1_y; let x2: f32 = l0_p1_x * l1_p0_x; let x3: f32 = l0_p1_y * l...
x.powi(2) - 1.0 * p3_x * x0 + 4.0 * p3_y.powi(2) - 1.0 * p3_y * x2 + 8.0 * x1 + 8.0 * x3 + x5 + x7 + 16.0 * x8 + 16.0 * x9; let result_1: f32 = 12.0 * p2_x * p3_x + 12.0 * p2_y * p3_y - 12.0 * x1 + 36.0 * x10 + 36.0 * x11 - 1.0 * x1...
+ l1_p1_y.powi(2) + 2.0 * x0 + 2.0 * x1 + 2.0 * x2 + 2.0 * x3 - 2.0 * x4 - 2.0 * x5 - 2.0 * x6 - 2.0 * x7 + x8; rnum / rden } pub fn nearest2_point_line( l0_p0_x: f32, l0_p0_y: f32, l0_p1_x: f32, l0_p1_y: f32, p0_x: f32, ...
random
[ { "content": "#[inline(always)]\n\n#[allow(dead_code)]\n\npub fn parse_le_u16_as_f32(input: &[u8], min: f32, max: f32) -> nom::IResult<&[u8], f32> {\n\n let (input, v) = nom::number::complete::le_u16(input)?;\n\n Ok((input, ((v as f32 / u16::MAX as f32) * (max - min)) + min))\n\n}\n\n\n", "file_path":...
Rust
src/run.rs
Simonwep/cleanup-files
0af5843df478050077fadca182a14fff0e8c2d79
use std::fs::OpenOptions; use std::io::Write; use chrono::Utc; use colored::Colorize; use crate::cli::result::CLIResult; use crate::file::{accept, FileResult, Options}; use crate::lib::resolve_directories; fn resolve_cs_list(val: Option<&String>) -> Option<Vec<String>> { if val.is_none() { return Option:...
use std::fs::OpenOptions; use std::io::Write; use chrono::Utc; use colored::Colorize; use crate::cli::result::CLIResult; use crate::file::{accept, FileResult, Options}; use crate::lib::resolve_directories; fn resolve_cs_list(val: Option<&String>) -> Option<Vec<String>> { if val.is_none() { return Option:...
] {} ({})", path, error), FileResult::Moved(dest) => { format!("[MOVED] {} -> {}", path, dest.to_str().unwrap()) } FileResult::Skipped => format!("[SKIPPED] {}", path), FileResult::Checked => format!("[CHECKED] {}", ...
.or(Option::Some(default_log_file)) .unwrap(); if log_file.eq("false") { return; } let log_file_path = target.join(log_file); if !log_file_path.exists() { std::fs::write(&log_file_path, "") .ok() .expect(&format!("Fai...
random
[ { "content": "pub fn resolve_directories(app: &CLIResult) -> (PathBuf, PathBuf) {\n\n let source_path = PathBuf::from(app.get_value(\"source\").unwrap().clone())\n\n .absolutize()\n\n .unwrap();\n\n\n\n let target_path = PathBuf::from(app.get_value(\"target\").unwrap().clone())\n\n .a...
Rust
src/lib.rs
hsivonen/detone
9c407c2d6c98ae4109215466af9020f4ffedef24
#![doc(html_root_url = "https://docs.rs/DecomposeVietnamese/1.0.0")] #[repr(align(64))] struct ToneData { windows_1258_key: [u8; 16], windows_1258_value: [u8; 16], middle_key: [u8; 14], middle_value: [u8; 14], extensions_for_vietnamese: [u16; 90], } static TONE_DATA: ToneData = ToneData { w...
#![doc(html_root_url = "https://docs.rs/DecomposeVietnamese/1.0.0")] #[repr(align(64))] struct ToneData { windows_1258_key: [u8; 16], windows_1258_value: [u8; 16], middle_key: [u8; 14], middle_value: [u8; 14], extensions_for_vietnamese: [u16; 90], } static TONE_DATA: ToneData = ToneData { w...
#[test] fn test_tones() { let bases = [ 'A', 'a', 'Ă', 'ă', 'Â', 'â', 'E', 'e', 'Ê', 'ê', 'I', 'i', 'O', 'o', 'Ô', 'ô', 'Ơ', 'ơ', 'U', 'u', 'Ư', 'ư', 'Y', 'y', ]; let tones = ['\u{0300}', '\u{0309}', '\u{0303}', '\u{0301}', '\u{0323}']; for &base in base...
assert_eq!(decompose_vietnamese.next(), Some(base)); assert_eq!(decompose_vietnamese.next(), Some(tone)); assert_eq!(decompose_vietnamese.next(), None); }
function_block-function_prefix_line
[ { "content": "# detone\n\n\n\n[![crates.io](https://meritbadge.herokuapp.com/detone)](https://crates.io/crates/detone)\n\n[![docs.rs](https://docs.rs/detone/badge.svg)](https://docs.rs/detone/)\n\n[![Apache 2 / MIT dual-licensed](https://img.shields.io/badge/license-Apache%202%20%2F%20MIT-blue.svg)](https://git...
Rust
cargo-atelier/src/actions.rs
koalp/rust-atelier
a199e222b99d75673a8b1603e5401df53eec7b91
use crate::{FileCommand, FileFormat, TransformCommand}; use atelier_lib::action::{standard_model_lint, standard_model_validation}; use atelier_lib::core::action::ActionIssue; use atelier_lib::core::error::{Error as ModelError, ErrorKind, Result as ModelResult}; use atelier_lib::core::io::read_model_from_string; use ate...
use crate::{FileCommand, FileFormat, TransformCommand}; use atelier_lib::action::{standard_model_lint, standard_model_validation}; use atelier_lib::core::action::ActionIssue; use atelier_lib::core::error::{Error as ModelError, ErrorKind, Result as ModelResult}; use atelier_lib::core::io::read_model_from_string; use ate...
atch cmd.input_file.file_name { None => Box::new(std::io::stdin()), Some(file_name) => Box::new(File::open(file_name)?), }; let mut content: Vec<u8> = Vec::default(); let _ = file.read_to_end(&mut content).unwrap(); check_fn(&reader(content)?, false) } pub fn transform_file( cmd: T...
ead_json(content: Vec<u8>) -> Result<Model, ModelError> { read_model_from_string(&mut JsonReader::default(), content) } fn read_smithy(content: Vec<u8>) -> Result<Model, ModelError> { read_model_from_string(&mut SmithyReader::default(), content) } let err: ModelError = ErrorKind::Invalid...
random
[ { "content": "pub fn report_action_issues(issues: Vec<ActionIssue>, color: bool) -> Result<(), Box<dyn Error>> {\n\n println!();\n\n if !issues.is_empty() {\n\n for issue in issues {\n\n if color {\n\n report_issue(issue)\n\n } else {\n\n report_i...
Rust
src/ffi.rs
Nercury/egli-rs
c48a78b49242499a282f065a20f44d698ebdfcd2
#[allow(unused_imports)] use libc::{c_char, c_void}; use egl::{EGLBoolean, EGLClientBuffer, EGLConfig, EGLContext, EGLDisplay, EGLenum, EGLint, EGLNativeDisplayType, EGLNativePixmapType, EGLNativeWindowType, EGLSurface}; #[cfg(feature = "egl_1_5")] use egl::{EGLSync, EGLAttrib, EGLImage, EGLTime}; extern...
#[allow(unused_imports)] use libc::{c_char, c_void}; use egl::{EGLBoolean, EGLClientBuffer, EGLConfig, EGLContext, EGLDisplay, EGLenum, EGLint, EGLNativeDisplayType, EGLNativePixmapType, EGLNativeWindowType, EGLSurface}; #[cfg(feature = "egl_1_5")] use egl::{EGLSync, EGLAttrib, EGLImage, EGLTime}; extern...
eglQueryString(dpy: EGLDisplay, name: EGLint) -> *const c_char; pub fn eglQuerySurface(dpy: EGLDisplay, surface: EGLSurface, attribute: EGLint, value: *mut EGLint) -> EGLBoolean; pub fn eglSwapBuffers(d...
ub fn eglQueryContext(dpy: EGLDisplay, ctx: EGLContext, attribute: EGLint, value: *mut EGLint) -> EGLBoolean; pub fn
random
[ { "content": "/// `[EGL 1.0]` Return a GL or an EGL extension function.\n\npub fn get_proc_address(procname: &str) -> extern \"C\" fn() {\n\n unsafe {\n\n let string = CString::new(procname).unwrap();\n\n\n\n ffi::eglGetProcAddress(string.as_ptr())\n\n }\n\n}\n\n\n", "file_path": "src/eg...
Rust
src/bin/c07p06.rs
simonsan/cracking-the-coding-interview-rust
9d4c82bf57cbeaec1ab3fdcd219b1d96f6f6a052
use rand::seq::SliceRandom; use rand::thread_rng; use std::cell::RefCell; use std::rc::Rc; #[derive(PartialEq)] enum Side { Top, Left, Right, Bottom, None, } #[derive(Clone, Eq, PartialEq)] struct Piece { top: Option<PieceRef>, left: Option<PieceRef>, right: Option<PieceRef>, botto...
use rand::seq::SliceRandom; use rand::thread_rng; use std::cell::RefCell; use std::rc::Rc; #[derive(PartialEq)] enum Side { Top, Left, Right, Bottom, None, } #[
ceRef>, second: &PieceRef) -> bool { if let Some(first_ptr) = first { return Rc::ptr_eq(first_ptr, second); } false } fn fits_with(&self, other: &PieceRef) -> Side { if self.fits_with_inner(&self.top, other) { Side::Top } else if self.fits_with_in...
derive(Clone, Eq, PartialEq)] struct Piece { top: Option<PieceRef>, left: Option<PieceRef>, right: Option<PieceRef>, bottom: Option<PieceRef>, w: usize, h: usize, } type PieceRef = Rc<RefCell<Piece>>; #[derive(Clone)] struct Puzzle { pieces: Vec<PieceRef>, width: usize, height: usi...
random
[ { "content": "## Prerequisites\n\n\n\nTo run the code, you'll need an up-to-date version of Rust. The recommended way of\n\ninstalling Rust is [using a tool called rustup](https://rustup.rs/):\n\n\n\n```ShellSession\n\n$ curl https://sh.rustup.rs -sSf | sh\n\n...\n\n```\n\n\n\nOnce you have Rust installed, you ...
Rust
src/client.rs
asisdrico/trsh
c1b51f418ff20cf0a1a4d1475bd80c6b0ba5a187
use cryptolib::cryptolib_salsa::Crypto; use std::env; use std::io::BufReader; use std::net::SocketAddr; use std::net::TcpStream; use std::path; use std::process; use std::process::{Command, Stdio}; use std::{ fs::File, io::prelude::*, sync::mpsc::{self, Receiver, Sender}, }; use rand::{thread_rng, Rng}; ...
use cryptolib::cryptolib_salsa::Crypto; use std::env; use std::io::BufReader; use std::net::SocketAddr; use std::net::TcpStream; use std::path; use std::process; use std::process::{Command, Stdio};
("error copying data: {}", e); return; } }; drop(output); } else if cmd.starts_with("SHELL") { let v: Vec<&str> = cmd.split('|').collect(); println!("Allocating shell {}, {}", v[1], v[2]); let w = v[1].parse().expect("not a number"); let h...
use std::{ fs::File, io::prelude::*, sync::mpsc::{self, Receiver, Sender}, }; use rand::{thread_rng, Rng}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::process::CommandExt; use std::{thread, time}; use daemonize::Daemonize; const KEY: &'static [u8] = env!("TRSH_KEY").as_bytes(); const...
random
[ { "content": "use std::process::Command;\n\nuse std::process::Stdio;\n\n\n", "file_path": "build.rs", "rank": 0, "score": 5.204393973276478 }, { "content": "//! \n\n//! shell <-r> - start an interactive shell on the client an forward it to server, when \n\n//! started with <-r> ...
Rust
components/director/src/config.rs
tomrobison/habitat
e3bc2af7cb9e1852f1cbeca7518341ed0ad962fc
use std::net::SocketAddrV4; use std::str::FromStr; use hcore::config::ConfigFile; use toml; use error::{Error, Result}; use super::ServiceDef; #[derive(Clone, Debug, PartialEq, Eq)] pub struct Config { pub service_defs: Vec<ServiceDef>, pub dir_sup_listen: Option<SocketAddrV4>, } impl ConfigFile...
use std::net::SocketAddrV4; use std::str::FromStr; use hcore::config::ConfigFile; use toml; use error::{Error, Result}; use super::ServiceDef; #[derive(Clone, Debug, PartialEq, Eq)] pub struct Config { pub service_defs: Vec<ServiceDef>, pub dir_sup_listen: Option<SocketAddrV4>, } impl ConfigFile...
as_table() { if tbl.values().all(|ref v| v.as_table().is_none()) { paths.push(current_path); return; } for (k, v) in tbl.iter() { path.push(k.clone()); _traverse(v, path, path...
let c = match toml.lookup("cfg.services") { Some(c) => c, None => return Err(Error::NoServices), }; let paths = Config::traverse(c); for p in &paths { let mut sd = ServiceDef::from_str(p).unwrap(); println!("Loaded service def: {}", &sd.to...
random
[ { "content": "type Handler = fn(&Config) -> result::Result<(), sup::error::SupError>;\n\n\n\n/// The entrypoint for the Supervisor.\n\n///\n\n/// * Set up the logger\n\n/// * Pull in the arguments from the Command Line, push through clap\n\n/// * Dispatch to a function that handles that action called\n\n/// * E...
Rust
src/api/district.rs
cesindo/pandemia
1add0633c413237e8b4d64d3c197dc5ecf1a0087
#![allow(missing_docs)] use actix_web::{HttpRequest, HttpResponse}; use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use validator::Validate; use crate::{ api, api::types::*, api::{error::*, ApiResult, Error as ApiError, HttpRequest as ApiHttpRequest}, ...
#![allow(missing_docs)] use actix_web::{HttpRequest, HttpResponse}; use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use validator::Validate; use crate::{ api, api::types::*, api::{error::*, ApiResult, Error as ApiError, HttpRequest as ApiHttpRequest}, ...
} #[api_endpoint(path = "/search", auth = "required", accessor = "admin")] pub fn search_districts(query: SearchDistrict) -> ApiResult<EntriesResult<District>> { query.validate()?; let conn = state.db(); let dao = DistrictDao::new(&conn); let (province, city) = match ...
Ok(ApiResult::success(EntriesResult { count, entries: entries.into_iter().map(|a| a.into()).collect(), }))
call_expression
[ { "content": "/// Build parameter error\n\npub fn unauthorized<T>() -> Result<T, Error> {\n\n Err(Error::Unauthorized)?;\n\n panic!(\"Unhandled error\");\n\n}\n", "file_path": "src/api/error.rs", "rank": 0, "score": 246512.2475177499 }, { "content": "struct PublicApi;\n\n\n\n/// API en...
Rust
orbtk_core/src/layout/popup.rs
hugefiver/orbtk
5e5f3852a5e3d7c54fcc8b56da1ae2feb5ed87f2
use std::{cell::RefCell, collections::BTreeMap}; use dces::prelude::*; use crate::{ prelude::*, proc_macros::IntoLayout, render::RenderContext2D, theming::*, tree::Tree, utils::prelude::*, }; use super::{component, component_or_default, component_try_mut, try_component, Layout}; #[derive(Default, IntoLayout...
use std::{cell::RefCell, collections::BTreeMap}; use dces::prelude::*; use crate::{ prelude::*, proc_macros::IntoLayout, render::RenderContext2D, theming::*, tree::Tree, utils::prelude::*, }; use super::{component, component_or_default, component_try_mut, try_component, Layout}; #[derive(Default, IntoLayout...
fn arrange( &self, render_context_2_d: &mut RenderContext2D, parent_size: (f64, f64), entity: Entity, ecm: &mut EntityComponentManager<Tree>, layouts: &BTreeMap<Entity, Box<dyn Layout>>, theme: &Theme, ) -> (f64, f64) { if component::<Visibility>...
m .component_store() .get::<Thickness>("margin", child) .unwrap(); desired_size.0 = desired_size.0.max( child_desired_size.width() + padding.left() ...
function_block-function_prefixed
[ { "content": "/// Mark the widget dirty.\n\npub fn mark_as_dirty_self(entity: Entity, ecm: &mut EntityComponentManager<Tree>) {\n\n let root = ecm.entity_store().root();\n\n\n\n *ecm.component_store_mut()\n\n .get_mut::<bool>(\"dirty\", entity)\n\n .unwrap() = true;\n\n\n\n if let Ok(dirt...
Rust
src/main.rs
input-output-hk/carnix
50fc904925ec82345214ded4db5298d6b7a5cf2d
#[macro_use] extern crate clap; extern crate env_logger; extern crate itertools; #[macro_use] extern crate log; #[macro_use] extern crate nom; extern crate regex; extern crate serde; #[macro_use] extern crate serde_derive; extern crate dirs; extern crate failure; extern crate serde_json; extern crate tempdir; extern cr...
#[macro_use] extern crate clap; extern crate env_logger; extern crate itertools; #[macro_use] extern crate log; #[macro_use] extern crate nom; extern crate regex; extern crate serde; #[macro_use] extern crate serde_derive; extern crate dirs; extern crate failure; extern crate serde_json; extern crate tempdir; extern cr...
.dependencies .iter_mut() .chain(meta.build_dependencies.iter_mut()) { dep.cr.found_in_lock = true } for (_, dep) in meta.target_dependencies.iter_mut() { ...
mod cache; mod cfg; mod error; mod krate; mod output; mod prefetch; use error::*; fn main() { env_logger::init(); let version = crate_version!(); let matches = App::new("carnix") .version(version) .author("pmeunier <pe@pijul.org>") .about("Generate a nix derivation set from a carg...
random
[ { "content": "fn get_package_version(package: &toml::Value) -> Crate {\n\n let mut name = package\n\n .as_table()\n\n .unwrap()\n\n .get(\"name\")\n\n .unwrap()\n\n .as_str()\n\n .unwrap()\n\n .to_string();\n\n let version = package.get(\"version\").unwrap(...
Rust
common/invensense-mpu/src/lib.rs
e-belski/rust-copter
562703c30a16c8d2763ca0f3e3fbb7d8be7c6681
#![no_std] pub mod i2c; pub mod spi; pub mod regs { pub use mpu9250_regs::{ ak8963::flags::*, ak8963::Regs as AK8963, ak8963::I2C_ADDRESS as AK8963_I2C_ADDRESS, mpu9250::flags::*, mpu9250::Regs as MPU9250, mpu9250::I2C_ADDRESS as MPU9250_I2C_ADDRESS, }; } use core::fmt::Debug; use embedded_...
#![no_std] pub mod i2c; pub mod spi; pub mod regs { pub use mpu9250_regs::{ ak8963::flags::*, ak8963::Regs as AK8963, ak8963::I2C_ADDRESS as AK8963_I2C_ADDRESS, mpu9250::flags::*, mpu9250::Regs as MPU9250, mpu9250::I2C_ADDRESS as MPU9250_I2C_ADDRESS, }; } use core::fmt::Debug; use embedded_...
} fn mag_sensitivity<T: Transport>( transport: &mut T, delay: &mut dyn DelayMs<u8>, ) -> Result<Triplet<f32>, Error<T::Error>> { use regs::*; let cntl1 = transport.ak8963_read(AK8963::CNTL1)?; transport.ak8963_write( AK8963::CNTL1, CNTL1 { mode: CNTL1_MODE::FUSE_ROM_ACC...
MPU9250::ACCEL_CONFIG, ACCEL_CONFIG { full_scale: self.accel_scale, ..Default::default() }, )?; transport.mpu9250_write(MPU9250::ACCEL_CONFIG_2, self.accel_rate)?; transport.mpu9250_write(MPU9250::SMPLRT_DIV, self.sample_rate_divider)?; ...
function_block-function_prefix_line
[ { "content": "/// Re-create the MPU from a SPI peripheral and an MPU `Handle`\n\n///\n\n/// Caller is reponsible for matching the peripheral to the handle.\n\n/// Otherwise, we might be using the wrong handle for a different\n\n/// physical MPU.\n\npub fn from_handle<S>(spi: S, handle: Handle) -> Mpu<Spi<S>>\n\...
Rust
src/main.rs
cdecompilador/rlcount
32606eb33f7bd7e0e080155b0540e5b46ac8b628
use std::fmt; use std::io; use std::path::{Path, PathBuf}; use clap::{App, Arg}; use rayon::prelude::*; use walkdir::{DirEntry, WalkDir}; mod parser; use parser::parse_file; fn get_language_name<'a>(extension: &'a str) -> &'a str { match extension { "rs" => "Rust", ...
use std::fmt; use std::io; use std::path::{Path, PathBuf}; use clap::{App, Arg}; use rayon::prelude::*; use walkdir::{DirEntry, WalkDir}; mod parser; use parser::parse_file; fn get_language_name<'a>(extension: &'a str) -> &'a str { match extension { "rs" => "Rust", ...
pub fn push(&mut self, lang_name: &str, lines: usize) -> Option<()> { if self .lines_per_language .iter() .any(|(lang, _)| lang_name == lang) { let (_, l) = self .lines_per_language .iter_mut() ...
jectData { lines_per_language: Vec::with_capacity(8), total_lines: 0, name: name.to_owned(), percentage_per_language: Vec::with_capacity(8), } }
function_block-function_prefixed
[ { "content": "/// Given an `input` and an `extension` (to match the kind of file to parse),\n\n/// it returns the lines of code of that file, if not capable of parsing it\n\n/// (not implemneted a parser yet) it counts 0\n\nfn lines_of_code(input: String, extension: &str) -> usize {\n\n if let Some(ltor) = l...
Rust
src/spacework/workspace.rs
m-rsha/spacework
323a5c7cedf4dfbb9fb1f3ba0195e368c5f1904e
use crate::config::languagefile::LanguageFile; use crate::config::spaceworkfile::SpaceworkFile; use crate::spacework::history::History; use std::env::{self, VarError}; use std::error::Error; use std::fs::{self, File}; use std::io::{ErrorKind, Write}; use std::path::{Path, PathBuf}; use std::process::Output; use std::s...
use crate::config::languagefile::LanguageFile; use crate::config::spaceworkfile::SpaceworkFile; use crate::spacework::history::History; use std::env::{self, VarError}; use std::error::Error; use std::fs::{self, File}; use std::io::{ErrorKind, Write}; use std::path::{Path, PathBuf}; use std::process::Output; use std::s...
fn create_subdirs( proj_dir: &Path, ) -> Result<(PathBuf, PathBuf), Box<dyn Error>> { let src_dir = proj_dir.join("src"); fs::create_dir_all(&src_dir)?; let bin_dir = proj_dir.join("bin"); fs::create_dir_all(&bin_dir)?; Ok((src_dir, bin_dir)) } pub fn build() -> Result<Output, Box<dyn Error...
guageFile, ) -> Result<(), Box<dyn Error>> { Ok(File::create(src_dir.join(&langfile.workspace.src))? .write_all(langfile.template()?.as_bytes())?) }
function_block-function_prefixed
[ { "content": "pub fn delete_history_file() -> Result<(), Box<dyn Error>> {\n\n History::new()?.delete_history_file()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n // use super::*;\n\n\n\n #[test]\n\n fn todo() {\n\n assert!(true);\n\n }\n\n}\n", "file_path": "src/spacework/history.rs", ...
Rust
rust/sbp/src/messages/orientation.rs
zk20/libsbp
041c5055f5db422258ebb3ce3f8e9f6e5d3e5fa9
#[allow(unused_imports)] use std::convert::TryFrom; #[allow(unused_imports)] use byteorder::{LittleEndian, ReadBytesExt}; #[allow(unused_imports)] use crate::serialize::SbpSerialize; #[allow(unused_imports)] use crate::SbpString; #[cfg_attr(feature = "sbp_serde", derive(serde::Serialize))] #[derive(Debug, Clone)] ...
#[allow(unused_imports)] use std::convert::TryFrom; #[allow(unused_imports)] use byteorder::{LittleEndian, ReadBytesExt}; #[allow(unused_imports)] use crate::serialize::SbpSerialize; #[allow(unused_imports)] use crate::SbpString; #[cfg_attr(feature = "sbp_serde", derive(serde::Serialize))] #[derive(Debug, Clone)] ...
} impl super::ConcreteMessage for MsgBaselineHeading { const MESSAGE_TYPE: u16 = 527; const MESSAGE_NAME: &'static str = "MSG_BASELINE_HEADING"; } impl TryFrom<super::SBP> for MsgBaselineHeading { type Error = super::TryFromSBPError; fn try_from(msg: super::SBP) -> Result<Self, Self::Error> { ...
fn gps_time( &self, ) -> Option<std::result::Result<crate::time::MessageTime, crate::time::GpsTimeError>> { let tow_s = (self.tow as f64) / 1000.0; let gps_time = match crate::time::GpsTime::new(0, tow_s) { Ok(gps_time) => gps_time.tow(), Err(e) => return Some(Err(e.i...
function_block-full_function
[ { "content": "pub fn read_u16_array_limit(buf: &mut &[u8], n: usize) -> Result<Vec<u16>> {\n\n let mut v = Vec::new();\n\n for _ in 0..n {\n\n v.push(buf.read_u16::<LittleEndian>()?);\n\n }\n\n Ok(v)\n\n}\n\n\n", "file_path": "rust/sbp/src/parser.rs", "rank": 0, "score": 477523.33...
Rust
crates/swift-bridge-ir/src/parse/parse_extern_mod/opaque_type_attributes.rs
chinedufn/swift-bridge
91b480250a59fee392b6f74c75682e4ee871bd99
use crate::parse::OpaqueCopy; use proc_macro2::Ident; use quote::ToTokens; use std::ops::Deref; use syn::parse::{Parse, ParseStream}; use syn::{Attribute, LitInt, Meta}; #[derive(Default, Clone)] pub(crate) struct OpaqueTypeAllAttributes { pub swift_bridge: OpaqueTypeSwiftBridgeAttributes, #[allow(un...
use crate::parse::OpaqueCopy; use proc_macro2::Ident; use quote::ToTokens; use std::ops::Deref; use syn::parse::{Parse, ParseStream}; use syn::{Attribute, LitInt, Meta}; #[derive(Default, Clone)] pub(crate) struct OpaqueTypeAllAttributes { pub swift_bridge: OpaqueTypeSwiftBridgeAttributes, #[allow(un...
} impl OpaqueTypeSwiftBridgeAttributes { pub(super) fn store_attrib(&mut self, attrib: OpaqueTypeAttr) { match attrib { OpaqueTypeAttr::AlreadyDeclared => self.already_declared = true, OpaqueTypeAttr::Copy { size } => self.copy = Some(OpaqueCopy { size_bytes: size }), O...
pub(super) fn from_attributes(attribs: &[Attribute]) -> Result<Self, syn::Error> { let mut attributes = OpaqueTypeAllAttributes::default(); for attr in attribs.iter() { let attribute_name = attr.path.to_token_stream().to_string(); match attribute_name.as_str() { ...
function_block-full_function
[ { "content": "#[doc(hidden)]\n\npub fn assert_copy<T: Copy>() {}\n", "file_path": "src/lib.rs", "rank": 0, "score": 135927.73436634958 }, { "content": "#[doc(hidden)]\n\npub trait SharedStruct {\n\n /// The FFI friendly representation of this struct.\n\n ///\n\n /// ```\n\n /// s...
Rust
src/tree.rs
Kiiyya/memory_spider
af0ce99b2869841de06a3579916b7c6ff620bb86
use std::{marker::PhantomData, mem::size_of, rc::Rc, rc::Weak}; use crate::{Error, Get, Result, arch::Arch}; pub trait GetAddress<A: Arch> { fn get_address(&self) -> Result<A::Pointer>; } pub trait Parent<A: Arch> : GetAddress<A> { fn root(&self) -> Result<Weak<dyn Root<A>>>; } pub trait Root...
use std::{marker::PhantomData, mem::size_of, rc::Rc, rc::Weak}; use crate::{Error, Get, Result, arch::Arch}; pub trait GetAddress<A: Arch> { fn get_address(&self) -> Result<A::Pointer>; } pub trait Parent<A: Arch> : GetAddress<A> { fn root(&self) -> Result<Weak<dyn Root<A>>>; } pub trait Root...
} impl<A: Arch, T: Sized> Parent<A> for Value<A, T> { fn root(&self) -> Result<Weak<dyn Root<A>>> { self.parent.upgrade().unwrap().root() } } impl <A, T> Get<A> for Value<A, T> where A: Arch, T: Sized + Copy, [(); std::mem::size_of::<T>...
fn get_address(&self) -> Result<A::Pointer> { if let Some(s) = self.parent.upgrade() { Ok(s.get_address()? + self.offset) } else { panic!() } }
function_block-full_function
[ { "content": "pub trait Get<A: Arch> {\n\n type T;\n\n // type Res = Result<Rc<Self::T>>;\n\n fn get(&self) -> Result<Self::T>;\n\n}\n\n\n\n\n\n////////////////////////////////////////////////////////////////////\n\n////////////////////////////////////////////////////////////////////\n\n\n", "file_...
Rust
core-contracts/staking-pool-factory/src/lib.rs
DaviRain-Su/learn-near
5c4e59585ae2b2b7a61dc8c102e98f7913d3d568
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::UnorderedSet; use near_sdk::json_types::{Base58PublicKey, U128}; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::{env, ext_contract, near_bindgen, AccountId, Balance, Promise, PromiseOrValue}; mod utils; use crate::u...
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::UnorderedSet; use near_sdk::json_types::{Base58PublicKey, U128}; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::{env, ext_contract, near_bindgen, AccountId, Balance, Promise, PromiseOrValue}; mod utils; use crate::u...
testing_env!(context.clone()); let mut contract = StakingPoolFactory::new(account_whitelist()); context.is_view = true; testing_env!(context.clone()); assert_eq!(contract.get_min_attached_balance().0, MIN_ATTACHED_BALANCE); assert_eq!(contract.get_number_of_st...
let mut context = VMContextBuilder::new() .current_account_id(account_factory()) .predecessor_account_id(account_near()) .finish();
assignment_statement
[ { "content": "pub fn owner() -> AccountId {\n\n \"owner\".to_string()\n\n}\n\n\n", "file_path": "core-contracts/staking-pool/src/test_utils.rs", "rank": 0, "score": 475849.7927271097 }, { "content": "pub fn account_pool_owner() -> AccountId {\n\n \"pool-owner\".to_string()\n\n}\n\n\n",...
Rust
src/date.rs
19h/extrablatt
ab16dc3bd9f0e5a13ac12ad4289b3b69d31709da
use std::collections::HashMap; use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; use regex::Regex; use select::document::Document; use select::predicate::{Attr, Name, Predicate, Text}; #[cfg(feature = "serde0")] use serde::{Deserialize, Serialize}; use lazy_static::lazy_static; use crate::extract::NodeValueQuery;...
use std::collections::HashMap; use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; use regex::Regex; use select::document::Document; use select::predicate::{Attr, Name, Predicate, Text}; #[cfg(feature = "serde0")] use serde::{Deserialize, Serialize}; use lazy_static::lazy_static; use crate::extract::NodeValueQuery;...
ified":"2019-12-05T15:34:34+0100""#) .unwrap(); assert_eq!( caps.name("date").unwrap().as_str(), "2019-12-05T15:34:34+0100" ) } #[test] fn publish_modified() { let caps = RE_KEY_VALUE_PUBLISH_DATE .captures(r#""datePublished":"2019-12-...
.name("date") .and_then(|m| DateExtractor::fuzzy_dtparse(m.as_str())) } else { None } }) .next() } fn fuzzy_dtparse(s: &str) -> Option<NaiveDateTime> { let mut tzinfod = HashMap::new(); tzin...
random
[ { "content": "/// Extracts the name valuable author text and ignores hidden content\n\npub fn author_text(node: Node) -> String {\n\n if Name(\"meta\").matches(&node) {\n\n return node\n\n .attr(\"content\")\n\n .map(str::to_string)\n\n .unwrap_or_else(String::new);\n\...
Rust
src/read/index.rs
SOF3/phar.rs
ceb4035732d05322447bb20a23f97624a91708b6
use std::collections::{BTreeMap, HashMap}; use std::io::{Read, Result, Seek, SeekFrom}; use std::iter::{self, Extend}; use std::ops::Range; use super::{Entry, Section}; use crate::Compression; pub trait FileIndex: Default { fn scan_files() -> bool { true } fn requires_name() -> bool {...
use std::collections::{BTreeMap, HashMap}; use std::io::{Read, Result, Seek, SeekFrom}; use std::iter::{self, Extend}; use std::ops::Range; use super::{Entry, Section}; use crate::Compression; pub trait FileIndex: Default { fn scan_files() -> bool { true } fn requires_name() -> bool {...
} #[derive(Debug, Default)] pub struct NameMap<M> { map: M, last_offset: u64, content_offset: u64, } impl<M: Default + Extend<(Vec<u8>, (u32, Range<u64>))>> FileIndex for NameMap<M> where for<'t> &'t M: IntoIterator<Item = (&'t Vec<u8>, &'t (u32, Range<u64>))>, { fn requires_name() -> bool { ...
F: FnMut(&[u8], &mut (dyn Read)) -> Result<U>, G: FnMut(Option<T>, U) -> T, { let mut start_offset = self.content_offset; let mut reduced = None; for OffsetOnlyEntry { name, flags, end_offset_from_co, } in &self.entries { ...
function_block-function_prefix_line
[ { "content": "pub fn tell(mut seek: impl Seek) -> io::Result<u64> {\n\n seek.seek(SeekFrom::Current(0))\n\n}\n", "file_path": "src/util.rs", "rank": 0, "score": 219831.8127864679 }, { "content": "pub fn read_find_bstr(file: &mut impl Read, buf: &mut Section, bstr: &[u8]) -> Result<()> {\n...
Rust
src/endpoints/gitignore.rs
llde/roctogen
3b4636f090838de53d6bfbea1bc82de6d7bd1bb2
#![allow( unused_imports, )] /* * GitHub v3 REST API * * GitHub's v3 REST API. * * OpenAPI spec version: 1.1.4 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ use serde::Deserialize; use crate::adapters::{AdapterError, FromJson, GitHubRequest, GitHubRequestBuilder, GitHubRespons...
#![allow( unused_imports, )] /* * GitHub v3 REST API * * GitHub's v3 REST API. * * OpenAPI spec version: 1.1.4 * * Generated by: https://github.com/swagger-api/swagge
e)] Generic { code: u16 }, } #[derive(Debug, thiserror::Error)] pub enum GitignoreGetTemplateError { #[error(transparent)] AdapterError(#[from] AdapterError), #[error(transparent)] SerdeJson(#[from] serde_json::Error), #[error(transparent)] SerdeUrl(#[from] serde_urlencoded::ser::Error), ...
r-codegen.git */ use serde::Deserialize; use crate::adapters::{AdapterError, FromJson, GitHubRequest, GitHubRequestBuilder, GitHubResponseExt}; use crate::auth::Auth; use crate::models::*; use super::PerPage; use std::collections::HashMap; use serde_json::value::Value; pub struct Gitignore<'api> { auth: &'api...
random
[ { "content": " protected String apiVersion = \"1.0.0\";\n", "file_path": "java/github/RustServerCodegen.java", "rank": 0, "score": 99139.0333549089 }, { "content": " protected String packageVersion;\n", "file_path": "java/github/RustServerCodegen.java", "rank": 1, "score": ...
Rust
src/lib/visualizer.rs
ShamylZakariya/Cutlist
7e532f6cd883464c8d822b7bfe65a6ecfe2dc141
use macroquad::prelude::*; use super::solver; const PADDING: f32 = 10f32; const FONT_SIZE: f32 = 16f32; const BOARD_COLOR: Color = Color::new(0f32, 0f32, 0f32, 0.1); const BOARD_STROKE_COLOR: Color = Color::new(0f32, 0f32, 0f32, 0.2); const CUT_COLOR: Color = Color::new(0.5f32, 0.5f32, 0.5f32, 1f32); const CUT_STROK...
use macroquad::prelude::*; use super::solver; const PADDING: f32 = 10f32; const FONT_SIZE: f32 = 16f32; const BOARD_COLOR: Color = Color::new(0f32, 0f32, 0f32, 0.1); const BOARD_STROKE_COLOR: Color = Color::new(0f32, 0f32, 0f32, 0.2); const CUT_COLOR: Color = Color::new(0.5f32, 0.5f32, 0.5f32, 1f32); const CUT_STROK...
fn render_board(board: &solver::Board, top_left: Vec2, scale: f32) -> Vec<Label> { let mut labels = Vec::new(); draw_rectangle_scaled( top_left, Vec2::new(board.length, board.width), scale, BOARD_COLOR, BOARD_STROKE_COLOR, ); labels.push(Label { te...
start.x * scale, start.y * scale, end.x * scale, end.y * scale, 1f32, color, ); }
function_block-function_prefix_line
[ { "content": "fn f32_eq(a: f32, b: f32) -> bool {\n\n (a - b).abs() < 1e-4\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Board {\n\n pub width: f32,\n\n pub length: f32,\n\n pub id: String,\n\n}\n\n\n\nimpl PartialEq for Board {\n\n fn eq(&self, other: &Self) -> bool {\n\n f32_eq(self....
Rust
anni-repo/src/models/tag.rs
ProjectAnni/anni
e9f3df5159fb7d26a9b327f62aa717aa1b6e5a73
use std::fmt::{Display, Formatter}; use std::hash::{Hash, Hasher}; use serde::{Serialize, Deserialize, Serializer, Deserializer}; use toml::Value; #[derive(Debug, Eq)] pub enum RepoTag { Ref(TagRef), Full(Tag), } impl Hash for RepoTag { fn hash<H: Hasher>(&self, state: &mut H) { match self { ...
use std::fmt::{Display, Formatter}; use std::hash::{Hash, Hasher}; use serde::{Serialize, Deserialize, Serializer, Deserializer}; use toml::Value; #[derive(Debug, Eq)] pub enum RepoTag { Ref(TagRef), Full(Tag), } impl Hash for RepoTag { fn hash<H: Hasher>(&self, state: &mut H) { match self { ...
} impl RepoTag { pub fn get_ref(&self) -> TagRef { match self { RepoTag::Ref(r) => r.clone(), RepoTag::Full(t) => t.get_ref(), } } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct TagRef(String); impl TagRef { pub fn name(&self) -> &str { self.0.as...
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { RepoTag::Ref(r) => write!(f, "{}", r), RepoTag::Full(t) => write!(f, "{}", t), } }
function_block-full_function
[ { "content": "pub fn walk_path<P: AsRef<Path>>(path: P, recursive: bool, callback: impl Fn(&Path) -> bool) -> io::Result<()> {\n\n let _ = fs_walk_path(path, recursive, &callback)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "anni-common/src/fs.rs", "rank": 0, "score": 176710.38025953685 }, { ...
Rust
imxrt1062-pac/imxrt1062-pmu/src/reg_1p1_set.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register REG_1P1_SET"] pub type R = crate::R<u32, super::REG_1P1_SET>; #[doc = "Writer for register REG_1P1_SET"] pub type W = crate::W<u32, super::REG_1P1_SET>; #[doc = "Register REG_1P1_SET `reset()`'s with value 0x1073"] impl crate::ResetValue for super::REG_1P1_SET { type Type = u32; #[in...
#[doc = "Reader of register REG_1P1_SET"] pub type R = crate::R<u32, super::REG_1P1_SET>; #[doc = "Writer for register REG_1P1_SET"] pub type W = crate::W<u32, super::REG_1P1_SET>; #[doc = "Register REG_1P1_SET `reset()`'s with value 0x1073"] impl crate::ResetValue for super::REG_1P1_SET { type Type = u32; #[in...
#[doc = "Checks if the value of the field is `OUTPUT_TRG_4`"] #[inline(always)] pub fn is_output_trg_4(&self) -> bool { *self == OUTPUT_TRG_A::OUTPUT_TRG_4 } #[doc = "Checks if the value of the field is `OUTPUT_TRG_16`"] #[inline(always)] pub fn is_output_trg_16(&self) -> bool { ...
pub fn variant(&self) -> crate::Variant<u8, OUTPUT_TRG_A> { use crate::Variant::*; match self.bits { 4 => Val(OUTPUT_TRG_A::OUTPUT_TRG_4), 16 => Val(OUTPUT_TRG_A::OUTPUT_TRG_16), i => Res(i), } }
function_block-full_function
[ { "content": "/// Migrate the `lib.rs` of the PAC subscrate, adding\n\n/// our necessary header to the top of the file.\n\nfn write_lib<R: Read>(crate_path: &Path, mut src: R) {\n\n static LIB_PRELUDE: &str = r#\"#![deny(warnings)]\n\n#![allow(non_camel_case_types)]\n\n#![allow(clippy::all)]\n\n#![no_std]\n\...
Rust
tonic/src/service/interceptor.rs
xoac/tonic
6763d191d267c1b9f861b96ad0f4b850e0264f4d
use crate::{ body::{boxed, BoxBody}, request::SanitizeHeaders, Status, }; use bytes::Bytes; use pin_project::pin_project; use std::{ fmt, future::Future, pin::Pin, task::{Context, Poll}, }; use tower_layer::Layer; use tower_service::Service; pub trait Interceptor { fn call(&mut s...
use crate::{ body::{boxed, BoxBody}, request::SanitizeHeaders, Status, }; use bytes::Bytes; use pin_project::pin_project; use std::{ fmt, future::Future, pin::Pin, task::{Context, Poll}, }; use tower_layer::Layer; use tower_service::Service; pub trait Interceptor { fn call(&mut s...
}
c { Ok::<_, Status>(http::Response::new(TestBody)) }); let svc = InterceptedService::new(svc, |_: crate::Request<()>| { Err(Status::permission_denied(message)) }); let request = http::Request::builder().body(TestBody).unwrap(); let response = svc.oneshot...
function_block-function_prefixed
[ { "content": "type BoxFuture<T, E> = Pin<Box<dyn Future<Output = std::result::Result<T, E>> + Send + 'static>>;\n\n\n\n#[tonic::async_trait]\n\nimpl pb::test_service_server::TestService for TestService {\n\n async fn empty_call(&self, _request: Request<Empty>) -> Result<Empty> {\n\n Ok(Response::new(E...
Rust
tetris-analyser/src/main.rs
cdubz/mos6502
d88ad4deb8bc55ecba72d833ec05eafb76eb3807
use gif_renderer::{Frame as GifFrame, Renderer as GifRenderer}; use ines::Ines; use mos6502_model::debug::{InstructionType, InstructionWithOperand}; use mos6502_model::machine::{Address, Cpu, Memory, MemoryReadOnly}; use nes_emulator_core::{dynamic_nes::DynamicNes, nes::RunForCycles}; use nes_render_output::NoRenderOut...
use gif_renderer::{Frame as GifFrame, Renderer as GifRenderer}; use ines::Ines; use mos6502_model::debug::{InstructionType, InstructionWithOperand}; use mos6502_model::machine::{Address, Cpu, Memory, MemoryReadOnly}; use nes_emulator_core::{dynamic_nes::DynamicNes, nes::RunForCycles}; use nes_render_output::NoRenderOut...
wrap(); } } { for i in 0..256 { let byte = nes.read_u8_read_only(0x8A9C + i); println!("{:X}", byte); } } }
::parser().with_help_default().parse_env_or_exit(); let ines = ines_from_file(args.rom_path.as_str()); let mut nes = DynamicNes::from_ines(&ines).unwrap(); let mut trace_run = TraceRun::new(); start_game(&mut nes, 0, &mut trace_run); let mut renderer = GifRenderer::new(File::create(args.gif_path.as_...
random
[]
Rust
src/bin/main.rs
andylokandy/elba
e8258722f8744604b310afce85f8615ca6f0c2a5
#![allow(unused_variables, dead_code)] #[macro_use] extern crate clap; extern crate elba; #[macro_use] extern crate failure; extern crate toml; #[macro_use] extern crate slog; extern crate slog_term; mod cmds; use clap::{App, AppSettings, Arg, ArgMatches}; use elba::util::config::{Config, Verbosity}; use failure::E...
#![allow(unused_variables, dead_code)] #[macro_use] extern crate clap; extern crate elba; #[macro_use] extern crate failure; extern crate toml; #[macro_use] extern crate slog; extern crate slog_term; mod cmds; use clap::{App, AppSettings, Arg, ArgMatches}; use elba::util::config::{Config, Verbosity}; use failure::E...
fn go() -> Result<(), Error> { let args = cli().get_matches(); let mut config = Config::default(); let args = expand_aliases(&mut config, args)?; let verbosity = if args.is_present("verbose") { Some(Verbosity::Verbose) } else if args.is_present("quiet") { Some(Verbosity::Quie...
fn expand_aliases( config: &mut Config, args: ArgMatches<'static>, ) -> Result<ArgMatches<'static>, Error> { if let (cmd, Some(args)) = args.subcommand() { match (cmds::execute_internal(cmd), unalias(config, cmd)) { (None, Some(alias)) => { let mut vec = vec![alias]; ...
function_block-full_function
[ { "content": "fn retriever(root: Summary) -> Retriever<'static> {\n\n let mut ixs = indices();\n\n\n\n let root_deps = ixs\n\n .select(&root)\n\n .unwrap()\n\n .dependencies\n\n .iter()\n\n .cloned()\n\n .map(|d| (PackageId::new(d.name, Resolution::Index(d.index))...
Rust
embassy-stm32/src/rcc/g0/mod.rs
mryndzionek/embassy
1650983e463e5f237d68957b0de1537f807cbc63
pub use super::types::*; use crate::pac; use crate::peripherals::{self, RCC}; use crate::rcc::{get_freqs, set_freqs, Clocks}; use crate::time::Hertz; use crate::time::U32Ext; use core::marker::PhantomData; use embassy::util::Unborrow; use embassy_hal_common::unborrow; pub const HSI_FREQ: u32 = 16_000_000; pub const L...
pub use super::types::*; use crate::pac; use crate::peripherals::{self, RCC}; use crate::rcc::{get_freqs, set_freqs, Clocks}; use crate::time::Hertz; use crate::time::U32Ext; use core::marker::PhantomData; use embassy::util::Unborrow; use embassy_hal_common::unborrow; pub const HSI_FREQ: u32 = 16_000_000; pub const L...
} pub unsafe fn init(config: Config) { let r = <peripherals::RCC as embassy::util::Steal>::steal(); let clocks = r.freeze(config); set_freqs(clocks); }
rcc.cr().read().hserdy() {} } (freq.0, 0x01) } ClockSrc::LSI => { unsafe { rcc.csr().write(|w| w.set_lsion(true)); while !rcc.csr().read().lsirdy() {} } (LSI_...
function_block-function_prefixed
[ { "content": "/// Low power blocking wait loop using WFE/SEV.\n\npub fn low_power_wait_until(mut condition: impl FnMut() -> bool) {\n\n while !condition() {\n\n // WFE might \"eat\" an event that would have otherwise woken the executor.\n\n cortex_m::asm::wfe();\n\n }\n\n // Retrigger an ...
Rust
src/lib.rs
jawid-h/rust-rocksdb
81a9edea83473012378e808606cdd92c1212c076
#![warn(clippy::pedantic)] #![allow( clippy::cast_possible_wrap, clippy::cast_possible_truncation, clippy::cast_sign_loss, clippy::module_name_repetitions, clippy::similar_names, clippy::must_use_candidate, clippy::pub_enum_variant_names, clippy::indexing_slicing, clippy::missi...
#![warn(clippy::pedantic)] #![allow( clippy::cast_possible_wrap, clippy::cast_possible_truncation, clippy::cast_sign_loss, clippy::module_name_repetitions, clippy::similar_names, clippy::must_use_candidate, clippy::pub_enum_variant_names, clippy::indexing_slicing, clippy::missi...
}
t>(); is_sync::<Options>(); is_sync::<ReadOptions>(); is_sync::<WriteOptions>(); is_sync::<IngestExternalFileOptions>(); is_sync::<BlockBasedOptions>(); is_sync::<PlainTableFactoryOptions>(); is_sync::<ColumnFamilyDescriptor>(); is_sync::<SstFileWriter>();...
function_block-function_prefixed
[ { "content": "fn convert_options(opts: &[(&str, &str)]) -> Result<Vec<(CString, CString)>, Error> {\n\n opts.iter()\n\n .map(|(name, value)| {\n\n let cname = match CString::new(name.as_bytes()) {\n\n Ok(cname) => cname,\n\n Err(e) => return Err(Error::new(form...
Rust
src/spim0.rs
cvetaevvitaliy/nrf52840-pac
bf07243a5a043883d915999f0f8ccd6cbf6229b8
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 16usize], #[doc = "0x10 - Start SPI transaction"] pub tasks_start: TASKS_START, #[doc = "0x14 - Stop SPI transaction"] pub tasks_stop: TASKS_STOP, _reserved1: [u8; 4usize], #[doc = "0x1c - Suspend SPI transact...
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 16usize], #[doc = "0x10 - Start SPI transaction"] pub tasks_start: TASKS_START, #[doc = "0x14 - Stop SPI transaction"] pub tasks_stop: TASKS_STOP, _reserved1: [u8; 4usize], #[doc = "0x1c - Suspend SPI transact...
nsaction started"] pub mod events_started; #[doc = "Shortcut register"] pub struct SHORTS { register: ::vcell::VolatileCell<u32>, } #[doc = "Shortcut register"] pub mod shorts; #[doc = "Enable interrupt"] pub struct INTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable interrupt"] pub mod intenset;...
fer reached"] pub mod events_endtx; #[doc = "Transaction started"] pub struct EVENTS_STARTED { register: ::vcell::VolatileCell<u32>, } #[doc = "Tra
random
[ { "content": " #[doc = r\" Writes raw bits to the field\"]\n\n #[inline]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n const MASK: u8 = 7;\n\n const OFFSET: u8 = 0;\n\n self.w.bits &= !((MASK as u32) << OFFSET);\n\n self.w.bits |= ((value & MASK) as u32) << OFFS...
Rust
examples/counter_reactive.rs
geom3trik/tuix
c1e5979cddd18f4afd4124c336fc95331004e4bf
use tuix::*; use tuix::widgets::*; const STYLE: &str = r#" button { border-radius: 3px; child-space: 1s; } button.increment { background-color: #2e7d32; border-radius: 3px; } button.increment:hover { background-color: #60ad5e; } button.increment:ac...
use tuix::*; use tuix::widgets::*; const STYLE: &str = r#" button { border-radius: 3px; child-space: 1s; } button.increment { background-color: #2e7d32; border-radius: 3px; } button.increment:hover { background-color: #60ad5e; } button.increment:ac...
} } #[derive(Default)] struct Counter { label: Entity, } impl Widget for Counter { type Ret = Entity; type Data = i32; fn on_build(&mut self, state: &mut State, entity: Entity) -> Self::Ret { let row = Row::new().build(state, entity, |builder| builder .set_...
if let Some(counter_event) = event.message.downcast() { match counter_event { CounterEvent::Increment => { self.value += 1; entity.emit(state, BindEvent::Update); } CounterEvent::Decrement => { self....
if_condition
[ { "content": "pub fn apply_styles(state: &mut State, tree: &Tree) {\n\n //println!(\"RESTYLE\");\n\n // Loop through all entities\n\n for entity in tree.into_iter() {\n\n // Skip the root\n\n if entity == Entity::root() {\n\n continue;\n\n }\n\n\n\n // Create a li...
Rust
witchcraft-metrics/src/meter.rs
svc-excavator-bot-org/witchcraft-rust-logging
05c3b5dc0009fe37b2e72624ca4ebc02775b8ec0
use crate::Clock; use parking_lot::Mutex; use std::convert::TryFrom; use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; use std::sync::Arc; use std::time::Instant; const INTERVAL_SECS: u64 = 5; const SECONDS_PER_MINUTE: f64 = 60.; struct State { count: i64, rate_1m: Ewma, rate_5m: Ewma, rate_1...
use crate::Clock; use parking_lot::Mutex; use std::convert::TryFrom; use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; use std::sync::Arc; use std::time::Instant; const INTERVAL_SECS: u64 = 5; const SECONDS_PER_MINUTE: f64 = 60.; struct State { count: i64, rate_1m: Ewma, rate_5m: Ewma, rate_1...
fn tick(&mut self, count: i64) { let instant_rate = count as f64 / INTERVAL_SECS as f64; if self.initialized { self.rate += self.alpha * (instant_rate - self.rate); } else { self.rate = instant_rate; self.initialized = true; } } ...
alpha: 1. - (-(INTERVAL_SECS as f64) / SECONDS_PER_MINUTE / minutes).exp(), initialized: false, } }
function_block-function_prefix_line
[ { "content": "pub fn enabled(level: Level, target: &str) -> bool {\n\n crate::logger().enabled(&Metadata::builder().level(level).target(target).build())\n\n}\n", "file_path": "witchcraft-log/src/private.rs", "rank": 2, "score": 103860.2556999997 }, { "content": "/// A source of monotonic ...
Rust
day_04/src/main.rs
Stefan99353/advent-of-code-2020
1a2677436dfd0d4c8e518038846869ddef983ab6
use std::fs::File; use std::io::Read; use std::str::FromStr; use anyhow::Result; use regex::Regex; const DAY: &str = "04"; fn main() -> Result<()> { println!("----- Advent of Code -- Day {} -----", DAY); println!("--------------------------------------"); println!(); let mut input_file = File::ope...
use std::fs::File; use std::io::Read; use std::str::FromStr; use anyhow::Result; use regex::Regex; const DAY: &str = "04"; fn main() -> Result<()> { println!("----- Advent of Code -- Day {} -----", DAY); println!("--------------------------------------"); println!(); let mut input_file = File::ope...
&& self.ecl.is_some() && self.pid.is_some() } pub fn validate_part_2(&self) -> Result<bool> { let regex_hgt = Regex::new(r"^((1[5-8]\dcm)|(19[0-3]cm)|(59in)|(6\din)|(7[0-6]in))$")?; let regex_hcl = Regex::new(r"^#[\da-f]{6}$")?; let regex_ecl = Regex::new(r"^((amb)|(blu)|(brn)|(gry)|(gr...
eyr: None, hgt: None, hcl: None, ecl: None, pid: None, cid: None, } } pub fn validate_part_1(&self) -> bool { self.byr.is_some() && self.iyr.is_some() && self.eyr.is_some() && self.hgt.is_some() && self.hcl.is_some()
random
[ { "content": "/// Reads input as lines, where every line is parsed to given type.\n\npub fn input_iter<T, Input>(input: Input) -> impl Iterator<Item=Result<T>>\n\n where\n\n T: FromStr,\n\n T::Err: Into<Error>,\n\n Input: io::BufRead,\n\n{\n\n input\n\n .lines()\n\n .map...
Rust
compiler/crates/schema-print/src/lib.rs
SeshanPillay25/relay
5d2f08fb6ac81fff44c4f202aae0011087bfff33
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use itertools::Itertools; use schema::*; use std::collections::BTreeMap; use std::fmt::{Result, Write}; pub fn print(schema: &Sche...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use itertools::Itertools; use schema::*; use std::collections::BTreeMap; use std::fmt::{Result, Write}; pub fn print(schema: &Sche...
fn print_type(&mut self, type_: &Type) -> Result { match type_ { Type::Enum(id) => self.print_enum(*id), Type::InputObject(id) => self.print_input_object(*id), Type::Interface(id) => self.print_interface(*id), Type::Object(id) => self.print_object(*id), ...
fn print_types(&mut self) -> Result { let ordered_type_map = self.schema.get_type_map().collect::<BTreeMap<_, _>>(); for (_key, value) in ordered_type_map.iter() { self.print_type(&value)?; } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn write_value(schema: &Schema, value: &Value, mut result: &mut impl Write) -> Result {\n\n let mut printer = Printer::new(&schema, &mut result);\n\n printer.print_value(value)\n\n}\n\n\n", "file_path": "compiler/crates/graphql-text-printer/src/print_to_text.rs", "rank": 3, "...
Rust
src/libstd/sys/vxworks/thread.rs
Kinrany/rust
95b1fe560d2bd8472f250fb8cfd2168520a58405
use crate::cmp; use crate::ffi::CStr; use crate::io; use crate::mem; use crate::ptr; use crate::sys::os; use crate::time::Duration; use crate::sys_common::thread::*; #[cfg(not(target_os = "l4re"))] pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024; #[cfg(target_os = "l4re")] pub const DEFAULT_MIN_STACK_SIZE:...
use crate::cmp; use crate::ffi::CStr; use crate::io; use crate::mem; use crate::ptr; use crate::sys::os; use crate::time::Duration; use crate::sys_common::thread::*; #[cfg(not(target_os = "l4re"))] pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024; #[cfg(target_os = "l4re")] pub const DEFAULT_MIN_STACK_SIZE:...
#[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))] fn min_stack_size(_: *const libc::pthread_attr_t) -> usize { libc::PTHREAD_STACK_MIN } #[cfg(target_os = "netbsd")] fn min_stack_size(_: *const libc::pthread_attr_t) -> usize { 2048 }
match __pthread_get_minstack.get() { None => libc::PTHREAD_STACK_MIN, Some(f) => unsafe { f(attr) }, } }
function_block-function_prefix_line
[]
Rust
src/wayland/compositor/handlers.rs
schickst/smithay
c136cd5f34d5eeac7150b08b253e27c8241a051e
use std::{ cell::RefCell, ops::Deref as _, rc::Rc, sync::{ atomic::{AtomicBool, Ordering}, Mutex, }, }; use wayland_server::{ protocol::{wl_compositor, wl_region, wl_subcompositor, wl_subsurface, wl_surface}, DispatchData, Filter, Main, }; use crate::utils::{Logical, Point}...
use std::{ cell::RefCell, ops::Deref as _, rc::Rc, sync::{ atomic::{AtomicBool, Ordering}, Mutex, }, }; use wayland_server::{ protocol::{wl_compositor, wl_region, wl_subcompositor, wl_subsurface, wl_surface}, DispatchData, Filter, Main, }; use crate::utils::{Logical, Point}...
/* * wl_subcompositor */ pub(crate) fn implement_subcompositor( subcompositor: Main<wl_subcompositor::WlSubcompositor>, ) -> wl_subcompositor::WlSubcompositor { subcompositor.quick_assign(move |subcompositor, request, _| match request { wl_subcompositor::Request::GetSubsurface { id, surface, parent...
n::WlRegion>) -> wl_region::WlRegion { region.quick_assign(|region, req, _| region_implem(req, region.deref().clone())); region .as_ref() .user_data() .set_threadsafe(|| Mutex::new(RegionAttributes::default())); region.deref().clone() }
function_block-function_prefixed
[ { "content": "/// Retrieve the metadata associated with a `wl_region`\n\n///\n\n/// If the region is not managed by the `CompositorGlobal` that provided this token, this\n\n/// will panic (having more than one compositor is not supported).\n\npub fn get_region_attributes(region: &wl_region::WlRegion) -> RegionA...
Rust
juniper/src/types/nullable.rs
scott-wilson/juniper
46be97ada48dce335d73d04edea41ef89d28a3d1
use crate::{ ast::{FromInputValue, InputValue, Selection, ToInputValue}, executor::{ExecutionResult, Executor, Registry}, schema::meta::MetaType, types::{ async_await::GraphQLValueAsync, base::{GraphQLType, GraphQLValue}, marker::IsInputType, }, value::{ScalarValue, Value...
use crate::{ ast::{FromInputValue, InputValue, Selection, ToInputValue}, executor::{ExecutionResult, Executor, Registry}, schema::meta::MetaType, types::{ async_await::GraphQLValueAsync, base::{GraphQLType, GraphQLValue}, marker::IsInputType, }, value::{ScalarValue, Value...
} impl<S, T> IsInputType<S> for Nullable<T> where T: IsInputType<S>, S: ScalarValue, { }
fn to_input_value(&self) -> InputValue<S> { match *self { Self::Some(ref v) => v.to_input_value(), _ => InputValue::null(), } }
function_block-full_function
[ { "content": "pub fn expect_fails_rule<'a, V, F, S>(factory: F, q: &'a str, expected_errors: &[RuleError])\n\nwhere\n\n S: ScalarValue + 'a,\n\n V: Visitor<'a, S> + 'a,\n\n F: Fn() -> V,\n\n{\n\n expect_fails_rule_with_schema(QueryRoot, MutationRoot, factory, q, expected_errors);\n\n}\n\n\n", "f...
Rust
src/librustrt/local_ptr.rs
Kroisse/rust
5716abe3f019ab7d9c8cdde9879332040191cf88
#![allow(dead_code)] use core::prelude::*; use core::mem; use alloc::owned::Box; #[cfg(windows)] #[cfg(target_os = "android")] #[cfg(target_os = "ios")] pub use self::native::{init, cleanup, put, take, try_take, unsafe_take, exists, unsafe_borrow, try_unsafe_borrow}; #[cfg(n...
#![allow(dead_code)] use core::prelude::*; use core::mem; use alloc::owned::Box; #[cfg(windows)] #[cfg(target_os = "android")] #[cfg(target_os = "ios")] pub use self::native::{init, cleanup, put, take, try_take, unsafe_take, exists, unsafe_borrow, try_unsafe_borrow}; #[cfg(n...
} } pub unsafe fn unsafe_borrow<T>() -> *mut T { let key = tls_key(); let void_ptr = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } void_ptr as *mut T } pub unsafe fn ...
match maybe_tls_key() { Some(key) => tls::get(key).is_not_null(), None => false }
if_condition
[ { "content": "#[allow(experimental)]\n\npub fn init(argc: int, argv: *const *const u8) {\n\n rustrt::init(argc, argv);\n\n unsafe { unwind::register(failure::on_fail); }\n\n}\n\n\n\n/// One-time runtime cleanup.\n\n///\n\n/// This function is unsafe because it performs no checks to ensure that the\n\n/// ...
Rust
pyo3-derive-backend/src/utils.rs
roblabla/pyo3
dcca3f828ca40e02ea6f1af262baaef7e000e7d0
use proc_macro2::Span; use std::fmt::Display; pub fn is_python(ty: &syn::Type) -> bool { match ty { syn::Type::Path(typath) => typath .path .segments .last() .map(|seg| seg.ident == "Python") .unwrap_or(false), _ => false, } } pub fn...
use proc_macro2::Span; use std::fmt::Display; pub fn is_python(ty: &syn::Type) -> bool { match ty { syn::Type::Path(typath) => typath .path .segments .last() .map(|seg| seg.ident == "Python") .unwrap_or(false), _ => false, } } pub fn...
; } else { text_signature = Some(value); } } else { attrs_out.push(attr); } } *attrs = attrs_out; Ok(text_signature) } pub fn get_doc( attrs: &[syn::Attribute], text_signature: Option<syn::LitStr>, null_terminated: bool, ) -> s...
Err(syn::Error::new_spanned( attr, "text_signature attribute already specified previously", ))
call_expression
[ { "content": "pub fn parse_name_attribute(attrs: &mut Vec<syn::Attribute>) -> syn::Result<Option<syn::Ident>> {\n\n let mut name_attrs = Vec::new();\n\n\n\n // Using retain will extract all name attributes from the attribute list\n\n attrs.retain(|attr| match attr.parse_meta() {\n\n Ok(syn::Meta...
Rust
src/sst_file_writer.rs
mina86/rust-rocksdb
953b1a36b5711fb18abab1b1084489d1bc4756f0
use crate::{ffi, ffi_util::to_cpath, Error, Options}; use libc::{self, c_char, size_t}; use std::{ffi::CString, marker::PhantomData, path::Path}; pub struct SstFileWriter<'a> { pub(crate) inner: *mut ffi::rocksdb_sstfilewriter_t, phantom: PhantomData<&'a Options>, } unsafe impl<'a> Send for SstFi...
use crate::{ffi, ffi_util::to_cpath, Error, Options}; use libc::{self, c_char, size_t}; use std::{ffi::CString, marker::PhantomData, path::Path}; pub struct SstFileWriter<'a> { pub(crate) inner: *mut ffi::rocksdb_sstfilewriter_t, phantom: PhantomData<&'a Options>, } unsafe impl<'a> Send for SstFi...
iter_finish(self.inner,)); Ok(()) } } pub fn file_size(&self) -> u64 { let mut file_size: u64 = 0; unsafe { ffi::rocksdb_sstfilewriter_file_size(self.inner, &mut file_size); } file_size } pub fn put<K, V>(&mut self, key: K,...
(()) } } pub fn finish(&mut self) -> Result<(), Error> { unsafe { ffi_try!(ffi::rocksdb_sstfilewr
random
[ { "content": "pub fn opt_bytes_to_ptr<T: AsRef<[u8]>>(opt: Option<T>) -> *const c_char {\n\n match opt {\n\n Some(v) => v.as_ref().as_ptr() as *const c_char,\n\n None => ptr::null(),\n\n }\n\n}\n\n\n\npub(crate) fn to_cpath<P: AsRef<Path>>(path: P) -> Result<CString, Error> {\n\n match CS...
Rust
tooling/cli/src/build.rs
dumpmemory/tauri
c8667f9ff75275b1c8743411cc996aac032434f2
use crate::helpers::{ app_paths::{app_dir, tauri_dir}, command_env, config::{get as get_config, AppUrl, WindowUrl}, manifest::rewrite_manifest, updater_signature::sign_file_from_env_variables, }; use crate::{CommandExt, Result}; use anyhow::{bail, Context}; use clap::Parser; #[cfg(target_os = "linux")] use ...
use crate::helpers::{ app_paths::{app_dir, tauri_dir}, command_env, config::{get as get_config, AppUrl, WindowUrl}, manifest::rewrite_manifest, updater_signature::sign_file_from_env_variables, }; use crate::{CommandExt, Result}; use anyhow::{bail, Context}; use clap::Parser; #[cfg(target_os = "linux")] use ...
out_folders, if out_folders.len() == 1 { "folder" }else { "folders" } ) ); } } let runner_from_config = config_.build.runner.clone(); let runner = options .runner .or(runner_from_config) .unwrap_or_else(|| "cargo".to_string()); let mut features = confi...
"Unable to find your web assets, did you forget to build your web app? Your distDir is set to \"{:?}\".", web_asset_path )); } if web_asset_path.canonicalize()?.file_name() == Some(std::ffi::OsStr::new("src-tauri")) { return Err(anyhow::anyhow!( "The configured distDir is ...
random
[ { "content": "/// Run the Tauri CLI with the passed arguments.\n\n///\n\n/// The passed arguments should have the binary argument(s) stripped out before being passed.\n\n///\n\n/// e.g.\n\n/// 1. `tauri-cli 1 2 3` -> `1 2 3`\n\n/// 2. `cargo tauri 1 2 3` -> `1 2 3`\n\n/// 3. `node tauri.js 1 2 3` -> `1 2 3`\n\n...
Rust
src/generic.rs
rv32m1-rust/rv32m1_ri5cy-pac
1f98f7ab62b6f99f9de0157085ecd09855b6560f
use core::marker; #[doc = "This trait shows that register has `read` method"] #[doc = ""] #[doc = "Registers marked with `Writable` can be also `modify`'ed"] pub trait Readable {} #[doc = "This trait shows that register has `write`, `write_with_zero` and `reset` method"] #[doc = ""] #[doc = "Registers marked with `Read...
use core::marker; #[doc = "This trait shows that register has `read` method"] #[doc = ""] #[doc = "Registers marked with `Writable` can be also `modify`'ed"] pub trait Readable {} #[doc = "This trait shows that register has `write`, `write_with_zero` and `reset` method"] #[doc = ""] #[doc = "Registers marked with `Read...
} impl<U, REG> Reg<U, REG> where Self: Readable + Writable, U: Copy, { #[doc = "Modifies the contents of the register"] #[doc = ""] #[doc = "E.g. to do a read-modify-write sequence to change parts of a register:"] #[doc = "```ignore"] #[doc = "periph.reg.modify(|r, w| unsafe { w.bits("] #[doc = " r.b...
pub fn write_with_zero<F>(&self, f: F) where F: FnOnce(&mut W<U, Self>) -> &mut W<U, Self>, { self.register.set( f(&mut W { bits: U::default(), _reg: marker::PhantomData, }) .bits, ); }
function_block-full_function
[ { "content": "#[doc = \"Reader of register PRES_STATE\"]\n\npub type R = crate::R<u32, super::PRES_STATE>;\n\n#[doc = \"Command Inhibit (CMD)\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CIHB_A {\n\n #[doc = \"0: Can issue command using only CMD line\"]\n\n CIHB_0,\n\n #[...
Rust
daemon/src/rest_api/routes/locations.rs
isabeltomb/grid
e8232f12a23f0da9a4310cc75a443a6ce8bab4ea
use crate::rest_api::{ error::RestApiResponseError, routes::DbExecutor, AcceptServiceIdParam, AppState, QueryServiceId, }; use actix::{Handler, Message, SyncContext}; use actix_web::{web, HttpResponse}; use grid_sdk::locations::store::{LatLongValue, Location, LocationAttribute}; use serde::{Deserialize, Serializ...
use crate::rest_api::{ error::RestApiResponseError, routes::DbExecutor, AcceptServiceIdParam, AppState, QueryServiceId, }; use actix::{Handler, Message, SyncContext}; use actix_web::{web, HttpResponse}; use grid_sdk::locations::store::{LatLongValue, Location, LocationAttribute}; use serde::{Deserialize, Serializ...
} } pub async fn list_locations( state: web::Data<AppState>, query: web::Query<QueryServiceId>, _: AcceptServiceIdParam, ) -> Result<HttpResponse, RestApiResponseError> { state .database_connection .send(ListLocations { service_id: query.into_inner().service_id, ...
Ok(self .location_store .list_locations(msg.service_id.as_deref())? .into_iter() .map(LocationSlice::from) .collect())
call_expression
[ { "content": "pub fn compute_schema_address(name: &str) -> String {\n\n let mut sha = Sha512::new();\n\n sha.input(name.as_bytes());\n\n\n\n String::from(GRID_NAMESPACE) + \"01\" + &sha.result_str()[..62].to_string()\n\n}\n", "file_path": "contracts/location/src/addressing.rs", "rank": 0, "...
Rust
src/preference.rs
timchenxiaoyu/ssssh
9c03e1d7bab2b1cdc52892d4c28e11daf639bd94
use std::path::Path; use std::time::Duration; use getset::Getters; use crate::cipher; use crate::comp; use crate::hostkey::{HostKeys, HostKeysBuilder}; use crate::kex; use crate::mac; use crate::msg::kexinit::{Kexinit, KexinitBuilder}; use crate::negotiate::AlgorithmName; use crate::SshError; #[derive(Debug, Default...
use std::path::Path; use std::time::Duration; use getset::Getters; use crate::cipher; use crate::comp; use crate::hostkey::{HostKeys, HostKeysBuilder}; use crate::kex; use crate::mac; use crate::msg::kexinit::{Kexinit, KexinitBuilder}; use crate::negotiate::AlgorithmName; use crate::SshError; #[derive(Debug, Default...
impl Preference { pub(crate) fn to_kexinit(&self) -> Kexinit { let cookie = generate_cookie(); KexinitBuilder::default() .cookie(cookie) .kex_algorithms( self.kex_algorithms .iter() .map(AlgorithmName::to_string) ...
fn generate_cookie() -> u128 { use ring::rand::{SecureRandom as _, SystemRandom}; let mut cookie = 0u128.to_ne_bytes(); SystemRandom::new().fill(&mut cookie).unwrap(); u128::from_ne_bytes(cookie) }
function_block-full_function
[ { "content": "fn maybe_timeout(preference: &Preference) -> impl Future<Output = ()> {\n\n if let Some(timeout) = preference.timeout() {\n\n Either::Left(time::sleep(*timeout))\n\n } else {\n\n Either::Right(futures::future::pending())\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub(super) struc...
Rust
examples/openapi/auth/src/main.rs
12foo/poem
33686657256861c8eed50b3f3efd5a8bb7373f24
use poem::{handler, http::StatusCode, listener::TcpListener, route, Error, Result}; use poem_openapi::{ auth::{ApiKey, Basic, Bearer}, payload::PlainText, OAuthScopes, OpenApi, OpenApiService, SecurityScheme, }; #[derive(SecurityScheme)] #[oai(type = "basic")] struct MyBasicAuthorization(Basic); #[derive(...
use poem::{handler, http::StatusCode, listener::TcpListener, route, Error, Result}; use poem_openapi::{ auth::{ApiKey, Basic, Bearer}, payload::PlainText, OAuthScopes, OpenApi, OpenApiService, SecurityScheme, }; #[derive(SecurityScheme)] #[oai(type = "basic")] struct MyBasicAuthorization(Basic); #[derive(...
tring>> { let client = reqwest::Client::new(); let text = client .get("https://api.github.com/repositories") .bearer_auth(auth.0.token) .header("accept", "application/vnd.github.v3+json") .header("user-agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7...
#[oai(path = "/api_key", method = "get")] async fn auth_api_key( &self, #[oai(auth)] auth: MyApiKeyAuthorization, ) -> Result<PlainText<String>> { if auth.0.key != "123456" { return Err(Error::new(StatusCode::UNAUTHORIZED)); } Ok(PlainText("hello".to_str...
random
[ { "content": "/// A helper function, similar to `RouteMethod::new().get(ep)`.\n\npub fn get(ep: impl IntoEndpoint) -> RouteMethod {\n\n RouteMethod::new().get(ep)\n\n}\n\n\n", "file_path": "poem/src/route/router.rs", "rank": 0, "score": 296748.1113440877 }, { "content": "fn get_meta<T: Ty...
Rust
cli/ops/dispatch_json.rs
naynaydoshkeh3/deno
383206797ea1a73e7b86094fc0e17edab7664877
use crate::op_error::OpError; use deno_core::Buf; use deno_core::CoreIsolateState; use deno_core::Op; use deno_core::OpDispatcher; use deno_core::ZeroCopyBuf; use futures::future::FutureExt; pub use serde_derive::Deserialize; use serde_json::json; pub use serde_json::Value; use std::future::Future; use std::pin::Pin; ...
use crate::op_error::OpError; use deno_core::Buf; use deno_core::CoreIsolateState; use deno_core::Op; use deno_core::OpDispatcher; use deno_core::ZeroCopyBuf; use futures::future::FutureExt; pub use serde_derive::Deserialize; use serde_json::json; pub use serde_json::Value; use std::future::Future; use std::pin::Pin; ...
serde_json::to_vec(&value).unwrap().into_boxed_slice() } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct AsyncArgs { promise_id: Option<u64>, } pub trait JsonOpDispatcher { fn dispatch( &self, isolate_state: &mut CoreIsolateState, json: Value, zero_copy: &mut [ZeroCopyBuf], )...
let value = match result { Ok(v) => json!({ "ok": v, "promiseId": promise_id }), Err(err) => json!({ "err": json_err(err), "promiseId": promise_id }), };
assignment_statement
[ { "content": "pub fn enum_name_media_type(mt: MediaType) -> &'static str {\n\n match mt {\n\n MediaType::JavaScript => \"JavaScript\",\n\n MediaType::JSX => \"JSX\",\n\n MediaType::TypeScript => \"TypeScript\",\n\n MediaType::TSX => \"TSX\",\n\n MediaType::Json => \"Json\",\n\n MediaType::Was...
Rust
src/bin/nabu/watch.rs
jmg-duarte/nabu
44a86831658a32b65780894ec5f6a06abfd8defe
use nabu::{ config::{global_config_path, Config, DEFAULT_DELAY}, fs::list_subdirs, git::{AuthenticationMethod, DummyRepository, Repository, WatchedRepository}, }; use std::{ collections::HashSet, env, ffi::OsStr, io, path::PathBuf, sync::{ atomic::{AtomicBool, Ordering}, ...
use nabu::{ config::{global_config_path, Config, DEFAULT_DELAY}, fs::list_subdirs, git::{AuthenticationMethod, DummyRepository, Repository, WatchedRepository}, }; use std::{ collections::HashSet, env, ffi::OsStr, io, path::PathBuf, sync::{ atomic::{AtomicBool, Ordering}, ...
Recursive).unwrap(); } log::debug!("watching over {:?}", &self.watchlist); while self.running.load(Ordering::SeqCst) { match event_rcv.recv_timeout(Duration::from_millis(500)) { Ok(event) => { log::debug!("event received: {:?}", &event); ...
atching, watched_directories, delay, self.push_on_exit, self.push_timeout, self.get_authentication_method()?, ) .run(); } else { let directory = self.directory.clone().canonicalize()?; ...
random
[ { "content": "#[inline(always)]\n\nfn default_delay() -> u64 {\n\n DEFAULT_DELAY\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 0, "score": 84665.57838352364 }, { "content": "pub fn global_config_path() -> PathBuf {\n\n let path = std::env::var(\"HOME\").unwrap() + \"/.config/nabu....
Rust
d2fileformats/src/dt1.rs
AridTag/d2rust
258370fd9e0beb00b4bdaca3a20aa919062b7514
use std::io::{Cursor, Seek, SeekFrom, Read}; use byteorder::{ReadBytesExt,LittleEndian}; #[derive(Clone,Debug)] pub struct Dt1 { pub version1: u32, pub version2: u32, pub tiles: Vec<Tile>, } #[derive(Clone,Debug)] pub struct Tile { pub direction: u32, pub roof_height: u16, pub ma...
use std::io::{Cursor, Seek, SeekFrom, Read}; use byteorder::{ReadBytesExt,LittleEndian}; #[derive(Clone,Debug)] pub struct Dt1 { pub version1: u32, pub version2: u32, pub tiles: Vec<Tile>, } #[derive(Clone,Debug)] pub struct Tile { pub direction: u32, pub roof_height: u16, pub ma...
Ok(block_data) } }
an>()?; reader.seek(SeekFrom::Start(tiles_pointer as u64))?; let tiles = Dt1::read_tiles(&mut reader, num_tiles as usize)?; Ok(Dt1 { version1, version2, tiles }) } fn read_tiles(reader: &mut Cursor<&[u8]>, num_tiles: usize) -> Resu...
random
[ { "content": "fn is_reader_at_end(reader: &mut Cursor<&[u8]>) -> bool {\n\n let current_pos = reader.position();\n\n if let Err(_) = reader.seek(SeekFrom::End(0)) {\n\n return true;\n\n }\n\n let end_pos = reader.position();\n\n reader.seek(SeekFrom::Start(current_pos)).expect(\"this shoul...
Rust
rustbus/src/tests/verify_marshalling.rs
avrabe/rustbus
08aca595d1b54880a855a80c0cc279be0eedaec0
use crate::wire::marshal::base::marshal_base_param; use crate::wire::marshal::container::marshal_container_param; use crate::ByteOrder; use crate::Marshal; #[test] fn verify_base_marshalling() { use crate::wire::marshal::MarshalContext; let mut fds = Vec::new(); let mut valid_buf = Vec::new(); let mut...
use crate::wire::marshal::base::marshal_base_param; use crate::wire::marshal::container::marshal_container_param; use crate::ByteOrder; use crate::Marshal; #[test] fn verify_base_marshalling() { use crate::wire::marshal::MarshalContext; let mut fds = Vec::new(); let mut valid_buf = Vec::new(); let mut...
mut valid_buf, fds: &mut fds, byteorder: ByteOrder::LittleEndian, }; let ctx = &mut ctx; [(32u64, 64u64), (32u64, 64u64)][..].marshal(ctx).unwrap(); assert_eq!( ctx.buf, &vec![ 32, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0,...
crate::params::Base::Uint32(32)); let arr = crate::params::Container::make_array("u", vec![param].into_iter()).unwrap(); marshal_container_param(&arr, ctx).unwrap(); assert_eq!(ctx.buf, &[4, 0, 0, 0, 32, 0, 0, 0]); ctx.buf.clear(); let param = crate::params::Param::Base(crate::params::Base::U...
function_block-random_span
[ { "content": "fn marshal_struct(params: &[params::Param], ctx: &mut MarshalContext) -> message::Result<()> {\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
src/parsers/firewall.rs
u-siem/usiem-sonicwall
fd3460f5063dd6c99745719d666743f73de4b1bc
use std::borrow::Cow; use std::collections::BTreeMap; use usiem::events::field::SiemField; use usiem::events::field_dictionary; use usiem::events::firewall::FirewallOutcome; use usiem::events::protocol::NetworkProtocol; use usiem::events::{SiemEvent, SiemLog}; use super::common::{add_value_or_not, firewall_event, get_...
use std::borrow::Cow; use std::collections::BTreeMap; use usiem::events::field::SiemField; use usiem::events::field_dictionary; use usiem::events::firewall::FirewallOutcome; use usiem::events::protocol::NetworkProtocol; use usiem::events::{SiemEvent, SiemLog}; use super::common::{add_value_or_not, firewall_event, get_...
pub fn sonicwall_firewall<'a>( field_map: BTreeMap<&'a str, &'a str>, mut log: SiemLog, ) -> Result<SiemLog, SiemLog> { let user_name = field_map.get("usr").map(|v| v.to_string()); add_value_or_not(&mut log, field_map.get("srcMac"), "source.mac"); add_value_or_not(&mut log, field_map.get("dstMac"), ...
function_block-full_function
[ { "content": "pub fn is_ips_module(code: u32) -> bool {\n\n [\n\n 22, 23, 25, 27, 81, 82, 83, 165, 177, 178, 179, 229, 248, 267, 446, 580, 583, 606, 608,\n\n 609, 48, 789, 790, 793, 794, 795, 809, 815, 860, 866, 869, 897, 899, 902, 904, 905, 908,\n\n 909, 1098, 1099, 1180, 1181, 1182, 12...
Rust
kernel/src/arch/x86_64/cpu/idt.rs
MalteDoemer/yeetos
39a8cbfde861196795e87d9808657a7435375908
use core::arch::asm; use log::info; use x86::{ current::segmentation::Descriptor64, dtables::{lidt, DescriptorTablePointer}, segmentation::{BuildDescriptor, DescriptorBuilder, GateDescriptorBuilder}, Ring, }; use super::{gdt::CODE_SEL, get_local}; pub const NUM_IDT_ENTRIES: usize = 256; unsafe trait...
use core::arch::asm; use log::info; use x86::{ current::segmentation::Descriptor64, dtables::{lidt, DescriptorTablePointer}, segmentation::{BuildDescriptor, DescriptorBuilder, GateDescriptorBuilder}, Ring, }; use super::{gdt::CODE_SEL, get_local}; pub const NUM_IDT_ENTRIES: usize = 256; unsafe trait...
"mov al, 0x74", "out dx, al", "mov al, 0x0a", "out dx, al", "hlt", ); } }
fn addr(&self) -> usize { *self as usize } } unsafe impl IntHandlerFunc for IntFuncErrCode { fn addr(&self) -> usize { *self as usize } } unsafe impl IntHandlerFunc for HandlerFunc { fn addr(&self) -> usize { *self as usize } } #[repr(C)] pub struct IntStackFrame { ...
random
[ { "content": "#[inline(always)]\n\npub fn now_ns() -> u64 {\n\n let cycle = rdtsc();\n\n\n\n let factor = unsafe { TSC_NS_FACTOR };\n\n\n\n // the calculation here is:\n\n // ns = (cycle * 10⁹) / rate\n\n // = cycle * (10⁹ / rate)\n\n // = (cycle * ((10⁹ * SCALE) / rate)) ...
Rust
boa_engine/src/syntax/parser/cursor/mod.rs
nekevss/boa
ae01d5c20bef227a47d7a9647d85da8bcd2b48c5
mod buffered_lexer; use super::{statement::PrivateElement, ParseError}; use crate::syntax::{ ast::{Position, Punctuator}, lexer::{InputElement, Lexer, Token, TokenKind}, }; use boa_interner::{Interner, Sym}; use buffered_lexer::BufferedLexer; use rustc_hash::FxHashMap; use std::io::Read; #[derive(Debug)] pub...
mod buffered_lexer; use super::{statement::PrivateElement, ParseError}; use crate::syntax::{ ast::{Position, Punctuator}, lexer::{InputElement, Lexer, Token, TokenKind}, }; use boa_interner::{Interner, Sym}; use buffered_lexer::BufferedLexer; use rustc_hash::FxHashMap; use std::io::Read; #[derive(Debug)] pub...
#[inline] pub(super) fn next_if<K>( &mut self, kind: K, interner: &mut Interner, ) -> Result<Option<Token>, ParseError> where K: Into<TokenKind>, { Ok(if let Some(token) = self.peek(0, interner)? { if token.kind() == &kin...
context, )) } else { Ok(t) } } else { Err(ParseError::AbruptEnd) } }
function_block-function_prefix_line
[ { "content": "fn parse_regex_flags(s: &str, start: Position, interner: &mut Interner) -> Result<Sym, Error> {\n\n match RegExpFlags::from_str(s) {\n\n Err(message) => Err(Error::Syntax(message.into(), start)),\n\n Ok(flags) => Ok(interner.get_or_intern(flags.to_string())),\n\n }\n\n}\n\n\n\n...
Rust
src/main.rs
EliseZeroTwo/WARS-8
b73657f3453c04c3d067e23aa079747af7e1ee08
#![feature(slice_fill)] extern crate directories; #[macro_use] extern crate lazy_static; extern crate rand; extern crate rand_pcg; extern crate regex; extern crate sdl2; extern crate serde_json; extern crate wasmtime; mod cart; mod config; mod draw_state; mod font; mod palette; mod runtime; mod utils; mod api; use ...
#![feature(slice_fill)] extern crate directories; #[macro_use] extern crate lazy_static; extern crate rand; extern crate rand_pcg; extern crate regex; extern crate sdl2; extern crate serde_json; extern crate wasmtime; mod cart; mod config; mod draw_state; mod font; mod palette; mod runtime; mod utils; mod api; use ...
for y in 0..HEIGHT { for x in 0..WIDTH { let loc = TerminalLocation(x, y); let raw_idx = usize::from(loc) * 4; let color = Color::from(get_pixel(Some(&memory), loc)); buffer[raw_idx + 1] = color.b; ...
t mut runtime = cart_pre_mutex.as_deref().unwrap().create_runtime(); drop(cart_pre_mutex); draw_state::reset(None); runtime.init(); let mut cart_start_offset: f32 = 0.0; let mut sdl_timer = sdl_ctx.timer().unwrap(); let mut target_ms = sdl_timer.ticks() + FRAME_LEN_MS; let mut fps_counter ...
function_block-random_span
[ { "content": "pub fn mset(x: i32, y: i32, val: u8) {\n\n set_map(None, x, y, val);\n\n}\n", "file_path": "src/api/gfx.rs", "rank": 2, "score": 228593.17947090795 }, { "content": "pub fn set_pen_color(mutex_guard: Option<&mut MutexGuard<[u8; 0x8000]>>, col: ColorPalette) {\n\n let mut m...
Rust
curiefense/curieproxy/rust/curiefense/src/body.rs
denis-reblaze/curiefense
9861c3c18fcb1fad94a6938dc9f61f62fd6dc6b2
use multipart::server::Multipart; use serde_json::Value; use std::io::Read; use xmlparser::{ElementEnd, EntityDefinition, ExternalId, Token}; use crate::logs::Logs; use crate::requestfields::RequestField; use crate::utils::url::parse_urlencoded_params_bytes; fn json_path(prefix: &[String]) -> String { if prefix...
use multipart::server::Multipart; use serde_json::Value; use std::io::Read; use xmlparser::{ElementEnd, EntityDefinition, ExternalId, Token}; use crate::logs::Logs; use crate::requestfields::RequestField; use crate::utils::url::parse_urlencoded_params_bytes; fn json_path(prefix: &[String]) -> String { if prefix...
fn forms_body(args: &mut RequestField, body: &[u8]) -> Result<(), String> { if body.contains(&b'=') && body.iter().all(|x| *x > 0x20 && *x < 0x7f) { parse_urlencoded_params_bytes(args, body); Ok(()) } else { Err("Body is not forms encoded".to_string()) } } fn multipart_form_e...
ext { text } => { let trimmed = text.trim(); if !trimmed.is_empty() { xml_increment_last(&mut stack); args.add(xml_path(&stack), trimmed.to_string()); } } Token::Cdata { text, .. } => { xml_in...
function_block-function_prefixed
[ { "content": "fn from_map<V: Clone>(mp: &HashMap<String, V>, k: &str) -> Result<V, String> {\n\n mp.get(k).cloned().ok_or_else(|| {\n\n let all_keys: String = mp.keys().map(|s| s.as_str()).collect::<Vec<&str>>().join(\",\");\n\n format!(\"id not found: {}, all ids are: {}\", k, all_keys)\n\n ...
Rust
src/embedded_flash/syscall.rs
gregvinyard/OpenSK
53b46ce6d5596d3565815bd4381c9f18acd6d72c
use super::{Index, Storage, StorageError, StorageResult}; use libtock::syscalls; const DRIVER_NUMBER: usize = 0x50003; mod command_nr { pub const GET_INFO: usize = 1; pub mod get_info_nr { pub const WORD_SIZE: usize = 0; pub const PAGE_SIZE: usize = 1; pub const MAX_WORD_WRITES: usiz...
use super::{Index, Storage, StorageError, StorageResult}; use libtock::syscalls; const DRIVER_NUMBER: usize = 0x50003; mod command_nr { pub const GET_INFO: usize = 1; pub mod get_info_nr { pub const WORD_SIZE: usize = 0; pub const PAGE_SIZE: usize = 1; pub const MAX_WORD_WRITES: usiz...
mpl Storage for SyscallStorage { fn word_size(&self) -> usize { self.word_size } fn page_size(&self) -> usize { self.page_size } fn num_pages(&self) -> usize { self.storage.len() / self.page_size } fn max_word_writes(&self) -> usize { self.max_word_writes ...
SE_PAGE: usize = 3; } mod allow_nr { pub const WRITE_SLICE: usize = 0; } fn get_info(nr: usize) -> StorageResult<usize> { let code = unsafe { syscalls::command(DRIVER_NUMBER, command_nr::GET_INFO, nr, 0) }; if code < 0 { Err(StorageError::KernelError { code }) } else { Ok(code as usize...
random
[ { "content": "/// Abstraction for embedded flash storage.\n\npub trait Storage {\n\n /// Returns the size of a word in bytes.\n\n fn word_size(&self) -> usize;\n\n\n\n /// Returns the size of a page in bytes.\n\n fn page_size(&self) -> usize;\n\n\n\n /// Returns the number of pages in the storage...
Rust
pallets/kitties/src/lib.rs
konrads/substrate-exercise-3
dfcb11191fac6e3139803eb1bb57398143286131
#![cfg_attr(not(feature = "std"), no_std)] use std::fmt; use codec::{Encode, Decode}; use frame_support::{ decl_module, decl_storage, decl_event, decl_error, StorageValue, StorageDoubleMap, Parameter, traits::{Randomness, Currency, ExistenceRequirement}, ensure, RuntimeDebug, }; use frame_support::dispatch::{Dispat...
#![cfg_attr(not(feature = "std"), no_std)] use std::fmt; use codec::{Encode, Decode}; use frame_support::{ decl_module, decl_storage, decl_event, decl_error, StorageValue, StorageDoubleMap, Parameter, traits::{Randomness, Currency, ExistenceRequirement}, ensure, RuntimeDebug, }; use frame_support::dispatch::{Dispat...
fn mix_dna(mixer: [u8; 16], dna1: [u8; 16], dna2: [u8; 16]) -> [u8; 16] { let mut res: [u8; 16] = [0u8; 16]; for i in 0..mixer.len() { res[i] = (!mixer[i] & dna1[i]) + (mixer[i] & dna2[i]); } res } #[cfg(test)] mod tests;
fn get_female_male<'a>(kitty1: &'a Kitty, kitty2: &'a Kitty) -> Option<(&'a Kitty, &'a Kitty)> { match (kitty1.get_gender(), kitty2.get_gender()) { (Gender::Female, Gender::Male) => Some((kitty1, kitty2)), (Gender::Male, Gender::Female) => Some((kitty2, kitty1)), _ => None } }
function_block-function_prefix_line
[ { "content": "\t#[pallet::config]\n\n\tpub trait Config: frame_system::Config {\n\n\t\t/// Because this pallet emits events, it depends on the runtime's definition of an event.\n\n\t\ttype Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;\n\n\t}\n\n\n\n\t#[pallet::pallet]\n\n\t#[pallet::...
Rust
aya/src/maps/sock/sock_map.rs
xuhui187/aya
9cbb7958c13a8ef881302398975fde886ae1d910
use std::{ convert::TryFrom, mem, ops::{Deref, DerefMut}, os::unix::{io::AsRawFd, prelude::RawFd}, }; use crate::{ generated::bpf_map_type::BPF_MAP_TYPE_SOCKMAP, maps::{sock::SocketMap, Map, MapError, MapKeys, MapRef, MapRefMut}, sys::{bpf_map_delete_elem, bpf_map_update_elem, bpf_map_loo...
use std::{ convert::TryFrom, mem, ops::{Deref, DerefMut}, os::unix::{io::AsRawFd, prelude::RawFd}, }; use crate::{ generated::bpf_map_type::BPF_MAP_TYPE_SOCKMAP, maps::{sock::SocketMap, Map, MapError, MapKeys, MapRef, MapRefMut}, sys::{bpf_map_delete_elem, bpf_map_update_elem, bpf_map_loo...
value.ok_or(MapError::KeyNotFound) } } impl<T: Deref<Target = Map> + DerefMut<Target = Map>> SocketMap for SockMap<T> { fn fd_or_err(&self) -> Result<RawFd, MapError> { self.inner.fd_or_err() } } impl TryFrom<MapRef> for SockMap<MapRef> { type Error = MapError; fn try_from(a: Map...
let value = bpf_map_lookup_elem(fd, &index, flags).map_err( |(code, io_error)| MapError::SyscallError { call: "bpf_map_lookup_elem".to_owned(), code, io_error, }, )?;
assignment_statement
[ { "content": "/// Loads kernel symbols from `/proc/kallsyms`.\n\n///\n\n/// The symbols can be passed to [`StackTrace::resolve`](crate::maps::stack_trace::StackTrace::resolve).\n\npub fn kernel_symbols() -> Result<BTreeMap<u64, String>, io::Error> {\n\n let mut reader = BufReader::new(File::open(\"/proc/kall...
Rust
src/main.rs
coniferprod/harmonik
63f10f8033be9e56b1942e914347f9dff1be6663
use std::collections::HashMap; use std::fmt; use structopt::StructOpt; use rand::Rng; use ksynth::k5000::harmonic::{Levels, Envelope}; use syxpack::{Message, Manufacturer, ManufacturerId}; const MAX_LEVEL: u8 = 127; const HARMONIC_COUNT: usize = 64; fn get_level(a: f64) -> u8 { ((a.abs().log2() * 8.0) + MAX_LEVE...
use std::collections::HashMap; use std::fmt; use structopt::StructOpt; use rand::Rng; use ksynth::k5000::harmonic::{Levels, Envelope}; use syxpack::{Message, Manufacturer, ManufacturerId}; const MAX_LEVEL: u8 = 127; const HARMONIC_COUNT: usize = 64; fn get_level(a: f64) -> u8 { ((a.abs().log2() * 8.0) + MAX_LEVE...
println!("{}", make_graph(&levels)); make_sysex_messages(&device, &levels, channel, 0, 0); } _ => { eprintln!("Unknown waveform"); } } /* let mut custom_params = HashMap::<&str, Parameters>::new(); custom_params.insert("saw", Parameters { a: 1.0, b: 0.0, ...
let max_level = 127f64; let a_max = 1.0; let a = compute(n, params); let v = ((a / a_max).abs()).log2(); eprintln!("{}: a = {}, v = {}", n, a, v); let level = max_level + 8.0 * v; if level >= 0.0 { level.floor() as u8 } else { 0 } } fn get_custom_levels(params: &P...
random
[ { "content": "# harmonik\n\n\n\nGenerate harmonic levels for the Kawai K5000 Advanced Additive Synthesizer.\n\n\n\nThis program uses a parameterized method to generate amplitude levels for\n\nadditive harmonics. The method was patented as [U.S. patent 6143974A](https://patents.google.com/patent/US6143974A/en),\...
Rust
language/evm/exec-utils/src/exec.rs
awelc/move
2f0d73d518c9dc178d02592e665e78fd391d9dc9
use evm::{ backend::{Apply, ApplyBackend, Basic, MemoryAccount, MemoryBackend, MemoryVicinity}, executor::stack::{MemoryStackState, StackExecutor, StackSubstateMetadata}, Config, Context, CreateScheme, ExitReason, Runtime, }; use primitive_types::{H160, U256}; use sha3::{Digest, Keccak256}; use std::{coll...
use evm::{ backend::{Apply, ApplyBackend, Basic, MemoryAccount, MemoryBackend, MemoryVicinity}, executor::stack::{MemoryStackState, StackExecutor, StackSubstateMetadata}, Config, Context, CreateScheme, ExitReason, Runtime, }; use primitive_types::{H160, U256}; use sha3::{Digest, Keccak256}; use std::{coll...
}
pub fn execute_custom_code( &mut self, caller_address: H160, contract_address: H160, code: Vec<u8>, data: Vec<u8>, ) -> ExecuteResult { self.transact(|exec| { let context = Context { address: contract_address, caller: caller...
function_block-full_function
[]
Rust
tests/redirect.rs
liushuyu/conch-parser
9fb470f4dcea6bb86fe64071ee5ae2121dbc4adf
#![deny(rust_2018_idioms)] use conch_parser::ast::ComplexWord::*; use conch_parser::ast::PipeableCommand::*; use conch_parser::ast::SimpleWord::*; use conch_parser::ast::*; use conch_parser::parse::ParseError::*; use conch_parser::token::Token; mod parse_support; use crate::parse_support::*; fn simple_command_with_re...
#![deny(rust_2018_idioms)] use conch_parser::ast::ComplexWord::*; use conch_parser::ast::PipeableCommand::*; use conch_parser::ast::SimpleWord::*; use conch_parser::ast::*; use conch_parser::parse::ParseError::*; use conch_parser::token::Token; mod parse_support; use crate::parse_support::*; fn simple_command_with_re...
Err(BadFd(src(7, 1, 8), src(10, 1, 11))), make_parser("1>>out abc<in 2>&-").redirect_list() ); assert_eq!( Err(BadFd(src(7, 1, 8), src(10, 1, 11))), make_parser("1>>out abc <in 2>&-").redirect_list() ); }
).unwrap(); assert_eq!( cmd, simple_command_with_redirect("foo", Redirect::DupRead(Some(1234), word("-"))) ); } #[test] fn test_redirect_dst_fd_need_not_be_single_token() { let mut p = make_parser_from_tokens(vec![ Token::GreatAnd, Token::Literal(String::from("12")), ...
random
[ { "content": "pub fn cmd(cmd: &str) -> TopLevelCommand<String> {\n\n cmd_args(cmd, &[])\n\n}\n\n\n", "file_path": "tests/parse_support.rs", "rank": 2, "score": 161085.60470303625 }, { "content": "pub fn word(s: &str) -> TopLevelWord<String> {\n\n TopLevelWord(Single(lit(s)))\n\n}\n\n\n...
Rust
src/question/expand/mod.rs
Lutetium-Vanadium/discourse
4e2dc9bdfa70cb777090eb288155f3d2a845954d
use std::io; use ui::{ backend::{Backend, MoveDirection}, events::{EventIterator, KeyEvent}, style::{Color, Stylize}, widgets::{self, Text}, Prompt, Validation, Widget, }; use super::{Choice, Transform}; use crate::{Answer, Answers, ExpandItem}; pub use builder::ExpandBuilder; mod builder; #[cfg...
use std::io; use ui::{ backend::{Backend, MoveDirection}, events::{EventIterator, KeyEvent}, style::{Color, Stylize}, widgets::{self, Text}, Prompt, Validation, Widget, }; use super::{Choice, Transform}; use crate::{Answer, Answers, ExpandItem}; pub use builder::ExpandBuilder; mod builder; #[cfg...
|| self.choices.choices.iter().any( |c| matches!(c, Choice::Choice(ExpandText { key, .. }) if *key == self.default), ) } fn render_choice<B: Backend>( &mut self, index: Option<usize>, mut layout: ui::layout::Layout, b: &mut B, ) -> io::Result...
ut self.choices[index] { Choice::Choice(_) => self.render_choice(Some(index), layout, b), separator => { b.set_fg(Color::DarkGrey)?; b.write_all(b" ")?; super::get_sep_str(separator).render(&mut layout.with_line_offset(3), b)?; b....
random
[ { "content": "fn choices_with_default(len: usize) -> impl Iterator<Item = Choice<(String, bool)>> {\n\n let mut rng = ChaCha12Rng::seed_from_u64(SEED);\n\n\n\n (0..len).map(move |i| {\n\n let rand: f32 = rng.gen();\n\n if rand < DEFAULT_SEP_RATIO {\n\n Choice::DefaultSeparator\n\n...
Rust
sync/src/tasks/inner_sync_task.rs
xielong/starcoin
14faf39ea7231d6a24780a87f847584824e7ff18
use crate::tasks::{ AccumulatorCollector, BlockAccumulatorSyncTask, BlockCollector, BlockConnectedEventHandle, BlockFetcher, BlockIdFetcher, BlockSyncTask, PeerOperator, }; use anyhow::format_err; use network_api::PeerProvider; use starcoin_accumulator::node::AccumulatorStoreType; use starcoin_chain::BlockChain...
use crate::tasks::{ AccumulatorCollector, BlockAccumulatorSyncTask, BlockCollector, BlockConnectedEventHandle, BlockFetcher, BlockIdFetcher, BlockSyncTask, PeerOperator, }; use anyhow::format_err; use network_api::PeerProvider; use starcoin_accumulator::node::AccumulatorStoreType; use starcoin_chain::BlockChain...
); let block_chain = fut.await?; Ok((block_chain, handle)) } }
ancestor, self.fetcher.clone(), check_local_store, self.storage.clone(), 1, ); let chain = BlockChain::new(self.time_service.clone(), ancestor.id, self.storage.clone())?; let block_collector = BlockCol...
random
[ { "content": "pub fn full_sync_task<H, A, F, N>(\n\n current_block_id: HashValue,\n\n target: SyncTarget,\n\n skip_pow_verify: bool,\n\n time_service: Arc<dyn TimeService>,\n\n storage: Arc<dyn Store>,\n\n block_event_handle: H,\n\n fetcher: Arc<F>,\n\n ancestor_event_handle: A,\n\n p...
Rust
src/proto/go_away.rs
alex/h2
4398e169e87afa0daaf9f49c2f411e51096d5cd3
use crate::codec::Codec; use crate::frame::{self, Reason, StreamId}; use bytes::Buf; use std::io; use std::task::{Context, Poll}; use tokio::io::AsyncWrite; #[derive(Debug)] pub(super) struct GoAway { close_now: bool, going_away: Option<GoingAway>, is_user_initiated: bool, pending:...
use crate::codec::Codec; use crate::frame::{self, Reason, StreamId}; use bytes::Buf; use std::io; use std::task::{Context, Poll}; use tokio::io::AsyncWrite; #[derive(Debug)] pub(super) struct GoAway { close_now: bool, going_away: Option<GoingAway>, is_user_initiated: bool, pending:...
let reason = frame.reason(); dst.buffer(frame.into()).expect("invalid GOAWAY frame"); return Poll::Ready(Some(Ok(reason))); } else if self.should_close_now() { return match self.going_away_reason() { Some(reason) => Poll::Ready(Some(Ok(reason)))...
if !dst.poll_ready(cx)?.is_ready() { self.pending = Some(frame); return Poll::Pending; }
if_condition
[ { "content": "// TODO: return error when there is not enough room to encode the value\n\npub fn encode<B: BufMut>(src: &[u8], dst: &mut B) -> Result<(), EncoderError> {\n\n let mut bits: u64 = 0;\n\n let mut bits_left = 40;\n\n let mut rem = dst.remaining_mut();\n\n\n\n for &b in src {\n\n le...
Rust
bee-api/bee-rest-api/src/endpoints/routes/api/v1/submit_message.rs
TeeVeeEss/bee
b98bd114e763a0cebe47ac4b8055873e8009e8e6
use std::net::IpAddr; use bee_common::packable::Packable; use bee_message::{parents::Parents, payload::Payload, Message, MessageBuilder, MessageId}; use bee_pow::providers::{miner::MinerBuilder, NonceProviderBuilder}; use bee_protocol::workers::{config::ProtocolConfig, MessageSubmitterError, MessageSubmitterWorkerEv...
use std::net::IpAddr; use bee_common::packable::Packable; use bee_message::{parents::Parents, payload::Payload, Message, MessageBuilder, MessageId}; use bee_pow::providers::{miner::MinerBuilder, NonceProviderBuilder}; use bee_protocol::workers::{config::ProtocolConfig, MessageSubmitterError, MessageSubmitterWorkerEv...
fig.feature_proof_of_work() { return Err(reject::custom(CustomRejection::ServiceUnavailable( "can not auto-fill nonce: feature `PoW` not enabled".to_string(), ))); } let mut builder = MessageBuilder::new() .with_network_id(network_id) .with...
ssage, Rejection> { let message = if let Some(nonce) = nonce { let mut builder = MessageBuilder::new() .with_network_id(network_id) .with_parents( Parents::new(parents).map_err(|e| reject::custom(CustomRejection::BadRequest(e.to_string())))?, ) ...
function_block-random_span
[ { "content": "fn path() -> impl Filter<Extract = (MessageId,), Error = Rejection> + Clone {\n\n super::path()\n\n .and(warp::path(\"messages\"))\n\n .and(message_id())\n\n .and(warp::path::end())\n\n}\n\n\n\npub(crate) fn filter<B: StorageBackend>(\n\n public_routes: Box<[String]>,\n\...
Rust
compiler/llvm/src/diagnostics.rs
mwatts/lumen
521fda4d040a53ad53ed88174650c60959bdbcc8
use std::ffi::CStr; use std::marker::PhantomData; use std::mem::MaybeUninit; use std::path::{Path, PathBuf}; use std::slice; use liblumen_session::Options; use liblumen_util::diagnostics::{DiagnosticsHandler, FileName, InFlightDiagnostic, Severity}; use crate::sys::{self as llvm_sys, LLVMDiagnosticInfo}; use crate::u...
use std::ffi::CStr; use std::marker::PhantomData; use std::mem::MaybeUninit; use std::path::{Path, PathBuf}; use std::slice; use liblumen_session::Options; use liblumen_util::diagnostics::{DiagnosticsHandler, FileName, InFlightDiagnostic, Severity}; use crate::sys::{self as llvm_sys, LLVMDiagnosticInfo}; use crate::u...
pub fn last_error() -> Option<String> { unsafe { let cstr = LLVMLumenGetLastError(); if cstr.is_null() { None } else { let err = CStr::from_ptr(cstr).to_bytes(); let err = String::from_utf8_lossy(err).to_string(); libc::free(cstr as *mut _); ...
pub(crate) unsafe extern "C" fn diagnostic_handler( info: &LLVMDiagnosticInfo, user: *mut libc::c_void, ) { use std::sync::Weak; if user.is_null() { return; } let (context, options, diagnostics) = &*(user as *const (&Context, Weak<Options>, Weak<DiagnosticsHandler>)); if le...
function_block-full_function
[ { "content": "pub fn term_is_not_type(name: &str, value: Term, r#type: &str) -> String {\n\n format!(\"{} ({}) is not {}\", name, value, r#type)\n\n}\n\n\n", "file_path": "runtimes/core/src/context.rs", "rank": 0, "score": 608867.7948310329 }, { "content": "fn get_object_file_path(options...
Rust
rs/crypto/internal/crypto_service_provider/src/server/local_csp_server/multi_sig/tests.rs
LaudateCorpus1/ic
e05b8568bcef4147b5999d2c489f875afde2f8bb
use crate::api::CspSigner; use crate::secret_key_store::test_utils::TempSecretKeyStore; use crate::server::api::{ BasicSignatureCspServer, CspMultiSignatureError, CspMultiSignatureKeygenError, MultiSignatureCspServer, }; use crate::server::local_csp_server::LocalCspServer; use crate::{CryptoServiceProvider, Cs...
use crate::api::CspSigner; use crate::secret_key_store::test_utils::TempSecretKeyStore; use crate::server::api::{ BasicSignatureCspServer, CspMultiSignatureError, CspMultiSignatureKeygenError, MultiSignatureCspServer, }; use crate::server::local_csp_server::LocalCspServer; use crate::{CryptoServiceProvider, Cs...
#[test] fn should_fail_to_sign_with_unsupported_algorithm_id() { let csp_server = csp_server_with_empty_key_store(); let (key_id, _csp_pub_key, _csp_pop) = csp_server .gen_key_pair_with_pop(AlgorithmId::MultiBls12_381) .expect("failed to generate keys"); let msg = [31; 41]; for algo...
fn should_sign_verifiably_with_generated_key() { let mut rng = thread_rng(); let csp_server = csp_server_with_empty_key_store(); let verifier = verifier(); let (key_id, csp_pub_key, csp_pop) = csp_server .gen_key_pair_with_pop(AlgorithmId::MultiBls12_381) .expect("failed to generate key...
function_block-full_function
[ { "content": "pub fn random_algorithm_id(rng: &mut ChaCha20Rng) -> AlgorithmId {\n\n AlgorithmId::iter()\n\n .choose(rng)\n\n .expect(\"Could not choose an AlgorithmId\")\n\n}\n\n\n\n/// A single node with its CSP\n\npub struct MockNode {\n\n pub node_id: NodeId,\n\n pub fs_key_id: KeyId,...
Rust
src/eager/tensor_handle.rs
dumpmemory/rust-2
110b139696794f18bcd8b66429ab587693e8b1dc
use std::ffi::{CStr, CString}; use std::marker::PhantomData; use tensorflow_sys as tf; use crate::eager::{Context, ReadonlyTensor}; use crate::{AnyTensor, DataType, Result, Status, TensorType}; #[derive(Debug)] pub struct TensorHandle<'a> { pub(super) inner: *mut tf::TFE_TensorHandle, ctx: PhantomData<&...
use std::ffi::{CStr, CString}; use std::marker::PhantomData; use tensorflow_sys as tf; use crate::eager::{Context, ReadonlyTensor}; use crate::{AnyTensor, DataType, Result, Status, TensorType}; #[derive(Debug)] pub struct TensorHandle<'a> { pub(super) inner: *mut tf::TFE_TensorHandle, ctx: PhantomData<&...
q!(&h_gpu.device_name().unwrap(), target_device); let t2 = h_gpu.resolve::<i32>().unwrap(); assert_eq!(&values[..], &t2[..]); } } }
inner: *mut tf::TFE_TensorHandle, ) -> Self { Self { inner, ctx: PhantomData, } } } #[cfg(test)] mod tests { use super::*; use crate::eager::ContextOptions; use crate::Tensor; #[test] fn test_tensor_handle() { let opts = ContextOptions::n...
random
[ { "content": "/// Shorthand for `Abort::new().call(&ctx)`.\n\n///\n\n/// See : <https://www.tensorflow.org/api_docs/python/tf/raw_ops/Abort>\n\npub fn abort<'a>(ctx: &'a crate::eager::Context) -> crate::Result<()> {\n\n let op = Abort::new();\n\n op.call(ctx)\n\n}\n\n\n\n/// Abs\n\n///\n\n/// See : <https...
Rust
src/context.rs
PolySignInc/rust-secp256k1
0782872fb0bed2e9166e91e837b8242bcf761859
use core::marker::PhantomData; use core::mem::ManuallyDrop; use ptr; use ffi::{self, CPtr}; use ffi::types::{c_uint, c_void}; use Error; use Secp256k1; #[cfg(feature = "std")] pub use self::std_only::*; pub unsafe trait Context : private::Sealed { const FLAGS: c_uint; const DESCRIPTION: &'static str...
use core::marker::PhantomData; use core::mem::ManuallyDrop; use ptr; use ffi::{self, CPtr}; use ffi::types::{c_uint, c_void}; use Error; use Secp256k1; #[cfg(feature = "std")] pub use self::std_only::*; pub unsafe trait Context : private::Sealed { const FLAGS: c_uint; const DESCRIPTION: &'static str...
} impl<'buf> Secp256k1<AllPreallocated<'buf>> { pub fn preallocated_new(buf: &'buf mut [u8]) -> Result<Secp256k1<AllPreallocated<'buf>>, Error> { Secp256k1::preallocated_gen_new(buf) } pub fn preallocate_size() -> usize { Self::preallocate_size_gen() } ...
ocate_size_gen() { return Err(Error::NotEnoughMemory); } Ok(Secp256k1 { ctx: unsafe { ffi::secp256k1_context_preallocated_create( buf.as_mut_c_ptr() as *mut c_void, C::FLAGS) }, phantom: PhantomData, ...
function_block-function_prefixed
[ { "content": "fn verify<C: Verification>(secp: &Secp256k1<C>, msg: &[u8], sig: [u8; 64], pubkey: [u8; 33]) -> Result<bool, Error> {\n\n let msg = sha256::Hash::hash(msg);\n\n let msg = Message::from_slice(&msg)?;\n\n let sig = Signature::from_compact(&sig)?;\n\n let pubkey = PublicKey::from_slice(&p...
Rust
src/server.rs
jonastepe/pthreadbook-rs
c24a27ad5d7d96b24bd129289ed2a285423fa03a
use std::sync::{Condvar,Mutex,Arc}; use std::collections::VecDeque; use std::io::prelude::*; use std::thread; enum Request { Read(String, SyncType), Write(String), Quit, } enum SyncType { Sync(Arc<Response>), NonSync, } struct Response { ready: Condvar, payload: Mutex<Payload>, } struct ...
use std::sync::{Condvar,Mutex,Arc}; use std::collections::VecDeque; use std::io::prelude::*; use std::thread; enum Request { Read(String, SyncType), Write(String), Quit, } enum SyncType { Sync(Arc<Response>), NonSync, } struct Response { ready: Condvar, payload: Mutex<Payload>, } struct ...
server.clone(), write_req); thread::sleep(std::time::Duration::from_secs(1)); } }, }; } match client_threads.0.lock() { Err(e) => panic!(format!("Failed to lock client_threads mutex to decrement: {}", e)), Ok(mut num) => { ...
print!("{}", prompt); try!(std::io::stdout().flush()); try!(std::io::stdin().read_line(&mut buffer)); Ok(buffer.trim().to_string()) } fn server_request(server: Arc<Server>, request: Request) { match server.running.lock() { Err(e) => panic!(format!("Failed to lock mutex to start up a s...
random
[ { "content": "fn worker_func(data_vec: Arc<Vec<Data>>, mut thread_data: ThreadData) -> ThreadData {\n\n let mut index: usize = 0;\n\n let mut repeats: usize = 0;\n\n \n\n for iteration in 0..ITERATIONS {\n\n \n\n if iteration % thread_data.interval == 0 {\n\n match data_vec[...
Rust
edgelet/edgelet-http-mgmt/src/server/module/logs.rs
gri6507/iotedge
892c0cc94335472b69da6f254ec24afd824ae671
use failure::ResultExt; use futures::{future, Future, IntoFuture}; use hyper::{Body, Request, Response, StatusCode}; use url::form_urlencoded; use edgelet_core::{LogOptions, LogTail, ModuleRuntime, RuntimeOperation}; use edgelet_http::route::{Handler, Parameters}; use edgelet_http::Error as HttpError; use crate::er...
use failure::ResultExt; use futures::{future, Future, IntoFuture}; use hyper::{Body, Request, Response, StatusCode}; use url::form_urlencoded; use edgelet_core::{LogOptions, LogTail, ModuleRuntime, RuntimeOperation}; use edgelet_http::route::{Handler, Parameters}; use edgelet_http::Error as HttpError; use crate::er...
#[test] fn test_success() { let state = ModuleRuntimeState::default() .with_status(ModuleStatus::Running) .with_exit_code(Some(0)) .with_status_description(Some("description".to_string())) .with_started_at(Some(Utc.ymd(2018, 4, 13).and_hms_milli(14, 20, ...
y); assert!(options.is_err()); assert_eq!( "The request parameter `since` is malformed", options.err().unwrap().to_string() ); }
function_block-function_prefixed
[ { "content": "#[allow(clippy::needless_pass_by_value)]\n\nfn invalid_image_name_pull_handler(req: Request<Body>) -> ResponseFuture {\n\n // verify that path is /images/create and that the \"fromImage\" query\n\n // parameter has the image name we expect\n\n assert_eq!(req.uri().path(), \"/images/create...
Rust
nnef/src/framework.rs
mattalhonte/tract
67530c27fb757e116ed3cbcd2ff81cead05aaef2
use std::path::Path; use crate::ast::ProtoModel; use crate::internal::*; pub fn stdlib() -> Vec<FragmentDef> { crate::ast::parse::parse_fragments(include_str!("../stdlib.nnef")).unwrap() } pub struct Nnef { pub stdlib: Vec<FragmentDef>, pub registries: Vec<Registry>, } impl Nnef { pub fn new() -> Nn...
use std::path::Path; use crate::ast::ProtoModel; use crate::internal::*; pub fn stdlib() -> Vec<FragmentDef> { crate::ast::parse::parse_fragments(include_str!("../stdlib.nnef")).unwrap() } pub struct Nnef { pub stdlib: Vec<FragmentDef>, pub registries: Vec<Registry>, } impl Nnef { pub fn new() -> Nn...
fn model_for_proto_model(&self, proto: &ProtoModel) -> TractResult<TypedModel> { self.translate(proto).map_err(|e| e.1) } } fn read_stream<R: std::io::Read>( path: &std::path::Path, reader: &mut R, text: &mut Option<String>, tensors: &mut HashMap<String, Arc<Tensor>>, ) -> TractResult...
let text = text.ok_or_else(|| format!("Model must contain graph.nnef at top level"))?; let doc = crate::ast::parse::parse_document(&text)?; Ok(ProtoModel { doc, tensors }) }
function_block-function_prefix_line
[ { "content": "pub fn to_proto_model(framework: &Nnef, model: &TypedModel) -> TractResult<ProtoModel> {\n\n let mut into_ast = IntoAst::new(framework, model);\n\n into_ast.translate()?;\n\n into_ast.into_proto_model()\n\n}\n\n\n", "file_path": "nnef/src/ser.rs", "rank": 0, "score": 453007.20...
Rust
src/steps.rs
Baev1/cucumber-rust
2fb7e52a01118f03801664a4e4cce149bb3da7df
use std::rc::Rc; use cute_custom_default::CustomDefault; use crate::collection::StepsCollection; use crate::runner::{BasicStepFn, RegexStepFn}; use crate::World; use gherkin::StepType; #[derive(CustomDefault)] pub struct Steps<W: World> { pub(crate) steps: StepsCollection<W>, } impl<W: World> Steps<W> { p...
use std::rc::Rc; use cute_custom_default::CustomDefault; use crate::collection::StepsCollection; use crate::runner::{BasicStepFn, RegexStepFn}; use crate::World; use gherkin::StepType; #[derive(CustomDefault)] pub struct Steps<W: World> { pub(crate) steps: StepsCollection<W>, } impl<W: World> Steps<W> { p...
fn insert_regex_async( &mut self, ty: StepType, name: &'static str, test_fn: RegexStepFn<W>, ) -> &mut Self { let regex = regex::Regex::new(name) .unwrap_or_else(|_| panic!("`{}` is not a valid regular expression", name)); self.steps.insert_regex(ty,...
fn insert_sync( &mut self, ty: StepType, name: &'static str, test_fn: fn(W, Rc<gherkin::Step>) -> W, ) -> &mut Self { use futures::future::FutureExt; let test_fn = std::rc::Rc::new(move |world: W, step| { std::panic::AssertUnwindSafe(async mo...
function_block-full_function
[ { "content": "#[async_trait(?Send)]\n\npub trait World: Sized + UnwindSafe + 'static {\n\n type Error: std::error::Error;\n\n\n\n async fn new() -> Result<Self, Self::Error>;\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 88128.47541410085 }, { "content": "#[derive(CustomD...
Rust
src/db/file.rs
jackgerrits/docs.rs
8989f8d74f53943fa5701b231569ac21b4291343
use std::path::{PathBuf, Path}; use postgres::Connection; use rustc_serialize::json::{Json, ToJson}; use std::cmp; use std::fs; use std::io::Read; use error::Result; use failure::err_msg; use rusoto_s3::{S3, PutObjectRequest, GetObjectRequest, S3Client}; use rusoto_core::region::Region; use rusoto_credential::Default...
use std::path::{PathBuf, Path}; use postgres::Connection; use rustc_serialize::json::{Json, ToJson}; use std::cmp; use std::fs; use std::io::Read; use error::Result; use failure::err_msg; use rusoto_s3::{S3, PutObjectRequest, GetObjectRequest, S3Client}; use rusoto_core::region::Region; use rusoto_credential::Default...
&rows { let path: String = row.get(0); let mime: String = row.get(1); let content: Vec<u8> = row.get(2); let path_1 = path.clone(); futures.push(client.put_object(PutObjectRequest { bucket: S3_BUCKET_NAME.into(), key: path.clone(), body: Some(...
get_file_list(&path)?; let mut batch_size = cmp::min(to_upload.len(), MAX_CONCURRENT_UPLOADS); let mut currently_uploading: Vec<_> = to_upload.drain(..batch_size).collect(); let mut attempts = 0; while !to_upload.is_empty() || !currently_uploading.is_empty() { let mut futures = Vec::new(); ...
random
[ { "content": "/// Adds a crate to the blacklist.\n\npub fn add_crate(conn: &Connection, name: &str) -> Result<(), Error> {\n\n if is_blacklisted(conn, name)? {\n\n return Err(BlacklistError::CrateAlreadyOnBlacklist(name.into()).into());\n\n }\n\n\n\n conn.execute(\n\n \"INSERT INTO blackl...
Rust
ecmascript/parser/src/parser/ident.rs
JasperDeSutter/swc
bc4a2976e5ab4df35a669bb6e4c5aca06d2e489c
use super::*; use crate::token::Keyword; use either::Either; #[parser] impl<'a, I: Tokens> Parser<'a, I> { pub(super) fn parse_maybe_private_name(&mut self) -> PResult<'a, Either<PrivateName, Ident>> { let start = cur_pos!(); let is_private = is!('#'); if is_private { self.par...
use super::*; use crate::token::Keyword; use either::Either; #[parser] impl<'a, I: Tokens> Parser<'a, I> {
pub(super) fn parse_private_name(&mut self) -> PResult<'a, PrivateName> { let start = cur_pos!(); assert_and_bump!('#'); let hash_end = self.input.prev_span().hi(); if self.input.cur_pos() - hash_end != BytePos(0) { syntax_error!(span!(start), SyntaxError::SpaceBetween...
pub(super) fn parse_maybe_private_name(&mut self) -> PResult<'a, Either<PrivateName, Ident>> { let start = cur_pos!(); let is_private = is!('#'); if is_private { self.parse_private_name().map(Either::Left) } else { self.parse_ident_name().map(Either::Right) ...
function_block-full_function
[ { "content": "#[proc_macro_attribute]\n\npub fn parser(attr: TokenStream, item: TokenStream) -> TokenStream {\n\n let item = syn::parse(item).expect(\"failed to parse input as an item\");\n\n let item = expand::expand(attr.into(), item);\n\n\n\n print(\"parser\", item.dump())\n\n}\n", "file_path": ...
Rust
src/sync.rs
codeforks/glium
fb98803529996f2ead54784c4b8be29c80a92057
use context::CommandContext; use version::Api; use version::Version; use gl; use backend::Facade; use context::Context; use ContextExt; use std::rc::Rc; use std::thread; #[derive(Copy, Clone, Debug)] pub struct SyncNotSupportedError; pub struct SyncFence { context: Rc<Context>, id: Option<gl::types::GLsync>...
use context::CommandContext; use version::Api; use version::Version; use gl; use backend::Facade; use context::Context; use ContextExt; use std::rc::Rc; use std::thread; #[derive(Copy, Clone, Debug)] pub struct SyncNotSupportedError; pub struct SyncFence { context: Rc<Context>, id: Option<gl::types::GLsync>...
}) } else if ctxt.extensions.gl_apple_sync { Ok(LinearSyncFence { id: Some(ctxt.gl.FenceSyncAPPLE(gl::SYNC_GPU_COMMANDS_COMPLETE_APPLE, 0)), }) } else { Err(SyncNotSupportedError) } } #[inline] pub unsafe fn wait_linear_sync_fence_and_drop(mut fence: LinearSyncFence,...
f) { let sync = self.id.take().unwrap(); let mut ctxt = self.context.make_current(); let result = unsafe { client_wait(&mut ctxt, sync) }; unsafe { delete_fence(&mut ctxt, sync) }; match result { gl::ALREADY_SIGNALED | gl::CONDITION_SATISFIED => (), _ =>...
random
[ { "content": "pub fn sync_stencil(ctxt: &mut context::CommandContext, params: &Stencil) {\n\n // checks if stencil operations can be disabled\n\n if params.test_clockwise == StencilTest::AlwaysPass &&\n\n params.test_counter_clockwise == StencilTest::AlwaysPass &&\n\n params.fail_operation_clo...
Rust
web/src/responder/data.rs
DSpeckhals/bible.rs
f196ee37d5f7e929cc50bd9aaebd025cd0a707c1
use actix_web::HttpRequest; use handlebars::Handlebars; use log::error; use serde_derive::{Deserialize, Serialize}; use db::models::{Book, Reference, Verse, VerseFTS}; use crate::error::Error; use crate::responder::link::{verse_url, AllBooksLinks, BookLinks, Link, VersesLinks}; use crate::responder::meta::Meta; #[de...
use actix_web::HttpRequest; use handlebars::Handlebars; use log::error; use serde_derive::{Deserialize, Serialize}; use db::models::{Book, Reference, Verse, VerseFTS}; use crate::error::Error; use crate::responder::link::{verse_url, AllBooksLinks, BookLinks, Link, VersesLinks}; use crate::responder::meta::Meta; #[de...
; } #[test] fn template_data() { let mut tpl = Handlebars::new(); tpl.register_template_string("test", "<html></html") .unwrap(); let data = TemplateData::new(EmptyData {}, Meta::for_about()); let html = data.to_html("test", &tpl).unwrap(); assert!(html.s...
with_service(|req| { let prov = BOOKS[20]; let book = Book { id: 20, name: prov.0.to_string(), testament: Testament::Old, chapter_count: prov.1, }; let book_2 = book.clone(); let verses = vec![Ver...
call_expression
[ { "content": "/// Generates a book URL for the given book.\n\nfn book_url(b: &str, req: &HttpRequest) -> Link {\n\n Link::new(\n\n &req.url_for(\"book\", &[b]).unwrap_or_else(invalid_url),\n\n b.to_string(),\n\n )\n\n}\n\n\n", "file_path": "web/src/responder/link.rs", "rank": 0, ...
Rust
src/main.rs
cassaundra/raymarch
b3d763031c399f007508333fece880977187bfb3
use std::fs::File; use std::io::prelude::*; use std::time::{Duration, Instant}; #[macro_use] extern crate glium; use glium::{Display, glutin, index, Surface, VertexBuffer}; use glium::glutin::{ElementState, Event, VirtualKeyCode, WindowEvent}; mod math; use math::Vec3; #[derive(Debug)] struct Controls { left: bo...
use std::fs::File; use std::io::prelude::*; use std::time::{Duration, Instant}; #[macro_use] extern crate glium; use glium::{Display, glutin, index, Surface, VertexBuffer}; use glium::glutin::{ElementState, Event, VirtualKeyCode, WindowEvent}; mod math; use math::Vec3; #[derive(Debug)] struct Controls { left: bo...
fn update(&mut self, dt: f32, controls: &Controls) { let move_speed = 2.0 * dt; if controls.left { self.position -= self.right * move_speed; } if controls.right { self.position += self.right * move_speed; } if controls.up { self.po...
cos_phi * sin_theta, -sin_phi, cos_phi * cos_theta ); let right = Vec3::new( cos_theta, 0.0f32, -sin_theta ); let up = forward.cross(right).norm(); Camera { theta, phi, up, right, forward, position } }
function_block-function_prefix_line
[ { "content": "use std::ops;\n\n\n\n\n\n#[derive(Clone, Copy, Debug)]\n\npub struct Vec3 {\n\n pub x: f32,\n\n pub y: f32,\n\n pub z: f32\n\n}\n\n\n\nimpl Vec3 {\n\n pub fn new(x: f32, y: f32, z: f32) -> Self {\n\n Vec3 { x, y, z}\n\n }\n\n\n\n pub fn squared_length(self) -> f32 {\n\n ...
Rust
src/api/r0/login.rs
agraven/ruma-deprecated
8d0817090620f93dc9f421304154c7322f3ac6ab
use std::convert::TryFrom; use std::error::Error; use std::fmt::{Formatter, Result as FmtResult}; use bodyparser; use iron::{status, Chain, Handler, IronResult, Plugin, Request, Response}; use ruma_identifiers::UserId; use serde::de::{Deserialize, Deserializer, Error as SerdeError, Visitor}; use crate::authenticati...
use std::convert::TryFrom; use std::error::Error; use std::fmt::{Formatter, Result as FmtResult}; use bodyparser; use iron::{status, Chain, Handler, IronResult, Plugin, Request, Response}; use ruma_identifiers::UserId; use serde::de::{Deserialize, Deserializer, Error as SerdeError, Visitor}; use crate::authenticati...
?; } user_id } Err(_) => { UserId::try_from(format!("@{}:{}", login_request.user, &config.domain).as_ref()) .map_err(ApiError::from)? } }; let auth_params = AuthParams::Password(PasswordAuthParams {...
Err(ApiError::unauthorized( "User cannot be identified by this homeserver".to_string(), ))
call_expression
[ { "content": "/// Hash a password with Argon2.\n\npub fn hash_password(password: &str) -> Result<String, ApiError> {\n\n let salt = generate_salt()?;\n\n let encoded_hash = Encoded::default2i(password.as_bytes(), &salt, &[], &[]).to_u8();\n\n\n\n String::from_utf8(encoded_hash).map_err(ApiError::from)\...
Rust
gb_core/src/gameboy/ppu/mod.rs
bengdahl/gb-emu
add624277cc4334efb25d309b94ec7dc5edfefbb
pub mod color; pub mod consts; mod execute; pub mod frame; pub mod registers; use frame::Frame; use std::ops::{Deref, DerefMut, GeneratorState}; use gb_cpu::CpuOutputPins; use self::execute::PpuState; use super::Chip; pub struct Ppu { state: Option<Box<PpuState>>, gen: execute::PpuGenerator, } impl Ppu {...
pub mod color; pub mod consts; mod execute; pub mod frame; pub mod registers; use frame::Frame;
let basey = TILE_WIDTH * row; for col in 0..ROW_LENGTH { let basex = TILE_WIDTH * col; let tile_id = row * ROW_LENGTH + col; for offy in 0..TILE_WIDTH { let row_lo = self.tile_data[tile_id * 16 + 2 * offy + 0]; let row_...
use std::ops::{Deref, DerefMut, GeneratorState}; use gb_cpu::CpuOutputPins; use self::execute::PpuState; use super::Chip; pub struct Ppu { state: Option<Box<PpuState>>, gen: execute::PpuGenerator, } impl Ppu { pub fn new() -> Self { Ppu { state: Some(Box::new(PpuState::new())), ...
random
[ { "content": "pub fn gen() -> PpuGenerator {\n\n Box::pin(|mut state: Box<PpuState>| {\n\n macro_rules! ppu_yield {\n\n () => {\n\n state = yield state\n\n };\n\n }\n\n\n\n loop {\n\n // The window is rendered if ly==wy at any point during ...
Rust
src/handler.rs
bartlomieju/miette
5151411ebb3121379c18ad9ffff884f20547ff16
use std::fmt; use atty::Stream; use crate::protocol::Diagnostic; use crate::GraphicalReportHandler; use crate::GraphicalTheme; use crate::NarratableReportHandler; use crate::ReportHandler; use crate::ThemeCharacters; use crate::ThemeStyles; /** Create a custom [`MietteHandler`] from options. ## Example ```no_run m...
use std::fmt; use atty::Stream; use crate::protocol::Diagnostic; use crate::GraphicalReportHandler; use crate::GraphicalTheme; use crate::NarratableReportHandler; use crate::ReportHandler; use crate::ThemeCharacters; use crate::ThemeStyles; /** Create a custom [`MietteHandler`] from options. ## Example ```no_run m...
lf, context_lines: usize) -> Self { self.context_lines = Some(context_lines); self } pub fn tab_width(mut self, width: usize) -> Self { self.tab_width = Some(width); self } pub fn build(self) -> MietteHandler { let graphical = self.is_graphical(); ...
Default::default() } pub fn terminal_links(mut self, linkify: bool) -> Self { self.linkify = Some(linkify); self } pub fn graphical_theme(mut self, theme: GraphicalTheme) -> Self { self.theme = Some(theme); self } pu...
random
[ { "content": "/// Tells miette to render panics using its rendering engine.\n\npub fn set_panic_hook() {\n\n std::panic::set_hook(Box::new(move |info| {\n\n let mut message = \"Something went wrong\".to_string();\n\n let payload = info.payload();\n\n if let Some(msg) = payload.downcast_r...
Rust
tests/expectations/tests/union_bitfield_1_0.rs
tathanhdinh/rust-bindgen
f9b2007ecd830adec8d98a25bcc2f84c104076ac
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct __BindgenBitfieldUnit<Storage, Align> where Storage: AsRef<[u8]> + A...
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct __BindgenBitfieldUnit<Storage, Align> where Storage: AsRef<[u8]> + A...
} #[repr(C)] #[derive(Copy)] pub struct HasBigBitfield { pub _bitfield_1: __BindgenUnionField<__BindgenBitfieldUnit<[u8; 16usize], u64>>, pub bindgen_union_field: [u8; 16usize], } #[test] fn bindgen_test_layout_HasBigBitfield() { assert_eq!( ::std::mem::size_of::<HasBigBitfield>(), 16usize,...
let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize], u32> = Default::default(); __bindgen_bitfield_unit.set(0usize, 31u8, { let foo: u32 = unsafe { ::std::mem::transmute(foo) }; foo as u64 }); __bindgen_bitfield_unit.set(31usize, 1u8, { ...
function_block-function_prefix_line
[ { "content": "/// Returns the lower power of two byte count that can hold at most n bits.\n\npub fn bytes_from_bits_pow2(mut n: usize) -> usize {\n\n if n == 0 {\n\n return 0;\n\n }\n\n\n\n if n <= 8 {\n\n return 1;\n\n }\n\n\n\n if !n.is_power_of_two() {\n\n n = n.next_power...
Rust
compiler/rustc_middle/src/ty/list.rs
david-perez/rust
89b9f7b284aacc5f8613438b80e4dd7bdd10549e
use crate::arena::Arena; use rustc_serialize::{Encodable, Encoder}; use std::alloc::Layout; use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::iter; use std::mem; use std::ops::Deref; use std::ptr; use std::slice; #[repr(C)] pub struct List<T> { len: usize, data: [T; 0], ...
use crate::arena::Arena; use rustc_serialize::{Encodable, Encoder}; use std::alloc::Layout; use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::iter; use std::mem; use std::ops::Deref; use std::ptr; use std::slice; #[repr(C)] pub struct List<T> { len: usize, data: [T; 0], ...
} impl<T> Hash for List<T> { #[inline] fn hash<H: Hasher>(&self, s: &mut H) { (self as *const List<T>).hash(s) } } impl<T> Deref for List<T> { type Target = [T]; #[inline(always)] fn deref(&self) -> &[T] { self.as_ref() } } impl<T> AsRef<[T]> for List<T>...
fn partial_cmp(&self, other: &List<T>) -> Option<Ordering> { if self == other { Some(Ordering::Equal) } else { <[T] as PartialOrd>::partial_cmp(&**self, &**other) } }
function_block-full_function
[]
Rust
quinn-proto/src/token.rs
zz85/quinn
80376ff305f4ba538f14a954f4231953eea0839a
use std::{ fmt, io, net::{IpAddr, SocketAddr}, time::{Duration, SystemTime, UNIX_EPOCH}, }; use bytes::BufMut; use crate::{ coding::{BufExt, BufMutExt}, crypto::{AeadKey, CryptoError, HandshakeTokenKey, HmacKey}, shared::ConnectionId, RESET_TOKEN_SIZE, }; pub struct RetryToken<'a> { ...
use std::{ fmt, io, net::{IpAddr, SocketAddr}, time::{Duration, SystemTime, UNIX_EPOCH}, }; use bytes::BufMut; use crate::{ coding::{BufExt, BufMutExt}, crypto::{AeadKey, CryptoError, HandshakeTokenKey, HmacKey}, shared::ConnectionId, RESET_TOKEN_SIZE, }; pub struct RetryToken<'a> { ...
ndom_data); invalid_token.put_slice(&random_data); assert!(RetryToken::from_bytes(&prk, &addr, &retry_src_cid, &invalid_token).is_err()); let invalid_token = [0; 31]; rand::thread_rng().fill_bytes(&mut random_bytes); assert!(RetryToken::from_bytes(&prk, &addr...
keTokenKey::from_secret(&master_key); let addr = SocketAddr::new(Ipv6Addr::LOCALHOST.into(), 4433); let retry_src_cid = RandomConnectionIdGenerator::new(MAX_CID_SIZE).generate_cid(); let mut invalid_token = Vec::new(); invalid_token.put_slice(&random_bytes); let mut random_dat...
random
[ { "content": "pub fn decode<B: Buf>(size: u8, buf: &mut B) -> Result<(u8, usize), Error> {\n\n assert!(size <= 8);\n\n let mut first = buf.get::<u8>()?;\n\n\n\n // NOTE: following casts to u8 intend to trim the most significant bits, they are used as a\n\n // workaround for shiftoverflow error...
Rust
pac/atsam4e8e/src/pioe/pcmr.rs
haata/atsam4-pac
849dd8fcf3be0074d98b8fc65e4fb03fdfd4b6b1
#[doc = "Reader of register PCMR"] pub type R = crate::R<u32, super::PCMR>; #[doc = "Writer for register PCMR"] pub type W = crate::W<u32, super::PCMR>; #[doc = "Register PCMR `reset()`'s with value 0"] impl crate::ResetValue for super::PCMR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register PCMR"] pub type R = crate::R<u32, super::PCMR>; #[doc = "Writer for register PCMR"] pub type W = crate::W<u32, super::PCMR>; #[doc = "Register PCMR `reset()`'s with value 0"] impl crate::ResetValue for super::PCMR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
} #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } impl R { #[doc = "Bit 0 - Parallel Capture Mode Enable"] #[inline(always)] pub...
&'a mut W, } impl<'a> PCEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bit...
random
[]
Rust
crates/nu-command/src/commands/dataframe/where_.rs
margguo/nushell
e4c282f0a611face3b68dfb51780d5cc5f3347ed
use crate::prelude::*; use nu_engine::{evaluate_baseline_expr, WholeStreamCommand}; use nu_errors::ShellError; use nu_protocol::{ dataframe::{Column, NuDataFrame}, hir::{CapturedBlock, ClassifiedCommand, Expression, Literal, Operator, SpannedExpression}, Primitive, Signature, SyntaxShape, UnspannedPathMembe...
use crate::prelude::*; use nu_engine::{evaluate_baseline_expr, WholeStreamCommand}; use nu_errors::ShellError; use nu_protocol::{ dataframe::{Column, NuDataFrame}, hir::{CapturedBlock, ClassifiedCommand, Expression, Literal, Operator, SpannedExpression}, Primitive, Signature, SyntaxShape, UnspannedPathMembe...
(pat) => { let casted = col.utf8().map_err(|e| { parse_polars_error::<&str>(&e, &args.call_info.name_tag.span, None) })?; casted.contains(pat).map_err(|e| { parse_polars_error::<&str>(&e, &args.call_info.name_ta...
; [1 2] [3 4]] | dataframe to-df | dataframe where a == 1", result: Some(vec![NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![UntaggedValue::int(1).into()]), Column::new("b".to_string(), vec![UntaggedValue::int(2).into()]), ...
random
[ { "content": "#[cfg(feature = \"dataframe\")]\n\npub fn test_dataframe(cmd: impl WholeStreamCommand + 'static) -> Result<(), ShellError> {\n\n use nu_protocol::UntaggedValue;\n\n\n\n let examples = cmd.examples();\n\n\n\n let base_context = EvaluationContext::basic();\n\n\n\n base_context.add_comman...
Rust
criner/src/persistence/table.rs
crates-io/criner
040cd804266a3cb1942177361842661267d37b2a
use crate::persistence::KEY_SEP_CHAR; use crate::{ model::{Context, Crate, TaskResult}, model::{CrateVersion, Task}, persistence::{merge::Merge, Keyed}, Result, }; use rusqlite::{params, OptionalExtension}; use std::time::{Duration, SystemTime}; pub type ThreadSafeConnection = std::sync::Arc<parking_lo...
use crate::persistence::KEY_SEP_CHAR; use crate::{ model::{Context, Crate, TaskResult}, model::{CrateVersion, Task}, persistence::{merge::Merge, Keyed}, Result, }; use rusqlite::{params, OptionalExtension}; use std::time::{Duration, SystemTime}; pub type ThreadSafeConnection = std::sync::Arc<parking_lo...
} pub fn key_value_iter<'stm, 'conn, StorageItem>( statement: &'stm mut rusqlite::Statement<'conn>, ) -> Result<impl Iterator<Item = Result<(String, StorageItem)>> + 'stm> where StorageItem: for<'a> From<&'a [u8]>, { Ok(statement .query_map([], |r| { let key = r.get::<_, String>(0)?; ...
Ok(statement .query_map([], |r| r.get::<_, Vec<u8>>(0).map(|v| StorageItem::from(v.as_slice())))? .map(|r| r.map_err(Into::into)))
call_expression
[ { "content": "pub fn tar_path_to_utf8_str(mut bytes: &[u8]) -> &str {\n\n // Tar paths include the parent directory, cut it to crate relative paths\n\n if let Some(pos) = bytes.iter().position(|b| *b == b'/' || *b == b'\\\\') {\n\n bytes = bytes.get(pos + 1..).unwrap_or(bytes);\n\n }\n\n std:...
Rust
src/test/ui/privacy/private-inferred-type.rs
adnanademovic/rust
88f755f8a84df1d9e6b17cf10c96ae8b93481b2e
#![feature(decl_macro)] #![allow(private_in_public)] mod m { fn priv_fn() {} static PRIV_STATIC: u8 = 0; enum PrivEnum { Variant } pub enum PubEnum { Variant } trait PrivTrait { fn method() {} } impl PrivTrait for u8 {} pub trait PubTrait { fn method() {} } impl PubTrait for u8 {} s...
#![feature(decl_macro)] #![allow(private_in_public)] mod m { fn priv_fn() {} static PRIV_STATIC: u8 = 0; enum PrivEnum { Variant } pub enum PubEnum { Variant } trait PrivTrait { fn method() {} } impl PrivTrait for u8 {} pub trait PubTrait { fn method() {} } impl PubTrait for u8 {} s...
eak_dyn3(); let a = m::Alias {}; let mut b = a; b = a; match a { _ => {} } }
cTy = Alias> { 0 } pub fn leak_dyn1() -> Box<Trait + 'static> { Box::new(0) } pub fn leak_dyn2() -> Box<TraitWithTyParam<Alias>> { Box::new(0) } pub fn leak_dyn3() -> Box<TraitWithAssocTy<AssocTy = Alias>> { Box::new(0) } } mod adjust { use std::ops::Deref; pub struct S1; struct S2; ...
random
[]
Rust
src/dataflow/src/server/metrics.rs
PedramNavid/materialize
757b376c11a28fb3429e52cb591288dcfb038c06
use std::collections::HashMap; use ore::metrics::{ CounterVecExt, DeleteOnDropCounter, DeleteOnDropGauge, GaugeVecExt, MetricsRegistry, }; use ore::{ metric, metrics::{IntCounterVec, IntGaugeVec}, }; use super::PendingPeek; use dataflow_types::client::{Command, ComputeCommandKind, StorageCommandKind}; u...
use std::collections::HashMap; use ore::metrics::{ CounterVecExt, DeleteOnDropCounter, DeleteOnDropGauge, GaugeVecExt, MetricsRegistry, }; use ore::{ metric, metrics::{IntCounterVec, IntGaugeVec}, }; use super::PendingPeek; use dataflow_types::client::{Command, ComputeCommandKind, StorageCommandKind}; u...
fn observe(&mut self, command: &Command) { let metrics_name = command.metric_name(); *self.cache.entry(metrics_name).or_insert(0) += 1; } fn finish(&mut self) { for (key, count) in self.cache.drain() { self.counters[key].inc_by(count); } } }
let names = compute_names.chain(storage_names); CommandsProcessedMetrics { cache: names.clone().map(|name| (name, 0)).collect(), counters: names .map(|name| { ( name, commands_processed_metric ...
function_block-function_prefix_line
[ { "content": "fn create_address_row(id: i64, worker: i64, address: &[usize]) -> Row {\n\n let id_datum = Datum::Int64(id);\n\n let worker_datum = Datum::Int64(worker);\n\n // we're collecting into a Vec because we need to iterate over the Datums\n\n // twice: once for determining the size of the row...
Rust
server/src/db/access.rs
mwatts/influxdb_iox
f085af034ee411e6e8357955ab7048607a3bdb55
use crate::{db::system_tables, JobRegistry}; use std::{any::Any, sync::Arc}; use super::{ catalog::{Catalog, TableNameFilter}, chunk::DbChunk, Error, Result, }; use async_trait::async_trait; use data_types::chunk_metadata::ChunkSummary; use datafusion::{ catalog::{catalog::CatalogProvider, schema::S...
use crate::{db::system_tables, JobRegistry}; use std::{any::Any, sync::Arc}; use super::{ catalog::{Catalog, TableNameFilter}, chunk::DbChunk, Error, Result, }; use async_trait::async_trait; use data_types::chunk_metadata::ChunkSummary; use datafusion::{ catalog::{catalog::CatalogProvider, schema::S...
} impl CatalogProvider for QueryCatalogAccess { fn as_any(&self) -> &dyn Any { self as &dyn Any } fn schema_names(&self) -> Vec<String> { vec![ DEFAULT_SCHEMA.to_string(), system_tables::SYSTEM_SCHEMA.to_string(), ] } fn schema(&self, name: &str) -...
fn table_schema(&self, table_name: &str) -> Option<Arc<Schema>> { self.catalog .table(table_name) .ok() .map(|table| Arc::clone(&table.schema().read())) }
function_block-full_function
[]
Rust
src/args.rs
nokia/nperf
20e4ddc2bf8895d96664ab839a64c36f416023c8
use std::ffi::OsString; use structopt::StructOpt; use perf_event_open::EventSource; use crate::cmd_collate::CollateFormat; fn parse_event_source( source: &str ) -> EventSource { match source { "hw_cpu_cycles" => EventSource::HwCpuCycles, "hw_ref_cpu_cycles" => EventSource::HwRefCpuCycles, ...
use std::ffi::OsString; use structopt::StructOpt; use perf_event_open::EventSource; use crate::cmd_collate::CollateFormat; fn parse_event_source( source: &str ) -> EventSource { match source { "hw_cpu_cycles" => EventSource::HwCpuCycles, "hw_ref_cpu_cycles" => EventSource::HwRefCpuCycles, ...
d::process::exit( 1 ); } } } pub enum TargetProcess { ByPid( u32 ), ByName( String ), ByNameWaiting( String, u64 ) } #[derive(StructOpt, Clone, Debug)] #[structopt(rename_all = "kebab-case")] pub struct ProcessFilter { #[structopt( long, short = "p", raw(requir...
match try_parse_period( period ) { Ok( period ) => period, Err( _ ) => { eprintln!( "error: invalid '--period' specified" ); st
function_block-random_span
[ { "content": "pub fn wait_for_process( sigint: &SigintHandler, process: &str, duration: u64 ) -> io::Result< Option< u32 > > {\n\n info!( \"Waiting for process named '{}'...\", process );\n\n\n\n let timestamp = Instant::now();\n\n loop {\n\n if let Some( _ ) = find_process( process )? {\n\n ...