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
geo/src/algorithm/simplify.rs
BaptisteB-A/geo
15a48fe3a949f5b9537f224308c3ee86c8f25712
use crate::algorithm::euclidean_distance::EuclideanDistance; use crate::{Line, LineString, MultiLineString, MultiPolygon, Point, Polygon}; use num_traits::Float; fn rdp<T>(points: &[Point<T>], epsilon: &T) -> Vec<Point<T>> where T: Float, { if points.is_empty() { return points.to_vec(); } let m...
use crate::algorithm::euclidean_distance::EuclideanDistance; use crate::{Line, LineString, MultiLineString, MultiPolygon, Point, Polygon}; use num_traits::Float; fn rdp<T>(points: &[Point<T>], epsilon: &T) -> Vec<Point<T>> where T: Float, { if points.is_empty() { return points.to_vec(); } let m...
; let mpoly2 = mpoly.simplify(&2.); assert_eq!( mpoly2, MultiPolygon(vec![Polygon::new( LineString::from(vec![(0., 0.), (0., 10.), (10., 10.), (10., 0.), (0., 0.)]), vec![], )]) ); } }
MultiPolygon(vec![Polygon::new( LineString::from(vec![ (0., 0.), (0., 10.), (5., 11.), (10., 10.), (10., 0.), (0., 0.), ]), vec![], )])
call_expression
[ { "content": "// much of the following code is ported from Java, copyright 1999 Hormoz Pirzadeh, available at:\n\n// http://web.archive.org/web/20150330010154/http://cgm.cs.mcgill.ca/%7Eorm/rotcal.html\n\nfn unitvector<T>(slope: &T, poly: &Polygon<T>, p: Point<T>, idx: usize) -> Point<T>\n\nwhere\n\n T: Floa...
Rust
server/src/auth.rs
dicej/tagger
8dfc3c16eba8e356c39f7aed974ae8c9b741835c
use { crate::warp_util::HttpError, anyhow::Result, http::{header, status::StatusCode, Response}, hyper::Body, jsonwebtoken::{self, Algorithm, DecodingKey, EncodingKey, Header, Validation}, sqlx::SqliteConnection, std::{ num::NonZeroU32, ops::DerefMut, sync::Arc, ...
use { crate::warp_util::HttpError, anyhow::Result, http::{header, status::StatusCode, Response}, hyper::Body, jsonwebtoken::{self, Algorithm, DecodingKey, EncodingKey, Header, Validation}, sqlx::SqliteConnection, std::{ num::NonZeroU32, ops::DerefMut, sync::Arc, ...
} pub fn authorize(token: &str, key: &[u8]) -> Result<Arc<Authorization>, HttpError> { Ok(Arc::new( jsonwebtoken::decode::<Authorization>( token, &DecodingKey::from_secret(key), &Validation::new(Algorithm::HS256), ) .map_err(|e| { warn!("rece...
Ok(if let Some(permissions) = permissions { let expiration = (SystemTime::now() + Duration::from_secs(TOKEN_EXPIRATION_SECS)) .duration_since(UNIX_EPOCH)? .as_secs(); let success = TokenSuccess { access_token: jsonwebtoken::encode( &Header::new(Algori...
call_expression
[ { "content": "fn maybe_wrap_filter(filter: &mut Option<TagExpression>, auth: &Authorization) {\n\n if let Some(user_filter) = &auth.filter {\n\n if let Some(inner) = filter.take() {\n\n *filter = Some(TagExpression::And(\n\n Box::new(inner),\n\n Box::new(user_f...
Rust
src/state/world/mod.rs
z2oh/roguelike_experiment
ec05616cf285db79dc8f8b0569fd837506b1fda6
use std::collections::HashMap; use crate::util::prelude::*; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct WorldId(u32); #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct MaterialId(u32); #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Tick(u64); impl std::ops::Add<u64> for T...
use std::collections::HashMap; use crate::util::prelude::*; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct WorldId(u32); #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct MaterialId(u32); #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Tick(u64); impl std::ops::Add<u64> for T...
}
2 { flat_map[(y * self.width as i32 + x) as usize] = '.'; } } } let regions_wide = (self.width / REGION_DIM as u32) + 1; let regions_tall = (self.height / REGION_DIM as u32) + 1; for ry in 0..regions_tall { for rx in 0..region...
function_block-function_prefixed
[ { "content": "struct CachedRegion {\n\n tick: Tick,\n\n region: GfxRegion\n\n}\n\n\n\npub struct WorldRenderer {\n\n world_id: WorldId,\n\n render_modifiers: HashSet<RenderModifier>,\n\n render_cache: HashMap<(i32, i32, i32), CachedRegion>,\n\n camera: gfx::camera::Camera,\n\n}\n\n\n\nconst OF...
Rust
src/book/walk.rs
toyboot4e/adbook
416f3ad7f9bd12e6799b22102c752cd06463df78
/*! Book builder */ use { anyhow::*, indicatif::{ProgressBar, ProgressStyle}, std::{ path::{Path, PathBuf}, sync::{Arc, Mutex}, }, }; use crate::book::{ toc::{Toc, TocItem}, BookStructure, }; pub trait BookBuilder: Clone + Send + Sync { fn can_skip_build(&se...
/*! Book builder */ use { anyhow::*, indicatif::{ProgressBar, ProgressStyle}, std::{ path::{Path, PathBuf}, sync::{Arc, Mutex}, }, }; use crate::book::{ toc::{Toc, TocItem}, BookStructure, }; pub trait BookBuilder: Clone + Send + Sync { fn can_skip_build(&se...
pub async fn walk_book_async<V: BookBuilder + 'static>(v: &mut V, book: &BookStructure, log: bool) { let src_files = self::list_src_files(&book); let mut errors = Vec::with_capacity(16); let filtered = src_files .into_iter() .filter(|src_file| { let mut v = v....
function_block-full_function
[ { "content": "/// Recursively runs given procedure to files just under the directory\n\n///\n\n/// The user procedure takes an absolute path as a parameter.\n\n///\n\n/// Stops immediately when any error is found.\n\npub fn visit_files_rec(dir: &Path, proc: &mut impl FnMut(&Path) -> Result<()>) -> Result<()> {\...
Rust
crate/src/editor.rs
deep-gaurav/dcodefront
aae7b73b9e58dfe67a5e0dcc81853fafd3a352e9
use yew::prelude::*; use wasm_bindgen::JsCast; use web_sys::HtmlElement; use super::editor_src::AceEditor; use super::file_manager::{FsEntry}; use super::socket_agent::{AgentInput,AgentOutput,SocketAgent,TransferData}; use lazy_static::lazy_static; use std::collections::HashMap; use maplit::hashmap; use std::iter::Dou...
use yew::prelude::*; use wasm_bindgen::JsCast; use web_sys::HtmlElement; use super::editor_src::AceEditor; use super::file_manager::{FsEntry}; use super::socket_agent::{AgentInput,AgentOutput,SocketAgent,TransferData}; use lazy_static::lazy_static; use std::collections::HashMap; use maplit::hashmap; use std::iter::Dou...
fn mounted(&mut self)->bool{ let par:HtmlElement = self.editor_ref.cast().expect("Not HtmlElement"); let editor=AceEditor::new(par); editor.set_mode_from_filename(&self.props.file.path); self.editor=Some( editor ); false } fn update(&mut self,ms...
fn create(props: Self::Properties, link: ComponentLink<Self>)->Self{ let propsc = props.file.clone(); let mut bridge = SocketAgent::bridge(link.callback(move|out|{ if let AgentOutput::SocketMessage(data)=out{ Msg::SocketMessage(data) } else if let AgentOutput::Sav...
function_block-full_function
[ { "content": "#[derive(Serialize)]\n\nstruct AceConfig{\n\n enableBasicAutocompletion: bool,\n\n enableSnippets: bool,\n\n enableLiveAutocompletion: bool\n\n}\n\n\n\nimpl AceEditor{\n\n\n\n pub fn new(parent:HtmlElement)->AceEditor{\n\n let parent_jsval:&JsValue = parent.as_ref();\n\n ...
Rust
src/verify.rs
epage/toml-test-rs
6e22ca1caf547324463e2c98b81063f40477bdcc
use std::io::Write; pub trait Encoder { fn encode(&self, data: crate::decoded::Decoded) -> Result<String, crate::Error>; fn verify_valid_case(&self, decoded: &[u8], fixture: &dyn Decoder) -> Result<(), crate::Error> { let decoded_expected = crate::decoded::Decoded::from_slice(decoded)?; let ac...
use std::io::Write; pub trait Encoder { fn encode(&self, data: crate::decoded::Decoded) -> Result<String, crate::Error>; fn verify_valid_case(&self, decoded: &[u8], fixture: &dyn Decoder) -> Result<(), crate::Error> { let decoded_expected = crate::decoded::Decoded::from_slice(decoded)?; let ac...
fn name(&self) -> &str; } pub trait Decoder { fn decode(&self, data: &[u8]) -> Result<crate::decoded::Decoded, crate::Error>; fn verify_valid_case(&self, fixture: &[u8], expected: &[u8]) -> Result<(), crate::Error> { let actual = self.decode(fixture)?; let expected = crate::decoded::Deco...
e.decode(actual.as_bytes()).map_err(|err| { crate::Error::new(format!( "Could not parse encoded TOML: {}\n```\n{}\n```", err, actual )) })?; if decoded_actual == decoded_expected { Ok(()) } else { Err(crate::Error::...
function_block-function_prefixed
[ { "content": "pub fn invalid() -> impl Iterator<Item = Invalid<'static>> {\n\n let invalid_dir = TESTS_DIR.get_dir(\"invalid\").unwrap();\n\n assert!(invalid_dir.files().is_empty());\n\n invalid_dir.dirs().iter().flat_map(|d| {\n\n assert!(d.dirs().is_empty());\n\n d.files().iter().map(|f...
Rust
experimental/encoding_bench/src/capnproto.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
pub mod ingress { #[derive(Copy, Clone)] pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined f...
pub mod ingress { #[derive(Copy, Clone)] pub struct Owned; impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } impl ::capnp::traits::Pipelined f...
inline] pub fn get_source(self) -> u64 { self.builder.get_data_field::<u64>(0) } #[inline] pub fn set_source(&mut self, value: u64) { self.builder.set_data_field::<u64>(0, value); } #[inline] pub fn get_receiver(self) -> u64 { self.builder.get_data_field::<u64>(1) } ...
#[inline] fn type_id() -> u64 { _private::TYPE_ID } } impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { Reader { reader: reader, } } } impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reade...
random
[]
Rust
adm/src/commands/batch.rs
CLEckhardt/sawtooth-core
241cf34695ca1b2aab5c99959fe4cf7ca2a091c4
use clap::ArgMatches; use sawtooth::client::{ rest::RestApiSawtoothClientBuilder, Batch, SawtoothClient, SawtoothClientError as ClientError, SawtoothClientError, }; use serde::Serialize; use crate::err::CliError; pub fn run<'a>(args: &ArgMatches<'a>) -> Result<(), CliError> { match args.subcommand() { ...
use clap::ArgMatches; use sawtooth::client::{ rest::RestApiSawtoothClientBuilder, Batch, SawtoothClient, SawtoothClientError as ClientError, SawtoothClientError, }; use serde::Serialize; use crate::err::CliError; pub fn run<'a>(args: &ArgMatches<'a>) -> Result<(), CliError> { match args.subcommand() { ...
#[derive(Debug, Serialize)] struct StructuredOutputBatch { batch_id: String, signer: String, txns: usize, } impl<'a> From<&'a Batch> for StructuredOutputBatch { fn from(batch: &Batch) -> Self { StructuredOutputBatch { batch_id: batch.header_signature.to_string(), signe...
n()) } } } for row in table.iter() { let mut col_string = String::from(""); for (i, len) in max_lengths.iter().enumerate() { if let Some(value) = row.get(i) { col_string += &format!("{}{} ", value, " ".repeat(*len - value.len()),); ...
function_block-function_prefixed
[ { "content": "pub fn run<'a>(args: &ArgMatches<'a>) -> Result<(), CliError> {\n\n let path_config = config::get_path_config();\n\n let key_dir = &path_config.key_dir;\n\n if !key_dir.exists() {\n\n return Err(CliError::EnvironmentError(format!(\n\n \"Key directory does not exist: {:?}...
Rust
crates/interpreter/src/instr/primitive.rs
Robbepop/runwell
0e5186ce79b4de9957c3e35a904eaee07813c662
use crate::InterpretationError; #[rustfmt::skip] mod conv { pub fn reg_to_i8(reg: u64) -> i8 { reg as u8 as i8 } pub fn reg_to_i16(reg: u64) -> i16 { reg as u16 as i16 } pub fn reg_to_i32(reg: u64) -> i32 { reg as u32 as i32 } pub fn reg_to_i64(reg: u64) -> i64 { reg as u64 as i64 } pub fn reg_to...
use crate::InterpretationError; #[rustfmt::skip] mod conv { pub fn reg_to_i8(reg: u64) -> i8 { reg as u8 as i8 } pub fn reg_to_i16(reg: u64) -> i16 { reg as u16 as i16 } pub fn reg_to_i32(reg: u64) -> i32 { reg as u32 as i32 } pub fn reg_to_i64(reg: u64) -> i64 { r
self.checked_div(rhs).ok_or(InterpretationError::DivisionByZero) } fn checked_rem(self, rhs: Self) -> Result<Self, InterpretationError> { self.checked_rem(rhs).ok_or(InterpretationError::DivisionByZero) } } )* }; ...
eg as u64 as i64 } pub fn reg_to_u8(reg: u64) -> u8 { reg as u8 } pub fn reg_to_u16(reg: u64) -> u16 { reg as u16 } pub fn reg_to_u32(reg: u64) -> u32 { reg as u32 } pub fn reg_to_u64(reg: u64) -> u64 { reg } pub fn i8_to_reg(val: i8) -> u64 { val as u8 as u64 } pub fn i16_to_reg(val: i16) -> u6...
random
[ { "content": "/// Parses the binary WebAssembly (Wasm) bytes given through `reader`.\n\n///\n\n/// Returns the fully parsed and validated Wasm module.\n\n///\n\n/// # Note\n\n///\n\n/// Reuses the allocation from the `buffer` bytes vector.\n\n///\n\n/// # Errors\n\n///\n\n/// - If the given Wasm does not valida...
Rust
src/config_core/catch.rs
exogress/exogress
643ac113066ce0d517929f518c6ca47f1ec23b35
use crate::{ config_core::{ referenced::Container, status_code::{StatusCode, StatusCodeRangeParseError}, StaticResponse, StatusCodeRange, }, entities::{ schemars::{gen::SchemaGenerator, schema::Schema}, Exception, ExceptionParseError, StaticResponseName, }, }; use...
use crate::{ config_core::{ referenced::Container, status_code::{StatusCode, StatusCodeRangeParseError}, StaticResponse, StatusCodeRange, }, entities::{ schemars::{gen::SchemaGenerator, schema::Schema}, Exception, ExceptionParseError, StaticResponseName, }, }; use...
} #[derive(Debug, thiserror::Error)] pub enum CatchMatcherParseError { #[error("unknown kind")] UnknownKind, #[error("exception matcher parse error: {_0}")] ExceptionParseError(#[from] ExceptionParseError), #[error("status code range parse error: {_0}")] StatusCodeRangeParseError(#[from] Sta...
fn to_string(&self) -> String { match self { CatchMatcher::StatusCode(codes) => { format!("status-code:{}", codes.to_string()) } CatchMatcher::Exception(exception) => { format!("exception:{}", exception.to_string()) } } ...
function_block-full_function
[ { "content": "pub trait Config: Serialize + DeserializeOwned + Debug + Clone + Hash {\n\n type Error: std::error::Error;\n\n\n\n fn checksum(&self) -> u64;\n\n fn check_mount_points(&self, existing: &[MountPointName]) -> Result<(), Self::Error>;\n\n fn validate(&self) -> Result<(), Self::Error>;\n\n...
Rust
src/games.rs
Lokathor/randomize
951347d23c35ce6ad713c2925581d6c56724d08f
use super::*; mod standard_die; pub use standard_die::*; mod exploding_die; pub use exploding_die::*; #[inline] pub fn dice(g: &mut impl Gen32, mut count: i32, sides: i32) -> i32 { use core::cmp::Ordering; let range = match sides.cmp(&1) { Ordering::Less => return 0, Ordering::Equal => return count, ...
use super::*; mod standard_die; pub use standard_die::*; mod exploding_die; pub use exploding_die::*; #[inline] pub fn dice(g: &mut impl Gen32, mut count: i32, sides: i32) -> i32 { use core::cmp::Ordering; let range = match sides.cmp(&1) { Ordering::Less => return 0, Ordering::Equal => return count, ...
x(1), 2 => X4.sample(g).wrapping_sub(1).max(1), 3 => X4.sample(g), 4 => X6.sample(g), 5 => X8.sample(g), 6 => X10.sample(g), 7 => X12.sample(g), 8 => X6.sample(g).wrapping_add(X6.sample(g)), 9 => X8.sample(g).wrapping_add(X6.sample(g)), 10 => X8.sa...
step > 13 { total = total.wrapping_add(X12.sample(g)); step -= 7; } total.wrapping_add(match step { 1 => X4.sample(g).wrapping_sub(2).ma
random
[ { "content": "#[inline]\n\npub fn next_binary_exp_distr32<G: Gen32 + ?Sized>(g: &mut G) -> u32 {\n\n // This function provided by <https://github.com/orlp>\n\n\n\n let r: u32 = g.next_u32();\n\n if r > 0 {\n\n r.trailing_zeros()\n\n } else {\n\n 32 + next_binary_exp_distr32(g)\n\n }\n\n}\n\n\n", ...
Rust
language/move-lang/src/cfgir/cfg.rs
lifesboy/libra
3193ec4b7afff05e9476fd923f331f18fb7f3050
use super::ast::*; use crate::errors::*; use std::collections::{BTreeMap, BTreeSet, VecDeque}; pub trait CFG { fn successors(&self, label: Label) -> &BTreeSet<Label>; fn predecessors(&self, label: Label) -> &BTreeSet<Label>; fn commands<'a>(&'a self, label: Label) -> Box<dyn Iterator<Item = (usize, &'a ...
use super::ast::*; use crate::errors::*; use std::collections::{BTreeMap, BTreeSet, VecDeque}; pub trait CFG { fn successors(&self, label: Label) -> &BTreeSet<Label>; fn predecessors(&self, label: Label) -> &BTreeSet<Label>; fn commands<'a>(&'a self, label: Label) -> Box<dyn Iterator<Item = (usize, &'a ...
} impl<'a> CFG for BlockCFG<'a> { fn successors(&self, label: Label) -> &BTreeSet<Label> { self.successor_map.get(&label).unwrap() } fn predecessors(&self, label: Label) -> &BTreeSet<Label> { self.predecessor_map.get(&label).unwrap() } fn commands<'s>(&'s self, label: Label) -> B...
pub fn display_blocks(&self) { for (lbl, block) in self.blocks() { println!("--BLOCK {}--", lbl); for cmd in block { println!("{:#?}", cmd.value); } println!(); } }
function_block-full_function
[ { "content": "pub fn code(mut blocks: Vec<Vec<F::Bytecode>>) -> Vec<F::Bytecode> {\n\n let mut offset = 0;\n\n let mut label_to_offset = HashMap::new();\n\n for (lbl, block) in blocks.iter().enumerate() {\n\n label_to_offset.insert(lbl as u16, offset.try_into().unwrap());\n\n offset += bl...
Rust
src/main.rs
Chi-Task-Force/Chi-Telegram-Inline-Bot-Neo
34642d5e5d906fb769e7e06ec5fcee0a7f285674
#![allow( clippy::non_ascii_literal, clippy::cast_lossless, clippy::module_name_repetitions )] use std::env; use std::fs::File; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use mongodb::Client; use parking_lot::RwLock; use teloxide::dispatching2::{Dispatcher, HandlerExt, UpdateFilte...
#![allow( clippy::non_ascii_literal, clippy::cast_lossless, clippy::module_name_repetitions )] use std::env; use std::fs::File; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use mongodb::Client; use parking_lot::RwLock; use teloxide::dispatching2::{Dispatcher, HandlerExt, UpdateFilte...
b_db_name = env::var("APP_MONGODB_DBNAME").expect("missing mongodb dbname"); let client = Client::with_uri_str(mongodb_uri).await?; let db = client.database(mongodb_db_name.as_str()); let migrate_log = env::var("APP_MIGRATE_LOG").ok(); if let Some(migrate_log) = migrate_log { let f = File::open...
function_block-function_prefixed
[ { "content": "#[allow(clippy::cast_sign_loss)]\n\npub fn mask_user(user: i64) -> String {\n\n format!(\"{:x}\", md5::compute((user as u128).to_le_bytes()))\n\n}\n", "file_path": "src/utils.rs", "rank": 0, "score": 53132.13487551771 }, { "content": "fn random_text() -> String {\n\n let ...
Rust
src/bin/rustfmt.rs
casey/rustfmt
90db34a9618011e5ac189612e7954624582cf05a
#![cfg(not(test))] extern crate log; extern crate rustfmt; extern crate toml; extern crate env_logger; extern crate getopts; use rustfmt::{run, Input, Summary}; use rustfmt::file_lines::FileLines; use rustfmt::config::{Config, WriteMode}; use std::{env, error}; use std::fs::{self, File}; use std::io::{self, ErrorK...
#![cfg(not(test))] extern crate log; extern crate rustfmt; extern crate toml; extern crate env_logger; extern crate getopts; use rustfmt::{run, Input, Summary}; use rustfmt::file_lines::FileLines; use rustfmt::config::{Config, WriteMode}; use std::{env, error}; use std::fs::{self, File}; use std::io::{self, ErrorK...
}); } fn determine_operation(matches: &Matches) -> FmtResult<Operation> { if matches.opt_present("h") { return Ok(Operation::Help); } if matches.opt_present("config-help") { return Ok(Operation::ConfigHelp); } if matches.opt_present("version") { return Ok(Operati...
nwrap_or("unknown"), COMMIT_HASH.unwrap_or("git commit unavailable"), match WORKTREE_CLEAN { Some(false) => " worktree dirty", _ => "",
function_block-random_span
[ { "content": "// Formatting done on a char by char or line by line basis.\n\n// FIXME(#209) warn on bad license\n\n// FIXME(#20) other stuff for parity with make tidy\n\nfn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &mut FormatReport) {\n\n // Iterate over the chars in the fil...
Rust
src/raycast.rs
DarinM223/mold2d
776c5b7f45a4c61acaad0e380eece60c3088d236
use crate::collision::CollisionSide; use crate::vector::Vector2D; use crate::viewport::Viewport; use sdl2::pixels::Color; use sdl2::rect::{Point, Rect}; use sdl2::render::Renderer; use std::error::Error; #[derive(Clone, Debug, PartialEq)] pub struct Segment { pub point: (f64, f64), pub vector: Vector...
use crate::collision::CollisionSide; use crate::vector::Vector2D; use crate::viewport::Viewport; use sdl2::pixels::Color; use sdl2::rect::{Point, Rect}; use sdl2::render::Renderer; use std::error::Error; #[derive(Clone, Debug, PartialEq)] pub struct Segment { pub point: (f64, f64), pub vector: Vector...
#[test] fn test_shorten_ray_top() { let rect = Rect::new(2, 3, 2, 2); let mut segment = Segment { point: (3., 0.), vector: Vector2D { x: 0., y: 4. }, }; let side = shorten_ray(&mut segment, &rect); assert_eq!(side, Some(CollisionSide::Top)); ...
fn test_shorten_ray_left() { let rect = Rect::new(2, 3, 2, 2); let mut segment = Segment { point: (0., 3.), vector: Vector2D { x: 4., y: 0. }, }; let side = shorten_ray(&mut segment, &rect); assert_eq!(side, Some(CollisionSide::Left)); assert_eq!(...
function_block-full_function
[ { "content": "/// Returns the center point of a rectangle as a tuple of decimals\n\npub fn center_point(rect: &Rect) -> (f64, f64) {\n\n (\n\n f64::from(rect.x()) + 0.5 * f64::from(rect.width()),\n\n f64::from(rect.y()) + 0.5 * f64::from(rect.height()),\n\n )\n\n}\n\n\n\n#[repr(u8)]\n\n#[der...
Rust
termio/src/string.rs
nathdobson/rust-public
cad37803e239e92dfeb2be61716502e521138eec
use crate::screen::Style; use std::fmt::{Display, Arguments}; use std::collections::BTreeMap; use std::fmt::Write; use std::{iter, fmt}; use itertools::Itertools; use crate::color::Color; use serde::{Serialize, Deserialize}; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)] pub struct __UseD...
use crate::screen::Style; use std::fmt::{Display, Arguments}; use std::collections::BTreeMap; use std::fmt::Write; use std::{iter, fmt}; use itertools::Itertools; use crate::color::Color; use serde::{Serialize, Deserialize}; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)] pub struct __UseD...
formatter.push()); } } } } macro_rules! style_format_display { ($($xs:ty)*) => { $( impl StyleFormat for $xs { fn style_format(&self, mut formatter: StyleFormatter) { write!(formatter, "{}", self); } } ...
writer, style: StyleOption::default(), } } pub fn push<'b>(&'b mut self) -> StyleFormatter<'b> { StyleFormatter { writer: self.writer, style: self.style, } } pub fn push_style<'b>(&'b mut self, style: StyleOption) -> StyleFormatter<'b...
random
[ { "content": "pub trait Keys: Hash + Eq + Clone + Debug + Send + 'static {}\n\n\n\nimpl<T> Keys for T where T: Hash + Eq + Clone + Debug + Send + 'static, T: Tuple, T::TupleList: KeyList {}\n", "file_path": "metric/src/keys.rs", "rank": 0, "score": 362895.02894857794 }, { "content": "pub tra...
Rust
src/common.rs
Erutuon/templatehoard-server
8cbf06bc72e13e7aa5a56c6d52d9138860db1e1f
use memmap::Mmap; use regex::{Error as RegexError, Regex}; use serde::{ de, ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer, }; use std::{ collections::BTreeMap, fmt::{Debug, Display, Formatter, Result as FmtResult}, fs::File, io::Result as IoResult, ops::Deref, path::...
use memmap::Mmap; use regex::{Error as RegexError, Regex}; use serde::{ de, ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer, }; use std::{ collections::BTreeMap, fmt::{Debug, Display, Formatter, Result as FmtResult}, fs::File, io::Result as IoResult, ops::Deref, path::...
} #[derive(Debug, Clone)] pub struct RegexWrapper(Regex); impl Deref for RegexWrapper { type Target = Regex; fn deref(&self) -> &Self::Target { &self.0 } } impl From<Regex> for RegexWrapper { fn from(regex: Regex) -> Self { RegexWrapper(regex) } } impl FromStr for RegexWrapper ...
state.serialize_field("title", &self.title.into_inner())?; state.serialize_field("templates", &self.templates)?; state.end() }
function_block-function_prefix_line
[ { "content": "fn spaces_to_underscores(s: &mut str) {\n\n unsafe {\n\n for b in s.as_bytes_mut().iter_mut() {\n\n if *b == b' ' {\n\n *b = b'_';\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<Query> for Args {\n\n type Error = Error;\n\n\n\n fn try_from...
Rust
src/pmap.rs
msp432-rust/msp432p401r-hal
77afff974865fa31f77fd7d47abd91eb859ba791
pub use pac::PMAP; pub use pac::pmap; use cortex_m::interrupt; use crate::gpio::{Alternate, Primary}; const UNLOCK_KEY: u16 = 0x2D52; const OFFSET0: u16 = 0x0000; const OFFSET1: u16 = 0x0008; static mut PORT_MAP: PmapControl = PmapControl {map: None}; #[derive(Debug, Clone, Copy)] #[repr(u8)] pub enum Mapping { ...
pub use pac::PMAP; pub use pac::pmap; use cortex_m::interrupt; use crate::gpio::{Alternate, Primary}; const UNLOCK_KEY: u16 = 0x2D52; const OFFSET0: u16 = 0x0000; const OFFSET1: u16 = 0x0008; static mut PORT_MAP: PmapControl = PmapControl {map: None}; #[derive(Debug, Clone, Copy)] #[repr(u8)] pub enum Mapping { ...
} pub trait PortMap { fn remap(self, mapping: Mapping, allow_reconfiguration: bool) -> Self; } macro_rules! portmap { ($($PI_i:ident, $portx:ident, $pimapxy:ident, $offset:ident),*) => { $( use crate::gpio::$portx::$PI_i; impl PortMap for $PI_i<Alternate<Primary>> { ...
f.map.as_ref().unwrap().pmapkeyid.write(|w| unsafe { w.pmapkey().bits(UNLOCK_KEY) }); } self }
function_block-function_prefixed
[ { "content": "#[doc(hidden)]\n\npub trait SmclkState {\n\n fn div(&self) -> Option<SMPrescaler>;\n\n}\n\n\n\nimpl SmclkState for SmclkDefined {\n\n fn div(&self) -> Option<SMPrescaler> {\n\n Some(*&self.0)\n\n }\n\n}\n\n\n\n/// Builder object that configures system clocks\n\n/// Can only commit ...
Rust
src/main.rs
cgwalters/mygithubstatus
be79892e7dbcdae2b961b6ebbb6f8558bf630e2c
use anyhow::Result; use chrono::prelude::*; use serde_derive::*; use std::collections::{BTreeMap, HashMap}; use structopt::StructOpt; const STARTING_HOUR: u32 = 6; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct Actor { pub id: u64, pub login: String, } #[derive...
use anyhow::Result; use chrono::prelude::*; use serde_derive::*; use std::collections::{BTreeMap, HashMap}; use structopt::StructOpt; const STARTING_HOUR: u32 = 6; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct Actor { pub id: u64, pub login: String, } #[derive...
#[tokio::main] async fn main() -> Result<()> { simple_logger::SimpleLogger::from_env().init().unwrap(); let opt = Opt::from_args(); let user = opt.user.as_str(); let c = github_v3::Client::new_from_env(); let day = Local::today() - chrono::Duration::days(opt.previous_day as i64); let span = ma...
println!(); } if !events.issues.is_empty() { println!("Commented: "); for (url, _) in events.issues.iter() { let title = events.titles.get(url).map(|s| s.as_str()).unwrap_or(""); println!(" - 📝 {}", link(url.as_str(), title)); } ...
function_block-function_prefix_line
[ { "content": "# A tool to render my github activity for the last day\n\n\n\nPlaying around with a tool to render my activity on Github\n\nin Markdown form so that I can copy/paste it into status.\n", "file_path": "README.md", "rank": 10, "score": 18563.75935854189 }, { "content": "# Debuggin...
Rust
src/download_view.rs
kennroo/titanium
0da011f0aab57477c7af8ad096d92b0194f13cf2
/* * Copyright (c) 2016-2018 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
/* * Copyright (c) 2016-2018 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
} else { self.model.download.cancel(); } self.model.relm.stream().emit(Remove); } fn destination(&mut self, destination: String) { if let Some(filename) = urls::get_filename(&destination) { self.model.filename = filename; } self.m...
if let Some(ref destination) = self.model.original_destination { let _ = remove_file(destination); }
if_condition
[ { "content": "/// Open a file in a new process.\n\npub fn open_app_for_file(url: String) {\n\n thread::spawn(move ||\n\n open::that(url).ok()\n\n );\n\n}\n", "file_path": "src/file.rs", "rank": 0, "score": 276788.7817346044 }, { "content": "/// Get the filename from the URL.\n\n...
Rust
chain-crypto/src/algorithms/sumed25519/sumrec.rs
cameron1024/chain-libs
2744ba2d3980e025b728293cb2ec08372d5f0526
#![allow(clippy::large_enum_variant)] use super::common::{self, Depth, Seed}; use ed25519_dalek as ed25519; use ed25519_dalek::{Signer as _, Verifier as _}; pub enum SecretKey { Leaf(ed25519::Keypair), Node(usize, Depth, Box<SecretKey>, Seed, PublicKey, PublicKey), } #[derive(Clone)] pub enum PublicKey { ...
#![allow(clippy::large_enum_variant)] use super::common::{self, Depth, Seed}; use ed25519_dalek as ed25519; use ed25519_dalek::{Signer as _, Verifier as _}; pub enum SecretKey { Leaf(ed25519::Keypair), Node(usize, Depth, Box<SecretKey>, Seed, PublicKey, PublicKey), } #[derive(Clone)] pub enum PublicKey { ...
#[allow(dead_code)] pub fn verify(pk: &PublicKey, m: &[u8], sig: &Signature) -> bool { match sig { Signature::Leaf(s) => match pk { PublicKey::Leaf(pk) => pk.verify(m, s).is_ok(), PublicKey::Node(_) => panic!("xxxxxxxx"), }, Signature::Node(tsig, depth, sigma, pk0, ...
re::Leaf(sigma) } SecretKey::Node(t, depth, sk, _, pk0, pk1) => { let sigma = if t < &depth.half() { sign(sk, m) } else { sign(sk, m) }; Signature::Node(*t, *depth, Box::new(sigma), pk0.clone(), pk1.clone()) ...
function_block-function_prefixed
[ { "content": "pub fn verify(pk: &PublicKey, m: &[u8], sig: &Signature) -> bool {\n\n // verify the signature of the leaf\n\n if sig.pk().verify(m, &sig.sigma()).is_err() {\n\n return false;\n\n }\n\n\n\n let t = sig.t();\n\n\n\n // verify that we have the expected root public key afterall\...
Rust
virtio_sys/src/virtio_ring.rs
google/crosvm
df929efce3261ca5383f66eea6c7041b3439eb77
/* automatically generated by tools/bindgen-all-the-things */ #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { ...
/* automatically generated by tools/bindgen-all-the-things */ #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { ...
} #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct vring_packed_desc_event { pub off_wrap: __le16, pub flags: __le16, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct vring_packed_desc { pub addr: __le64, pub len: __le32, pub id: __le16, pub flags: __le16, }
let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } }
function_block-function_prefix_line
[ { "content": "/// Constructor for a conventional segment GDT (or LDT) entry. Derived from the kernel's segment.h.\n\npub fn gdt_entry(flags: u16, base: u32, limit: u32) -> u64 {\n\n (((base as u64) & 0xff000000u64) << (56 - 24))\n\n | (((flags as u64) & 0x0000f0ffu64) << 40)\n\n | (((limit as u...
Rust
src/lib.rs
snarkyboojum/aes_gcm
c99346c47d9a317a8bbe7d31a3a59cb0e8e66265
/* References: [1] https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf Implementation notes: Authenticated encryption function Input data: - plaintext, P - additional authenticated data (AAD), A - initialisation vector (IV), IV (basically a nonce) GCM protects the authenticity of both ...
/* References: [1] https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf Implementation notes: Authenticated encryption function Input data: - plaintext, P - additional authenticated data (AAD), A - initialisation vector (IV), IV (basically a nonce) GCM protects the authenticity of both ...
fn build_tag( additional_data: &[u8], ciphertext: &mut [u8], hash_subkey: u128, key_schedule: &[u32; 44], j0: u128, tag: &mut Vec<u8>, tag_size: usize, ) { let cipher_len = ciphertext.len() * 8; let ad_len = additional_data.len() * 8; let u = 128 * ((cipher_len + 128 - 1) / 128...
fn init_iv(iv_bytes: &[u8], hash_subkey: u128) -> u128 { assert!(iv_bytes.len() <= 16); let mut padded_iv = Vec::<u128>::new(); let j0; let iv = u8_to_u128(iv_bytes); if iv_bytes.len() == 12 { j0 = iv << 32 | 0x00000001; } else { let s = 128 * (((iv_bytes.len() * 8) + 128 - 1) ...
function_block-full_function
[ { "content": "## Overview\n\n\n\nThis library provides a GCM mode for AES (currently AES-128).\n\n\n\n## Resources\n\n\n\n- [Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf)\n\n- [Cryptographic ...
Rust
cfgrammar/src/lib/yacc/ast.rs
michelleyw/grmtools
efa06b86283dde34f9c63f6933abb0f620703501
use std::{ collections::{HashMap, HashSet}, error::Error, fmt, }; use indexmap::{IndexMap, IndexSet}; use super::Precedence; pub struct GrammarAST { pub start: Option<String>, pub rules: IndexMap<String, Rule>, pub prods: Vec<Production>, pub tokens: IndexSet<String>, pub precs: ...
use std::{ collections::{HashMap, HashSet}, error::Error, fmt, }; use indexmap::{IndexMap, IndexSet}; use super::Precedence; pub struct GrammarAST { pub start: Option<String>, pub rules: IndexMap<String, Rule>, pub prods: Vec<Production>, pub tokens: IndexSet<String>, pub precs: ...
; } } } for rule in self.rules.values() { for &pidx in &rule.pidxs { let prod = &self.prods[pidx]; if let Some(ref n) = prod.precedence { if !self.tokens.contains(n) { return Err(GrammarVa...
Err(GrammarValidationError { kind: GrammarValidationErrorKind::InvalidStartRule, sym: Some(Symbol::Rule(s.clone())), })
call_expression
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // Since we're using both lrlex and lrpar, we use lrlex's `lrpar_config` convenience function\n\n // that makes it easy to a) create a lexer and parser and b) link them together.\n\n CTLexerBuilder::new()\n\n .lrpar_config(|...
Rust
surface-dtx-userd/src/main.rs
runekaagaard/surface-dtx-daemon
d8948fba93645de1a926782720c402f89a551d39
mod error; use error::{Error, ErrorKind, ErrorStr, Result, ResultExt, CliResult}; mod cli; mod config; use config::Config; mod notify; use notify::{Notification, NotificationHandle, Timeout}; use std::rc::Rc; use std::cell::Cell; use slog::{Logger, debug, crit, o}; use tokio::prelude::*; use tokio::reactor::Handl...
mod error; use error::{Error, ErrorKind, ErrorStr, Result, ResultExt, CliResult}; mod cli; mod config; use config::Config; mod notify; use notify::{Notification, NotificationHandle, Timeout}; use std::rc::Rc; use std::cell::Cell; use slog::{Logger, debug, crit, o}; use tokio::prelude::*; use tokio::reactor::Handl...
g, "Error: {}", err); for cause in err.iter_causes() { crit!(log, "Caused by: {}", cause); } panic!(format!("{}", err)) }
function_block-function_prefixed
[ { "content": "fn panic_with_critical_error(log: &Logger, err: &Error) -> ! {\n\n crit!(log, \"Error: {}\", err);\n\n for cause in err.iter_causes() {\n\n crit!(log, \"Caused by: {}\", cause);\n\n }\n\n\n\n panic!(format!(\"{}\", err))\n\n}\n", "file_path": "surface-dtx-daemon/src/main.rs"...
Rust
src/extractor.rs
sadsnake42/paperoni
1cbbc7527f012e7649b79a4f90fa391d0bfbc45e
use std::collections::HashMap; use kuchiki::{traits::*, NodeRef}; use crate::errors::PaperoniError; use crate::moz_readability::{MetaData, Readability}; pub type ResourceInfo = (String, Option<String>); lazy_static! { static ref ESC_SEQ_REGEX: regex::Regex = regex::Regex::new(r#"(&|<|>|'|")"#).unwrap(); } pub ...
use std::collections::HashMap; use kuchiki::{traits::*, NodeRef}; use crate::errors::PaperoniError; use crate::moz_readability::{MetaData, Readability}; pub type ResourceInfo = (String, Option<String>); lazy_static! { static ref ESC_SEQ_REGEX: regex::Regex = regex::Regex::new(r#"(&|<|>|'|")"#).unwrap(); } pub ...
VIVEDYFOUYQFWD"> </article> <footer> <p>Made in HTML</p> </footer> </body> </html> "#; #[test] fn test_extract_img_urls() { let mut extractor = Extractor::from_html(TEST_HTML, "http://example.com/"); ...
}, kuchiki::iter::NodeEdge::End(n) => match n.data() { kuchiki::NodeData::Element(elem_data) => { write!(&mut w, "</{}>", &elem_data.name.local)?; } _ => (), }, } } Ok(()) } #[cfg(test)] mod test { ...
random
[ { "content": "pub fn is_match_ok_maybe(match_str: &str) -> bool {\n\n lazy_static! {\n\n static ref OK_MAYBE_REGEX: Regex =\n\n Regex::new(r\"(?i)and|article|body|column|content|main|shadow\").unwrap();\n\n }\n\n OK_MAYBE_REGEX.is_match(match_str)\n\n}\n\n\n", "file_path": "src/mo...
Rust
src/pk/ec.rs
lkatalin/mbedtls
15f195ebd7d3c396498ae2838a249192d12abbe3
/* Copyright (c) Fortanix, Inc. * * Licensed under the GNU General Public License, version 2 <LICENSE-GPL or * https://www.gnu.org/licenses/gpl-2.0.html> or the Apache License, Version * 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your * option. This file may not be copied, modified, or ...
/* Copyright (c) Fortanix, Inc. * * Licensed under the GNU General Public License, version 2 <LICENSE-GPL or * https://www.gnu.org/licenses/gpl-2.0.html> or the Apache License, Version * 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your * option. This file may not be copied, modified, or ...
)] #[repr(C)] struct EcpKeypair; const init: fn() -> Self = mbedtls_ecp_keypair_init; const drop: fn(&mut Self) = mbedtls_ecp_keypair_free; impl<'a> Into<ptr> {} impl<'a> UnsafeFrom<ptr> {} ); define!( #[c_ty(mbedtls_ecdh_context)] #[repr(C)] struct Ecdh; const init: fn() -> Sel...
CURVE448, } ); impl From<mbedtls_ecp_group_id> for EcGroupId { fn from(inner: mbedtls_ecp_group_id) -> EcGroupId { match inner { MBEDTLS_ECP_DP_NONE => EcGroupId::None, MBEDTLS_ECP_DP_SECP192R1 => EcGroupId::SecP192R1, MBEDTLS_ECP_DP_SECP224R1 => EcGroupId::SecP224R1...
random
[ { "content": "#[derive(Copy, Clone, Debug, Eq, PartialEq)]\n\nenum Test {\n\n CallbackSetVerifyFlags,\n\n CallbackError,\n\n}\n\n\n", "file_path": "tests/ssl_conf_verify.rs", "rank": 0, "score": 64606.402038384134 }, { "content": "#[derive(Debug, Clone)]\n\nenum AuthenticatedSafe {\n\n...
Rust
automerge-backend/src/actor_map.rs
datalayer-externals/automerge-rs
3c0c407192076cf97ab4e51f439dc00ead04ea6b
use std::cmp::Ordering; use automerge_protocol as amp; use smol_str::SmolStr; use crate::{ expanded_op::ExpandedOp, internal::{ActorId, ElementId, InternalOp, Key, ObjectId, OpId}, }; #[derive(PartialEq, Debug, Clone, Default)] pub(crate) struct ActorMap(Vec<amp::ActorId>); impl ActorMap { pub fn import...
use std::cmp::Ordering; use automerge_protocol as amp; use smol_str::SmolStr; use crate::{ expanded_op::ExpandedOp, internal::{ActorId, ElementId, InternalOp, Key, ObjectId, OpId}, }; #[derive(PartialEq, Debug, Clone, Default)] pub(crate) struct ActorMap(Vec<amp::ActorId>); impl ActorMap { pub fn import...
fn cmp_opid(&self, op1: &OpId, op2: &OpId) -> Ordering { if op1.0 == op2.0 { let actor1 = &self.0[(op1.1).0]; let actor2 = &self.0[(op2.1).0]; actor1.cmp(actor2) } else { op1.0.cmp(&op2.0) } } }
pub fn key_to_string(&self, key: &Key) -> SmolStr { match &key { Key::Map(s) => s.clone(), Key::Seq(eid) => self.elementid_to_string(eid), } }
function_block-function_prefix_line
[ { "content": "fn print_opid(opid: &crate::types::OpId, actor_shorthands: &HashMap<usize, String>) -> String {\n\n format!(\"{}@{}\", opid.counter(), actor_shorthands[&opid.actor()])\n\n}\n", "file_path": "rust/automerge/src/visualisation.rs", "rank": 0, "score": 333750.9852664324 }, { "co...
Rust
src/protocol_parser.rs
YangKeao/Qingtuan
932fb11a9adf371b8ddddb9ec08f61ae3ea86509
use crate::database::*; use crate::slice::Slice; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::io::{Read, Write}; use std::net::TcpStream; pub struct Protocol { stream: TcpStream, } impl From<TcpStream> for Protocol { fn from(stream: TcpStream) -> Self { return Protocol { stream };...
use crate::database::*; use crate::slice::Slice; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::io::{Read, Write}; use std::net::TcpStream; pub struct Protocol { stream: TcpStream, } impl From<TcpStream>
} } } } impl<T: Read> ProtocolReader for T {} pub trait ProtocolWriter: Write { fn write_prefix(&mut self, prefix: Prefix) { match prefix { Prefix::Count => self.write_u8('*' as u8).unwrap(), Prefix::String => self.write_u8('$' as u8).unwrap(), }; ...
for Protocol { fn from(stream: TcpStream) -> Self { return Protocol { stream }; } } pub enum Prefix { Count, String, } pub trait ProtocolReader: Read { fn read_prefix(&mut self) -> Prefix { match self.read_u8().unwrap().into() { '*' => Prefix::Count, '$' =>...
random
[ { "content": "#[derive(Clone)]\n\nstruct Key {\n\n version_number: u32,\n\n data: Slice,\n\n}\n\n\n\nimpl PartialOrd for Key {\n\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n\n match self.data.partial_cmp(&other.data).unwrap() {\n\n Ordering::Less => Some(Ordering::Les...
Rust
src/main.rs
ErickHdez96/Chor
2f889695beb2ee3becc61417585185a0308bd164
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; extern crate chor; use chor::Chip8; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; use std...
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; extern crate chor; use chor::Chip8; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; use std...
Key::A => chip_8.release_key(8), Key::S => chip_8.release_key(9), Key::D => chip_8.release_key(10), Key::F => chip_8.release_key(11), Key::Z => chip_8.release_key(12), Key::X => chip_8.release_key(13), Key::C => chi...
_key(3), Key::Q => chip_8.press_key(4), Key::W => chip_8.press_key(5), Key::E => chip_8.press_key(6), Key::R => chip_8.press_key(7), Key::A => chip_8.press_key(8), Key::S => chip_8.press_key(9), Key::D => chi...
random
[ { "content": "# Chor\n\nChip 8 emulator written in Rust using **piston** for the graphics.\n\n\n\n## Space Invaders\n\n\n\n#### Controls\n\n```\n\nW - Start game\n\n\n\nQ - Move Left\n\nW - Shoot\n\nE - Move Right\n\n```\n\n\n\n<p align=\"center\">\n\n\n\n![Space Invaders Start Screen](images/space-invaders-sta...
Rust
tests/smoke.rs
soywod/maildir
3288a0022b336f989f55ee40c0efe48099c33c94
use maildir::*; #[cfg(unix)] use std::borrow::Cow; #[cfg(unix)] use std::ffi::OsStr; #[cfg(windows)] use std::ffi::OsString; use std::fs; #[cfg(unix)] use std::os::unix::ffi::OsStrExt; #[cfg(windows)] use std::os::windows::ffi::{OsStrExt, OsStringExt}; use mailparse::MailHeaderMap; use percent_encoding::percent_decod...
use maildir::*; #[cfg(unix)] use std::borrow::Cow; #[cfg(unix)] use std::ffi::OsStr; #[cfg(windows)] use std::ffi::OsString; use std::fs; #[cfg(unix)] use std::os::unix::ffi::OsStrExt; #[cfg(windows)] use std::os::windows::ffi::{OsStrExt, OsStringExt}; use mailparse::MailHeaderMap; use percent_encoding::percent_decod...
#[test] fn check_store_cur() { with_maildir_empty("maildir2", |maildir| { maildir.create_dirs().unwrap(); let testflags = "FRS"; assert_eq!(maildir.count_cur(), 0); maildir .store_cur_with_flags(TEST_MAIL_BODY, testflags) .unwrap(); assert_eq!(maild...
fn check_store_new() { with_maildir_empty("maildir2", |maildir| { maildir.create_dirs().unwrap(); assert_eq!(maildir.count_new(), 0); let id = maildir.store_new(TEST_MAIL_BODY); assert!(id.is_ok()); assert_eq!(maildir.count_new(), 1); let id = id.unwrap(); l...
function_block-full_function
[ { "content": "fn list_mail(mail: MailEntry) {\n\n println!(\"Path: {}\", mail.path().display());\n\n println!(\"ID: {}\", mail.id());\n\n println!(\"Flags: {}\", mail.flags());\n\n println!(\"is_draft: {}\", mail.is_draft());\n\n println!(\"is_flagged: {}\", mail.is...
Rust
tests/src/tlua/functions_write.rs
chertov/tarantool-module
d0f92a7510eda72e058b752ce4596fa1a5f9480f
use tarantool::tlua::{ self, function, AsLua, Lua, LuaFunction, Function, function0, function1, function2, }; use std::sync::Arc; pub fn simple_function() { let lua = Lua::new(); fn ret5() -> i32 { 5 } let f: function![() -> i32] = function0(ret5); lua.s...
use tarantool::tlua::{ self, function, AsLua, Lua, LuaFunction, Function, function0, function1, function2, }; use std::sync::Arc; pub fn simple_function() { let lua = Lua::new(); fn ret5() -> i32 { 5 } let f: function![() -> i32] = function0(ret5); lua.s...
ert!(err_msg.starts_with("Execution error: " )); assert!(err_msg.ends_with( "> catch this")); }
lua.push(f).read().unwrap(); let () = f.call().unwrap(); assert_eq!(unsafe { GLOBAL_DATA }, 1); let () = f.call().unwrap(); assert_eq!(unsafe { GLOBAL_DATA }, 2); fn access_global_state() { unsafe { GLOBAL_DATA += 1 } } } pub fn push_callback_by_ref() { let lua...
random
[ { "content": "pub fn typename(lua: impl AsLua, index: i32) -> &'static CStr {\n\n unsafe {\n\n let lua_type = ffi::lua_type(lua.as_lua(), index);\n\n let typename = ffi::lua_typename(lua.as_lua(), lua_type);\n\n CStr::from_ptr(typename)\n\n }\n\n}\n\n\n", "file_path": "tlua/src/li...
Rust
src/dataset.rs
domoinc/domo-rust-sdk
3be85e61225591f5205e43772ca06599d3909d84
use super::util; use domo::public::dataset::{DataSet, Policy}; use domo::public::Client; use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt, Debug)] pub enum DataSetCommand { #[structopt(name = "list")] List { #[structopt(short = "l", long = "limit")] limit: Option<u32>...
use super::util; use domo::public::dataset::{DataSet, Policy}; use domo::public::Client; use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt, Debug)] pub enum DataSetCommand { #[structopt(name = "list")] List { #[structopt(short = "l", long = "limit")] limit: Option<u32>...
t r = util::edit_obj(editor, r, "").unwrap(); let r = dc.post_dataset(r).await.unwrap(); util::obj_template_output(r, template); } DataSetCommand::Retrieve { id } => { let r = dc.get_dataset(&id).await.unwrap(); util::obj_template_output(r, template); ...
function_block-function_prefixed
[ { "content": "pub fn query_template_output(r: QueryResult, template: Option<String>) {\n\n match template.as_deref() {\n\n Some(\"debug\") => println!(\"{:#?}\", r),\n\n Some(\"json\") => {\n\n println!(\"{}\", serde_json::to_string(&r).unwrap());\n\n }\n\n Some(\"yaml\...
Rust
src/editor_transport.rs
Screwtapello/kak-lsp
e39f73a76ef145bcf069b0ae125fc5a63c6a5466
use crossbeam_channel::{after, bounded, Receiver, Sender}; use std::fs; use std::io::{stderr, stdout, Read, Write}; use std::net::{IpAddr, SocketAddr, TcpListener}; use std::os::unix::net::{UnixListener, UnixStream}; use std::process::{exit, Command, Stdio}; use std::thread; use std::time::Duration; use toml; use types...
use crossbeam_channel::{after, bounded, Receiver, Sender}; use std::fs; use std::io::{stderr, stdout, Read, Write}; use std::net::{IpAddr, SocketAddr, TcpListener}; use std::os::unix::net::{UnixListener, UnixStream}; use std::process::{exit, Command, Stdio}; use std::thread; use std::time::Duration; use toml; use types...
rite to editor stdin"); } } child.wait().unwrap(); } Err(e) => error!("Failed to run Kakoune: {}", e), } } }); (writer_tx, reader_rx) } pub fn start_tcp...
ssion) = config.server.session { let session = session.to_string(); let timeout = config.server.timeout; if timeout > 0 { let (timeout_tx, timeout_rx) = bounded(1); thread::spawn(move || { let timeout = Duration::from_secs(timeout); loop {...
random
[ { "content": "pub fn start(config: &Config, initial_request: Option<&str>) {\n\n info!(\"Starting Controller\");\n\n\n\n let extensions = extension_to_language_id_map(&config);\n\n let languages = config.language.clone();\n\n\n\n let (editor_tx, editor_rx) = editor_transport::start(config, initial_r...
Rust
kernel/arch/x64/interrupt.rs
CProgrammer21/kerla
f55fa00c23fd2628cf53411d50d093cc43c76220
use super::{ apic::ack_interrupt, ioapic::VECTOR_IRQ_BASE, serial::SERIAL_IRQ, PageFaultReason, UserVAddr, }; use crate::{ interrupt::handle_irq, mm::page_fault::handle_page_fault, process::{current_process, signal::SIGSEGV, Process}, timer::handle_timer_irq, }; use x86::{controlregs::cr2, current:...
use super::{ apic::ack_interrupt, ioapic::VECTOR_IRQ_BASE, serial::SERIAL_IRQ, PageFaultReason, UserVAddr, }; use crate::{ interrupt::handle_irq, mm::page_fault::handle_page_fault, process::{current_process, signal::SIGSEGV, Process}, timer::handle_timer_irq, }; use x86::{controlregs::cr2, current:...
pub unsafe fn enable_interrupt() { asm!("sti"); } pub fn is_interrupt_enabled() -> bool { x86::current::rflags::read().contains(RFlags::FLAGS_IF) }
unsafe extern "C" fn x64_handle_interrupt(vec: u8, frame: *const InterruptFrame) { let frame = &*frame; const TIMER_IRQ: u8 = 0; const TIMER_IRQ2: u8 = 2; if vec != VECTOR_IRQ_BASE + TIMER_IRQ && vec != VECTOR_IRQ_BASE + TIMER_IRQ2 && vec != 14 && vec != 36 { tr...
function_block-full_function
[ { "content": "pub fn handle_irq(irq: u8) {\n\n let handler = &mut IRQ_HANDLERS.lock()[irq as usize];\n\n unsafe { (*handler.assume_init_mut())(); }\n\n process_packets();\n\n}\n", "file_path": "kernel/interrupt.rs", "rank": 0, "score": 133088.01321969042 }, { "content": "pub fn enab...
Rust
src/cells.rs
ray33ee/Torpedo
23fff0067e5cee444b2f9b4bc8751989a0ddc3d9
use std::net::{IpAddr, Ipv4Addr}; use chrono::{DateTime, Local}; use torserde_macros::Torserde; use torserde::{TorSerde, NLengthVector, VersionsVector}; use std::io::{Read, Write}; use std::borrow::{BorrowMut}; use lazy_static::lazy_static; use ring::rand::SecureRandom; use crate::misc::UnpackedCell; lazy_static!{...
use std::net::{IpAddr, Ipv4Addr}; use chrono::{DateTime, Local}; use torserde_macros::Torserde; use torserde::{TorSerde, NLengthVector, VersionsVector}; use std::io::{Read, Write}; use std::borrow::{BorrowMut}; use lazy_static::lazy_static; use ring::rand::SecureRandom; use crate::misc::UnpackedCell; lazy_static!{...
pub fn get_command(& self) -> &Command { &self.payload } pub fn try_from_stream<R: Read>(mut stream: R, version: u32) -> torserde::Result<Self> { todo!() } pub fn from_stream<R: Read>(mut stream: R, version: u32) -> torserde::Result<Self> { let circuit_id = if versio...
pub fn new(circuit_id: u32, payload: Command) -> Self { Self { circuit_id, payload, } }
function_block-full_function
[ { "content": "pub fn kdf_tor(shared_secret: &[u8]) -> Vec<u8> {\n\n let mut hasher = Sha1::new();\n\n\n\n let mut key_stuff = Vec::new();\n\n\n\n for i in 0..5 {\n\n\n\n hasher.write(shared_secret).unwrap();\n\n hasher.write(&[i]).unwrap();\n\n\n\n key_stuff.extend_from_slice(&hash...
Rust
src/afi/evpn.rs
wladwm/zettabgp
85d8e21742e948907cf3fcc64552f40c9e852524
use crate::afi::*; #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct EVPNESI { pub v: Vec<u8>, } impl EVPNESI { pub fn empty() -> EVPNESI { EVPNESI { v: Vec::new() } } pub fn new(src: &[u8]) -> EVPNESI { EVPNESI { v: src.to_vec() } } pub fn is_zero(&self...
use crate::afi::*; #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct EVPNESI { pub v: Vec<u8>, } impl EVPNESI { pub fn empty() -> EVPNESI { EVPNESI { v: Vec::new() } } pub fn new(src: &[u8]) -> EVPNESI { EVPNESI { v: src.to_vec() } } pub fn is_zero(&self...
r(format!("{}", self).as_str()) } }
write!(f, "{}:", self.esi_type)?; } write!(f, "{}:{:08x}::{}::", self.esi, self.ether_tag, self.mac)?; if let Some(ip) = self.ip { ip.fmt(f)?; }; write!(f, " {}", self.labels) } } #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct BgpEV...
random
[ { "content": "pub fn setn_u32(s: u32, a: &mut [u8]) {\n\n a[0] = (s >> 24) as u8;\n\n a[1] = ((s >> 16) & 0xff) as u8;\n\n a[2] = ((s >> 8) & 0xff) as u8;\n\n a[3] = (s & 0xff) as u8;\n\n}\n", "file_path": "src/util.rs", "rank": 0, "score": 208952.56896537877 }, { "content": "///...
Rust
kube-core/src/object.rs
jeffa5/kube-rs
3b46233e7cb019751ff7c6cc085f2914acf00b4c
use crate::{ discovery::ApiResource, metadata::{ListMeta, ObjectMeta, TypeMeta}, resource::Resource, }; use serde::{Deserialize, Serialize}; use std::borrow::Cow; #[derive(Deserialize, Debug)] pub struct ObjectList<T> where T: Clone, { pub metadata: ListMeta, #[serde(...
use crate::{ discovery::ApiResource, metadata::{ListMeta, ObjectMeta, TypeMeta}, resource::Resource, }; use serde::{Deserialize, Serialize}; use std::borrow::Cow; #[derive(Deserialize, Debug)] pub struct ObjectList<T> where T: Clone, { pub metadata: ListMeta, #[serde(...
let data = PodSpecSimple { containers: vec![ContainerSimple { image: "blog".into() }], }; let mypod = PodSimple::new("blog", &ar, data).within("dev"); assert_eq!(mypod.metadata.namespace.unwrap(), "dev"); assert_eq!(mypod.metadata.name.unwrap(), "blog"); assert_e...
ault, Debug)] pub struct NotUsed {} #[cfg(test)] mod test { use super::{ApiResource, NotUsed, Object}; #[test] fn simplified_k8s_object() { use k8s_openapi::api::core::v1::Pod; #[derive(Clone)] struct PodSpecSimple { containers: Vec<ContainerSimple>, } ...
random
[ { "content": "/// Watches a Kubernetes Resource for changes continuously\n\n///\n\n/// Compared to [`Api::watch`], this automatically tries to recover the stream upon errors.\n\n///\n\n/// Errors from the underlying watch are propagated, after which the stream will go into recovery mode on the next poll.\n\n///...
Rust
src/shaders/generated/desc.rs
Epsylon42/sdf-walker
cc0c00ea7f711b37da79ae6bf353595c726d59bf
use crate::shaders::{GeneratedScene, ShaderProvider}; use std::collections::HashSet; use super::codegen::Glsl; use super::parser; use super::typed::*; pub mod camera; pub mod loader; use camera::{CameraDesc, CameraDescError}; #[derive(Debug, thiserror::Error)] pub enum SceneDescError { #[error("Parse error")] ...
use crate::shaders::{GeneratedScene, ShaderProvider}; use std::collections::HashSet; use super::codegen::Glsl; use super::parser; use super::typed::*; pub mod camera; pub mod loader; use camera::{CameraDesc, CameraDescError}; #[derive(Debug, thiserror::Error)] pub enum SceneDescError { #[error("Parse error")] ...
fn construct_opaque( &self, color: Vec<String>, geometry: impl IGeometry, ) -> Result<Self::Output, StatementError> { Ok(box OpaqueShape { color, geometry }) } } pub struct TransparentVisitor; impl StatementVisitor for TransparentVisitor { type Output = Box<dyn ITransp...
fn construct_transform(&self, tf: impl ITransform, item: Self::Output) -> Self::Output { box Transform { tf, item, marker: OpaqueMarker, } }
function_block-full_function
[ { "content": "pub fn parse_marker(stmt: Statement) -> Result<(String, glm::Vec3), MarkerError> {\n\n if stmt.args.len() != 4 {\n\n return Err(MarkerError::WrongNumberOfArguments);\n\n }\n\n\n\n let name = stmt.args[0].clone();\n\n\n\n let x = stmt.args[1].parse()?;\n\n let y = stmt.args[2]...
Rust
src/realtps_import/src/client.rs
graydon/realtps
511b9a3dbeb40e3973af706560290bc6af6da0f1
use anyhow::{anyhow, Result}; use async_trait::async_trait; use ethers::prelude::*; use ethers::utils::hex::ToHex; use log::{debug, trace}; use near_jsonrpc_client::{auth::Unauthenticated, methods, JsonRpcClient}; use near_jsonrpc_primitives::types::chunks::ChunkReference; use near_primitives::{ types::{BlockId, Bl...
use anyhow::{anyhow, Result}; use async_trait::async_trait; use ethers::prelude::*; use ethers::utils::hex::ToHex; use log::{debug, trace}; use near_jsonrpc_client::{auth::Unauthenticated, methods, JsonRpcClient}; use near_jsonrpc_primitives::types::chunks::ChunkReference; use near_primitives::{ types::{BlockId, Bl...
} pub struct NearClient { client: JsonRpcClient<Unauthenticated>, } impl NearClient { pub fn new(url: &str) -> Result<Self> { let client = JsonRpcClient::connect(url); Ok(NearClient { client }) } } #[async_trait] impl Client for NearClient { async fn client_version(&self) -> Result<...
async fn get_block(&self, block_number: u64) -> Result<Option<Block>> { if let Some(block) = self.provider.get_block(block_number).await? { ethers_block_to_block(self.chain, block).map(Some) } else { Ok(None) } }
function_block-full_function
[ { "content": "pub trait Db: Send + Sync + 'static {\n\n fn store_block(&self, block: Block) -> Result<()>;\n\n fn load_block(&self, chain: Chain, block_number: u64) -> Result<Option<Block>>;\n\n\n\n fn store_highest_block_number(&self, chain: Chain, block_number: u64) -> Result<()>;\n\n fn load_high...
Rust
game/src/ungap/mod.rs
sven-wikberg/abstreet
dba9ba192b5f6392e2ad2b6b424f9b7738598ae4
mod bike_network; mod explore; mod layers; mod predict; mod quick_sketch; mod trip; use geom::CornerRadii; use map_gui::tools::{grey_out_map, open_browser, CityPicker}; use widgetry::{ EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Panel, ScreenDims, SimpleState, State, Text, VerticalAlignment, Widget, DEF...
mod bike_network; mod explore; mod layers; mod predict; mod quick_sketch; mod trip; use geom::CornerRadii; use map_gui::tools::{grey_out_map, open_browser, CityPicker}; use widgetry::{ EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Panel, ScreenDims, SimpleState, State, Text, VerticalAlignment, Widget, DEF...
fn draw(&self, g: &mut GfxCtx, app: &App) { grey_out_map(g, app); } }
fn on_click(&mut self, _: &mut EventCtx, _: &mut App, x: &str, _: &Panel) -> Transition { if x == "close" { return Transition::Pop; } else if x == "Read more" { open_browser("https://a-b-street.github.io/docs/software/ungap_the_map/index.html"); } Transition::Keep...
function_block-full_function
[ { "content": "/// A button to change maps, with default keybindings\n\npub fn change_map_btn(ctx: &EventCtx, app: &dyn AppLike) -> Widget {\n\n ctx.style()\n\n .btn_popup_icon_text(\n\n \"system/assets/tools/map.svg\",\n\n nice_map_name(app.map().get_name()),\n\n )\n\n ...
Rust
src/lib.rs
dssgabriel/retro
dfe415cf5d8857f3be994de28cd3bdaf7c403eda
use std::fs; pub struct Station { pub id: usize, pub line: String, pub state: bool, pub name: String, } impl Station { pub fn new(description: &str) -> Self { let parsed: Vec<&str> = description ...
use std::fs; pub struct Station { pub id: usize, pub line: String, pub state: bool, pub name: String, } impl Station { pub fn new(description: &str) -> Self { let parsed: Vec<&str> = description ...
Trip { first: parsed[0] .parse::<usize>() .expect("Could not cast as u32"), second: parsed[1] .parse::<usize>() .expect("Could not cast as u32"), time: parsed[2] .parse::<usize>() ...
let parsed: Vec<&str> = config .clone() .trim_start_matches("E ") .splitn(3, " ") .collect();
assignment_statement
[ { "content": "fn main() {\n\n let filename = String::from(\"metro.txt\");\n\n let metro = Metro::new(&filename);\n\n\n\n print!(\"\\n\\x1b[1mDeparture:\\x1b[0m\");\n\n let departures = Metro::get_station(&metro);\n\n print!(\"\\n\\x1b[1mArrival:\\x1b[0m\");\n\n let arrivals = Metro::get_statio...
Rust
serde-generate/src/config.rs
texas16/serde-reflection
6820d5b97d8cbe9fa4fb5acaa95f29c48f0a0bf2
use std::collections::{BTreeMap, BTreeSet}; #[derive(Clone, Debug)] pub struct CodeGeneratorConfig { pub(crate) module_name: String, pub(crate) serialization: bool, pub(crate) encodings: BTreeSet<Encoding>, pub(crate) external_definitions: ExternalDefinitions, pub(crate) comments: DocComments, ...
use std::collections::{BTreeMap, BTreeSet}; #[derive(Clone, Debug)] pub struct CodeGeneratorConfig { pub(crate) module_name: String, pub(crate) serialization: bool, pub(crate) encodings: BTreeSet<Encoding>, pub(crate) external_definitions: ExternalDefinitions, pub(crate) comments: DocComments, ...
pub fn module_name(&self) -> &str { &self.module_name } pub fn with_serialization(mut self, serialization: bool) -> Self { self.serialization = serialization; self } pub fn with_encodings<I>(mut self, encodings: I) -> Self where I: IntoIterator<Item ...
pub fn new(module_name: String) -> Self { Self { module_name, serialization: true, encodings: BTreeSet::new(), external_definitions: BTreeMap::new(), comments: BTreeMap::new(), custom_code: BTreeMap::new(), c_style_enums: false,...
function_block-full_function
[ { "content": "fn get_codegen_config<'a, I>(name: String, runtimes: I, c_style_enums: bool) -> CodeGeneratorConfig\n\nwhere\n\n I: IntoIterator<Item = &'a Runtime>,\n\n{\n\n let mut encodings = Vec::new();\n\n for runtime in runtimes {\n\n match runtime {\n\n Runtime::Bincode => {\n\n ...
Rust
server/svix-server/tests/e2e_message.rs
fcjr/svix-webhooks
c541c88fb63c1e3f0d57538cd6c959feb78408ab
use reqwest::StatusCode; use svix_server::v1::{endpoints::message::MessageOut, utils::ListResponse}; mod utils; use utils::{ common_calls::{create_test_app, create_test_endpoint, message_in}, start_svix_server, }; #[tokio::test] async fn test_message_create_read_list() { let (client, _jh) = start_svix...
use reqwest::StatusCode; use svix_server::v1::{endpoints::message::MessageOut, utils::ListResponse}; mod utils; use utils::{ common_calls::{create_test_app, create_test_endpoint, message_in}, start_svix_server, }; #[tokio::test] async fn test_message_create_read_list() { let (client, _jh) = start_svix...
.get( &format!("api/v1/app/{}/msg/?with_content=false", &app_id), StatusCode::OK, ) .await .unwrap(); assert_eq!(list.data.len(), 2); assert!(list.data.contains(&msg_1_wo_payload)); assert!(list.data.contains(&msg_2_wo_payload)); }
.unwrap(), *m ); } let list: ListResponse<MessageOut> = client .get(&format!("api/v1/app/{}/msg", &app_id), StatusCode::OK) .await .unwrap(); assert_eq!(list.data.len(), 2); assert!(list.data.contains(&msg_1_w_payload)); assert!(list.data.conta...
random
[ { "content": "pub fn start_svix_server() -> (TestClient, tokio::task::JoinHandle<()>) {\n\n start_svix_server_with_cfg(&get_default_test_config())\n\n}\n\n\n", "file_path": "server/svix-server/tests/utils/mod.rs", "rank": 0, "score": 227873.67982147183 }, { "content": "pub fn start_svix_s...
Rust
src/metrics.rs
FindoraNetwork/findora-exporter
97d9c82fdbd33c0a0c8adb8b5bd4945759b7b9b5
use anyhow::{bail, Context, Result}; use prometheus::{ core::{Atomic, GenericGauge}, proto::MetricFamily, Registry, }; use crate::{config::TaskName, utils::calculate_hash}; use std::{collections::HashMap, sync::Arc}; pub(crate) struct Metrics<T: Atomic> { metrics: HashMap<u64, Arc<Metric<T>>>, } imp...
use anyhow::{bail, Context, Result}; use prometheus::{ core::{Atomic, GenericGauge}, proto::MetricFamily, Registry, }; use crate::{config::TaskName, utils::calculate_hash}; use std::{collections::HashMap, sync::Arc}; pub(crate) struct Metrics<T: Atomic> { metrics: HashMap<u64, Arc<Metric<T>>>, } imp...
pub(crate) fn gather(&self) -> Vec<MetricFamily> { self.metrics .values() .flat_map(|metric| metric.gather()) .collect() } pub(crate) fn get_metric(&self, hash: u64) -> Result<Arc<Metric<T>>> { match self.metrics.get(&hash) { Some(...
pub(crate) fn new(cfg: &crate::config::Crawler) -> Result<Self> { let mut metrics = HashMap::with_capacity(cfg.targets.len()); for target in &cfg.targets { metrics.insert( calculate_hash(target), Arc::new( Metric::new(target) ...
function_block-full_function
[ { "content": "#[derive(Clone)]\n\nstruct Task<T: Atomic> {\n\n name: String,\n\n addr: String,\n\n metric: Arc<Metric<T>>,\n\n option: Option<ExtraOpts>,\n\n f: fn(&str, &Option<ExtraOpts>) -> Result<<T as Atomic>::T>,\n\n}\n\n\n\nimpl<T> Task<T>\n\nwhere\n\n T: Atomic + 'static,\n\n{\n\n f...
Rust
src/plu/wakeint_ctrl.rs
geky/lpc55s6x-pac
766a1eec50a670a5872aa1a8c7637a9d5b9d6478
#[doc = "Reader of register WAKEINT_CTRL"] pub type R = crate::R<u32, super::WAKEINT_CTRL>; #[doc = "Writer for register WAKEINT_CTRL"] pub type W = crate::W<u32, super::WAKEINT_CTRL>; #[doc = "Register WAKEINT_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::WAKEINT_CTRL { type Type = u32; #[i...
#[doc = "Reader of register WAKEINT_CTRL"] pub type R = crate::R<u32, super::WAKEINT_CTRL>; #[doc = "Writer for register WAKEINT_CTRL"] pub type W = crate::W<u32, super::WAKEINT_CTRL>; #[doc = "Register WAKEINT_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::WAKEINT_CTRL { type Type = u32; #[i...
} #[doc = "Reader of field `FILTER_CLKSEL`"] pub type FILTER_CLKSEL_R = crate::R<u8, FILTER_CLKSEL_A>; impl FILTER_CLKSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, FILTER_CLKSEL_A> { use crate::Variant::*; match self.bits { ...
fn from(variant: FILTER_CLKSEL_A) -> Self { match variant { FILTER_CLKSEL_A::FRO1MHZ => 0, FILTER_CLKSEL_A::FRO12MHZ => 1, FILTER_CLKSEL_A::OTHER_CLOCK => 2, } }
function_block-function_prefix_line
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/security/scrutiny/lib/plugins/src/verify/collector/component_tree.rs
EnderNightLord-ChromeBook/zircon-rpi
b09b1eb3aa7a127c65568229fe10edd251869283
use { crate::core::collection::{Components, ManifestData, Manifests}, crate::verify::collection::V2ComponentTree, anyhow::{anyhow, Result}, cm_fidl_analyzer::component_tree::ComponentTreeBuilder, cm_rust::{ComponentDecl, FidlIntoNative}, fidl::encoding::decode_persistent, fidl_fuchsia_sys2...
use { crate::core::collection::{Components, ManifestData, Manifests}, crate::verify::collection::V2ComponentTree, anyhow::{anyhow, Result}, cm_fidl_analyzer::component_tree::ComponentTreeBuilder, cm_rust::{ComponentDecl, FidlIntoNative}, fidl::encoding::decode_persistent, fidl_fuchsia_sys2...
fn v1_and_v2_component_model() -> Result<Arc<DataModel>> { let model = data_model(); let root_id = 0; let root_component = make_v2_component(root_id, "fuchsia-boot:///#meta/root.cm".to_string()); let root_manifest = make_v2_manifest(root_id, new_component_decl(vec![]))?...
ult<Arc<DataModel>> { let model = data_model(); let root_id = 0; let root_component = make_v2_component(root_id, "fuchsia-boot:///#meta/root.cm".to_string()); let root_manifest = make_v2_manifest(root_id, new_component_decl(vec![]))?; model.set(Components::new(vec![ro...
function_block-function_prefixed
[]
Rust
src/cmd/count.rs
markschl/seqtool
5bf7e3d136850409fd76f8a942bea882c8482b3d
use std::fmt::Debug; use std::fmt::Write; use std::mem; use csv; use cfg; use error::CliResult; use fxhash::FxHashMap; use opt; use var::varstring; static USAGE: &'static str = concat!( " This command counts the number of sequences and prints the number to STDOUT. Advanced grouping of sequences is possible by su...
use std::fmt::Debug; use std::fmt::Write; use std::mem; use csv; use cfg; use error::CliResult; use fxhash::FxHashMap; use opt; use var::varstring; static USAGE: &'static str = concat!( " This command counts the number of sequences and prints the number to STDOUT. Advanced grouping of sequences is possible by su...
fn count_simple(cfg: &cfg::Config) -> CliResult<()> { cfg.io_writer(|writer, _| { let mut n = 0; cfg.read_sequential(|_| { n += 1; Ok(true) })?; writeln!(writer, "{}", n)?; Ok(()) })?; Ok(()) } fn count_categorized(cfg: &cfg::Config, keys...
let keys = args.get_vec("--key"); let print_intervals = !args.get_bool("--no-int"); if keys.is_empty() { count_simple(&cfg) } else { count_categorized(&cfg, &keys, print_intervals) } }
function_block-function_prefix_line
[ { "content": "pub fn parse_format_str(string: &str) -> CliResult<(String, Compression)> {\n\n let string = string.to_ascii_lowercase();\n\n let parts: Vec<_> = string.split('.').collect();\n\n let (ext, compr) = if parts.len() == 1 {\n\n (parts[0].to_string(), Compression::None)\n\n } else {\...
Rust
src/values/src/extractors/lists.rs
mrrabbitte/buttercup
19cddc486d539ab899cff587befc1cb8f5c6bc52
use std::sync::Arc; use serde_json::Value; use crate::extractors::{ListExtractionError, ListExtractorInput, ValueExtractorInput, ValueExtractorService}; use crate::lists::ValueHoldersList; use crate::ValueHolder; pub struct ListExtractor; impl ListExtractor { pub fn extract(input: &ListExtractorInput) -> Resul...
use std::sync::Arc; use serde_json::Value; use crate::extractors::{ListExtractionError, ListExtractorInput, ValueExtractorInput, ValueExtractorService}; use crate::lists::ValueHoldersList; use crate::ValueHolder; pub struct ListExtractor; impl ListExtractor { pub fn extract(input: &ListExtractorInput) -> Resul...
#[test] fn test_mismatched_list_type_error() { let result = extract(STRING_LIST, &ValueType::Integer); assert!(result.is_err(), "{:?}", result); assert_eq!(ListExtractionError::ListElementExtractionError( ValueExtractionError::InvalidValueTypeError(ValueExtrac...
ERROR_ELEMENT_TYPE_LIST, ListExtractionError::ListElementExtractionError( ValueExtractionError::InvalidValueTypeError(ValueExtractionPolicy::Strict), 1)); }
function_block-function_prefix_line
[ { "content": "pub fn add_test_trees(bt_service: &BehaviorTreeService) {\n\n bt_service.insert(build_one_off_tree());\n\n bt_service.insert(build_until_stopped_tree());\n\n bt_service.insert(build_to_first_fail_tree());\n\n bt_service.insert(build_tree_with_subtree(bt_service.get_by_id(&1).unwrap()))...
Rust
askar-bbs/src/signature.rs
simnic/aries-askar
eafdc85e76f073426ea2ba57991cdf5d881b37a5
use askar_crypto::{ alg::bls::{BlsKeyPair, G2}, buffer::Writer, }; use bls12_381::{pairing, G1Affine, G1Projective, G2Affine, G2Projective, Scalar}; use group::Curve; use subtle::ConstantTimeEq; use crate::{ commitment::{Blinding, Commitment}, generators::Generators, hash::HashScalar, io::{Comp...
use askar_crypto::{ alg::bls::{BlsKeyPair, G2}, buffer::Writer, }; use bls12_381::{pairing, G1Affine, G1Projective, G2Affine, G2Projective, Scalar}; use group::Curve; use subtle::ConstantTimeEq; use crate::{ commitment::{Blinding, Commitment}, generators::Generators, hash::HashScalar, io::{Comp...
let c = self.message_count + count; if c > self.generators.message_count() { return Err(err_msg!(Usage, "Message index exceeds generator count")); } self.message_count = c; Ok(()) } pub fn len(&self) -> usize { self.message_count } pub fn t...
generators, &self) } pub fn unblind(self, blinding: Blinding) -> Self { let Signature { a, e, s } = self; Self { a, e, s: s + blinding.0, } } pub fn verify<G>( &self, generators: &G, messages: impl IntoIterat...
random
[ { "content": "/// Obtain an instance of the default random number generator\n\npub fn default_rng() -> impl CryptoRng + RngCore + Debug + Clone {\n\n #[cfg(feature = \"std_rng\")]\n\n {\n\n rand::rngs::ThreadRng::default()\n\n }\n\n #[cfg(not(feature = \"std_rng\"))]\n\n {\n\n rand:...
Rust
runfs/src/directory_entry.rs
wei-huan/MyOS
0592dd73fd9768a9a69975f7d18c758999195774
pub(crate) const DIRENT_SZ: u32 = 32; pub const ATTR_READ_ONLY: u8 = 0x01; pub const ATTR_HIDDEN: u8 = 0x02; pub const ATTR_SYSTEM: u8 = 0x04; pub const ATTR_VOLUME_ID: u8 = 0x08; pub const ATTR_DIRECTORY: u8 = 0x10; pub const ATTR_ARCHIVE: u8 = 0x20; pub const ATTR_LONG_NAME: u8 = ATTR_READ_ONLY | ATTR_HIDDEN | ATTR...
pub(crate) const DIRENT_SZ: u32 = 32; pub const ATTR_READ_ONLY: u8 = 0x01; pub const ATTR_HIDDEN: u8 = 0x02; pub const ATTR_SYSTEM: u8 = 0x04; pub const ATTR_VOLUME_ID: u8 = 0x08; pub const ATTR_DIRECTORY: u8 = 0x10; pub const ATTR_ARCHIVE: u8 = 0x20; pub const ATTR_LONG_NAME: u8 = ATTR_READ_ONLY | ATTR_HIDDEN | ATTR...
order: u8, name1: [u8; 10], attribute: u8, type_: u8, check_sum: u8, name2: [u8; 12], zero: [u8; 2], name3: [u8; 4], } impl LongDirectoryEntry { pub fn attribute(&self) -> u8 { self.attribute } pub fn is_empty(&self) -> bool { self.o...
&self) -> bool { self.name[0] == 0xE5 } pub fn is_empty(&self) -> bool { self.name[0] == 0x00 } pub fn is_file(&self) -> bool { (self.attribute != ATTR_DIRECTORY) && (self.attribute != ATTR_VOLUME_ID) } pub fn is_long(&self) -> bool { self.attribute == ATTR_LONG_N...
random
[ { "content": "// TODO:文件所有权\n\npub fn sys_open_at(dirfd: isize, path: *const u8, flags: u32, _mode: u32) -> isize {\n\n let task = current_task().unwrap();\n\n let token = current_user_token();\n\n // 这里传入的地址为用户的虚地址,因此要使用用户的虚地址进行映射\n\n let path = translated_str(token, path);\n\n let mut inner = t...
Rust
odc_core/src/window.rs
F3kilo/odc
8fd9a1b72d0e923bcaed98d2dc0b6b262863e6a3
use crate::{mdl, Swapchain}; use raw_window_handle::HasRawWindowHandle; use wgpu::TextureSampleType; pub struct WindowInfo<'a, Handle: HasRawWindowHandle> { pub name: &'a str, pub handle: &'a Handle, pub size: mdl::Size2d, } pub struct WindowSource { pub texture_view: wgpu::TextureView, pub format...
use crate::{mdl, Swapchain}; use raw_window_handle::HasRawWindowHandle; use wgpu::TextureSampleType; pub struct WindowInfo<'a, Handle: HasRawWindowHandle> { pub name: &'a str, pub handle: &'a Handle, pub size: mdl::Size2d, } pub struct WindowSource { pub texture_view: wgpu::TextureView, pub format...
le: Default::default(), multiview: None, }; device.create_render_pipeline(&descriptor) } fn create_bind_group( device: &wgpu::Device, layout: &wgpu::BindGroupLayout, view: &wgpu::TextureView, sampler: &wgpu::Sampler, ) -> wgpu::BindGroup { ...
texture_format: wgpu::TextureFormat, ) -> wgpu::BindGroupLayout { let sample_type = texture_format.describe().sample_type; let ty = wgpu::BindingType::Texture { sample_type, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false, }; ...
random
[ { "content": "pub fn run_example<E: Example + 'static>(mut ex: E) -> ! {\n\n env_logger::init();\n\n let event_loop = EventLoop::new();\n\n\n\n let mut renderer = OdcCore::new(E::render_model());\n\n\n\n let windows = E::windows();\n\n let window_handles: HashMap<_, _> = windows\n\n .iter(...
Rust
fmm-c/src/expression.rs
zhhailon/fmm
8aeebaa14a57470fe365a9e271b822872a4c6eb4
use crate::{name, type_}; use fmm::{ir::*, types}; use fnv::{FnvHashMap, FnvHashSet}; pub fn compile( expression: &Expression, global_variables: &FnvHashSet<String>, type_ids: &FnvHashMap<fmm::types::Type, String>, ) -> String { let compile = |expression| compile(expression, global_variables, type_ids)...
use crate::{name, type_}; use fmm::{ir::*, types}; use fnv::{FnvHashMap, FnvHashSet}; pub fn compile( expression: &Expression, global_variables: &FnvHashSet<String>, type_ids: &FnvHashMap<fmm::types::Type, String>, ) -> String { let compile = |expression| compile(expression, global_variables, type_ids)...
Primitive::Integer8(number) => format!("{}", number), Primitive::Integer32(number) => format!("{}", number), Primitive::Integer64(number) => format!("{}", number), Primitive::PointerInteger(number) => format!("{}", number), } } fn compile_undefined_primitive(primitive: types::Primitive) -> ...
+ variable.name() } } } fn compile_undefined( undefined: &Undefined, type_ids: &FnvHashMap<fmm::types::Type, String>, ) -> String { match undefined.type_() { types::Type::Function(_) => "NULL".into(), types::Type::Primitive(primitive) => compile_undefined_primitive(*primi...
random
[ { "content": "pub fn compile_record_id(record: &types::Record, type_ids: &FnvHashMap<Type, String>) -> String {\n\n \"struct \".to_owned() + &type_ids[&record.clone().into()]\n\n}\n\n\n", "file_path": "fmm-c/src/type_.rs", "rank": 0, "score": 319507.9176179393 }, { "content": "pub fn comp...
Rust
polar-core/src/polar.rs
Guara92/oso
6144d7b6576c43e5e67ba395bf6d5c9011169c81
use std::sync::{Arc, RwLock}; use super::data_filtering::{build_filter_plan, FilterPlan, PartialResults, Types}; use super::diagnostic::{set_context_for_diagnostics, Diagnostic}; use super::error::PolarResult; use super::kb::*; use super::messages::*; use super::parser; use super::query::Query; use super::resource_blo...
use std::sync::{Arc, RwLock}; use super::data_filtering::{build_filter_plan, FilterPlan, PartialResults, Types}; use super::diagnostic::{set_context_for_diagnostics, Diagnostic}; use super::error::PolarResult; use super::kb::*; use super::messages::*; use super::parser; use super::query::Query; use super::resource_blo...
).new_id() } pub fn register_constant(&self, name: Symbol, value: Term) -> PolarResult<()> { self.kb.write().unwrap().register_constant(name, value) } pub fn register_mro(&self, name: Symbol, mro: Vec<u64>) -> PolarResult<()> { self.kb.write().unwrap().add...
kb.create_resource_specific_rule_types(); diagnostics.append(&mut kb.validate_rules()); if !self.ignore_no_allow_warning { if let Some(w) = check_no_allow_rule(&kb) { diagnostics.push(w) } } if let Some(w) = check_...
random
[ { "content": "pub fn parse_lines(src_id: u64, src: &str) -> PolarResult<Vec<Line>> {\n\n polar::LinesParser::new()\n\n .parse(src_id, Lexer::new(src))\n\n .map_err(|e| to_parse_error(e).into())\n\n}\n\n\n", "file_path": "polar-core/src/parser.rs", "rank": 0, "score": 538080.74089215...
Rust
cargo-pgx/src/command/get.rs
tcdi/pgx
1a89778046547c52c714fe6885069eab5638f965
/* Portions Copyright 2019-2021 ZomboDB, LLC. Portions Copyright 2021-2022 Technology Concepts & Design, Inc. <support@tcdi.com> All rights reserved. Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ use crate::CommandExecute; use eyre::{eyre, WrapErr}; use std::{ f...
/* Portions Copyright 2019-2021 ZomboDB, LLC. Portions Copyright 2021-2022 Technology Concepts & Design, Inc. <support@tcdi.com> All rights reserved. Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ use crate::CommandExecute; use eyre::{eyre, WrapErr}; use std::{ f...
} Err(e) => Err(e).wrap_err("problem running `git` to determine the current revision hash"), } }
return Err(eyre!( "problem running `git` to determine the current revision hash: {}", stderr )); } Ok(Some( String::from_utf8(output.stdout) .expect("`git rev-parse head` did not return valid ...
function_block-random_span
[ { "content": "fn create_control_file(path: &PathBuf, name: &str) -> Result<(), std::io::Error> {\n\n let mut filename = path.clone();\n\n\n\n filename.push(format!(\"{}.control\", name));\n\n let mut file = std::fs::File::create(filename)?;\n\n\n\n file.write_all(&format!(include_str!(\"../templates...
Rust
src/pools/pool_internal/instrumentation/mod.rs
chridou/reool
e8661777f84b9be931fede4624fbd069e0220884
use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use std::time::Duration; use crate::instrumentation::{Instrumentation, InstrumentationFlavour, PoolId}; use crate::PoolState; #[derive(Clone)] pub(crate) struct PoolInstrumentation { pub id: PoolId, pub flavour: InstrumentationFlavour, in_...
use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use std::time::Duration; use crate::instrumentation::{Instrumentation, InstrumentationFlavour, PoolId}; use crate::PoolState; #[derive(Clone)] pub(crate) struct PoolInstrumentation { pub id: PoolId, pub flavour: InstrumentationFlavour, in_...
hed(self.id) } pub fn connection_factory_failed(&self) { self.flavour.connection_factory_failed(self.id) } pub fn internal_message_received(&self, latency: Duration) { self.flavour.internal_message_received(latency, self.id) } pub fn checkout_message_received(&self, latency: Du...
: Arc::new(AtomicUsize::new(0)), pools: Arc::new(AtomicUsize::new(0)), reservations: Arc::new(AtomicUsize::new(0)), connections: Arc::new(AtomicUsize::new(0)), idle: Arc::new(AtomicUsize::new(0)), } } pub fn state(&self) -> PoolState { PoolState {...
random
[ { "content": "struct MyConnectionFactory(Arc<String>, AtomicUsize);\n\n\n\nimpl ConnectionFactory for MyConnectionFactory {\n\n type Connection = MyConn;\n\n\n\n fn create_connection(&self) -> BoxFuture<Result<Self::Connection, Error>> {\n\n let count = self.1.fetch_add(1, Ordering::SeqCst);\n\n ...
Rust
src/lib.rs
lukaslueg/sqlite3_hyperminhash
87dc48caf4e50860412bb2d1ecdde0f217f7f1d9
mod bindings { #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } use bindings::*; use std::{ffi, fmt, io, mem, os::raw, slice}; use hyperminhash::Sketch; #[cfg(feature = "serialize"...
mod bindings { #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } use bindings::*; use std::{ffi, fmt, io, mem, os::raw, slice}; use hyperminhash::Sketch; #[cfg(feature = "serialize"...
} else { Ok(RawValue::Blob(&[])) } } _ => Err(HMHError::UnknownValueType), } } #[cfg(feature = "serialize")] fn as_blob(self) -> Result<&'a [u8], HMHError<'a>> { match self { RawValue::Blob(b) => Ok(b),...
Ok(RawValue::Blob(std::slice::from_raw_parts( blob as *const u8, len as usize, )))
call_expression
[ { "content": "#[test]\n\nfn data_types() -> rusqlite::Result<()> {\n\n let con = init_db()?;\n\n con.execute(\n\n \"CREATE TABLE bar (i INT, f FLOAT, s TEXT, b BLOB)\",\n\n rusqlite::params![],\n\n )?;\n\n con.execute(\n\n \"INSERT INTO bar (i, f, s, b) VALUES (?1, ?2, ?3, ?4)\"...
Rust
src/tds/codec/column_data.rs
sec-researcher/tiberius
8a9acb11e0ddce3b1fce37800ba890c851075e0f
mod binary; mod bit; #[cfg(feature = "tds73")] mod date; #[cfg(feature = "tds73")] mod datetime2; mod datetimen; #[cfg(feature = "tds73")] mod datetimeoffsetn; mod fixed_len; mod float; mod guid; mod image; mod int; mod money; mod plp; mod string; mod text; #[cfg(feature = "tds73")] mod time; mod var_len; mod xml; use...
mod binary; mod bit; #[cfg(feature = "tds73")] mod date; #[cfg(feature = "tds73")] mod datetime2; mod datetimen; #[cfg(feature = "tds73")] mod datetimeoffsetn; mod fixed_len; mod float; mod guid; mod image; mod int; mod money; mod plp; mod string; mod text; #[cfg(feature = "tds73")] mod time; mod var_len; mod xml; use...
}
let mut length = 0u32; let len_pos = dst.len(); dst.put_u32_le(length); for chr in s.encode_utf16() { length += 1; dst.put_u16_le(chr); } dst.put_u32_le(0); let ds...
function_block-function_prefix_line
[ { "content": "#[derive(Debug)]\n\n#[repr(u16)]\n\n#[allow(dead_code)]\n\nenum AllHeaderTy {\n\n QueryDescriptor = 1,\n\n TransactionDescriptor = 2,\n\n TraceActivity = 3,\n\n}\n\n\n\npub struct PacketCodec;\n\n\n\npub(crate) async fn collect_from<S, T>(stream: &mut S) -> crate::Result<T>\n\nwhere\n\n ...
Rust
atat/src/derive.rs
burrbull/atat
6732e8d099e2536302e35556c68a472558dab2bd
use heapless::{String, Vec}; use serde_at::CharVec; pub trait AtatLen { const LEN: usize; } #[cfg(feature = "bytes")] impl<const N: usize> AtatLen for heapless_bytes::Bytes<N> { const LEN: usize = N; } macro_rules! impl_length { ($type:ty, $len:expr) => { #[allow(clippy::use_self)] impl A...
use heapless::{String, Vec}; use serde_at::CharVec; pub trait AtatLen { const LEN: usize; } #[cfg(feature = "bytes")] impl<const N: usize> AtatLen for heapless_bytes::Bytes<N> { const LEN: usize = N; } macro_rules! impl_length { ($type:ty, $len:expr) => { #[allow(clippy::use_self)] impl A...
b: String::from("whaat"), c: 88, d: SimpleEnum::B }, "CMD", SerializeOptions::default() ) .unwrap(), String::<50>::from("4,77,\"whaat\",88,1") ); assert_eq!(Ok(Mi...
try_from(3), Ok(SimpleEnum::D)); assert_eq!(SimpleEnumU32::try_from(1), Ok(SimpleEnumU32::B)); assert_eq!( to_string::<_, 1>(&MixedEnum::UnitVariant, "CMD", SerializeOptions::default()).unwrap(), String::<1>::from("0") ); assert_eq!( to_string::<_, 10>...
function_block-random_span
[]
Rust
src/data/item.rs
avielmenter/seriatim-server
c0256288623422820246b2fd490ebfdf11a5edb9
use diesel; use diesel::prelude::*; use data; use data::db::Connection; use data::document::DocumentID; use data::schema::items; use data::schema::items::dsl::*; use data::schema::styles::dsl::*; use data::schema::{StyleProperty, StyleUnit}; use data::style::{style_vec_to_map, Style}; use serde::ser::{Serialize, Seri...
use diesel; use diesel::prelude::*; use data; use data::db::Connection; use data::document::DocumentID; use data::schema::items; use data::schema::items::dsl::*; use data::schema::styles::dsl::*; use data::schema::{StyleProperty, StyleUnit}; use data::style::{style_vec_to_map, Style}; use serde::ser::{Serialize, Seri...
on.pg_connection) } pub fn create_style( &self, p_property: StyleProperty, p_value_string: Option<String>, p_value_number: Option<i32>, p_unit: Option<StyleUnit>, ) -> Style<'a> { Style::create( self.connection, &self.get_id(), ...
t_id(); diesel::delete(items) .filter(parent_id.eq(&*p_item_uuid)) .execute(&self.connecti
function_block-random_span
[ { "content": "pub fn style_vec_to_map<'a>(style_vec: Vec<Style<'a>>) -> HashMap<StyleProperty, Style<'a>> {\n\n style_vec\n\n .into_iter()\n\n .map(|se| (se.data.property, se))\n\n .collect()\n\n}\n", "file_path": "src/data/style.rs", "rank": 0, "score": 150301.79385048046 ...
Rust
buttplug/src/device/protocol/satisfyer.rs
ashkitten/buttplug
6f7fa1a6584fbd7196b563f8efb4226b2c18e08f
use super::{ButtplugDeviceResultFuture, ButtplugProtocol, ButtplugProtocolCommandHandler}; use crate::{ core::messages::{self, ButtplugDeviceCommandMessageUnion, DeviceMessageAttributesMap}, device::{ protocol::{generic_command_manager::GenericCommandManager, ButtplugProtocolProperties}, DeviceImpl, Dev...
use super::{ButtplugDeviceResultFuture, ButtplugProtocol, ButtplugProtocolCommandHandler}; use crate::{ core::messages::{self, ButtplugDeviceCommandMessageUnion, DeviceMessageAttributesMap}, device::{ protocol::{generic_command_manager::GenericCommandManager, ButtplugProtocolProperties}, DeviceImpl, Dev...
let command_receiver = test_device .get_endpoint_receiver(&Endpoint::Tx) .expect("Test, assuming infallible"); device .parse_message(VibrateCmd::new(0, vec![VibrateSubcommand::new(0, 0.5)]).into()) .await .expect("Test, assuming infallible"); /* check_tes...
let (device, test_device) = new_bluetoothle_test_device("SF Curvy 2+") .await .expect("Test, assuming infallible");
assignment_statement
[ { "content": "pub fn vec_to_protocol_json<T>(msg: Vec<T>) -> String\n\nwhere\n\n T: ButtplugMessage + Serialize + Deserialize<'static>,\n\n{\n\n serde_json::to_string(&msg).expect(\"Infallible serialization\")\n\n}\n\n\n", "file_path": "buttplug/src/core/messages/serializer/json_serializer.rs", "rank"...
Rust
tests/core/matrix_slice.rs
aepsil0n/nalgebra
bba1993e58f9d03a16b6161dc1aab2381485b9bf
use na::{U2, U3, U4}; use na::{DMatrix, RowVector4, Vector3, Matrix2, Matrix3, Matrix3x4, Matrix4x2, Matrix2x4, Matrix6x2, Matrix2x6}; #[test] fn nested_fixed_slices() { let a = Matrix3x4::new(11.0, 12.0, 13.0, 14.0, 21.0, 22.0, 23.0, 24.0, ...
use na::{U2, U3, U4}; use na::{DMatrix, RowVector4, Vector3, Matrix2, Matrix3, Matrix3x4, Matrix4x2, Matrix2x4, Matrix6x2, Matrix2x6}; #[test] fn nested_fixed_slices() { let a = Matrix3x4::new(11.0, 12.0, 13.0, 14.0, 21.0, 22.0, 23.0, 24.0, ...
31.0, 32.0, 0.0, 0.0, 51.0, 52.0, 0.0, 0.0); assert_eq!(expected_a, a); } #[test] fn nested_col_slices() { let a = Matrix2x6::new(11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ...
32.0, 41.0, 42.0, 51.0, 52.0); let expected_owned_s2 = Matrix2::new(31.0, 32.0, 51.0, 52.0); assert_eq!(expected_owned_s1, s1.clone_owned()); assert_eq!(expected_owned_s2, s2.clo...
random
[ { "content": "fn unzero_diagonal(a: &mut Matrix4<f64>) {\n\n for i in 0 .. 4 {\n\n if a[(i, i)] < 1.0e-7 {\n\n a[(i, i)] = 1.0;\n\n }\n\n }\n\n}\n\n\n\nquickcheck! {\n\n fn solve_lower_triangular(a: Matrix4<f64>, b: Matrix4x5<f64>) -> bool {\n\n let mut a = a;\n\n ...
Rust
src/usbfsh/hcrhstatus.rs
geky/lpc55s6x-pac
766a1eec50a670a5872aa1a8c7637a9d5b9d6478
#[doc = "Reader of register HCRHSTATUS"] pub type R = crate::R<u32, super::HCRHSTATUS>; #[doc = "Writer for register HCRHSTATUS"] pub type W = crate::W<u32, super::HCRHSTATUS>; #[doc = "Register HCRHSTATUS `reset()`'s with value 0"] impl crate::ResetValue for super::HCRHSTATUS { type Type = u32; #[inline(always...
#[doc = "Reader of register HCRHSTATUS"] pub type R = crate::R<u32, super::HCRHSTATUS>; #[doc = "Writer for register HCRHSTATUS"] pub type W = crate::W<u32, super::HCRHSTATUS>; #[doc = "Register HCRHSTATUS `reset()`'s with value 0"] impl crate::ResetValue for super::HCRHSTATUS { type Type = u32; #[inline(always...
(self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `OCIC`"] pub type OCIC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OCIC`"] pub struct OCIC_W<'a> { w: &'a mut W, } impl<'a> OCIC_W<'a> { #[doc = r"Sets the field bit"] #[inline(alw...
pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `OCI`"] pub type OCI_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OCI`"] pub struct OCI_W<'a> { w: &'a mut W, } impl<'a> OCI_W<'a> { ...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
core/src/types.rs
davebryson/rapido
80b64ddb06a48f35cfe54c584dd62efeb643c6e0
use std::cell::RefCell; use abci::{Event, Pair}; use anyhow::{anyhow, Result}; use borsh::{BorshDeserialize, BorshSerialize}; use exonum_crypto::{Hash, PublicKey, SecretKey, Signature}; use protobuf::RepeatedField; use crate::store::StoreView; pub type AccountId = Vec<u8>; pub struct Context { pub sender:...
use std::cell::RefCell; use abci::{Event, Pair}; use anyhow::{anyhow, Result}; use borsh::{BorshDeserialize, BorshSerialize}; use exonum_crypto::{Hash, PublicKey, SecretKey, Signature}; use protobuf::RepeatedField; use crate::store::StoreView; pub type AccountId = Vec<u8>; pub struct Context { pub sender:...
p_err(|_| anyhow!("problem decoding the signed tx")) } pub fn sign(&mut self, private_key: &SecretKey) { self.signature = exonum_crypto::sign(&self.hash()[..], private_key) .as_ref() .into(); } fn hash(&self) -> Hash { let contents: Vec<u8> = vec![...
e.set_field_type(full_event_type.into()); e.set_attributes(rf); self.events.borrow_mut().push(e); } pub fn get_events(&self) -> RepeatedField<Event> { RepeatedField::from_vec(self.events.borrow().clone()) } } pub trait Authenticato...
random
[ { "content": "/// Helper to generate consistent keypairs for a given user-friendly value.\n\n/// Not to be used for other than testing.\n\n/// Example: `let (pk, sk) = testing_keypair(\"bob\")`\n\npub fn testing_keypair(val: &str) -> (PublicKey, SecretKey) {\n\n let seed = Seed::new(hash(val.as_bytes()).as_b...
Rust
src/main.rs
RedditNobility/rn_bot
f9e889e8441e9a3572e3a359856f5eebc6021421
#[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; use std::collections::HashSet; use std::ops::Sub; use std::sync::Arc; use chrono::{DateTime, Local}; use diesel::r2d2::ConnectionManager; use diesel::r2d2::{self}; use diesel::MysqlConnection; use serenity::client::bridge::gateway::Gatew...
#[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; use std::collections::HashSet; use std::ops::Sub; use std::sync::Arc; use chrono::{DateTime, Local}; use diesel::r2d2::ConnectionManager; use diesel::r2d2::{self}; use diesel::MysqlConnection; use serenity::client::bridge::gateway::Gatew...
#[command] async fn botinfo(ctx: &Context, msg: &Message) -> CommandResult { let mut data = ctx.data.write().await; let x: &mut Bot = data.get_mut::<DataHolder>().unwrap(); let _msg = msg .channel_id .send_message(&ctx.http, |m| { m.reference_message(msg); m.embed(|...
async fn serverinfo(ctx: &Context, msg: &Message) -> CommandResult { let string = msg .guild_id .unwrap() .members(&ctx.http, None, None) .await .unwrap() .len() .to_string(); let _msg = msg .channel_id .send_message(&ctx.http, |m| { ...
function_block-full_function
[ { "content": "pub fn add_user(user: &User, conn: &MysqlConnection) -> Result<(), diesel::result::Error> {\n\n use crate::schema::users::dsl::*;\n\n\n\n diesel::insert_into(users)\n\n .values(user)\n\n .execute(conn)\n\n .unwrap();\n\n\n\n Ok(())\n\n}\n", "file_path": "src/actio...
Rust
src/simulations.rs
nuhtan/minecraft_analysis
93d5dfaa87dbdf276881fd1c61d4ea17ba463fc3
use std::{ collections::HashMap, fs::{self, File}, io::{BufRead, BufReader}, sync::mpsc::Sender, time::Instant, }; use mvp_anvil::region::Region; use crate::{CachingRegion, ProgramStatus, mining::Direction, techniques::{self, branch_mining, branch_mining_with_poke_holes, chunks, Technique}}; pub ...
use std::{ collections::HashMap, fs::{self, File}, io::{BufRead, BufReader}, sync::mpsc::Sender, time::Instant, }; use mvp_anvil::region::Region; use crate::{CachingRegion, ProgramStatus, mining::Direction, techniques::{self, branch_mining, branch_mining_with_poke_holes, chunks, Technique}}; pub ...
l").unwrap().to_string(), results.get("copper").unwrap().to_string(), results.get("iron").unwrap().to_string(), results.get("lapis").unwrap().to_string(), results.get("redstone").unwrap().to_string(), ...
nk_data/{}_chunks.csv", region_file_name,)).unwrap(); csv_writer .write_record(&[ "chunk_x", "chunk_z", "y", "air", "lava", "coal", "copper", "iron", "lapis", "redstone", "gold", "emeralds", "diamonds", ]) .unwrap(); let region = Region::from_file(format!("regions...
random
[ { "content": "/// Takes a region file and coordinates and returns the name of the block at that location. This handles the intermediary step of determining the x and z [chunks](`mvp_anvil::chunk::Chunk`) that correspond with the coordinates.\n\n///\n\n/// * `region` - The [region](`mvp_anvil::region::Region`) f...
Rust
src/error.rs
cohomology/simplemm
be5c84ac7b3e721d18c4a2b12b63805bb63e3ab9
use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub))] pub enum Error { #[snafu(display("Could not open config file \"{}\": {}", filename, source))] FileOpenError { filename: String, source: std::io::Error, }, #[snafu(display("Could not parse configuration file \"{}\": {}",...
use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub))] pub enum Error { #[snafu(display("Could not open config file \"{}\": {}", filename, source))] FileOpenError { filename: String, source: std::io::Error, }, #[snafu(display("Could not parse configuration file \"{}\": {}",...
header in request \"{:?}\"", header, request))] CouldNotParseHeader { header: &'static str, request: String, }, #[snafu(display("Request {} without list name: \"{:?}\"", request_type, request))] RequestWithoutListName { request_type: &'static str, request: String, }, ...
lay("Empty or missing {} header in request \"{:?}\"", header, request))] EmptyOrMissingHeader { header: &'static str, request: String, }, #[snafu(display("Could not parse {}
random
[ { "content": "pub fn read_config(filename: &str) -> error::Result<types::Config> {\n\n let file = File::open(filename).context(error::FileOpenError { filename })?;\n\n let mut buf_reader = BufReader::new(file);\n\n let mut contents = String::new();\n\n buf_reader\n\n .read_to_string(&mut cont...
Rust
src/structs/style.rs
vonkruel/umya-spreadsheet
4e91f8fb6dc78fde50af7cf582ca55be7575f6b2
use structs::Alignment; use structs::Borders; use structs::Fill; use structs::Font; use structs::NumberingFormat; use structs::UInt32Value; #[derive(Clone, Default, Debug, PartialEq, PartialOrd)] pub struct Style { font: Option<Font>, fill: Option<Fill>, borders: Option<Borders>, alignment: Option<Alig...
use structs::Alignment; use structs::Borders; use structs::Fill; use structs::Font; use structs::NumberingFormat; use structs::UInt32Value; #[derive(Clone, Default, Debug, PartialEq, PartialOrd)] pub struct Style { font: Option<Font>, fill: Option<Fill>, borders: Option<Borders>, alignment: Option<Alig...
pub fn set_numbering_format(&mut self, value: NumberingFormat) -> &mut Self { self.numbering_format = Some(value); self } pub fn get_number_format(&self) -> &Option<NumberingFormat> { &self.get_numbering_format() } pub fn get_number_format_mut(&mut self) -> &mut Numbering...
e(_) => return self.numbering_format.as_mut().unwrap(), None => {} } self.set_numbering_format(NumberingFormat::default()); self.numbering_format.as_mut().unwrap() }
function_block-function_prefixed
[]
Rust
src/lib.rs
TomBebbington/cbox-rs
31bae23ba2d42066c2ac2f9d45f19de4fb04185a
extern crate libc; use libc::{free, c_char, c_void, size_t}; use std::borrow::Borrow; use std::ffi::{CString, CStr}; use std::{fmt, mem, str}; use std::ops::{Deref, DerefMut, Drop}; use std::cmp::PartialEq; use std::marker::PhantomData; pub trait DisposeRef { type RefTo; unsafe fn dispose(...
extern crate libc; use libc::{free, c_char, c_void, size_t}; use std::borrow::Borrow; use std::ffi::{CString, CStr}; use std::{fmt, mem, str}; use std::ops::{Deref, DerefMut, Drop}; use std::cmp::PartialEq; use std::marker::PhantomData; pub trait DisposeRef { type RefTo; unsafe fn dispose(...
tr(self.deref()) } } impl<T> Deref for CBox<T> where T:DisposeRef { type Target = T; fn deref(&self) -> &T { unsafe { mem::transmute(self.ptr) } } } impl<T> Borrow<T> for CBox<T> where T:DisposeRef { fn borrow(&self) -> &T { unsafe { mem::transmute(self.ptr) } } } impl<T> DerefM...
elf.ptr } #[inline(always)] pub unsafe fn unwrap(self) -> *mut D::RefTo { let ptr = self.ptr; mem::forget(self); ptr } pub fn as_semi<'a>(&'a self) -> &CSemiBox<'a, D> { unsafe { mem::transmute(self) } } pub fn as_semi_mut<'a...
random
[ { "content": "fn main() {\n\n unsafe {\n\n let text = CBox::from(\"Hello, world!\");\n\n steal_print(text.unwrap());\n\n }\n\n}\n", "file_path": "examples/str.rs", "rank": 1, "score": 30459.584544501005 }, { "content": "extern crate cbox;\n\nextern crate libc;\n\n\n\nuse ...
Rust
src/graph/stage/source/tick.rs
dmrolfs/proctor
9b2fac5e80e4a8874906a85302af7b34b4433f46
use std::fmt::{self, Debug}; use std::time::Duration; use async_stream::stream; use async_trait::async_trait; use cast_trait_object::dyn_upcast; use futures_util::stream::StreamExt; use tokio::sync::{mpsc, oneshot}; use crate::error::StageError; use crate::graph::shape::SourceShape; use crate::graph::{stage, Outlet, ...
use std::fmt::{self, Debug}; use std::time::Duration; use async_stream::stream; use async_trait::async_trait; use cast_trait_object::dyn_upcast; use futures_util::stream::StreamExt; use tokio::sync::{mpsc, oneshot}; use crate::error::StageError; use crate::graph::shape::SourceShape; use crate::graph::{stage, Outlet, ...
} impl<T> Debug for Tick<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Tick") .field("name", &self.name) .field("initial_delay", &self.initial_delay) .field("interval", &self.interval) .field("outlet", &self.outlet) ...
mpsc::UnboundedReceiver<TickMsg>, } impl<T> Tick<T> { pub fn new<S: Into<SharedString>>(name: S, initial_delay: Duration, interval: Duration, tick: T) -> Self { Self::with_constraint(name, initial_delay, interval, tick, Constraint::None) } pub fn with_constraint<S: Into<SharedString>>( na...
random
[ { "content": "#[dyn_upcast]\n\n#[async_trait]\n\npub trait Stage: fmt::Debug + Send + Sync {\n\n fn name(&self) -> SharedString;\n\n async fn check(&self) -> ProctorResult<()>;\n\n async fn run(&mut self) -> ProctorResult<()>;\n\n async fn close(self: Box<Self>) -> ProctorResult<()>;\n\n}\n\n\n", ...
Rust
src/error.rs
key262yek/rust_rts
00de5f51c3875b7b9acf43906633a581f136cdb7
use crate::prelude::*; #[derive(Debug)] pub struct Error{ err: Box<ErrorCode>, } pub const MAX_TRIAL : usize = 100; pub type Result<T> = std::result::Result<T, Error>; impl Error{ pub fn make_error_msg(msg: String) -> Self{ Error { err: Box::new(...
use crate::prelude::*; #[derive(Debug)] pub struct Error{ err: Box<ErrorCode>, } pub const MAX_TRIAL : usize = 100; pub type Result<T> = std::result::Result<T, Error>; impl Error{ pub fn make_error_msg(msg: String) -> Self{ Error { err: Box::new(...
#[test] fn test_classify(){ use std::io; assert_eq!(Error::make_error_msg("Test message".to_string()).classify(), Category::Data); assert_eq!(Error::make_error_io(io::Error::new(io::ErrorKind::NotFound, "Test io error")).classify(), Category::Io); asse...
d"); assert_eq!(format!("{}", Error::make_error_syntax(ErrorCode::InvalidArgumentInput)).as_str(), "Given argument is invalid"); assert_eq!(format!("{}", Error::make_error_syntax(ErrorCode::InvalidFormat)).as_str(), "Invalid Format"); assert_eq!(format!("{}", Error::make_...
function_block-function_prefixed
[ { "content": "fn enum_iter(timeiter : &mut ExponentialStep){\n\n for _time in timeiter.into_iter(){\n\n }\n\n timeiter.renew();\n\n}\n\n\n", "file_path": "benches/bench_enum_vs_struct.rs", "rank": 0, "score": 194844.4342988215 }, { "content": "fn enum_renew(timeiter : &mut Exponenti...
Rust
src/container/builder_impl.rs
fbrv/youki
388dcaf5bdfb25c8759f3864039b6e793553a60a
use std::{fs, io::Write, path::PathBuf}; use anyhow::{Context, Result}; use nix::{ sched, unistd::{Gid, Uid}, }; use oci_spec::Spec; use crate::{ capabilities, cgroups, namespaces::Namespaces, notify_socket::NotifyListener, process::{child, fork, parent}, rootfs, rootless::Rootless, ...
use std::{fs, io::Write, path::PathBuf}; use anyhow::{Context, Result}; use nix::{ sched, unistd::{Gid, Uid}, }; use oci_spec::Spec; use crate::{ capabilities, cgroups, namespaces::Namespaces, notify_socket::NotifyListener, process::{child, fork, parent}, rootfs, rootless::Rootless, ...
{ log::debug!("failed to run container_init: {:?}", error); return -1; } 0 }); let init_pid = fork::clone(cb, namespaces.clone_flags)?; log::debug!("init pid is {:?}", init_pid); parent.wait_for_child_ready(init_pid)?; ...
container_init( self.init, self.rootless.clone(), self.spec.clone(), self.syscall.clone(), self.rootfs.clone(), self.console_socket.clone(), self.notify_path.clone(), &mut child, )
call_expression
[ { "content": "/// Drop any extra granted capabilities, and reset to defaults which are in oci specification\n\npub fn drop_privileges(cs: &LinuxCapabilities, syscall: &impl Syscall) -> Result<()> {\n\n log::debug!(\"dropping bounding capabilities to {:?}\", cs.bounding);\n\n syscall.set_capability(CapSet:...
Rust
scheme/src/bulletproofs/mod.rs
Vawheter/CLINKv2
e699bbf3e3c96cea65407826a1c73a00b5bac417
pub mod arithmetic_circuit; pub mod inner_product_proof; use math::{msm::VariableBaseMSM, Field, PairingEngine, PrimeField, Zero}; use crate::r1cs::{Index, LinearCombination}; use crate::Vec; #[cfg(test)] #[cfg(test_bulletproofs)] mod test; pub fn vector_matrix_product<E: PairingEngine>(v: &Vec<E::Fr>, m: &Vec<Vec<...
pub mod arithmetic_circuit; pub mod inner_product_proof; use math::{msm::VariableBaseMSM, Field, PairingEngine, PrimeField, Zero}; use crate::r1cs::{Index, LinearCombination}; use crate::Vec; #[cfg(test)] #[cfg(test_bulletproofs)] mod test; pub fn vector_matrix_product<E: PairingEngine>(v: &Vec<E::Fr>, m: &Vec<Vec<...
} out } pub struct VecPoly3<E: PairingEngine>( pub Vec<E::Fr>, pub Vec<E::Fr>, pub Vec<E::Fr>, pub Vec<E::Fr>, ); impl<E: PairingEngine> VecPoly3<E> { pub fn zero(n: usize) -> Self { VecPoly3( vec![E::Fr::zero(); n], vec![E::Fr::zero(); n], vec![E...
ct<E: PairingEngine>(a: &[E::Fr], b: &[E::Fr]) -> E::Fr { let mut out = E::Fr::zero(); if a.len() != b.len() { panic!("inner_product(a,b): lengths of vectors do not match"); } for i in 0..a.len() { out += &(a[i] * &(b[i]));
function_block-random_span
[ { "content": "pub fn batch_inversion<F: Field>(v: &mut [F]) {\n\n // Montgomery’s Trick and Fast Implementation of Masked AES\n\n // Genelle, Prouff and Quisquater\n\n // Section 3.2\n\n\n\n // First pass: compute [a, ab, abc, ...]\n\n let mut prod = Vec::with_capacity(v.len());\n\n let mut tm...
Rust
src/ic-certified-map/src/rbtree/test.rs
edddyguo/cdk-rs
73298f1eb6e8f3030acb26c52dd1fc1acd0f9711
use super::*; use std::convert::AsRef; fn insert(t: &mut RbTree<Vec<u8>, Vec<u8>>, k: impl AsRef<[u8]>, v: impl AsRef<[u8]>) { t.insert(k.as_ref().to_vec(), v.as_ref().to_vec()) } fn get_labels<'a>(ht: &HashTree<'a>) -> Vec<&'a [u8]> { fn go<'a>(t: &HashTree<'a>, keys: &mut Vec<&'a [u8]>) { match t { ...
use super::*; use std::convert::AsRef; fn insert(t: &mut RbTree<Vec<u8>, Vec<u8>>, k: impl AsRef<[u8]>, v: impl AsRef<[u8]>) { t.insert(k.as_ref().to_vec(), v.as_ref().to_vec()) } fn get_labels<'a>(ht: &HashTree<'a>) -> Vec<&'a [u8]> { fn go<'a>(t: &HashTree<'a>, keys: &mut Vec<&'a [u8]>) { match t { ...
let mut values = vec![]; go(ht, &mut values); values } #[test] fn test_witness() { let mut t = RbTree::<Vec<u8>, Vec<u8>>::new(); for i in 0u64..10 { let key = (1 + 2 * i).to_be_bytes(); let val = (1 + 2 * i).to_le_bytes(); insert(&mut t, key, val); assert_eq!(t.get...
s); go(&lr.1, values); } HashTree::Labeled(_, t) => { go(&*t, values); } _ => (), } }
function_block-function_prefixed
[ { "content": "/// Returns a copy of the stable memory. This will map the whole memory (even if not all of it\n\n/// has been written to).\n\npub fn stable_bytes() -> Vec<u8> {\n\n let size = (stable_size() as usize) << 16;\n\n let mut vec = Vec::with_capacity(size);\n\n unsafe {\n\n vec.set_len(...
Rust
examples/triangle.rs
lmtr0/bgfx-rs
0ba5350b00d4ed3953e611f7b02fa51beb8e7aa3
use bgfx_rs::*; use glam::{EulerRot, Mat4, Vec3}; use glfw::{Action, Context, Key}; use std::{time::Instant}; mod common; use common::{get_render_type, get_platform_data}; const WIDTH: usize = 1280; const HEIGHT: usize = 720; #[repr(packed)] struct PosColorVertex { _x: f32, _y: f32, } static TRIANGLE_VERTIC...
use bgfx_rs::*; use glam::{EulerRot, Mat4, Vec3}; use glfw::{Action, Context, Key}; use std::{time::Instant}; mod common; use common::{get_render_type, get_platform_data}; const WIDTH: usize = 1280; const HEIGHT: usize = 720; #[repr(packed)] struct PosColorVertex { _x: f32, _y: f32, } static TRIANGLE_VERTIC...
t mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); let (mut window, events) = glfw .create_window( WIDTH as _, HEIGHT as _, "triangle.rs bgfx-rs example - ESC to close", glfw::WindowMode::Windowed, ) .expect("Failed to create GLFW window....
rerType::OpenGL => "gl", RendererType::Vulkan => "vk", e => panic!("Unsupported render type {:#?}", e), }; let mut data = std::fs::read(format!("./resources/triangle/{}.{}", name, ext))?; data.push(0); Ok(data) } pub fn load_shader_program(vs: &str, ps: &str) -> std:...
random
[ { "content": "/// * `width`:\n\n/// Back-buffer width.\n\n/// * `height`:\n\n/// Back-buffer height.\n\n/// * `flags`:\n\n/// See: [ResetFlags] for more info.\n\n/// - [ResetFlags::NONE] - No reset flags.\n\n/// - [ResetFlags::FULLSCREEN] - Not supported yet.\n\n/// - [ResetMsaaFlags::X[2/4/8/16]] - Enabl...
Rust
tests/async.rs
faern/oneshot
90f22768c26e1c90b972cdc5669bed4a7c876a24
#![cfg(all(feature = "async", not(loom)))] use core::mem; use core::time::Duration; mod helpers; use helpers::DropCounter; #[tokio::test] async fn send_before_await_tokio() { let (sender, receiver) = oneshot::channel(); assert!(sender.send(19i128).is_ok()); assert_eq!(receiver.await, Ok(19i128)); } #[as...
#![cfg(all(feature = "async", not(loom)))] use core::mem; use core::time::Duration; mod helpers; use helpers::DropCounter; #[tokio::test] async fn send_before_await_tokio() { let (sender, receiver) = oneshot::channel(); assert!(sender.send(19i128).is_ok()); assert_eq!(receiver.await, Ok(19i128)); } #[as...
#[tokio::test] async fn await_before_send_then_drop_sender_tokio() { let (sender, receiver) = oneshot::channel::<u128>(); let t = tokio::spawn(async { tokio::time::sleep(Duration::from_millis(10)).await; mem::drop(sender); }); assert!(receiver.await.is_err()); t.await.unwrap(); } ...
async fn await_before_send_async_std() { let (sender, receiver) = oneshot::channel(); let (message, counter) = DropCounter::new(79u128); let t = async_std::task::spawn(async move { async_std::task::sleep(Duration::from_millis(10)).await; sender.send(message) }); let returned_message ...
function_block-full_function
[ { "content": "/// Creates a new oneshot channel and returns the two endpoints, [`Sender`] and [`Receiver`].\n\npub fn channel<T>() -> (Sender<T>, Receiver<T>) {\n\n // Allocate the channel on the heap and get the pointer.\n\n // The last endpoint of the channel to be alive is responsible for freeing the c...
Rust
src/semantics/statement/variable_declarators.rs
noiz354/javaparser.rs
7165b63bd596e5ecfb1e1f16f21b0b9a6ce20650
use analyze::resolve; use analyze::resolve::scope::Scope; use parse::tree::{VariableDeclarator, VariableDeclarators}; use semantics::{expr, Context}; use std::ops::Deref; pub fn apply<'def>( declarator: &mut VariableDeclarators<'def>, context: &mut Context<'def, '_, '_>, ) { for decl in &mut declarator.dec...
use analyze::resolve; use analyze::resolve::scope::Scope; use parse::tree::{VariableDeclarator, VariableDeclarators}; use semantics::{expr, Context}; use std::ops::Deref; pub fn apply<'def>( declarator: &mut VariableDeclarators<'def>, context: &mut Context<'def, '_, '_>, ) { for decl in &mut declarator.dec...
}
rap!( Type::Array, var.declarators .first() .unwrap() .tpe .borrow() .deref() .clone() ); assert_eq!( tpe, ArrayType { tpe: Box::new(Type::Param...
function_block-function_prefixed
[ { "content": "pub fn apply(root: &mut Root) {\n\n let mut grapher = Grapher::new(root);\n\n grapher.collect();\n\n\n\n let queue = SegQueue::new();\n\n\n\n for &node_index in grapher.pool.iter() {\n\n queue.push(grapher.nodes.get(node_index).unwrap());\n\n }\n\n\n\n let mut threads = ve...
Rust
src/rust/rust-proto-new/src/graplinc/grapl/api/plugin_work_queue/v1beta1_server.rs
insanitybit/grapl
39c6019fba893c1f4299c6a27e97eba6f149cec0
use std::time::Duration; use futures::{ channel::oneshot::{ self, Receiver, Sender, }, Future, FutureExt, }; use proto::plugin_work_queue_service_server::{ PluginWorkQueueService, PluginWorkQueueServiceServer as ServerProto, }; use tokio::net::TcpListener; use tokio_stre...
use std::time::Duration; use futures::{ channel::oneshot::{ self, Receiver, Sender, }, Future, FutureExt, }; use proto::plugin_work_queue_service_server::{ PluginWorkQueueService, PluginWorkQueueServiceServer as ServerProto, }; use tokio::net::TcpListener; use tokio_stre...
pub fn service_name(&self) -> &'static str { self.service_name } pub async fn serve(self) -> Result<(), Box<dyn std::error::Error>> { let (healthcheck_handle, health_service) = init_health_service::<ServerProto<GrpcApi<T>>, _, _>( self....
pub fn new( api_server: T, tcp_listener: TcpListener, healthcheck: H, healthcheck_polling_interval: Duration, ) -> (Self, Sender<()>) { let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); ( Self { api_server, healthch...
function_block-full_function
[ { "content": "#[async_trait]\n\npub trait Cache: Clone + Send + Sync {\n\n type CacheErrorT: CheckedError + Send + Sync + 'static;\n\n\n\n async fn all_exist<CA>(&mut self, cacheables: &[CA]) -> bool\n\n where\n\n CA: Cacheable + Send + Sync + Clone + 'static,\n\n {\n\n // If cacheable...
Rust
src/core/bitvec.rs
LukasKalbertodt/stable-vec
7e6d29cea532c76a4a5d196c71e9f4edc07e5596
use std::{ alloc::{alloc, alloc_zeroed, dealloc, handle_alloc_error, realloc, Layout}, fmt, mem::{align_of, size_of}, ptr::{self, NonNull}, }; use super::Core; pub struct BitVecCore<T> { elem_ptr: NonNull<T>, bit_ptr: NonNull<usize>, cap: usize, ...
use std::{ alloc::{alloc, alloc_zeroed, dealloc, handle_alloc_error, realloc, Layout}, fmt, mem::{align_of, size_of}, ptr::{self, NonNull}, }; use super::Core; pub struct BitVecCore<T> { elem_ptr: NonNull<T>, bit_ptr: NonNull<usize>, cap: usize, ...
assert_eq!(num_usizes_for(256), 4); assert_eq!(num_usizes_for(257), 5); assert_eq!(num_usizes_for(258), 5); assert_eq!(num_usizes_for(259), 5); } #[cfg(target_pointer_width = "32")] { assert_eq!(num_usizes_for(31), 1); assert...
unsafe fn has_element_at(&self, idx: usize) -> bool { debug_assert!(idx < self.cap()); let usize_pos = idx / BITS_PER_USIZE; let bit_pos = idx % BITS_PER_USIZE; let block = *self.bit_ptr.as_ptr().add(usize_pos); ((block >> bit_pos) & 0b1) != 0 } unsafe fn...
random
[ { "content": "// ===========================================================================\n\n// ===== Functions to generate instances with a given size\n\n// ===========================================================================\n\nfn full_sv(size: usize) -> StableVec<u32> {\n\n (0..size as u32).coll...
Rust
storage/src/cache/dummycache.rs
bergwolf/image-service
90d06189e867b334fc982e994bde593f49465154
use std::io::Result; use std::sync::Arc; use vm_memory::VolatileSlice; use crate::backend::BlobBackend; use crate::cache::*; use crate::device::{BlobPrefetchControl, RafsBio}; use crate::factory::CacheConfig; use crate::utils::{alloc_buf, copyv}; use crate::{compress, StorageResult}; use nydus_utils::digest; pub ...
use std::io::Result; use std::sync::Arc; use vm_memory::VolatileSlice; use crate::backend::BlobBackend; use crate::cache::*; use crate::device::{BlobPrefetchControl, RafsBio}; use crate::factory::CacheConfig; use crate::utils::{alloc_buf, copyv}; use crate::{compress, StorageResult}; use nydus_utils::digest; pub ...
fn blob_size(&self, blob: &RafsBlobEntry) -> Result<u64> { self.backend() .blob_size(&blob.blob_id) .map_err(|e| eother!(e)) } fn digester(&self) -> digest::Algorithm { self.digester } fn compressor(&self) -> compress::Algorithm { self.compressor ...
fn read(&self, bios: &mut [RafsBio], bufs: &[VolatileSlice]) -> Result<usize> { let mut buffer_holder: Vec<Vec<u8>> = Vec::new(); let offset = bios[0].offset; let mut user_size = 0; let bios_len = bios.len(); for bio in bios { if !bio.user_io { conti...
function_block-full_function
[ { "content": "/// Check hash of data matches provided one\n\npub fn digest_check(data: &[u8], digest: &RafsDigest, digester: digest::Algorithm) -> bool {\n\n digest == &RafsDigest::from_buf(data, digester)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use vm_memory::VolatileSlice;\n\n\n\n use crate::Stor...
Rust
src/frame_queue.rs
sunsided/realsense-rust
6908a3d6ca172b8d7f388c10434b1800ceefafbe
use crate::{ base::DEFAULT_TIMEOUT, common::*, error::{Error as RsError, ErrorChecker, Result as RsResult}, frame::{ marker::{Any, FrameKind}, Frame, GenericFrame, }, }; #[derive(Debug)] pub struct FrameQueue { pub(crate) ptr: NonNull<realsense_sys::rs2_frame_queue>, } impl F...
use crate::{ base::DEFAULT_TIMEOUT, common::*, error::{Error as RsError, ErrorChecker, Result as RsResult}, frame::{ marker::{Any, FrameK
= rx.await.unwrap()?; Ok(frame) } pub fn try_wait(&mut self) -> RsResult<Option<Frame<Any>>> { unsafe { let mut checker = ErrorChecker::new(); let mut ptr: *mut realsense_sys::rs2_frame = std::ptr::null_mut(); let ret = realsense_sys::rs2_poll_for_frame...
ind}, Frame, GenericFrame, }, }; #[derive(Debug)] pub struct FrameQueue { pub(crate) ptr: NonNull<realsense_sys::rs2_frame_queue>, } impl FrameQueue { pub fn with_capacity(capacity: usize) -> RsResult<Self> { let queue = unsafe { let mut checker = ErrorChecker::new(); ...
random
[ { "content": "fn main() -> Result<()> {\n\n println!(\"Looking for RealSense devices\");\n\n let ctx = realsense_rust::Context::new()?;\n\n let devices = ctx.query_devices(None)?;\n\n let mut devices_found: bool = false;\n\n for device in devices {\n\n let device = device.unwrap();\n\n ...
Rust
examples/game/gng.rs
fabiao/bevy
0dfb30599f6b8f272b22b66dc601b1b5176ec43c
use bevy::{ input::{keyboard::KeyCode, Input}, prelude::*, }; fn main() { App::build() .add_default_plugins() .add_startup_system(setup.system()) .add_system(player_movement_system.system()) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>,...
use bevy::{ input::{keyboard::KeyCode, Input}, prelude::*, }; fn main() { App::build() .add_default_plugins() .add_startup_system(setup.system()) .add_system(player_movement_system.system()) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>,...
} if keyboard_input.pressed(KeyCode::Down) { if keyboard_input.pressed(KeyCode::LShift) { h_direction = 0.0; sprite.index = 7; } else { v_direction -= 1.0; if timer.finished { if sprite.index <...
if timer.finished { if sprite.index < 18 || sprite.index > 20 { sprite.index = 18; } else { sprite.index += 1; } timer.reset(); }
if_condition
[ { "content": "/// rotates the parent, which will result in the child also rotating\n\nfn rotator_system(time: Res<Time>, mut query: Query<(&Rotator, &mut Rotation)>) {\n\n for (_rotator, mut rotation) in &mut query.iter() {\n\n rotation.0 = rotation.0 * Quat::from_rotation_x(3.0 * time.delta_seconds);...
Rust
benches/json_benchmark_c7d3d9b/src/lib.rs
camchenry/lolbench
941ebb099a398ad33cb3658bcd021a98081dfa80
#[macro_use] extern crate serde_derive; #[macro_use] extern crate lolbench_support; extern crate time; extern crate serde; extern crate serde_json; extern crate rustc_serialize; #[macro_use] pub mod enums; pub mod adapter; pub mod color; pub mod empty; pub mod prim_str; pub mod timer; pub mod copy; pub use self::...
#[macro_use] extern crate serde_derive; #[macro_use] extern crate lolbench_support; extern crate time; extern crate serde; extern crate serde_json; extern crate rustc_serialize; #[macro_use] pub mod enums; pub mod adapter; pub mod color; pub mod empty; pub mod prim_str; pub mod timer; pub mod copy; pub use self::...
fn rustc_serialize_parse_dom( mut bytes: &[u8], ) -> Result<rustc_serialize::json::Json, rustc_serialize::json::BuilderError> { rustc_serialize::json::Json::from_reader(&mut bytes) } fn rustc_serialize_parse_struct<T>(bytes: &[u8]) -> rustc_serialize::json::DecodeResult<T> where T: rustc_serialize::Decod...
fn serde_json_parse_struct<'de, T>(bytes: &'de [u8]) -> serde_json::Result<T> where T: serde::Deserialize<'de>, { use std::str; let s = str::from_utf8(bytes).unwrap(); serde_json::from_str(s) }
function_block-full_function
[ { "content": "pub fn seq_merge_sort<T: Ord + Copy>(v: &mut [T]) {\n\n let n = v.len();\n\n let mut buf = Vec::with_capacity(n);\n\n // We always overwrite the buffer before reading to it, and we want to\n\n // duplicate the behavior of parallel sort.\n\n unsafe {\n\n buf.set_len(n);\n\n ...
Rust
vicis_codegen/src/codegen/pass/spiller.rs
maekawatoshiki/vicis
506168224630929d51bccabf783ff009c45ec21e
use super::liveness::{Liveness, ProgramPoint}; use crate::codegen::{ function::{ basic_block::BasicBlockId, instruction::{InstructionData as ID, InstructionId, InstructionInfo as II}, slot::SlotId, Function, }, isa::TargetIsa, register::VReg, }; use vicis_core::ir::types:...
use super::liveness::{Liveness, ProgramPoint}; use crate::codegen::{ function::{ basic_block::BasicBlockId, instruction::{InstructionData as ID, InstructionId, InstructionInfo as II}, slot::SlotId, Function, }, isa::TargetIsa, register::VReg, }; use vicis_core::ir::types:...
:InstInfo as II>::Data>, inst: InstructionId<<T::InstInfo as II>::Data>, block: BasicBlockId, ) { let after_pp = self.liveness.inst_to_pp[&after]; let next_after = self.function.layout.next_inst_of(after).unwrap(); let next_after_pp = self.liveness.inst_to_pp[&next_after]; ...
def_id = Some(id); def_block = Some(inst.parent); } inst.replace_vreg(&mut self.function.data.vreg_users, vreg, new_vreg); } let def_id = def_id.unwrap(); let def_block = def_block.unwrap(); let inst = T::InstInfo::st...
random
[ { "content": "pub fn find_preferred_registers<T: TargetIsa>(function: &Function<T>, vreg: VReg) -> Vec<Reg> {\n\n let mut list = vec![];\n\n let users = function.data.vreg_users.get(vreg);\n\n for user in users {\n\n let inst = function.data.inst_ref(user.inst_id);\n\n if user.write {\n\n...
Rust
api/src/views/locations.rs
bloveless/spacemonger-api
4546becdaf8520bd4cced9f9e4611b6bd195d6b5
use actix_web::{web, get, Responder, HttpResponse}; use serde::Deserialize; use sqlx::{PgPool, Error, Row}; use sqlx::postgres::PgRow; use crate::models::{MarketData, Route}; #[get("/locations/{location_symbol}/goods")] pub async fn goods(location_symbol: web::Path<String>, pg_pool: web::Data<PgPool>) -> impl Responde...
use actix_web::{web, get, Responder, HttpResponse}; use serde::Deserialize; use sqlx::{PgPool, Error, Row}; use sqlx::postgres::PgRow; use crate::models::{MarketData, Route}; #[get("/locations/{location_symbol}/goods")] pub async fn goods(location_symbol: web::Path<String>, pg_pool: web::Data<PgPool>) -> impl Responde...
#[get("/locations/{location_symbol}/routes")] pub async fn routes(location_symbol: web::Path<String>, pg_pool: web::Data<PgPool>) -> impl Responder { let mut tx = pg_pool.begin().await.unwrap(); sqlx::query("DROP TABLE IF EXISTS tmp_latest_location_goods;") .execute(&mut tx) .await.unwrap(); ...
on_market_data md WHERE md.location_symbol = $1; ") .bind(location_symbol.as_str()) .map(|row: PgRow| { row.get("good_symbol") }) .fetch_all(pg_pool.as_ref()) .await; match market_data_goods { Ok(market_data_goods) => HttpResponse::Ok().json(m...
function_block-function_prefixed
[ { "content": "// function that will be called on new Application to configure views for this module\n\npub fn init(cfg: &mut web::ServiceConfig) {\n\n // index\n\n cfg.service(index::index);\n\n\n\n // users\n\n cfg.service(users::users);\n\n cfg.service(users::user_stats);\n\n cfg.service(use...
Rust
byztimed/src/core.rs
akamai-contrib/byztimed
9236fc2d8e34a9007405263116fca110ae45e7af
use crate::config::*; use crate::peer_name::PeerName; use byztime::*; use std::collections::*; use std::io; use std::iter::FromIterator; #[cfg(test)] use quickcheck::{Arbitrary, Gen}; pub type UniqueId = [u8; 16]; fn light_gigameter() -> Timestamp { Timestamp::new(3, 335_640_952) } #[derive(Debug, Clone, Eq, ...
use crate::config::*; use crate::peer_name::PeerName; use byztime::*; use std::collections::*; use std::io; use std::iter::FromIterator; #[cfg(test)] use quickcheck::{Arbitrary, Gen}; pub type UniqueId = [u8; 16]; fn light_gigameter() -> Timestamp { Timestamp::new(3, 335_640_952) } #[derive(Debug, Clone, Eq, ...
global_offset: Timestamp::arbitrary(g), } } } pub struct CoreState { ctx: ProviderContext, ro_mode: bool, drift_ppb: i64, era: Era, inflight: HashMap<UniqueId, PeerName>, peers: HashMap<PeerName, PeerState>, } #[derive(Debug, Clone)] pub stru...
G: Gen>(g: &mut G) -> Response { let mut unique_id = [0; 16]; g.fill_bytes(&mut unique_id); Response { unique_id, era: Era::arbitrary(g), local_clock: Timestamp::arbitrary(g),
function_block-random_span
[ { "content": "///Construct a crypto-NAK error response\n\npub fn serialize_crypto_nak(out: &mut Vec<u8>, unique_id: &core::UniqueId) {\n\n let packet = wire::Packet {\n\n msg: Some(wire::packet::Msg::Error(wire::Error {\n\n unique_id: unique_id.to_vec(),\n\n error: Some(wire::err...
Rust
src/policy/sync.rs
Nytelife26/stretto
97b7ca2c15b8cbdd383379a1dcbbcf6a31fccb68
use crate::policy::PolicyInner; use crate::sync::{ select, spawn, stop_channel, unbounded, JoinHandle, Receiver, Sender, UnboundedReceiver, UnboundedSender, }; use crate::{CacheError, MetricType, Metrics}; use crossbeam_channel::RecvError; use parking_lot::Mutex; use std::collections::hash_map::RandomState; use...
use crate::policy::PolicyInner; use crate::sync::{ select, spawn, stop_channel, unbounded, JoinHandle, Receiver, Sender, UnboundedReceiver, UnboundedSender, }; use crate::{CacheError, MetricType, Metrics}; use crossbeam_channel::RecvError; use parking_lot::Mutex; use std::collections::hash_map::RandomState; use...
} #[inline] fn handle_items(&self, items: Result<Vec<u64>, RecvError>) { match items { Ok(items) => { let mut inner = self.inner.lock(); inner.admit.increments(items); } #[cfg(feature = "log")] Err(e) => { ...
spawn(move || loop { select! { recv(self.items_rx) -> items => self.handle_items(items), recv(self.stop_rx) -> _ => { drop(self); return; }, } })
call_expression
[ { "content": "/// CacheCallback is for customize some extra operations on values when related event happens.\n\npub trait CacheCallback<V: Send + Sync>: Send + Sync + 'static {\n\n /// on_exit is called whenever a value is removed from cache. This can be\n\n /// used to do manual memory deallocation. Woul...
Rust
src/channel/channel_width.rs
zatchl/kawaiifi
5bf2b1106a77cec320c1c5480751e6dbd478361a
use crate::Ie; use derive_more::{ BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Deref, DerefMut, From, Not, }; use enumflags2::{bitflags, BitFlags}; use std::{convert::From, fmt::Display}; #[bitflags] #[derive(Copy, Clone, Debug, PartialEq, Ord, PartialOrd, Eq)] #[repr(u8)] pub enum ChannelWidth ...
use crate::Ie; use derive_more::{ BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Deref, DerefMut, From, Not, }; use enumflags2::{bitflags, BitFlags}; use std::{convert::From, fmt::Display}; #[bitflags] #[derive(Copy, Clone, Debug, PartialEq, Ord, PartialOrd, Eq)] #[repr(u8)] pub enum ChannelWidth ...
}
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut channel_widths = Vec::new(); for channel_width in [ ChannelWidth::TwentyMhz, ChannelWidth::TwentyTwoMhz, ChannelWidth::FortyMhz, ChannelWidth::EightyMhz, ChannelWidth...
function_block-full_function
[ { "content": "pub fn from_bytes(bytes: &[u8]) -> Result<Vec<Ie>, IeError> {\n\n let mut bytes = Cursor::new(bytes);\n\n\n\n let mut ies = Vec::new();\n\n\n\n loop {\n\n // The first byte of the IE is the ID\n\n // Break out of the loop if reading the byte fails\n\n let ie_id = matc...
Rust
src/data_structure/bitset.rs
katandps/rust_lib_for_comp
8375ce89a31ecc9a87f11b71727b6eccaf888c03
use crate::prelude::*; #[snippet(name = "bit-set", doc_hidden)] #[derive(Clone, Eq, PartialEq)] pub struct BitSet { bits: Vec<u64>, size: usize, } #[snippet(name = "bit-set", doc_hidden)] impl BitSet { const BLOCK_LEN: usize = 1 << Self::BLOCK_LEN_LEN; const BLOCK_LEN_LEN: usize = 6; pub fn new(...
use crate::prelude::*; #[snippet(name = "bit-set", doc_hidden)] #[derive(Clone, Eq, PartialEq)] pub struct BitSet { bits: Vec<u64>, size: usize, } #[snippet(name = "bit-set", doc_hidden)] impl BitSet { const BLOCK_LEN: usize = 1 << Self::BLOCK_LEN_LEN; const BLOCK_LEN_LEN: usize = 6; pub fn new(...
} #[snippet(name = "bit-set", doc_hidden)] impl BitAnd for BitSet { type Output = BitSet; fn bitand(self, rhs: Self) -> Self::Output { assert_eq!(self.size, rhs.size); Self { bits: (0..self.bits.len()) .map(|i| self.bits[i] & rhs.bits[i]) .collect()...
fn index(&self, index: usize) -> &bool { assert!(index < self.size); &[false, true][((self.bits[index >> Self::BLOCK_LEN_LEN] >> (index & (Self::BLOCK_LEN - 1))) & 1) as usize] }
function_block-full_function
[ { "content": "#[snippet(name = \"solver\", doc_hidden)]\n\npub fn solve<R: BufRead, W: Write, F: FnMut() -> R>(mut reader: Reader<F>, mut writer: Writer<W>) {\n\n let n: usize = reader.v();\n\n writer.ln(n);\n\n}\n", "file_path": "src/solver.rs", "rank": 0, "score": 234000.54784930527 }, {...
Rust
src/commands/bindle.rs
fermyon/spin
ec9a74b14d2af7cff860122eba067ecaf44ca0d1
use std::path::PathBuf; use anyhow::{Context, Result}; use clap::{Parser, Subcommand}; use semver::BuildMetadata; use crate::{opts::*, parse_buildinfo}; #[derive(Subcommand, Debug)] pub enum BindleCommands { Prepare(Prepare), Push(Push), } impl BindleCommands { pub async fn run(self) -> Resul...
use std::path::PathBuf; use anyhow::{Context, Result}; use clap::{Parser, Subcommand}; use semver::BuildMetadata; use crate::{opts::*, parse_buildinfo}; #[derive(Subcommand, Debug)] pub enum BindleCommands { Prepare(Prepare), Push(Push), } impl BindleCommands { pub async fn run(self) -> Resul...
} } #[derive(Parser, Debug)] pub struct Prepare { #[clap( name = APP_CONFIG_FILE_OPT, short = 'f', long = "file", )] pub app: Option<PathBuf>, #[clap( name = BUILDINFO_OPT, long = "buildinfo", parse(try_from_str = parse_buildinfo), )] ...
match self { Self::Prepare(cmd) => cmd.run().await, Self::Push(cmd) => cmd.run().await, }
if_condition
[ { "content": "/// Return the hex-encoded SHA256 digest of the given file.\n\npub fn file_sha256_digest_string(path: impl AsRef<Path>) -> std::io::Result<String> {\n\n let mut file = std::fs::File::open(path)?;\n\n let mut sha = sha2::Sha256::new();\n\n std::io::copy(&mut file, &mut sha)?;\n\n let di...
Rust
lib/src/record/warp_exchange.rs
beltram/stubr
c140fd6a0f32c8bccdd1f7c7c7fb18692f27eac3
use std::{iter::FromIterator, str::FromStr}; use http_types::{ Body as HttpBody, headers::HeaderName as HttpHeaderName, headers::HeaderValue as HttpHeaderValue, headers::HeaderValues as HttpHeaderValues, Method as HttpMethod, Request as HttpRequest, Response as HttpResponse, Url, }; use...
use std::{iter::FromIterator, str::FromStr}; use http_types::{ Body as HttpBody, headers::HeaderName as HttpHeaderName, headers::HeaderValue as HttpHeaderValue, headers::HeaderValues as HttpHeaderValues, Method as HttpMethod, Request as HttpRequest, Response as HttpResponse, Url, }; use...
#[test] fn should_strip_leading_path_slash() { let input = WarpRequest { addr: String::from("http://github.com/"), path: String::from("/api/colors"), ..Default::default() }; let output = RecordedRequest::from(input).0; assert_eq!(output.url().as_str(), "http://githu...
let input = WarpRequest { addr: String::from("http://github.com/"), path: String::from("api/colors"), ..Default::default() }; let output = RecordedRequest::from(input).0; assert_eq!(output.url().as_str(), "http://github.com/api/colors"); }
function_block-function_prefix_line
[ { "content": "fn req_header(uri: String, values: &[(&str, &str)]) -> Request<()> {\n\n let mut base = Request::get(uri);\n\n for (k, v) in values {\n\n base = base.header(*k, *v);\n\n }\n\n base.body(()).unwrap()\n\n}\n", "file_path": "lib/tests/record/req_headers.rs", "rank": 0, ...
Rust
src/identity.rs
mamcx/forbidden
77c8bce8720d9255684055a8f1e5f1003a27a057
use std::collections::HashMap; use crate::credentials::Credential; use crate::errors::{ResultAuth, ResultPwd}; use crate::forms::{EmailPassForm, UserPassForm}; use crate::prelude::AuthError; use crate::properties::Properties; use crate::token::Token; pub const REALM_DEFAULT: &str = "GLOBAL"; pub trait Identity { ...
use std::collections::HashMap; use crate::credentials::Credential; use crate::errors::{ResultAuth, ResultPwd}; use crate::forms::{EmailPassForm, UserPassForm}; use crate::prelude::AuthError; use crate::properties::Properties; use crate::token::Token; pub const REALM_DEFAULT: &str = "GLOBAL"; pub trait Identity { ...
} } pub trait IdentityProviderEmailPwd: IdentityProvider<EmailPassForm> { fn login(&self, identity: &EmailPassForm) -> ResultAuth<Token> { self.verify_password(identity) } fn verify_password(&self, credentials: &EmailPassForm) -> ResultAuth<Token> { if let Some(user) = self.find(&cred...
if let Some(user) = self.find(&credentials.username)? { user.verify_challenge(&credentials.pwd)?; Ok(credentials.into()) } else { Err(AuthError::UserNotFound { named: credentials.username.clone(), }) }
if_condition
[ { "content": "/// This trait allow to define rules to check if the raw password [&str] is safe to store.\n\n///\n\n/// # Examples\n\n///\n\n/// Verify the password have a minimum length in chars (this is implemented already with [CHECKER_MIN_SIZE]).\n\n/// ```\n\n/// use forbidden::prelude::*;\n\n///\n\n/// str...
Rust
src/ty_param.rs
Manishearth/aster
ae1f5cd8c987282ec7c1e5bc281174cd2a607ea2
use syntax::ast; use syntax::codemap::{DUMMY_SP, Span}; use syntax::owned_slice::OwnedSlice; use syntax::ptr::P; use ident::ToIdent; use invoke::{Invoke, Identity}; use lifetime::{IntoLifetime, IntoLifetimeDef, LifetimeDefBuilder}; use name::ToName; use path::IntoPath; pub struct TyParamBuilder<F=Identity> { call...
use syntax::ast; use syntax::codemap::{DUMMY_SP, Span}; use syntax::owned_slice::OwnedSlice; use syntax::ptr::P; use ident::ToIdent; use invoke::{Invoke, Identity}; use lifetime::{IntoLifetime, IntoLifetimeDef, LifetimeDefBuilder}; use name::ToName; use path::IntoPath; pub struct TyParamBuilder<F=Identity> { call...
: Invoke<ast::TyParam>, { type Result = Self; fn invoke(self, trait_ref: ast::PolyTraitRef) -> Self { self.with_trait_bound(trait_ref) } } pub struct PolyTraitRefBuilder<F> { callback: F, span: Span, trait_ref: ast::TraitRef, lifetimes: Vec<ast::LifetimeDef>, } impl<F> PolyTraitRe...
und<P>(self, path: P) -> PolyTraitRefBuilder<Self> where P: IntoPath, { PolyTraitRefBuilder::new_with_callback(path, self) } pub fn lifetime_bound<L>(mut self, lifetime: L) -> Self where L: IntoLifetime, { let lifetime = lifetime.into_lifetime(); self.bounds.pus...
random
[ { "content": "pub trait ToIdent {\n\n fn to_ident(&self) -> ast::Ident;\n\n}\n\n\n\nimpl ToIdent for ast::Ident {\n\n fn to_ident(&self) -> ast::Ident {\n\n *self\n\n }\n\n}\n\n\n\nimpl ToIdent for ast::Name {\n\n fn to_ident(&self) -> ast::Ident {\n\n ast::Ident::new(*self)\n\n }\n...
Rust
db/src/models/event_interest.rs
taritom/bn-api
6fbf05bf426c4ddd3d5f50378ac9b51f3ebf2a3f
use chrono::NaiveDateTime; use diesel; use diesel::expression::dsl::count; use diesel::prelude::*; use models::*; use schema::{event_interest, users}; use std::collections::HashMap; use utils::errors::DatabaseError; use utils::errors::ErrorCode; use utils::errors::*; use uuid::Uuid; #[derive(Associations, Identifiable...
use chrono::NaiveDateTime; use diesel; use diesel::expression::dsl::count; use diesel::prelude::*; use models::*; use schema::{event_interest, users}; use std::collections::HashMap; use utils::errors::DatabaseError; use utils::errors::ErrorCode; use utils::errors::*; use uuid::Uuid; #[derive(Associations, Identifiable...
.filter(event_interest::user_id.ne(user_id)) .inner_join(users::table) .select(users::all_columns) .order_by(event_interest::user_id.asc()) .limit(limit as i64) .offset(limit as i64 * page as i64) .load::<User>(con...
terest_by_event_ids_for_user( event_ids: &[Uuid], user_id: Uuid, conn: &PgConnection, ) -> Result<HashMap<Uuid, bool>, DatabaseError> { let mut event_interest_map: HashMap<Uuid, bool> = HashMap::new(); let result = event_interest::table .filter(event_interest::eve...
random
[ { "content": "pub fn create_urls(front_url: &String, slug_ids: Vec<Uuid>, url_parm: String, conn: &PgConnection) -> Vec<String> {\n\n let slugs = Slug::find_all(slug_ids, conn).unwrap();\n\n let gen_urls = slugs\n\n .iter()\n\n .map(|slug| &slug.slug)\n\n .unique()\n\n .map(|s|...
Rust
bb/src/main.rs
scott-linder/bb
6dfc1ed1fc0dd5c1b904d53fc83f4aa3fd1c6caf
extern crate mysql; extern crate iron; extern crate hyper; extern crate router; extern crate urlencoded; #[macro_use] extern crate horrorshow; extern crate time; mod board; mod thread; mod post; mod htmlafter; mod doctypeafter; use board::Board; use thread::Thread; use post::Post; use std::default::Default; use mysq...
extern crate mysql; extern crate iron; extern crate hyper; extern crate router; extern crate urlencoded; #[macro_use] extern crate horrorshow; extern crate time; mod board; mod thread; mod post; mod htmlafter; mod doctypeafter; use board::Board; use thread::Thread; use post::Post; use std::default::Default; use mysq...
let redir_url = Url { path: vec![board_name], ..req.url.clone() }; Ok(Response::with((status::SeeOther, Redirect(redir_url)))) }); let pool = my_pool.clone(); router.get("/:board_name/thread/:thread_id/", move |req: &mut Request| { let board_name: String = { let router = req.ext...
function_block-function_prefix_line
[ { "content": "use iron::{Request, Response, IronResult};\n\nuse iron::middleware::AfterMiddleware;\n\nuse hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};\n\nuse hyper::header::ContentType;\n\nuse iron::modifier::Set;\n\nuse iron::modifiers::Header;\n\n\n\n/// Iron middleware which sets content-type header...
Rust
apps/src/bin/pravega_to_screen.rs
jdmaguire/gstreamer-pravega
5d684c1699284632fbb5333bb30e3aa52a140a5b
use gst::prelude::*; use gst::MessageView; struct CustomData { pipeline: gst::Pipeline, playing: bool, terminate: bool, seek_enabled: bool, seek_done: bool, duration: gst::ClockTime, } fn main() { std::env::set_var("GST_DEBUG", "pravegasrc:6,base...
use gst::prelude::*; use gst::MessageView; struct CustomData { pipeline: gst::Pipeline, playing: bool, terminate: bool, seek_enabled: bool, seek_done: bool, duration: gst::ClockTime, } fn main() { std::env::set_var("GST_DEBUG", "pravegasrc:6,base...
println!("Performing seek..."); custom_data .pipeline .seek_simple( gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT, 1601791512680733 * gst::USECOND, ...
ata.terminate { let msg = bus.timed_pop(100 * gst::MSECOND); match msg { Some(msg) => { handle_message(&mut custom_data, &msg); } None => { if custom_data.playing { let position = custom_data ...
random
[ { "content": "fn main() {\n\n let opts: Opts = Opts::parse();\n\n\n\n let filter = std::env::var(\"RUST_LOG\")\n\n .unwrap_or_else(|_| \"pravega_video_server=debug,warp=debug,debug\".to_owned());\n\n tracing_subscriber::fmt()\n\n .with_env_filter(filter)\n\n .with_span_events(FmtSp...
Rust
src/output.rs
DanCardin/sauce
b131ca5318279bda2b764a6db3ad7a5b7ee573ff
use crate::toml::{ensure_section, write_document}; use crate::{ colors::{BLUE, TABLE_BLUE, TABLE_YELLOW, YELLOW}, toml::unwrap_toml_value, }; use anyhow::Result; use comfy_table::{Attribute, Cell, ContentArrangement, Row, Table}; use std::{fmt::Display, io::Write, ops::Deref, path::Path}; use toml_edit::{Docume...
use crate::toml::{ensure_section, write_document}; use crate::{ colors::{BLUE, TABLE_BLUE, TABLE_YELLOW, YELLOW}, toml::unwrap_toml_value, }; use anyhow::Result; use comfy_table::{Attribute, Cell, ContentArrangement, Row, Table}; use std::{fmt::Display, io::Write, ops::Deref, path::Path}; use toml_edit::{Docume...
} row.add_cell(cell); } table.add_row(row); } self.format(table) } pub fn output(&mut self, output: impl Display) -> bool { let data = self.format(output); let stream = if self.show { &mut self.err } ...
if i == 0 { cell = cell.add_attribute(Attribute::Bold).fg(TABLE_BLUE); } else { cell = cell.fg(TABLE_YELLOW); }
if_condition
[ { "content": "fn render_items<F>(items: Vec<(&str, String)>, mut format_row: F) -> String\n\nwhere\n\n F: FnMut(&str, &str) -> String,\n\n{\n\n items\n\n .iter()\n\n .map(|(k, v)| format_row(k, v))\n\n .map(|mut v| {\n\n v += \";\\n\";\n\n v\n\n })\n\n ...
Rust
lockup/client/src/inner.rs
paul-schaaf/serum-dex
feebf9d3debb58730b02aa446c2b652b7438a6a3
use crate::InitializeResponse; use serum_common::client::rpc; use serum_common::pack::Pack; use serum_lockup::accounts::{Safe, Whitelist}; use serum_lockup::client::{Client as InnerClient, ClientError as InnerClientError}; use solana_client_gen::prelude::*; use solana_client_gen::solana_sdk; use solana_client_gen::sola...
use crate::InitializeResponse; use serum_common::client::rpc; use serum_common::pack::Pack; use serum_lockup::accounts::{Safe, Whitelist}; use serum_lockup::client::{Client as InnerClient, ClientError as InnerClientError}; use solana_client_gen::prelude::*; use solana_client_gen::solana_sdk; use solana_client_gen::sola...
pub fn create_vesting_account( client: &InnerClient, depositor: &Pubkey, depositor_owner: &Keypair, safe_acc: &Pubkey, safe_vault: &Pubkey, safe_vault_authority: &Pubkey, vesting_acc_beneficiary: &Pubkey, end_slot: u64, period_count: u64, deposit_amount: u64, mint_decimals: ...
pub fn create_all_accounts_and_initialize( client: &InnerClient, srm_mint: &Pubkey, safe_authority: &Pubkey, ) -> Result<InitializeResponse, InnerClientError> { let safe_acc = Keypair::generate(&mut OsRng); let (safe_vault_authority, nonce) = Pubkey::find_program_add...
function_block-full_function
[ { "content": "pub fn whitelist<'a>(\n\n wl_acc_info: AccountInfo<'a>,\n\n safe: &Safe,\n\n program_id: &Pubkey,\n\n) -> Result<Whitelist<'a>, LockupError> {\n\n if program_id != wl_acc_info.owner {\n\n return Err(LockupErrorCode::InvalidAccountOwner)?;\n\n }\n\n\n\n if safe.whitelist !=...
Rust
src/bin/rust2rpm.rs
ignatenkobrain/rust2rpm
77a5c30faac95fde3ac1a151b1a7e4a9a1e1deb5
extern crate cargo; #[macro_use] extern crate clap; #[macro_use] extern crate failure; extern crate rust2rpm; use cargo::{ core::{Dependency, Source, SourceId}, sources::RegistrySource, Config, }; use clap::ArgMatches; use failure::Error; use rust2rpm::crates::dependencies_by_feature; use std::{collection...
extern crate cargo; #[macro_use] extern crate clap; #[macro_use] extern crate failure; extern crate rust2rpm; use cargo::{ core::{Dependency, Source, SourceId}, sources::RegistrySource, Config, }; use clap::ArgMatches; use failure::Error; use rust2rpm::crates::dependencies_by_feature; use std::{collection...
; println!(); } /* for (feature, (f_deps, o_deps)) in dependencies_by_feature(&package) { if feature == "" { println!("rust-{}-devel", package.name()); } else { println!("rust-{}+{}-devel", package.name(), feature); } for dep in f_deps { ...
match feature { "" => println!("%{{cargo_registry}}/%{{crate}}-%{{version}}/"), _ => println!("%ghost %{{cargo_registry}}/%{{crate}}-%{{version}}/Cargo.toml"), }
if_condition
[ { "content": "pub fn rpm_dep(dependency: &Dependency) -> Result<String, Error> {\n\n let req = range::parse(&dependency.version_req().to_string()).unwrap();\n\n let mut reqs = Vec::new();\n\n for p in &req.predicates {\n\n if p.pre.len() > 0 {\n\n unimplemented!();\n\n }\n\n ...
Rust
src/config.rs
snark/dive-rs
8ee43cebaa9fd7f8b655152086af57aa9594cc11
extern crate getopts; use glob::MatchOptions; use matching::{GlobTarget, MatchRule}; use std::num::ParseIntError; #[derive(Debug)] pub enum Filetype { BlockSpecial, CharacterSpecial, Directory, RegularFile, SymbolicLink, FIFO, Socket, } pub struct Config { pub all: bool, pub case_...
extern crate getopts; use glob::MatchOptions; use matching::{GlobTarget, MatchRule}; use std::num::ParseIntError; #[derive(Debug)] pub enum Filetype { BlockSpecial, CharacterSpecial, Directory, RegularFile, SymbolicLink, FIFO, Socket, } pub struct Config { pub all: bool, pub case_...
x_depth = Config::flag_to_usize(matches.opt_str("maxdepth")); match max_depth { Err(ref e) => errors.push(format!("unable to parse maxdepth argument: {}", e)), _ => (), } let glob_options = MatchOptions { case_sensitive: case_sensitive, require_li...
e = matches.opt_present("case-sensitive"); let filetype = try!(Config::flag_to_filetype(matches.opt_str("type"))); let mut rules = vec![]; let mut errors = vec![]; let mut rule_errors = vec![]; for target in vec!["exact", "regex", "regex-full"] { for n in matches.opt...
random
[ { "content": "pub fn run(start_paths: Vec<std::string::String>,\n\n config: config::Config)\n\n -> Result<(), Box<Error>> {\n\n for path_string in start_paths {\n\n let exists;\n\n {\n\n let path = Path::new(&path_string);\n\n exists = path.exists();\n\...